@rivinia/i18n 0.4.0 → 0.5.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,21 +1,56 @@
1
1
  import * as i0 from "@angular/core";
2
- import { DOCUMENT, InjectionToken, PendingTasks, Pipe, REQUEST, Service, TransferState, computed, effect, inject, isDevMode, makeEnvironmentProviders, makeStateKey, provideAppInitializer, signal } from "@angular/core";
2
+ import { DOCUMENT, InjectionToken, PendingTasks, Pipe, REQUEST, Service, TransferState, computed, effect, inject, isDevMode, makeEnvironmentProviders, makeStateKey, provideAppInitializer, signal, untracked } from "@angular/core";
3
+ var RiviniaLoadError = class extends Error {
4
+ url;
5
+ status;
6
+ language;
7
+ constructor(url, status, language, options) {
8
+ super(`[rivinia/i18n] Failed to load '${url}' (HTTP ${status})`, options);
9
+ this.name = "RiviniaLoadError";
10
+ this.url = url;
11
+ this.status = status;
12
+ this.language = language;
13
+ }
14
+ };
15
+ function resolveLoaderUrl(url, context) {
16
+ if (!context?.isServer) return url;
17
+ try {
18
+ return new URL(url, context.baseUrl).href;
19
+ } catch {
20
+ return url;
21
+ }
22
+ }
23
+ const DEFAULT_BASE_PATH = "i18n";
24
+ var JsonLoader = class {
25
+ _options;
26
+ constructor(_options) {
27
+ this._options = _options;
28
+ }
29
+ async load(language, context) {
30
+ const url = resolveLoaderUrl(`${this._options?.path ?? DEFAULT_BASE_PATH}/${language}.json`, context);
31
+ const response = await fetch(url);
32
+ if (!response.ok) throw new RiviniaLoadError(url, response.status, language);
33
+ return response.json();
34
+ }
35
+ };
36
+ function loadError(url, status, language) {
37
+ return new RiviniaLoadError(url, status, language);
38
+ }
3
39
  function jsonLoader(options) {
4
40
  return { async resolve() {
5
- const { JsonLoader } = await import("./rivinia-i18n-json-loader.impl-Bq-W-UW9.mjs");
6
41
  return new JsonLoader(options);
7
42
  } };
8
43
  }
9
44
  function httpLoader(options) {
10
45
  return { async resolve() {
11
- const { HttpLoader } = await import("./rivinia-i18n-http-loader.impl--BRii7w1.mjs");
12
- return new HttpLoader(options);
46
+ const { HttpLoader } = await import("./rivinia-i18n-http-loader.impl-sLjTazQZ.mjs");
47
+ return new HttpLoader(options, resolveLoaderUrl, loadError);
13
48
  } };
14
49
  }
15
50
  function remoteLoader(options) {
16
51
  return { async resolve() {
17
- const { RemoteLoader } = await import("./rivinia-i18n-remote-loader.impl-CqKS6JWN.mjs");
18
- return new RemoteLoader(options);
52
+ const { RemoteLoader } = await import("./rivinia-i18n-remote-loader.impl-DE90KQn_.mjs");
53
+ return new RemoteLoader(options, resolveLoaderUrl, loadError);
19
54
  } };
20
55
  }
21
56
  function customLoader(load) {
@@ -100,88 +135,135 @@ function shouldSecureCookie(location) {
100
135
  return false;
101
136
  }
102
137
  }
103
- function formatIcu(template, params, locale) {
104
- return parseMessage(template, 0, template.length, params, locale, null).text;
138
+ function formatIcu(template, params, locale, options) {
139
+ return renderMessage(compile(template), params, locale, options);
105
140
  }
106
- function parseMessage(src, start, end, params, locale, plural) {
107
- let out = "";
141
+ const COMPILE_LIMIT = 500;
142
+ const compiled = /* @__PURE__ */ new Map();
143
+ function compile(template) {
144
+ const hit = compiled.get(template);
145
+ if (hit !== void 0) return hit;
146
+ const message = { nodes: parseNodes(template, 0, template.length, false).nodes };
147
+ if (compiled.size >= COMPILE_LIMIT) {
148
+ const oldest = compiled.keys().next();
149
+ if (!oldest.done) compiled.delete(oldest.value);
150
+ }
151
+ compiled.set(template, message);
152
+ return message;
153
+ }
154
+ function parseNodes(src, start, end, inPlural) {
155
+ const nodes = [];
156
+ let buffer = "";
157
+ const flush = () => {
158
+ if (buffer !== "") {
159
+ nodes.push({
160
+ type: "text",
161
+ value: buffer
162
+ });
163
+ buffer = "";
164
+ }
165
+ };
108
166
  let i = start;
109
167
  while (i < end) {
110
- const ch = src[i];
111
- if (ch === "{") {
112
- const arg = parseArgument(src, i, end, params, locale, plural);
113
- if (!arg.ok) return {
114
- text: out + src.slice(i, end),
115
- next: end,
116
- ok: true
117
- };
118
- out += arg.text;
168
+ const ch = src.charCodeAt(i);
169
+ if (ch === 123) {
170
+ flush();
171
+ const arg = parseArgument(src, i, end, inPlural);
172
+ if (arg.rest) {
173
+ nodes.push({
174
+ type: "text",
175
+ value: src.slice(i, end)
176
+ });
177
+ return {
178
+ nodes,
179
+ next: end,
180
+ closed: false
181
+ };
182
+ }
183
+ nodes.push(arg.node);
119
184
  i = arg.next;
120
- } else if (ch === "}") return {
121
- text: out,
122
- next: i,
123
- ok: true
124
- };
125
- else if (ch === "#" && plural !== null) {
126
- out += formatNumberValue(plural.value - plural.offset, locale, void 0) ?? "#";
185
+ continue;
186
+ }
187
+ if (ch === 125) {
188
+ flush();
189
+ return {
190
+ nodes,
191
+ next: i,
192
+ closed: true
193
+ };
194
+ }
195
+ if (ch === 35 && inPlural) {
196
+ flush();
197
+ nodes.push({ type: "hash" });
127
198
  i++;
128
- } else {
129
- out += ch;
199
+ continue;
200
+ }
201
+ if (ch === 39) {
202
+ const after = i + 1 < end ? src.charCodeAt(i + 1) : -1;
203
+ if (after === 39) {
204
+ buffer += "'";
205
+ i += 2;
206
+ continue;
207
+ }
208
+ if (after === 123 || after === 125 || inPlural && after === 35) {
209
+ let j = i + 1;
210
+ while (j < end && src.charCodeAt(j) !== 39) j++;
211
+ buffer += src.slice(i + 1, j);
212
+ i = j < end ? j + 1 : end;
213
+ continue;
214
+ }
215
+ buffer += "'";
130
216
  i++;
217
+ continue;
131
218
  }
219
+ buffer += src[i];
220
+ i++;
132
221
  }
222
+ flush();
133
223
  return {
134
- text: out,
224
+ nodes,
135
225
  next: i,
136
- ok: true
226
+ closed: false
137
227
  };
138
228
  }
139
- function parseArgument(src, start, end, params, locale, outerPlural) {
229
+ function parseArgument(src, start, end, inPlural) {
230
+ const rest = () => ({
231
+ rest: true,
232
+ next: end
233
+ });
140
234
  let i = skipSpaces(src, start + 1, end);
141
235
  const name = readWord(src, i, end);
142
236
  i = skipSpaces(src, name.next, end);
143
- if (i >= end) return {
144
- text: src.slice(start, end),
145
- next: end,
146
- ok: true
147
- };
148
- if (src[i] === "}") {
149
- const value = params[name.word];
150
- return {
151
- text: value === void 0 || value === null || name.word === "" ? src.slice(start, i + 1) : String(value),
152
- next: i + 1,
153
- ok: true
154
- };
155
- }
156
- if (src[i] !== "," || name.word === "") return {
157
- text: src.slice(start, end),
158
- next: end,
159
- ok: true
237
+ if (i >= end) return rest();
238
+ if (src.charCodeAt(i) === 125) return {
239
+ node: {
240
+ type: "param",
241
+ name: name.word,
242
+ raw: src.slice(start, i + 1)
243
+ },
244
+ next: i + 1
160
245
  };
246
+ if (src.charCodeAt(i) !== 44 || name.word === "") return rest();
161
247
  i = skipSpaces(src, i + 1, end);
162
248
  const type = readWord(src, i, end);
163
249
  i = skipSpaces(src, type.next, end);
164
- if (type.word === "number" || type.word === "date") return formatTypedArgument(src, start, i, end, type.word, params[name.word], locale) ?? rawSegment(src, start, end);
165
- if (i >= end || src[i] !== ",") return {
166
- text: src.slice(start, end),
167
- next: end,
168
- ok: true
169
- };
170
- if (type.word !== "plural" && type.word !== "selectordinal" && type.word !== "select") return rawSegment(src, start, end);
250
+ if (type.word === "number" || type.word === "date") return parseTyped(src, start, i, end, type.word, name.word);
251
+ if (i >= end || src.charCodeAt(i) !== 44) return rest();
252
+ if (type.word !== "plural" && type.word !== "selectordinal" && type.word !== "select") return rawNode(src, start, end);
253
+ const branchPlural = type.word !== "select";
171
254
  i++;
172
- const numeric = type.word === "select" ? null : toFiniteNumber(params[name.word]);
173
- const ordinal = type.word === "selectordinal";
174
255
  const branches = /* @__PURE__ */ new Map();
256
+ const exacts = /* @__PURE__ */ new Map();
175
257
  let offset = 0;
176
258
  i = skipSpaces(src, i, end);
177
259
  let closed = false;
178
260
  while (i < end) {
179
261
  i = skipSpaces(src, i, end);
180
- if (i < end && src[i] === "}") {
262
+ if (i < end && src.charCodeAt(i) === 125) {
181
263
  closed = true;
182
264
  break;
183
265
  }
184
- if (type.word !== "select") {
266
+ if (branchPlural) {
185
267
  const offsetClause = readOffset(src, i, end);
186
268
  if (offsetClause) {
187
269
  offset = offsetClause.value;
@@ -189,103 +271,115 @@ function parseArgument(src, start, end, params, locale, outerPlural) {
189
271
  continue;
190
272
  }
191
273
  }
192
- const sel = readSelector(src, i, end);
193
- if (sel.selector === null) return rawSegment(src, start, end);
194
- i = skipSpaces(src, sel.next, end);
195
- if (i >= end || src[i] !== "{") return rawSegment(src, start, end);
196
- const scope = numeric !== null ? {
197
- value: numeric,
198
- offset
199
- } : outerPlural;
200
- const body = parseMessage(src, i + 1, end, params, locale, scope);
201
- branches.set(sel.selector, body.text);
274
+ const selector = readSelector(src, i, end);
275
+ if (selector.selector === null) return rawNode(src, start, end);
276
+ i = skipSpaces(src, selector.next, end);
277
+ if (i >= end || src.charCodeAt(i) !== 123) return rawNode(src, start, end);
278
+ const body = parseNodes(src, i + 1, end, branchPlural || inPlural);
279
+ branches.set(selector.selector, body.nodes);
280
+ if (selector.selector.charCodeAt(0) === 61) {
281
+ const exact = Number(selector.selector.slice(1));
282
+ if (Number.isFinite(exact)) exacts.set(exact, body.nodes);
283
+ }
202
284
  i = body.next + 1;
203
285
  }
204
- if (!closed) return {
205
- text: src.slice(start, end),
206
- next: end,
207
- ok: true
286
+ if (!closed) return rest();
287
+ if (type.word === "select") return {
288
+ node: {
289
+ type: "select",
290
+ name: name.word,
291
+ branches
292
+ },
293
+ next: i + 1
294
+ };
295
+ return {
296
+ node: {
297
+ type: "plural",
298
+ name: name.word,
299
+ ordinal: type.word === "selectordinal",
300
+ offset,
301
+ branches,
302
+ exacts
303
+ },
304
+ next: i + 1
208
305
  };
209
- if (type.word === "select") {
210
- const raw = params[name.word];
211
- const key = raw === void 0 || raw === null ? "" : String(raw);
306
+ }
307
+ function parseTyped(src, start, i, end, kind, name) {
308
+ let style;
309
+ let raw;
310
+ if (i < end && src.charCodeAt(i) === 125) {
311
+ style = void 0;
312
+ raw = src.slice(start, i + 1);
212
313
  return {
213
- text: branches.get(key) ?? branches.get("other") ?? "",
214
- next: i + 1,
215
- ok: true
314
+ node: {
315
+ type: kind,
316
+ name,
317
+ style,
318
+ raw
319
+ },
320
+ next: i + 1
216
321
  };
217
322
  }
218
- if (numeric === null) return {
219
- text: branches.get("other") ?? "",
220
- next: i + 1,
221
- ok: true
222
- };
223
- const exact = branches.get(`=${numeric}`);
224
- if (exact !== void 0) return {
225
- text: exact,
226
- next: i + 1,
227
- ok: true
228
- };
229
- let category;
230
- try {
231
- category = pluralRules(locale, ordinal).select(numeric - offset);
232
- } catch {
233
- category = "other";
234
- }
323
+ if (i >= end || src.charCodeAt(i) !== 44) return rawNode(src, start, end);
324
+ const word = readWord(src, i + 1, end);
325
+ const after = skipSpaces(src, word.next, end);
326
+ if (after >= end || src.charCodeAt(after) !== 125) return rawNode(src, start, end);
327
+ style = word.word;
328
+ raw = src.slice(start, after + 1);
235
329
  return {
236
- text: branches.get(category) ?? branches.get("other") ?? "",
237
- next: i + 1,
238
- ok: true
330
+ node: {
331
+ type: kind,
332
+ name,
333
+ style,
334
+ raw
335
+ },
336
+ next: after + 1
239
337
  };
240
338
  }
241
- function formatTypedArgument(src, start, i, end, kind, value, locale) {
242
- let style;
243
- if (i < end && src[i] === "}") style = void 0;
244
- else if (i < end && src[i] === ",") {
245
- const word = readWord(src, i + 1, end);
246
- const after = skipSpaces(src, word.next, end);
247
- if (after >= end || src[after] !== "}") return null;
248
- style = word.word;
249
- i = after;
250
- } else return null;
251
- const text = kind === "number" ? formatNumberValue(value, locale, style) : formatDateValue(value, locale, style);
252
- if (text === null) return null;
339
+ function rawNode(src, start, end) {
340
+ const segment = rawSegment(src, start, end);
253
341
  return {
254
- text,
255
- next: i + 1,
256
- ok: true
342
+ node: {
343
+ type: "raw",
344
+ value: segment.text
345
+ },
346
+ next: segment.next
257
347
  };
258
348
  }
259
349
  function readOffset(src, i, end) {
260
350
  const start = skipSpaces(src, i, end);
261
- if (!src.startsWith("offset:", start)) return null;
262
- let j = start + 7;
263
- const digits = j;
264
- while (j < end && /[0-9]/.test(src[j])) j++;
265
- if (j === digits) return null;
266
- const value = Number(src.slice(digits, j));
267
- if (!Number.isFinite(value)) return null;
268
- return {
269
- value,
270
- next: j
271
- };
272
- }
273
- function toFiniteNumber(value) {
274
- if (typeof value === "number") return Number.isFinite(value) ? value : null;
275
- if (typeof value === "string" && value.trim() !== "") {
276
- const n = Number(value);
277
- return Number.isFinite(n) ? n : null;
351
+ if (src.startsWith("offset:", start)) {
352
+ let j = start + 7;
353
+ const digits = j;
354
+ while (j < end && isDigit(src.charCodeAt(j))) j++;
355
+ if (j === digits) return null;
356
+ const value = Number(src.slice(digits, j));
357
+ if (!Number.isFinite(value)) return null;
358
+ return {
359
+ value,
360
+ next: j
361
+ };
278
362
  }
279
363
  return null;
280
364
  }
365
+ function isSpace(ch) {
366
+ return ch === 32 || ch >= 9 && ch <= 13 || ch === 160;
367
+ }
368
+ function isDigit(ch) {
369
+ return ch >= 48 && ch <= 57;
370
+ }
281
371
  function skipSpaces(src, i, end) {
282
- while (i < end && /\s/.test(src[i])) i++;
372
+ while (i < end && isSpace(src.charCodeAt(i))) i++;
283
373
  return i;
284
374
  }
285
375
  function readWord(src, i, end) {
286
376
  const start = skipSpaces(src, i, end);
287
377
  let j = start;
288
- while (j < end && /[^\s,}]+/.test(src[j])) j++;
378
+ while (j < end) {
379
+ const ch = src.charCodeAt(j);
380
+ if (isSpace(ch) || ch === 44 || ch === 123 || ch === 125) break;
381
+ j++;
382
+ }
289
383
  return {
290
384
  word: src.slice(start, j),
291
385
  next: j
@@ -293,14 +387,14 @@ function readWord(src, i, end) {
293
387
  }
294
388
  function readSelector(src, i, end) {
295
389
  i = skipSpaces(src, i, end);
296
- if (i < end && src[i] === "=") {
390
+ if (i < end && src.charCodeAt(i) === 61) {
297
391
  let j = i + 1;
298
- if (j < end && src[j] === "-") j++;
392
+ if (j < end && src.charCodeAt(j) === 45) j++;
299
393
  const digits = j;
300
- while (j < end && /[0-9]/.test(src[j])) j++;
301
- if (j < end && src[j] === "." && j + 1 < end && /[0-9]/.test(src[j + 1])) {
394
+ while (j < end && isDigit(src.charCodeAt(j))) j++;
395
+ if (j < end && src.charCodeAt(j) === 46 && j + 1 < end && isDigit(src.charCodeAt(j + 1))) {
302
396
  j++;
303
- while (j < end && /[0-9]/.test(src[j])) j++;
397
+ while (j < end && isDigit(src.charCodeAt(j))) j++;
304
398
  }
305
399
  if (j === digits) return {
306
400
  selector: null,
@@ -325,28 +419,126 @@ function rawSegment(src, start, end) {
325
419
  let depth = 0;
326
420
  let i = start;
327
421
  while (i < end) {
328
- const ch = src[i];
329
- if (ch === "{") depth++;
330
- else if (ch === "}") {
422
+ const ch = src.charCodeAt(i);
423
+ if (ch === 123) depth++;
424
+ else if (ch === 125) {
331
425
  depth--;
332
426
  if (depth === 0) return {
333
427
  text: src.slice(start, i + 1),
334
- next: i + 1,
335
- ok: true
428
+ next: i + 1
336
429
  };
337
430
  }
338
431
  i++;
339
432
  }
340
433
  return {
341
434
  text: src.slice(start, end),
342
- next: end,
343
- ok: true
435
+ next: end
344
436
  };
345
437
  }
438
+ function renderMessage(message, params, locale, options) {
439
+ return renderNodes(message.nodes, {
440
+ params,
441
+ locale,
442
+ plural: null,
443
+ options
444
+ });
445
+ }
446
+ function renderNodes(nodes, ctx) {
447
+ let out = "";
448
+ for (const node of nodes) switch (node.type) {
449
+ case "text":
450
+ out += node.value;
451
+ break;
452
+ case "raw":
453
+ out += node.value;
454
+ break;
455
+ case "hash":
456
+ out += ctx.plural === null ? "#" : formatNumberValue(ctx.plural.value - ctx.plural.offset, ctx.locale, void 0) ?? "#";
457
+ break;
458
+ case "param": {
459
+ const value = ctx.params[node.name];
460
+ if (value === void 0 || value === null || node.name === "") {
461
+ if (node.name !== "") ctx.options?.onMissingParam?.(node.name);
462
+ out += node.raw;
463
+ } else out += String(value);
464
+ break;
465
+ }
466
+ case "number": {
467
+ const value = ctx.params[node.name];
468
+ reportMissing(ctx, node.name, value);
469
+ out += formatNumberValue(value, ctx.locale, node.style) ?? node.raw;
470
+ break;
471
+ }
472
+ case "date": {
473
+ const value = ctx.params[node.name];
474
+ reportMissing(ctx, node.name, value);
475
+ out += formatDateValue(value, ctx.locale, node.style) ?? node.raw;
476
+ break;
477
+ }
478
+ case "plural": {
479
+ const value = ctx.params[node.name];
480
+ const numeric = toFiniteNumber(value);
481
+ reportMissing(ctx, node.name, value);
482
+ let branch;
483
+ if (numeric !== null) {
484
+ branch = node.exacts.get(numeric);
485
+ if (branch === void 0) branch = node.branches.get(selectCategory(numeric - node.offset, node.ordinal, ctx.locale));
486
+ if (branch === void 0) branch = node.branches.get("other");
487
+ } else branch = node.branches.get("other");
488
+ if (branch !== void 0) {
489
+ const saved = ctx.plural;
490
+ ctx.plural = numeric !== null ? {
491
+ value: numeric,
492
+ offset: node.offset
493
+ } : saved;
494
+ out += renderNodes(branch, ctx);
495
+ ctx.plural = saved;
496
+ }
497
+ break;
498
+ }
499
+ case "select": {
500
+ const value = ctx.params[node.name];
501
+ reportMissing(ctx, node.name, value);
502
+ const key = value === void 0 || value === null ? "" : String(value);
503
+ const branch = node.branches.get(key) ?? node.branches.get("other");
504
+ if (branch) out += renderNodes(branch, ctx);
505
+ break;
506
+ }
507
+ }
508
+ return out;
509
+ }
510
+ function reportMissing(ctx, name, value) {
511
+ if (value === void 0 || value === null) ctx.options?.onMissingParam?.(name);
512
+ }
513
+ function selectCategory(value, ordinal, locale) {
514
+ const key = `${ordinal ? 1 : 0}|${locale}|${value}`;
515
+ const hit = pluralCategories.get(key);
516
+ if (hit !== void 0) return hit;
517
+ let category;
518
+ try {
519
+ category = pluralRules(locale, ordinal).select(value);
520
+ } catch {
521
+ category = "other";
522
+ }
523
+ if (pluralCategories.size >= CACHE_LIMIT) pluralCategories.clear();
524
+ pluralCategories.set(key, category);
525
+ return category;
526
+ }
527
+ function toFiniteNumber(value) {
528
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
529
+ if (typeof value === "string" && value.trim() !== "") {
530
+ const n = Number(value);
531
+ return Number.isFinite(n) ? n : null;
532
+ }
533
+ return null;
534
+ }
346
535
  const CACHE_LIMIT = 40;
347
536
  const numberFormats = /* @__PURE__ */ new Map();
348
537
  const dateFormats = /* @__PURE__ */ new Map();
349
538
  const pluralRulesByLocale = /* @__PURE__ */ new Map();
539
+ const pluralCategories = /* @__PURE__ */ new Map();
540
+ const formattedNumbers = /* @__PURE__ */ new Map();
541
+ const FORMATTED_NUMBERS_LIMIT = 1e3;
350
542
  function memo(map, key, create) {
351
543
  const hit = map.get(key);
352
544
  if (hit !== void 0) return hit;
@@ -361,11 +553,25 @@ function pluralRules(locale, ordinal) {
361
553
  }
362
554
  function formatNumberValue(value, locale, style) {
363
555
  if (typeof value !== "number" || !Number.isFinite(value)) return null;
364
- const options = numberOptions(style);
365
- if (options === null) return null;
556
+ let key;
557
+ let options;
558
+ if (style === void 0) {
559
+ key = `${locale}|`;
560
+ options = {};
561
+ } else {
562
+ const resolved = numberOptions(style);
563
+ if (resolved === null) return null;
564
+ key = `${locale}|${style}`;
565
+ options = resolved;
566
+ }
567
+ const cacheKey = `${key}${value}`;
568
+ const cached = formattedNumbers.get(cacheKey);
569
+ if (cached !== void 0) return cached;
366
570
  try {
367
- const key = `${locale}|${JSON.stringify(options)}`;
368
- return memo(numberFormats, key, () => new Intl.NumberFormat(locale, options)).format(value);
571
+ const text = memo(numberFormats, key, () => new Intl.NumberFormat(locale, options)).format(value);
572
+ if (formattedNumbers.size >= FORMATTED_NUMBERS_LIMIT) formattedNumbers.clear();
573
+ formattedNumbers.set(cacheKey, text);
574
+ return text;
369
575
  } catch {
370
576
  return null;
371
577
  }
@@ -389,6 +595,8 @@ const DATE_STYLES = /* @__PURE__ */ new Set([
389
595
  "long",
390
596
  "full"
391
597
  ]);
598
+ const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
599
+ const ISO_DATE_TIME = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:?\d{2})?$/;
392
600
  function formatDateValue(value, locale, style) {
393
601
  const date = toDate(value);
394
602
  if (date === null) return null;
@@ -407,6 +615,18 @@ function toDate(value) {
407
615
  const date = new Date(value);
408
616
  return Number.isNaN(date.getTime()) ? null : date;
409
617
  }
618
+ if (typeof value === "string") {
619
+ if (ISO_DATE.test(value)) {
620
+ const [year, month, day] = value.split("-").map(Number);
621
+ const date = new Date(year, month - 1, day);
622
+ return date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day ? date : null;
623
+ }
624
+ if (ISO_DATE_TIME.test(value)) {
625
+ const date = new Date(value);
626
+ return Number.isNaN(date.getTime()) ? null : date;
627
+ }
628
+ return null;
629
+ }
410
630
  if (Object.prototype.toString.call(value) === "[object Date]") {
411
631
  const date = value;
412
632
  return Number.isNaN(date.getTime()) ? null : date;
@@ -503,6 +723,7 @@ var RiviniaI18n = class RiviniaI18n {
503
723
  _storageKey = this._config.storageKey ?? "rivinia.i18n.language";
504
724
  _storageStrategy = this._config.storageStrategy ?? "local";
505
725
  _autoApplyDirection = this._config.autoApplyDirection ?? true;
726
+ _persist = this._config.persist ?? true;
506
727
  _fallbackId = this._config.fallbackLanguage ?? null;
507
728
  _doc = inject(DOCUMENT);
508
729
  _request = inject(REQUEST, { optional: true });
@@ -517,6 +738,7 @@ var RiviniaI18n = class RiviniaI18n {
517
738
  _translationsCache = /* @__PURE__ */ new Map();
518
739
  _generations = /* @__PURE__ */ new Map();
519
740
  _inflight = /* @__PURE__ */ new Map();
741
+ _loadingCount = 0;
520
742
  _applyCount = 0;
521
743
  _initialized = false;
522
744
  _tasks = inject(PendingTasks, { optional: true });
@@ -540,27 +762,33 @@ var RiviniaI18n = class RiviniaI18n {
540
762
  _missingKeys = signal([], ...ngDevMode ? [{ debugName: "_missingKeys" }] : /* istanbul ignore next */ []);
541
763
  _reportedMissingKeys = /* @__PURE__ */ new Set();
542
764
  _pendingMissingKeys = [];
765
+ _pendingMissingEvents = [];
543
766
  _missingFlushQueued = false;
767
+ _warnOnMissingParam = this._config.warnOnMissingParam ?? (isDevMode() && this._config.onMissingParam === void 0);
768
+ _reportedMissingParams = /* @__PURE__ */ new Set();
769
+ _pendingMissingParams = [];
770
+ _missingParamsFlushQueued = false;
544
771
  missingKeys = this._missingKeys.asReadonly();
545
772
  clearMissingKeys() {
546
773
  this._reportedMissingKeys.clear();
547
774
  this._pendingMissingKeys.length = 0;
775
+ this._pendingMissingEvents.length = 0;
548
776
  this._missingKeys.set([]);
549
777
  }
778
+ clearMissingParams() {
779
+ this._reportedMissingParams.clear();
780
+ this._pendingMissingParams.length = 0;
781
+ }
550
782
  constructor() {
551
783
  if (this._config.languages.length === 0) throw new Error("[rivinia/i18n] At least one language must be provided in the languages array.");
552
784
  if (!this._config.languages.some((l) => l.id === this._config.defaultLanguage)) throw new Error(`[rivinia/i18n] defaultLanguage "${this._config.defaultLanguage}" must be one of the configured language IDs.`);
553
785
  if (this._fallbackId !== null && !this._config.languages.some((l) => l.id === this._fallbackId)) throw new Error(`[rivinia/i18n] fallbackLanguage "${this._fallbackId}" must be one of the configured language IDs.`);
554
- effect(() => {
555
- const id = this._currentLanguageId();
556
- this._writeStored(id);
557
- });
558
786
  if (this._autoApplyDirection) effect(() => {
559
787
  const lang = this.currentLanguageObject();
560
788
  const root = this._doc.documentElement;
561
789
  if (!root) return;
562
790
  root.dir = lang.dir;
563
- root.lang = lang.id;
791
+ root.lang = lang.locale ?? lang.id;
564
792
  });
565
793
  }
566
794
  getLanguage(id) {
@@ -622,10 +850,10 @@ var RiviniaI18n = class RiviniaI18n {
622
850
  }
623
851
  _resolveKeyText(key, defaultValue, params) {
624
852
  const resolved = this._lookupKey(key);
625
- if (resolved !== void 0) return this.render(resolved.text, params, resolved.locale);
626
- if (defaultValue === void 0) this._reportMissingKey(key);
853
+ if (resolved !== void 0) return this.render(resolved.text, params, resolved.locale, key);
854
+ if (defaultValue === void 0) untracked(() => this._reportMissingKey(key));
627
855
  const fallback = defaultValue ?? key;
628
- return params ? this.render(fallback, params, this.locale()) : fallback;
856
+ return params ? this.render(fallback, params, this.locale(), key) : fallback;
629
857
  }
630
858
  loadedTranslations = this._loadedTranslations.asReadonly();
631
859
  async loadTranslations(languageId, opts) {
@@ -660,6 +888,7 @@ var RiviniaI18n = class RiviniaI18n {
660
888
  toggle() {
661
889
  const langs = this._languages();
662
890
  if (langs.length < 2) return;
891
+ if (langs.length > 2 && isDevMode()) console.warn("[rivinia/i18n] toggle() only flips the first two languages; use next()/previous() when more than two are configured.");
663
892
  const newId = this._currentLanguageId() === langs[0].id ? langs[1].id : langs[0].id;
664
893
  this.applyLanguage(newId);
665
894
  }
@@ -735,12 +964,19 @@ var RiviniaI18n = class RiviniaI18n {
735
964
  this._loadTranslations(id);
736
965
  this._ensureFallback();
737
966
  }
967
+ this._persistLanguage(id);
968
+ }
969
+ _persistLanguage(id) {
970
+ if (!this._persist) return;
971
+ if (this._readStored() === id) return;
972
+ this._writeStored(id);
738
973
  }
739
- render(template, params, locale) {
740
- if (!params) return template;
741
- if (!template.includes("{")) return template;
974
+ render(template, params, locale, key) {
975
+ const quoting = template.includes("'");
976
+ if (params === void 0 && !quoting) return template;
977
+ if (!quoting && !template.includes("{")) return template;
742
978
  try {
743
- return formatIcu(template, params, locale);
979
+ return formatIcu(template, params ?? {}, locale, { onMissingParam: (name) => untracked(() => this._reportMissingParam(key, name)) });
744
980
  } catch {
745
981
  return template;
746
982
  }
@@ -792,8 +1028,8 @@ var RiviniaI18n = class RiviniaI18n {
792
1028
  fallbackLanguage
793
1029
  };
794
1030
  this._pendingMissingKeys.push(key);
1031
+ this._pendingMissingEvents.push(event);
795
1032
  this._queueMissingFlush();
796
- this._config.onMissingKey?.(event);
797
1033
  if (this._warnOnMissingKey) console.warn(`[rivinia/i18n] Missing key "${key}" for language "${language}"` + (fallbackLanguage === null ? "." : ` (fallback "${fallbackLanguage}" has no value either).`));
798
1034
  }
799
1035
  _queueMissingFlush() {
@@ -804,26 +1040,80 @@ var RiviniaI18n = class RiviniaI18n {
804
1040
  const pending = this._pendingMissingKeys.splice(0);
805
1041
  if (pending.length === 0) return;
806
1042
  this._missingKeys.update((current) => [...current, ...pending]);
1043
+ const events = this._pendingMissingEvents.splice(0);
1044
+ for (const event of events) this._config.onMissingKey?.(event);
1045
+ });
1046
+ }
1047
+ _reportMissingParam(key, param) {
1048
+ const dedupe = `${key}\u0000${param}`;
1049
+ if (this._reportedMissingParams.has(dedupe)) return;
1050
+ this._reportedMissingParams.add(dedupe);
1051
+ const language = this._currentLanguageId();
1052
+ this._pendingMissingParams.push({
1053
+ key,
1054
+ param,
1055
+ language
1056
+ });
1057
+ this._queueMissingParamsFlush();
1058
+ if (this._warnOnMissingParam) console.warn(`[rivinia/i18n] Missing parameter "${param}" for key "${key}" and language "${language}"; the placeholder was kept.`);
1059
+ }
1060
+ _queueMissingParamsFlush() {
1061
+ if (this._missingParamsFlushQueued) return;
1062
+ this._missingParamsFlushQueued = true;
1063
+ queueMicrotask(() => {
1064
+ this._missingParamsFlushQueued = false;
1065
+ const events = this._pendingMissingParams.splice(0);
1066
+ for (const event of events) this._config.onMissingParam?.(event);
807
1067
  });
808
1068
  }
809
1069
  async _loadTranslations(languageId, opts) {
810
- const current = () => languageId === this._currentLanguageId();
811
1070
  const background = opts?.background === true;
812
1071
  if (!opts?.force) {
813
1072
  const cached = this._translationsCache.get(languageId);
814
1073
  if (cached) {
815
- if (!opts?.silent && current()) this._loadedTranslations.set(cached);
816
- if (languageId === this._fallbackId) this._fallbackDict.set(cached);
1074
+ this._applyDictionary(languageId, cached);
817
1075
  return {
818
1076
  data: cached,
819
1077
  ok: true
820
1078
  };
821
1079
  }
822
- const inflight = this._inflight.get(languageId);
823
- if (inflight) return inflight;
824
1080
  }
825
- if (!background) this._loadingState.set("loading");
826
- const generation = this._generationOf(languageId);
1081
+ let task = opts?.force ? void 0 : this._inflight.get(languageId);
1082
+ if (!task) {
1083
+ task = this._fetchDictionary(languageId, this._generationOf(languageId));
1084
+ this._inflight.set(languageId, task);
1085
+ }
1086
+ if (!background) {
1087
+ this._loadingCount++;
1088
+ this._loadingState.set("loading");
1089
+ }
1090
+ try {
1091
+ const result = await task;
1092
+ if (result.ok) this._applyDictionary(languageId, result.data);
1093
+ else if (!background && result.error !== void 0 && languageId === this._currentLanguageId()) {
1094
+ this._loadingError.set(result.error);
1095
+ this._loadingState.set("error");
1096
+ }
1097
+ return {
1098
+ data: result.data,
1099
+ ok: result.ok
1100
+ };
1101
+ } finally {
1102
+ if (!background) {
1103
+ this._loadingCount = Math.max(0, this._loadingCount - 1);
1104
+ if (this._loadingCount === 0 && this._loadingState() === "loading") this._loadingState.set("idle");
1105
+ }
1106
+ }
1107
+ }
1108
+ _applyDictionary(languageId, data) {
1109
+ if (languageId === this._currentLanguageId()) {
1110
+ this._loadedTranslations.set(data);
1111
+ this._loadingError.set(null);
1112
+ if (this._loadingCount === 0 && this._loadingState() === "error") this._loadingState.set("idle");
1113
+ }
1114
+ if (languageId === this._fallbackId) this._fallbackDict.set(data);
1115
+ }
1116
+ _fetchDictionary(languageId, generation) {
827
1117
  let task;
828
1118
  task = (async () => {
829
1119
  const stale = () => this._generationOf(languageId) !== generation;
@@ -836,12 +1126,6 @@ var RiviniaI18n = class RiviniaI18n {
836
1126
  };
837
1127
  this._translationsCache.set(languageId, translations);
838
1128
  this.writeTransfer(languageId, translations);
839
- if (languageId === this._fallbackId && !current()) this._fallbackDict.set(translations);
840
- if (!opts?.silent && current()) {
841
- this._loadedTranslations.set(translations);
842
- this._loadingError.set(null);
843
- this._loadingState.set("idle");
844
- }
845
1129
  return {
846
1130
  data: translations,
847
1131
  ok: true
@@ -851,23 +1135,16 @@ var RiviniaI18n = class RiviniaI18n {
851
1135
  data: {},
852
1136
  ok: false
853
1137
  };
854
- if (!background && current()) {
855
- this._loadingError.set(error);
856
- this._loadingState.set("error");
857
- }
858
1138
  this._config.onLoadError?.(languageId, error);
859
1139
  return {
860
1140
  data: {},
861
- ok: false
1141
+ ok: false,
1142
+ error
862
1143
  };
863
1144
  } finally {
864
- if (this._inflight.get(languageId) === task) {
865
- this._inflight.delete(languageId);
866
- if (!background && this._inflight.size === 0 && this._loadingState() === "loading") this._loadingState.set("idle");
867
- }
1145
+ if (this._inflight.get(languageId) === task) this._inflight.delete(languageId);
868
1146
  }
869
1147
  })();
870
- this._inflight.set(languageId, task);
871
1148
  return task;
872
1149
  }
873
1150
  _readStored() {
@@ -910,7 +1187,7 @@ var RiviniaI18n = class RiviniaI18n {
910
1187
  this._transfer?.set(this.transferKey(languageId), dict);
911
1188
  }
912
1189
  _resolveKey(obj, path) {
913
- const value = path.split(".").reduce((acc, segment) => acc && typeof acc === "object" ? acc[segment] : void 0, obj);
1190
+ const value = Object.prototype.hasOwnProperty.call(obj, path) ? obj[path] : path.split(".").reduce((acc, segment) => acc && typeof acc === "object" ? acc[segment] : void 0, obj);
914
1191
  if (typeof value === "string") return value;
915
1192
  if (typeof value === "number" || typeof value === "boolean") return String(value);
916
1193
  }
@@ -1007,6 +1284,6 @@ i0.ɵɵngDeclareClassMetadata({
1007
1284
  }]
1008
1285
  }]
1009
1286
  });
1010
- export { RTranslatePipe, RiviniaI18n, ViewTransitionService, browserLanguages, customLoader, defineRiviniaI18n, detectBrowserLanguage, formatIcu, httpLoader, injectRiviniaI18n, jsonLoader, parseCookie, provideRiviniaI18n, remoteLoader, serializeCookie };
1287
+ export { RTranslatePipe, RiviniaI18n, RiviniaLoadError, ViewTransitionService, browserLanguages, customLoader, defineRiviniaI18n, detectBrowserLanguage, formatIcu, httpLoader, injectRiviniaI18n, jsonLoader, parseCookie, provideRiviniaI18n, remoteLoader, serializeCookie };
1011
1288
 
1012
1289
  //# sourceMappingURL=rivinia-i18n.mjs.map