verbaly 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,739 +1,814 @@
1
- // src/flatten.ts
1
+ //#region src/flatten.ts
2
2
  function flatten(tree, prefix = "", out = {}) {
3
- for (const [key, value] of Object.entries(tree)) {
4
- const path = prefix ? `${prefix}.${key}` : key;
5
- if (typeof value === "string") out[path] = value;
6
- else flatten(value, path, out);
7
- }
8
- return out;
3
+ for (const [key, value] of Object.entries(tree)) {
4
+ const path = prefix ? `${prefix}.${key}` : key;
5
+ if (typeof value === "string") out[path] = value;
6
+ else flatten(value, path, out);
7
+ }
8
+ return out;
9
+ }
10
+ //#endregion
11
+ //#region src/intl.ts
12
+ const CACHE_CAP = 200;
13
+ const nfCache = /* @__PURE__ */ new Map();
14
+ const dtfCache = /* @__PURE__ */ new Map();
15
+ const prCache = /* @__PURE__ */ new Map();
16
+ const rtfCache = /* @__PURE__ */ new Map();
17
+ const lfCache = /* @__PURE__ */ new Map();
18
+ function cached(cache, key, make) {
19
+ let hit = cache.get(key);
20
+ if (!hit) {
21
+ if (cache.size >= CACHE_CAP) cache.delete(cache.keys().next().value);
22
+ hit = make();
23
+ cache.set(key, hit);
24
+ }
25
+ return hit;
9
26
  }
10
-
11
- // src/intl.ts
12
- var nfCache = /* @__PURE__ */ new Map();
13
- var dtfCache = /* @__PURE__ */ new Map();
14
- var prCache = /* @__PURE__ */ new Map();
15
27
  function numberFormat(locale, options) {
16
- const key = locale + (options ? JSON.stringify(options) : "");
17
- let fmt = nfCache.get(key);
18
- if (!fmt) {
19
- fmt = new Intl.NumberFormat(locale, options);
20
- nfCache.set(key, fmt);
21
- }
22
- return fmt;
28
+ const key = locale + (options ? JSON.stringify(options) : "");
29
+ return cached(nfCache, key, () => new Intl.NumberFormat(locale, options));
23
30
  }
24
31
  function dateTimeFormat(locale, options) {
25
- const key = locale + (options ? JSON.stringify(options) : "");
26
- let fmt = dtfCache.get(key);
27
- if (!fmt) {
28
- fmt = new Intl.DateTimeFormat(locale, options);
29
- dtfCache.set(key, fmt);
30
- }
31
- return fmt;
32
+ const key = locale + (options ? JSON.stringify(options) : "");
33
+ return cached(dtfCache, key, () => new Intl.DateTimeFormat(locale, options));
32
34
  }
33
35
  function pluralRules(locale, type = "cardinal") {
34
- const key = locale + type;
35
- let rules = prCache.get(key);
36
- if (!rules) {
37
- rules = new Intl.PluralRules(locale, { type });
38
- prCache.set(key, rules);
39
- }
40
- return rules;
36
+ return cached(prCache, locale + type, () => new Intl.PluralRules(locale, { type }));
41
37
  }
42
-
43
- // src/format.ts
38
+ function relativeTimeFormat(locale) {
39
+ return cached(rtfCache, locale, () => new Intl.RelativeTimeFormat(locale, { numeric: "auto" }));
40
+ }
41
+ function listFormat(locale, type) {
42
+ return cached(lfCache, locale + type, () => new Intl.ListFormat(locale, { type }));
43
+ }
44
+ //#endregion
45
+ //#region src/format.ts
44
46
  function formatNodes(nodes, ctx) {
45
- let out = "";
46
- for (const node of nodes) {
47
- if (node.kind === "text") out += node.value;
48
- else if (node.kind === "hash") out += autoFormat(ctx.hashValue, ctx.locale);
49
- else out += formatParam(node, ctx);
50
- }
51
- return out;
47
+ let out = "";
48
+ for (const node of nodes) if (node.kind === "text") out += node.value;
49
+ else if (node.kind === "hash") out += autoFormat(ctx.hashValue, ctx.locale);
50
+ else out += formatParam(node, ctx);
51
+ return out;
52
52
  }
53
53
  function formatParam(node, ctx) {
54
- const value = ctx.params?.[node.name];
55
- if (value === void 0) return `{${node.name}}`;
56
- if (node.variants) {
57
- const chosen = pickVariant(node.variants, value, ctx.locale, node.ordinal);
58
- if (!chosen) return "";
59
- return formatNodes(chosen, { ...ctx, hashValue: value });
60
- }
61
- if (node.format) return applyFormat(value, node.format, node.arg, ctx);
62
- return autoFormat(value, ctx.locale);
54
+ const value = ctx.params?.[node.name];
55
+ if (value === void 0) return `{${node.name}}`;
56
+ if (node.variants) {
57
+ const chosen = pickVariant(node.variants, value, ctx.locale, node.ordinal);
58
+ if (!chosen) return "";
59
+ return formatNodes(chosen, {
60
+ ...ctx,
61
+ hashValue: value
62
+ });
63
+ }
64
+ if (node.format) return applyFormat(value, node.format, node.arg, ctx);
65
+ return autoFormat(value, ctx.locale);
63
66
  }
64
67
  function pickVariant(variants, value, locale, ordinal) {
65
- const raw = String(value);
66
- if (typeof value === "number") {
67
- for (const [key, nodes] of variants) if (key === `=${raw}`) return nodes;
68
- const category = pluralRules(locale, ordinal ? "ordinal" : "cardinal").select(value);
69
- for (const [key, nodes] of variants) if (key === category) return nodes;
70
- } else {
71
- for (const [key, nodes] of variants) if (key === raw) return nodes;
72
- }
73
- for (const [key, nodes] of variants) if (key === "other") return nodes;
74
- return void 0;
68
+ const raw = String(value);
69
+ if (typeof value === "number") {
70
+ for (const [key, nodes] of variants) if (key === `=${raw}`) return nodes;
71
+ const category = pluralRules(locale, ordinal ? "ordinal" : "cardinal").select(value);
72
+ for (const [key, nodes] of variants) if (key === category) return nodes;
73
+ } else for (const [key, nodes] of variants) if (key === raw) return nodes;
74
+ for (const [key, nodes] of variants) if (key === "other") return nodes;
75
75
  }
76
76
  function applyFormat(value, format, arg, ctx) {
77
- const custom = ctx.formatters[format];
78
- if (custom) return custom(value, ctx.locale, arg);
79
- const { locale } = ctx;
80
- switch (format) {
81
- case "number":
82
- return numberFormat(locale).format(Number(value));
83
- case "integer":
84
- return numberFormat(locale, { maximumFractionDigits: 0 }).format(Number(value));
85
- case "percent":
86
- return numberFormat(locale, { style: "percent" }).format(Number(value));
87
- case "currency":
88
- if (!arg) return String(value);
89
- return numberFormat(locale, { style: "currency", currency: arg }).format(Number(value));
90
- case "date":
91
- return dateTimeFormat(
92
- locale,
93
- arg ? { dateStyle: arg } : void 0
94
- ).format(toDate(value));
95
- case "time":
96
- return dateTimeFormat(locale, {
97
- timeStyle: arg ?? "short"
98
- }).format(toDate(value));
99
- default:
100
- return String(value);
101
- }
77
+ const custom = ctx.formatters[format];
78
+ if (custom) return custom(value, ctx.locale, arg);
79
+ const { locale } = ctx;
80
+ switch (format) {
81
+ case "number": return numberFormat(locale).format(Number(value));
82
+ case "integer": return numberFormat(locale, { maximumFractionDigits: 0 }).format(Number(value));
83
+ case "percent": return numberFormat(locale, { style: "percent" }).format(Number(value));
84
+ case "currency":
85
+ if (!arg) return String(value);
86
+ return numberFormat(locale, {
87
+ style: "currency",
88
+ currency: arg
89
+ }).format(Number(value));
90
+ case "date": return dateTimeFormat(locale, arg ? { dateStyle: arg } : void 0).format(toDate(value));
91
+ case "time": return dateTimeFormat(locale, { timeStyle: arg ?? "short" }).format(toDate(value));
92
+ case "relative": return formatRelative(value, arg, locale);
93
+ case "list":
94
+ if (!Array.isArray(value)) return String(value);
95
+ return listFormat(locale, arg === "or" ? "disjunction" : arg === "unit" ? "unit" : "conjunction").format(value.map((item) => autoFormat(item, locale)));
96
+ case "unit":
97
+ if (!arg) return String(value);
98
+ try {
99
+ return numberFormat(locale, {
100
+ style: "unit",
101
+ unit: arg
102
+ }).format(Number(value));
103
+ } catch {
104
+ warnOnce(`invalid unit "${arg}"`);
105
+ return String(value);
106
+ }
107
+ default:
108
+ warnOnce(`unknown format "${format}"`);
109
+ return String(value);
110
+ }
111
+ }
112
+ const REL_UNITS = [
113
+ ["year", 31536e3],
114
+ ["month", 2592e3],
115
+ ["week", 604800],
116
+ ["day", 86400],
117
+ ["hour", 3600],
118
+ ["minute", 60],
119
+ ["second", 1]
120
+ ];
121
+ function formatRelative(value, arg, locale) {
122
+ try {
123
+ if (typeof value === "number" && arg) return relativeTimeFormat(locale).format(value, arg);
124
+ if (value instanceof Date) {
125
+ const diffSec = (value.getTime() - Date.now()) / 1e3;
126
+ if (arg) {
127
+ const per = REL_UNITS.find(([unit]) => unit === arg)?.[1];
128
+ if (!per) throw new RangeError(arg);
129
+ return relativeTimeFormat(locale).format(Math.round(diffSec / per), arg);
130
+ }
131
+ const [unit, per] = REL_UNITS.find(([, s]) => Math.abs(diffSec) >= s) ?? ["second", 1];
132
+ return relativeTimeFormat(locale).format(Math.round(diffSec / per), unit);
133
+ }
134
+ } catch {
135
+ warnOnce(`invalid relative unit "${arg}"`);
136
+ }
137
+ return String(value);
138
+ }
139
+ const warned = /* @__PURE__ */ new Set();
140
+ function warnOnce(msg) {
141
+ if (warned.has(msg)) return;
142
+ warned.add(msg);
143
+ console.warn(`[verbaly] ${msg}`);
102
144
  }
103
145
  function autoFormat(value, locale) {
104
- if (value === null || value === void 0) return "";
105
- if (typeof value === "number") return numberFormat(locale).format(value);
106
- if (value instanceof Date) return dateTimeFormat(locale).format(value);
107
- return String(value);
146
+ if (value === null || value === void 0) return "";
147
+ if (typeof value === "number") return numberFormat(locale).format(value);
148
+ if (value instanceof Date) return dateTimeFormat(locale).format(value);
149
+ return String(value);
108
150
  }
109
151
  function toDate(value) {
110
- return value instanceof Date ? value : new Date(value);
152
+ return value instanceof Date ? value : new Date(value);
111
153
  }
112
-
113
- // src/icu.ts
114
- var ICU_ARG = /\{\s*[a-zA-Z0-9_]+\s*,\s*(?:plural|selectordinal|select|number|date|time)\b/;
154
+ //#endregion
155
+ //#region src/icu.ts
156
+ const ICU_ARG = /\{\s*[a-zA-Z0-9_]+\s*,\s*(?:plural|selectordinal|select|number|date|time)\b/;
115
157
  function isIcu(message) {
116
- return ICU_ARG.test(message);
158
+ return ICU_ARG.test(message);
117
159
  }
118
160
  function parseIcu(message) {
119
- let i = 0;
120
- const at = () => message.charAt(i);
121
- const skipWs = () => {
122
- while (i < message.length && /\s/.test(at())) i++;
123
- };
124
- const readIdent = () => {
125
- let s = "";
126
- while (i < message.length && /[a-zA-Z0-9_]/.test(at())) s += message[i++];
127
- return s;
128
- };
129
- function parseBody(inPlural) {
130
- const nodes = [];
131
- let buf = "";
132
- const flush = () => {
133
- if (buf) nodes.push({ kind: "text", value: buf });
134
- buf = "";
135
- };
136
- while (i < message.length) {
137
- const ch = at();
138
- if (ch === "}") break;
139
- if (ch === "{") {
140
- flush();
141
- nodes.push(parseArg());
142
- } else if (ch === "#" && inPlural) {
143
- flush();
144
- nodes.push({ kind: "hash" });
145
- i++;
146
- } else if (ch === "'") {
147
- buf += readQuoted();
148
- } else {
149
- buf += ch;
150
- i++;
151
- }
152
- }
153
- flush();
154
- return nodes;
155
- }
156
- function readQuoted() {
157
- i++;
158
- if (at() === "'") {
159
- i++;
160
- return "'";
161
- }
162
- const next = at();
163
- if (next !== "{" && next !== "}" && next !== "#") return "'";
164
- let out = "";
165
- while (i < message.length) {
166
- if (at() === "'") {
167
- if (message.charAt(i + 1) === "'") {
168
- out += "'";
169
- i += 2;
170
- continue;
171
- }
172
- i++;
173
- return out;
174
- }
175
- out += message[i++];
176
- }
177
- return out;
178
- }
179
- function parseArg() {
180
- i++;
181
- skipWs();
182
- const name = readIdent();
183
- skipWs();
184
- if (at() === "}") {
185
- i++;
186
- return { kind: "param", name };
187
- }
188
- if (at() === ",") i++;
189
- skipWs();
190
- const type = readIdent();
191
- const node = { kind: "param", name };
192
- if (type === "number" || type === "date" || type === "time") {
193
- skipWs();
194
- let style = "";
195
- if (at() === ",") {
196
- i++;
197
- skipWs();
198
- while (i < message.length && at() !== "}" && at() !== ",") style += message[i++];
199
- style = style.trim();
200
- }
201
- if (type === "number") {
202
- node.format = style === "integer" ? "integer" : style === "percent" ? "percent" : style === "currency" ? "currency" : "number";
203
- } else {
204
- node.format = type;
205
- if (style) node.arg = style;
206
- }
207
- skipToClose();
208
- return node;
209
- }
210
- if (type === "plural" || type === "selectordinal" || type === "select") {
211
- if (type === "selectordinal") node.ordinal = true;
212
- const variants = [];
213
- skipWs();
214
- if (at() === ",") i++;
215
- skipWs();
216
- if (type !== "select" && message.startsWith("offset:", i)) {
217
- i += 7;
218
- skipWs();
219
- while (i < message.length && /[0-9]/.test(at())) i++;
220
- skipWs();
221
- }
222
- while (i < message.length && at() !== "}") {
223
- const selector = readSelector();
224
- skipWs();
225
- if (at() !== "{") break;
226
- i++;
227
- const body = parseBody(type !== "select");
228
- if (at() === "}") i++;
229
- variants.push([selector, body]);
230
- skipWs();
231
- }
232
- if (at() === "}") i++;
233
- node.variants = variants;
234
- return node;
235
- }
236
- skipToClose();
237
- return node;
238
- }
239
- function readSelector() {
240
- if (at() === "=") {
241
- let s2 = "=";
242
- i++;
243
- while (i < message.length && /[0-9]/.test(at())) s2 += message[i++];
244
- return s2;
245
- }
246
- let s = "";
247
- while (i < message.length && !/[\s{]/.test(at())) s += message[i++];
248
- return s;
249
- }
250
- function skipToClose() {
251
- while (i < message.length && at() !== "}") i++;
252
- if (at() === "}") i++;
253
- }
254
- return parseBody(false);
161
+ let i = 0;
162
+ const at = () => message.charAt(i);
163
+ const skipWs = () => {
164
+ while (i < message.length && /\s/.test(at())) i++;
165
+ };
166
+ const readIdent = () => {
167
+ let s = "";
168
+ while (i < message.length && /[a-zA-Z0-9_]/.test(at())) s += message[i++];
169
+ return s;
170
+ };
171
+ function parseBody(inPlural) {
172
+ const nodes = [];
173
+ let buf = "";
174
+ const flush = () => {
175
+ if (buf) nodes.push({
176
+ kind: "text",
177
+ value: buf
178
+ });
179
+ buf = "";
180
+ };
181
+ while (i < message.length) {
182
+ const ch = at();
183
+ if (ch === "}") break;
184
+ if (ch === "{") {
185
+ flush();
186
+ nodes.push(parseArg());
187
+ } else if (ch === "#" && inPlural) {
188
+ flush();
189
+ nodes.push({ kind: "hash" });
190
+ i++;
191
+ } else if (ch === "'") buf += readQuoted();
192
+ else {
193
+ buf += ch;
194
+ i++;
195
+ }
196
+ }
197
+ flush();
198
+ return nodes;
199
+ }
200
+ function readQuoted() {
201
+ i++;
202
+ if (at() === "'") {
203
+ i++;
204
+ return "'";
205
+ }
206
+ const next = at();
207
+ if (next !== "{" && next !== "}" && next !== "#") return "'";
208
+ let out = "";
209
+ while (i < message.length) {
210
+ if (at() === "'") {
211
+ if (message.charAt(i + 1) === "'") {
212
+ out += "'";
213
+ i += 2;
214
+ continue;
215
+ }
216
+ i++;
217
+ return out;
218
+ }
219
+ out += message[i++];
220
+ }
221
+ return out;
222
+ }
223
+ function parseArg() {
224
+ i++;
225
+ skipWs();
226
+ const name = readIdent();
227
+ skipWs();
228
+ if (at() === "}") {
229
+ i++;
230
+ return {
231
+ kind: "param",
232
+ name
233
+ };
234
+ }
235
+ if (at() === ",") i++;
236
+ skipWs();
237
+ const type = readIdent();
238
+ const node = {
239
+ kind: "param",
240
+ name
241
+ };
242
+ if (type === "number" || type === "date" || type === "time") {
243
+ skipWs();
244
+ let style = "";
245
+ if (at() === ",") {
246
+ i++;
247
+ skipWs();
248
+ while (i < message.length && at() !== "}" && at() !== ",") style += message[i++];
249
+ style = style.trim();
250
+ }
251
+ if (type === "number") node.format = style === "integer" ? "integer" : style === "percent" ? "percent" : style === "currency" ? "currency" : "number";
252
+ else {
253
+ node.format = type;
254
+ if (style) node.arg = style;
255
+ }
256
+ skipToClose();
257
+ return node;
258
+ }
259
+ if (type === "plural" || type === "selectordinal" || type === "select") {
260
+ if (type === "selectordinal") node.ordinal = true;
261
+ const variants = [];
262
+ skipWs();
263
+ if (at() === ",") i++;
264
+ skipWs();
265
+ if (type !== "select" && message.startsWith("offset:", i)) {
266
+ i += 7;
267
+ skipWs();
268
+ while (i < message.length && /[0-9]/.test(at())) i++;
269
+ skipWs();
270
+ }
271
+ while (i < message.length && at() !== "}") {
272
+ const selector = readSelector();
273
+ skipWs();
274
+ if (at() !== "{") break;
275
+ i++;
276
+ const body = parseBody(type !== "select");
277
+ if (at() === "}") i++;
278
+ variants.push([selector, body]);
279
+ skipWs();
280
+ }
281
+ if (at() === "}") i++;
282
+ node.variants = variants;
283
+ return node;
284
+ }
285
+ skipToClose();
286
+ return node;
287
+ }
288
+ function readSelector() {
289
+ if (at() === "=") {
290
+ let s = "=";
291
+ i++;
292
+ while (i < message.length && /[0-9]/.test(at())) s += message[i++];
293
+ return s;
294
+ }
295
+ let s = "";
296
+ while (i < message.length && !/[\s{]/.test(at())) s += message[i++];
297
+ return s;
298
+ }
299
+ function skipToClose() {
300
+ while (i < message.length && at() !== "}") i++;
301
+ if (at() === "}") i++;
302
+ }
303
+ return parseBody(false);
255
304
  }
256
-
257
- // src/parse.ts
258
- var astCache = /* @__PURE__ */ new Map();
259
- var AST_CACHE_MAX = 2e3;
305
+ //#endregion
306
+ //#region src/parse.ts
307
+ const astCache = /* @__PURE__ */ new Map();
308
+ const AST_CACHE_MAX = 2e3;
260
309
  function parse(message) {
261
- let cached = astCache.get(message);
262
- if (!cached) {
263
- if (astCache.size >= AST_CACHE_MAX) astCache.clear();
264
- cached = isIcu(message) ? parseIcu(message) : parseMessage(message, false);
265
- astCache.set(message, cached);
266
- }
267
- return cached;
310
+ let cached = astCache.get(message);
311
+ if (!cached) {
312
+ if (astCache.size >= AST_CACHE_MAX) astCache.clear();
313
+ cached = isIcu(message) ? parseIcu(message) : parseMessage(message, false);
314
+ astCache.set(message, cached);
315
+ }
316
+ return cached;
268
317
  }
269
318
  function parseMessage(input, inVariant) {
270
- const nodes = [];
271
- let buf = "";
272
- let i = 0;
273
- const flush = () => {
274
- if (buf) nodes.push({ kind: "text", value: buf });
275
- buf = "";
276
- };
277
- while (i < input.length) {
278
- const ch = input[i];
279
- if (ch === "{") {
280
- if (input[i + 1] === "{") {
281
- buf += "{";
282
- i += 2;
283
- continue;
284
- }
285
- const close = findClose(input, i);
286
- if (close < 0) {
287
- buf += input.slice(i);
288
- break;
289
- }
290
- flush();
291
- nodes.push(parsePlaceholder(input.slice(i + 1, close)));
292
- i = close + 1;
293
- } else if (ch === "}" && input[i + 1] === "}") {
294
- buf += "}";
295
- i += 2;
296
- } else if (inVariant && ch === "#") {
297
- if (input[i + 1] === "#") {
298
- buf += "#";
299
- i += 2;
300
- } else {
301
- flush();
302
- nodes.push({ kind: "hash" });
303
- i += 1;
304
- }
305
- } else {
306
- buf += ch;
307
- i += 1;
308
- }
309
- }
310
- flush();
311
- return nodes;
319
+ const nodes = [];
320
+ let buf = "";
321
+ let i = 0;
322
+ const flush = () => {
323
+ if (buf) nodes.push({
324
+ kind: "text",
325
+ value: buf
326
+ });
327
+ buf = "";
328
+ };
329
+ while (i < input.length) {
330
+ const ch = input[i];
331
+ if (ch === "{") {
332
+ if (input[i + 1] === "{") {
333
+ buf += "{";
334
+ i += 2;
335
+ continue;
336
+ }
337
+ const close = findClose(input, i);
338
+ if (close < 0) {
339
+ buf += input.slice(i);
340
+ break;
341
+ }
342
+ flush();
343
+ nodes.push(parsePlaceholder(input.slice(i + 1, close)));
344
+ i = close + 1;
345
+ } else if (ch === "}" && input[i + 1] === "}") {
346
+ buf += "}";
347
+ i += 2;
348
+ } else if (inVariant && ch === "#") if (input[i + 1] === "#") {
349
+ buf += "#";
350
+ i += 2;
351
+ } else {
352
+ flush();
353
+ nodes.push({ kind: "hash" });
354
+ i += 1;
355
+ }
356
+ else {
357
+ buf += ch;
358
+ i += 1;
359
+ }
360
+ }
361
+ flush();
362
+ return nodes;
312
363
  }
313
364
  function findClose(input, open) {
314
- let depth = 0;
315
- let i = open;
316
- while (i < input.length) {
317
- const ch = input[i];
318
- if (ch === "{") {
319
- if (input[i + 1] === "{") {
320
- i += 2;
321
- continue;
322
- }
323
- depth += 1;
324
- } else if (ch === "}") {
325
- if (input[i + 1] === "}") {
326
- i += 2;
327
- continue;
328
- }
329
- depth -= 1;
330
- if (depth === 0) return i;
331
- }
332
- i += 1;
333
- }
334
- return -1;
365
+ let depth = 0;
366
+ let i = open;
367
+ while (i < input.length) {
368
+ const ch = input[i];
369
+ if (ch === "{") {
370
+ if (input[i + 1] === "{") {
371
+ i += 2;
372
+ continue;
373
+ }
374
+ depth += 1;
375
+ } else if (ch === "}") {
376
+ if (input[i + 1] === "}") {
377
+ i += 2;
378
+ continue;
379
+ }
380
+ depth -= 1;
381
+ if (depth === 0) return i;
382
+ }
383
+ i += 1;
384
+ }
385
+ return -1;
335
386
  }
336
387
  function parsePlaceholder(inner) {
337
- const segments = splitTop(inner);
338
- const head = (segments[0] ?? "").trim();
339
- if (!head) return { kind: "text", value: `{${inner}}` };
340
- const colon = head.indexOf(":");
341
- const name = (colon < 0 ? head : head.slice(0, colon)).trim();
342
- if (!name) return { kind: "text", value: `{${inner}}` };
343
- const node = { kind: "param", name };
344
- if (colon >= 0) {
345
- const fmtRaw = head.slice(colon + 1).trim();
346
- const slash = fmtRaw.indexOf("/");
347
- node.format = (slash < 0 ? fmtRaw : fmtRaw.slice(0, slash)).trim();
348
- if (slash >= 0) node.arg = fmtRaw.slice(slash + 1).trim();
349
- }
350
- if (segments.length > 1) {
351
- node.variants = [];
352
- for (const seg of segments.slice(1)) {
353
- const sep = seg.indexOf(":");
354
- if (sep < 0) continue;
355
- const key = seg.slice(0, sep).trim();
356
- const body = seg.slice(sep + 1).trim();
357
- if (key) node.variants.push([key, parseMessage(body, true)]);
358
- }
359
- }
360
- return node;
388
+ const segments = splitTop(inner);
389
+ const head = (segments[0] ?? "").trim();
390
+ if (!head) return {
391
+ kind: "text",
392
+ value: `{${inner}}`
393
+ };
394
+ const colon = head.indexOf(":");
395
+ const name = (colon < 0 ? head : head.slice(0, colon)).trim();
396
+ if (!name) return {
397
+ kind: "text",
398
+ value: `{${inner}}`
399
+ };
400
+ const node = {
401
+ kind: "param",
402
+ name
403
+ };
404
+ if (colon >= 0) {
405
+ const fmtRaw = head.slice(colon + 1).trim();
406
+ const slash = fmtRaw.indexOf("/");
407
+ node.format = (slash < 0 ? fmtRaw : fmtRaw.slice(0, slash)).trim();
408
+ if (slash >= 0) node.arg = fmtRaw.slice(slash + 1).trim();
409
+ }
410
+ if (segments.length > 1) {
411
+ node.variants = [];
412
+ for (const seg of segments.slice(1)) {
413
+ const sep = seg.indexOf(":");
414
+ if (sep < 0) continue;
415
+ const key = seg.slice(0, sep).trim();
416
+ const body = seg.slice(sep + 1).trim();
417
+ if (key) node.variants.push([key, parseMessage(body, true)]);
418
+ }
419
+ }
420
+ return node;
361
421
  }
362
422
  function splitTop(input) {
363
- const parts = [];
364
- let buf = "";
365
- let depth = 0;
366
- let i = 0;
367
- while (i < input.length) {
368
- const ch = input[i];
369
- if (ch === "{") {
370
- if (input[i + 1] === "{") {
371
- buf += "{{";
372
- i += 2;
373
- continue;
374
- }
375
- depth += 1;
376
- buf += ch;
377
- } else if (ch === "}") {
378
- if (input[i + 1] === "}") {
379
- buf += "}}";
380
- i += 2;
381
- continue;
382
- }
383
- depth -= 1;
384
- buf += ch;
385
- } else if (ch === "|" && depth === 0) {
386
- if (input[i + 1] === "|") {
387
- buf += "|";
388
- i += 2;
389
- continue;
390
- }
391
- parts.push(buf);
392
- buf = "";
393
- } else {
394
- buf += ch;
395
- }
396
- i += 1;
397
- }
398
- parts.push(buf);
399
- return parts;
423
+ const parts = [];
424
+ let buf = "";
425
+ let depth = 0;
426
+ let i = 0;
427
+ while (i < input.length) {
428
+ const ch = input[i];
429
+ if (ch === "{") {
430
+ if (input[i + 1] === "{") {
431
+ buf += "{{";
432
+ i += 2;
433
+ continue;
434
+ }
435
+ depth += 1;
436
+ buf += ch;
437
+ } else if (ch === "}") {
438
+ if (input[i + 1] === "}") {
439
+ buf += "}}";
440
+ i += 2;
441
+ continue;
442
+ }
443
+ depth -= 1;
444
+ buf += ch;
445
+ } else if (ch === "|" && depth === 0) {
446
+ if (input[i + 1] === "|") {
447
+ buf += "|";
448
+ i += 2;
449
+ continue;
450
+ }
451
+ parts.push(buf);
452
+ buf = "";
453
+ } else buf += ch;
454
+ i += 1;
455
+ }
456
+ parts.push(buf);
457
+ return parts;
400
458
  }
401
-
402
- // src/instance.ts
459
+ //#endregion
460
+ //#region src/instance.ts
403
461
  function createVerbaly(options = {}) {
404
- const dict = {};
405
- const listeners = /* @__PURE__ */ new Set();
406
- const formatters = options.formatters ?? {};
407
- const loaders = options.loaders ?? {};
408
- const loaded = /* @__PURE__ */ new Set();
409
- const inFlight = /* @__PURE__ */ new Map();
410
- const warned = /* @__PURE__ */ new Set();
411
- const fallbacks = options.fallback ? Array.isArray(options.fallback) ? options.fallback : [options.fallback] : [];
412
- let locale = options.locale ?? detectLocale();
413
- let version = 0;
414
- let chainCache = null;
415
- if (options.messages) {
416
- for (const [loc, tree] of Object.entries(options.messages)) {
417
- dict[loc] = flatten(tree);
418
- }
419
- }
420
- function chain() {
421
- if (chainCache) return chainCache;
422
- const result = [];
423
- const parts = locale.split("-");
424
- while (parts.length > 0) {
425
- result.push(parts.join("-"));
426
- parts.pop();
427
- }
428
- for (const fb of fallbacks) if (!result.includes(fb)) result.push(fb);
429
- chainCache = result;
430
- return result;
431
- }
432
- function lookup(key) {
433
- for (const loc of chain()) {
434
- const msg = dict[loc]?.[key];
435
- if (msg !== void 0) return msg;
436
- }
437
- return void 0;
438
- }
439
- function translate(key, params) {
440
- const msg = lookup(key);
441
- if (msg === void 0) {
442
- const replacement = options.onMissing?.(key, locale);
443
- if (typeof replacement === "string") return replacement;
444
- if (!options.onMissing && !warned.has(key)) {
445
- warned.add(key);
446
- console.warn(`[verbaly] missing key "${key}" (${locale})`);
447
- }
448
- return key;
449
- }
450
- return formatNodes(parse(msg), { locale, params, formatters });
451
- }
452
- function tagged(strings, values) {
453
- let out = strings[0] ?? "";
454
- for (let i = 0; i < values.length; i++) {
455
- out += autoFormat(values[i], locale) + (strings[i + 1] ?? "");
456
- }
457
- return out;
458
- }
459
- function notify() {
460
- version += 1;
461
- for (const fn of listeners) fn();
462
- }
463
- const t = ((first, ...rest) => {
464
- if (isTemplateStrings(first)) return tagged(first, rest);
465
- return translate(first, rest[0]);
466
- });
467
- t.id = () => (strings, ...values) => tagged(strings, values);
468
- function pendingLoader(target) {
469
- const parts = target.split("-");
470
- while (parts.length > 0) {
471
- const candidate = parts.join("-");
472
- if (loaders[candidate] && !loaded.has(candidate)) return candidate;
473
- if (loaders[candidate]) return void 0;
474
- parts.pop();
475
- }
476
- return void 0;
477
- }
478
- function loadLocale(target) {
479
- const pending = pendingLoader(target);
480
- if (!pending) return Promise.resolve();
481
- const running = inFlight.get(pending);
482
- if (running) return running;
483
- const load = loaders[pending]().then((mod) => {
484
- loaded.add(pending);
485
- inFlight.delete(pending);
486
- addMessages(
487
- pending,
488
- "default" in mod ? mod.default : mod
489
- );
490
- }).catch((error) => {
491
- inFlight.delete(pending);
492
- throw error;
493
- });
494
- inFlight.set(pending, load);
495
- return load;
496
- }
497
- function addMessages(loc, messages) {
498
- dict[loc] = { ...dict[loc], ...flatten(messages) };
499
- notify();
500
- }
501
- return {
502
- get locale() {
503
- return locale;
504
- },
505
- get locales() {
506
- return [.../* @__PURE__ */ new Set([...Object.keys(dict), ...Object.keys(loaders)])];
507
- },
508
- get version() {
509
- return version;
510
- },
511
- t,
512
- setLocale(next) {
513
- if (pendingLoader(next)) {
514
- void loadLocale(next).catch(() => {
515
- if (!warned.has(`load:${next}`)) {
516
- warned.add(`load:${next}`);
517
- console.warn(`[verbaly] failed to load catalog for "${next}"`);
518
- }
519
- });
520
- }
521
- if (next === locale) return;
522
- locale = next;
523
- chainCache = null;
524
- notify();
525
- },
526
- loadLocale,
527
- addMessages,
528
- subscribe(listener) {
529
- listeners.add(listener);
530
- return () => {
531
- listeners.delete(listener);
532
- };
533
- },
534
- has(key) {
535
- return lookup(key) !== void 0;
536
- }
537
- };
462
+ const dict = {};
463
+ const listeners = /* @__PURE__ */ new Set();
464
+ const formatters = options.formatters ?? {};
465
+ const loaders = options.loaders ?? {};
466
+ const loaded = /* @__PURE__ */ new Set();
467
+ const inFlight = /* @__PURE__ */ new Map();
468
+ const warned = /* @__PURE__ */ new Set();
469
+ const fallbacks = options.fallback ? Array.isArray(options.fallback) ? options.fallback : [options.fallback] : [];
470
+ let locale = options.locale ?? detectLocale();
471
+ let version = 0;
472
+ let chainCache = null;
473
+ if (options.messages) for (const [loc, tree] of Object.entries(options.messages)) dict[loc] = flatten(tree);
474
+ function chain() {
475
+ if (chainCache) return chainCache;
476
+ const result = [];
477
+ const parts = locale.split("-");
478
+ while (parts.length > 0) {
479
+ result.push(parts.join("-"));
480
+ parts.pop();
481
+ }
482
+ for (const fb of fallbacks) if (!result.includes(fb)) result.push(fb);
483
+ chainCache = result;
484
+ return result;
485
+ }
486
+ function lookup(key) {
487
+ for (const loc of chain()) {
488
+ const msg = dict[loc]?.[key];
489
+ if (msg !== void 0) return msg;
490
+ }
491
+ }
492
+ function translate(key, params) {
493
+ const msg = lookup(key);
494
+ if (msg === void 0) {
495
+ const replacement = options.onMissing?.(key, locale);
496
+ if (typeof replacement === "string") return replacement;
497
+ if (!options.onMissing && !warned.has(key)) {
498
+ warned.add(key);
499
+ console.warn(`[verbaly] missing key "${key}" (${locale})`);
500
+ }
501
+ return key;
502
+ }
503
+ return formatNodes(parse(msg), {
504
+ locale,
505
+ params,
506
+ formatters
507
+ });
508
+ }
509
+ function tagged(strings, values) {
510
+ let out = strings[0] ?? "";
511
+ for (let i = 0; i < values.length; i++) out += autoFormat(values[i], locale) + (strings[i + 1] ?? "");
512
+ return out;
513
+ }
514
+ function notify() {
515
+ version += 1;
516
+ for (const fn of listeners) fn();
517
+ }
518
+ const t = ((first, ...rest) => {
519
+ if (isTemplateStrings(first)) return tagged(first, rest);
520
+ return translate(first, rest[0]);
521
+ });
522
+ t.id = () => (strings, ...values) => tagged(strings, values);
523
+ function pendingLoader(target) {
524
+ const parts = target.split("-");
525
+ while (parts.length > 0) {
526
+ const candidate = parts.join("-");
527
+ if (loaders[candidate] && !loaded.has(candidate)) return candidate;
528
+ if (loaders[candidate]) return void 0;
529
+ parts.pop();
530
+ }
531
+ }
532
+ function loadLocale(target) {
533
+ const pending = pendingLoader(target);
534
+ if (!pending) return Promise.resolve();
535
+ const running = inFlight.get(pending);
536
+ if (running) return running;
537
+ const load = loaders[pending]().then((mod) => {
538
+ loaded.add(pending);
539
+ inFlight.delete(pending);
540
+ addMessages(pending, "default" in mod ? mod.default : mod);
541
+ }).catch((error) => {
542
+ inFlight.delete(pending);
543
+ throw error;
544
+ });
545
+ inFlight.set(pending, load);
546
+ return load;
547
+ }
548
+ function addMessages(loc, messages) {
549
+ dict[loc] = {
550
+ ...dict[loc],
551
+ ...flatten(messages)
552
+ };
553
+ notify();
554
+ }
555
+ return {
556
+ get locale() {
557
+ return locale;
558
+ },
559
+ get locales() {
560
+ return [.../* @__PURE__ */ new Set([...Object.keys(dict), ...Object.keys(loaders)])];
561
+ },
562
+ get version() {
563
+ return version;
564
+ },
565
+ t,
566
+ setLocale(next) {
567
+ if (pendingLoader(next)) loadLocale(next).catch(() => {
568
+ if (!warned.has(`load:${next}`)) {
569
+ warned.add(`load:${next}`);
570
+ console.warn(`[verbaly] failed to load catalog for "${next}"`);
571
+ }
572
+ });
573
+ if (next === locale) return;
574
+ locale = next;
575
+ chainCache = null;
576
+ notify();
577
+ },
578
+ loadLocale,
579
+ addMessages,
580
+ subscribe(listener) {
581
+ listeners.add(listener);
582
+ return () => {
583
+ listeners.delete(listener);
584
+ };
585
+ },
586
+ has(key) {
587
+ return lookup(key) !== void 0;
588
+ }
589
+ };
538
590
  }
539
591
  function isTemplateStrings(value) {
540
- return Array.isArray(value) && "raw" in value;
592
+ return Array.isArray(value) && "raw" in value;
541
593
  }
542
594
  function detectLocale() {
543
- return typeof navigator !== "undefined" && navigator.language ? navigator.language : "en";
595
+ return typeof navigator !== "undefined" && navigator.language ? navigator.language : "en";
544
596
  }
545
-
546
- // src/tags.ts
547
- var TAG = /<(\/?)([a-zA-Z][\w-]*)(\/?)>/g;
597
+ //#endregion
598
+ //#region src/tags.ts
599
+ const TAG = /<(\/?)([a-zA-Z][\w-]*)(\/?)>/g;
548
600
  function parseTags(text) {
549
- const re = new RegExp(TAG.source, "g");
550
- const root = [];
551
- const stack = [];
552
- const top = () => stack.length ? stack[stack.length - 1].children : root;
553
- const pushText = (s) => {
554
- if (s) top().push(s);
555
- };
556
- let last = 0;
557
- let m;
558
- while ((m = re.exec(text)) !== null) {
559
- const [full, closing, name, selfClose] = m;
560
- pushText(text.slice(last, m.index));
561
- last = m.index + full.length;
562
- if (selfClose) {
563
- top().push({ name, children: [] });
564
- } else if (closing) {
565
- if (stack.length && stack[stack.length - 1].name === name) {
566
- const node = stack.pop();
567
- top().push(node);
568
- } else {
569
- pushText(full);
570
- }
571
- } else {
572
- stack.push({ name, children: [] });
573
- }
574
- }
575
- pushText(text.slice(last));
576
- while (stack.length) {
577
- const node = stack.pop();
578
- top().push(...node.children);
579
- }
580
- return root;
601
+ const re = new RegExp(TAG.source, "g");
602
+ const root = [];
603
+ const stack = [];
604
+ const top = () => stack.length ? stack[stack.length - 1].children : root;
605
+ const pushText = (s) => {
606
+ if (s) top().push(s);
607
+ };
608
+ let last = 0;
609
+ let m;
610
+ while ((m = re.exec(text)) !== null) {
611
+ const [full, closing, name, selfClose] = m;
612
+ pushText(text.slice(last, m.index));
613
+ last = m.index + full.length;
614
+ if (selfClose) top().push({
615
+ name,
616
+ children: []
617
+ });
618
+ else if (closing) if (stack.length && stack[stack.length - 1].name === name) {
619
+ const node = stack.pop();
620
+ top().push(node);
621
+ } else pushText(full);
622
+ else stack.push({
623
+ name,
624
+ children: []
625
+ });
626
+ }
627
+ pushText(text.slice(last));
628
+ while (stack.length) {
629
+ const node = stack.pop();
630
+ top().push(...node.children);
631
+ }
632
+ return root;
581
633
  }
582
-
583
- // src/dom.ts
584
- var RICH_TAGS = [
585
- "em",
586
- "strong",
587
- "code",
588
- "b",
589
- "i",
590
- "u",
591
- "s",
592
- "small",
593
- "mark",
594
- "sub",
595
- "sup",
596
- "span",
597
- "kbd",
598
- "abbr",
599
- "br",
600
- "wbr"
634
+ //#endregion
635
+ //#region src/dom.ts
636
+ const UNSAFE_HREF = /^\s*(javascript|data|vbscript):/i;
637
+ function safeHref(href) {
638
+ if (UNSAFE_HREF.test(href)) {
639
+ console.warn(`[verbaly] blocked unsafe href: ${href}`);
640
+ return;
641
+ }
642
+ return href;
643
+ }
644
+ const RICH_TAGS = [
645
+ "em",
646
+ "strong",
647
+ "code",
648
+ "b",
649
+ "i",
650
+ "u",
651
+ "s",
652
+ "small",
653
+ "mark",
654
+ "sub",
655
+ "sup",
656
+ "span",
657
+ "kbd",
658
+ "abbr",
659
+ "br",
660
+ "wbr"
601
661
  ];
602
662
  function bindDom(instance, options = {}) {
603
- if (typeof document === "undefined") {
604
- throw new Error("[verbaly] bindDom requires a DOM");
605
- }
606
- const t = instance.t;
607
- const root = options.root ?? document.body;
608
- const attr = options.attribute ?? "data-verbaly";
609
- const argsAttr = `${attr}-args`;
610
- const attrsAttr = `${attr}-attr`;
611
- const richAttr = `${attr}-rich`;
612
- const richTags = new Set(options.richTags ?? RICH_TAGS);
613
- const argsCache = /* @__PURE__ */ new WeakMap();
614
- function cachedArgs(el) {
615
- const raw = el.getAttribute(argsAttr);
616
- const hit = argsCache.get(el);
617
- if (hit && hit.raw === raw) return hit.params;
618
- const params = parseArgs(raw);
619
- argsCache.set(el, { raw, params });
620
- return params;
621
- }
622
- function renderRich(el, nodes) {
623
- for (const node of nodes) {
624
- if (typeof node === "string") {
625
- el.append(node);
626
- } else if (richTags.has(node.name)) {
627
- const child = el.ownerDocument.createElement(node.name);
628
- renderRich(child, node.children);
629
- el.append(child);
630
- } else {
631
- renderRich(el, node.children);
632
- }
633
- }
634
- }
635
- function render(el) {
636
- const args = cachedArgs(el);
637
- const key = el.getAttribute(attr);
638
- if (key) {
639
- const text = t(key, args);
640
- if (el.hasAttribute(richAttr)) {
641
- el.textContent = "";
642
- renderRich(el, parseTags(text));
643
- } else {
644
- el.textContent = text;
645
- }
646
- }
647
- const attrMap = parseArgs(el.getAttribute(attrsAttr));
648
- if (attrMap) {
649
- for (const [name, attrKey] of Object.entries(attrMap)) {
650
- if (typeof attrKey !== "string" || name.toLowerCase().startsWith("on")) continue;
651
- el.setAttribute(name, t(attrKey, args));
652
- }
653
- }
654
- }
655
- const selector = `[${attr}], [${attrsAttr}]`;
656
- function renderAll(scope) {
657
- if (scope instanceof Element && scope.matches(selector)) render(scope);
658
- for (const el of scope.querySelectorAll(selector)) render(el);
659
- }
660
- renderAll(root);
661
- const unsubscribe = instance.subscribe(() => renderAll(root));
662
- const observer = new MutationObserver((records) => {
663
- for (const record of records) {
664
- if (record.type === "attributes" && record.target instanceof Element) {
665
- render(record.target);
666
- } else if (record.type === "childList") {
667
- for (const node of record.addedNodes) {
668
- if (node instanceof Element) renderAll(node);
669
- }
670
- }
671
- }
672
- });
673
- observer.observe(root instanceof Document ? root.documentElement : root, {
674
- childList: true,
675
- subtree: true,
676
- attributes: true,
677
- attributeFilter: [attr, argsAttr, attrsAttr, richAttr]
678
- });
679
- return () => {
680
- unsubscribe();
681
- observer.disconnect();
682
- };
663
+ if (typeof document === "undefined") throw new Error("[verbaly] bindDom requires a DOM");
664
+ const t = instance.t;
665
+ const root = options.root ?? document.body;
666
+ const attr = options.attribute ?? "data-verbaly";
667
+ const argsAttr = `${attr}-args`;
668
+ const attrsAttr = `${attr}-attr`;
669
+ const richAttr = `${attr}-rich`;
670
+ const linksAttr = `${attr}-links`;
671
+ const richTags = new Set(options.richTags ?? RICH_TAGS);
672
+ const globalLinks = options.richLinks;
673
+ const argsCache = /* @__PURE__ */ new WeakMap();
674
+ const linksCache = /* @__PURE__ */ new WeakMap();
675
+ function cachedArgs(el) {
676
+ const raw = el.getAttribute(argsAttr);
677
+ const hit = argsCache.get(el);
678
+ if (hit && hit.raw === raw) return hit.params;
679
+ const params = parseArgs(raw);
680
+ argsCache.set(el, {
681
+ raw,
682
+ params
683
+ });
684
+ return params;
685
+ }
686
+ function cachedLinks(el) {
687
+ const raw = el.getAttribute(linksAttr);
688
+ if (!raw) return globalLinks;
689
+ const hit = linksCache.get(el);
690
+ if (hit && hit.raw === raw) return hit.links;
691
+ const own = parseArgs(raw);
692
+ const links = own ? globalLinks ? {
693
+ ...globalLinks,
694
+ ...own
695
+ } : own : globalLinks;
696
+ linksCache.set(el, {
697
+ raw,
698
+ links
699
+ });
700
+ return links;
701
+ }
702
+ function renderRich(el, nodes, links) {
703
+ for (const node of nodes) if (typeof node === "string") el.append(node);
704
+ else if (links?.[node.name] !== void 0) {
705
+ const link = links[node.name];
706
+ const { href, target, rel } = typeof link === "string" ? { href: link } : link;
707
+ const a = el.ownerDocument.createElement("a");
708
+ const safe = safeHref(href);
709
+ if (safe !== void 0) a.setAttribute("href", safe);
710
+ if (target) a.setAttribute("target", target);
711
+ if (rel) a.setAttribute("rel", rel);
712
+ renderRich(a, node.children, links);
713
+ el.append(a);
714
+ } else if (richTags.has(node.name)) {
715
+ const child = el.ownerDocument.createElement(node.name);
716
+ renderRich(child, node.children, links);
717
+ el.append(child);
718
+ } else renderRich(el, node.children, links);
719
+ }
720
+ function render(el) {
721
+ const args = cachedArgs(el);
722
+ const key = el.getAttribute(attr);
723
+ if (key) {
724
+ const text = t(key, args);
725
+ if (el.hasAttribute(richAttr)) {
726
+ el.textContent = "";
727
+ renderRich(el, parseTags(text), cachedLinks(el));
728
+ } else el.textContent = text;
729
+ }
730
+ const attrMap = parseArgs(el.getAttribute(attrsAttr));
731
+ if (attrMap) for (const [name, attrKey] of Object.entries(attrMap)) {
732
+ if (typeof attrKey !== "string" || name.toLowerCase().startsWith("on")) continue;
733
+ el.setAttribute(name, t(attrKey, args));
734
+ }
735
+ }
736
+ const selector = `[${attr}], [${attrsAttr}]`;
737
+ function renderAll(scope) {
738
+ if (scope instanceof Element && scope.matches(selector)) render(scope);
739
+ for (const el of scope.querySelectorAll(selector)) render(el);
740
+ }
741
+ renderAll(root);
742
+ const unsubscribe = instance.subscribe(() => renderAll(root));
743
+ const observer = new MutationObserver((records) => {
744
+ for (const record of records) if (record.type === "attributes" && record.target instanceof Element) render(record.target);
745
+ else if (record.type === "childList") {
746
+ for (const node of record.addedNodes) if (node instanceof Element) renderAll(node);
747
+ }
748
+ });
749
+ observer.observe(root instanceof Document ? root.documentElement : root, {
750
+ childList: true,
751
+ subtree: true,
752
+ attributes: true,
753
+ attributeFilter: [
754
+ attr,
755
+ argsAttr,
756
+ attrsAttr,
757
+ richAttr,
758
+ linksAttr
759
+ ]
760
+ });
761
+ return () => {
762
+ unsubscribe();
763
+ observer.disconnect();
764
+ };
683
765
  }
684
766
  function parseArgs(raw) {
685
- if (!raw) return void 0;
686
- try {
687
- return JSON.parse(raw);
688
- } catch {
689
- console.warn(`[verbaly] invalid args JSON: ${raw}`);
690
- return void 0;
691
- }
767
+ if (!raw) return void 0;
768
+ try {
769
+ return JSON.parse(raw);
770
+ } catch {
771
+ console.warn(`[verbaly] invalid args JSON: ${raw}`);
772
+ return;
773
+ }
692
774
  }
693
-
694
- // src/locale.ts
695
- var DEFAULT_KEY = "verbaly-locale";
775
+ //#endregion
776
+ //#region src/locale.ts
777
+ const DEFAULT_KEY = "verbaly-locale";
696
778
  function resolveLocale(options) {
697
- const { supported, fallback = supported[0] ?? "en", storageKey = DEFAULT_KEY } = options;
698
- if (storageKey) {
699
- const stored = getStorage()?.getItem(storageKey);
700
- const match = stored && matchSupported(stored, supported);
701
- if (match) return match;
702
- }
703
- for (const lang of preferredLanguages()) {
704
- const match = matchSupported(lang, supported);
705
- if (match) return match;
706
- }
707
- return fallback;
779
+ const { supported, fallback = supported[0] ?? "en", storageKey = DEFAULT_KEY } = options;
780
+ if (storageKey) {
781
+ const stored = getStorage()?.getItem(storageKey);
782
+ const match = stored && matchSupported(stored, supported);
783
+ if (match) return match;
784
+ }
785
+ for (const lang of preferredLanguages()) {
786
+ const match = matchSupported(lang, supported);
787
+ if (match) return match;
788
+ }
789
+ return fallback;
708
790
  }
709
791
  function matchSupported(lang, supported) {
710
- if (supported.includes(lang)) return lang;
711
- const base = lang.split("-")[0];
712
- return supported.includes(base) ? base : void 0;
792
+ if (supported.includes(lang)) return lang;
793
+ const base = lang.split("-")[0];
794
+ return supported.includes(base) ? base : void 0;
713
795
  }
714
796
  function persistLocale(locale, storageKey = DEFAULT_KEY) {
715
- if (storageKey) getStorage()?.setItem(storageKey, locale);
716
- if (typeof document !== "undefined") document.documentElement.lang = locale;
797
+ if (storageKey) getStorage()?.setItem(storageKey, locale);
798
+ if (typeof document !== "undefined") document.documentElement.lang = locale;
717
799
  }
718
800
  function preferredLanguages() {
719
- if (typeof navigator === "undefined") return [];
720
- return navigator.languages?.length ? navigator.languages : [navigator.language];
801
+ if (typeof navigator === "undefined") return [];
802
+ return navigator.languages?.length ? navigator.languages : [navigator.language];
721
803
  }
722
804
  function getStorage() {
723
- try {
724
- return typeof localStorage === "undefined" ? null : localStorage;
725
- } catch {
726
- return null;
727
- }
728
- }
729
- export {
730
- RICH_TAGS,
731
- bindDom,
732
- createVerbaly,
733
- flatten,
734
- parse,
735
- parseTags,
736
- persistLocale,
737
- resolveLocale
738
- };
805
+ try {
806
+ return typeof localStorage === "undefined" ? null : localStorage;
807
+ } catch {
808
+ return null;
809
+ }
810
+ }
811
+ //#endregion
812
+ export { RICH_TAGS, bindDom, createVerbaly, flatten, parse, parseTags, persistLocale, resolveLocale, safeHref };
813
+
739
814
  //# sourceMappingURL=index.js.map