@intlify/core 11.4.18 → 12.0.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2225 +1,1733 @@
1
- /*!
2
- * core v11.4.18
3
- * (c) 2026 kazuya kawaguchi
4
- * Released under the MIT License.
5
- */
6
1
  /**
7
- * Original Utilities
8
- * written by kazuya kawaguchi
9
- */
10
- const inBrowser = typeof window !== 'undefined';
2
+ * @intlify/core v12.0.0-alpha.10
3
+ * (c) 2016-present kazuya kawaguchi and contributors
4
+ * @license MIT
5
+ **/
6
+ // packages/shared/src/utils.ts
7
+ /**
8
+ * Original Utilities
9
+ * written by kazuya kawaguchi
10
+ */
11
+ const inBrowser = typeof window !== "undefined";
11
12
  let mark;
12
13
  let measure;
13
14
  {
14
- const perf = inBrowser && window.performance;
15
- if (perf &&
16
- perf.mark &&
17
- perf.measure &&
18
- perf.clearMarks &&
19
- // @ts-ignore browser compat
20
- perf.clearMeasures) {
21
- mark = (tag) => {
22
- perf.mark(tag);
23
- };
24
- measure = (name, startTag, endTag) => {
25
- perf.measure(name, startTag, endTag);
26
- perf.clearMarks(startTag);
27
- perf.clearMarks(endTag);
28
- };
29
- }
30
- }
31
- const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
32
- /* eslint-disable */
15
+ const perf = inBrowser && window.performance;
16
+ if (perf && perf.mark && perf.measure && perf.clearMarks && perf.clearMeasures) {
17
+ mark = (tag) => {
18
+ perf.mark(tag);
19
+ };
20
+ measure = (name, startTag, endTag) => {
21
+ perf.measure(name, startTag, endTag);
22
+ perf.clearMarks(startTag);
23
+ perf.clearMarks(endTag);
24
+ perf.clearMeasures(name);
25
+ };
26
+ }
27
+ }
28
+ const RE_ARGS = /\{([0-9a-z]+)\}/gi;
33
29
  function format$1(message, ...args) {
34
- if (args.length === 1 && isObject(args[0])) {
35
- args = args[0];
36
- }
37
- if (!args || !args.hasOwnProperty) {
38
- args = {};
39
- }
40
- return message.replace(RE_ARGS, (match, identifier) => {
41
- return args.hasOwnProperty(identifier) ? args[identifier] : '';
42
- });
43
- }
44
- const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
45
- const friendlyJSONstringify = (json) => JSON.stringify(json)
46
- .replace(/\u2028/g, '\\u2028')
47
- .replace(/\u2029/g, '\\u2029')
48
- .replace(/\u0027/g, '\\u0027');
49
- const isNumber = (val) => typeof val === 'number' && isFinite(val);
30
+ if (args.length === 1 && isObject(args[0])) args = args[0];
31
+ if (!args || !args.hasOwnProperty) args = {};
32
+ return message.replace(RE_ARGS, (_match, identifier) => {
33
+ return args.hasOwnProperty(identifier) ? args[identifier] : "";
34
+ });
35
+ }
36
+ const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({
37
+ l: locale,
38
+ k: key,
39
+ s: source
40
+ });
41
+ const friendlyJSONstringify = (json) => JSON.stringify(json).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029").replace(/\u0027/g, "\\u0027");
42
+ const isNumber = (val) => typeof val === "number" && isFinite(val);
50
43
  function toDevtoolsGroupId(type, key) {
51
- return isString(key) || isNumber(key) ? `${type}:${key}` : type;
44
+ return isString(key) || isNumber(key) ? `${type}:${key}` : type;
52
45
  }
53
- const isDate = (val) => toTypeString(val) === '[object Date]';
54
- const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
55
- const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
46
+ const isDate = (val) => toTypeString(val) === "[object Date]";
47
+ const isRegExp = (val) => toTypeString(val) === "[object RegExp]";
48
+ const isKeylessObject = (val) => Object.keys(val).length === 0;
56
49
  const assign = Object.assign;
57
50
  const _create = Object.create;
58
51
  const create = (obj = null) => _create(obj);
59
52
  const hasOwnProperty = Object.prototype.hasOwnProperty;
60
53
  function hasOwn(obj, key) {
61
- return hasOwnProperty.call(obj, key);
54
+ return hasOwnProperty.call(obj, key);
62
55
  }
63
- /* eslint-enable */
64
56
  /**
65
- * Get `obj[key]` only when `key` is an own property of `obj`, so that a key
66
- * such as `constructor` does not read a property inherited from
67
- * `Object.prototype`.
68
- * The property is read before the check, so that a reactive `obj` tracks
69
- * `key` even when it is missing.
70
- */
71
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
57
+ * Get `obj[key]` only when `key` is an own property of `obj`, so that a key such as `constructor`
58
+ * does not read a property inherited from `Object.prototype`.
59
+ * The property is read before the check, so that a reactive `obj` tracks `key` even when it is missing.
60
+ */
72
61
  function getOwn(obj, key) {
73
- const value = obj[key];
74
- return hasOwn(obj, key) ? value : undefined;
62
+ const value = obj[key];
63
+ return hasOwn(obj, key) ? value : void 0;
75
64
  }
76
65
  /**
77
- * Whether `key` is a property name of `Object.prototype`, such as `__proto__`,
78
- * `constructor` or `toString`.
79
- * On a plain object, such a key reads a built-in, and assigning to `__proto__`
80
- * replaces the prototype.
81
- */
66
+ * Whether `key` is a property name of `Object.prototype`, such as `__proto__`, `constructor` or `toString`.
67
+ * On a plain object, such a key reads a built-in, and assigning to `__proto__` replaces the prototype.
68
+ */
82
69
  function isObjectPrototypeKey(key) {
83
- return hasOwn(Object.prototype, key);
70
+ return hasOwn(Object.prototype, key);
84
71
  }
85
72
  /**
86
- * Useful Utilities By Evan you
87
- * Modified by kazuya kawaguchi
88
- * MIT License
89
- * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
90
- * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
91
- */
73
+ * Useful Utilities By Evan you
74
+ * Modified by kazuya kawaguchi
75
+ * MIT License
76
+ * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
77
+ * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
78
+ */
92
79
  const isArray = Array.isArray;
93
- const isFunction = (val) => typeof val === 'function';
94
- const isString = (val) => typeof val === 'string';
95
- const isBoolean = (val) => typeof val === 'boolean';
96
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
97
- const isObject = (val) => val !== null && typeof val === 'object';
98
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
80
+ const isFunction = (val) => typeof val === "function";
81
+ const isString = (val) => typeof val === "string";
82
+ const isBoolean = (val) => typeof val === "boolean";
83
+ const isObject = (val) => val !== null && typeof val === "object";
99
84
  const isPromise = (val) => {
100
- return isObject(val) && isFunction(val.then) && isFunction(val.catch);
85
+ return isObject(val) && isFunction(val.then) && isFunction(val.catch);
101
86
  };
102
87
  const objectToString = Object.prototype.toString;
103
88
  const toTypeString = (value) => objectToString.call(value);
104
- const isPlainObject = (val) => toTypeString(val) === '[object Object]';
105
- // for converting list and named values to displayed strings.
89
+ const isPlainObject = (val) => toTypeString(val) === "[object Object]";
106
90
  const toDisplayString = (val) => {
107
- return val == null
108
- ? ''
109
- : isArray(val) || (isPlainObject(val) && val.toString === objectToString)
110
- ? JSON.stringify(val, null, 2)
111
- : String(val);
91
+ return val == null ? "" : isArray(val) || isPlainObject(val) && val.toString === objectToString ? JSON.stringify(val, null, 2) : String(val);
112
92
  };
113
- function join(items, separator = '') {
114
- return items.reduce((str, item, index) => (index === 0 ? str + item : str + separator + item), '');
93
+ function join(items, separator = "") {
94
+ return items.reduce((str, item, index) => index === 0 ? str + item : str + separator + item, "");
115
95
  }
116
96
  const RANGE = 2;
117
97
  function generateCodeFrame(source, start = 0, end = source.length) {
118
- const lines = source.split(/\r?\n/);
119
- let count = 0;
120
- const res = [];
121
- for (let i = 0; i < lines.length; i++) {
122
- count += lines[i].length + 1;
123
- if (count >= start) {
124
- for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
125
- if (j < 0 || j >= lines.length)
126
- continue;
127
- const line = j + 1;
128
- res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);
129
- const lineLength = lines[j].length;
130
- if (j === i) {
131
- // push underline
132
- const pad = start - (count - lineLength) + 1;
133
- const length = Math.max(1, end > count ? lineLength - pad : end - start);
134
- res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
135
- }
136
- else if (j > i) {
137
- if (end > count) {
138
- const length = Math.max(Math.min(end - count, lineLength), 1);
139
- res.push(` | ` + '^'.repeat(length));
140
- }
141
- count += lineLength + 1;
142
- }
143
- }
144
- break;
145
- }
146
- }
147
- return res.join('\n');
148
- }
149
-
98
+ const lines = source.split(/\r?\n/);
99
+ let count = 0;
100
+ const res = [];
101
+ for (let i = 0; i < lines.length; i++) {
102
+ count += lines[i].length + 1;
103
+ if (count >= start) {
104
+ for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
105
+ if (j < 0 || j >= lines.length) continue;
106
+ const line = j + 1;
107
+ res.push(`${line}${" ".repeat(3 - String(line).length)}| ${lines[j]}`);
108
+ const lineLength = lines[j].length;
109
+ if (j === i) {
110
+ const pad = start - (count - lineLength) + 1;
111
+ const length = Math.max(1, end > count ? lineLength - pad : end - start);
112
+ res.push(` | ` + " ".repeat(pad) + "^".repeat(length));
113
+ } else if (j > i) {
114
+ if (end > count) {
115
+ const length = Math.max(Math.min(end - count, lineLength), 1);
116
+ res.push(` | ` + "^".repeat(length));
117
+ }
118
+ count += lineLength + 1;
119
+ }
120
+ }
121
+ break;
122
+ }
123
+ }
124
+ return res.join("\n");
125
+ }
126
+ // packages/shared/src/warn.ts
150
127
  function warn(msg, err) {
151
- if (typeof console !== 'undefined') {
152
- console.warn(`[intlify] ` + msg);
153
- /* istanbul ignore if */
154
- if (err) {
155
- console.warn(err.stack);
156
- }
157
- }
128
+ if (typeof console !== "undefined") {
129
+ console.warn(`[intlify] ` + msg);
130
+ /* istanbul ignore if */
131
+ if (err) console.warn(err.stack);
132
+ }
158
133
  }
159
134
  const hasWarned = {};
160
135
  function warnOnce(msg) {
161
- if (!hasWarned[msg]) {
162
- hasWarned[msg] = true;
163
- warn(msg);
164
- }
136
+ if (!hasWarned[msg]) {
137
+ hasWarned[msg] = true;
138
+ warn(msg);
139
+ }
165
140
  }
166
-
141
+ // packages/shared/src/sanitize.ts
167
142
  function escapeHtml(rawText) {
168
- return rawText
169
- .replace(/&/g, '&amp;') // escape `&` first to avoid double escaping
170
- .replace(/</g, '&lt;')
171
- .replace(/>/g, '&gt;')
172
- .replace(/"/g, '&quot;')
173
- .replace(/'/g, '&apos;')
174
- .replace(/\//g, '&#x2F;') // escape `/` to prevent closing tags or JavaScript URLs
175
- .replace(/=/g, '&#x3D;'); // escape `=` to prevent attribute injection
143
+ return rawText.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;").replace(/\//g, "&#x2F;").replace(/=/g, "&#x3D;");
176
144
  }
177
145
  function escapeAttributeValue(value) {
178
- return value
179
- .replace(/&(?![a-z0-9#]{2,6};)/gi, '&amp;') // escape unescaped `&`
180
- .replace(/"/g, '&quot;')
181
- .replace(/'/g, '&apos;')
182
- .replace(/</g, '&lt;')
183
- .replace(/>/g, '&gt;');
146
+ return value.replace(/&(?![a-z0-9#]{2,6};)/gi, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&apos;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
184
147
  }
185
148
  const javascriptSchemePattern = /^javascript:/i;
186
- // `xlink:href` is the older spelling of `href` on SVG elements, and an SVG `<a>` follows either of them
187
149
  const urlAttributePattern = /^(?:href|xlink:href|src|action|formaction)$/i;
188
150
  const numericCharacterReferencePattern = /&#(?:x([0-9a-f]+)|(\d+));?/gi;
189
151
  const namedWhitespaceCharacterReferencePattern = /&(?:Tab|NewLine);/g;
190
152
  const colonCharacterReferencePattern = /&colon;?/gi;
191
- // eslint-disable-next-line no-control-regex -- URL scheme normalization requires the full control range
192
153
  const controlOrWhitespacePattern = /[\u0000-\u0020\u007f-\u009f]/g;
193
- const eventHandlerPattern = /(?:^|[\s"'<>/])on\w+\s*=\s*["']?[^"'>]+["']?/i;
194
- const eventHandlerAttributePattern = /(^|[\s"'<>/])on(\w+\s*=)/gi;
195
- // `srcdoc` holds a whole HTML document: its value is entity-decoded and then parsed again,
196
- // so neither escaping the value nor neutralizing `on*` inside it makes it inert
197
- const srcdocPattern = /(?:^|[\s"'<>/])srcdoc\s*=/i;
198
- const srcdocAttributePattern = /(^|[\s"'<>/])s(rcdoc\s*=)/gi;
199
- // `<base>` changes how the page resolves every relative URL after it, and SVG `<animate>` and `<set>`
200
- // can set `href` of an SVG `<a>` through `values` or `to`, which the URL check does not look at.
201
- // `<script>` does not run when inserted with `innerHTML`, but it runs when the HTML is rendered
202
- // on the server (SSR) and the browser parses it as part of the page
203
- const dangerousElementPattern = /<(?:base|animate|set|script)(?=[\s/>]|$)/i;
204
- const dangerousElementStartTagPattern = /<(base|animate|set|script)(?=[\s/>]|$)/gi;
205
- const unquotedUrlAttributePattern = /(^|[\s"'<>/])((?:href|xlink:href|src|action|formaction)\s*=\s*)([^\s"'=<>`]+)/gi;
154
+ const eventHandlerPattern = /^on\w/i;
155
+ const srcdocPattern = /^srcdoc$/i;
156
+ const dangerousElementPattern = /^(?:base|animate|set|script|plaintext)$/i;
157
+ const textContentElementPattern = /^(?:iframe|noembed|noframes|noscript|style|textarea|title|xmp)$/i;
158
+ const tagStartPattern = /<(\/?)([a-z][^\t\n\f\r />]*)/iy;
159
+ const tagStepPattern = /([\t\n\f\r /]*)(?:(>)|([^\t\n\f\r />][^\t\n\f\r />=]*)(?:[\t\n\f\r ]*=[\t\n\f\r ]*(?:(["'])([\s\S]*?)(\4|$)|([^\t\n\f\r >]*)))?)/y;
160
+ const commentPattern = /<!--(?:>|->|[\s\S]*?--!?>)/y;
206
161
  function decodeNumericCharacterReference(match, hex, decimal) {
207
- const digits = hex || decimal;
208
- if (!digits) {
209
- return match;
210
- }
211
- const codePoint = Number.parseInt(digits, hex ? 16 : 10);
212
- return codePoint <= 0x7f ? String.fromCharCode(codePoint) : match;
162
+ const digits = hex || decimal;
163
+ if (!digits) return match;
164
+ const codePoint = Number.parseInt(digits, hex ? 16 : 10);
165
+ return codePoint <= 127 ? String.fromCharCode(codePoint) : match;
213
166
  }
214
167
  function hasJavascriptScheme(value) {
215
- const normalized = value
216
- .replace(numericCharacterReferencePattern, decodeNumericCharacterReference)
217
- .replace(namedWhitespaceCharacterReferencePattern, '')
218
- .replace(colonCharacterReferencePattern, ':')
219
- .replace(controlOrWhitespacePattern, '');
220
- return javascriptSchemePattern.test(normalized);
168
+ const normalized = value.replace(numericCharacterReferencePattern, decodeNumericCharacterReference).replace(namedWhitespaceCharacterReferencePattern, "").replace(colonCharacterReferencePattern, ":").replace(controlOrWhitespacePattern, "");
169
+ return javascriptSchemePattern.test(normalized);
221
170
  }
222
171
  function sanitizeStyleValue(value) {
223
- const urlPattern = /url\s*\(/gi;
224
- let sanitized = '';
225
- let cursor = 0;
226
- let match;
227
- while ((match = urlPattern.exec(value)) !== null) {
228
- const urlStart = match.index;
229
- const openParenIndex = urlPattern.lastIndex - 1;
230
- let index = openParenIndex + 1;
231
- let depth = 1;
232
- let quote = null;
233
- for (; index < value.length; index++) {
234
- const char = value[index];
235
- if (quote) {
236
- if (char === quote) {
237
- quote = null;
238
- }
239
- continue;
240
- }
241
- if (char === '"' || char === "'") {
242
- quote = char;
243
- }
244
- else if (char === '(') {
245
- depth++;
246
- }
247
- else if (char === ')') {
248
- depth--;
249
- if (depth === 0) {
250
- break;
251
- }
252
- }
253
- }
254
- if (depth !== 0) {
255
- break;
256
- }
257
- const rawUrlValue = value.slice(openParenIndex + 1, index).trim();
258
- const unquotedUrlValue = (rawUrlValue.startsWith('"') && rawUrlValue.endsWith('"')) ||
259
- (rawUrlValue.startsWith("'") && rawUrlValue.endsWith("'"))
260
- ? rawUrlValue.slice(1, -1).trim()
261
- : rawUrlValue;
262
- sanitized += value.slice(cursor, urlStart);
263
- sanitized += hasJavascriptScheme(unquotedUrlValue)
264
- ? 'url(about:blank)'
265
- : value.slice(urlStart, index + 1);
266
- cursor = index + 1;
267
- }
268
- return sanitized + value.slice(cursor);
172
+ const urlPattern = /url\s*\(/gi;
173
+ let sanitized = "";
174
+ let cursor = 0;
175
+ let match;
176
+ while ((match = urlPattern.exec(value)) !== null) {
177
+ const urlStart = match.index;
178
+ const openParenIndex = urlPattern.lastIndex - 1;
179
+ let index = openParenIndex + 1;
180
+ let depth = 1;
181
+ let quote = null;
182
+ for (; index < value.length; index++) {
183
+ const char = value[index];
184
+ if (quote) {
185
+ if (char === quote) quote = null;
186
+ continue;
187
+ }
188
+ if (char === "\"" || char === "'") quote = char;
189
+ else if (char === "(") depth++;
190
+ else if (char === ")") {
191
+ depth--;
192
+ if (depth === 0) break;
193
+ }
194
+ }
195
+ if (depth !== 0) break;
196
+ const rawUrlValue = value.slice(openParenIndex + 1, index).trim();
197
+ const unquotedUrlValue = rawUrlValue.startsWith("\"") && rawUrlValue.endsWith("\"") || rawUrlValue.startsWith("'") && rawUrlValue.endsWith("'") ? rawUrlValue.slice(1, -1).trim() : rawUrlValue;
198
+ sanitized += value.slice(cursor, urlStart);
199
+ sanitized += hasJavascriptScheme(unquotedUrlValue) ? "url(about:blank)" : value.slice(urlStart, index + 1);
200
+ cursor = index + 1;
201
+ }
202
+ return sanitized + value.slice(cursor);
269
203
  }
270
204
  function sanitizeAttributeValue(attrName, value) {
271
- if (urlAttributePattern.test(attrName) && hasJavascriptScheme(value)) {
272
- return 'about:blank';
273
- }
274
- const sanitizedValue = attrName.toLowerCase() === 'style' ? sanitizeStyleValue(value) : value;
275
- return escapeAttributeValue(sanitizedValue);
205
+ if (urlAttributePattern.test(attrName) && hasJavascriptScheme(value)) return "about:blank";
206
+ return escapeAttributeValue(attrName.toLowerCase() === "style" ? sanitizeStyleValue(value) : value);
207
+ }
208
+ function escapeLessThan(text) {
209
+ return text.replace(/</g, "&lt;");
210
+ }
211
+ function serializeAttribute(attrName, value, quote, neutralized) {
212
+ let name = attrName;
213
+ if (eventHandlerPattern.test(attrName)) {
214
+ neutralized.eventHandler = true;
215
+ name = `&#111;n${attrName.slice(2)}`;
216
+ } else if (srcdocPattern.test(attrName)) {
217
+ neutralized.srcdoc = true;
218
+ name = `&#115;${attrName.slice(1)}`;
219
+ }
220
+ if (value === void 0) return name;
221
+ const valueQuote = quote || "";
222
+ return `${name}=${valueQuote}${sanitizeAttributeValue(attrName, value)}${valueQuote}`;
223
+ }
224
+ /**
225
+ * Read a tag with the rules of the HTML tokenizer.
226
+ * A start tag is written again with its attributes sanitized, and an end tag is kept as it is
227
+ *
228
+ * @param html - The HTML
229
+ * @param start - The index of `<`
230
+ * @param neutralized - What has been neutralized
231
+ * @returns The tag, the tag name, and the index after the tag (-1 when the tag is not closed),
232
+ * or `undefined` when `<` does not start a tag
233
+ */
234
+ function readTag(html, start, neutralized) {
235
+ tagStartPattern.lastIndex = start;
236
+ const tagStart = tagStartPattern.exec(html);
237
+ if (!tagStart) return;
238
+ const [, slash, tagName] = tagStart;
239
+ let tag = tagStart[0];
240
+ let step;
241
+ tagStepPattern.lastIndex = tagStartPattern.lastIndex;
242
+ while (step = tagStepPattern.exec(html)) {
243
+ const [raw, separator, close, attrName, quote, quotedValue, closingQuote, unquotedValue] = step;
244
+ if (close) {
245
+ const end = tagStepPattern.lastIndex;
246
+ return [
247
+ slash ? html.slice(start, end) : tag + raw,
248
+ tagName,
249
+ end
250
+ ];
251
+ }
252
+ if (quote && !closingQuote) break;
253
+ if (!slash) tag += separator + serializeAttribute(attrName, quote ? quotedValue : unquotedValue, quote, neutralized);
254
+ }
255
+ return [
256
+ tag,
257
+ tagName,
258
+ -1
259
+ ];
276
260
  }
261
+ /**
262
+ * Find the end tag of an element whose content is text, as the HTML tokenizer does:
263
+ * the first `</` followed by the tag name, and by whitespace, `/` or `>`
264
+ *
265
+ * @returns The index of the end tag, or -1 when it is not found or not closed in the string
266
+ */
267
+ function findTextContentEnd(html, from, tagName) {
268
+ for (let index = html.indexOf("</", from); index !== -1; index = html.indexOf("</", index + 2)) {
269
+ const endTag = readTag(html, index, {});
270
+ if (endTag && endTag[1].toLowerCase() === tagName.toLowerCase()) return endTag[2] === -1 ? -1 : index;
271
+ }
272
+ return -1;
273
+ }
274
+ /**
275
+ * Sanitize the translated HTML
276
+ *
277
+ * @remarks
278
+ * Tags are read with the rules of the HTML tokenizer, so that the sanitizer and browsers agree on
279
+ * where each tag and each attribute starts and ends, and every attribute of every start tag is checked.
280
+ * What is still open at the end of the string (a tag, a comment, or an element whose content is text,
281
+ * like `<textarea>`) becomes text: on the server (SSR), the rest of the page follows the translation,
282
+ * and it would be read as a part of what is open
283
+ *
284
+ * @param html - The translated HTML
285
+ * @returns The sanitized HTML
286
+ */
277
287
  function sanitizeTranslatedHtml(html) {
278
- // Escape dangerous characters in attribute values
279
- // Process attributes with double quotes
280
- html = html.replace(/([\w:-]+)\s*=\s*"([^"]*)"/g, (_, attrName, attrValue) => `${attrName}="${sanitizeAttributeValue(attrName, attrValue)}"`);
281
- // Process attributes with single quotes
282
- html = html.replace(/([\w:-]+)\s*=\s*'([^']*)'/g, (_, attrName, attrValue) => `${attrName}='${sanitizeAttributeValue(attrName, attrValue)}'`);
283
- // Detect and neutralize event handler attributes
284
- if (eventHandlerPattern.test(html)) {
285
- {
286
- warn('Potentially dangerous event handlers detected in translation. ' +
287
- 'Consider removing onclick, onerror, etc. from your translation messages.');
288
- }
289
- // Neutralize event handler attributes by escaping 'on'
290
- html = html.replace(eventHandlerAttributePattern, '$1&#111;n$2');
291
- }
292
- // Detect and neutralize `srcdoc` attributes
293
- if (srcdocPattern.test(html)) {
294
- {
295
- warn('Potentially dangerous srcdoc attribute detected in translation. ' +
296
- 'Consider removing srcdoc from your translation messages.');
297
- }
298
- // Neutralize `srcdoc` by escaping 's': character references are not decoded in attribute names
299
- html = html.replace(srcdocAttributePattern, '$1&#115;$2');
300
- }
301
- // Detect and neutralize `<base>`, `<animate>`, `<set>` and `<script>` elements
302
- if (dangerousElementPattern.test(html)) {
303
- {
304
- warn('Potentially dangerous element (<base>, <animate>, <set> or <script>) ' +
305
- 'detected in translation. Consider removing it from your translation messages.');
306
- }
307
- // Neutralize these elements by escaping '<': the start tag becomes text
308
- html = html.replace(dangerousElementStartTagPattern, '&lt;$1');
309
- }
310
- // Disable javascript: URLs in unquoted attributes
311
- html = html.replace(unquotedUrlAttributePattern, (match, boundary, prefix, attrValue) => hasJavascriptScheme(attrValue) ? `${boundary}${prefix}about:blank` : match);
312
- return html;
313
- }
314
-
288
+ const neutralized = {};
289
+ let result = "";
290
+ let index = 0;
291
+ let lessThan;
292
+ while ((lessThan = html.indexOf("<", index)) !== -1) {
293
+ result += html.slice(index, lessThan);
294
+ index = lessThan + 1;
295
+ const read = readTag(html, lessThan, neutralized);
296
+ if (read) {
297
+ const [tag, tagName, end] = read;
298
+ if (end === -1) {
299
+ neutralized.unclosed = true;
300
+ result += escapeLessThan(html.slice(lessThan));
301
+ index = html.length;
302
+ break;
303
+ }
304
+ index = end;
305
+ if (tag[1] === "/") result += tag;
306
+ else if (dangerousElementPattern.test(tagName)) {
307
+ neutralized.element = true;
308
+ result += escapeLessThan(tag);
309
+ } else if (textContentElementPattern.test(tagName)) {
310
+ const contentEnd = findTextContentEnd(html, end, tagName);
311
+ if (contentEnd === -1) {
312
+ neutralized.unclosed = true;
313
+ result += escapeLessThan(tag);
314
+ } else {
315
+ result += tag + escapeLessThan(html.slice(end, contentEnd));
316
+ index = contentEnd;
317
+ }
318
+ } else result += tag;
319
+ continue;
320
+ }
321
+ commentPattern.lastIndex = lessThan;
322
+ if (commentPattern.test(html)) {
323
+ result += html.slice(lessThan, commentPattern.lastIndex);
324
+ index = commentPattern.lastIndex;
325
+ continue;
326
+ }
327
+ if (html.startsWith("<!--", lessThan)) neutralized.unclosed = true;
328
+ result += "&lt;";
329
+ }
330
+ result += html.slice(index);
331
+ if (neutralized.eventHandler) warn("Potentially dangerous event handlers detected in translation. Consider removing onclick, onerror, etc. from your translation messages.");
332
+ if (neutralized.srcdoc) warn("Potentially dangerous srcdoc attribute detected in translation. Consider removing srcdoc from your translation messages.");
333
+ if (neutralized.element) warn("Potentially dangerous element (<base>, <animate>, <set>, <script> or <plaintext>) detected in translation. Consider removing it from your translation messages.");
334
+ if (neutralized.unclosed) warn("Unclosed tag, comment or element (such as <textarea>) detected in translation. Consider closing it in your translation messages.");
335
+ return result;
336
+ }
337
+ // packages/shared/src/messages.ts
338
+ const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val);
339
+ function deepCopy(src, des) {
340
+ if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des) || des === Object.prototype) throw new Error("Invalid value");
341
+ const stack = [src, des];
342
+ while (stack.length) {
343
+ const des = stack.pop();
344
+ const src = stack.pop();
345
+ const keys = Object.keys(src);
346
+ for (let i = 0; i < keys.length; i++) {
347
+ const key = keys[i];
348
+ if (key === "__proto__") continue;
349
+ const value = src[key];
350
+ if (!isObject(value)) {
351
+ des[key] = value;
352
+ continue;
353
+ }
354
+ if (isArray(value)) {
355
+ const copied = [];
356
+ copied.length = value.length;
357
+ des[key] = copied;
358
+ stack.push(value, copied);
359
+ continue;
360
+ }
361
+ let desValue = des[key];
362
+ if (!isObject(desValue) || isArray(desValue)) desValue = des[key] = create();
363
+ stack.push(value, desValue);
364
+ }
365
+ }
366
+ }
367
+ // packages/message-compiler/src/errors.ts
315
368
  const CompileErrorCodes = {
316
- // tokenizer error codes
317
- EXPECTED_TOKEN: 1,
318
- INVALID_TOKEN_IN_PLACEHOLDER: 2,
319
- UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
320
- UNKNOWN_ESCAPE_SEQUENCE: 4,
321
- INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
322
- UNBALANCED_CLOSING_BRACE: 6,
323
- UNTERMINATED_CLOSING_BRACE: 7,
324
- EMPTY_PLACEHOLDER: 8,
325
- NOT_ALLOW_NEST_PLACEHOLDER: 9,
326
- INVALID_LINKED_FORMAT: 10,
327
- // parser error codes
328
- MUST_HAVE_MESSAGES_IN_PLURAL: 11,
329
- UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
330
- UNEXPECTED_EMPTY_LINKED_KEY: 13,
331
- UNEXPECTED_LEXICAL_ANALYSIS: 14,
332
- // generator error codes
333
- UNHANDLED_CODEGEN_NODE_TYPE: 15,
334
- // minifier error codes
335
- UNHANDLED_MINIFIER_NODE_TYPE: 16
369
+ EXPECTED_TOKEN: 1,
370
+ INVALID_TOKEN_IN_PLACEHOLDER: 2,
371
+ UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
372
+ UNKNOWN_ESCAPE_SEQUENCE: 4,
373
+ INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
374
+ UNBALANCED_CLOSING_BRACE: 6,
375
+ UNTERMINATED_CLOSING_BRACE: 7,
376
+ EMPTY_PLACEHOLDER: 8,
377
+ NOT_ALLOW_NEST_PLACEHOLDER: 9,
378
+ INVALID_LINKED_FORMAT: 10,
379
+ MUST_HAVE_MESSAGES_IN_PLURAL: 11,
380
+ UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
381
+ UNEXPECTED_EMPTY_LINKED_KEY: 13,
382
+ UNEXPECTED_LEXICAL_ANALYSIS: 14,
383
+ UNHANDLED_CODEGEN_NODE_TYPE: 15,
384
+ UNHANDLED_MINIFIER_NODE_TYPE: 16
336
385
  };
337
- // Special value for higher-order compilers to pick up the last code
338
- // to avoid collision of error codes.
339
- // This should always be kept as the last item.
340
- const COMPILE_ERROR_CODES_EXTEND_POINT = 17;
341
386
  /** @internal */
342
387
  const errorMessages$1 = {
343
- // tokenizer error messages
344
- [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
345
- [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
346
- [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
347
- [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
348
- [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
349
- [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
350
- [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
351
- [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
352
- [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
353
- [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
354
- // parser error messages
355
- [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
356
- [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
357
- [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
358
- [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`,
359
- // generator error messages
360
- [CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE]: `unhandled codegen node type: '{0}'`,
361
- // minimizer error messages
362
- [CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE]: `unhandled mimifier node type: '{0}'`
388
+ [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
389
+ [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
390
+ [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
391
+ [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
392
+ [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
393
+ [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
394
+ [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
395
+ [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
396
+ [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
397
+ [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
398
+ [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
399
+ [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
400
+ [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
401
+ [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`,
402
+ [CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE]: `unhandled codegen node type: '{0}'`,
403
+ [CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE]: `unhandled mimifier node type: '{0}'`
363
404
  };
364
405
  function createCompileError(code, loc, options = {}) {
365
- const { domain, messages, args } = options;
366
- const msg = format$1((messages || errorMessages$1)[code] || '', ...(args || []))
367
- ;
368
- const error = new SyntaxError(String(msg));
369
- error.code = code;
370
- if (loc) {
371
- error.location = loc;
372
- }
373
- error.domain = domain;
374
- return error;
375
- }
376
-
406
+ const { domain, messages, args } = options;
407
+ const msg = format$1((messages || errorMessages$1)[code] || "", ...args || []);
408
+ const error = new SyntaxError(String(msg));
409
+ error.code = code;
410
+ if (loc) error.location = loc;
411
+ error.domain = domain;
412
+ return error;
413
+ }
414
+ // packages/core-base/src/ast.ts
377
415
  function isMessageAST(val) {
378
- return (isObject(val) &&
379
- resolveType(val) === 0 &&
380
- (hasOwn(val, 'b') || hasOwn(val, 'body')));
416
+ return isObject(val) && resolveType(val) === 0 && (hasOwn(val, "b") || hasOwn(val, "body"));
381
417
  }
382
- const PROPS_BODY = ['b', 'body'];
418
+ const PROPS_BODY = ["b", "body"];
383
419
  function resolveBody(node) {
384
- return resolveProps(node, PROPS_BODY);
420
+ return resolveProps(node, PROPS_BODY);
385
421
  }
386
- const PROPS_CASES = ['c', 'cases'];
422
+ const PROPS_CASES = ["c", "cases"];
387
423
  function resolveCases(node) {
388
- return resolveProps(node, PROPS_CASES, []);
424
+ return resolveProps(node, PROPS_CASES, []);
389
425
  }
390
- const PROPS_STATIC = ['s', 'static'];
426
+ const PROPS_STATIC = ["s", "static"];
391
427
  function resolveStatic(node) {
392
- return resolveProps(node, PROPS_STATIC);
428
+ return resolveProps(node, PROPS_STATIC);
393
429
  }
394
- const PROPS_ITEMS = ['i', 'items'];
430
+ const PROPS_ITEMS = ["i", "items"];
395
431
  function resolveItems(node) {
396
- return resolveProps(node, PROPS_ITEMS, []);
432
+ return resolveProps(node, PROPS_ITEMS, []);
397
433
  }
398
- const PROPS_TYPE = ['t', 'type'];
434
+ const PROPS_TYPE = ["t", "type"];
399
435
  function resolveType(node) {
400
- return resolveProps(node, PROPS_TYPE);
436
+ return resolveProps(node, PROPS_TYPE);
401
437
  }
402
- const PROPS_VALUE = ['v', 'value'];
438
+ const PROPS_VALUE = ["v", "value"];
403
439
  function resolveValue$1(node, type) {
404
- const resolved = resolveProps(node, PROPS_VALUE);
405
- if (resolved != null) {
406
- return resolved;
407
- }
408
- else {
409
- throw createUnhandleNodeError(type);
410
- }
411
- }
412
- const PROPS_MODIFIER = ['m', 'modifier'];
440
+ const resolved = resolveProps(node, PROPS_VALUE);
441
+ if (resolved != null) return resolved;
442
+ else throw createUnhandleNodeError(type);
443
+ }
444
+ const PROPS_MODIFIER = ["m", "modifier"];
413
445
  function resolveLinkedModifier(node) {
414
- return resolveProps(node, PROPS_MODIFIER);
446
+ return resolveProps(node, PROPS_MODIFIER);
415
447
  }
416
- const PROPS_KEY = ['k', 'key'];
448
+ const PROPS_KEY = ["k", "key"];
417
449
  function resolveLinkedKey(node) {
418
- const resolved = resolveProps(node, PROPS_KEY);
419
- if (resolved) {
420
- return resolved;
421
- }
422
- else {
423
- throw createUnhandleNodeError(6 /* NodeTypes.Linked */);
424
- }
450
+ const resolved = resolveProps(node, PROPS_KEY);
451
+ if (resolved) return resolved;
452
+ else throw createUnhandleNodeError(6);
425
453
  }
426
454
  function resolveProps(node, props, defaultValue) {
427
- for (let i = 0; i < props.length; i++) {
428
- const prop = props[i];
429
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
430
- if (hasOwn(node, prop) && node[prop] != null) {
431
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
432
- return node[prop];
433
- }
434
- }
435
- return defaultValue;
455
+ for (let i = 0; i < props.length; i++) {
456
+ const prop = props[i];
457
+ if (hasOwn(node, prop) && node[prop] != null) return node[prop];
458
+ }
459
+ return defaultValue;
436
460
  }
437
461
  const AST_NODE_PROPS_KEYS = [
438
- ...PROPS_BODY,
439
- ...PROPS_CASES,
440
- ...PROPS_STATIC,
441
- ...PROPS_ITEMS,
442
- ...PROPS_KEY,
443
- ...PROPS_MODIFIER,
444
- ...PROPS_VALUE,
445
- ...PROPS_TYPE
462
+ ...PROPS_BODY,
463
+ ...PROPS_CASES,
464
+ ...PROPS_STATIC,
465
+ ...PROPS_ITEMS,
466
+ ...PROPS_KEY,
467
+ ...PROPS_MODIFIER,
468
+ ...PROPS_VALUE,
469
+ ...PROPS_TYPE
446
470
  ];
447
471
  function createUnhandleNodeError(type) {
448
- return new Error(`unhandled node type: ${type}`);
472
+ return /* @__PURE__ */ new Error(`unhandled node type: ${type}`);
449
473
  }
450
-
474
+ // packages/core-base/src/format.ts
451
475
  function format(ast) {
452
- const msg = (ctx) => formatParts(ctx, ast);
453
- return msg;
476
+ return (ctx) => formatParts(ctx, ast);
454
477
  }
455
478
  function formatParts(ctx, ast) {
456
- const body = resolveBody(ast);
457
- if (body == null) {
458
- throw createUnhandleNodeError(0 /* NodeTypes.Resource */);
459
- }
460
- const type = resolveType(body);
461
- if (type === 1 /* NodeTypes.Plural */) {
462
- const plural = body;
463
- const cases = resolveCases(plural);
464
- return ctx.plural(cases.reduce((messages, c) => [
465
- ...messages,
466
- formatMessageParts(ctx, c)
467
- ], []));
468
- }
469
- else {
470
- return formatMessageParts(ctx, body);
471
- }
479
+ const body = resolveBody(ast);
480
+ if (body == null) throw createUnhandleNodeError(0);
481
+ if (resolveType(body) === 1) {
482
+ const cases = resolveCases(body);
483
+ return ctx.plural(cases.reduce((messages, c) => [...isArray(messages) ? messages : [messages], formatMessageParts(ctx, c)], []));
484
+ } else return formatMessageParts(ctx, body);
472
485
  }
473
486
  function formatMessageParts(ctx, node) {
474
- const static_ = resolveStatic(node);
475
- if (static_ != null) {
476
- return ctx.type === 'text'
477
- ? static_
478
- : ctx.normalize([static_]);
479
- }
480
- else {
481
- const messages = resolveItems(node).reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);
482
- return ctx.normalize(messages);
483
- }
487
+ const static_ = resolveStatic(node);
488
+ if (static_ != null) return ctx.type === "text" ? static_ : ctx.normalize([static_]);
489
+ else {
490
+ const messages = resolveItems(node).reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);
491
+ return ctx.normalize(messages);
492
+ }
484
493
  }
485
494
  function formatMessagePart(ctx, node) {
486
- const type = resolveType(node);
487
- switch (type) {
488
- case 3 /* NodeTypes.Text */: {
489
- return resolveValue$1(node, type);
490
- }
491
- case 9 /* NodeTypes.Literal */: {
492
- return resolveValue$1(node, type);
493
- }
494
- case 4 /* NodeTypes.Named */: {
495
- const named = node;
496
- if (hasOwn(named, 'k') && named.k) {
497
- return ctx.interpolate(ctx.named(named.k));
498
- }
499
- if (hasOwn(named, 'key') && named.key) {
500
- return ctx.interpolate(ctx.named(named.key));
501
- }
502
- throw createUnhandleNodeError(type);
503
- }
504
- case 5 /* NodeTypes.List */: {
505
- const list = node;
506
- if (hasOwn(list, 'i') && isNumber(list.i)) {
507
- return ctx.interpolate(ctx.list(list.i));
508
- }
509
- if (hasOwn(list, 'index') && isNumber(list.index)) {
510
- return ctx.interpolate(ctx.list(list.index));
511
- }
512
- throw createUnhandleNodeError(type);
513
- }
514
- case 6 /* NodeTypes.Linked */: {
515
- const linked = node;
516
- const modifier = resolveLinkedModifier(linked);
517
- const key = resolveLinkedKey(linked);
518
- return ctx.linked(formatMessagePart(ctx, key), modifier ? formatMessagePart(ctx, modifier) : undefined, ctx.type);
519
- }
520
- case 7 /* NodeTypes.LinkedKey */: {
521
- return resolveValue$1(node, type);
522
- }
523
- case 8 /* NodeTypes.LinkedModifier */: {
524
- return resolveValue$1(node, type);
525
- }
526
- default:
527
- throw new Error(`unhandled node on format message part: ${type}`);
528
- }
529
- }
530
-
495
+ const type = resolveType(node);
496
+ switch (type) {
497
+ case 3: return resolveValue$1(node, type);
498
+ case 9: return resolveValue$1(node, type);
499
+ case 4: {
500
+ const named = node;
501
+ if (hasOwn(named, "k") && named.k) return ctx.interpolate(ctx.named(named.k));
502
+ if (hasOwn(named, "key") && named.key) return ctx.interpolate(ctx.named(named.key));
503
+ throw createUnhandleNodeError(type);
504
+ }
505
+ case 5: {
506
+ const list = node;
507
+ if (hasOwn(list, "i") && isNumber(list.i)) return ctx.interpolate(ctx.list(list.i));
508
+ if (hasOwn(list, "index") && isNumber(list.index)) return ctx.interpolate(ctx.list(list.index));
509
+ throw createUnhandleNodeError(type);
510
+ }
511
+ case 6: {
512
+ const linked = node;
513
+ const modifier = resolveLinkedModifier(linked);
514
+ const key = resolveLinkedKey(linked);
515
+ return ctx.linked(formatMessagePart(ctx, key), modifier ? formatMessagePart(ctx, modifier) : void 0, ctx.type);
516
+ }
517
+ case 7: return resolveValue$1(node, type);
518
+ case 8: return resolveValue$1(node, type);
519
+ default: throw new Error(`unhandled node on format message part: ${type}`);
520
+ }
521
+ }
522
+ // packages/core-base/src/compilation.ts
531
523
  let compileCache = create();
532
524
  function clearCompileCache() {
533
- compileCache = create();
525
+ compileCache = create();
534
526
  }
535
527
  /* #__NO_SIDE_EFFECTS__ */
536
528
  function compile(message, context) {
537
- {
538
- // the message compiler is not included in this build (e.g. the runtime-only builds), so return a string message as is
539
- if (!isMessageAST(message)) {
540
- {
541
- warn(`Cannot compile the message of '${context.key}' key, because the message compiler is not included in this build. ` +
542
- `Pre-compile the message. So translate function returns the message as is.`);
543
- }
544
- return (() => message);
545
- }
546
- // AST case (passed from bundler)
547
- const cacheKey = message.cacheKey;
548
- if (cacheKey) {
549
- const cached = compileCache[cacheKey];
550
- if (cached) {
551
- return cached;
552
- }
553
- // compose message function from message (AST)
554
- return (compileCache[cacheKey] = format(message));
555
- }
556
- else {
557
- return format(message);
558
- }
559
- }
560
- }
561
-
562
- let devtools = null;
563
- function setDevToolsHook(hook) {
564
- devtools = hook;
565
- }
566
- function getDevToolsHook() {
567
- return devtools;
568
- }
569
- function initI18nDevTools(i18n, version, meta) {
570
- // TODO: queue if devtools is undefined
571
- devtools &&
572
- devtools.emit('i18n:init', {
573
- timestamp: Date.now(),
574
- i18n,
575
- version,
576
- meta
577
- });
578
- }
579
- const translateDevTools =
580
- /* #__PURE__*/ createDevToolsHook('function:translate');
581
- function createDevToolsHook(hook) {
582
- return (payloads) => devtools && devtools.emit(hook, payloads);
583
- }
584
-
529
+ {
530
+ if (!isMessageAST(message)) {
531
+ warn(`Cannot compile the message of '${context.key}' key, because the message compiler is not included in this build. Pre-compile the message. So translate function returns the message as is.`);
532
+ return (() => message);
533
+ }
534
+ const cacheKey = message.cacheKey;
535
+ if (cacheKey) {
536
+ const cached = compileCache[cacheKey];
537
+ if (cached) return cached;
538
+ return compileCache[cacheKey] = format(message);
539
+ } else return format(message);
540
+ }
541
+ }
542
+ // packages/core-base/src/errors.ts
585
543
  const CoreErrorCodes = {
586
- INVALID_ARGUMENT: COMPILE_ERROR_CODES_EXTEND_POINT, // 17
587
- INVALID_DATE_ARGUMENT: 18,
588
- INVALID_ISO_DATE_ARGUMENT: 19,
589
- NOT_SUPPORT_NON_STRING_MESSAGE: 20,
590
- NOT_SUPPORT_LOCALE_PROMISE_VALUE: 21,
591
- NOT_SUPPORT_LOCALE_ASYNC_FUNCTION: 22,
592
- NOT_SUPPORT_LOCALE_TYPE: 23
544
+ INVALID_ARGUMENT: 17,
545
+ INVALID_DATE_ARGUMENT: 18,
546
+ INVALID_ISO_DATE_ARGUMENT: 19,
547
+ NOT_SUPPORT_LOCALE_PROMISE_VALUE: 20,
548
+ NOT_SUPPORT_LOCALE_ASYNC_FUNCTION: 21,
549
+ NOT_SUPPORT_LOCALE_TYPE: 22
593
550
  };
594
- const CORE_ERROR_CODES_EXTEND_POINT = 24;
551
+ const CORE_ERROR_CODES_EXTEND_POINT = 23;
595
552
  function createCoreError(code) {
596
- return createCompileError(code, null, { messages: errorMessages } );
553
+ return createCompileError(code, null, { messages: errorMessages });
597
554
  }
598
555
  /** @internal */
599
556
  const errorMessages = {
600
- [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
601
- [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
602
- 'Make sure your Date represents a valid date.',
603
- [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string',
604
- [CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE]: 'Not support non-string message',
605
- [CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE]: 'cannot support promise value',
606
- [CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION]: 'cannot support async function',
607
- [CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE]: 'cannot support locale type'
557
+ [CoreErrorCodes.INVALID_ARGUMENT]: "Invalid arguments",
558
+ [CoreErrorCodes.INVALID_DATE_ARGUMENT]: "The date provided is an invalid Date object.Make sure your Date represents a valid date.",
559
+ [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: "The argument provided is not a valid ISO date string",
560
+ [CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE]: "cannot support promise value",
561
+ [CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION]: "cannot support async function",
562
+ [CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE]: "cannot support locale type"
608
563
  };
609
-
564
+ // packages/core-base/src/fallbacker.ts
610
565
  /** @internal */
611
566
  function getLocale(context, options) {
612
- return options.locale != null
613
- ? resolveLocale(options.locale)
614
- : resolveLocale(context.locale);
567
+ return options.locale != null ? resolveLocale(options.locale) : resolveLocale(context.locale);
615
568
  }
616
569
  let _resolveLocale;
617
570
  /** @internal */
618
571
  function resolveLocale(locale) {
619
- if (isString(locale)) {
620
- return locale;
621
- }
622
- else {
623
- if (isFunction(locale)) {
624
- if (locale.resolvedOnce && _resolveLocale != null) {
625
- return _resolveLocale;
626
- }
627
- else if (locale.constructor.name === 'Function') {
628
- const resolve = locale();
629
- if (isPromise(resolve)) {
630
- throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE);
631
- }
632
- return (_resolveLocale = resolve);
633
- }
634
- else {
635
- throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION);
636
- }
637
- }
638
- else {
639
- throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE);
640
- }
641
- }
572
+ if (isString(locale)) return locale;
573
+ else if (isFunction(locale)) {
574
+ if (locale.resolvedOnce && _resolveLocale != null) return _resolveLocale;
575
+ else if (locale.constructor.name === "Function") {
576
+ const resolve = locale();
577
+ if (isPromise(resolve)) throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE);
578
+ return _resolveLocale = resolve;
579
+ } else throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION);
580
+ } else throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE);
642
581
  }
643
582
  /**
644
- * Fallback with simple implemenation
645
- *
646
- * @remarks
647
- * A fallback locale function implemented with a simple fallback algorithm.
648
- *
649
- * Basically, the chain consists of `start` plus the specified fallback: for a string or array `fallbackLocale`, the value as specified in the props is used; for a map `fallbackLocale`, the map's **keys** are used and the `default` key is skipped since it is not a locale name.
650
- *
651
- * @param ctx - A {@link CoreContext | context}
652
- * @param fallback - A {@link FallbackLocale | fallback locale}
653
- * @param start - A starting {@link Locale | locale}
654
- *
655
- * @returns Fallback locales
656
- *
657
- * @VueI18nGeneral
658
- */
659
- function fallbackWithSimple(ctx, fallback, start) {
660
- // prettier-ignore
661
- return [...new Set([
662
- start,
663
- ...(isArray(fallback)
664
- ? fallback
665
- : isObject(fallback)
666
- ? Object.keys(fallback).filter(locale => locale !== 'default')
667
- : isString(fallback)
668
- ? [fallback]
669
- : [start])
670
- ])];
583
+ * Fallback with simple implemenation
584
+ *
585
+ * @remarks
586
+ * A fallback locale function implemented with a simple fallback algorithm.
587
+ *
588
+ * Basically, the chain consists of `start` plus the specified fallback: for a string or array `fallbackLocale`, the value as specified in the props is used; for a map `fallbackLocale`, the map's **keys** are used and the `default` key is skipped since it is not a locale name.
589
+ *
590
+ * @param ctx - A {@link CoreContext | context}
591
+ * @param fallback - A {@link FallbackLocale | fallback locale}
592
+ * @param start - A starting {@link Locale | locale}
593
+ *
594
+ * @returns Fallback locales
595
+ *
596
+ * @VueI18nGeneral
597
+ */
598
+ function fallbackWithSimple(_ctx, fallback, start) {
599
+ return [.../* @__PURE__ */ new Set([start, ...isArray(fallback) ? fallback : isObject(fallback) ? Object.keys(fallback).filter((locale) => locale !== "default") : isString(fallback) ? [fallback] : [start]])];
671
600
  }
672
601
  /**
673
- * Fallback with locale chain
674
- *
675
- * @remarks
676
- * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
677
- *
678
- * Chains are cached per fallback identity. If you mutate an object or array fallback in place,
679
- * pass a new object or array instead so that the chain is recomputed.
680
- *
681
- * @param ctx - A {@link CoreContext | context}
682
- * @param fallback - A {@link FallbackLocale | fallback locale}
683
- * @param start - A starting {@link Locale | locale}
684
- *
685
- * @returns Fallback locales
686
- *
687
- * @VueI18nSee [Fallbacking](../guide/essentials/fallback)
688
- *
689
- * @VueI18nGeneral
690
- */
602
+ * Fallback with locale chain
603
+ *
604
+ * @remarks
605
+ * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
606
+ *
607
+ * Chains are cached per fallback identity. If you mutate an object or array fallback in place,
608
+ * pass a new object or array instead so that the chain is recomputed.
609
+ *
610
+ * @param ctx - A {@link CoreContext | context}
611
+ * @param fallback - A {@link FallbackLocale | fallback locale}
612
+ * @param start - A starting {@link Locale | locale}
613
+ *
614
+ * @returns Fallback locales
615
+ *
616
+ * @VueI18nSee [Fallbacking](../../guide/essentials/fallback)
617
+ *
618
+ * @VueI18nGeneral
619
+ */
691
620
  function fallbackWithLocaleChain(ctx, fallback, start) {
692
- const startLocale = isString(start) ? start : DEFAULT_LOCALE;
693
- const context = ctx;
694
- // NOTE: chains are cached per fallback value, not per serialized content.
695
- // object / array fallbacks are keyed by identity in a WeakMap so that their
696
- // entries are released together with the fallback itself.
697
- let chains;
698
- if (isObject(fallback)) {
699
- if (!context.__localeChainObjectCache) {
700
- context.__localeChainObjectCache = new WeakMap();
701
- }
702
- chains = context.__localeChainObjectCache.get(fallback);
703
- if (!chains) {
704
- chains = new Map();
705
- context.__localeChainObjectCache.set(fallback, chains);
706
- }
707
- }
708
- else {
709
- if (!context.__localeChainCache) {
710
- context.__localeChainCache = new Map();
711
- }
712
- chains = context.__localeChainCache.get(fallback);
713
- if (!chains) {
714
- chains = new Map();
715
- context.__localeChainCache.set(fallback, chains);
716
- }
717
- }
718
- const cached = chains.get(startLocale);
719
- if (cached) {
720
- return cached;
721
- }
722
- const chain = [];
723
- // first block defined by start
724
- let block = [start];
725
- // while any intervening block found
726
- while (isArray(block)) {
727
- block = appendBlockToChain(chain, block, fallback);
728
- }
729
- // prettier-ignore
730
- // last block defined by default
731
- const defaults = isArray(fallback) || !isPlainObject(fallback)
732
- ? fallback
733
- : fallback['default']
734
- ? fallback['default']
735
- : null;
736
- // convert defaults to array
737
- block = isString(defaults) ? [defaults] : defaults;
738
- if (isArray(block)) {
739
- appendBlockToChain(chain, block, false);
740
- }
741
- chains.set(startLocale, chain);
742
- return chain;
621
+ const startLocale = isString(start) ? start : DEFAULT_LOCALE;
622
+ const context = ctx;
623
+ let chains;
624
+ if (isObject(fallback)) {
625
+ if (!context.__localeChainObjectCache) context.__localeChainObjectCache = /* @__PURE__ */ new WeakMap();
626
+ chains = context.__localeChainObjectCache.get(fallback);
627
+ if (!chains) {
628
+ chains = /* @__PURE__ */ new Map();
629
+ context.__localeChainObjectCache.set(fallback, chains);
630
+ }
631
+ } else {
632
+ if (!context.__localeChainCache) context.__localeChainCache = /* @__PURE__ */ new Map();
633
+ chains = context.__localeChainCache.get(fallback);
634
+ if (!chains) {
635
+ chains = /* @__PURE__ */ new Map();
636
+ context.__localeChainCache.set(fallback, chains);
637
+ }
638
+ }
639
+ const cached = chains.get(startLocale);
640
+ if (cached) return cached;
641
+ const chain = [];
642
+ let block = [start];
643
+ while (isArray(block)) block = appendBlockToChain(chain, block, fallback);
644
+ const defaults = isArray(fallback) || !isPlainObject(fallback) ? fallback : fallback["default"] ? fallback["default"] : null;
645
+ block = isString(defaults) ? [defaults] : defaults;
646
+ if (isArray(block)) appendBlockToChain(chain, block, false);
647
+ chains.set(startLocale, chain);
648
+ return chain;
743
649
  }
744
650
  function appendBlockToChain(chain, block, blocks) {
745
- let follow = true;
746
- for (let i = 0; i < block.length && isBoolean(follow); i++) {
747
- const locale = block[i];
748
- if (isString(locale)) {
749
- follow = appendLocaleToChain(chain, block[i], blocks);
750
- }
751
- }
752
- return follow;
651
+ let follow = true;
652
+ for (let i = 0; i < block.length && isBoolean(follow); i++) {
653
+ const locale = block[i];
654
+ if (isString(locale)) follow = appendLocaleToChain(chain, block[i], blocks);
655
+ }
656
+ return follow;
753
657
  }
754
658
  function appendLocaleToChain(chain, locale, blocks) {
755
- let follow;
756
- const tokens = locale.split('-');
757
- do {
758
- const target = tokens.join('-');
759
- follow = appendItemToChain(chain, target, blocks);
760
- tokens.splice(-1, 1);
761
- } while (tokens.length && follow === true);
762
- return follow;
659
+ let follow;
660
+ const tokens = locale.split("-");
661
+ do {
662
+ follow = appendItemToChain(chain, tokens.join("-"), blocks);
663
+ tokens.splice(-1, 1);
664
+ } while (tokens.length && follow === true);
665
+ return follow;
763
666
  }
764
667
  function appendItemToChain(chain, target, blocks) {
765
- let follow = false;
766
- if (!chain.includes(target)) {
767
- follow = true;
768
- if (target) {
769
- follow = target[target.length - 1] !== '!';
770
- const locale = target.replace(/!/g, '');
771
- chain.push(locale);
772
- if ((isArray(blocks) || isPlainObject(blocks)) &&
773
- blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
774
- ) {
775
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
776
- follow = blocks[locale];
777
- }
778
- }
779
- }
780
- return follow;
781
- }
782
-
668
+ let follow = false;
669
+ if (!chain.includes(target)) {
670
+ follow = true;
671
+ if (target) {
672
+ follow = target[target.length - 1] !== "!";
673
+ const locale = target.replace(/!/g, "");
674
+ chain.push(locale);
675
+ if ((isArray(blocks) || isPlainObject(blocks)) && blocks[locale]) follow = blocks[locale];
676
+ }
677
+ }
678
+ return follow;
679
+ }
680
+ // packages/core-base/src/resolver.ts
783
681
  const pathStateMachine = [];
784
- pathStateMachine[0 /* States.BEFORE_PATH */] = {
785
- ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
786
- ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
787
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
788
- ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
682
+ pathStateMachine[0] = {
683
+ ["w"]: [0],
684
+ ["i"]: [3, 0],
685
+ ["["]: [4],
686
+ ["o"]: [7]
789
687
  };
790
- pathStateMachine[1 /* States.IN_PATH */] = {
791
- ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
792
- ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
793
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
794
- ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
688
+ pathStateMachine[1] = {
689
+ ["w"]: [1],
690
+ ["."]: [2],
691
+ ["["]: [4],
692
+ ["o"]: [7]
795
693
  };
796
- pathStateMachine[2 /* States.BEFORE_IDENT */] = {
797
- ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
798
- ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
799
- ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
694
+ pathStateMachine[2] = {
695
+ ["w"]: [2],
696
+ ["i"]: [3, 0],
697
+ ["0"]: [3, 0]
800
698
  };
801
- pathStateMachine[3 /* States.IN_IDENT */] = {
802
- ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
803
- ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
804
- ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
805
- ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
806
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
807
- ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
699
+ pathStateMachine[3] = {
700
+ ["i"]: [3, 0],
701
+ ["0"]: [3, 0],
702
+ ["w"]: [1, 1],
703
+ ["."]: [2, 1],
704
+ ["["]: [4, 1],
705
+ ["o"]: [7, 1]
808
706
  };
809
- pathStateMachine[4 /* States.IN_SUB_PATH */] = {
810
- ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
811
- ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
812
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [
813
- 4 /* States.IN_SUB_PATH */,
814
- 2 /* Actions.INC_SUB_PATH_DEPTH */
815
- ],
816
- ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
817
- ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
818
- ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
707
+ pathStateMachine[4] = {
708
+ ["'"]: [5, 0],
709
+ ["\""]: [6, 0],
710
+ ["["]: [4, 2],
711
+ ["]"]: [1, 3],
712
+ ["o"]: 8,
713
+ ["l"]: [4, 0]
819
714
  };
820
- pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
821
- ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
822
- ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
823
- ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
715
+ pathStateMachine[5] = {
716
+ ["'"]: [4, 0],
717
+ ["o"]: 8,
718
+ ["l"]: [5, 0]
824
719
  };
825
- pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
826
- ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
827
- ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
828
- ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
720
+ pathStateMachine[6] = {
721
+ ["\""]: [4, 0],
722
+ ["o"]: 8,
723
+ ["l"]: [6, 0]
829
724
  };
830
725
  /**
831
- * Check if an expression is a literal value.
832
- */
726
+ * Check if an expression is a literal value.
727
+ */
833
728
  const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
834
729
  function isLiteral(exp) {
835
- return literalValueRE.test(exp);
730
+ return literalValueRE.test(exp);
836
731
  }
837
732
  /**
838
- * Strip quotes from a string
839
- */
733
+ * Strip quotes from a string
734
+ */
840
735
  function stripQuotes(str) {
841
- const a = str.charCodeAt(0);
842
- const b = str.charCodeAt(str.length - 1);
843
- return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
736
+ const a = str.charCodeAt(0);
737
+ return a === str.charCodeAt(str.length - 1) && (a === 34 || a === 39) ? str.slice(1, -1) : str;
844
738
  }
845
739
  /**
846
- * Determine the type of a character in a keypath.
847
- */
740
+ * Determine the type of a character in a keypath.
741
+ */
848
742
  function getPathCharType(ch) {
849
- if (ch === undefined || ch === null) {
850
- return "o" /* PathCharTypes.END_OF_FAIL */;
851
- }
852
- const code = ch.charCodeAt(0);
853
- switch (code) {
854
- case 0x5b: // [
855
- case 0x5d: // ]
856
- case 0x2e: // .
857
- case 0x22: // "
858
- case 0x27: // '
859
- return ch;
860
- case 0x5f: // _
861
- case 0x24: // $
862
- case 0x2d: // -
863
- return "i" /* PathCharTypes.IDENT */;
864
- case 0x09: // Tab (HT)
865
- case 0x0a: // Newline (LF)
866
- case 0x0d: // Return (CR)
867
- case 0xa0: // No-break space (NBSP)
868
- case 0xfeff: // Byte Order Mark (BOM)
869
- case 0x2028: // Line Separator (LS)
870
- case 0x2029: // Paragraph Separator (PS)
871
- return "w" /* PathCharTypes.WORKSPACE */;
872
- }
873
- return "i" /* PathCharTypes.IDENT */;
743
+ if (ch === void 0 || ch === null) return "o";
744
+ switch (ch.charCodeAt(0)) {
745
+ case 91:
746
+ case 93:
747
+ case 46:
748
+ case 34:
749
+ case 39: return ch;
750
+ case 95:
751
+ case 36:
752
+ case 45: return "i";
753
+ case 9:
754
+ case 10:
755
+ case 13:
756
+ case 160:
757
+ case 65279:
758
+ case 8232:
759
+ case 8233: return "w";
760
+ }
761
+ return "i";
874
762
  }
875
763
  /**
876
- * Format a subPath, return its plain form if it is
877
- * a literal string or number. Otherwise prepend the
878
- * dynamic indicator (*).
879
- */
764
+ * Format a subPath, return its plain form if it is
765
+ * a literal string or number. Otherwise prepend the
766
+ * dynamic indicator (*).
767
+ */
880
768
  function formatSubPath(path) {
881
- const trimmed = path.trim();
882
- // invalid leading 0
883
- if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
884
- return false;
885
- }
886
- return isLiteral(trimmed)
887
- ? stripQuotes(trimmed)
888
- : "*" /* PathCharTypes.ASTARISK */ + trimmed;
769
+ const trimmed = path.trim();
770
+ if (path.charAt(0) === "0" && isNaN(parseInt(path))) return false;
771
+ return isLiteral(trimmed) ? stripQuotes(trimmed) : "*" + trimmed;
889
772
  }
890
773
  /**
891
- * Parse a string path into an array of segments
892
- */
774
+ * Parse a string path into an array of segments
775
+ */
893
776
  function parse(path) {
894
- const keys = [];
895
- let index = -1;
896
- let mode = 0 /* States.BEFORE_PATH */;
897
- let subPathDepth = 0;
898
- let c;
899
- let key; // eslint-disable-line
900
- let newChar;
901
- let type;
902
- let transition;
903
- let action;
904
- let typeMap;
905
- const actions = [];
906
- actions[0 /* Actions.APPEND */] = () => {
907
- if (key === undefined) {
908
- key = newChar;
909
- }
910
- else {
911
- key += newChar;
912
- }
913
- };
914
- actions[1 /* Actions.PUSH */] = () => {
915
- if (key !== undefined) {
916
- keys.push(key);
917
- key = undefined;
918
- }
919
- };
920
- actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
921
- actions[0 /* Actions.APPEND */]();
922
- subPathDepth++;
923
- };
924
- actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
925
- if (subPathDepth > 0) {
926
- subPathDepth--;
927
- mode = 4 /* States.IN_SUB_PATH */;
928
- actions[0 /* Actions.APPEND */]();
929
- }
930
- else {
931
- subPathDepth = 0;
932
- if (key === undefined) {
933
- return false;
934
- }
935
- key = formatSubPath(key);
936
- if (key === false) {
937
- return false;
938
- }
939
- else {
940
- actions[1 /* Actions.PUSH */]();
941
- }
942
- }
943
- };
944
- function maybeUnescapeQuote() {
945
- const nextChar = path[index + 1];
946
- if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
947
- nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
948
- (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
949
- nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
950
- index++;
951
- newChar = '\\' + nextChar;
952
- actions[0 /* Actions.APPEND */]();
953
- return true;
954
- }
955
- }
956
- while (mode !== null) {
957
- index++;
958
- c = path[index];
959
- if (c === '\\' && maybeUnescapeQuote()) {
960
- continue;
961
- }
962
- type = getPathCharType(c);
963
- typeMap = pathStateMachine[mode];
964
- transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
965
- // check parse error
966
- if (transition === 8 /* States.ERROR */) {
967
- return;
968
- }
969
- mode = transition[0];
970
- if (transition[1] !== undefined) {
971
- action = actions[transition[1]];
972
- if (action) {
973
- newChar = c;
974
- if (action() === false) {
975
- return;
976
- }
977
- }
978
- }
979
- // check parse finish
980
- if (mode === 7 /* States.AFTER_PATH */) {
981
- return keys;
982
- }
983
- }
984
- }
985
- // path token cache
986
- const cache = new Map();
777
+ const keys = [];
778
+ let index = -1;
779
+ let mode = 0;
780
+ let subPathDepth = 0;
781
+ let c;
782
+ let key;
783
+ let newChar;
784
+ let type;
785
+ let transition;
786
+ let action;
787
+ let typeMap;
788
+ const actions = [];
789
+ actions[0] = () => {
790
+ if (key === void 0) key = newChar;
791
+ else key += newChar;
792
+ };
793
+ actions[1] = () => {
794
+ if (key !== void 0) {
795
+ keys.push(key);
796
+ key = void 0;
797
+ }
798
+ };
799
+ actions[2] = () => {
800
+ actions[0]();
801
+ subPathDepth++;
802
+ };
803
+ actions[3] = () => {
804
+ if (subPathDepth > 0) {
805
+ subPathDepth--;
806
+ mode = 4;
807
+ actions[0]();
808
+ } else {
809
+ subPathDepth = 0;
810
+ if (key === void 0) return false;
811
+ key = formatSubPath(key);
812
+ if (key === false) return false;
813
+ else actions[1]();
814
+ }
815
+ };
816
+ function maybeUnescapeQuote() {
817
+ const nextChar = path[index + 1];
818
+ if (mode === 5 && nextChar === "'" || mode === 6 && nextChar === "\"") {
819
+ index++;
820
+ newChar = "\\" + nextChar;
821
+ actions[0]();
822
+ return true;
823
+ }
824
+ }
825
+ while (mode !== null) {
826
+ index++;
827
+ c = path[index];
828
+ if (c === "\\" && maybeUnescapeQuote()) continue;
829
+ type = getPathCharType(c);
830
+ typeMap = pathStateMachine[mode];
831
+ transition = typeMap[type] || typeMap["l"] || 8;
832
+ if (transition === 8) return;
833
+ mode = transition[0];
834
+ if (transition[1] !== void 0) {
835
+ action = actions[transition[1]];
836
+ if (action) {
837
+ newChar = c;
838
+ if (action() === false) return;
839
+ }
840
+ }
841
+ if (mode === 7) return keys;
842
+ }
843
+ }
844
+ const cache = /* @__PURE__ */ new Map();
987
845
  /**
988
- * key-value message resolver
989
- *
990
- * @remarks
991
- * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
992
- *
993
- * @param obj - A target object to be resolved with path
994
- * @param path - A {@link Path | path} to resolve the value of message
995
- *
996
- * @returns A resolved {@link PathValue | path value}
997
- *
998
- * @VueI18nGeneral
999
- */
846
+ * key-value message resolver
847
+ *
848
+ * @remarks
849
+ * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
850
+ *
851
+ * @param obj - A target object to be resolved with path
852
+ * @param path - A {@link Path | path} to resolve the value of message
853
+ *
854
+ * @returns A resolved {@link PathValue | path value}
855
+ *
856
+ * @VueI18nGeneral
857
+ */
1000
858
  function resolveWithKeyValue(obj, path) {
1001
- // read only own properties, so that a key such as `toString` does not
1002
- // resolve a built-in function
1003
- return isObject(obj) ? getOwn(obj, path) : null;
859
+ return isObject(obj) ? getOwn(obj, path) : null;
1004
860
  }
1005
861
  /**
1006
- * message resolver
1007
- *
1008
- * @remarks
1009
- * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
1010
- *
1011
- * @param obj - A target object to be resolved with path
1012
- * @param path - A {@link Path | path} to resolve the value of message
1013
- *
1014
- * @returns A resolved {@link PathValue | path value}
1015
- *
1016
- * @VueI18nGeneral
1017
- */
862
+ * message resolver
863
+ *
864
+ * @remarks
865
+ * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
866
+ *
867
+ * @param obj - A target object to be resolved with path
868
+ * @param path - A {@link Path | path} to resolve the value of message
869
+ *
870
+ * @returns A resolved {@link PathValue | path value}
871
+ *
872
+ * @VueI18nGeneral
873
+ */
1018
874
  function resolveValue(obj, path) {
1019
- // check object
1020
- if (!isObject(obj)) {
1021
- return null;
1022
- }
1023
- // parse path
1024
- let hit = cache.get(path);
1025
- if (!hit) {
1026
- hit = parse(path);
1027
- if (hit) {
1028
- cache.set(path, hit);
1029
- }
1030
- }
1031
- // check hit
1032
- if (!hit) {
1033
- return null;
1034
- }
1035
- // resolve path value
1036
- const len = hit.length;
1037
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- for generic object
1038
- let last = obj;
1039
- let i = 0;
1040
- while (i < len) {
1041
- const key = hit[i];
1042
- /**
1043
- * NOTE:
1044
- * if `key` is intlify message format AST node key and `last` is intlify message format AST, skip it.
1045
- * because the AST node is not a key-value structure.
1046
- */
1047
- if (AST_NODE_PROPS_KEYS.includes(key) && isMessageAST(last)) {
1048
- return null;
1049
- }
1050
- if (!isObject(last)) {
1051
- return null;
1052
- }
1053
- if (!hasOwn(last, key)) {
1054
- return null;
1055
- }
1056
- const val = last[key];
1057
- if (val === undefined) {
1058
- return null;
1059
- }
1060
- if (isFunction(last)) {
1061
- return null;
1062
- }
1063
- last = val;
1064
- i++;
1065
- }
1066
- return last;
1067
- }
1068
-
875
+ if (!isObject(obj)) return null;
876
+ let hit = cache.get(path);
877
+ if (!hit) {
878
+ hit = parse(path);
879
+ if (hit) cache.set(path, hit);
880
+ }
881
+ if (!hit) return null;
882
+ const len = hit.length;
883
+ let last = obj;
884
+ let i = 0;
885
+ while (i < len) {
886
+ const key = hit[i];
887
+ /**
888
+ * NOTE:
889
+ * if `key` is intlify message format AST node key and `last` is intlify message format AST, skip it.
890
+ * because the AST node is not a key-value structure.
891
+ */
892
+ if (AST_NODE_PROPS_KEYS.includes(key) && isMessageAST(last)) return null;
893
+ if (!isObject(last)) return null;
894
+ if (!hasOwn(last, key)) return null;
895
+ const val = last[key];
896
+ if (val === void 0) return null;
897
+ if (isFunction(last)) return null;
898
+ last = val;
899
+ i++;
900
+ }
901
+ return last;
902
+ }
903
+ // packages/core-base/src/warnings.ts
1069
904
  const CoreWarnCodes = {
1070
- NOT_FOUND_KEY: 1,
1071
- FALLBACK_TO_TRANSLATE: 2,
1072
- CANNOT_FORMAT_NUMBER: 3,
1073
- FALLBACK_TO_NUMBER_FORMAT: 4,
1074
- CANNOT_FORMAT_DATE: 5,
1075
- FALLBACK_TO_DATE_FORMAT: 6,
1076
- EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: 7,
1077
- INVALID_NUMBER_ARGUMENT: 8,
1078
- INVALID_DATE_ARGUMENT: 9
905
+ NOT_FOUND_KEY: 1,
906
+ FALLBACK_TO_TRANSLATE: 2,
907
+ CANNOT_FORMAT_NUMBER: 3,
908
+ FALLBACK_TO_NUMBER_FORMAT: 4,
909
+ CANNOT_FORMAT_DATE: 5,
910
+ FALLBACK_TO_DATE_FORMAT: 6,
911
+ EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: 7,
912
+ INVALID_NUMBER_ARGUMENT: 8,
913
+ INVALID_DATE_ARGUMENT: 9,
914
+ IGNORE_UNSAFE_LOCALE: 10,
915
+ FALLBACK_TO_DEFAULT_PLURAL_RULE: 11,
916
+ FALLBACK_FROM_INVALID_LOCALE: 12
1079
917
  };
1080
- const CORE_WARN_CODES_EXTEND_POINT = 10;
918
+ const CORE_WARN_CODES_EXTEND_POINT = 13;
1081
919
  /** @internal */
1082
920
  const warnMessages = {
1083
- [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale {resource}.`,
1084
- [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
1085
- [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
1086
- [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
1087
- [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
1088
- [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`,
1089
- [CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER]: `This project is using Custom Message Compiler, which is an experimental feature. It may receive breaking changes or be removed in the future.`,
1090
- [CoreWarnCodes.INVALID_NUMBER_ARGUMENT]: `Invalid argument for number formatting: expected a number but received '{value}'.`,
1091
- [CoreWarnCodes.INVALID_DATE_ARGUMENT]: `Invalid argument for datetime formatting: expected a Date, number, or ISO string but received '{value}'.`
921
+ [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale {resource}.`,
922
+ [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
923
+ [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
924
+ [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
925
+ [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
926
+ [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`,
927
+ [CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER]: `This project is using Custom Message Compiler, which is an experimental feature. It may receive breaking changes or be removed in the future.`,
928
+ [CoreWarnCodes.INVALID_NUMBER_ARGUMENT]: `Invalid argument for number formatting: expected a number but received '{value}'.`,
929
+ [CoreWarnCodes.INVALID_DATE_ARGUMENT]: `Invalid argument for datetime formatting: expected a Date, number, or ISO string but received '{value}'.`,
930
+ [CoreWarnCodes.IGNORE_UNSAFE_LOCALE]: `Ignore '{locale}' locale: it is a property name of Object.prototype`,
931
+ [CoreWarnCodes.FALLBACK_TO_DEFAULT_PLURAL_RULE]: `Fall back to the default plural rule for '{locale}' locale: Intl.PluralRules does not support it`,
932
+ [CoreWarnCodes.FALLBACK_FROM_INVALID_LOCALE]: `Fall back to '{target}' locale for {type} formatting with '{locale}' locale: it is not a BCP 47 language tag`
1092
933
  };
1093
934
  function getWarnMessage(code, ...args) {
1094
- return format$1(warnMessages[code], ...args);
935
+ return format$1(warnMessages[code], ...args);
1095
936
  }
1096
-
1097
- /* eslint-disable @typescript-eslint/no-explicit-any */
937
+ // packages/core-base/src/context.ts
1098
938
  /**
1099
- * Intlify core-base version
1100
- * @internal
1101
- */
1102
- const VERSION = '11.4.18';
1103
- const NOT_REOSLVED = -1;
1104
- const DEFAULT_LOCALE = 'en-US';
1105
- const MISSING_RESOLVE_VALUE = '';
939
+ * Intlify core-base version
940
+ * @internal
941
+ */
942
+ const VERSION = "12.0.0-alpha.10";
943
+ const NOT_RESOLVED = -1;
944
+ const DEFAULT_LOCALE = "en-US";
945
+ const MISSING_RESOLVE_VALUE = "";
1106
946
  const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
1107
947
  function getDefaultLinkedModifiers() {
1108
- return {
1109
- upper: (val, type) => {
1110
- // prettier-ignore
1111
- return type === 'text' && isString(val)
1112
- ? val.toUpperCase()
1113
- : type === 'vnode' && isObject(val) && '__v_isVNode' in val
1114
- ? val.children.toUpperCase()
1115
- : val;
1116
- },
1117
- lower: (val, type) => {
1118
- // prettier-ignore
1119
- return type === 'text' && isString(val)
1120
- ? val.toLowerCase()
1121
- : type === 'vnode' && isObject(val) && '__v_isVNode' in val
1122
- ? val.children.toLowerCase()
1123
- : val;
1124
- },
1125
- capitalize: (val, type) => {
1126
- // prettier-ignore
1127
- return (type === 'text' && isString(val)
1128
- ? capitalize(val)
1129
- : type === 'vnode' && isObject(val) && '__v_isVNode' in val
1130
- ? capitalize(val.children)
1131
- : val);
1132
- }
1133
- };
948
+ return {
949
+ upper: (val, type) => {
950
+ return type === "text" && isString(val) ? val.toUpperCase() : type === "vnode" && isObject(val) && "__v_isVNode" in val ? val.children.toUpperCase() : val;
951
+ },
952
+ lower: (val, type) => {
953
+ return type === "text" && isString(val) ? val.toLowerCase() : type === "vnode" && isObject(val) && "__v_isVNode" in val ? val.children.toLowerCase() : val;
954
+ },
955
+ capitalize: (val, type) => {
956
+ return type === "text" && isString(val) ? capitalize(val) : type === "vnode" && isObject(val) && "__v_isVNode" in val ? capitalize(val.children) : val;
957
+ }
958
+ };
1134
959
  }
1135
960
  let _compiler;
961
+ /**
962
+ * Register the message compiler
963
+ *
964
+ * @param compiler - A {@link MessageCompiler} function
965
+ *
966
+ * @deprecated Use `messageCompiler` option of `createI18n` or `createCoreContext` instead. This function will be removed in v13.
967
+ *
968
+ * @VueI18nGeneral
969
+ */
1136
970
  function registerMessageCompiler(compiler) {
1137
- _compiler = compiler;
971
+ warnOnce(`registerMessageCompiler is deprecated. Use 'messageCompiler' option of 'createI18n' or 'createCoreContext' instead.`);
972
+ _compiler = compiler;
1138
973
  }
1139
974
  let _resolver;
1140
975
  /**
1141
- * Register the message resolver
1142
- *
1143
- * @param resolver - A {@link MessageResolver} function
1144
- *
1145
- * @VueI18nGeneral
1146
- */
976
+ * Register the message resolver
977
+ *
978
+ * @param resolver - A {@link MessageResolver} function
979
+ *
980
+ * @deprecated Use `messageResolver` option of `createI18n` or `createCoreContext` instead. This function will be removed in v13.
981
+ *
982
+ * @VueI18nGeneral
983
+ */
1147
984
  function registerMessageResolver(resolver) {
1148
- _resolver = resolver;
985
+ warnOnce(`registerMessageResolver is deprecated. Use 'messageResolver' option of 'createI18n' or 'createCoreContext' instead.`);
986
+ _resolver = resolver;
1149
987
  }
1150
988
  let _fallbacker;
1151
989
  /**
1152
- * Register the locale fallbacker
1153
- *
1154
- * @param fallbacker - A {@link LocaleFallbacker} function
1155
- *
1156
- * @VueI18nGeneral
1157
- */
990
+ * Register the locale fallbacker
991
+ *
992
+ * @param fallbacker - A {@link LocaleFallbacker} function
993
+ *
994
+ * @deprecated Use `localeFallbacker` option of `createI18n` or `createCoreContext` instead. This function will be removed in v13.
995
+ *
996
+ * @VueI18nGeneral
997
+ */
1158
998
  function registerLocaleFallbacker(fallbacker) {
1159
- _fallbacker = fallbacker;
999
+ warnOnce(`registerLocaleFallbacker is deprecated. Use 'localeFallbacker' option of 'createI18n' or 'createCoreContext' instead.`);
1000
+ _fallbacker = fallbacker;
1160
1001
  }
1161
- // Additional Meta for Intlify DevTools
1162
- let _additionalMeta = null;
1163
- /* #__NO_SIDE_EFFECTS__ */
1164
- const setAdditionalMeta = (meta) => {
1165
- _additionalMeta = meta;
1166
- };
1167
- /* #__NO_SIDE_EFFECTS__ */
1168
- const getAdditionalMeta = () => _additionalMeta;
1169
- let _fallbackContext = null;
1170
- const setFallbackContext = (context) => {
1171
- _fallbackContext = context;
1172
- };
1173
- const getFallbackContext = () => _fallbackContext;
1174
- // ID for CoreContext
1175
1002
  let _cid = 0;
1176
1003
  function createCoreContext(options = {}) {
1177
- // setup options
1178
- const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
1179
- const version = isString(options.version) ? options.version : VERSION;
1180
- const locale = isString(options.locale) || isFunction(options.locale)
1181
- ? options.locale
1182
- : DEFAULT_LOCALE;
1183
- const _locale = isFunction(locale) ? DEFAULT_LOCALE : locale;
1184
- const fallbackLocale = isArray(options.fallbackLocale) ||
1185
- isPlainObject(options.fallbackLocale) ||
1186
- isString(options.fallbackLocale) ||
1187
- options.fallbackLocale === false
1188
- ? options.fallbackLocale
1189
- : _locale;
1190
- const messages = isPlainObject(options.messages)
1191
- ? options.messages
1192
- : createResources(_locale);
1193
- const datetimeFormats = isPlainObject(options.datetimeFormats)
1194
- ? options.datetimeFormats
1195
- : createResources(_locale)
1196
- ;
1197
- const numberFormats = isPlainObject(options.numberFormats)
1198
- ? options.numberFormats
1199
- : createResources(_locale)
1200
- ;
1201
- const modifiers = assign(create(), options.modifiers, getDefaultLinkedModifiers());
1202
- const pluralRules = options.pluralRules || create();
1203
- const missing = isFunction(options.missing) ? options.missing : null;
1204
- const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
1205
- ? options.missingWarn
1206
- : true;
1207
- const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
1208
- ? options.fallbackWarn
1209
- : true;
1210
- const fallbackFormat = !!options.fallbackFormat;
1211
- const unresolving = !!options.unresolving;
1212
- const postTranslation = isFunction(options.postTranslation)
1213
- ? options.postTranslation
1214
- : null;
1215
- const processor = isPlainObject(options.processor) ? options.processor : null;
1216
- const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
1217
- ? options.warnHtmlMessage
1218
- : true;
1219
- const escapeParameter = !!options.escapeParameter;
1220
- const messageCompiler = isFunction(options.messageCompiler)
1221
- ? options.messageCompiler
1222
- : _compiler;
1223
- if (isFunction(options.messageCompiler)) {
1224
- warnOnce(getWarnMessage(CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER));
1225
- }
1226
- const messageResolver = isFunction(options.messageResolver)
1227
- ? options.messageResolver
1228
- : _resolver || resolveWithKeyValue;
1229
- const localeFallbacker = isFunction(options.localeFallbacker)
1230
- ? options.localeFallbacker
1231
- : _fallbacker || fallbackWithSimple;
1232
- const fallbackContext = isObject(options.fallbackContext)
1233
- ? options.fallbackContext
1234
- : undefined;
1235
- // setup internal options
1236
- const internalOptions = options;
1237
- const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
1238
- ? internalOptions.__datetimeFormatters
1239
- : new Map()
1240
- ;
1241
- const __numberFormatters = isObject(internalOptions.__numberFormatters)
1242
- ? internalOptions.__numberFormatters
1243
- : new Map()
1244
- ;
1245
- const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};
1246
- _cid++;
1247
- const context = {
1248
- version,
1249
- cid: _cid,
1250
- locale,
1251
- fallbackLocale,
1252
- messages,
1253
- modifiers,
1254
- pluralRules,
1255
- missing,
1256
- missingWarn,
1257
- fallbackWarn,
1258
- fallbackFormat,
1259
- unresolving,
1260
- postTranslation,
1261
- processor,
1262
- warnHtmlMessage,
1263
- escapeParameter,
1264
- messageCompiler,
1265
- messageResolver,
1266
- localeFallbacker,
1267
- fallbackContext,
1268
- onWarn,
1269
- __meta
1270
- };
1271
- {
1272
- context.datetimeFormats = datetimeFormats;
1273
- context.numberFormats = numberFormats;
1274
- context.__datetimeFormatters = __datetimeFormatters;
1275
- context.__numberFormatters = __numberFormatters;
1276
- }
1277
- // for vue-devtools timeline event
1278
- {
1279
- context.__v_emitter =
1280
- internalOptions.__v_emitter != null
1281
- ? internalOptions.__v_emitter
1282
- : undefined;
1283
- }
1284
- // NOTE: experimental !!
1285
- {
1286
- initI18nDevTools(context, version, __meta);
1287
- }
1288
- return context;
1004
+ const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
1005
+ const version = isString(options.version) ? options.version : VERSION;
1006
+ const locale = isString(options.locale) || isFunction(options.locale) ? options.locale : DEFAULT_LOCALE;
1007
+ const _locale = isFunction(locale) ? DEFAULT_LOCALE : locale;
1008
+ const fallbackLocale = isFallbackLocale(options.fallbackLocale) ? options.fallbackLocale : _locale;
1009
+ const messages = isPlainObject(options.messages) ? options.messages : createResources(_locale);
1010
+ const datetimeFormats = isPlainObject(options.datetimeFormats) ? options.datetimeFormats : createResources(_locale);
1011
+ const numberFormats = isPlainObject(options.numberFormats) ? options.numberFormats : createResources(_locale);
1012
+ const modifiers = assign(create(), options.modifiers, getDefaultLinkedModifiers());
1013
+ const pluralRules = options.pluralRules || create();
1014
+ const missing = isFunction(options.missing) ? options.missing : null;
1015
+ const missingWarn = isWarnOption(options.missingWarn) ? options.missingWarn : true;
1016
+ const fallbackWarn = isWarnOption(options.fallbackWarn) ? options.fallbackWarn : true;
1017
+ const fallbackFormat = !!options.fallbackFormat;
1018
+ const unresolving = !!options.unresolving;
1019
+ const postTranslation = isFunction(options.postTranslation) ? options.postTranslation : null;
1020
+ const processor = isPlainObject(options.processor) ? options.processor : null;
1021
+ const warnHtmlMessage = isBoolean(options.warnHtmlMessage) ? options.warnHtmlMessage : true;
1022
+ const escapeParameter = !!options.escapeParameter;
1023
+ const messageCompiler = isFunction(options.messageCompiler) ? options.messageCompiler : _compiler || null;
1024
+ const messageResolver = isFunction(options.messageResolver) ? options.messageResolver : _resolver || resolveWithKeyValue;
1025
+ const localeFallbacker = isFunction(options.localeFallbacker) ? options.localeFallbacker : _fallbacker || fallbackWithSimple;
1026
+ const fallbackContext = isObject(options.fallbackContext) ? options.fallbackContext : void 0;
1027
+ _cid++;
1028
+ const context = {
1029
+ version,
1030
+ cid: _cid,
1031
+ locale,
1032
+ fallbackLocale,
1033
+ messages,
1034
+ modifiers,
1035
+ pluralRules,
1036
+ missing,
1037
+ missingWarn,
1038
+ fallbackWarn,
1039
+ fallbackFormat,
1040
+ unresolving,
1041
+ postTranslation,
1042
+ processor,
1043
+ warnHtmlMessage,
1044
+ escapeParameter,
1045
+ messageCompiler,
1046
+ messageResolver,
1047
+ localeFallbacker,
1048
+ fallbackContext,
1049
+ onWarn
1050
+ };
1051
+ context.datetimeFormats = datetimeFormats;
1052
+ context.numberFormats = numberFormats;
1053
+ context.__datetimeFormatters = /* @__PURE__ */ new Map();
1054
+ context.__numberFormatters = /* @__PURE__ */ new Map();
1055
+ return context;
1289
1056
  }
1290
1057
  const createResources = (locale) => ({ [locale]: create() });
1058
+ /**
1059
+ * @version 12.0.0
1060
+ */
1061
+ function getLocaleMessage(ctx, locale) {
1062
+ const src = getOwn(ctx.messages, locale);
1063
+ if (src == null) return;
1064
+ const dest = create();
1065
+ deepCopy(src, dest);
1066
+ return dest;
1067
+ }
1068
+ /**
1069
+ * @version 12.0.0
1070
+ */
1071
+ function setLocaleMessage(ctx, locale, messages) {
1072
+ if (isObjectPrototypeKey(locale)) {
1073
+ ctx.onWarn(getWarnMessage(CoreWarnCodes.IGNORE_UNSAFE_LOCALE, { locale }));
1074
+ return;
1075
+ }
1076
+ ctx.messages[locale] = messages;
1077
+ }
1078
+ /** @internal */
1079
+ function isFallbackLocale(val) {
1080
+ return isString(val) || isArray(val) || isPlainObject(val) || val === false;
1081
+ }
1082
+ /** @internal */
1083
+ function isWarnOption(val) {
1084
+ return isBoolean(val) || isRegExp(val);
1085
+ }
1291
1086
  /** @internal */
1292
1087
  function isTranslateFallbackWarn(fallback, key) {
1293
- return fallback instanceof RegExp ? fallback.test(key) : fallback;
1088
+ return isRegExp(fallback) ? fallback.test(key) : fallback;
1294
1089
  }
1295
1090
  /** @internal */
1296
1091
  function isTranslateMissingWarn(missing, key) {
1297
- return missing instanceof RegExp ? missing.test(key) : missing;
1092
+ return isRegExp(missing) ? missing.test(key) : missing;
1298
1093
  }
1299
1094
  /** @internal */
1300
1095
  function handleMissing(context, key, locale, missingWarn, type) {
1301
- const { missing, onWarn } = context;
1302
- // for vue-devtools timeline event
1303
- {
1304
- const emitter = context.__v_emitter;
1305
- if (emitter) {
1306
- emitter.emit('missing', {
1307
- locale,
1308
- key,
1309
- type,
1310
- groupId: toDevtoolsGroupId(type, key)
1311
- });
1312
- }
1313
- }
1314
- if (missing !== null) {
1315
- const ret = missing(context, locale, key, type);
1316
- return isString(ret) ? ret : key;
1317
- }
1318
- else {
1319
- if (isTranslateMissingWarn(missingWarn, key)) {
1320
- onWarn(getWarnMessage(CoreWarnCodes.NOT_FOUND_KEY, {
1321
- key,
1322
- locale,
1323
- resource: type === 'datetime format'
1324
- ? 'datetime formats'
1325
- : type === 'number format'
1326
- ? 'number formats'
1327
- : 'messages'
1328
- }));
1329
- }
1330
- return key;
1331
- }
1096
+ const { missing, onWarn } = context;
1097
+ {
1098
+ const emitter = context.__v_emitter;
1099
+ if (emitter) emitter.emit("missing", {
1100
+ locale,
1101
+ key,
1102
+ type,
1103
+ groupId: toDevtoolsGroupId(type, key)
1104
+ });
1105
+ }
1106
+ if (missing !== null) {
1107
+ const ret = missing(context, locale, key, type);
1108
+ return isString(ret) ? ret : key;
1109
+ } else {
1110
+ if (isTranslateMissingWarn(missingWarn, key)) onWarn(getWarnMessage(CoreWarnCodes.NOT_FOUND_KEY, {
1111
+ key,
1112
+ locale,
1113
+ resource: type === "datetime format" ? "datetime formats" : type === "number format" ? "number formats" : "messages"
1114
+ }));
1115
+ return key;
1116
+ }
1332
1117
  }
1333
1118
  function invalidateLocaleChainCache(ctx, fallback) {
1334
- const context = ctx;
1335
- if (isObject(fallback)) {
1336
- context.__localeChainObjectCache?.delete(fallback);
1337
- }
1338
- else {
1339
- context.__localeChainCache?.delete(fallback);
1340
- }
1119
+ const context = ctx;
1120
+ if (isObject(fallback)) context.__localeChainObjectCache?.delete(fallback);
1121
+ else context.__localeChainCache?.delete(fallback);
1341
1122
  }
1342
1123
  /** @internal */
1343
1124
  function updateFallbackLocale(ctx, locale, fallback) {
1344
- invalidateLocaleChainCache(ctx, fallback);
1345
- // NOTE: getMessageContextOptions() queries the root context with *this*
1346
- // (local) fallback, so the root holds an entry under the same identity key.
1347
- // Clearing only the local context leaves a stale chain behind.
1348
- if (ctx.fallbackContext) {
1349
- invalidateLocaleChainCache(ctx.fallbackContext, fallback);
1350
- }
1351
- ctx.localeFallbacker(ctx, fallback, locale);
1125
+ invalidateLocaleChainCache(ctx, fallback);
1126
+ if (ctx.fallbackContext) invalidateLocaleChainCache(ctx.fallbackContext, fallback);
1127
+ {
1128
+ const { __datetimeFormatters, __numberFormatters } = ctx;
1129
+ __datetimeFormatters.clear();
1130
+ __numberFormatters.clear();
1131
+ }
1132
+ ctx.localeFallbacker(ctx, fallback, locale);
1352
1133
  }
1353
1134
  /** @internal */
1354
1135
  function isAlmostSameLocale(locale, compareLocale) {
1355
- if (locale === compareLocale)
1356
- return false;
1357
- return locale.split('-')[0] === compareLocale.split('-')[0];
1136
+ if (locale === compareLocale) return false;
1137
+ return locale.split("-")[0] === compareLocale.split("-")[0];
1358
1138
  }
1359
1139
  /** @internal */
1360
1140
  function isImplicitFallback(targetLocale, locales) {
1361
- const index = locales.indexOf(targetLocale);
1362
- if (index === -1) {
1363
- return false;
1364
- }
1365
- for (let i = index + 1; i < locales.length; i++) {
1366
- if (isAlmostSameLocale(targetLocale, locales[i])) {
1367
- return true;
1368
- }
1369
- }
1370
- return false;
1371
- }
1372
- /* eslint-enable @typescript-eslint/no-explicit-any */
1373
-
1141
+ const index = locales.indexOf(targetLocale);
1142
+ if (index === -1) return false;
1143
+ for (let i = index + 1; i < locales.length; i++) if (isAlmostSameLocale(targetLocale, locales[i])) return true;
1144
+ return false;
1145
+ }
1146
+ // packages/core-base/src/formatter.ts
1374
1147
  function resolveFormatLocale(context, key, locale, formats, missingWarn, fallbackWarn, type) {
1375
- const { fallbackLocale, localeFallbacker, onWarn } = context;
1376
- const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1377
- fallbackLocale, locale);
1378
- let from = locale;
1379
- for (let i = 0; i < locales.length; i++) {
1380
- const targetLocale = locales[i];
1381
- if (locale !== targetLocale &&
1382
- isTranslateFallbackWarn(fallbackWarn, key)) {
1383
- onWarn(getWarnMessage(type === 'datetime format'
1384
- ? CoreWarnCodes.FALLBACK_TO_DATE_FORMAT
1385
- : CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
1386
- key,
1387
- target: targetLocale
1388
- }));
1389
- }
1390
- if (locale !== targetLocale) {
1391
- const emitter = context.__v_emitter;
1392
- if (emitter) {
1393
- emitter.emit('fallback', {
1394
- type,
1395
- key,
1396
- from,
1397
- to: targetLocale,
1398
- groupId: toDevtoolsGroupId(type, key)
1399
- });
1400
- }
1401
- }
1402
- // read only own properties, so that a locale such as `constructor` does not
1403
- // read a built-in object
1404
- const format = getOwn(getOwn(formats, targetLocale) || {}, key);
1405
- if (isPlainObject(format) && isString(targetLocale)) {
1406
- return targetLocale;
1407
- }
1408
- handleMissing(context, key, targetLocale, missingWarn, type);
1409
- from = targetLocale;
1410
- }
1411
- return null;
1148
+ const { fallbackLocale, localeFallbacker, onWarn } = context;
1149
+ const locales = localeFallbacker(context, fallbackLocale, locale);
1150
+ let from = locale;
1151
+ for (let i = 0; i < locales.length; i++) {
1152
+ const targetLocale = locales[i];
1153
+ if (locale !== targetLocale && isTranslateFallbackWarn(fallbackWarn, key)) onWarn(getWarnMessage(type === "datetime format" ? CoreWarnCodes.FALLBACK_TO_DATE_FORMAT : CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
1154
+ key,
1155
+ target: targetLocale
1156
+ }));
1157
+ if (locale !== targetLocale) {
1158
+ const emitter = context.__v_emitter;
1159
+ if (emitter) emitter.emit("fallback", {
1160
+ type,
1161
+ key,
1162
+ from,
1163
+ to: targetLocale,
1164
+ groupId: toDevtoolsGroupId(type, key)
1165
+ });
1166
+ }
1167
+ const format = getOwn(getOwn(formats, targetLocale) || {}, key);
1168
+ if (isPlainObject(format) && isString(targetLocale)) return targetLocale;
1169
+ handleMissing(context, key, targetLocale, missingWarn, type);
1170
+ from = targetLocale;
1171
+ }
1172
+ return null;
1173
+ }
1174
+ function isLanguageTag(locale) {
1175
+ try {
1176
+ Intl.getCanonicalLocales(locale);
1177
+ return true;
1178
+ } catch {
1179
+ return false;
1180
+ }
1181
+ }
1182
+ /**
1183
+ * Create an `Intl.DateTimeFormat` or `Intl.NumberFormat` formatter
1184
+ *
1185
+ * @remarks
1186
+ * `Intl` throws a RangeError for a locale that is not a BCP 47 language tag (e.g. `pt_BR`),
1187
+ * so fall back to the first language tag in the locale chain, or the default locale
1188
+ */
1189
+ function createFormatter(context, IntlFormatter, locale, options, type) {
1190
+ try {
1191
+ return new IntlFormatter(locale, options);
1192
+ } catch (error) {
1193
+ if (isLanguageTag(locale)) throw error;
1194
+ const { fallbackLocale, localeFallbacker, onWarn } = context;
1195
+ const target = localeFallbacker(context, fallbackLocale, locale).find(isLanguageTag) || "en-US";
1196
+ onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_FROM_INVALID_LOCALE, {
1197
+ locale,
1198
+ target,
1199
+ type: type === "datetime format" ? "datetime" : "number"
1200
+ }));
1201
+ return new IntlFormatter(target, options);
1202
+ }
1203
+ }
1204
+ /**
1205
+ * Format a value with the format of a key, or only with the overrides when no key is given
1206
+ *
1207
+ * @remarks
1208
+ * The common part of `datetime()` and `number()`, after they check and parse the arguments
1209
+ */
1210
+ function formatValue(context, [key, value, options, overrides], IntlFormatter, formatters, formats, type) {
1211
+ const missingWarn = isBoolean(options.missingWarn) ? options.missingWarn : context.missingWarn;
1212
+ const fallbackWarn = isBoolean(options.fallbackWarn) ? options.fallbackWarn : context.fallbackWarn;
1213
+ const part = !!options.part;
1214
+ const locale = getLocale(context, options);
1215
+ if (!isString(key) || key === "") {
1216
+ const formatter = createFormatter(context, IntlFormatter, locale.replace(/!/g, ""), overrides, type);
1217
+ return !part ? formatter.format(value) : formatter.formatToParts(value);
1218
+ }
1219
+ const targetLocale = resolveFormatLocale(context, key, locale, formats, missingWarn, fallbackWarn, type);
1220
+ if (!isString(targetLocale)) return context.unresolving ? -1 : key;
1221
+ const format = formats[targetLocale][key];
1222
+ const id = getFormatterCacheKey(targetLocale, key, overrides);
1223
+ let formatter = formatters.get(id);
1224
+ if (!formatter) {
1225
+ formatter = createFormatter(context, IntlFormatter, targetLocale, assign({}, format, overrides), type);
1226
+ formatters.set(id, formatter);
1227
+ }
1228
+ return !part ? formatter.format(value) : formatter.formatToParts(value);
1412
1229
  }
1413
1230
  function getFormatterCacheKey(locale, key, overrides) {
1414
- let id = `${locale}__${key}`;
1415
- if (isPlainObject(overrides) && !isEmptyObject(overrides)) {
1416
- id = `${id}__${JSON.stringify(overrides)}`;
1417
- }
1418
- return id;
1231
+ let id = `${locale}__${key}`;
1232
+ if (isPlainObject(overrides) && !isKeylessObject(overrides)) id = `${id}__${JSON.stringify(overrides)}`;
1233
+ return id;
1419
1234
  }
1420
1235
  function clearFormatCache(formatters, locale, format) {
1421
- for (const key in format) {
1422
- const prefix = `${locale}__${key}`;
1423
- for (const id of formatters.keys()) {
1424
- if (id === prefix || id.startsWith(`${prefix}__`)) {
1425
- formatters.delete(id);
1426
- }
1427
- }
1428
- }
1236
+ for (const key in format) {
1237
+ const prefix = `${locale}__${key}`;
1238
+ for (const id of formatters.keys()) if (id === prefix || id.startsWith(`${prefix}__`)) formatters.delete(id);
1239
+ }
1429
1240
  }
1430
1241
  function parseFormatArgs(args, options, initialOverrides, optionsKeys) {
1431
- const [, arg2, arg3, arg4] = args;
1432
- let overrides = initialOverrides;
1433
- if (isString(arg2)) {
1434
- options.key = arg2;
1435
- }
1436
- else if (isPlainObject(arg2)) {
1437
- Object.keys(arg2).forEach(key => {
1438
- if (optionsKeys.includes(key)) {
1439
- overrides[key] = arg2[key];
1440
- }
1441
- else {
1442
- options[key] = arg2[key];
1443
- }
1444
- });
1445
- }
1446
- if (isString(arg3)) {
1447
- options.locale = arg3;
1448
- }
1449
- else if (isPlainObject(arg3)) {
1450
- overrides = arg3;
1451
- }
1452
- if (isPlainObject(arg4)) {
1453
- overrides = arg4;
1454
- }
1455
- return overrides;
1456
- }
1457
-
1458
- const intlDefined = typeof Intl !== 'undefined';
1242
+ const [, arg2, arg3, arg4] = args;
1243
+ let overrides = initialOverrides;
1244
+ if (isString(arg2)) options.key = arg2;
1245
+ else if (isPlainObject(arg2)) Object.keys(arg2).forEach((key) => {
1246
+ if (optionsKeys.includes(key)) overrides[key] = arg2[key];
1247
+ else options[key] = arg2[key];
1248
+ });
1249
+ if (isString(arg3)) options.locale = arg3;
1250
+ else if (isPlainObject(arg3)) overrides = arg3;
1251
+ if (isPlainObject(arg4)) overrides = arg4;
1252
+ return overrides;
1253
+ }
1254
+ // packages/core-base/src/intl.ts
1255
+ const intlDefined = typeof Intl !== "undefined";
1459
1256
  const Availabilities = {
1460
- dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
1461
- numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
1257
+ dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== "undefined",
1258
+ numberFormat: intlDefined && typeof Intl.NumberFormat !== "undefined"
1462
1259
  };
1463
-
1464
- // implementation of `datetime` function
1260
+ // packages/core-base/src/datetime.ts
1465
1261
  function datetime(context, ...args) {
1466
- const { datetimeFormats, unresolving, onWarn } = context;
1467
- const { __datetimeFormatters } = context;
1468
- if (!Availabilities.dateTimeFormat) {
1469
- onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));
1470
- return MISSING_RESOLVE_VALUE;
1471
- }
1472
- if (!isString(args[0]) && !isDate(args[0]) && !isNumber(args[0])) {
1473
- {
1474
- onWarn(getWarnMessage(CoreWarnCodes.INVALID_DATE_ARGUMENT, {
1475
- value: String(args[0])
1476
- }));
1477
- }
1478
- return MISSING_RESOLVE_VALUE;
1479
- }
1480
- const [key, value, options, overrides] = parseDateTimeArgs(...args);
1481
- const missingWarn = isBoolean(options.missingWarn)
1482
- ? options.missingWarn
1483
- : context.missingWarn;
1484
- const fallbackWarn = isBoolean(options.fallbackWarn)
1485
- ? options.fallbackWarn
1486
- : context.fallbackWarn;
1487
- const part = !!options.part;
1488
- const locale = getLocale(context, options);
1489
- if (!isString(key) || key === '') {
1490
- const formatter = new Intl.DateTimeFormat(locale.replace(/!/g, ''), overrides);
1491
- return !part ? formatter.format(value) : formatter.formatToParts(value);
1492
- }
1493
- const targetLocale = resolveFormatLocale(context, key, locale, datetimeFormats, missingWarn, fallbackWarn, 'datetime format');
1494
- if (!isString(targetLocale)) {
1495
- return unresolving ? NOT_REOSLVED : key;
1496
- }
1497
- const format = datetimeFormats[targetLocale][key];
1498
- const id = getFormatterCacheKey(targetLocale, key, overrides);
1499
- let formatter = __datetimeFormatters.get(id);
1500
- if (!formatter) {
1501
- formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
1502
- __datetimeFormatters.set(id, formatter);
1503
- }
1504
- return !part ? formatter.format(value) : formatter.formatToParts(value);
1262
+ const { datetimeFormats, onWarn } = context;
1263
+ const { __datetimeFormatters } = context;
1264
+ if (!Availabilities.dateTimeFormat) {
1265
+ onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));
1266
+ return "";
1267
+ }
1268
+ if (!isString(args[0]) && !isDate(args[0]) && !isNumber(args[0])) {
1269
+ onWarn(getWarnMessage(CoreWarnCodes.INVALID_DATE_ARGUMENT, { value: String(args[0]) }));
1270
+ return "";
1271
+ }
1272
+ return formatValue(context, parseDateTimeArgs(...args), Intl.DateTimeFormat, __datetimeFormatters, datetimeFormats, "datetime format");
1505
1273
  }
1506
1274
  /** @internal */
1507
1275
  const DATETIME_FORMAT_OPTIONS_KEYS = [
1508
- 'localeMatcher',
1509
- 'weekday',
1510
- 'era',
1511
- 'year',
1512
- 'month',
1513
- 'day',
1514
- 'hour',
1515
- 'minute',
1516
- 'second',
1517
- 'timeZoneName',
1518
- 'formatMatcher',
1519
- 'hour12',
1520
- 'timeZone',
1521
- 'dateStyle',
1522
- 'timeStyle',
1523
- 'calendar',
1524
- 'dayPeriod',
1525
- 'numberingSystem',
1526
- 'hourCycle',
1527
- 'fractionalSecondDigits'
1276
+ "localeMatcher",
1277
+ "weekday",
1278
+ "era",
1279
+ "year",
1280
+ "month",
1281
+ "day",
1282
+ "hour",
1283
+ "minute",
1284
+ "second",
1285
+ "timeZoneName",
1286
+ "formatMatcher",
1287
+ "hour12",
1288
+ "timeZone",
1289
+ "dateStyle",
1290
+ "timeStyle",
1291
+ "calendar",
1292
+ "dayPeriod",
1293
+ "numberingSystem",
1294
+ "hourCycle",
1295
+ "fractionalSecondDigits"
1528
1296
  ];
1529
1297
  /** @internal */
1530
1298
  function parseDateTimeArgs(...args) {
1531
- const [arg1] = args;
1532
- const options = create();
1533
- const initialOverrides = create();
1534
- let value;
1535
- if (isString(arg1)) {
1536
- // Only allow ISO strings - other date formats are often supported,
1537
- // but may cause different results in different browsers.
1538
- const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
1539
- if (!matches) {
1540
- throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1541
- }
1542
- // Some browsers can not parse the iso datetime separated by space,
1543
- // this is a compromise solution by replace the 'T'/' ' with 'T'
1544
- const dateTime = matches[3]
1545
- ? matches[3].trim().startsWith('T')
1546
- ? `${matches[1].trim()}${matches[3].trim()}`
1547
- : `${matches[1].trim()}T${matches[3].trim()}`
1548
- : matches[1].trim();
1549
- value = new Date(dateTime);
1550
- try {
1551
- // This will fail if the date is not valid
1552
- value.toISOString();
1553
- }
1554
- catch {
1555
- throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1556
- }
1557
- }
1558
- else if (isDate(arg1)) {
1559
- if (isNaN(arg1.getTime())) {
1560
- throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
1561
- }
1562
- value = arg1;
1563
- }
1564
- else if (isNumber(arg1)) {
1565
- value = arg1;
1566
- }
1567
- else {
1568
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1569
- }
1570
- const overrides = parseFormatArgs(args, options, initialOverrides, DATETIME_FORMAT_OPTIONS_KEYS);
1571
- return [options.key || '', value, options, overrides];
1299
+ const [arg1] = args;
1300
+ const options = create();
1301
+ const initialOverrides = create();
1302
+ let value;
1303
+ if (isString(arg1)) {
1304
+ const matches = arg1.match(/^(\d{4}-\d{2}-\d{2})(?:(T|\s)(.+))?$/);
1305
+ if (!matches) throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1306
+ const dateTime = matches[3] ? matches[3].trim().startsWith("T") ? `${matches[1].trim()}${matches[3].trim()}` : `${matches[1].trim()}T${matches[3].trim()}` : matches[1].trim();
1307
+ value = new Date(dateTime);
1308
+ try {
1309
+ value.toISOString();
1310
+ } catch {
1311
+ throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1312
+ }
1313
+ } else if (isDate(arg1)) {
1314
+ if (isNaN(arg1.getTime())) throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
1315
+ value = arg1;
1316
+ } else if (isNumber(arg1)) value = arg1;
1317
+ else throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1318
+ const overrides = parseFormatArgs(args, options, initialOverrides, DATETIME_FORMAT_OPTIONS_KEYS);
1319
+ return [
1320
+ options.key || "",
1321
+ value,
1322
+ options,
1323
+ overrides
1324
+ ];
1572
1325
  }
1573
1326
  /** @internal */
1574
1327
  function clearDateTimeFormat(ctx, locale, format) {
1575
- const context = ctx;
1576
- clearFormatCache(context.__datetimeFormatters, locale, format);
1328
+ clearFormatCache(ctx.__datetimeFormatters, locale, format);
1577
1329
  }
1578
-
1579
- // implementation of `number` function
1330
+ // packages/core-base/src/number.ts
1580
1331
  function number(context, ...args) {
1581
- const { numberFormats, unresolving, onWarn } = context;
1582
- const { __numberFormatters } = context;
1583
- if (!Availabilities.numberFormat) {
1584
- onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
1585
- return MISSING_RESOLVE_VALUE;
1586
- }
1587
- if (!isNumber(args[0])) {
1588
- {
1589
- onWarn(getWarnMessage(CoreWarnCodes.INVALID_NUMBER_ARGUMENT, {
1590
- value: String(args[0])
1591
- }));
1592
- }
1593
- return MISSING_RESOLVE_VALUE;
1594
- }
1595
- const [key, value, options, overrides] = parseNumberArgs(...args);
1596
- const missingWarn = isBoolean(options.missingWarn)
1597
- ? options.missingWarn
1598
- : context.missingWarn;
1599
- const fallbackWarn = isBoolean(options.fallbackWarn)
1600
- ? options.fallbackWarn
1601
- : context.fallbackWarn;
1602
- const part = !!options.part;
1603
- const locale = getLocale(context, options);
1604
- if (!isString(key) || key === '') {
1605
- const formatter = new Intl.NumberFormat(locale.replace(/!/g, ''), overrides);
1606
- return !part ? formatter.format(value) : formatter.formatToParts(value);
1607
- }
1608
- const targetLocale = resolveFormatLocale(context, key, locale, numberFormats, missingWarn, fallbackWarn, 'number format');
1609
- if (!isString(targetLocale)) {
1610
- return unresolving ? NOT_REOSLVED : key;
1611
- }
1612
- const format = numberFormats[targetLocale][key];
1613
- const id = getFormatterCacheKey(targetLocale, key, overrides);
1614
- let formatter = __numberFormatters.get(id);
1615
- if (!formatter) {
1616
- formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
1617
- __numberFormatters.set(id, formatter);
1618
- }
1619
- return !part ? formatter.format(value) : formatter.formatToParts(value);
1332
+ const { numberFormats, onWarn } = context;
1333
+ const { __numberFormatters } = context;
1334
+ if (!Availabilities.numberFormat) {
1335
+ onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
1336
+ return "";
1337
+ }
1338
+ if (!isNumber(args[0])) {
1339
+ onWarn(getWarnMessage(CoreWarnCodes.INVALID_NUMBER_ARGUMENT, { value: String(args[0]) }));
1340
+ return "";
1341
+ }
1342
+ return formatValue(context, parseNumberArgs(...args), Intl.NumberFormat, __numberFormatters, numberFormats, "number format");
1620
1343
  }
1621
1344
  /** @internal */
1622
1345
  const NUMBER_FORMAT_OPTIONS_KEYS = [
1623
- 'localeMatcher',
1624
- 'style',
1625
- 'currency',
1626
- 'currencyDisplay',
1627
- 'currencySign',
1628
- 'useGrouping',
1629
- 'minimumIntegerDigits',
1630
- 'minimumFractionDigits',
1631
- 'maximumFractionDigits',
1632
- 'minimumSignificantDigits',
1633
- 'maximumSignificantDigits',
1634
- 'compactDisplay',
1635
- 'notation',
1636
- 'signDisplay',
1637
- 'unit',
1638
- 'unitDisplay',
1639
- 'roundingMode',
1640
- 'roundingPriority',
1641
- 'roundingIncrement',
1642
- 'trailingZeroDisplay'
1346
+ "localeMatcher",
1347
+ "style",
1348
+ "currency",
1349
+ "currencyDisplay",
1350
+ "currencySign",
1351
+ "useGrouping",
1352
+ "minimumIntegerDigits",
1353
+ "minimumFractionDigits",
1354
+ "maximumFractionDigits",
1355
+ "minimumSignificantDigits",
1356
+ "maximumSignificantDigits",
1357
+ "compactDisplay",
1358
+ "notation",
1359
+ "signDisplay",
1360
+ "unit",
1361
+ "unitDisplay",
1362
+ "roundingMode",
1363
+ "roundingPriority",
1364
+ "roundingIncrement",
1365
+ "trailingZeroDisplay"
1643
1366
  ];
1644
1367
  /** @internal */
1645
1368
  function parseNumberArgs(...args) {
1646
- const [arg1] = args;
1647
- const options = create();
1648
- const initialOverrides = create();
1649
- if (!isNumber(arg1)) {
1650
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1651
- }
1652
- const value = arg1;
1653
- const overrides = parseFormatArgs(args, options, initialOverrides, NUMBER_FORMAT_OPTIONS_KEYS);
1654
- return [options.key || '', value, options, overrides];
1369
+ const [arg1] = args;
1370
+ const options = create();
1371
+ const initialOverrides = create();
1372
+ if (!isNumber(arg1)) throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1373
+ const value = arg1;
1374
+ const overrides = parseFormatArgs(args, options, initialOverrides, NUMBER_FORMAT_OPTIONS_KEYS);
1375
+ return [
1376
+ options.key || "",
1377
+ value,
1378
+ options,
1379
+ overrides
1380
+ ];
1655
1381
  }
1656
1382
  /** @internal */
1657
1383
  function clearNumberFormat(ctx, locale, format) {
1658
- const context = ctx;
1659
- clearFormatCache(context.__numberFormatters, locale, format);
1384
+ clearFormatCache(ctx.__numberFormatters, locale, format);
1660
1385
  }
1661
-
1386
+ // packages/core-base/src/runtime.ts
1662
1387
  const DEFAULT_MODIFIER = (str) => str;
1663
- const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
1664
- const DEFAULT_MESSAGE_DATA_TYPE = 'text';
1665
- const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : join(values);
1388
+ const DEFAULT_MESSAGE = (_ctx) => "";
1389
+ const DEFAULT_MESSAGE_DATA_TYPE = "text";
1390
+ const DEFAULT_NORMALIZE = (values) => values.length === 0 ? "" : join(values);
1666
1391
  const DEFAULT_INTERPOLATE = toDisplayString;
1667
1392
  function pluralDefault(choice, choicesLength) {
1668
- choice = Math.abs(choice);
1669
- // singular (0) | plural (1)
1670
- if (choicesLength === 2) {
1671
- // prettier-ignore
1672
- return choice === 1
1673
- ? 0
1674
- : 1;
1675
- }
1676
- // zero (0) | singular (1) | plural (2)
1677
- return Math.min(choice, 2);
1393
+ choice = Math.abs(choice);
1394
+ if (choicesLength === 2) return choice === 1 ? 0 : 1;
1395
+ return Math.min(choice, 2);
1396
+ }
1397
+ const PLURAL_CATEGORY_ORDER = [
1398
+ "zero",
1399
+ "one",
1400
+ "two",
1401
+ "few",
1402
+ "many",
1403
+ "other"
1404
+ ];
1405
+ const intlPluralRulesCache = /* @__PURE__ */ new Map();
1406
+ const INTL_PLURAL_RULES_CACHE_SIZE = 1e3;
1407
+ function createIntlPluralRules(locale) {
1408
+ try {
1409
+ if (Intl.PluralRules.supportedLocalesOf(locale).length === 0) return null;
1410
+ const rules = new Intl.PluralRules(locale);
1411
+ return {
1412
+ rules,
1413
+ categories: rules.resolvedOptions().pluralCategories.slice().sort((a, b) => PLURAL_CATEGORY_ORDER.indexOf(a) - PLURAL_CATEGORY_ORDER.indexOf(b))
1414
+ };
1415
+ } catch {
1416
+ return null;
1417
+ }
1418
+ }
1419
+ function getIntlPluralRules(locale) {
1420
+ let cached = intlPluralRulesCache.get(locale);
1421
+ if (cached === void 0) {
1422
+ cached = createIntlPluralRules(locale);
1423
+ if (cached === null) warn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_DEFAULT_PLURAL_RULE, { locale }));
1424
+ if (intlPluralRulesCache.size >= INTL_PLURAL_RULES_CACHE_SIZE) intlPluralRulesCache.delete(intlPluralRulesCache.keys().next().value);
1425
+ intlPluralRulesCache.set(locale, cached);
1426
+ }
1427
+ return cached;
1678
1428
  }
1679
1429
  function getPluralIndex(options) {
1680
- // prettier-ignore
1681
- const index = isNumber(options.pluralIndex)
1682
- ? options.pluralIndex
1683
- : -1;
1684
- return isNumber(options.named?.count)
1685
- ? options.named.count
1686
- : isNumber(options.named?.n)
1687
- ? options.named.n
1688
- : index;
1430
+ if (isNumber(options.pluralIndex)) return options.pluralIndex;
1431
+ return isNumber(options.named?.count) ? options.named.count : isNumber(options.named?.n) ? options.named.n : -1;
1689
1432
  }
1690
1433
  function createMessageContext(options = {}) {
1691
- const locale = options.locale;
1692
- const pluralIndex = getPluralIndex(options);
1693
- const pluralRule = isString(locale) &&
1694
- options.pluralRules &&
1695
- isFunction(getOwn(options.pluralRules, locale))
1696
- ? options.pluralRules[locale]
1697
- : pluralDefault;
1698
- const orgPluralRule = pluralRule === pluralDefault ? undefined : pluralDefault;
1699
- const plural = (messages) => messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
1700
- const _list = options.list || [];
1701
- const list = (index) => _list[index];
1702
- const _named = options.named || create(); // eslint-disable-line @typescript-eslint/no-explicit-any
1703
- // `count` and `n` are the implicit named values of a plural call. supply the
1704
- // plural index for them, without writing into the named values that the
1705
- // caller passed
1706
- const hasPluralIndex = isNumber(options.pluralIndex);
1707
- const named = (key) => {
1708
- // read only own properties for the names of Object.prototype properties,
1709
- // such as `toString`, so that the getters of class instances still work as
1710
- // named values
1711
- const value = isObjectPrototypeKey(key) ? getOwn(_named, key) : _named[key];
1712
- return hasPluralIndex && !value && (key === 'count' || key === 'n')
1713
- ? options.pluralIndex
1714
- : value;
1715
- };
1716
- function message(key, useLinked) {
1717
- // prettier-ignore
1718
- const msg = isFunction(options.messages)
1719
- ? options.messages(key, !!useLinked)
1720
- : isObject(options.messages)
1721
- ? options.messages[key]
1722
- : false;
1723
- return !msg
1724
- ? options.parent
1725
- ? options.parent.message(key) // resolve from parent messages
1726
- : DEFAULT_MESSAGE
1727
- : msg;
1728
- }
1729
- const _modifier = (name) => options.modifiers
1730
- ? getOwn(options.modifiers, name)
1731
- : DEFAULT_MODIFIER;
1732
- const normalize = isFunction(options.processor?.normalize)
1733
- ? options.processor.normalize
1734
- : DEFAULT_NORMALIZE;
1735
- const interpolate = isFunction(options.processor?.interpolate)
1736
- ? options.processor.interpolate
1737
- : DEFAULT_INTERPOLATE;
1738
- const type = isString(options.processor?.type)
1739
- ? options.processor.type
1740
- : DEFAULT_MESSAGE_DATA_TYPE;
1741
- const linked = (key, ...args) => {
1742
- const [arg1, arg2] = args;
1743
- let type = 'text';
1744
- let modifier = '';
1745
- if (args.length === 1) {
1746
- if (isObject(arg1)) {
1747
- modifier = arg1.modifier || modifier;
1748
- type = arg1.type || type;
1749
- }
1750
- else if (isString(arg1)) {
1751
- modifier = arg1 || modifier;
1752
- }
1753
- }
1754
- else if (args.length === 2) {
1755
- if (isString(arg1)) {
1756
- modifier = arg1 || modifier;
1757
- }
1758
- if (isString(arg2)) {
1759
- type = arg2 || type;
1760
- }
1761
- }
1762
- const ret = message(key, true)(ctx);
1763
- // If the linked message is not resolved (empty string), fall back to the key itself
1764
- const resolved = ret === '' || ret === undefined ? key : ret;
1765
- const msg =
1766
- // The message in vnode resolved with linked are returned as an array by processor.nomalize
1767
- type === 'vnode' && isArray(resolved) && modifier
1768
- ? resolved[0]
1769
- : resolved;
1770
- if (!modifier) {
1771
- return msg;
1772
- }
1773
- const modify = _modifier(modifier);
1774
- if (isFunction(modify)) {
1775
- return modify(msg, type);
1776
- }
1777
- // an unknown modifier, such as a typo, does not stop the translation
1778
- {
1779
- warnOnce(`Not found '${modifier}' modifier for the linked message of '${key}' key. ` +
1780
- `Use a built-in modifier, or set a custom modifier with 'modifiers' option. ` +
1781
- `So the linked message is used as is.`);
1782
- }
1783
- return msg;
1784
- };
1785
- const ctx = {
1786
- ["list" /* HelperNameMap.LIST */]: list,
1787
- ["named" /* HelperNameMap.NAMED */]: named,
1788
- ["plural" /* HelperNameMap.PLURAL */]: plural,
1789
- ["linked" /* HelperNameMap.LINKED */]: linked,
1790
- ["message" /* HelperNameMap.MESSAGE */]: message,
1791
- ["type" /* HelperNameMap.TYPE */]: type,
1792
- ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
1793
- ["normalize" /* HelperNameMap.NORMALIZE */]: normalize,
1794
- // custom message compilers read the values, so give them the same `count`
1795
- // and `n` as `named()`
1796
- ["values" /* HelperNameMap.VALUES */]: assign(create(), _list, _named, hasPluralIndex ? { count: named('count'), n: named('n') } : {})
1797
- };
1798
- return ctx;
1799
- }
1800
-
1801
- const NOOP_MESSAGE_FUNCTION = () => '';
1434
+ const locale = options.locale;
1435
+ const pluralIndex = getPluralIndex(options);
1436
+ let resolvedPluralRule;
1437
+ if (isString(locale) && options.pluralRules && isFunction(getOwn(options.pluralRules, locale))) resolvedPluralRule = options.pluralRules[locale];
1438
+ else if (isString(locale) && typeof Intl !== "undefined" && typeof Intl.PluralRules !== "undefined") resolvedPluralRule = (choice, choicesLength) => {
1439
+ const intlPluralRules = getIntlPluralRules(locale);
1440
+ if (intlPluralRules === null || choicesLength > intlPluralRules.categories.length) return pluralDefault(choice, choicesLength);
1441
+ const { rules, categories } = intlPluralRules;
1442
+ const category = rules.select(Math.abs(choice));
1443
+ const index = categories.indexOf(category);
1444
+ return Math.min(index === -1 ? choicesLength - 1 : index, choicesLength - 1);
1445
+ };
1446
+ else resolvedPluralRule = pluralDefault;
1447
+ const orgPluralRule = resolvedPluralRule === pluralDefault ? void 0 : pluralDefault;
1448
+ const plural = (messages) => messages[resolvedPluralRule(pluralIndex, messages.length, orgPluralRule)];
1449
+ const _list = options.list || [];
1450
+ const list = (index) => _list[index];
1451
+ const _named = options.named || create();
1452
+ const hasPluralIndex = isNumber(options.pluralIndex);
1453
+ const named = (key) => {
1454
+ const value = isObjectPrototypeKey(key) ? getOwn(_named, key) : _named[key];
1455
+ return hasPluralIndex && value == null && (key === "count" || key === "n") ? options.pluralIndex : value;
1456
+ };
1457
+ function message(key, useLinked) {
1458
+ const msg = isFunction(options.messages) ? options.messages(key, !!useLinked) : isObject(options.messages) ? options.messages[key] : false;
1459
+ return !msg ? options.parent ? options.parent.message(key) : DEFAULT_MESSAGE : msg;
1460
+ }
1461
+ const _modifier = (name) => options.modifiers ? getOwn(options.modifiers, name) : DEFAULT_MODIFIER;
1462
+ const normalize = isFunction(options.processor?.normalize) ? options.processor.normalize : DEFAULT_NORMALIZE;
1463
+ const interpolate = isFunction(options.processor?.interpolate) ? options.processor.interpolate : DEFAULT_INTERPOLATE;
1464
+ const type = isString(options.processor?.type) ? options.processor.type : DEFAULT_MESSAGE_DATA_TYPE;
1465
+ const linked = (key, ...args) => {
1466
+ const [arg1, arg2] = args;
1467
+ let type = "text";
1468
+ let modifier = "";
1469
+ if (args.length === 1) {
1470
+ if (isObject(arg1)) {
1471
+ modifier = arg1.modifier || modifier;
1472
+ type = arg1.type || type;
1473
+ } else if (isString(arg1)) modifier = arg1 || modifier;
1474
+ } else if (args.length === 2) {
1475
+ if (isString(arg1)) modifier = arg1 || modifier;
1476
+ if (isString(arg2)) type = arg2 || type;
1477
+ }
1478
+ const ret = message(key, true)(ctx);
1479
+ const resolved = ret === "" || ret === void 0 ? key : ret;
1480
+ const msg = type === "vnode" && isArray(resolved) && modifier ? resolved[0] : resolved;
1481
+ if (!modifier) return msg;
1482
+ const modify = _modifier(modifier);
1483
+ if (isFunction(modify)) return modify(msg, type);
1484
+ warnOnce(`Not found '${modifier}' modifier for the linked message of '${key}' key. Use a built-in modifier, or set a custom modifier with 'modifiers' option. So the linked message is used as is.`);
1485
+ return msg;
1486
+ };
1487
+ const ctx = {
1488
+ ["list"]: list,
1489
+ ["named"]: named,
1490
+ ["plural"]: plural,
1491
+ ["linked"]: linked,
1492
+ ["message"]: message,
1493
+ ["type"]: type,
1494
+ ["interpolate"]: interpolate,
1495
+ ["normalize"]: normalize,
1496
+ ["values"]: assign(create(), _list, _named, hasPluralIndex ? {
1497
+ count: named("count"),
1498
+ n: named("n")
1499
+ } : {})
1500
+ };
1501
+ return ctx;
1502
+ }
1503
+ // packages/core-base/src/translate.ts
1504
+ const NOOP_MESSAGE_FUNCTION = () => "";
1802
1505
  const isMessageFunction = (val) => isFunction(val);
1803
1506
  /** @internal */
1804
1507
  const isMessageFormat = (val) => isString(val) || isMessageAST(val) || isMessageFunction(val);
1805
- // implementation of `translate` function
1806
1508
  function translate(context, ...args) {
1807
- const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
1808
- const [key, options] = parseTranslateArgs(...args);
1809
- const missingWarn = isBoolean(options.missingWarn)
1810
- ? options.missingWarn
1811
- : context.missingWarn;
1812
- const fallbackWarn = isBoolean(options.fallbackWarn)
1813
- ? options.fallbackWarn
1814
- : context.fallbackWarn;
1815
- const escapeParameter = isBoolean(options.escapeParameter)
1816
- ? options.escapeParameter
1817
- : context.escapeParameter;
1818
- const resolvedMessage = !!options.resolvedMessage;
1819
- // prettier-ignore
1820
- const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
1821
- ? !isBoolean(options.default)
1822
- ? options.default
1823
- : (!messageCompiler ? () => key : key)
1824
- : fallbackFormat // default by `fallbackFormat` option
1825
- ? (!messageCompiler ? () => key : key)
1826
- : null;
1827
- const enableDefaultMsg = fallbackFormat ||
1828
- (defaultMsgOrKey != null &&
1829
- (isString(defaultMsgOrKey) || isFunction(defaultMsgOrKey)));
1830
- const locale = getLocale(context, options);
1831
- // escape params
1832
- escapeParameter && escapeParams(options);
1833
- // resolve message format
1834
- // eslint-disable-next-line prefer-const
1835
- let [formatScope, targetLocale, message] = !resolvedMessage
1836
- ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
1837
- : [key, locale, getOwn(messages, locale) || create()];
1838
- // NOTE:
1839
- // Fix to work around `ssrTransfrom` bug in Vite.
1840
- // https://github.com/vitejs/vite/issues/4306
1841
- // To get around this, use temporary variables.
1842
- // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
1843
- let format = formatScope;
1844
- // if you use default message, set it as message format!
1845
- let cacheBaseKey = key;
1846
- if (!resolvedMessage && !isMessageFormat(format)) {
1847
- if (enableDefaultMsg) {
1848
- format = defaultMsgOrKey;
1849
- cacheBaseKey = format;
1850
- }
1851
- }
1852
- // checking message format and target locale
1853
- if (!resolvedMessage &&
1854
- (!isMessageFormat(format) || !isString(targetLocale))) {
1855
- return unresolving ? NOT_REOSLVED : key;
1856
- }
1857
- // without a message compiler, `compileMessageFormat()` returns the message as is
1858
- if (isString(format) && context.messageCompiler == null) {
1859
- warn(`The message format compilation is not supported in this build. ` +
1860
- `Because message compiler isn't included. ` +
1861
- `You need to pre-compilation all message format. ` +
1862
- `So translate function returns the message as is.`);
1863
- }
1864
- // setup compile error detecting
1865
- let occurred = false;
1866
- const onError = () => {
1867
- occurred = true;
1868
- };
1869
- // compile message format
1870
- const msg = !isMessageFunction(format)
1871
- ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError)
1872
- : format;
1873
- // if occurred compile error, return the message format
1874
- if (occurred) {
1875
- return format;
1876
- }
1877
- // evaluate message with context
1878
- const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
1879
- const msgContext = createMessageContext(ctxOptions);
1880
- const messaged = evaluateMessage(context, msg, msgContext);
1881
- // if use post translation option, proceed it with handler
1882
- let ret = postTranslation
1883
- ? postTranslation(messaged, key)
1884
- : messaged;
1885
- // apply HTML sanitization for security
1886
- if (escapeParameter && isString(ret)) {
1887
- ret = sanitizeTranslatedHtml(ret);
1888
- }
1889
- // NOTE: experimental !!
1890
- {
1891
- // prettier-ignore
1892
- const payloads = {
1893
- timestamp: Date.now(),
1894
- key: isString(key)
1895
- ? key
1896
- : isMessageFunction(format)
1897
- ? format.key
1898
- : '',
1899
- locale: targetLocale || (isMessageFunction(format)
1900
- ? format.locale
1901
- : ''),
1902
- format: isString(format)
1903
- ? format
1904
- : isMessageFunction(format)
1905
- ? format.source
1906
- : '',
1907
- message: ret
1908
- };
1909
- payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
1910
- translateDevTools(payloads);
1911
- }
1912
- return ret;
1509
+ const [key, options] = parseTranslateArgs(...args);
1510
+ const locale = getLocale(context, options);
1511
+ const escapeParameter = isBoolean(options.escapeParameter) ? options.escapeParameter : context.escapeParameter;
1512
+ escapeParameter && escapeParams(options);
1513
+ const resolvedMessage = !!options.resolvedMessage;
1514
+ let [format, targetLocale, message] = !resolvedMessage ? resolveMessageFormat(context, key, locale, context.fallbackLocale, isBoolean(options.fallbackWarn) ? options.fallbackWarn : context.fallbackWarn, isBoolean(options.missingWarn) ? options.missingWarn : context.missingWarn) : [
1515
+ key,
1516
+ locale,
1517
+ getOwn(context.messages, locale) || create()
1518
+ ];
1519
+ let cacheBaseKey = key;
1520
+ if (!resolvedMessage && !isMessageFormat(format)) {
1521
+ const defaultMsgOrKey = isString(options.default) ? options.default : isBoolean(options.default) || context.fallbackFormat ? !context.messageCompiler ? () => key : key : null;
1522
+ if (context.fallbackFormat || defaultMsgOrKey != null && (isString(defaultMsgOrKey) || isFunction(defaultMsgOrKey))) {
1523
+ format = defaultMsgOrKey;
1524
+ cacheBaseKey = format;
1525
+ }
1526
+ }
1527
+ if (!resolvedMessage && (!isMessageFormat(format) || !isString(targetLocale))) return context.unresolving ? -1 : key;
1528
+ if (isString(format) && context.messageCompiler == null) warn(`Cannot compile the message of '${stringifyKey(key)}' key, because no message compiler is set. Use 'messageCompiler' option of 'createCoreContext', or pre-compile the message. So translate function returns the message as is.`);
1529
+ let occurred = false;
1530
+ const onError = () => {
1531
+ occurred = true;
1532
+ };
1533
+ const msg = !isMessageFunction(format) ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) : format;
1534
+ if (occurred) return format;
1535
+ const msgContext = createMessageContext(getMessageContextOptions(context, targetLocale, message, options));
1536
+ const timeline = startTimelineMeasure(context, "evaluation");
1537
+ const messaged = msg(msgContext);
1538
+ if (timeline) timeline.emitter.emit("message-evaluation", {
1539
+ type: "message-evaluation",
1540
+ value: messaged,
1541
+ time: endTimelineMeasure(timeline),
1542
+ groupId: toDevtoolsGroupId("translate", msg.key)
1543
+ });
1544
+ let ret = context.postTranslation ? context.postTranslation(messaged, key) : messaged;
1545
+ if (escapeParameter && isString(ret)) ret = sanitizeTranslatedHtml(ret);
1546
+ return ret;
1913
1547
  }
1914
1548
  function escapeParams(options) {
1915
- // a call can pass both list and named values, so escape each of them
1916
- if (isArray(options.list)) {
1917
- options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
1918
- }
1919
- if (isObject(options.named)) {
1920
- // escape into a new object, so that the values of the caller are not rewritten
1921
- const source = options.named;
1922
- const named = create();
1923
- for (const key of Object.keys(source)) {
1924
- const value = source[key];
1925
- named[key] = isString(value) ? escapeHtml(value) : value;
1926
- }
1927
- options.named = named;
1928
- }
1549
+ if (isArray(options.list)) options.list = options.list.map((item) => isString(item) ? escapeHtml(item) : item);
1550
+ if (isObject(options.named)) {
1551
+ const source = options.named;
1552
+ const named = create();
1553
+ for (const key of Object.keys(source)) {
1554
+ const value = source[key];
1555
+ named[key] = isString(value) ? escapeHtml(value) : value;
1556
+ }
1557
+ options.named = named;
1558
+ }
1929
1559
  }
1930
1560
  function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
1931
- const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
1932
- const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
1933
- let message = create();
1934
- let targetLocale;
1935
- let format = null;
1936
- let from = locale;
1937
- let to = null;
1938
- const type = 'translate';
1939
- for (let i = 0; i < locales.length; i++) {
1940
- targetLocale = to = locales[i];
1941
- if (locale !== targetLocale &&
1942
- !isAlmostSameLocale(locale, targetLocale) &&
1943
- isTranslateFallbackWarn(fallbackWarn, key)) {
1944
- onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
1945
- key,
1946
- target: targetLocale
1947
- }));
1948
- }
1949
- const emitter = context.__v_emitter
1950
- ;
1951
- // for vue-devtools timeline event
1952
- if (locale !== targetLocale) {
1953
- if (emitter) {
1954
- emitter.emit('fallback', {
1955
- type,
1956
- key,
1957
- from,
1958
- to,
1959
- groupId: toDevtoolsGroupId(type, key)
1960
- });
1961
- }
1962
- }
1963
- // read only own properties, so that a locale such as `constructor` does not
1964
- // read a built-in object
1965
- message = getOwn(messages, targetLocale) || create();
1966
- // for vue-devtools timeline event
1967
- let start = null;
1968
- let startTag;
1969
- let endTag;
1970
- if (inBrowser && emitter) {
1971
- start = window.performance.now();
1972
- startTag = 'intlify-message-resolve-start';
1973
- endTag = 'intlify-message-resolve-end';
1974
- mark && mark(startTag);
1975
- }
1976
- if ((format = resolveValue(message, key)) === null) {
1977
- // if null, resolve with object key path, from own properties only
1978
- format = getOwn(message, key);
1979
- }
1980
- // for vue-devtools timeline event
1981
- if (inBrowser && emitter) {
1982
- const end = window.performance.now();
1983
- if (emitter && start && format) {
1984
- emitter.emit('message-resolve', {
1985
- type: 'message-resolve',
1986
- key,
1987
- message: format,
1988
- time: end - start,
1989
- groupId: toDevtoolsGroupId(type, key)
1990
- });
1991
- }
1992
- if (startTag && endTag && mark && measure) {
1993
- mark(endTag);
1994
- measure('intlify message resolve', startTag, endTag);
1995
- }
1996
- }
1997
- if (isMessageFormat(format)) {
1998
- break;
1999
- }
2000
- if (!isImplicitFallback(targetLocale, locales)) {
2001
- const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
2002
- key, targetLocale, missingWarn, type);
2003
- if (missingRet !== key) {
2004
- format = missingRet;
2005
- }
2006
- }
2007
- from = to;
2008
- }
2009
- return [format, targetLocale, message];
1561
+ const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
1562
+ const locales = localeFallbacker(context, fallbackLocale, locale);
1563
+ let message = create();
1564
+ let targetLocale;
1565
+ let format = null;
1566
+ let from = locale;
1567
+ const type = "translate";
1568
+ for (let i = 0; i < locales.length; i++) {
1569
+ targetLocale = locales[i];
1570
+ if (locale !== targetLocale && !isAlmostSameLocale(locale, targetLocale) && isTranslateFallbackWarn(fallbackWarn, key)) onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
1571
+ key,
1572
+ target: targetLocale
1573
+ }));
1574
+ if (locale !== targetLocale) {
1575
+ const emitter = context.__v_emitter;
1576
+ if (emitter) emitter.emit("fallback", {
1577
+ type,
1578
+ key,
1579
+ from,
1580
+ to: targetLocale,
1581
+ groupId: toDevtoolsGroupId(type, key)
1582
+ });
1583
+ }
1584
+ message = getOwn(messages, targetLocale) || create();
1585
+ const timeline = startTimelineMeasure(context, "resolve");
1586
+ if ((format = resolveValue(message, key)) === null) format = getOwn(message, key);
1587
+ if (timeline) {
1588
+ const time = endTimelineMeasure(timeline);
1589
+ if (format) timeline.emitter.emit("message-resolve", {
1590
+ type: "message-resolve",
1591
+ key,
1592
+ message: format,
1593
+ time,
1594
+ groupId: toDevtoolsGroupId(type, key)
1595
+ });
1596
+ }
1597
+ if (isMessageFormat(format)) break;
1598
+ if (!isImplicitFallback(targetLocale, locales)) {
1599
+ const missingRet = handleMissing(context, key, targetLocale, missingWarn, type);
1600
+ if (missingRet !== key) format = missingRet;
1601
+ }
1602
+ from = targetLocale;
1603
+ }
1604
+ return [
1605
+ format,
1606
+ targetLocale,
1607
+ message
1608
+ ];
1609
+ }
1610
+ function stringifyKey(key) {
1611
+ return isString(key) ? key : isObject(key) ? JSON.stringify(key) : isFunction(key) ? key.name || "function" : "";
2010
1612
  }
2011
1613
  function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) {
2012
- const { messageCompiler, warnHtmlMessage } = context;
2013
- if (isMessageFunction(format)) {
2014
- const msg = format;
2015
- msg.locale = msg.locale || targetLocale;
2016
- msg.key = msg.key || key;
2017
- return msg;
2018
- }
2019
- if (messageCompiler == null) {
2020
- const msg = (() => format);
2021
- msg.locale = targetLocale;
2022
- msg.key = key;
2023
- return msg;
2024
- }
2025
- // for vue-devtools timeline event
2026
- const emitter = context.__v_emitter
2027
- ;
2028
- let start = null;
2029
- let startTag;
2030
- let endTag;
2031
- if (inBrowser && emitter) {
2032
- start = window.performance.now();
2033
- startTag = 'intlify-message-compilation-start';
2034
- endTag = 'intlify-message-compilation-end';
2035
- mark && mark(startTag);
2036
- }
2037
- const msg = messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, onError));
2038
- // for vue-devtools timeline event
2039
- if (inBrowser && emitter) {
2040
- const end = window.performance.now();
2041
- if (emitter && start) {
2042
- emitter.emit('message-compilation', {
2043
- type: 'message-compilation',
2044
- message: format,
2045
- time: end - start,
2046
- groupId: toDevtoolsGroupId('translate', key)
2047
- });
2048
- }
2049
- if (startTag && endTag && mark && measure) {
2050
- mark(endTag);
2051
- measure('intlify message compilation', startTag, endTag);
2052
- }
2053
- }
2054
- msg.locale = targetLocale;
2055
- msg.key = key;
2056
- msg.source = format;
2057
- return msg;
2058
- }
2059
- function evaluateMessage(context, msg, msgCtx) {
2060
- // for vue-devtools timeline event
2061
- const emitter = context.__v_emitter
2062
- ;
2063
- let start = null;
2064
- let startTag;
2065
- let endTag;
2066
- if (inBrowser && emitter) {
2067
- start = window.performance.now();
2068
- startTag = 'intlify-message-evaluation-start';
2069
- endTag = 'intlify-message-evaluation-end';
2070
- mark && mark(startTag);
2071
- }
2072
- const messaged = msg(msgCtx);
2073
- // for vue-devtools timeline event
2074
- if (inBrowser && emitter) {
2075
- const end = window.performance.now();
2076
- if (emitter && start) {
2077
- emitter.emit('message-evaluation', {
2078
- type: 'message-evaluation',
2079
- value: messaged,
2080
- time: end - start,
2081
- groupId: toDevtoolsGroupId('translate', msg.key)
2082
- });
2083
- }
2084
- if (startTag && endTag && mark && measure) {
2085
- mark(endTag);
2086
- measure('intlify message evaluation', startTag, endTag);
2087
- }
2088
- }
2089
- return messaged;
1614
+ if (isMessageFunction(format)) {
1615
+ const msg = format;
1616
+ msg.locale = msg.locale || targetLocale;
1617
+ msg.key = msg.key || key;
1618
+ return msg;
1619
+ }
1620
+ if (context.messageCompiler == null) {
1621
+ const msg = (() => format);
1622
+ msg.locale = targetLocale;
1623
+ msg.key = key;
1624
+ return msg;
1625
+ }
1626
+ const timeline = startTimelineMeasure(context, "compilation");
1627
+ const msg = context.messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, context.warnHtmlMessage, onError));
1628
+ if (timeline) timeline.emitter.emit("message-compilation", {
1629
+ type: "message-compilation",
1630
+ message: format,
1631
+ time: endTimelineMeasure(timeline),
1632
+ groupId: toDevtoolsGroupId("translate", key)
1633
+ });
1634
+ msg.locale = targetLocale;
1635
+ msg.key = key;
1636
+ msg.source = format;
1637
+ return msg;
1638
+ }
1639
+ function startTimelineMeasure(context, name) {
1640
+ const emitter = context.__v_emitter;
1641
+ if (!inBrowser || !emitter) return null;
1642
+ const start = window.performance.now();
1643
+ mark?.(`intlify-message-${name}-start`);
1644
+ return {
1645
+ emitter,
1646
+ name,
1647
+ start
1648
+ };
1649
+ }
1650
+ function endTimelineMeasure({ name, start }) {
1651
+ const time = window.performance.now() - start;
1652
+ if (mark && measure) {
1653
+ const startTag = `intlify-message-${name}-start`;
1654
+ const endTag = `intlify-message-${name}-end`;
1655
+ mark(endTag);
1656
+ measure(`intlify message ${name}`, startTag, endTag);
1657
+ }
1658
+ return time;
2090
1659
  }
2091
1660
  /** @internal */
2092
1661
  function parseTranslateArgs(...args) {
2093
- const [arg1, arg2, arg3] = args;
2094
- const options = create();
2095
- if (!isString(arg1) &&
2096
- !isNumber(arg1) &&
2097
- !isMessageFunction(arg1) &&
2098
- !isMessageAST(arg1)) {
2099
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
2100
- }
2101
- // prettier-ignore
2102
- const key = isNumber(arg1)
2103
- ? String(arg1)
2104
- : isMessageFunction(arg1)
2105
- ? arg1
2106
- : arg1;
2107
- if (isNumber(arg2)) {
2108
- options.plural = arg2;
2109
- }
2110
- else if (isString(arg2)) {
2111
- options.default = arg2;
2112
- }
2113
- else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
2114
- options.named = arg2;
2115
- }
2116
- else if (isArray(arg2)) {
2117
- options.list = arg2;
2118
- }
2119
- if (isNumber(arg3)) {
2120
- options.plural = arg3;
2121
- }
2122
- else if (isString(arg3)) {
2123
- options.default = arg3;
2124
- }
2125
- else if (isPlainObject(arg3)) {
2126
- assign(options, arg3);
2127
- }
2128
- return [key, options];
1662
+ const [arg1, arg2, arg3] = args;
1663
+ if (!isString(arg1) && !isNumber(arg1) && !isMessageFunction(arg1) && !isMessageAST(arg1)) throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1664
+ const key = isNumber(arg1) ? String(arg1) : isMessageFunction(arg1) ? arg1 : arg1;
1665
+ const options = create();
1666
+ if (isNumber(arg2)) options.plural = arg2;
1667
+ else if (isString(arg2)) options.default = arg2;
1668
+ else if (isPlainObject(arg2) && !isKeylessObject(arg2)) options.named = arg2;
1669
+ else if (isArray(arg2)) options.list = arg2;
1670
+ if (isNumber(arg3)) options.plural = arg3;
1671
+ else if (isString(arg3)) options.default = arg3;
1672
+ else if (isPlainObject(arg3)) assign(options, arg3);
1673
+ return [key, options];
2129
1674
  }
2130
1675
  function getCompileContext(context, locale, key, source, warnHtmlMessage, onError) {
2131
- return {
2132
- locale,
2133
- key,
2134
- warnHtmlMessage,
2135
- onError: (err) => {
2136
- onError && onError(err);
2137
- {
2138
- const _source = getSourceForCodeFrame(source);
2139
- const codeFrame = err.location &&
2140
- _source &&
2141
- generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);
2142
- const emitter = context.__v_emitter;
2143
- if (emitter && _source) {
2144
- emitter.emit('compile-error', {
2145
- message: _source,
2146
- error: err.message,
2147
- start: err.location && err.location.start.offset,
2148
- end: err.location && err.location.end.offset,
2149
- groupId: toDevtoolsGroupId('translate', key)
2150
- });
2151
- }
2152
- const message = `Message compilation error: ${err.message}`;
2153
- throw new SyntaxError(codeFrame ? `${message}\n${codeFrame}` : message);
2154
- }
2155
- },
2156
- onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
2157
- };
1676
+ return {
1677
+ locale,
1678
+ key,
1679
+ warnHtmlMessage,
1680
+ onError: (err) => {
1681
+ onError?.(err);
1682
+ {
1683
+ const _source = getSourceForCodeFrame(source);
1684
+ const codeFrame = err.location && _source && generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);
1685
+ const emitter = context.__v_emitter;
1686
+ if (emitter && _source) emitter.emit("compile-error", {
1687
+ message: _source,
1688
+ error: err.message,
1689
+ start: err.location && err.location.start.offset,
1690
+ end: err.location && err.location.end.offset,
1691
+ groupId: toDevtoolsGroupId("translate", key)
1692
+ });
1693
+ const message = `Message compilation error: ${err.message}`;
1694
+ throw new SyntaxError(codeFrame ? `${message}\n${codeFrame}` : message);
1695
+ }
1696
+ },
1697
+ onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
1698
+ };
2158
1699
  }
2159
1700
  function getSourceForCodeFrame(source) {
2160
- if (isString(source)) {
2161
- return source;
2162
- }
2163
- else {
2164
- if (source.loc && source.loc.source) {
2165
- return source.loc.source;
2166
- }
2167
- }
1701
+ if (isString(source)) return source;
1702
+ else if (source.loc?.source) return source.loc.source;
2168
1703
  }
2169
1704
  function getMessageContextOptions(context, locale, message, options) {
2170
- const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
2171
- const resolveMessage = (key, useLinked) => {
2172
- let val = resolveValue(message, key);
2173
- // fallback
2174
- if (val == null && (fallbackContext || useLinked)) {
2175
- const [format, , message] = resolveMessageFormat(fallbackContext || context, // NOTE: if has fallbackContext, fallback to root, else if use linked, fallback to local context
2176
- key, locale, fallbackLocale, fallbackWarn, missingWarn);
2177
- val = format ?? resolveValue(message, key);
2178
- }
2179
- if (isString(val) || isMessageAST(val)) {
2180
- let occurred = false;
2181
- const onError = () => {
2182
- occurred = true;
2183
- };
2184
- const msg = compileMessageFormat(context, key, locale, val, key, onError);
2185
- return !occurred
2186
- ? msg
2187
- : NOOP_MESSAGE_FUNCTION;
2188
- }
2189
- else if (isMessageFunction(val)) {
2190
- return val;
2191
- }
2192
- else {
2193
- // TODO: should be implemented warning message
2194
- return NOOP_MESSAGE_FUNCTION;
2195
- }
2196
- };
2197
- const ctxOptions = {
2198
- locale,
2199
- modifiers,
2200
- pluralRules,
2201
- messages: resolveMessage
2202
- };
2203
- if (context.processor) {
2204
- ctxOptions.processor = context.processor;
2205
- }
2206
- if (options.list) {
2207
- ctxOptions.list = options.list;
2208
- }
2209
- if (options.named) {
2210
- ctxOptions.named = options.named;
2211
- }
2212
- if (isNumber(options.plural)) {
2213
- ctxOptions.pluralIndex = options.plural;
2214
- }
2215
- return ctxOptions;
2216
- }
2217
-
2218
- // register message compiler for jit compilation
2219
- registerMessageCompiler(compile);
2220
- // register message resolver at @intlify/core
2221
- registerMessageResolver(resolveValue);
2222
- // register fallback locale at @intlify/core
2223
- registerLocaleFallbacker(fallbackWithLocaleChain);
2224
-
2225
- export { AST_NODE_PROPS_KEYS, CORE_ERROR_CODES_EXTEND_POINT, CORE_WARN_CODES_EXTEND_POINT, CompileErrorCodes, CoreErrorCodes, CoreWarnCodes, DATETIME_FORMAT_OPTIONS_KEYS, DEFAULT_LOCALE, DEFAULT_MESSAGE_DATA_TYPE, MISSING_RESOLVE_VALUE, NOT_REOSLVED, NUMBER_FORMAT_OPTIONS_KEYS, VERSION, clearCompileCache, clearDateTimeFormat, clearNumberFormat, compile, createCompileError, createCoreContext, createCoreError, createMessageContext, datetime, fallbackWithLocaleChain, fallbackWithSimple, getAdditionalMeta, getDevToolsHook, getFallbackContext, getLocale, getWarnMessage, handleMissing, initI18nDevTools, isAlmostSameLocale, isImplicitFallback, isMessageAST, isMessageFormat, isMessageFunction, isTranslateFallbackWarn, isTranslateMissingWarn, number, parse, parseDateTimeArgs, parseNumberArgs, parseTranslateArgs, registerLocaleFallbacker, registerMessageCompiler, registerMessageResolver, resolveLocale, resolveValue, resolveWithKeyValue, setAdditionalMeta, setDevToolsHook, setFallbackContext, translate, translateDevTools, updateFallbackLocale };
1705
+ const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
1706
+ const resolveMessage = (key, useLinked) => {
1707
+ let val = resolveValue(message, key);
1708
+ if (val == null && (fallbackContext || useLinked)) {
1709
+ const [format, , message] = resolveMessageFormat(fallbackContext || context, key, locale, fallbackLocale, fallbackWarn, missingWarn);
1710
+ val = format ?? resolveValue(message, key);
1711
+ }
1712
+ if (isString(val) || isMessageAST(val)) {
1713
+ let occurred = false;
1714
+ const onError = () => {
1715
+ occurred = true;
1716
+ };
1717
+ const msg = compileMessageFormat(context, key, locale, val, key, onError);
1718
+ return !occurred ? msg : NOOP_MESSAGE_FUNCTION;
1719
+ } else if (isMessageFunction(val)) return val;
1720
+ else return NOOP_MESSAGE_FUNCTION;
1721
+ };
1722
+ return {
1723
+ locale,
1724
+ modifiers,
1725
+ pluralRules,
1726
+ messages: resolveMessage,
1727
+ processor: context.processor ?? void 0,
1728
+ list: options.list ?? void 0,
1729
+ named: options.named ?? void 0,
1730
+ pluralIndex: isNumber(options.plural) ? options.plural : void 0
1731
+ };
1732
+ }
1733
+ export { AST_NODE_PROPS_KEYS, CORE_ERROR_CODES_EXTEND_POINT, CORE_WARN_CODES_EXTEND_POINT, CoreWarnCodes, DATETIME_FORMAT_OPTIONS_KEYS, DEFAULT_LOCALE, DEFAULT_MESSAGE_DATA_TYPE, MISSING_RESOLVE_VALUE, NOT_RESOLVED, NUMBER_FORMAT_OPTIONS_KEYS, VERSION, clearCompileCache, clearDateTimeFormat, clearNumberFormat, compile, createCompileError, createCoreContext, createCoreError, createMessageContext, datetime, fallbackWithLocaleChain, fallbackWithSimple, getLocale, getLocaleMessage, getWarnMessage, handleMissing, isAlmostSameLocale, isFallbackLocale, isImplicitFallback, isMessageAST, isMessageFormat, isMessageFunction, isTranslateFallbackWarn, isTranslateMissingWarn, isWarnOption, number, parse, parseDateTimeArgs, parseNumberArgs, parseTranslateArgs, registerLocaleFallbacker, registerMessageCompiler, registerMessageResolver, resolveLocale, resolveValue, resolveWithKeyValue, setLocaleMessage, translate, updateFallbackLocale };