@momotombodevs/istmo 0.0.0-stage → 0.1.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 (52) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE +21 -0
  3. package/README.md +442 -2
  4. package/dist/dates.cjs +314 -0
  5. package/dist/dates.d.cts +127 -0
  6. package/dist/dates.d.ts +127 -0
  7. package/dist/dates.js +302 -0
  8. package/dist/formatted-input.cjs +51 -0
  9. package/dist/formatted-input.js +49 -0
  10. package/dist/index.cjs +38 -0
  11. package/dist/index.d.cts +6 -0
  12. package/dist/index.d.ts +6 -0
  13. package/dist/index.js +6 -0
  14. package/dist/metadata.cjs +3 -0
  15. package/dist/metadata.js +4 -0
  16. package/dist/money.cjs +172 -0
  17. package/dist/money.d.cts +69 -0
  18. package/dist/money.d.ts +69 -0
  19. package/dist/money.js +166 -0
  20. package/dist/phone-examples.json.cjs +11 -0
  21. package/dist/phone-examples.json.js +11 -0
  22. package/dist/phone-input.cjs +34 -0
  23. package/dist/phone-input.d.cts +18 -0
  24. package/dist/phone-input.d.ts +18 -0
  25. package/dist/phone-input.js +33 -0
  26. package/dist/phone-metadata.json.cjs +224 -0
  27. package/dist/phone-metadata.json.js +224 -0
  28. package/dist/phone.cjs +121 -0
  29. package/dist/phone.d.cts +78 -0
  30. package/dist/phone.d.ts +78 -0
  31. package/dist/phone.js +117 -0
  32. package/dist/react.cjs +238 -0
  33. package/dist/react.d.cts +128 -0
  34. package/dist/react.d.ts +128 -0
  35. package/dist/react.js +232 -0
  36. package/dist/regions.cjs +94 -0
  37. package/dist/regions.d.cts +77 -0
  38. package/dist/regions.d.ts +77 -0
  39. package/dist/regions.js +85 -0
  40. package/dist/regions.json.cjs +136 -0
  41. package/dist/regions.json.js +125 -0
  42. package/dist/require.cjs +14 -0
  43. package/dist/require.js +13 -0
  44. package/flags/LICENSE +21 -0
  45. package/flags/bz.svg +145 -0
  46. package/flags/cr.svg +7 -0
  47. package/flags/gt.svg +204 -0
  48. package/flags/hn.svg +18 -0
  49. package/flags/ni.svg +129 -0
  50. package/flags/pa.svg +7 -0
  51. package/flags/sv.svg +593 -0
  52. package/package.json +201 -4
package/dist/dates.js ADDED
@@ -0,0 +1,302 @@
1
+ import { requireCountry } from "./require.js";
2
+ // src/dates.ts
3
+ const LOCAL_DATE = /^(\d{1,2})([/-])(\d{1,2})\2(\d{4})$/;
4
+ const ISO_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
5
+ const ISO_INSTANT = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,9}))?)?(?:Z|([+-])(\d{2}):(\d{2}))$/;
6
+ const TIME = /^(\d{1,2}):(\d{2})$/;
7
+ const pad = (value, length = 2) => String(value).padStart(length, "0");
8
+ function isLeapYear(year) {
9
+ return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
10
+ }
11
+ function toIsoDate(year, month, day) {
12
+ const lengths = [
13
+ 31,
14
+ isLeapYear(year) ? 29 : 28,
15
+ 31,
16
+ 30,
17
+ 31,
18
+ 30,
19
+ 31,
20
+ 31,
21
+ 30,
22
+ 31,
23
+ 30,
24
+ 31
25
+ ];
26
+ if (!Number.isInteger(year) || year < 1 || year > 9999 || month < 1 || month > 12 || day < 1 || day > (lengths[month - 1] ?? 0)) return null;
27
+ return `${pad(year, 4)}-${pad(month)}-${pad(day)}`;
28
+ }
29
+ function offsetMinutes({ utcOffset }) {
30
+ const sign = utcOffset.startsWith("-") ? -1 : 1;
31
+ const [hours = 0, minutes = 0] = utcOffset.slice(1).split(":").map(Number);
32
+ return sign * (hours * 60 + minutes);
33
+ }
34
+ function requireIsoDate(date) {
35
+ const match = typeof date === "string" ? ISO_DATE.exec(date) : null;
36
+ if (!match || toIsoDate(Number(match[1]), Number(match[2]), Number(match[3])) === null) throw new RangeError("Fecha inválida: se espera YYYY-MM-DD.");
37
+ }
38
+ function utcEpoch(year, month, day, minutes, milliseconds) {
39
+ const moment = /* @__PURE__ */ new Date(0);
40
+ moment.setUTCFullYear(year, month - 1, day);
41
+ return moment.getTime() + minutes * 6e4 + milliseconds;
42
+ }
43
+ function invalidInstant() {
44
+ return /* @__PURE__ */ new RangeError("Instante inválido: use ISO 8601 con Z o con desfase, como 2026-11-24T20:30:00Z.");
45
+ }
46
+ const toNumber = (part) => Number(part ?? 0);
47
+ function parseInstant(text) {
48
+ const match = ISO_INSTANT.exec(text.trim());
49
+ if (!match) throw invalidInstant();
50
+ const [year, month, day, hours, minutes, seconds, fraction = "", sign, offsetHours, offsetMinutes] = match.slice(1);
51
+ const date = {
52
+ year: toNumber(year),
53
+ month: toNumber(month),
54
+ day: toNumber(day)
55
+ };
56
+ const time = {
57
+ hours: toNumber(hours),
58
+ minutes: toNumber(minutes),
59
+ seconds: toNumber(seconds)
60
+ };
61
+ const offset = {
62
+ hours: toNumber(offsetHours),
63
+ minutes: toNumber(offsetMinutes)
64
+ };
65
+ if (toIsoDate(date.year, date.month, date.day) === null || time.hours > 23 || time.minutes > 59 || time.seconds > 59 || offset.hours > 23 || offset.minutes > 59) throw invalidInstant();
66
+ const offsetMinutesTotal = (sign === "-" ? -1 : 1) * (offset.hours * 60 + offset.minutes);
67
+ const milliseconds = time.seconds * 1e3 + Number(fraction.padEnd(3, "0").slice(0, 3));
68
+ return utcEpoch(date.year, date.month, date.day, time.hours * 60 + time.minutes - offsetMinutesTotal, milliseconds);
69
+ }
70
+ function toEpoch(instant) {
71
+ const time = typeof instant === "string" ? parseInstant(instant) : typeof instant === "number" ? instant : instant.getTime();
72
+ if (!Number.isFinite(time)) throw new RangeError("Instante inválido.");
73
+ return time;
74
+ }
75
+ /**
76
+ * Reads a date written `dd/mm/aaaa` (also `d/m/aaaa` and `dd-mm-aaaa`) and rejects dates that do not exist.
77
+ *
78
+ * @returns The date as `YYYY-MM-DD`, or `null` when it is not a valid date.
79
+ * @example parseDate('24/11/2026') // "2026-11-24"
80
+ * @example parseDate('29/02/2026') // null
81
+ */
82
+ function parseDate(input) {
83
+ if (typeof input !== "string") return null;
84
+ const match = LOCAL_DATE.exec(input.trim());
85
+ if (!match) return null;
86
+ return toIsoDate(Number(match[4]), Number(match[3]), Number(match[1]));
87
+ }
88
+ /**
89
+ * Tells whether a text is a valid `dd/mm/aaaa` date. Same rules as {@link parseDate}.
90
+ *
91
+ * @example isValidDate('31/04/2026') // false
92
+ */
93
+ function isValidDate(input) {
94
+ return parseDate(input) !== null;
95
+ }
96
+ /**
97
+ * Writes a `YYYY-MM-DD` date as `dd/mm/aaaa`.
98
+ *
99
+ * @throws {RangeError} When the date is not a valid `YYYY-MM-DD` date.
100
+ * @example formatDate('2026-11-24') // "24/11/2026"
101
+ */
102
+ function formatDate(date) {
103
+ requireIsoDate(date);
104
+ const [year, month, day] = date.split("-");
105
+ return `${day}/${month}/${year}`;
106
+ }
107
+ /**
108
+ * Date and time on the wall clock of a country, whatever the device or server time zone is.
109
+ *
110
+ * @param instant The moment to read. Default: now.
111
+ * @throws {RangeError} When the country is not supported or the instant is not valid.
112
+ * @example localDateTime('NI', '2026-11-25T04:30:00Z') // { date: '2026-11-24', time: '22:30', iso: '2026-11-24T22:30:00-06:00' }
113
+ */
114
+ function localDateTime(countryCode, instant = Date.now()) {
115
+ const target = requireCountry(countryCode);
116
+ const local = new Date(toEpoch(instant) + offsetMinutes(target) * 6e4);
117
+ const date = toIsoDate(local.getUTCFullYear(), local.getUTCMonth() + 1, local.getUTCDate());
118
+ if (date === null) throw new RangeError("Instante fuera del rango de fechas soportado.");
119
+ const time = `${pad(local.getUTCHours())}:${pad(local.getUTCMinutes())}`;
120
+ return {
121
+ date,
122
+ time,
123
+ iso: `${date}T${time}:${pad(local.getUTCSeconds())}${target.utcOffset}`
124
+ };
125
+ }
126
+ /**
127
+ * Today's date in a country, whatever the device or server time zone is.
128
+ *
129
+ * @param instant The moment to read. Default: now.
130
+ * @throws {RangeError} When the country is not supported or the instant is not valid.
131
+ * @example today('NI') // "2026-11-24"
132
+ */
133
+ function today(countryCode, instant) {
134
+ return localDateTime(countryCode, instant).date;
135
+ }
136
+ /**
137
+ * The moment a wall-clock date and time happen in a country, as ISO 8601 with the country's offset.
138
+ * Use it to send a chosen date and time (a reservation, a delivery slot) to the server.
139
+ *
140
+ * @param time `HH:MM` or `H:MM`, 24-hour clock.
141
+ * @throws {RangeError} When the date, the time or the country is not valid.
142
+ * @example zonedDateTime('2026-11-24', '14:30', 'NI') // "2026-11-24T14:30:00-06:00"
143
+ */
144
+ function zonedDateTime(date, time, countryCode) {
145
+ const target = requireCountry(countryCode);
146
+ requireIsoDate(date);
147
+ const match = typeof time === "string" ? TIME.exec(time.trim()) : null;
148
+ const hours = Number(match?.[1]);
149
+ const minutes = Number(match?.[2]);
150
+ if (!match || hours > 23 || minutes > 59) throw new RangeError("Hora inválida: se espera HH:MM.");
151
+ return `${date}T${pad(hours)}:${pad(minutes)}:00${target.utcOffset}`;
152
+ }
153
+ const MONTHS = [
154
+ "enero",
155
+ "febrero",
156
+ "marzo",
157
+ "abril",
158
+ "mayo",
159
+ "junio",
160
+ "julio",
161
+ "agosto",
162
+ "septiembre",
163
+ "octubre",
164
+ "noviembre",
165
+ "diciembre"
166
+ ];
167
+ const WEEKDAYS = [
168
+ "domingo",
169
+ "lunes",
170
+ "martes",
171
+ "miércoles",
172
+ "jueves",
173
+ "viernes",
174
+ "sábado"
175
+ ];
176
+ const TIME_TEXT = /^(\d{1,2})(?::(\d{2}))?\s*(?:([ap])\.?\s*m\.?)?$/i;
177
+ const DAY_MS = 864e5;
178
+ function dateParts(date) {
179
+ requireIsoDate(date);
180
+ const [year = 0, month = 0, day = 0] = date.split("-").map(Number);
181
+ return {
182
+ year,
183
+ month,
184
+ day
185
+ };
186
+ }
187
+ function dayNumber(date) {
188
+ const { year, month, day } = dateParts(date);
189
+ return Math.round(utcEpoch(year, month, day, 0, 0) / DAY_MS);
190
+ }
191
+ /**
192
+ * Reads a time as people write it: `14:30`, `2:30 pm`, `2:30 p. m.`, `2 pm`, `12 am`.
193
+ *
194
+ * @returns The time as `HH:MM` on a 24-hour clock, or `null` when it is not a valid time.
195
+ * @example parseTime('2:30 p. m.') // "14:30"
196
+ * @example parseTime('12 am') // "00:00"
197
+ * @example parseTime('25:00') // null
198
+ */
199
+ function parseTime(input) {
200
+ if (typeof input !== "string") return null;
201
+ const match = TIME_TEXT.exec(input.trim());
202
+ if (!match) return null;
203
+ const meridiem = match[3]?.toLowerCase();
204
+ const minutes = Number(match[2] ?? 0);
205
+ let hours = Number(match[1]);
206
+ if (minutes > 59) return null;
207
+ if (meridiem) {
208
+ if (hours < 1 || hours > 12) return null;
209
+ hours = hours % 12 + (meridiem === "p" ? 12 : 0);
210
+ } else if (hours > 23 || match[2] === void 0) return null;
211
+ return `${pad(hours)}:${pad(minutes)}`;
212
+ }
213
+ /**
214
+ * Writes a `HH:MM` time the way it is read in the region: `2:30 p. m.`, or `14:30` with `clock: '24h'`.
215
+ *
216
+ * @throws {RangeError} When the time is not a valid `HH:MM` time.
217
+ * @example formatTime('14:30') // "2:30 p. m."
218
+ * @example formatTime('00:05') // "12:05 a. m."
219
+ * @example formatTime('14:30', { clock: '24h' }) // "14:30"
220
+ */
221
+ function formatTime(time, options = {}) {
222
+ const match = typeof time === "string" ? /^(\d{2}):(\d{2})$/.exec(time) : null;
223
+ const hours = Number(match?.[1]);
224
+ const minutes = Number(match?.[2]);
225
+ if (!match || hours > 23 || minutes > 59) throw new RangeError("Hora inválida: se espera HH:MM.");
226
+ if (options.clock === "24h") return time;
227
+ return `${hours % 12 || 12}:${pad(minutes)} ${hours < 12 ? "a. m." : "p. m."}`;
228
+ }
229
+ /**
230
+ * Writes a `YYYY-MM-DD` date in words, in Spanish.
231
+ *
232
+ * @throws {RangeError} When the date is not a valid `YYYY-MM-DD` date.
233
+ * @example formatLongDate('2026-11-24') // "martes 24 de noviembre de 2026"
234
+ * @example formatLongDate('2026-11-24', { weekday: false, year: false }) // "24 de noviembre"
235
+ */
236
+ function formatLongDate(date, options = {}) {
237
+ const { year, month, day } = dateParts(date);
238
+ const weekday = WEEKDAYS[new Date(utcEpoch(year, month, day, 0, 0)).getUTCDay()];
239
+ const text = `${day} de ${MONTHS[month - 1]}${options.year === false ? "" : ` de ${year}`}`;
240
+ return options.weekday === false ? text : `${weekday} ${text}`;
241
+ }
242
+ /**
243
+ * Days from one `YYYY-MM-DD` date to another; negative when `to` is earlier.
244
+ *
245
+ * @throws {RangeError} When a date is not a valid `YYYY-MM-DD` date.
246
+ * @example daysBetween('2026-11-24', '2026-12-25') // 31
247
+ */
248
+ function daysBetween(from, to) {
249
+ return dayNumber(to) - dayNumber(from);
250
+ }
251
+ /**
252
+ * Completed years between a birth date and another date, such as {@link today}.
253
+ *
254
+ * @throws {RangeError} When a date is not valid or `onDate` is before `birthDate`.
255
+ * @example ageOn('2008-11-25', '2026-11-24') // 17
256
+ * @example ageOn('2008-11-24', '2026-11-24') // 18
257
+ */
258
+ function ageOn(birthDate, onDate) {
259
+ const birth = dateParts(birthDate);
260
+ const on = dateParts(onDate);
261
+ if (onDate < birthDate) throw new RangeError("La fecha es anterior al nacimiento.");
262
+ const birthdayPassed = on.month > birth.month || on.month === birth.month && on.day >= birth.day;
263
+ return on.year - birth.year - (birthdayPassed ? 0 : 1);
264
+ }
265
+ /**
266
+ * Formats a `dd/mm/aaaa` date while it is being typed: adds `/` after the day and the month, and pads a one-digit
267
+ * day or month when the person types the `/` themselves (`1/` becomes `01/`).
268
+ *
269
+ * @example formatDateInput('2411') // { text: '24/11', date: null }
270
+ * @example formatDateInput('24112026') // { text: '24/11/2026', date: '2026-11-24' }
271
+ * @example formatDateInput('1/2/2026') // { text: '01/02/2026', date: '2026-02-01' }
272
+ */
273
+ function formatDateInput(text) {
274
+ const typed = typeof text === "string" ? text.slice(0, 32) : "";
275
+ const fields = [
276
+ "",
277
+ "",
278
+ ""
279
+ ];
280
+ const limits = [
281
+ 2,
282
+ 2,
283
+ 4
284
+ ];
285
+ let field = 0;
286
+ let closedBySeparator = false;
287
+ for (const character of typed) if (/\d/.test(character)) {
288
+ if (field < 2 && fields[field]?.length === limits[field]) field++;
289
+ if ((fields[field]?.length ?? 0) < (limits[field] ?? 0)) fields[field] += character;
290
+ closedBySeparator = false;
291
+ } else if (/[/.-]/.test(character) && field < 2 && fields[field]) {
292
+ fields[field] = (fields[field] ?? "").padStart(2, "0");
293
+ field++;
294
+ closedBySeparator = true;
295
+ }
296
+ const shown = fields.filter(Boolean).join("/") + (closedBySeparator ? "/" : "");
297
+ return {
298
+ text: shown,
299
+ date: fields[2]?.length === 4 ? parseDate(shown) : null
300
+ };
301
+ }
302
+ export { ageOn, daysBetween, formatDate, formatDateInput, formatLongDate, formatTime, isValidDate, localDateTime, parseDate, parseTime, today, zonedDateTime };
@@ -0,0 +1,51 @@
1
+ // src/formatted-input.ts
2
+ function commonPrefix(left, right) {
3
+ let length = 0;
4
+ while (length < left.length && length < right.length && left[length] === right[length]) length++;
5
+ return length;
6
+ }
7
+ function commonSuffix(left, right, prefix) {
8
+ let length = 0;
9
+ while (length < left.length - prefix && length < right.length - prefix && left[left.length - 1 - length] === right[right.length - 1 - length]) length++;
10
+ return length;
11
+ }
12
+ function countMatches(text, significant) {
13
+ let count = 0;
14
+ for (const character of text) if (significant.test(character)) count++;
15
+ return count;
16
+ }
17
+ function caretAfter(text, count, significant) {
18
+ let seen = 0;
19
+ for (let index = 0; index < text.length; index++) {
20
+ if (!significant.test(text[index] ?? "")) continue;
21
+ if (seen === count) return index;
22
+ seen++;
23
+ }
24
+ return text.length;
25
+ }
26
+ function applyEdit(previous, next, format, significant) {
27
+ const prefix = commonPrefix(previous, next);
28
+ const suffix = commonSuffix(previous, next, prefix);
29
+ const removed = previous.slice(prefix, previous.length - suffix);
30
+ const inserted = next.slice(prefix, next.length - suffix);
31
+ let typed = next;
32
+ let caret = next.length - suffix;
33
+ if (!inserted && removed && countMatches(removed, significant) === 0) {
34
+ const before = previous.slice(0, prefix);
35
+ let last = before.length - 1;
36
+ while (last >= 0 && !significant.test(before[last] ?? "")) last--;
37
+ if (last >= 0) {
38
+ typed = before.slice(0, last) + previous.slice(last + 1);
39
+ caret = last;
40
+ }
41
+ }
42
+ const count = countMatches(typed.slice(0, caret), significant);
43
+ const text = format(typed);
44
+ return {
45
+ text,
46
+ caret: count === countMatches(text, significant) ? text.length : caretAfter(text, count, significant)
47
+ };
48
+ }
49
+ exports.applyEdit = applyEdit;
50
+ exports.commonPrefix = commonPrefix;
51
+ exports.commonSuffix = commonSuffix;
@@ -0,0 +1,49 @@
1
+ // src/formatted-input.ts
2
+ function commonPrefix(left, right) {
3
+ let length = 0;
4
+ while (length < left.length && length < right.length && left[length] === right[length]) length++;
5
+ return length;
6
+ }
7
+ function commonSuffix(left, right, prefix) {
8
+ let length = 0;
9
+ while (length < left.length - prefix && length < right.length - prefix && left[left.length - 1 - length] === right[right.length - 1 - length]) length++;
10
+ return length;
11
+ }
12
+ function countMatches(text, significant) {
13
+ let count = 0;
14
+ for (const character of text) if (significant.test(character)) count++;
15
+ return count;
16
+ }
17
+ function caretAfter(text, count, significant) {
18
+ let seen = 0;
19
+ for (let index = 0; index < text.length; index++) {
20
+ if (!significant.test(text[index] ?? "")) continue;
21
+ if (seen === count) return index;
22
+ seen++;
23
+ }
24
+ return text.length;
25
+ }
26
+ function applyEdit(previous, next, format, significant) {
27
+ const prefix = commonPrefix(previous, next);
28
+ const suffix = commonSuffix(previous, next, prefix);
29
+ const removed = previous.slice(prefix, previous.length - suffix);
30
+ const inserted = next.slice(prefix, next.length - suffix);
31
+ let typed = next;
32
+ let caret = next.length - suffix;
33
+ if (!inserted && removed && countMatches(removed, significant) === 0) {
34
+ const before = previous.slice(0, prefix);
35
+ let last = before.length - 1;
36
+ while (last >= 0 && !significant.test(before[last] ?? "")) last--;
37
+ if (last >= 0) {
38
+ typed = before.slice(0, last) + previous.slice(last + 1);
39
+ caret = last;
40
+ }
41
+ }
42
+ const count = countMatches(typed.slice(0, caret), significant);
43
+ const text = format(typed);
44
+ return {
45
+ text,
46
+ caret: count === countMatches(text, significant) ? text.length : caretAfter(text, count, significant)
47
+ };
48
+ }
49
+ export { applyEdit, commonPrefix, commonSuffix };
package/dist/index.cjs ADDED
@@ -0,0 +1,38 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_dates = require("./dates.cjs");
3
+ const require_money = require("./money.cjs");
4
+ const require_phone = require("./phone.cjs");
5
+ const require_phone_input = require("./phone-input.cjs");
6
+ const require_regions = require("./regions.cjs");
7
+ exports.MAX_INTEGER_DIGITS = require_money.MAX_INTEGER_DIGITS;
8
+ exports.acceptsCurrency = require_regions.acceptsCurrency;
9
+ exports.ageOn = require_dates.ageOn;
10
+ exports.countries = require_regions.countries;
11
+ exports.country = require_regions.country;
12
+ exports.countryCodes = require_regions.countryCodes;
13
+ exports.currencies = require_regions.currencies;
14
+ exports.currency = require_regions.currency;
15
+ exports.currencyCodes = require_regions.currencyCodes;
16
+ exports.daysBetween = require_dates.daysBetween;
17
+ exports.formatDate = require_dates.formatDate;
18
+ exports.formatDateInput = require_dates.formatDateInput;
19
+ exports.formatLongDate = require_dates.formatLongDate;
20
+ exports.formatMoney = require_money.formatMoney;
21
+ exports.formatMoneyInput = require_money.formatMoneyInput;
22
+ exports.formatPhoneInput = require_phone_input.formatPhoneInput;
23
+ exports.formatTime = require_dates.formatTime;
24
+ exports.fromMinorUnits = require_money.fromMinorUnits;
25
+ exports.isCountryCode = require_regions.isCountryCode;
26
+ exports.isCurrencyCode = require_regions.isCurrencyCode;
27
+ exports.isValidDate = require_dates.isValidDate;
28
+ exports.isValidPhone = require_phone.isValidPhone;
29
+ exports.localDateTime = require_dates.localDateTime;
30
+ exports.parseDate = require_dates.parseDate;
31
+ exports.parseMoney = require_money.parseMoney;
32
+ exports.parsePhone = require_phone.parsePhone;
33
+ exports.parseTime = require_dates.parseTime;
34
+ exports.phoneExample = require_phone.phoneExample;
35
+ exports.toMinorUnits = require_money.toMinorUnits;
36
+ exports.today = require_dates.today;
37
+ exports.validatePhone = require_phone.validatePhone;
38
+ exports.zonedDateTime = require_dates.zonedDateTime;
@@ -0,0 +1,6 @@
1
+ import { DateInputText, Instant, IsoDate, LocalDateTime, ageOn, daysBetween, formatDate, formatDateInput, formatLongDate, formatTime, isValidDate, localDateTime, parseDate, parseTime, today, zonedDateTime } from "./dates.cjs";
2
+ import { Amount, FormatMoneyOptions, MAX_INTEGER_DIGITS, MoneyDisplay, MoneyInputText, formatMoney, formatMoneyInput, fromMinorUnits, parseMoney, toMinorUnits } from "./money.cjs";
3
+ import { Phone, PhoneError, PhoneOptions, PhoneType, PhoneValidation, isValidPhone, parsePhone, phoneExample, validatePhone } from "./phone.cjs";
4
+ import { PhoneInputText, formatPhoneInput } from "./phone-input.cjs";
5
+ import { Country, CountryCode, Currency, CurrencyCode, UtcOffset, acceptsCurrency, countries, country, countryCodes, currencies, currency, currencyCodes, isCountryCode, isCurrencyCode } from "./regions.cjs";
6
+ export { Amount, type Country, type CountryCode, type Currency, type CurrencyCode, DateInputText, FormatMoneyOptions, Instant, IsoDate, LocalDateTime, MAX_INTEGER_DIGITS, MoneyDisplay, MoneyInputText, Phone, PhoneError, PhoneInputText, PhoneOptions, PhoneType, PhoneValidation, type UtcOffset, acceptsCurrency, ageOn, countries, country, countryCodes, currencies, currency, currencyCodes, daysBetween, formatDate, formatDateInput, formatLongDate, formatMoney, formatMoneyInput, formatPhoneInput, formatTime, fromMinorUnits, isCountryCode, isCurrencyCode, isValidDate, isValidPhone, localDateTime, parseDate, parseMoney, parsePhone, parseTime, phoneExample, toMinorUnits, today, validatePhone, zonedDateTime };
@@ -0,0 +1,6 @@
1
+ import { DateInputText, Instant, IsoDate, LocalDateTime, ageOn, daysBetween, formatDate, formatDateInput, formatLongDate, formatTime, isValidDate, localDateTime, parseDate, parseTime, today, zonedDateTime } from "./dates.js";
2
+ import { Amount, FormatMoneyOptions, MAX_INTEGER_DIGITS, MoneyDisplay, MoneyInputText, formatMoney, formatMoneyInput, fromMinorUnits, parseMoney, toMinorUnits } from "./money.js";
3
+ import { Phone, PhoneError, PhoneOptions, PhoneType, PhoneValidation, isValidPhone, parsePhone, phoneExample, validatePhone } from "./phone.js";
4
+ import { PhoneInputText, formatPhoneInput } from "./phone-input.js";
5
+ import { Country, CountryCode, Currency, CurrencyCode, UtcOffset, acceptsCurrency, countries, country, countryCodes, currencies, currency, currencyCodes, isCountryCode, isCurrencyCode } from "./regions.js";
6
+ export { Amount, type Country, type CountryCode, type Currency, type CurrencyCode, DateInputText, FormatMoneyOptions, Instant, IsoDate, LocalDateTime, MAX_INTEGER_DIGITS, MoneyDisplay, MoneyInputText, Phone, PhoneError, PhoneInputText, PhoneOptions, PhoneType, PhoneValidation, type UtcOffset, acceptsCurrency, ageOn, countries, country, countryCodes, currencies, currency, currencyCodes, daysBetween, formatDate, formatDateInput, formatLongDate, formatMoney, formatMoneyInput, formatPhoneInput, formatTime, fromMinorUnits, isCountryCode, isCurrencyCode, isValidDate, isValidPhone, localDateTime, parseDate, parseMoney, parsePhone, parseTime, phoneExample, toMinorUnits, today, validatePhone, zonedDateTime };
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ import { ageOn, daysBetween, formatDate, formatDateInput, formatLongDate, formatTime, isValidDate, localDateTime, parseDate, parseTime, today, zonedDateTime } from "./dates.js";
2
+ import { MAX_INTEGER_DIGITS, formatMoney, formatMoneyInput, fromMinorUnits, parseMoney, toMinorUnits } from "./money.js";
3
+ import { isValidPhone, parsePhone, phoneExample, validatePhone } from "./phone.js";
4
+ import { formatPhoneInput } from "./phone-input.js";
5
+ import { acceptsCurrency, countries, country, countryCodes, currencies, currency, currencyCodes, isCountryCode, isCurrencyCode } from "./regions.js";
6
+ export { MAX_INTEGER_DIGITS, acceptsCurrency, ageOn, countries, country, countryCodes, currencies, currency, currencyCodes, daysBetween, formatDate, formatDateInput, formatLongDate, formatMoney, formatMoneyInput, formatPhoneInput, formatTime, fromMinorUnits, isCountryCode, isCurrencyCode, isValidDate, isValidPhone, localDateTime, parseDate, parseMoney, parsePhone, parseTime, phoneExample, toMinorUnits, today, validatePhone, zonedDateTime };
@@ -0,0 +1,3 @@
1
+ // src/metadata.ts
2
+ const metadata = require("./phone-metadata.json.cjs");
3
+ exports.metadata = metadata;
@@ -0,0 +1,4 @@
1
+ import phone_metadata_default from "./phone-metadata.json.js";
2
+ // src/metadata.ts
3
+ const metadata = phone_metadata_default;
4
+ export { metadata };
package/dist/money.cjs ADDED
@@ -0,0 +1,172 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_require = require("./require.cjs");
3
+ // src/money.ts
4
+ /** Longest integer part accepted, in digits. Large enough for any `decimal` database column. */
5
+ const MAX_INTEGER_DIGITS = 30;
6
+ const MAX_INPUT_LENGTH = 64;
7
+ const DECIMAL = /^(-)?(\d+)(?:\.(\d+))?$/;
8
+ const NBSP = "\xA0";
9
+ const SPACES = " \xA0 ";
10
+ function toDecimal(amount) {
11
+ if (typeof amount === "number" && (!Number.isFinite(amount) || Math.abs(amount) > Number.MAX_SAFE_INTEGER)) throw new RangeError("Monto inválido: use un texto decimal para montos fuera del rango seguro de number.");
12
+ const text = typeof amount === "number" ? String(amount) : typeof amount === "string" ? amount.trim() : "";
13
+ const match = DECIMAL.exec(text);
14
+ if (!match || (match[2] ?? "").replace(/^0+(?=\d)/, "").length > 30) throw new RangeError("Monto inválido: se espera un decimal como \"1250.50\".");
15
+ return {
16
+ negative: match[1] === "-",
17
+ integer: match[2] ?? "0",
18
+ fraction: match[3] ?? ""
19
+ };
20
+ }
21
+ function increment(digits) {
22
+ let result = "";
23
+ let carry = 1;
24
+ for (let index = digits.length - 1; index >= 0; index--) {
25
+ const sum = Number(digits[index]) + carry;
26
+ result = String(sum % 10) + result;
27
+ carry = sum > 9 ? 1 : 0;
28
+ }
29
+ return carry ? `1${result}` : result;
30
+ }
31
+ function round({ negative, integer, fraction }, decimals) {
32
+ const kept = `${integer}${fraction.padEnd(decimals, "0").slice(0, decimals)}`;
33
+ const digits = (Number(fraction[decimals] ?? "0") >= 5 ? increment(kept) : kept).replace(/^0+(?=\d)/, "").padStart(decimals + 1, "0");
34
+ const result = {
35
+ integer: digits.slice(0, digits.length - decimals),
36
+ fraction: decimals > 0 ? digits.slice(-decimals) : ""
37
+ };
38
+ return {
39
+ negative: negative && /[1-9]/.test(digits),
40
+ ...result
41
+ };
42
+ }
43
+ function group(integer, separator) {
44
+ const head = integer.length % 3 || 3;
45
+ const parts = [integer.slice(0, head)];
46
+ for (let index = head; index < integer.length; index += 3) parts.push(integer.slice(index, index + 3));
47
+ return parts.join(separator);
48
+ }
49
+ /**
50
+ * Formats an amount for display. Rounds half away from zero on the decimal text, so `1.005` gives `1.01`.
51
+ * The label and the number are joined with a non-breaking space so they never wrap apart.
52
+ *
53
+ * @param amount Decimal text with `.` (`"1250.5"`, as stored in a `decimal` column) or a safe number.
54
+ * @throws {RangeError} When the currency is not supported or the amount is not a decimal.
55
+ * @example formatMoney('1250.5', 'NIO') // "C$ 1,250.50"
56
+ * @example formatMoney('1234567.5', 'CRC') // "₡ 1,234,567.50"
57
+ * @example formatMoney('180', 'NIO', { decimals: 'auto' }) // "C$ 180"
58
+ */
59
+ function formatMoney(amount, currencyCode, options = {}) {
60
+ const target = require_require.requireCurrency(currencyCode);
61
+ const { negative, integer, fraction } = round(toDecimal(amount), target.decimals);
62
+ const hideFraction = options.decimals === "auto" && !/[1-9]/.test(fraction);
63
+ const number = `${group(integer, target.groupSeparator)}${hideFraction || !fraction ? "" : target.decimalSeparator + fraction}`;
64
+ const display = options.display ?? "symbol";
65
+ const label = display === "none" ? "" : `${display === "code" ? target.code : target.symbol}${NBSP}`;
66
+ return `${negative ? "-" : ""}${label}${number}`;
67
+ }
68
+ function escapeRegExp(text) {
69
+ return text.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
70
+ }
71
+ const GROUPS = [
72
+ ",",
73
+ "\\.",
74
+ `[${SPACES}]`
75
+ ];
76
+ function amountPatterns(decimals) {
77
+ const fraction = decimals > 0 ? `(?:[.,](\\d{1,${decimals}}))?` : "";
78
+ return [new RegExp(`^(\\d+)${fraction}$`), ...GROUPS.map((group) => {
79
+ const decimal = decimals > 0 ? `(?:${group === "," ? "\\." : group === "\\." ? "," : "[.,]"}(\\d{1,${decimals}}))?` : "";
80
+ return new RegExp(`^(\\d{1,3}(?:${group}\\d{3})+)${decimal}$`);
81
+ })];
82
+ }
83
+ /**
84
+ * Reads an amount typed by a person and returns it as decimal text with exactly the currency's decimals,
85
+ * ready to send to the server. Accepts an optional symbol or code of that currency (any case) and the three ways
86
+ * amounts are written in the region: `1,234.50`, `1.234,50` and `1 234,50`. A separator followed by one or two
87
+ * digits at the end is the decimal one; the others must all be the same and group exactly three digits, so
88
+ * `12.345` is twelve thousand. Negative amounts are rejected.
89
+ *
90
+ * @returns The normalized amount, or `null` when the text is not a valid amount in that currency.
91
+ * @throws {RangeError} When the currency is not supported.
92
+ * @example parseMoney('C$ 1,250.50', 'NIO') // "1250.50"
93
+ * @example parseMoney('₡1.234,5', 'CRC') // "1234.50"
94
+ * @example parseMoney('12.345', 'NIO') // "12345.00"
95
+ * @example parseMoney('$20', 'NIO') // null, symbol of another currency
96
+ */
97
+ function parseMoney(input, currencyCode) {
98
+ const target = require_require.requireCurrency(currencyCode);
99
+ if (typeof input !== "string" || input.length > MAX_INPUT_LENGTH) return null;
100
+ let text = input.trim();
101
+ for (const label of [target.code, target.symbol]) {
102
+ const prefix = new RegExp(`^${escapeRegExp(label)}[${SPACES}]*`, "i");
103
+ if (prefix.test(text)) {
104
+ text = text.replace(prefix, "");
105
+ break;
106
+ }
107
+ }
108
+ const match = amountPatterns(target.decimals).map((pattern) => pattern.exec(text)).find((result) => result !== null);
109
+ if (!match) return null;
110
+ const integer = (match[1] ?? "").replace(/\D/g, "").replace(/^0+(?=\d)/, "");
111
+ const fraction = match[2] ?? "";
112
+ if (integer.length > 30) return null;
113
+ return target.decimals > 0 ? `${integer}.${fraction.padEnd(target.decimals, "0")}` : integer;
114
+ }
115
+ /**
116
+ * Converts an amount to an integer count of the currency's minor unit (cents), rounding like {@link formatMoney}.
117
+ *
118
+ * @throws {RangeError} When the currency is not supported, the amount is not a decimal, or the result is not a safe integer.
119
+ * @example toMinorUnits('12.34', 'USD') // 1234
120
+ */
121
+ function toMinorUnits(amount, currencyCode) {
122
+ const target = require_require.requireCurrency(currencyCode);
123
+ const { negative, integer, fraction } = round(toDecimal(amount), target.decimals);
124
+ const minor = Number(`${integer}${fraction}`);
125
+ if (!Number.isSafeInteger(minor)) throw new RangeError("Monto demasiado grande para unidades menores.");
126
+ return negative ? -minor : minor;
127
+ }
128
+ /**
129
+ * Converts an integer count of minor units back to decimal text.
130
+ *
131
+ * @throws {RangeError} When the currency is not supported or `minor` is not a safe integer.
132
+ * @example fromMinorUnits(1234, 'USD') // "12.34"
133
+ */
134
+ function fromMinorUnits(minor, currencyCode) {
135
+ const target = require_require.requireCurrency(currencyCode);
136
+ if (!Number.isSafeInteger(minor)) throw new RangeError("Las unidades menores tienen que ser un entero seguro.");
137
+ const digits = Math.abs(minor).toString().padStart(target.decimals + 1, "0");
138
+ const integer = digits.slice(0, digits.length - target.decimals);
139
+ const fraction = target.decimals > 0 ? `.${digits.slice(-target.decimals)}` : "";
140
+ return `${minor < 0 ? "-" : ""}${integer}${fraction}`;
141
+ }
142
+ /**
143
+ * Formats an amount while it is being typed, for the value of a text field. Keeps digits and the first `.` as the
144
+ * decimal point, groups thousands with `,`, and cuts the decimals the currency does not have.
145
+ *
146
+ * @throws {RangeError} When the currency is not supported.
147
+ * @example formatMoneyInput('1250.5', 'NIO') // { text: '1,250.5', amount: '1250.50' }
148
+ * @example formatMoneyInput('.', 'NIO') // { text: '0.', amount: '0.00' }
149
+ */
150
+ function formatMoneyInput(text, currencyCode) {
151
+ const target = require_require.requireCurrency(currencyCode);
152
+ const typed = typeof text === "string" ? text.slice(0, MAX_INPUT_LENGTH) : "";
153
+ const point = typed.indexOf(".");
154
+ const hasPoint = point >= 0 && target.decimals > 0;
155
+ const integerDigits = (hasPoint ? typed.slice(0, point) : typed).replace(/\D/g, "");
156
+ const fraction = hasPoint ? typed.slice(point + 1).replace(/\D/g, "").slice(0, target.decimals) : "";
157
+ if (!integerDigits && !hasPoint) return {
158
+ text: "",
159
+ amount: null
160
+ };
161
+ const integer = (integerDigits.replace(/^0+(?=\d)/, "") || "0").slice(0, 30);
162
+ return {
163
+ text: `${group(integer, target.groupSeparator)}${hasPoint ? `${target.decimalSeparator}${fraction}` : ""}`,
164
+ amount: target.decimals > 0 ? `${integer}.${fraction.padEnd(target.decimals, "0")}` : integer
165
+ };
166
+ }
167
+ exports.MAX_INTEGER_DIGITS = MAX_INTEGER_DIGITS;
168
+ exports.formatMoney = formatMoney;
169
+ exports.formatMoneyInput = formatMoneyInput;
170
+ exports.fromMinorUnits = fromMinorUnits;
171
+ exports.parseMoney = parseMoney;
172
+ exports.toMinorUnits = toMinorUnits;