react-smart-copy 1.21.0 → 1.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +67 -0
  2. package/dist/chunks/digits-BUEvSVrs.cjs +51 -0
  3. package/dist/chunks/digits-BUEvSVrs.cjs.map +1 -0
  4. package/dist/chunks/digits-DkU-O9_A.js +46 -0
  5. package/dist/chunks/digits-DkU-O9_A.js.map +1 -0
  6. package/dist/chunks/field-BHo5y-t_.js +535 -0
  7. package/dist/chunks/field-BHo5y-t_.js.map +1 -0
  8. package/dist/chunks/field-BTsKTs2M.d.cts +87 -0
  9. package/dist/chunks/field-BTsKTs2M.d.ts +87 -0
  10. package/dist/chunks/field-Bytz2WfN.cjs +558 -0
  11. package/dist/chunks/field-Bytz2WfN.cjs.map +1 -0
  12. package/dist/chunks/{text-field-Ba8W3v4R.cjs → text-field-BEzUVOag.cjs} +26 -5
  13. package/dist/chunks/text-field-BEzUVOag.cjs.map +1 -0
  14. package/dist/chunks/{text-field-DUvrMMaK.js → text-field-D7PF2WlX.js} +21 -6
  15. package/dist/chunks/text-field-D7PF2WlX.js.map +1 -0
  16. package/dist/code.cjs +1 -1
  17. package/dist/code.js +1 -1
  18. package/dist/color.cjs +1 -1
  19. package/dist/color.js +1 -1
  20. package/dist/index.cjs +89 -0
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.cts +42 -1
  23. package/dist/index.d.ts +42 -1
  24. package/dist/index.js +89 -1
  25. package/dist/index.js.map +1 -1
  26. package/dist/link.cjs +1 -1
  27. package/dist/link.js +1 -1
  28. package/dist/markdown.cjs +1 -1
  29. package/dist/markdown.js +1 -1
  30. package/dist/number.cjs +442 -0
  31. package/dist/number.cjs.map +1 -0
  32. package/dist/number.d.cts +172 -0
  33. package/dist/number.d.ts +172 -0
  34. package/dist/number.js +436 -0
  35. package/dist/number.js.map +1 -0
  36. package/dist/otp.cjs +7 -0
  37. package/dist/otp.d.cts +54 -0
  38. package/dist/otp.d.ts +54 -0
  39. package/dist/otp.js +2 -0
  40. package/dist/secrets.cjs +1 -1
  41. package/dist/secrets.js +1 -1
  42. package/package.json +71 -3
  43. package/dist/chunks/text-field-Ba8W3v4R.cjs.map +0 -1
  44. package/dist/chunks/text-field-DUvrMMaK.js.map +0 -1
package/dist/number.js ADDED
@@ -0,0 +1,436 @@
1
+
2
+ import { n as copyFailure } from "./chunks/errors-9h8sdFFX.js";
3
+ import { t as asciiDigits } from "./chunks/digits-DkU-O9_A.js";
4
+ import { n as insertText, r as replaceFieldValue, t as asTextField } from "./chunks/text-field-D7PF2WlX.js";
5
+ //#region src/number/currency.ts
6
+ /** Longest first, so `US$` is read before `$` and `Rs.` before `Rs`. */
7
+ const BY_LENGTH = [...[
8
+ ["US$", "USD"],
9
+ ["CA$", "CAD"],
10
+ ["C$", "CAD"],
11
+ ["AU$", "AUD"],
12
+ ["A$", "AUD"],
13
+ ["NZ$", "NZD"],
14
+ ["HK$", "HKD"],
15
+ ["S$", "SGD"],
16
+ ["R$", "BRL"],
17
+ ["MX$", "MXN"],
18
+ ["NT$", "TWD"],
19
+ ["$", null],
20
+ ["€", "EUR"],
21
+ ["£", "GBP"],
22
+ ["JP¥", "JPY"],
23
+ ["CN¥", "CNY"],
24
+ ["¥", null],
25
+ ["₹", "INR"],
26
+ ["Rs.", null],
27
+ ["Rs", null],
28
+ ["₩", "KRW"],
29
+ ["₽", "RUB"],
30
+ ["₺", "TRY"],
31
+ ["₪", "ILS"],
32
+ ["₫", "VND"],
33
+ ["₱", "PHP"],
34
+ ["฿", "THB"],
35
+ ["₴", "UAH"],
36
+ ["₦", "NGN"],
37
+ ["₸", "KZT"],
38
+ ["৳", "BDT"],
39
+ ["zł", "PLN"],
40
+ ["Kč", "CZK"],
41
+ ["kr.", null],
42
+ ["kr", null],
43
+ ["Fr.", "CHF"]
44
+ ]].sort((a, b) => b[0].length - a[0].length).map(([symbol, code]) => [
45
+ symbol,
46
+ symbol.toLowerCase(),
47
+ code
48
+ ]);
49
+ let codes;
50
+ /** Whether `code` (upper case) is an ISO 4217 code the runtime knows; any three letters where it can't say. */
51
+ function isCurrencyCode(code) {
52
+ if (codes === void 0) {
53
+ const supported = Intl.supportedValuesOf;
54
+ codes = typeof supported === "function" ? new Set(supported("currency")) : null;
55
+ }
56
+ return /^[A-Z]{3}$/.test(code) && (codes === null || codes.has(code));
57
+ }
58
+ const LETTER = /\p{L}/u;
59
+ /**
60
+ * The currency at the start of `text`, and how many characters it takes. A symbol or code
61
+ * made of letters must end there: `Rs` is not read from `Rsx`, nor `USD` from `USDT`.
62
+ */
63
+ function readCurrency(text) {
64
+ const lower = text.toLowerCase();
65
+ for (const [symbol, key, code] of BY_LENGTH) if (lower.startsWith(key) && !(LETTER.test(symbol.slice(-1)) && LETTER.test(text.charAt(key.length)))) return {
66
+ currency: {
67
+ symbol,
68
+ code
69
+ },
70
+ length: key.length
71
+ };
72
+ const word = /^\p{L}+/u.exec(text)?.[0] ?? "";
73
+ const code = word.toUpperCase();
74
+ return word.length === 3 && isCurrencyCode(code) ? {
75
+ currency: {
76
+ symbol: code,
77
+ code
78
+ },
79
+ length: 3
80
+ } : null;
81
+ }
82
+ //#endregion
83
+ //#region src/number/locale.ts
84
+ const cache = /* @__PURE__ */ new Map();
85
+ const CACHE_SIZE = 32;
86
+ /**
87
+ * How `locale` writes numbers, from `Intl.NumberFormat`.
88
+ *
89
+ * @throws {CopyFailure} `invalid-payload` for a string that is not a locale.
90
+ */
91
+ function numberSymbols(locale) {
92
+ const cached = cache.get(locale);
93
+ if (cached !== void 0) return cached;
94
+ let parts;
95
+ try {
96
+ parts = new Intl.NumberFormat(locale, { numberingSystem: "latn" }).formatToParts(123456789012.5);
97
+ } catch (cause) {
98
+ throw copyFailure("invalid-payload", `"${locale}" is not a locale.`, cause);
99
+ }
100
+ const integers = parts.filter((part) => part.type === "integer").map((part) => part.value.length);
101
+ const symbols = {
102
+ decimal: parts.some((part) => part.type === "decimal" && part.value === ",") ? "," : ".",
103
+ group: parts.find((part) => part.type === "group")?.value ?? "",
104
+ primary: Number(integers[integers.length - 1]),
105
+ secondary: Number(integers[Math.max(0, integers.length - 2)])
106
+ };
107
+ if (cache.size >= CACHE_SIZE) cache.clear();
108
+ cache.set(locale, symbols);
109
+ return symbols;
110
+ }
111
+ //#endregion
112
+ //#region src/number/parse.ts
113
+ /** Longer text holds more than a number: it is not read at all. */
114
+ const NUMBER_MAX_LENGTH = 256;
115
+ /** Group separators that are never decimal separators: spaces and apostrophes. */
116
+ const GROUP_ONLY = /* @__PURE__ */ new Set([" ", "'"]);
117
+ /** The largest exponent read from scientific notation, past which no number is finite. */
118
+ const MAX_EXPONENT = 400;
119
+ /**
120
+ * Reads the signs, brackets, currency and percent on one side of the number. Returns
121
+ * `false` when something else is there, or when one of them appears twice.
122
+ */
123
+ function readAdornments(text, into, side) {
124
+ let rest = text;
125
+ for (;;) {
126
+ rest = rest.trimStart();
127
+ if (rest === "") return true;
128
+ const char = rest.charAt(0);
129
+ let length = 1;
130
+ if (char === "(" && side === "prefix" && !into.open) into.open = true;
131
+ else if (char === ")" && side === "suffix" && !into.close) into.close = true;
132
+ else if ((char === "-" || char === "+" && side === "prefix") && into.sign === "") into.sign = char;
133
+ else if ((char === "%" || char === "‰") && into.kind === "number") into.kind = char === "%" ? "percent" : "permille";
134
+ else {
135
+ const read = into.currency === null ? readCurrency(rest) : null;
136
+ if (read === null) return false;
137
+ into.currency = read.currency;
138
+ length = read.length;
139
+ }
140
+ rest = rest.slice(length);
141
+ }
142
+ }
143
+ /** The text in a form the reader understands: ASCII digits, one minus, one apostrophe, plain spaces. */
144
+ function normalize(text) {
145
+ return asciiDigits(text).replace(/[\u2212\u2012\u2013]/g, "-").replace(/\u066A/g, "%").replace(/[\u2019\u02BC\u066C]/g, "'").replace(/\s/g, " ");
146
+ }
147
+ /** Whether `groups` (the integer part, split at its group separator) are grouped the way locales group. */
148
+ function validGroups(groups) {
149
+ const [first, ...rest] = groups;
150
+ if (first === void 0 || first === "" || first.length > 3 || rest.length === 0) return false;
151
+ if (rest.every((group) => group.length === 3)) return true;
152
+ return first.length <= 2 && rest.slice(0, -1).every((group) => group.length === 2) && rest[rest.length - 1]?.length === 3;
153
+ }
154
+ /** The integer and fractional digits of `text` (digits and separators only), or `null`. */
155
+ function readMantissa(text, decimalOfLocale, arabicDecimal) {
156
+ const separators = text.replace(/\d/g, "");
157
+ if (separators === "") return {
158
+ integer: text,
159
+ fraction: "",
160
+ ambiguous: false
161
+ };
162
+ const candidate = arabicDecimal ? "." : separators.charAt(separators.length - 1);
163
+ const once = separators.split(candidate).length === 2;
164
+ if (arabicDecimal && !once) return null;
165
+ let decimal = null;
166
+ let ambiguous = false;
167
+ if (once && !GROUP_ONLY.has(candidate)) {
168
+ const at = text.lastIndexOf(candidate);
169
+ const before = text.slice(0, at);
170
+ if (arabicDecimal || separators.length > 1 || text.length - at - 1 !== 3 || before === "" || before.length > 3 || before.startsWith("0")) decimal = candidate;
171
+ else {
172
+ ambiguous = true;
173
+ decimal = candidate === decimalOfLocale ? candidate : null;
174
+ }
175
+ }
176
+ const at = decimal === null ? text.length : text.lastIndexOf(decimal);
177
+ const integerPart = text.slice(0, at);
178
+ const fraction = text.slice(at + 1);
179
+ if (!/^\d*$/.test(fraction)) return null;
180
+ const groupSeparators = integerPart.replace(/\d/g, "");
181
+ if (groupSeparators === "") return {
182
+ integer: integerPart,
183
+ fraction,
184
+ ambiguous
185
+ };
186
+ const group = groupSeparators.charAt(0);
187
+ if (groupSeparators !== group.repeat(groupSeparators.length) || !validGroups(integerPart.split(group))) return null;
188
+ return {
189
+ integer: integerPart.split(group).join(""),
190
+ fraction,
191
+ ambiguous
192
+ };
193
+ }
194
+ /** `integer.fraction` times ten to the `exponent`, as an exact decimal string without a sign. */
195
+ function shift(integer, fraction, exponent) {
196
+ const digits = integer + fraction;
197
+ const point = integer.length + exponent;
198
+ let whole;
199
+ let decimals;
200
+ if (exponent === 0) [whole, decimals] = [integer, fraction];
201
+ else if (point <= 0) [whole, decimals] = ["0", "0".repeat(-point) + digits];
202
+ else if (point >= digits.length) [whole, decimals] = [digits + "0".repeat(point - digits.length), ""];
203
+ else [whole, decimals] = [digits.slice(0, point), digits.slice(point)];
204
+ if (exponent !== 0) decimals = decimals.replace(/0+$/, "");
205
+ whole = whole.replace(/^0+(?=\d)/, "");
206
+ return decimals === "" ? whole : `${whole}.${decimals}`;
207
+ }
208
+ /**
209
+ * Reads a number the way people paste one: from a spreadsheet, a bank statement, an invoice
210
+ * or a web page, in any locale's format. The whole text must be one number, with at most a
211
+ * sign, a currency and a percent sign around it; anything else gives `null`.
212
+ *
213
+ * - Group separators `,` `.` `'` and spaces (no-break and narrow ones too), in groups of
214
+ * three or the lakh and crore grouping (`12,34,567`). Wrong grouping gives `null`.
215
+ * - The decimal separator is whichever of `,` and `.` the text shows is one (`1.234,5`,
216
+ * `1,5`, `0.500`); only a lone separator before three digits (`1,234`) is settled by `locale`.
217
+ * - `-`, `+`, `\u2212`, a trailing minus (`1234-`) and accounting brackets (`(1,234)`).
218
+ * - Currency symbols and ISO codes, before or after: `$`, `\u20AC`, `R$`, `kr`, `USD`, `CHF`.
219
+ * - `%` and `\u2030`, before or after; scientific notation (`1.5E-7`).
220
+ * - Digits of any script, full-width characters, and Arabic separators.
221
+ *
222
+ * @throws {CopyFailure} `invalid-payload` for a `locale` that is not one.
223
+ * @example
224
+ * parseNumber('1.234,50 \u20AC', { locale: 'de-DE' });
225
+ * // { value: 1234.5, exact: '1234.50', kind: 'number', currency: { symbol: '\u20AC', code: 'EUR' }, ambiguous: false }
226
+ */
227
+ function parseNumber(text, options = {}) {
228
+ const symbols = numberSymbols(options.locale ?? "en-US");
229
+ if (text.length > 256) return null;
230
+ const arabicDecimal = text.includes("٫");
231
+ const normalized = normalize(text.replace(/\u066B/g, "."));
232
+ let start = normalized.search(/\d/);
233
+ if (start === -1) return null;
234
+ if (/[.,]/.test(normalized.charAt(start - 1)) && !/\p{L}/u.test(normalized.charAt(start - 2))) start -= 1;
235
+ let end = normalized.length;
236
+ while (!/\d/.test(normalized.charAt(end - 1))) end -= 1;
237
+ const adornments = {
238
+ sign: "",
239
+ open: false,
240
+ close: false,
241
+ currency: null,
242
+ kind: "number"
243
+ };
244
+ if (!readAdornments(normalized.slice(0, start), adornments, "prefix") || !readAdornments(normalized.slice(end), adornments, "suffix")) return null;
245
+ if (adornments.open !== adornments.close || adornments.open && adornments.sign !== "") return null;
246
+ const core = normalized.slice(start, end);
247
+ const scientific = /^(\d*)(?:[.,](\d*))?[eE]([+-]?\d{1,3})$/.exec(core);
248
+ let mantissa;
249
+ if (scientific === null) mantissa = /^[\d.,' ]+$/.test(core) ? readMantissa(core, symbols.decimal, arabicDecimal) : null;
250
+ else mantissa = {
251
+ integer: String(scientific[1]),
252
+ fraction: scientific[2] ?? "",
253
+ ambiguous: false
254
+ };
255
+ if (mantissa === null) return null;
256
+ const exponent = scientific === null ? 0 : Number(scientific[3]);
257
+ if (Math.abs(exponent) > MAX_EXPONENT) return null;
258
+ const digits = shift(mantissa.integer === "" ? "0" : mantissa.integer, mantissa.fraction, exponent);
259
+ const zero = /^0(?:\.0*)?$/.test(digits);
260
+ const negative = (adornments.sign === "-" || adornments.open) && !zero;
261
+ const exact = negative ? `-${digits}` : digits;
262
+ const value = Number(exact);
263
+ if (!Number.isFinite(value)) return null;
264
+ if (options.negative === false && negative) return null;
265
+ if (options.fraction === false && /\.\d*[1-9]/.test(digits)) return null;
266
+ if (options.currency === false && adornments.currency !== null) return null;
267
+ if (options.percent === false && adornments.kind !== "number") return null;
268
+ if (adornments.currency !== null && adornments.kind !== "number") return null;
269
+ return {
270
+ value,
271
+ exact,
272
+ kind: adornments.kind,
273
+ currency: adornments.currency,
274
+ ambiguous: mantissa.ambiguous
275
+ };
276
+ }
277
+ //#endregion
278
+ //#region src/number/format.ts
279
+ /** Plain decimal notation, as `parseNumber` gives in `exact`: `-1234.50`, `0.00000015`. */
280
+ const EXACT = /^(-?)(\d+)(?:\.(\d+))?$/;
281
+ const NUMBER = /^(-?)(\d+)(?:\.(\d+))?(?:e([+-]\d+))?$/;
282
+ /** `value` as sign, integer digits and fraction digits, exactly. */
283
+ function decompose(value) {
284
+ if (typeof value === "bigint") {
285
+ const text = value.toString();
286
+ return text.startsWith("-") ? [
287
+ true,
288
+ text.slice(1),
289
+ ""
290
+ ] : [
291
+ false,
292
+ text,
293
+ ""
294
+ ];
295
+ }
296
+ if (typeof value === "number") {
297
+ if (!Number.isFinite(value)) throw copyFailure("invalid-payload", `${String(value)} is not a finite number.`);
298
+ const match = NUMBER.exec(String(value));
299
+ const sign = String(match[1]);
300
+ const integer = String(match[2]);
301
+ const fraction = match[3] ?? "";
302
+ const shiftBy = Number(match[4] ?? "0");
303
+ const digits = integer + fraction;
304
+ const point = integer.length + shiftBy;
305
+ if (point <= 0) return [
306
+ sign === "-",
307
+ "0",
308
+ "0".repeat(-point) + digits
309
+ ];
310
+ if (point >= digits.length) return [
311
+ sign === "-",
312
+ digits + "0".repeat(point - digits.length),
313
+ ""
314
+ ];
315
+ return [
316
+ sign === "-",
317
+ digits.slice(0, point),
318
+ digits.slice(point)
319
+ ];
320
+ }
321
+ const match = EXACT.exec(value);
322
+ if (match === null) throw copyFailure("invalid-payload", `"${value.slice(0, 40)}" is not a decimal number such as "-1234.5".`);
323
+ return [
324
+ match[1] === "-",
325
+ String(match[2]),
326
+ match[3] ?? ""
327
+ ];
328
+ }
329
+ /** `digits` plus one, carrying: `"199"` gives `"200"`, `"99"` gives `"100"`. */
330
+ function increment(digits) {
331
+ let out = "";
332
+ let carry = true;
333
+ for (let index = digits.length - 1; index >= 0; index -= 1) {
334
+ const digit = Number(digits.charAt(index)) + (carry ? 1 : 0);
335
+ carry = digit === 10;
336
+ out = String(digit % 10) + out;
337
+ }
338
+ return carry ? `1${out}` : out;
339
+ }
340
+ /** Groups `integer` from the right: the last group of `primary` digits, the others of `secondary`. */
341
+ function group(integer, separator, primary, secondary) {
342
+ if (integer.length <= primary) return integer;
343
+ const groups = [integer.slice(-primary)];
344
+ let rest = integer.slice(0, -primary);
345
+ while (rest.length > secondary) {
346
+ groups.unshift(rest.slice(-secondary));
347
+ rest = rest.slice(0, -secondary);
348
+ }
349
+ groups.unshift(rest);
350
+ return groups.join(separator);
351
+ }
352
+ /**
353
+ * Writes a number in a locale's format, exactly: no float rounding, whatever its size.
354
+ * Takes a `number`, a `bigint`, or an exact decimal string (`parseNumber`'s `exact`), so
355
+ * money read from one locale can be written in another without losing a cent.
356
+ *
357
+ * @throws {CopyFailure} `invalid-payload` for a number that is not finite, a string that is
358
+ * not plain decimal notation, a `fractionDigits` out of range, or a `locale` that is not one.
359
+ * @example
360
+ * formatNumber('1234.5', { locale: 'de-DE', grouping: true, fractionDigits: 2 }); // "1.234,50"
361
+ */
362
+ function formatNumber(value, options = {}) {
363
+ const symbols = numberSymbols(options.locale ?? "en-US");
364
+ const digits = options.fractionDigits;
365
+ if (digits !== void 0 && !(Number.isInteger(digits) && digits >= 0 && digits <= 100)) throw copyFailure("invalid-payload", `fractionDigits must be a whole number from 0 to 100, not ${String(digits)}.`);
366
+ const [negative, rawInteger, rawFraction] = decompose(value);
367
+ let integer = rawInteger.replace(/^0+(?=\d)/, "");
368
+ let fraction = rawFraction;
369
+ if (digits !== void 0) {
370
+ if (fraction.length > digits) {
371
+ const roundUp = fraction.charAt(digits) >= "5";
372
+ fraction = fraction.slice(0, digits);
373
+ if (roundUp) {
374
+ const rounded = increment(integer + fraction);
375
+ integer = rounded.slice(0, rounded.length - digits);
376
+ fraction = rounded.slice(rounded.length - digits);
377
+ }
378
+ } else fraction = fraction.padEnd(digits, "0");
379
+ }
380
+ const zero = /^0*$/.test(integer + fraction);
381
+ const whole = options.grouping === true ? group(integer, symbols.group, symbols.primary, symbols.secondary) : integer;
382
+ return `${negative && !zero ? "-" : ""}${whole}${fraction === "" ? "" : symbols.decimal + fraction}`;
383
+ }
384
+ /**
385
+ * A copy payload for a number, written for the locale it will be pasted in: ungrouped by
386
+ * default, so a spreadsheet reads it as a number. Pass it to `copy()` or `useCopy`.
387
+ *
388
+ * @example
389
+ * copy(numberPayload(invoice.total, { locale: navigator.language, fractionDigits: 2 }));
390
+ */
391
+ function numberPayload(value, options = {}) {
392
+ return {
393
+ kind: "text",
394
+ value: formatNumber(value, options)
395
+ };
396
+ }
397
+ //#endregion
398
+ //#region src/number/paste.ts
399
+ function asNumberInput(target) {
400
+ const element = target;
401
+ return element?.nodeName === "INPUT" && element.type === "number" ? target : null;
402
+ }
403
+ /**
404
+ * A paste handler for number and amount fields. People paste `1.234,50 €` from a bank
405
+ * statement, `$1,234.50` from an invoice, or `(1,234)` from a spreadsheet; a browser either
406
+ * rejects these from `<input type="number">` or keeps the text as it is. This reads the
407
+ * number, inserts it the way the field takes it (with undo intact in text fields), and
408
+ * turns away pastes that are not a number.
409
+ *
410
+ * Works on `<input type="number">`, text `<input>`s (use `inputmode="decimal"`) and
411
+ * `<textarea>`s; other elements are left to the browser.
412
+ *
413
+ * @example
414
+ * <input inputMode="decimal" onPaste={(event) => pasteAsNumber(event, { locale: 'de-DE' })} />
415
+ */
416
+ function pasteAsNumber(event, options = {}) {
417
+ if (event.defaultPrevented || event.clipboardData === null) return "ignored";
418
+ const numberInput = asNumberInput(event.currentTarget) ?? asNumberInput(event.target);
419
+ const field = numberInput ?? asTextField(event.currentTarget) ?? asTextField(event.target);
420
+ if (field === null) return "ignored";
421
+ const text = event.clipboardData.getData("text/plain");
422
+ if (text === "") return "ignored";
423
+ event.preventDefault();
424
+ const parsed = parseNumber(text.trim(), options);
425
+ if (parsed !== null && !field.disabled && !field.readOnly) {
426
+ options.onNumber?.(parsed);
427
+ const value = options.format?.(parsed) ?? (numberInput === null ? formatNumber(parsed.exact, options) : parsed.exact);
428
+ if (numberInput === null ? insertText(field, value) : replaceFieldValue(numberInput, value)) return "pasted";
429
+ }
430
+ options.onReject?.(text);
431
+ return "rejected";
432
+ }
433
+ //#endregion
434
+ export { NUMBER_MAX_LENGTH, formatNumber, numberPayload, numberSymbols, parseNumber, pasteAsNumber };
435
+
436
+ //# sourceMappingURL=number.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"number.js","names":[],"sources":["../src/number/currency.ts","../src/number/locale.ts","../src/number/parse.ts","../src/number/format.ts","../src/number/paste.ts"],"sourcesContent":["/** A currency written next to a number. */\nexport interface NumberCurrency {\n /** As it was written, normalized: `\\u20AC`, `R$`, `kr`, `USD`. */\n readonly symbol: string;\n /** Its ISO 4217 code, when the symbol names one currency: `null` for `$`, `\\u00A5`, `kr` and `Rs`. */\n readonly code: string | null;\n}\n\n/**\n * Currency symbols, after NFKC (so `\\uFF04` is `$` and `\\u20A8` is `Rs`). Symbols that several\n * currencies share have no code: the text alone can't tell a dollar from another.\n */\nconst SYMBOLS: readonly (readonly [string, string | null])[] = [\n ['US$', 'USD'], ['CA$', 'CAD'], ['C$', 'CAD'], ['AU$', 'AUD'], ['A$', 'AUD'], ['NZ$', 'NZD'], ['HK$', 'HKD'],\n ['S$', 'SGD'], ['R$', 'BRL'], ['MX$', 'MXN'], ['NT$', 'TWD'], ['$', null],\n ['\\u20AC', 'EUR'], ['\\u00A3', 'GBP'], ['JP\\u00A5', 'JPY'], ['CN\\u00A5', 'CNY'], ['\\u00A5', null],\n ['\\u20B9', 'INR'], ['Rs.', null], ['Rs', null], ['\\u20A9', 'KRW'], ['\\u20BD', 'RUB'], ['\\u20BA', 'TRY'],\n ['\\u20AA', 'ILS'], ['\\u20AB', 'VND'], ['\\u20B1', 'PHP'], ['\\u0E3F', 'THB'], ['\\u20B4', 'UAH'], ['\\u20A6', 'NGN'],\n ['\\u20B8', 'KZT'], ['\\u09F3', 'BDT'], ['z\\u0142', 'PLN'], ['K\\u010D', 'CZK'], ['kr.', null], ['kr', null], ['Fr.', 'CHF'],\n];\n\n/** Longest first, so `US$` is read before `$` and `Rs.` before `Rs`. */\nconst BY_LENGTH = [...SYMBOLS].sort((a, b) => b[0].length - a[0].length).map(([symbol, code]) => [symbol, symbol.toLowerCase(), code] as const);\n\nlet codes: ReadonlySet<string> | null | undefined;\n\n/** Whether `code` (upper case) is an ISO 4217 code the runtime knows; any three letters where it can't say. */\nexport function isCurrencyCode(code: string): boolean {\n if (codes === undefined) {\n const supported = (Intl as { supportedValuesOf?: (key: 'currency') => string[] }).supportedValuesOf;\n codes = typeof supported === 'function' ? new Set(supported('currency')) : null;\n }\n return /^[A-Z]{3}$/.test(code) && (codes === null || codes.has(code));\n}\n\n/** For tests: forget the runtime's codes, so they are read again. */\nexport function resetCurrencyCodes(): void {\n codes = undefined;\n}\n\nconst LETTER = /\\p{L}/u;\n\n/**\n * The currency at the start of `text`, and how many characters it takes. A symbol or code\n * made of letters must end there: `Rs` is not read from `Rsx`, nor `USD` from `USDT`.\n */\nexport function readCurrency(text: string): { readonly currency: NumberCurrency; readonly length: number } | null {\n const lower = text.toLowerCase();\n for (const [symbol, key, code] of BY_LENGTH) {\n if (lower.startsWith(key) && !(LETTER.test(symbol.slice(-1)) && LETTER.test(text.charAt(key.length)))) {\n return { currency: { symbol, code }, length: key.length };\n }\n }\n const word = /^\\p{L}+/u.exec(text)?.[0] ?? '';\n const code = word.toUpperCase();\n return word.length === 3 && isCurrencyCode(code) ? { currency: { symbol: code, code }, length: 3 } : null;\n}\n","import { copyFailure } from '../core/errors';\n\n/** How a locale writes numbers, in Latin digits. */\nexport interface NumberSymbols {\n /** The decimal separator. */\n readonly decimal: '.' | ',';\n /** The group separator, as the locale writes it (a no-break space in French, for one); `''` for none. */\n readonly group: string;\n /** Digits in the last group of the integer part: 3 almost everywhere. */\n readonly primary: number;\n /** Digits in the groups before it: 2 in India's lakh and crore grouping, 3 elsewhere. */\n readonly secondary: number;\n}\n\nconst cache = new Map<string, NumberSymbols>();\nconst CACHE_SIZE = 32;\n\n/**\n * How `locale` writes numbers, from `Intl.NumberFormat`.\n *\n * @throws {CopyFailure} `invalid-payload` for a string that is not a locale.\n */\nexport function numberSymbols(locale: string): NumberSymbols {\n const cached = cache.get(locale);\n if (cached !== undefined) return cached;\n let parts: Intl.NumberFormatPart[];\n try {\n parts = new Intl.NumberFormat(locale, { numberingSystem: 'latn' }).formatToParts(123456789012.5);\n } catch (cause) {\n throw copyFailure('invalid-payload', `\"${locale}\" is not a locale.`, cause);\n }\n // 123,456,789,012 in most locales; 1,23,45,67,89,012 in India's.\n const integers = parts.filter((part) => part.type === 'integer').map((part) => part.value.length);\n const symbols: NumberSymbols = {\n decimal: parts.some((part) => part.type === 'decimal' && part.value === ',') ? ',' : '.',\n // A locale that writes no group separator has none to add.\n group: parts.find((part) => part.type === 'group')?.value ?? '',\n primary: Number(integers[integers.length - 1]),\n secondary: Number(integers[Math.max(0, integers.length - 2)]),\n };\n // A small cache: locales come from settings, but a hostile caller could pass many.\n if (cache.size >= CACHE_SIZE) cache.clear();\n cache.set(locale, symbols);\n return symbols;\n}\n","import { asciiDigits } from '../core/digits';\nimport { readCurrency, type NumberCurrency } from './currency';\nimport { numberSymbols } from './locale';\n\n/** What a number was written as: `12` is a number, `12%` a percentage, `12\\u2030` per mille. */\nexport type NumberKind = 'number' | 'percent' | 'permille';\n\n/** A number read from text. */\nexport interface ParsedNumber {\n /** The number as written: `12` for `12%`, `-1234.5` for `(1.234,50 \\u20AC)`. */\n readonly value: number;\n /**\n * The same number as an exact decimal string, without rounding: `-1234.50` keeps its\n * trailing zero, and `0.1` is not `0.1000000000000000055\\u2026`. Use it for money.\n */\n readonly exact: string;\n /** `'percent'` or `'permille'` when the number was written with `%` or `\\u2030`. */\n readonly kind: NumberKind;\n /** The currency written with it, if any. */\n readonly currency: NumberCurrency | null;\n /**\n * The text had one `,` or `.` before exactly three digits (`1,234`, `1.234`): a group\n * separator in some locales and a decimal separator in others. `locale` decided which;\n * ask the person when it matters.\n */\n readonly ambiguous: boolean;\n}\n\nexport interface ParseNumberOptions {\n /**\n * The locale whose decimal separator settles an ambiguous `1,234` or `1.234`: grouping\n * in `en-US`, a decimal in `de-DE`. Default `'en-US'`. Text that can only be read one way\n * is read that way in every locale: `1.234,5` is 1234.5 everywhere.\n */\n readonly locale?: string;\n /** Accept negative numbers. Default `true`. */\n readonly negative?: boolean;\n /** Accept numbers with a fractional part. Default `true`. */\n readonly fraction?: boolean;\n /** Accept a currency symbol or code. Default `true`. */\n readonly currency?: boolean;\n /** Accept `%` and `\\u2030`. Default `true`. */\n readonly percent?: boolean;\n}\n\n/** Longer text holds more than a number: it is not read at all. */\nexport const NUMBER_MAX_LENGTH = 256;\n\n/** Group separators that are never decimal separators: spaces and apostrophes. */\nconst GROUP_ONLY = new Set([' ', \"'\"]);\n/** The largest exponent read from scientific notation, past which no number is finite. */\nconst MAX_EXPONENT = 400;\n\ninterface Adornments {\n sign: '' | '-' | '+';\n /** An opening bracket before the number, and a closing one after it: accounting's minus. */\n open: boolean;\n close: boolean;\n currency: NumberCurrency | null;\n kind: NumberKind;\n}\n\n/**\n * Reads the signs, brackets, currency and percent on one side of the number. Returns\n * `false` when something else is there, or when one of them appears twice.\n */\nfunction readAdornments(text: string, into: Adornments, side: 'prefix' | 'suffix'): boolean {\n let rest = text;\n for (;;) {\n rest = rest.trimStart();\n if (rest === '') return true;\n const char = rest.charAt(0);\n let length = 1;\n if (char === '(' && side === 'prefix' && !into.open) into.open = true;\n else if (char === ')' && side === 'suffix' && !into.close) into.close = true;\n // A minus after the number is a trailing minus (`1234-`), as some accounting systems write it.\n else if ((char === '-' || (char === '+' && side === 'prefix')) && into.sign === '') into.sign = char;\n else if ((char === '%' || char === '\\u2030') && into.kind === 'number') into.kind = char === '%' ? 'percent' : 'permille';\n else {\n const read = into.currency === null ? readCurrency(rest) : null;\n if (read === null) return false;\n into.currency = read.currency;\n length = read.length;\n }\n rest = rest.slice(length);\n }\n}\n\n/** The text in a form the reader understands: ASCII digits, one minus, one apostrophe, plain spaces. */\nfunction normalize(text: string): string {\n return (\n asciiDigits(text)\n // Minus signs and dashes used as one.\n .replace(/[\\u2212\\u2012\\u2013]/g, '-')\n // Arabic percent sign; Arabic decimal and thousands separators come next.\n .replace(/\\u066A/g, '%')\n .replace(/[\\u2019\\u02BC\\u066C]/g, \"'\")\n .replace(/\\s/g, ' ')\n );\n}\n\n/** Whether `groups` (the integer part, split at its group separator) are grouped the way locales group. */\nfunction validGroups(groups: readonly string[]): boolean {\n const [first, ...rest] = groups;\n if (first === undefined || first === '' || first.length > 3 || rest.length === 0) return false;\n if (rest.every((group) => group.length === 3)) return true;\n // Lakh and crore: 12,34,567. The last group has 3 digits and the others 2.\n return first.length <= 2 && rest.slice(0, -1).every((group) => group.length === 2) && rest[rest.length - 1]?.length === 3;\n}\n\ninterface Mantissa {\n readonly integer: string;\n readonly fraction: string;\n readonly ambiguous: boolean;\n}\n\n/** The integer and fractional digits of `text` (digits and separators only), or `null`. */\nfunction readMantissa(text: string, decimalOfLocale: '.' | ',', arabicDecimal: boolean): Mantissa | null {\n const separators = text.replace(/\\d/g, '');\n if (separators === '') return { integer: text, fraction: '', ambiguous: false };\n // The decimal separator can only be the last separator, appearing once: `1,234,567.8`,\n // `1.234,5`. An Arabic decimal separator is one wherever it is.\n const candidate = arabicDecimal ? '.' : separators.charAt(separators.length - 1);\n const once = separators.split(candidate).length === 2;\n if (arabicDecimal && !once) return null;\n let decimal: string | null = null;\n let ambiguous = false;\n if (once && !GROUP_ONLY.has(candidate)) {\n const at = text.lastIndexOf(candidate);\n const before = text.slice(0, at);\n // A lone separator is a decimal unless it could also start a group of three.\n if (arabicDecimal || separators.length > 1 || text.length - at - 1 !== 3 || before === '' || before.length > 3 || before.startsWith('0')) decimal = candidate;\n else {\n ambiguous = true;\n decimal = candidate === decimalOfLocale ? candidate : null;\n }\n }\n const at = decimal === null ? text.length : text.lastIndexOf(decimal);\n const integerPart = text.slice(0, at);\n const fraction = text.slice(at + 1);\n if (!/^\\d*$/.test(fraction)) return null;\n const groupSeparators = integerPart.replace(/\\d/g, '');\n if (groupSeparators === '') return { integer: integerPart, fraction, ambiguous };\n const group = groupSeparators.charAt(0);\n if (groupSeparators !== group.repeat(groupSeparators.length) || !validGroups(integerPart.split(group))) return null;\n return { integer: integerPart.split(group).join(''), fraction, ambiguous };\n}\n\n/** `integer.fraction` times ten to the `exponent`, as an exact decimal string without a sign. */\nfunction shift(integer: string, fraction: string, exponent: number): string {\n const digits = integer + fraction;\n const point = integer.length + exponent;\n let whole: string;\n let decimals: string;\n if (exponent === 0) [whole, decimals] = [integer, fraction];\n else if (point <= 0) [whole, decimals] = ['0', '0'.repeat(-point) + digits];\n else if (point >= digits.length) [whole, decimals] = [digits + '0'.repeat(point - digits.length), ''];\n else [whole, decimals] = [digits.slice(0, point), digits.slice(point)];\n // Scientific notation's own trailing zeros say nothing about precision: they go.\n if (exponent !== 0) decimals = decimals.replace(/0+$/, '');\n whole = whole.replace(/^0+(?=\\d)/, '');\n return decimals === '' ? whole : `${whole}.${decimals}`;\n}\n\n/**\n * Reads a number the way people paste one: from a spreadsheet, a bank statement, an invoice\n * or a web page, in any locale's format. The whole text must be one number, with at most a\n * sign, a currency and a percent sign around it; anything else gives `null`.\n *\n * - Group separators `,` `.` `'` and spaces (no-break and narrow ones too), in groups of\n * three or the lakh and crore grouping (`12,34,567`). Wrong grouping gives `null`.\n * - The decimal separator is whichever of `,` and `.` the text shows is one (`1.234,5`,\n * `1,5`, `0.500`); only a lone separator before three digits (`1,234`) is settled by `locale`.\n * - `-`, `+`, `\\u2212`, a trailing minus (`1234-`) and accounting brackets (`(1,234)`).\n * - Currency symbols and ISO codes, before or after: `$`, `\\u20AC`, `R$`, `kr`, `USD`, `CHF`.\n * - `%` and `\\u2030`, before or after; scientific notation (`1.5E-7`).\n * - Digits of any script, full-width characters, and Arabic separators.\n *\n * @throws {CopyFailure} `invalid-payload` for a `locale` that is not one.\n * @example\n * parseNumber('1.234,50 \\u20AC', { locale: 'de-DE' });\n * // { value: 1234.5, exact: '1234.50', kind: 'number', currency: { symbol: '\\u20AC', code: 'EUR' }, ambiguous: false }\n */\nexport function parseNumber(text: string, options: ParseNumberOptions = {}): ParsedNumber | null {\n const symbols = numberSymbols(options.locale ?? 'en-US');\n if (text.length > NUMBER_MAX_LENGTH) return null;\n const arabicDecimal = text.includes('\\u066B');\n const normalized = normalize(text.replace(/\\u066B/g, '.'));\n // The number: from its first digit (or a separator right before it, as in `.5`) to its last\n // digit. Not a dot that ends a word (`Rs.5` is 5 rupees).\n let start = normalized.search(/\\d/);\n if (start === -1) return null;\n if (/[.,]/.test(normalized.charAt(start - 1)) && !/\\p{L}/u.test(normalized.charAt(start - 2))) start -= 1;\n let end = normalized.length;\n while (!/\\d/.test(normalized.charAt(end - 1))) end -= 1;\n const adornments: Adornments = { sign: '', open: false, close: false, currency: null, kind: 'number' };\n if (!readAdornments(normalized.slice(0, start), adornments, 'prefix') || !readAdornments(normalized.slice(end), adornments, 'suffix')) return null;\n // Brackets come in pairs, and mean the minus: `-(5)` is a typo, not a number.\n if (adornments.open !== adornments.close || (adornments.open && adornments.sign !== '')) return null;\n\n const core = normalized.slice(start, end);\n // Scientific notation, as spreadsheets copy it: one decimal separator, never grouped.\n const scientific = /^(\\d*)(?:[.,](\\d*))?[eE]([+-]?\\d{1,3})$/.exec(core);\n let mantissa: Mantissa | null;\n if (scientific === null) mantissa = /^[\\d.,' ]+$/.test(core) ? readMantissa(core, symbols.decimal, arabicDecimal) : null;\n else mantissa = { integer: String(scientific[1]), fraction: scientific[2] ?? '', ambiguous: false };\n if (mantissa === null) return null;\n const exponent = scientific === null ? 0 : Number(scientific[3]);\n if (Math.abs(exponent) > MAX_EXPONENT) return null;\n\n const digits = shift(mantissa.integer === '' ? '0' : mantissa.integer, mantissa.fraction, exponent);\n const zero = /^0(?:\\.0*)?$/.test(digits);\n const negative = (adornments.sign === '-' || adornments.open) && !zero;\n const exact = negative ? `-${digits}` : digits;\n const value = Number(exact);\n if (!Number.isFinite(value)) return null;\n\n if (options.negative === false && negative) return null;\n if (options.fraction === false && /\\.\\d*[1-9]/.test(digits)) return null;\n if (options.currency === false && adornments.currency !== null) return null;\n if (options.percent === false && adornments.kind !== 'number') return null;\n if (adornments.currency !== null && adornments.kind !== 'number') return null;\n return { value, exact, kind: adornments.kind, currency: adornments.currency, ambiguous: mantissa.ambiguous };\n}\n","import { copyFailure } from '../core/errors';\nimport type { TextPayload } from '../core/payload';\nimport { numberSymbols } from './locale';\n\nexport interface FormatNumberOptions {\n /** The locale whose decimal and group separators to use. Default `'en-US'`. Digits are always Latin. */\n readonly locale?: string;\n /**\n * Group the integer part (`1,234,567`; `12,34,567` in `en-IN`). Default `false`: spreadsheets\n * read ungrouped numbers in every locale, and grouped ones only in their own.\n */\n readonly grouping?: boolean;\n /** Exactly this many decimals (0 to 100), rounding half away from zero. Default: as many as the number has. */\n readonly fractionDigits?: number;\n}\n\n/** Plain decimal notation, as `parseNumber` gives in `exact`: `-1234.50`, `0.00000015`. */\nconst EXACT = /^(-?)(\\d+)(?:\\.(\\d+))?$/;\nconst NUMBER = /^(-?)(\\d+)(?:\\.(\\d+))?(?:e([+-]\\d+))?$/;\n\n/** `value` as sign, integer digits and fraction digits, exactly. */\nfunction decompose(value: number | string | bigint): readonly [boolean, string, string] {\n if (typeof value === 'bigint') {\n const text = value.toString();\n return text.startsWith('-') ? [true, text.slice(1), ''] : [false, text, ''];\n }\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw copyFailure('invalid-payload', `${String(value)} is not a finite number.`);\n // `String` gives the shortest text that reads back as the same number: 0.1 is `0.1`.\n const match = NUMBER.exec(String(value)) as RegExpExecArray;\n const sign = String(match[1]);\n const integer = String(match[2]);\n const fraction = match[3] ?? '';\n const shiftBy = Number(match[4] ?? '0');\n const digits = integer + fraction;\n const point = integer.length + shiftBy;\n if (point <= 0) return [sign === '-', '0', '0'.repeat(-point) + digits];\n if (point >= digits.length) return [sign === '-', digits + '0'.repeat(point - digits.length), ''];\n return [sign === '-', digits.slice(0, point), digits.slice(point)];\n }\n const match = EXACT.exec(value);\n if (match === null) throw copyFailure('invalid-payload', `\"${value.slice(0, 40)}\" is not a decimal number such as \"-1234.5\".`);\n return [match[1] === '-', String(match[2]), match[3] ?? ''];\n}\n\n/** `digits` plus one, carrying: `\"199\"` gives `\"200\"`, `\"99\"` gives `\"100\"`. */\nfunction increment(digits: string): string {\n let out = '';\n let carry = true;\n for (let index = digits.length - 1; index >= 0; index -= 1) {\n const digit: number = Number(digits.charAt(index)) + (carry ? 1 : 0);\n carry = digit === 10;\n out = String(digit % 10) + out;\n }\n return carry ? `1${out}` : out;\n}\n\n/** Groups `integer` from the right: the last group of `primary` digits, the others of `secondary`. */\nfunction group(integer: string, separator: string, primary: number, secondary: number): string {\n if (integer.length <= primary) return integer;\n const groups = [integer.slice(-primary)];\n let rest = integer.slice(0, -primary);\n while (rest.length > secondary) {\n groups.unshift(rest.slice(-secondary));\n rest = rest.slice(0, -secondary);\n }\n groups.unshift(rest);\n return groups.join(separator);\n}\n\n/**\n * Writes a number in a locale's format, exactly: no float rounding, whatever its size.\n * Takes a `number`, a `bigint`, or an exact decimal string (`parseNumber`'s `exact`), so\n * money read from one locale can be written in another without losing a cent.\n *\n * @throws {CopyFailure} `invalid-payload` for a number that is not finite, a string that is\n * not plain decimal notation, a `fractionDigits` out of range, or a `locale` that is not one.\n * @example\n * formatNumber('1234.5', { locale: 'de-DE', grouping: true, fractionDigits: 2 }); // \"1.234,50\"\n */\nexport function formatNumber(value: number | string | bigint, options: FormatNumberOptions = {}): string {\n const symbols = numberSymbols(options.locale ?? 'en-US');\n const digits = options.fractionDigits;\n if (digits !== undefined && !(Number.isInteger(digits) && digits >= 0 && digits <= 100)) {\n throw copyFailure('invalid-payload', `fractionDigits must be a whole number from 0 to 100, not ${String(digits)}.`);\n }\n const [negative, rawInteger, rawFraction] = decompose(value);\n let integer = rawInteger.replace(/^0+(?=\\d)/, '');\n let fraction = rawFraction;\n if (digits !== undefined) {\n if (fraction.length > digits) {\n const roundUp = fraction.charAt(digits) >= '5';\n fraction = fraction.slice(0, digits);\n if (roundUp) {\n const rounded = increment(integer + fraction);\n integer = rounded.slice(0, rounded.length - digits);\n fraction = rounded.slice(rounded.length - digits);\n }\n } else fraction = fraction.padEnd(digits, '0');\n }\n const zero = /^0*$/.test(integer + fraction);\n const whole = options.grouping === true ? group(integer, symbols.group, symbols.primary, symbols.secondary) : integer;\n return `${negative && !zero ? '-' : ''}${whole}${fraction === '' ? '' : symbols.decimal + fraction}`;\n}\n\n/**\n * A copy payload for a number, written for the locale it will be pasted in: ungrouped by\n * default, so a spreadsheet reads it as a number. Pass it to `copy()` or `useCopy`.\n *\n * @example\n * copy(numberPayload(invoice.total, { locale: navigator.language, fractionDigits: 2 }));\n */\nexport function numberPayload(value: number | string | bigint, options: FormatNumberOptions = {}): TextPayload {\n return { kind: 'text', value: formatNumber(value, options) };\n}\n","import { asTextField, insertText, replaceFieldValue, type TextField } from '../core/text-field';\nimport { formatNumber } from './format';\nimport { parseNumber, type ParsedNumber, type ParseNumberOptions } from './parse';\n\n/** What {@link pasteAsNumber} did. */\nexport type NumberPasteOutcome =\n /** The paste held a number: it was inserted, written the way the field takes it. */\n | 'pasted'\n /** The paste was not a number (or the field is read-only): nothing was inserted. */\n | 'rejected'\n /** Not a paste for this handler (no text, already handled, or not a text or number field): left to the browser. */\n | 'ignored';\n\nexport interface PasteAsNumberOptions extends ParseNumberOptions {\n /**\n * How to write the number into the field. Default: `exact` for `<input type=\"number\">`,\n * which only takes `.` as the decimal separator; elsewhere the number in `locale`'s format,\n * ungrouped (`1234,5` in `de-DE`).\n */\n readonly format?: (parsed: ParsedNumber) => string;\n /** Called with the number before it is inserted: show `ambiguous` readings here. */\n readonly onNumber?: (parsed: ParsedNumber) => void;\n /** Called with the pasted text when it was not a number, or the field takes no input. */\n readonly onReject?: (text: string) => void;\n}\n\n/** Structural paste event: a DOM `ClipboardEvent` and React's `onPaste` event both fit. */\nexport interface NumberPasteEvent {\n readonly clipboardData: { getData(format: string): string } | null;\n readonly currentTarget: EventTarget | null;\n readonly target: EventTarget | null;\n readonly defaultPrevented: boolean;\n preventDefault(): void;\n}\n\nfunction asNumberInput(target: EventTarget | null): HTMLInputElement | null {\n const element = target as (Partial<Element> & { type?: unknown }) | null;\n return element?.nodeName === 'INPUT' && element.type === 'number' ? (target as HTMLInputElement) : null;\n}\n\n/**\n * A paste handler for number and amount fields. People paste `1.234,50 €` from a bank\n * statement, `$1,234.50` from an invoice, or `(1,234)` from a spreadsheet; a browser either\n * rejects these from `<input type=\"number\">` or keeps the text as it is. This reads the\n * number, inserts it the way the field takes it (with undo intact in text fields), and\n * turns away pastes that are not a number.\n *\n * Works on `<input type=\"number\">`, text `<input>`s (use `inputmode=\"decimal\"`) and\n * `<textarea>`s; other elements are left to the browser.\n *\n * @example\n * <input inputMode=\"decimal\" onPaste={(event) => pasteAsNumber(event, { locale: 'de-DE' })} />\n */\nexport function pasteAsNumber(event: NumberPasteEvent, options: PasteAsNumberOptions = {}): NumberPasteOutcome {\n if (event.defaultPrevented || event.clipboardData === null) return 'ignored';\n const numberInput = asNumberInput(event.currentTarget) ?? asNumberInput(event.target);\n const field: TextField | null = numberInput ?? asTextField(event.currentTarget) ?? asTextField(event.target);\n if (field === null) return 'ignored';\n const text = event.clipboardData.getData('text/plain');\n if (text === '') return 'ignored';\n event.preventDefault();\n const parsed = parseNumber(text.trim(), options);\n if (parsed !== null && !field.disabled && !field.readOnly) {\n options.onNumber?.(parsed);\n const value = options.format?.(parsed) ?? (numberInput === null ? formatNumber(parsed.exact, options) : parsed.exact);\n if (numberInput === null ? insertText(field, value) : replaceFieldValue(numberInput, value)) return 'pasted';\n }\n options.onReject?.(text);\n return 'rejected';\n}\n"],"mappings":";;;;;;AAsBA,MAAM,YAAY,CAAC,GAAG;CATpB,CAAC,OAAO,KAAK;CAAG,CAAC,OAAO,KAAK;CAAG,CAAC,MAAM,KAAK;CAAG,CAAC,OAAO,KAAK;CAAG,CAAC,MAAM,KAAK;CAAG,CAAC,OAAO,KAAK;CAAG,CAAC,OAAO,KAAK;CAC3G,CAAC,MAAM,KAAK;C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AAW,OAAO,KAAK,IAAI,kBAAkB,aAAa,KAAK,GAAG,OAAO;CACtG;CACA,QAAQ,WAAW,IAAI;CACvB,OAAO;AACT"}
package/dist/otp.cjs ADDED
@@ -0,0 +1,7 @@
1
+
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const require_field = require("./chunks/field-Bytz2WfN.cjs");
4
+ exports.OTP_SCAN_LENGTH = require_field.OTP_SCAN_LENGTH;
5
+ exports.createOtpField = require_field.createOtpField;
6
+ exports.extractOtp = require_field.extractOtp;
7
+ exports.normalizeOtpText = require_field.normalizeOtpText;
package/dist/otp.d.cts ADDED
@@ -0,0 +1,54 @@
1
+
2
+ import { a as WebOtpStatus, i as createOtpField, n as OtpFieldOptions, o as OtpAlphabet, r as OtpSnapshot, s as normalizeOtpText, t as OtpField } from "./chunks/field-BTsKTs2M.cjs";
3
+ //#region src/otp/extract.d.ts
4
+ /** Text past this many characters is not read: a code is near the start of a message. */
5
+ export declare const OTP_SCAN_LENGTH = 100000;
6
+ interface ExtractOtpOptions {
7
+ /** The code's length, or its range. Default 4 to 8. */
8
+ readonly length?: number | {
9
+ readonly min: number;
10
+ readonly max: number;
11
+ };
12
+ /** Default `'numeric'`. Alphanumeric codes are upper case: pasted letters are made so. */
13
+ readonly alphabet?: OtpAlphabet;
14
+ /**
15
+ * Your site's host name, as in `example.com`. An origin-bound message (`@example.com #123456`,
16
+ * the format the WebOTP API reads) for another host gives no code: it was not meant for you.
17
+ */
18
+ readonly domain?: string;
19
+ }
20
+ /**
21
+ * Where the code was found.
22
+ *
23
+ * - `whole-text`: the text is the code (`482913`, `482 913`, `482-913`).
24
+ * - `origin-bound`: the message's last line binds it to a site (`@example.com #482913`).
25
+ * - `keyword`: next to a word such as "code", "OTP", "verification" or "PIN", in any of
26
+ * many languages.
27
+ * - `only-candidate`: the only number of the right length that is not a price, a date, a
28
+ * time, a phone number or an order number.
29
+ */
30
+ type OtpSource = 'whole-text' | 'origin-bound' | 'keyword' | 'only-candidate';
31
+ interface OtpMatch {
32
+ /** The code: ASCII digits (and upper-case letters, for alphanumeric codes), no separators. */
33
+ readonly code: string;
34
+ readonly source: OtpSource;
35
+ /** `medium` for `only-candidate`; `high` otherwise. */
36
+ readonly confidence: 'high' | 'medium';
37
+ /** The site an origin-bound message names; `null` otherwise. */
38
+ readonly domain: string | null;
39
+ }
40
+ /**
41
+ * The one-time code in `text`: an SMS or e-mail people paste, or a code they copied. Digits
42
+ * of any script and full-width characters are read as ASCII, and separators are dropped
43
+ * (`482 913`, `482-913`).
44
+ *
45
+ * Prices, dates, times, phone numbers, order numbers and postal codes are never taken for a
46
+ * code. When several numbers could be the code and no keyword points at one, the result is
47
+ * `null`: guessing would fill in a wrong code.
48
+ *
49
+ * @throws {CopyFailure} `invalid-payload` for a `length` that is not 1 to 32, or a reversed range.
50
+ */
51
+ export declare function extractOtp(text: string, options?: ExtractOtpOptions): OtpMatch | null;
52
+ //#endregion
53
+ export { type ExtractOtpOptions, type OtpAlphabet, type OtpField, type OtpFieldOptions, type OtpMatch, type OtpSnapshot, type OtpSource, type WebOtpStatus, createOtpField, normalizeOtpText };
54
+ //# sourceMappingURL=otp.d.cts.map
package/dist/otp.d.ts ADDED
@@ -0,0 +1,54 @@
1
+
2
+ import { a as WebOtpStatus, i as createOtpField, n as OtpFieldOptions, o as OtpAlphabet, r as OtpSnapshot, s as normalizeOtpText, t as OtpField } from "./chunks/field-BTsKTs2M.js";
3
+ //#region src/otp/extract.d.ts
4
+ /** Text past this many characters is not read: a code is near the start of a message. */
5
+ export declare const OTP_SCAN_LENGTH = 100000;
6
+ interface ExtractOtpOptions {
7
+ /** The code's length, or its range. Default 4 to 8. */
8
+ readonly length?: number | {
9
+ readonly min: number;
10
+ readonly max: number;
11
+ };
12
+ /** Default `'numeric'`. Alphanumeric codes are upper case: pasted letters are made so. */
13
+ readonly alphabet?: OtpAlphabet;
14
+ /**
15
+ * Your site's host name, as in `example.com`. An origin-bound message (`@example.com #123456`,
16
+ * the format the WebOTP API reads) for another host gives no code: it was not meant for you.
17
+ */
18
+ readonly domain?: string;
19
+ }
20
+ /**
21
+ * Where the code was found.
22
+ *
23
+ * - `whole-text`: the text is the code (`482913`, `482 913`, `482-913`).
24
+ * - `origin-bound`: the message's last line binds it to a site (`@example.com #482913`).
25
+ * - `keyword`: next to a word such as "code", "OTP", "verification" or "PIN", in any of
26
+ * many languages.
27
+ * - `only-candidate`: the only number of the right length that is not a price, a date, a
28
+ * time, a phone number or an order number.
29
+ */
30
+ type OtpSource = 'whole-text' | 'origin-bound' | 'keyword' | 'only-candidate';
31
+ interface OtpMatch {
32
+ /** The code: ASCII digits (and upper-case letters, for alphanumeric codes), no separators. */
33
+ readonly code: string;
34
+ readonly source: OtpSource;
35
+ /** `medium` for `only-candidate`; `high` otherwise. */
36
+ readonly confidence: 'high' | 'medium';
37
+ /** The site an origin-bound message names; `null` otherwise. */
38
+ readonly domain: string | null;
39
+ }
40
+ /**
41
+ * The one-time code in `text`: an SMS or e-mail people paste, or a code they copied. Digits
42
+ * of any script and full-width characters are read as ASCII, and separators are dropped
43
+ * (`482 913`, `482-913`).
44
+ *
45
+ * Prices, dates, times, phone numbers, order numbers and postal codes are never taken for a
46
+ * code. When several numbers could be the code and no keyword points at one, the result is
47
+ * `null`: guessing would fill in a wrong code.
48
+ *
49
+ * @throws {CopyFailure} `invalid-payload` for a `length` that is not 1 to 32, or a reversed range.
50
+ */
51
+ export declare function extractOtp(text: string, options?: ExtractOtpOptions): OtpMatch | null;
52
+ //#endregion
53
+ export { type ExtractOtpOptions, type OtpAlphabet, type OtpField, type OtpFieldOptions, type OtpMatch, type OtpSnapshot, type OtpSource, type WebOtpStatus, createOtpField, normalizeOtpText };
54
+ //# sourceMappingURL=otp.d.ts.map
package/dist/otp.js ADDED
@@ -0,0 +1,2 @@
1
+
2
+ export { n as OTP_SCAN_LENGTH, t as createOtpField, r as extractOtp, i as normalizeOtpText } from "./chunks/field-BHo5y-t_.js";
package/dist/secrets.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
 
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const require_errors = require("./chunks/errors-BwOF6T_M.cjs");
4
- const require_text_field = require("./chunks/text-field-Ba8W3v4R.cjs");
4
+ const require_text_field = require("./chunks/text-field-BEzUVOag.cjs");
5
5
  //#region src/secrets/checks.ts
6
6
  /** Checks that tell real secrets from look-alikes: checksums, structure and randomness. */
7
7
  /** The Luhn checksum of card numbers. `digits` holds only digits. */