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