@mdgascar/ariary 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -24,9 +24,11 @@ var FRANC_SYMBOL = "Fmg";
24
24
  var FRANCS_PER_ARIARY = 5;
25
25
  var FRANC_DIVISION_FACTOR = 2;
26
26
  var MIN_AMOUNT = 0;
27
+ var MAX_TEXT_LENGTH = 100;
28
+ var MAX_READ_LENGTH = 329;
27
29
 
28
30
  // src/generated/errors.ts
29
- var SPEC_VERSION = "0.8.0";
31
+ var SPEC_VERSION = "0.9.0";
30
32
  var MdgError = class extends Error {
31
33
  /** Always `'MdgError'`. */
32
34
  name = "MdgError";
@@ -56,27 +58,12 @@ var MdgError = class extends Error {
56
58
  }
57
59
  };
58
60
 
59
- // src/amount.ts
60
- var MAX_AMOUNT = Number.MAX_SAFE_INTEGER;
61
- function assertAmount(value) {
62
- if (typeof value !== "number" || !Number.isFinite(value)) {
63
- throw new MdgError("INVALID_TYPE", "Amounts are finite numbers.");
64
- }
65
- assertInRange(value);
66
- }
67
- function assertInRange(value) {
68
- if (value < MIN_AMOUNT || value > MAX_AMOUNT) {
69
- throw new MdgError(
70
- "OUT_OF_RANGE",
71
- `Amounts go from ${String(MIN_AMOUNT)} to ${String(MAX_AMOUNT)}.`
72
- );
73
- }
74
- }
75
-
76
61
  // src/decimal.ts
77
62
  var DECIMAL_POINT = ".";
78
63
  var ZERO = "0";
79
64
  var NEGATIVE_EXPONENT = /^(\d)(?:\.(\d+))?e-(\d+)$/;
65
+ var LEADING_ZEROS = /^0+(?=\d)/;
66
+ var TRAILING_DECIMAL_ZEROS = /\.?0+$/;
80
67
  function plainDecimal(value) {
81
68
  const text = String(value);
82
69
  const match = NEGATIVE_EXPONENT.exec(text);
@@ -84,38 +71,107 @@ function plainDecimal(value) {
84
71
  const [, lead = "", rest = "", exponent = ""] = match;
85
72
  return `0${DECIMAL_POINT}${ZERO.repeat(Number(exponent) - 1)}${lead}${rest}`;
86
73
  }
87
- function toScaled(value) {
88
- const [whole = "", decimals = ""] = plainDecimal(value).split(DECIMAL_POINT);
74
+ function toScaled(digits) {
75
+ const [whole = "", decimals = ""] = digits.split(DECIMAL_POINT);
89
76
  return { units: BigInt(`${whole}${decimals}`), places: decimals.length };
90
77
  }
91
- function toNumber({ units, places }) {
78
+ function toDigits({ units, places }) {
92
79
  const digits = units.toString().padStart(places + 1, ZERO);
93
80
  const point = digits.length - places;
94
- return Number(`${digits.slice(0, point)}${DECIMAL_POINT}${digits.slice(point)}`);
81
+ const whole = digits.slice(0, point).replace(LEADING_ZEROS, "");
82
+ if (places === 0) return whole;
83
+ return `${whole}${DECIMAL_POINT}${digits.slice(point)}`.replace(TRAILING_DECIMAL_ZEROS, "");
84
+ }
85
+ function multiplyExact(digits, factor) {
86
+ const { units, places } = toScaled(digits);
87
+ return toDigits({ units: units * BigInt(factor), places });
88
+ }
89
+ function divideExact(digits, divisionFactor) {
90
+ const { units, places } = toScaled(digits);
91
+ return toDigits({ units: units * BigInt(divisionFactor), places: places + 1 });
92
+ }
93
+
94
+ // src/amount.ts
95
+ var MAX_AMOUNT = Number.MAX_SAFE_INTEGER;
96
+ var RESULT_KINDS = /* @__PURE__ */ new Set(["number", "text"]);
97
+ var DECIMAL_TEXT = /^[0-9]+(?:\.[0-9]+)?$/;
98
+ var LEADING_ZEROS2 = /^0+(?=\d)/;
99
+ var TRAILING_DECIMAL_ZEROS2 = /\.?0+$/;
100
+ var POINT = ".";
101
+ function canonical(text) {
102
+ const whole = text.replace(LEADING_ZEROS2, "");
103
+ return whole.includes(POINT) ? whole.replace(TRAILING_DECIMAL_ZEROS2, "") : whole;
104
+ }
105
+ function assertInRange(value) {
106
+ if (value < MIN_AMOUNT || value > MAX_AMOUNT) {
107
+ throw new MdgError(
108
+ "OUT_OF_RANGE",
109
+ `Amounts go from ${String(MIN_AMOUNT)} to ${String(MAX_AMOUNT)}.`
110
+ );
111
+ }
95
112
  }
96
- function multiplyExact(value, factor) {
97
- const { units, places } = toScaled(value);
98
- return toNumber({ units: units * BigInt(factor), places });
113
+ function amountDigits(value) {
114
+ if (typeof value === "string") {
115
+ if (value.length > MAX_TEXT_LENGTH || !DECIMAL_TEXT.test(value)) {
116
+ throw new MdgError(
117
+ "INVALID_FORMAT",
118
+ `Amount text is digits with an optional .decimals, at most ${String(MAX_TEXT_LENGTH)} characters.`
119
+ );
120
+ }
121
+ return canonical(value);
122
+ }
123
+ if (typeof value !== "number" || !Number.isFinite(value)) {
124
+ throw new MdgError("INVALID_TYPE", "Amounts are finite numbers or decimal text.");
125
+ }
126
+ assertInRange(value);
127
+ return plainDecimal(value);
128
+ }
129
+ function resultKind(options) {
130
+ if (typeof options !== "object" || options === null) return void 0;
131
+ const { as = "number" } = options;
132
+ return RESULT_KINDS.has(as) ? as : void 0;
133
+ }
134
+ function exactNumber(digits) {
135
+ const value = Number(digits);
136
+ if (value <= MAX_AMOUNT && plainDecimal(value) === digits) return { success: true, data: value };
137
+ return {
138
+ success: false,
139
+ error: new MdgError(
140
+ "PRECISION_LOSS",
141
+ `${digits} does not fit a number exactly; pass { as: 'text' } for the exact digits.`
142
+ )
143
+ };
99
144
  }
100
- function divideExact(value, divisionFactor) {
101
- const { units, places } = toScaled(value);
102
- return toNumber({ units: units * BigInt(divisionFactor), places: places + 1 });
145
+ function amountResult(digits, kind) {
146
+ if (kind === "text") return digits;
147
+ const result = exactNumber(digits);
148
+ if (!result.success) throw result.error;
149
+ return result.data;
103
150
  }
104
151
 
105
152
  // src/convert.ts
106
153
  function spellAriary(amount, options = {}) {
107
- if (typeof amount !== "string") assertAmount(amount);
154
+ if (typeof amount !== "string") amountDigits(amount);
108
155
  return `${spell(amount, options)} ${CURRENCY_WORD}`;
109
156
  }
110
- function fmgToAriary(francs) {
111
- assertAmount(francs);
112
- return divideExact(francs, FRANC_DIVISION_FACTOR);
157
+ function kindFor(options) {
158
+ const kind = resultKind(options);
159
+ if (kind === void 0) throw new MdgError("INVALID_TYPE", "as is 'number' or 'text'.");
160
+ return kind;
113
161
  }
114
- function ariaryToFmg(amount) {
115
- assertAmount(amount);
116
- const francs = multiplyExact(amount, FRANCS_PER_ARIARY);
117
- assertInRange(francs);
118
- return francs;
162
+ function fmgToAriary(francs, options = {}) {
163
+ const digits = amountDigits(francs);
164
+ return amountResult(
165
+ divideExact(digits, FRANC_DIVISION_FACTOR),
166
+ kindFor(options)
167
+ );
168
+ }
169
+ function ariaryToFmg(amount, options = {}) {
170
+ const digits = amountDigits(amount);
171
+ return amountResult(
172
+ multiplyExact(digits, FRANCS_PER_ARIARY),
173
+ kindFor(options)
174
+ );
119
175
  }
120
176
 
121
177
  // src/separators.ts
@@ -156,20 +212,18 @@ function layoutFor(options) {
156
212
  const grouping = groupingFor(formatGroupingId(options), decimal);
157
213
  return { grouping, decimal, symbolAfter: symbolPosition === "after" };
158
214
  }
159
- function layOut(amount, symbol, options) {
215
+ function layOut(digits, symbol, options) {
160
216
  const layout = layoutFor(options);
161
- const [whole = "", decimals] = plainDecimal(amount).split(DECIMAL_POINT2);
217
+ const [whole = "", decimals] = digits.split(DECIMAL_POINT2);
162
218
  const grouped = whole.replace(DIGIT_GROUP_BOUNDARY, layout.grouping);
163
- const digits = decimals === void 0 ? grouped : `${grouped}${layout.decimal}${decimals}`;
164
- return layout.symbolAfter ? `${digits}${SYMBOL_SEPARATOR}${symbol}` : `${symbol}${SYMBOL_SEPARATOR}${digits}`;
219
+ const text = decimals === void 0 ? grouped : `${grouped}${layout.decimal}${decimals}`;
220
+ return layout.symbolAfter ? `${text}${SYMBOL_SEPARATOR}${symbol}` : `${symbol}${SYMBOL_SEPARATOR}${text}`;
165
221
  }
166
222
  function formatAriary(amount, options = {}) {
167
- assertAmount(amount);
168
- return layOut(amount, CURRENCY_SYMBOL, options);
223
+ return layOut(amountDigits(amount), CURRENCY_SYMBOL, options);
169
224
  }
170
225
  function formatFmg(francs, options = {}) {
171
- assertAmount(francs);
172
- return layOut(francs, FRANC_SYMBOL, options);
226
+ return layOut(amountDigits(francs), FRANC_SYMBOL, options);
173
227
  }
174
228
 
175
229
  // src/read-digits.ts
@@ -241,44 +295,42 @@ function readDigits(text, separators) {
241
295
  }
242
296
 
243
297
  // src/parse.ts
244
- var PARSE_OPTION_KEYS = /* @__PURE__ */ new Set(["grouping", "decimal"]);
245
- var MAX_INPUT_LENGTH = 32;
298
+ var PARSE_OPTION_KEYS = /* @__PURE__ */ new Set(["grouping", "decimal", "as"]);
299
+ var RESULT_KINDS2 = /* @__PURE__ */ new Set(["number", "text"]);
246
300
  function failure(code, message) {
247
301
  return { success: false, error: new MdgError(code, message) };
248
302
  }
249
- function safeReadSeparators(options) {
303
+ function safeReadOptions(options) {
250
304
  try {
251
- return readSeparatorsFor(options);
305
+ return readOptionsFor(options);
252
306
  } catch (error) {
253
307
  return error;
254
308
  }
255
309
  }
256
- function readSeparatorsFor(options) {
310
+ function readOptionsFor(options) {
257
311
  assertOptionsObject(options);
258
312
  if (Object.keys(options).some((key) => !PARSE_OPTION_KEYS.has(key))) {
259
- throw new MdgError("INVALID_TYPE", "Reading takes only the grouping and decimal options.");
313
+ throw new MdgError("INVALID_TYPE", "Reading takes only the grouping, decimal and as options.");
260
314
  }
261
- const separators = options;
315
+ const { as: kind = "number", ...separators } = options;
316
+ if (!RESULT_KINDS2.has(kind)) throw new MdgError("INVALID_TYPE", "as is 'number' or 'text'.");
262
317
  const decimal = decimalFor(separators);
263
318
  const grouping = separators.grouping === void 0 ? void 0 : groupingFor(separators.grouping, decimal);
264
- return { grouping: readableGrouping(grouping, decimal), decimal };
319
+ return { grouping: readableGrouping(grouping, decimal), decimal, kind };
265
320
  }
266
321
  function safeParseAriary(text, options = {}) {
267
322
  if (typeof text !== "string") return failure("INVALID_TYPE", "Expected the amount as text.");
268
- const separators = safeReadSeparators(options);
269
- if (separators instanceof MdgError) return { success: false, error: separators };
270
- if (text.length > MAX_INPUT_LENGTH) {
271
- return failure("INVALID_FORMAT", `Amounts are at most ${String(MAX_INPUT_LENGTH)} characters.`);
323
+ const read = safeReadOptions(options);
324
+ if (read instanceof MdgError) return { success: false, error: read };
325
+ if (text.length > MAX_READ_LENGTH) {
326
+ return failure("INVALID_FORMAT", `Amounts are at most ${String(MAX_READ_LENGTH)} characters.`);
272
327
  }
273
- const digits = readDigits(text, separators);
328
+ const digits = readDigits(text, read);
274
329
  if (digits === void 0) {
275
330
  return failure("INVALID_FORMAT", "Expected an amount such as Ar 1 500 or Ar 1 500,50.");
276
331
  }
277
- const amount = Number(digits);
278
- if (amount > MAX_AMOUNT) {
279
- return failure("OUT_OF_RANGE", `Amounts go up to ${String(MAX_AMOUNT)}.`);
280
- }
281
- return { success: true, data: amount };
332
+ const exact = canonical(digits);
333
+ return read.kind === "text" ? { success: true, data: exact } : exactNumber(exact);
282
334
  }
283
335
  function parseAriary(text, options = {}) {
284
336
  const result = safeParseAriary(text, options);
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/generated/data.ts","../src/generated/errors.ts","../src/amount.ts","../src/decimal.ts","../src/convert.ts","../src/separators.ts","../src/format.ts","../src/read-digits.ts","../src/parse.ts"],"names":["DECIMAL_POINT"],"mappings":";;;;;AAKO,IAAM,eAAA,GAAkB,IAAA;AAGxB,IAAM,aAAA,GAAgB,QAAA;AAGtB,IAAM,gBAAA,GAAmB,MAAA;AAGzB,IAAM,UAAA,GAAa,CAAA;AAMnB,IAAM,gBAAA,uBAA4D,GAAA,CAGvE;AAAA,EACA,CAAC,SAAS,MAAQ,CAAA;AAAA,EAClB,CAAC,OAAO,GAAG,CAAA;AAAA,EACX,CAAC,SAAS,GAAG;AACf,CAAC,CAAA;AAGM,IAAM,gBAAA,GAAmB,OAAA;AAMzB,IAAM,kBAAA,uBAA6D,GAAA,CAGxE;AAAA,EACA,CAAC,SAAS,GAAG,CAAA;AAAA,EACb,CAAC,OAAO,GAAG;AACb,CAAC,CAAA;AAGM,IAAM,eAAA,GAAkB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A,CAAO,IAAA,GAAO,MAAA;AACxC","file":"index.js","sourcesContent":["// GENERATED — edit spec/ instead. Run `just codegen` to refresh.\n\n// From spec/modules/ariary/data.yaml, spec 0.8.0.\n\n/** @internal */\nexport const CURRENCY_SYMBOL = 'Ar' as const;\n\n/** @internal */\nexport const CURRENCY_WORD = 'ariary' as const;\n\n/** @internal */\nexport const SYMBOL_SEPARATOR = '\\u00a0' as const;\n\n/** @internal */\nexport const GROUP_SIZE = 3 as const;\n\n/** Thousand separator used by {@link formatAriary}: `space` (default) or `dot`. */\nexport type AriaryGrouping = 'space' | 'dot' | 'comma';\n\n/** @internal Grouping option → separator character; the first entry is the default. */\nexport const GROUP_SEPARATORS: ReadonlyMap<AriaryGrouping, string> = new Map<\n AriaryGrouping,\n string\n>([\n ['space', '\\u00a0'],\n ['dot', '.'],\n ['comma', ','],\n]);\n\n/** @internal */\nexport const DEFAULT_GROUPING = 'space' as const;\n\n/** Decimal separator used by {@link formatAriary} and the parsers: `comma` (default) or `dot`. */\nexport type AriaryDecimal = 'comma' | 'dot';\n\n/** @internal Decimal option → separator character; the first entry is the default. */\nexport const DECIMAL_SEPARATORS: ReadonlyMap<AriaryDecimal, string> = new Map<\n AriaryDecimal,\n string\n>([\n ['comma', ','],\n ['dot', '.'],\n]);\n\n/** @internal */\nexport const DEFAULT_DECIMAL = 'comma' as const;\n\n/** @internal */\nexport const READABLE_SEPARATORS = [' ', '\\u00a0', '\\u202f', '.'] as const;\n\n/** @internal Lower-cased, longest first. */\nexport const CURRENCY_TOKENS = ['ariary', 'mga', 'ar'] as const;\n\n/** @internal */\nexport const FRANC_SYMBOL = 'Fmg' as const;\n\n/** @internal */\nexport const FRANCS_PER_ARIARY = 5 as const;\n\n/** @internal 10 ÷ FRANCS_PER_ARIARY. */\nexport const FRANC_DIVISION_FACTOR = 2 as const;\n\n/** @internal */\nexport const MIN_AMOUNT = 0 as const;\n","// GENERATED — edit spec/ instead. Run `just codegen` to refresh.\n\n/** Version of the shared spec this code was generated from. */\nexport const SPEC_VERSION = '0.8.0';\n\n/**\n * Error code shared by every mdg-utils language port.\n *\n * - `INVALID_TYPE`: The input is not of the accepted type (for example a string or a non-integer where an integer is expected).\n * - `OUT_OF_RANGE`: The input has the right type but lies outside the supported range.\n * - `INVALID_FORMAT`: The input text cannot be read as a value of this module (wrong characters or wrong length).\n * - `UNKNOWN_OPERATOR`: The phone number is well formed but its operator code is not assigned to a mobile operator.\n */\nexport type ErrorCode = 'INVALID_TYPE' | 'OUT_OF_RANGE' | 'INVALID_FORMAT' | 'UNKNOWN_OPERATOR';\n\n/**\n * Outcome of a `safeParse…` function: the value, or the error that would have been thrown.\n *\n * @example\n * ```ts\n * const result = safeParsePhone(input);\n * if (result.success) console.log(result.data);\n * else console.log(result.error.code);\n * ```\n */\nexport type SafeParseResult<T> =\n | { readonly success: true; readonly data: T }\n | { readonly success: false; readonly error: MdgError };\n\n/**\n * Error thrown by mdg-utils functions. Check `code`, which is the same in every language.\n *\n * @example\n * ```ts\n * try {\n * spell(-1);\n * } catch (error) {\n * if (error instanceof MdgError && error.code === 'OUT_OF_RANGE') {\n * // handle it\n * }\n * }\n * ```\n */\nexport class MdgError extends Error {\n /** Always `'MdgError'`. */\n override readonly name = 'MdgError';\n /** Why the call failed; the same code in every language. */\n readonly code: ErrorCode;\n\n /**\n * Creates an error with a shared spec code.\n *\n * @param code - Shared spec error code.\n * @param message - Human-readable explanation, in English.\n */\n constructor(code: ErrorCode, message: string) {\n super(message);\n this.code = code;\n }\n\n /**\n * Makes `instanceof MdgError` true for errors from any mdg-utils package or build.\n *\n * @remarks Each package, and its ESM and CommonJS builds, has its own copy of this class,\n * so the check looks at the error's shape instead of its prototype chain.\n *\n * @param value - Any value, usually a caught error.\n * @returns `true` when `value` is an mdg-utils error.\n */\n static override [Symbol.hasInstance](value: unknown): boolean {\n return value instanceof Error && value.name === 'MdgError' && 'code' in value;\n }\n}\n","import { MIN_AMOUNT } from './generated/data.ts';\nimport { MdgError } from './generated/errors.ts';\n\n/** @internal The spec sets no maximum: amounts stop where a number stops being exact. */\nexport const MAX_AMOUNT = Number.MAX_SAFE_INTEGER;\n\n/**\n * @internal Validates an amount, whole or decimal, at the public boundary.\n *\n * @param value - The amount the caller passed.\n */\nexport function assertAmount(value: unknown): asserts value is number {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new MdgError('INVALID_TYPE', 'Amounts are finite numbers.');\n }\n assertInRange(value);\n}\n\n/**\n * @internal Throws OUT_OF_RANGE for a number below 0 or above {@link MAX_AMOUNT}.\n *\n * @param value - A finite number.\n */\nexport function assertInRange(value: number): void {\n if (value < MIN_AMOUNT || value > MAX_AMOUNT) {\n throw new MdgError(\n 'OUT_OF_RANGE',\n `Amounts go from ${String(MIN_AMOUNT)} to ${String(MAX_AMOUNT)}.`,\n );\n }\n}\n","// Exact decimal helpers. Amounts are number values, but money must never show binary rounding\n// artefacts (0.07 × 5 is 0.35000000000000003 in floating point), so these work on the decimal\n// digits of the value's shortest exact form.\n\nconst DECIMAL_POINT = '.';\nconst ZERO = '0';\n// String(value) of a small number, e.g. '1e-7' or '1.5e-10'.\nconst NEGATIVE_EXPONENT = /^(\\d)(?:\\.(\\d+))?e-(\\d+)$/;\n\n/**\n * @internal The shortest exact decimal form of a number, never in exponent notation.\n *\n * @param value - A non-negative finite number.\n * @returns Its digits: `1500.5` → `'1500.5'`, `1e-7` → `'0.0000001'`.\n */\nexport function plainDecimal(value: number): string {\n const text = String(value);\n const match = NEGATIVE_EXPONENT.exec(text);\n if (match === null) return text;\n const [, lead = '', rest = '', exponent = ''] = match;\n return `0${DECIMAL_POINT}${ZERO.repeat(Number(exponent) - 1)}${lead}${rest}`;\n}\n\ninterface Scaled {\n /** All the digits, as one integer. */\n readonly units: bigint;\n /** How many of them come after the point. */\n readonly places: number;\n}\n\nfunction toScaled(value: number): Scaled {\n const [whole = '', decimals = ''] = plainDecimal(value).split(DECIMAL_POINT);\n return { units: BigInt(`${whole}${decimals}`), places: decimals.length };\n}\n\nfunction toNumber({ units, places }: Scaled): number {\n const digits = units.toString().padStart(places + 1, ZERO);\n const point = digits.length - places;\n return Number(`${digits.slice(0, point)}${DECIMAL_POINT}${digits.slice(point)}`);\n}\n\n/**\n * @internal Multiplies exactly in decimal, then reads the result as the nearest number.\n *\n * @param value - A non-negative finite number.\n * @param factor - A whole multiplier.\n * @returns `value × factor`: `0.07 × 5` → `0.35`.\n */\nexport function multiplyExact(value: number, factor: number): number {\n const { units, places } = toScaled(value);\n return toNumber({ units: units * BigInt(factor), places });\n}\n\n/**\n * @internal Divides exactly by a divisor of 10: multiplies by `10 ÷ divisor`, then moves the\n * point one place left.\n *\n * @param value - A non-negative finite number.\n * @param divisionFactor - `10 ÷ divisor` (2 to divide by 5).\n * @returns `value ÷ divisor`: `7501 ÷ 5` → `1500.2`.\n */\nexport function divideExact(value: number, divisionFactor: number): number {\n const { units, places } = toScaled(value);\n return toNumber({ units: units * BigInt(divisionFactor), places: places + 1 });\n}\n","import { spell, type SpellOptions } from '@mdgascar/words';\nimport { CURRENCY_WORD, FRANC_DIVISION_FACTOR, FRANCS_PER_ARIARY } from './generated/data.ts';\nimport { assertAmount, assertInRange } from './amount.ts';\nimport { divideExact, multiplyExact } from './decimal.ts';\n\n/**\n * Writes an Ariary amount in Malagasy words.\n *\n * @param amount - Ariary from 0 to `Number.MAX_SAFE_INTEGER`, whole or decimal, or plain\n * decimal text such as `'2000000000000000.9'`, read exactly.\n * @param options - The words `system`: `standard` (default) or `traditional`.\n * @returns The amount in words followed by `ariary`; decimals follow `faingo`.\n * @throws {@link MdgError} `INVALID_TYPE`, `INVALID_FORMAT` (text) or `OUT_OF_RANGE`.\n *\n * @example\n * ```ts\n * spellAriary(1500); // 'dimanjato sy arivo ariary'\n * spellAriary(1500.5); // 'dimanjato sy arivo faingo dimy ariary'\n * spellAriary(30_000_000, { system: 'traditional' }); // 'telo safatsiroa ariary'\n * spellAriary('2000000000000000.9'); // 'roa tapitrisa lavitrisa faingo sivy ariary'\n * ```\n */\nexport function spellAriary(amount: number | string, options: SpellOptions = {}): string {\n // Text is checked by spell (rule 13); a number by the Ariary range.\n if (typeof amount !== 'string') assertAmount(amount);\n return `${spell(amount, options)} ${CURRENCY_WORD}`;\n}\n\n/**\n * Converts old Malagasy francs (FMG) to ariary: 5 FMG = 1 Ar, exactly in decimal.\n *\n * @param francs - Francs from 0 to `Number.MAX_SAFE_INTEGER`, whole or decimal.\n * @returns The amount in ariary: `7501` → `1500.2`.\n * @throws {@link MdgError} `INVALID_TYPE` if `francs` is not a finite number, `OUT_OF_RANGE` when\n * it is negative or above `Number.MAX_SAFE_INTEGER`.\n *\n * @example\n * ```ts\n * fmgToAriary(7500); // 1500\n * fmgToAriary(7501); // 1500.2\n * ```\n */\nexport function fmgToAriary(francs: number): number {\n assertAmount(francs);\n return divideExact(francs, FRANC_DIVISION_FACTOR);\n}\n\n/**\n * Converts ariary to old Malagasy francs (FMG): 1 Ar = 5 FMG, exactly in decimal.\n *\n * @param amount - Ariary from 0 up, whole or decimal.\n * @returns The amount in francs: `0.07` → `0.35`, never `0.35000000000000003`.\n * @throws {@link MdgError} `INVALID_TYPE` if `amount` is not a finite number, `OUT_OF_RANGE` when\n * it is negative or the francs would exceed `Number.MAX_SAFE_INTEGER`.\n *\n * @example\n * ```ts\n * ariaryToFmg(1500); // 7500\n * ariaryToFmg(0.07); // 0.35\n * ```\n */\nexport function ariaryToFmg(amount: number): number {\n assertAmount(amount);\n const francs = multiplyExact(amount, FRANCS_PER_ARIARY);\n assertInRange(francs);\n return francs;\n}\n","// Grouping and decimal options shared by formatting and reading. Every default is the Malagasy\n// way; the comma grouping and the decimal dot are opt-in for text in another convention.\nimport {\n DECIMAL_SEPARATORS,\n DEFAULT_DECIMAL,\n DEFAULT_GROUPING,\n GROUP_SEPARATORS,\n type AriaryDecimal,\n type AriaryGrouping,\n} from './generated/data.ts';\nimport { MdgError } from './generated/errors.ts';\n\n/**\n * Separator options for formatting and reading amounts.\n *\n * @example\n * ```ts\n * const english: AriarySeparatorOptions = { grouping: 'comma', decimal: 'dot' };\n * ```\n */\nexport interface AriarySeparatorOptions {\n /** Thousand separator: `space` (default), `dot`, or `comma` for another convention. */\n readonly grouping?: AriaryGrouping;\n /** Decimal separator: `comma` (default), or `dot` for another convention. */\n readonly decimal?: AriaryDecimal;\n}\n\n/**\n * @internal Throws INVALID_TYPE unless `options` is an object.\n *\n * @param options - What the caller passed as options.\n */\nexport function assertOptionsObject(options: unknown): asserts options is Record<string, unknown> {\n if (typeof options !== 'object' || options === null) {\n throw new MdgError('INVALID_TYPE', 'Options must be an object.');\n }\n}\n\n/**\n * @internal Reads the `decimal` option.\n *\n * @param options - The caller's options.\n * @returns The decimal character, a comma by default.\n */\nexport function decimalFor(options: AriarySeparatorOptions): string {\n const decimal = DECIMAL_SEPARATORS.get(options.decimal ?? DEFAULT_DECIMAL);\n if (decimal === undefined) throw new MdgError('INVALID_TYPE', 'decimal is comma or dot.');\n return decimal;\n}\n\n/**\n * @internal Reads a `grouping` option and checks it against the decimal character.\n *\n * @param id - The grouping option.\n * @param decimal - The decimal character in use.\n * @returns The grouping character.\n */\nexport function groupingFor(id: AriaryGrouping, decimal: string): string {\n const grouping = GROUP_SEPARATORS.get(id);\n if (grouping === undefined)\n throw new MdgError('INVALID_TYPE', 'grouping is space, dot or comma.');\n if (grouping === decimal) {\n throw new MdgError('INVALID_TYPE', 'grouping and decimal must be different characters.');\n }\n return grouping;\n}\n\n/**\n * @internal The grouping option for formatting.\n *\n * @param options - The caller's options.\n * @returns The one given, or the Malagasy default.\n */\nexport function formatGroupingId(options: AriarySeparatorOptions): AriaryGrouping {\n return options.grouping ?? DEFAULT_GROUPING;\n}\n","import { CURRENCY_SYMBOL, FRANC_SYMBOL, GROUP_SIZE, SYMBOL_SEPARATOR } from './generated/data.ts';\nimport { MdgError } from './generated/errors.ts';\nimport { assertAmount } from './amount.ts';\nimport { plainDecimal } from './decimal.ts';\nimport {\n assertOptionsObject,\n decimalFor,\n formatGroupingId,\n groupingFor,\n type AriarySeparatorOptions,\n} from './separators.ts';\n\n/**\n * Where the currency symbol goes: `before` (default, `Ar 1 500`) or `after` (`1 500 Ar`).\n *\n * @example\n * ```ts\n * const position: AriarySymbolPosition = 'after';\n * ```\n */\nexport type AriarySymbolPosition = 'before' | 'after';\n\n/**\n * Layout options for {@link formatAriary} and {@link formatFmg}.\n *\n * @example\n * ```ts\n * const options: AriaryFormatOptions = { grouping: 'dot', symbolPosition: 'after' };\n * ```\n */\nexport interface AriaryFormatOptions extends AriarySeparatorOptions {\n /** Symbol `before` (default) or `after` the amount. */\n readonly symbolPosition?: AriarySymbolPosition;\n}\n\nconst SYMBOL_POSITIONS: ReadonlySet<unknown> = new Set<AriarySymbolPosition>(['before', 'after']);\nconst DECIMAL_POINT = '.';\nconst DIGIT_GROUP_BOUNDARY = new RegExp(`\\\\B(?=(\\\\d{${String(GROUP_SIZE)}})+(?!\\\\d))`, 'g');\n\ninterface Layout {\n readonly grouping: string;\n readonly decimal: string;\n readonly symbolAfter: boolean;\n}\n\nfunction layoutFor(options: unknown): Layout {\n assertOptionsObject(options);\n const { symbolPosition = 'before' } = options as AriaryFormatOptions;\n if (!SYMBOL_POSITIONS.has(symbolPosition)) {\n throw new MdgError('INVALID_TYPE', 'symbolPosition is before or after.');\n }\n const decimal = decimalFor(options);\n const grouping = groupingFor(formatGroupingId(options), decimal);\n return { grouping, decimal, symbolAfter: symbolPosition === 'after' };\n}\n\n// Groups the whole part only; decimals follow a comma as they are, never grouped or rounded.\nfunction layOut(amount: number, symbol: string, options: AriaryFormatOptions): string {\n const layout = layoutFor(options);\n const [whole = '', decimals] = plainDecimal(amount).split(DECIMAL_POINT);\n const grouped = whole.replace(DIGIT_GROUP_BOUNDARY, layout.grouping);\n const digits = decimals === undefined ? grouped : `${grouped}${layout.decimal}${decimals}`;\n return layout.symbolAfter\n ? `${digits}${SYMBOL_SEPARATOR}${symbol}`\n : `${symbol}${SYMBOL_SEPARATOR}${digits}`;\n}\n\n/**\n * Writes an Ariary amount the Malagasy way: symbol `Ar`, digits grouped by no-break spaces.\n *\n * @param amount - Ariary from 0 to `Number.MAX_SAFE_INTEGER`, whole or decimal.\n * @param options - Optional `grouping` (`space`, `dot` or `comma`), `decimal` (`comma` or `dot`)\n * and `symbolPosition` (`before` or `after`). The defaults are the Malagasy way.\n * @returns The formatted amount, e.g. `Ar 1 500` or `Ar 1 500,5` (the spaces are U+00A0).\n * @throws {@link MdgError} `INVALID_TYPE` for a value that is not a finite number or unknown options,\n * `OUT_OF_RANGE` outside 0 to `Number.MAX_SAFE_INTEGER`.\n *\n * @example\n * ```ts\n * formatAriary(1500); // 'Ar 1 500'\n * formatAriary(1500, { grouping: 'dot', symbolPosition: 'after' }); // '1.500 Ar'\n * formatAriary(1500.5); // 'Ar 1 500,5'\n * ```\n */\nexport function formatAriary(amount: number, options: AriaryFormatOptions = {}): string {\n assertAmount(amount);\n return layOut(amount, CURRENCY_SYMBOL, options);\n}\n\n/**\n * Writes an amount in old Malagasy francs, with the same layout as {@link formatAriary}.\n *\n * @param francs - Francs from 0 to `Number.MAX_SAFE_INTEGER`, whole or decimal.\n * @param options - Same options as {@link formatAriary}.\n * @returns The formatted amount, e.g. `Fmg 7 500`.\n * @throws {@link MdgError} `INVALID_TYPE` or `OUT_OF_RANGE`, as {@link formatAriary}.\n *\n * @example\n * ```ts\n * formatFmg(7500); // 'Fmg 7 500'\n * ```\n */\nexport function formatFmg(francs: number, options: AriaryFormatOptions = {}): string {\n assertAmount(francs);\n return layOut(francs, FRANC_SYMBOL, options);\n}\n","// Reads the digits of an amount typed by a user: an optional currency token, then plain or\n// grouped digits, then optionally a decimal separator and the decimals.\nimport { CURRENCY_TOKENS, GROUP_SIZE, READABLE_SEPARATORS } from './generated/data.ts';\n\nconst SPACE = ' ';\nconst WHITESPACE = /\\s/;\nconst PLAIN_AMOUNT = /^(?:0|[1-9]\\d*)$/;\nconst DECIMALS = /^\\d+$/;\nconst NON_DIGITS = /\\D/g;\nconst REGEX_SPECIAL = /[\\\\^$.*+?()[\\]{}|-]/g;\nconst DECIMAL_POINT = '.';\n\n/** @internal What a reader accepts: grouping characters between digit groups, and the decimal one. */\nexport interface ReadSeparators {\n readonly grouping: readonly string[];\n readonly decimal: string;\n}\n\ntype Reader = (amount: string) => string | undefined;\n\nconst readers = new Map<string, Reader>();\n\nfunction isWhitespace(character: string): boolean {\n return WHITESPACE.test(character);\n}\n\nfunction escapeForClass(character: string): string {\n return character.replace(REGEX_SPECIAL, '\\\\$&');\n}\n\n// One digit group of three after the first, repeating the same separator: '1 500 000'.\nfunction groupedPattern(separatorClass: string): RegExp {\n const group = `\\\\d{${String(GROUP_SIZE)}}`;\n return new RegExp(\n `^[1-9]\\\\d{0,${String(GROUP_SIZE - 1)}}([${separatorClass}])${group}(?:\\\\1${group})*$`,\n );\n}\n\n// Spaces of every kind count as one separator: they are turned into a plain space first.\nfunction wholeReader(grouping: readonly string[]): Reader {\n const spaces = grouping.filter(isWhitespace);\n const normalizeSpaces = new RegExp(`[${spaces.map(escapeForClass).join('')}]`, 'g');\n const others = grouping.filter((character) => !isWhitespace(character));\n const separators = [...(spaces.length > 0 ? [SPACE] : []), ...others];\n const grouped = groupedPattern(separators.map(escapeForClass).join(''));\n return (whole) => {\n const normalized = spaces.length > 0 ? whole.replace(normalizeSpaces, SPACE) : whole;\n const isAmount = PLAIN_AMOUNT.test(normalized) || grouped.test(normalized);\n return isAmount ? normalized.replace(NON_DIGITS, '') : undefined;\n };\n}\n\nfunction makeReader({ grouping, decimal }: ReadSeparators): Reader {\n const wholeDigits = wholeReader(grouping);\n return (amount) => {\n const [whole = '', decimals, extra] = amount.split(decimal);\n if (extra !== undefined) return undefined;\n const digits = wholeDigits(whole);\n if (digits === undefined || decimals === undefined) return digits;\n return DECIMALS.test(decimals) ? `${digits}${DECIMAL_POINT}${decimals}` : undefined;\n };\n}\n\nfunction readerFor(separators: ReadSeparators): Reader {\n const key = `${separators.grouping.join('')}|${separators.decimal}`;\n const cached = readers.get(key);\n if (cached !== undefined) return cached;\n const reader = makeReader(separators);\n readers.set(key, reader);\n return reader;\n}\n\nfunction stripCurrency(text: string): string | undefined {\n const lower = text.toLowerCase();\n const prefix = CURRENCY_TOKENS.find((token) => lower.startsWith(token)) ?? '';\n const suffix = CURRENCY_TOKENS.find((token) => lower.endsWith(token)) ?? '';\n if (prefix !== '' && suffix !== '') return undefined;\n return text.slice(prefix.length, text.length - suffix.length).trim();\n}\n\n/**\n * @internal The grouping characters a reader accepts.\n *\n * @param grouping - The chosen grouping character, or undefined for every Malagasy one.\n * @param decimal - The decimal character, which never counts as grouping.\n * @returns Every Malagasy separator (spaces and dot) when none is chosen; else the chosen one,\n * a space standing for every kind of space.\n */\nexport function readableGrouping(grouping: string | undefined, decimal: string): string[] {\n if (grouping === undefined) return READABLE_SEPARATORS.filter((value) => value !== decimal);\n return isWhitespace(grouping) ? READABLE_SEPARATORS.filter(isWhitespace) : [grouping];\n}\n\n/**\n * Extracts the digits of an amount such as `Ar 1 500`, `1.500 Ar`, `MGA 1500` or `1 500,50`.\n *\n * @param text - An amount as typed by a user.\n * @param separators - The grouping and decimal characters to accept.\n * @returns The digits with a `.` before any decimals (`'1500'`, `'1500.50'`), or `undefined`\n * when the text is not an amount.\n *\n * @example\n * ```ts\n * readDigits('1 500,50', { grouping: [' ', '.'], decimal: ',' }); // '1500.50'\n * ```\n */\nexport function readDigits(text: string, separators: ReadSeparators): string | undefined {\n const amount = stripCurrency(text.trim());\n if (amount === undefined) return undefined;\n return readerFor(separators)(amount);\n}\n","import { MAX_AMOUNT } from './amount.ts';\nimport { MdgError, type ErrorCode, type SafeParseResult } from './generated/errors.ts';\nimport { readableGrouping, readDigits, type ReadSeparators } from './read-digits.ts';\nimport {\n assertOptionsObject,\n decimalFor,\n groupingFor,\n type AriarySeparatorOptions,\n} from './separators.ts';\n\n/**\n * Options for reading amounts: which `grouping` and `decimal` separators the text uses.\n * Without `grouping`, every Malagasy one is accepted (spaces or dot); `decimal` defaults to a\n * comma. Say so for text in another convention: `{ grouping: 'comma', decimal: 'dot' }`.\n *\n * @example\n * ```ts\n * const english: AriaryParseOptions = { grouping: 'comma', decimal: 'dot' };\n * ```\n */\nexport type AriaryParseOptions = AriarySeparatorOptions;\n\nconst PARSE_OPTION_KEYS: ReadonlySet<string> = new Set(['grouping', 'decimal']);\n\n// Bounded so a parser that reads user input never scans unbounded text.\nconst MAX_INPUT_LENGTH = 32;\n\nfunction failure(code: ErrorCode, message: string): SafeParseResult<never> {\n return { success: false, error: new MdgError(code, message) };\n}\n\n// The parsers never throw for bad options either: the error comes back as a value.\nfunction safeReadSeparators(options: unknown): ReadSeparators | MdgError {\n try {\n return readSeparatorsFor(options);\n } catch (error) {\n return error as MdgError;\n }\n}\n\nfunction readSeparatorsFor(options: unknown): ReadSeparators {\n assertOptionsObject(options);\n if (Object.keys(options).some((key) => !PARSE_OPTION_KEYS.has(key))) {\n throw new MdgError('INVALID_TYPE', 'Reading takes only the grouping and decimal options.');\n }\n const separators = options as AriaryParseOptions;\n const decimal = decimalFor(separators);\n const grouping =\n separators.grouping === undefined ? undefined : groupingFor(separators.grouping, decimal);\n return { grouping: readableGrouping(grouping, decimal), decimal };\n}\n\n/**\n * Reads an Ariary amount without throwing.\n *\n * @param text - An amount such as `Ar 1 500`, `1.500 Ar`, `MGA 1500` or `1 500,50`.\n * @param options - Optional `grouping` and `decimal`; see {@link AriaryParseOptions}.\n * @returns `{ success: true, data }` with the amount, or `{ success: false, error }`.\n *\n * @example\n * ```ts\n * const result = safeParseAriary('1 500 Ar');\n * if (result.success) result.data; // 1500\n * ```\n */\nexport function safeParseAriary(\n text: unknown,\n options: AriaryParseOptions = {},\n): SafeParseResult<number> {\n if (typeof text !== 'string') return failure('INVALID_TYPE', 'Expected the amount as text.');\n const separators = safeReadSeparators(options);\n if (separators instanceof MdgError) return { success: false, error: separators };\n if (text.length > MAX_INPUT_LENGTH) {\n return failure('INVALID_FORMAT', `Amounts are at most ${String(MAX_INPUT_LENGTH)} characters.`);\n }\n const digits = readDigits(text, separators);\n if (digits === undefined) {\n return failure('INVALID_FORMAT', 'Expected an amount such as Ar 1 500 or Ar 1 500,50.');\n }\n const amount = Number(digits);\n if (amount > MAX_AMOUNT) {\n return failure('OUT_OF_RANGE', `Amounts go up to ${String(MAX_AMOUNT)}.`);\n }\n return { success: true, data: amount };\n}\n\n/**\n * Reads an Ariary amount written in any common way.\n *\n * @param text - An amount such as `Ar 1 500`, `1.500 Ar`, `MGA 1500` or `1 500,50`.\n * @param options - Optional `grouping` and `decimal`; see {@link AriaryParseOptions}.\n * @returns The amount, whole or decimal.\n * @throws {@link MdgError} `INVALID_TYPE` for non-strings or bad options, `INVALID_FORMAT` for text\n * that is not an amount (signs, a dot as decimal point by default), `OUT_OF_RANGE` above\n * `Number.MAX_SAFE_INTEGER`.\n *\n * @example\n * ```ts\n * parseAriary('Ar 1 500'); // 1500\n * parseAriary('1.500 Ar'); // 1500\n * parseAriary('1 500,50 Ar'); // 1500.5\n * parseAriary('1,500.50', { grouping: 'comma', decimal: 'dot' }); // 1500.5\n * ```\n */\nexport function parseAriary(text: string, options: AriaryParseOptions = {}): number {\n const result = safeParseAriary(text, options);\n if (!result.success) throw result.error;\n return result.data;\n}\n\n/**\n * Reads an Ariary amount, or gives `undefined` instead of throwing.\n *\n * Use {@link safeParseAriary} when you need to know why the text was rejected.\n *\n * @param text - An amount such as `Ar 1 500`, `1.500 Ar`, `MGA 1500` or `1 500,50`.\n * @param options - Optional `grouping` and `decimal`; see {@link AriaryParseOptions}.\n * @returns The amount, or `undefined` when {@link parseAriary} would throw.\n *\n * @example\n * ```ts\n * tryParseAriary('1.500 Ar'); // 1500\n * tryParseAriary('1.5'); // undefined\n * ```\n */\nexport function tryParseAriary(\n text: unknown,\n options: AriaryParseOptions = {},\n): number | undefined {\n const result = safeParseAriary(text, options);\n return result.success ? result.data : undefined;\n}\n"]}
1
+ {"version":3,"sources":["../src/generated/data.ts","../src/generated/errors.ts","../src/decimal.ts","../src/amount.ts","../src/convert.ts","../src/separators.ts","../src/format.ts","../src/read-digits.ts","../src/parse.ts"],"names":["LEADING_ZEROS","TRAILING_DECIMAL_ZEROS","DECIMAL_POINT","RESULT_KINDS"],"mappings":";;;;;AAKO,IAAM,eAAA,GAAkB,IAAA;AAGxB,IAAM,aAAA,GAAgB,QAAA;AAGtB,IAAM,gBAAA,GAAmB,MAAA;AAGzB,IAAM,UAAA,GAAa,CAAA;AAMnB,IAAM,gBAAA,uBAA4D,GAAA,CAGvE;AAAA,EACA,CAAC,SAAS,MAAQ,CAAA;AAAA,EAClB,CAAC,OAAO,GAAG,CAAA;AAAA,EACX,CAAC,SAAS,GAAG;AACf,CAAC,CAAA;AAGM,IAAM,gBAAA,GAAmB,OAAA;AAMzB,IAAM,kBAAA,uBAA6D,GAAA,CAGxE;AAAA,EACA,CAAC,SAAS,GAAG,CAAA;AAAA,EACb,CAAC,OAAO,GAAG;AACb,CAAC,CAAA;AAGM,IAAM,eAAA,GAAkB,OAAA;AAGxB,IAAM,mBAAA,GAAsB,CAAC,GAAA,EAAK,MAAA,EAAU,UAAU,GAAG,CAAA;AAGzD,IAAM,eAAA,GAAkB,CAAC,QAAA,EAAU,KAAA,EAAO,IAAI,CAAA;AAG9C,IAAM,YAAA,GAAe,KAAA;AAGrB,IAAM,iBAAA,GAAoB,CAAA;AAG1B,IAAM,qBAAA,GAAwB,CAAA;AAG9B,IAAM,UAAA,GAAa,CAAA;AAGnB,IAAM,eAAA,GAAkB,GAAA;AAGxB,IAAM,eAAA,GAAkB,GAAA;;;AClExB,IAAM,YAAA,GAAe;AAgDrB,IAAM,QAAA,GAAN,cAAuB,KAAA,CAAM;AAAA;AAAA,EAEhB,IAAA,GAAO,UAAA;AAAA;AAAA,EAEhB,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQT,WAAA,CAAY,MAAiB,OAAA,EAAiB;AAC5C,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAA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A,EAAM,KAAA,EAAM,GAAI,WAAA,CAAY,KAAK,CAAA;AAClF;AAoBO,SAAS,WAAA,CACd,IAAA,EACA,OAAA,GAA2D,EAAC,EACzC;AACnB,EAAA,MAAM,MAAA,GAAS,eAAA,CAAgB,IAAA,EAAM,OAAO,CAAA;AAC5C,EAAA,IAAI,CAAC,MAAA,CAAO,OAAA,EAAS,MAAM,MAAA,CAAO,KAAA;AAClC,EAAA,OAAO,MAAA,CAAO,IAAA;AAChB;AAiBO,SAAS,cAAA,CACd,IAAA,EACA,OAAA,GAA8B,EAAC,EACF;AAC7B,EAAA,MAAM,MAAA,GAAS,eAAA,CAAgB,IAAA,EAAM,OAAO,CAAA;AAC5C,EAAA,OAAO,MAAA,CAAO,OAAA,GAAU,MAAA,CAAO,IAAA,GAAO,MAAA;AACxC","file":"index.js","sourcesContent":["// GENERATED — edit spec/ instead. Run `just codegen` to refresh.\n\n// From spec/modules/ariary/data.yaml, spec 0.9.0.\n\n/** @internal */\nexport const CURRENCY_SYMBOL = 'Ar' as const;\n\n/** @internal */\nexport const CURRENCY_WORD = 'ariary' as const;\n\n/** @internal */\nexport const SYMBOL_SEPARATOR = '\\u00a0' as const;\n\n/** @internal */\nexport const GROUP_SIZE = 3 as const;\n\n/** Thousand separator used by {@link formatAriary}: `space` (default) or `dot`. */\nexport type AriaryGrouping = 'space' | 'dot' | 'comma';\n\n/** @internal Grouping option → separator character; the first entry is the default. */\nexport const GROUP_SEPARATORS: ReadonlyMap<AriaryGrouping, string> = new Map<\n AriaryGrouping,\n string\n>([\n ['space', '\\u00a0'],\n ['dot', '.'],\n ['comma', ','],\n]);\n\n/** @internal */\nexport const DEFAULT_GROUPING = 'space' as const;\n\n/** Decimal separator used by {@link formatAriary} and the parsers: `comma` (default) or `dot`. */\nexport type AriaryDecimal = 'comma' | 'dot';\n\n/** @internal Decimal option → separator character; the first entry is the default. */\nexport const DECIMAL_SEPARATORS: ReadonlyMap<AriaryDecimal, string> = new Map<\n AriaryDecimal,\n string\n>([\n ['comma', ','],\n ['dot', '.'],\n]);\n\n/** @internal */\nexport const DEFAULT_DECIMAL = 'comma' as const;\n\n/** @internal */\nexport const READABLE_SEPARATORS = [' ', '\\u00a0', '\\u202f', '.'] as const;\n\n/** @internal Lower-cased, longest first. */\nexport const CURRENCY_TOKENS = ['ariary', 'mga', 'ar'] as const;\n\n/** @internal */\nexport const FRANC_SYMBOL = 'Fmg' as const;\n\n/** @internal */\nexport const FRANCS_PER_ARIARY = 5 as const;\n\n/** @internal 10 ÷ FRANCS_PER_ARIARY. */\nexport const FRANC_DIVISION_FACTOR = 2 as const;\n\n/** @internal */\nexport const MIN_AMOUNT = 0 as const;\n\n/** @internal Longest decimal text taken as an amount. */\nexport const MAX_TEXT_LENGTH = 100 as const;\n\n/** @internal Longest text the parsers read. */\nexport const MAX_READ_LENGTH = 329 as const;\n","// GENERATED — edit spec/ instead. Run `just codegen` to refresh.\n\n/** Version of the shared spec this code was generated from. */\nexport const SPEC_VERSION = '0.9.0';\n\n/**\n * Error code shared by every mdg-utils language port.\n *\n * - `INVALID_TYPE`: The input is not of the accepted type (for example a string or a non-integer where an integer is expected).\n * - `OUT_OF_RANGE`: The input has the right type but lies outside the supported range.\n * - `INVALID_FORMAT`: The input text cannot be read as a value of this module (wrong characters or wrong length).\n * - `UNKNOWN_OPERATOR`: The phone number is well formed but its operator code is not assigned to an operator.\n * - `PRECISION_LOSS`: The value is exact in the text but the port's number type cannot hold it exactly; ask for the exact text instead.\n * - `AMBIGUOUS`: The text reads as more than one value, so none is chosen.\n */\nexport type ErrorCode =\n | 'INVALID_TYPE'\n | 'OUT_OF_RANGE'\n | 'INVALID_FORMAT'\n | 'UNKNOWN_OPERATOR'\n | 'PRECISION_LOSS'\n | 'AMBIGUOUS';\n\n/**\n * Outcome of a `safeParse…` function: the value, or the error that would have been thrown.\n *\n * @example\n * ```ts\n * const result = safeParsePhone(input);\n * if (result.success) console.log(result.data);\n * else console.log(result.error.code);\n * ```\n */\nexport type SafeParseResult<T> =\n | { readonly success: true; readonly data: T }\n | { readonly success: false; readonly error: MdgError };\n\n/**\n * Error thrown by mdg-utils functions. Check `code`, which is the same in every language.\n *\n * @example\n * ```ts\n * try {\n * spell(-1);\n * } catch (error) {\n * if (error instanceof MdgError && error.code === 'OUT_OF_RANGE') {\n * // handle it\n * }\n * }\n * ```\n */\nexport class MdgError extends Error {\n /** Always `'MdgError'`. */\n override readonly name = 'MdgError';\n /** Why the call failed; the same code in every language. */\n readonly code: ErrorCode;\n\n /**\n * Creates an error with a shared spec code.\n *\n * @param code - Shared spec error code.\n * @param message - Human-readable explanation, in English.\n */\n constructor(code: ErrorCode, message: string) {\n super(message);\n this.code = code;\n }\n\n /**\n * Makes `instanceof MdgError` true for errors from any mdg-utils package or build.\n *\n * @remarks Each package, and its ESM and CommonJS builds, has its own copy of this class,\n * so the check looks at the error's shape instead of its prototype chain.\n *\n * @param value - Any value, usually a caught error.\n * @returns `true` when `value` is an mdg-utils error.\n */\n static override [Symbol.hasInstance](value: unknown): boolean {\n return value instanceof Error && value.name === 'MdgError' && 'code' in value;\n }\n}\n","// Exact decimal helpers. Money must never show binary rounding artefacts (0.07 × 5 is\n// 0.35000000000000003 in floating point), so these work on decimal digits only.\n\nconst DECIMAL_POINT = '.';\nconst ZERO = '0';\n// String(value) of a small number, e.g. '1e-7' or '1.5e-10'.\nconst NEGATIVE_EXPONENT = /^(\\d)(?:\\.(\\d+))?e-(\\d+)$/;\nconst LEADING_ZEROS = /^0+(?=\\d)/;\nconst TRAILING_DECIMAL_ZEROS = /\\.?0+$/;\n\n/**\n * @internal The shortest exact decimal form of a number, never in exponent notation.\n *\n * @param value - A non-negative finite number.\n * @returns Its digits: `1500.5` → `'1500.5'`, `1e-7` → `'0.0000001'`.\n */\nexport function plainDecimal(value: number): string {\n const text = String(value);\n const match = NEGATIVE_EXPONENT.exec(text);\n if (match === null) return text;\n const [, lead = '', rest = '', exponent = ''] = match;\n return `0${DECIMAL_POINT}${ZERO.repeat(Number(exponent) - 1)}${lead}${rest}`;\n}\n\ninterface Scaled {\n /** All the digits, as one integer. */\n readonly units: bigint;\n /** How many of them come after the point. */\n readonly places: number;\n}\n\nfunction toScaled(digits: string): Scaled {\n const [whole = '', decimals = ''] = digits.split(DECIMAL_POINT);\n return { units: BigInt(`${whole}${decimals}`), places: decimals.length };\n}\n\n// Canonical decimal text: no leading zeros, no trailing decimal zeros.\nfunction toDigits({ units, places }: Scaled): string {\n const digits = units.toString().padStart(places + 1, ZERO);\n const point = digits.length - places;\n const whole = digits.slice(0, point).replace(LEADING_ZEROS, '');\n if (places === 0) return whole;\n return `${whole}${DECIMAL_POINT}${digits.slice(point)}`.replace(TRAILING_DECIMAL_ZEROS, '');\n}\n\n/**\n * @internal Multiplies decimal text exactly.\n *\n * @param digits - Canonical decimal text.\n * @param factor - A whole multiplier.\n * @returns `digits × factor`: `'0.07' × 5` → `'0.35'`.\n */\nexport function multiplyExact(digits: string, factor: number): string {\n const { units, places } = toScaled(digits);\n return toDigits({ units: units * BigInt(factor), places });\n}\n\n/**\n * @internal Divides decimal text exactly by a divisor of 10: multiplies by `10 ÷ divisor`,\n * then moves the point one place left.\n *\n * @param digits - Canonical decimal text.\n * @param divisionFactor - `10 ÷ divisor` (2 to divide by 5).\n * @returns `digits ÷ divisor`: `'7501' ÷ 5` → `'1500.2'`.\n */\nexport function divideExact(digits: string, divisionFactor: number): string {\n const { units, places } = toScaled(digits);\n return toDigits({ units: units * BigInt(divisionFactor), places: places + 1 });\n}\n","// Amounts at the public boundary: a number, or decimal text read exactly. Both become the\n// amount's exact decimal digits, so nothing below ever rounds.\nimport { MAX_TEXT_LENGTH, MIN_AMOUNT } from './generated/data.ts';\nimport { MdgError, type SafeParseResult } from './generated/errors.ts';\nimport { plainDecimal } from './decimal.ts';\n\n/** @internal The spec sets no maximum: number amounts stop where a number stops being exact. */\nexport const MAX_AMOUNT = Number.MAX_SAFE_INTEGER;\n\n/**\n * What the functions that compute or read an amount give back: a `number` (default), or the\n * exact decimal `text`, of any size.\n *\n * @example\n * ```ts\n * const exact: AmountResultKind = 'text';\n * ```\n */\nexport type AmountResultKind = 'number' | 'text';\n\n/**\n * Options for the functions that give back an amount.\n *\n * @example\n * ```ts\n * const options: AmountResultOptions = { as: 'text' };\n * ```\n */\nexport interface AmountResultOptions {\n /** `number` (default), or `text` for the exact decimal digits. */\n readonly as?: AmountResultKind;\n}\n\n/**\n * The value an amount function gives back for an {@link AmountResultKind}: `string` for `text`,\n * otherwise `number`.\n *\n * @example\n * ```ts\n * const digits: AmountValue<'text'> = '1500.5';\n * ```\n */\nexport type AmountValue<Kind extends AmountResultKind> = Kind extends 'text' ? string : number;\n\nconst RESULT_KINDS: ReadonlySet<unknown> = new Set<AmountResultKind>(['number', 'text']);\n// Words rule 13: ASCII digits, then optionally a point and more digits. Nothing else.\nconst DECIMAL_TEXT = /^[0-9]+(?:\\.[0-9]+)?$/;\nconst LEADING_ZEROS = /^0+(?=\\d)/;\nconst TRAILING_DECIMAL_ZEROS = /\\.?0+$/;\nconst POINT = '.';\n\n/**\n * @internal Canonical decimal text: no leading zeros, no trailing decimal zeros.\n *\n * @param text - Digits with an optional point and decimals.\n * @returns `'0012.50'` → `'12.5'`.\n */\nexport function canonical(text: string): string {\n const whole = text.replace(LEADING_ZEROS, '');\n return whole.includes(POINT) ? whole.replace(TRAILING_DECIMAL_ZEROS, '') : whole;\n}\n\n/**\n * @internal Throws OUT_OF_RANGE for a number below 0 or above {@link MAX_AMOUNT}.\n *\n * @param value - A finite number.\n */\nexport function assertInRange(value: number): void {\n if (value < MIN_AMOUNT || value > MAX_AMOUNT) {\n throw new MdgError(\n 'OUT_OF_RANGE',\n `Amounts go from ${String(MIN_AMOUNT)} to ${String(MAX_AMOUNT)}.`,\n );\n }\n}\n\n/**\n * @internal An amount's exact decimal digits, validated at the public boundary.\n *\n * @param value - A number from 0 to `Number.MAX_SAFE_INTEGER`, or plain decimal text.\n * @returns Canonical decimal text: `1500.50` → `'1500.5'`.\n */\nexport function amountDigits(value: unknown): string {\n if (typeof value === 'string') {\n if (value.length > MAX_TEXT_LENGTH || !DECIMAL_TEXT.test(value)) {\n throw new MdgError(\n 'INVALID_FORMAT',\n `Amount text is digits with an optional .decimals, at most ${String(MAX_TEXT_LENGTH)} characters.`,\n );\n }\n return canonical(value);\n }\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new MdgError('INVALID_TYPE', 'Amounts are finite numbers or decimal text.');\n }\n assertInRange(value);\n return plainDecimal(value);\n}\n\n/**\n * @internal The result kind the options ask for.\n *\n * @param options - The options the caller passed.\n * @returns `number` or `text`, or `undefined` for bad options.\n */\nexport function resultKind(options: unknown): AmountResultKind | undefined {\n if (typeof options !== 'object' || options === null) return undefined;\n const { as = 'number' } = options as AmountResultOptions;\n return RESULT_KINDS.has(as) ? as : undefined;\n}\n\n/**\n * @internal Exact digits as a number, only when the number holds them exactly.\n *\n * @param digits - Canonical decimal text.\n * @returns The number, or PRECISION_LOSS: never a silent rounding.\n */\nexport function exactNumber(digits: string): SafeParseResult<number> {\n const value = Number(digits);\n if (value <= MAX_AMOUNT && plainDecimal(value) === digits) return { success: true, data: value };\n return {\n success: false,\n error: new MdgError(\n 'PRECISION_LOSS',\n `${digits} does not fit a number exactly; pass { as: 'text' } for the exact digits.`,\n ),\n };\n}\n\n/**\n * @internal Gives exact digits back as the options ask, throwing on PRECISION_LOSS.\n *\n * @param digits - Canonical decimal text.\n * @param kind - `number` or `text`.\n * @returns The number or the text.\n */\nexport function amountResult(digits: string, kind: AmountResultKind): number | string {\n if (kind === 'text') return digits;\n const result = exactNumber(digits);\n if (!result.success) throw result.error;\n return result.data;\n}\n","import { spell, type SpellOptions } from '@mdgascar/words';\nimport { CURRENCY_WORD, FRANC_DIVISION_FACTOR, FRANCS_PER_ARIARY } from './generated/data.ts';\nimport { MdgError } from './generated/errors.ts';\nimport {\n amountDigits,\n amountResult,\n resultKind,\n type AmountResultKind,\n type AmountValue,\n} from './amount.ts';\nimport { divideExact, multiplyExact } from './decimal.ts';\n\n/**\n * Writes an Ariary amount in Malagasy words.\n *\n * @param amount - Ariary from 0 to `Number.MAX_SAFE_INTEGER`, whole or decimal, or plain\n * decimal text such as `'1500.25'`, read exactly.\n * @param options - The words `system`: `standard` (default) or `traditional`.\n * @returns The amount in words followed by `ariary`; decimals follow `faingo`.\n * @throws {@link MdgError} `INVALID_TYPE`, `INVALID_FORMAT` (text) or `OUT_OF_RANGE`.\n *\n * @example\n * ```ts\n * spellAriary(1500); // 'dimanjato sy arivo ariary'\n * spellAriary(1500.5); // 'dimanjato sy arivo faingo dimy ariary'\n * ```\n */\nexport function spellAriary(amount: number | string, options: SpellOptions = {}): string {\n // Text is checked by spell (words rule 13); a number by the Ariary range.\n if (typeof amount !== 'string') amountDigits(amount);\n return `${spell(amount, options)} ${CURRENCY_WORD}`;\n}\n\nfunction kindFor(options: unknown): AmountResultKind {\n const kind = resultKind(options);\n if (kind === undefined) throw new MdgError('INVALID_TYPE', \"as is 'number' or 'text'.\");\n return kind;\n}\n\n/**\n * Converts old Malagasy francs (FMG) to ariary: 5 FMG = 1 Ar, exactly in decimal.\n *\n * @param francs - Francs from 0 up, whole or decimal, as a number or decimal text.\n * @param options - Optional `as`: `number` (default) or `text` for the exact digits.\n * @returns The amount in ariary: `7501` → `1500.2`.\n * @throws {@link MdgError} `INVALID_TYPE` for a value that is not a finite number or text,\n * `INVALID_FORMAT` for text that is not plain decimal, `OUT_OF_RANGE` for a negative number,\n * `PRECISION_LOSS` when a number cannot hold the result exactly.\n *\n * @example\n * ```ts\n * fmgToAriary(7500); // 1500\n * fmgToAriary(7501); // 1500.2\n * ```\n */\nexport function fmgToAriary<Kind extends AmountResultKind = 'number'>(\n francs: number | string,\n options: { readonly as?: Kind } = {},\n): AmountValue<Kind> {\n const digits = amountDigits(francs);\n return amountResult(\n divideExact(digits, FRANC_DIVISION_FACTOR),\n kindFor(options),\n ) as AmountValue<Kind>;\n}\n\n/**\n * Converts ariary to old Malagasy francs (FMG): 1 Ar = 5 FMG, exactly in decimal.\n *\n * @param amount - Ariary from 0 up, whole or decimal, as a number or decimal text.\n * @param options - Optional `as`: `number` (default) or `text` for the exact digits.\n * @returns The amount in francs: `0.07` → `0.35`, never `0.35000000000000003`.\n * @throws {@link MdgError} as {@link fmgToAriary}.\n *\n * @example\n * ```ts\n * ariaryToFmg(1500); // 7500\n * ```\n */\nexport function ariaryToFmg<Kind extends AmountResultKind = 'number'>(\n amount: number | string,\n options: { readonly as?: Kind } = {},\n): AmountValue<Kind> {\n const digits = amountDigits(amount);\n return amountResult(\n multiplyExact(digits, FRANCS_PER_ARIARY),\n kindFor(options),\n ) as AmountValue<Kind>;\n}\n","// Grouping and decimal options shared by formatting and reading. Every default is the Malagasy\n// way; the comma grouping and the decimal dot are opt-in for text in another convention.\nimport {\n DECIMAL_SEPARATORS,\n DEFAULT_DECIMAL,\n DEFAULT_GROUPING,\n GROUP_SEPARATORS,\n type AriaryDecimal,\n type AriaryGrouping,\n} from './generated/data.ts';\nimport { MdgError } from './generated/errors.ts';\n\n/**\n * Separator options for formatting and reading amounts.\n *\n * @example\n * ```ts\n * const english: AriarySeparatorOptions = { grouping: 'comma', decimal: 'dot' };\n * ```\n */\nexport interface AriarySeparatorOptions {\n /** Thousand separator: `space` (default), `dot`, or `comma` for another convention. */\n readonly grouping?: AriaryGrouping;\n /** Decimal separator: `comma` (default), or `dot` for another convention. */\n readonly decimal?: AriaryDecimal;\n}\n\n/**\n * @internal Throws INVALID_TYPE unless `options` is an object.\n *\n * @param options - What the caller passed as options.\n */\nexport function assertOptionsObject(options: unknown): asserts options is Record<string, unknown> {\n if (typeof options !== 'object' || options === null) {\n throw new MdgError('INVALID_TYPE', 'Options must be an object.');\n }\n}\n\n/**\n * @internal Reads the `decimal` option.\n *\n * @param options - The caller's options.\n * @returns The decimal character, a comma by default.\n */\nexport function decimalFor(options: AriarySeparatorOptions): string {\n const decimal = DECIMAL_SEPARATORS.get(options.decimal ?? DEFAULT_DECIMAL);\n if (decimal === undefined) throw new MdgError('INVALID_TYPE', 'decimal is comma or dot.');\n return decimal;\n}\n\n/**\n * @internal Reads a `grouping` option and checks it against the decimal character.\n *\n * @param id - The grouping option.\n * @param decimal - The decimal character in use.\n * @returns The grouping character.\n */\nexport function groupingFor(id: AriaryGrouping, decimal: string): string {\n const grouping = GROUP_SEPARATORS.get(id);\n if (grouping === undefined)\n throw new MdgError('INVALID_TYPE', 'grouping is space, dot or comma.');\n if (grouping === decimal) {\n throw new MdgError('INVALID_TYPE', 'grouping and decimal must be different characters.');\n }\n return grouping;\n}\n\n/**\n * @internal The grouping option for formatting.\n *\n * @param options - The caller's options.\n * @returns The one given, or the Malagasy default.\n */\nexport function formatGroupingId(options: AriarySeparatorOptions): AriaryGrouping {\n return options.grouping ?? DEFAULT_GROUPING;\n}\n","import { CURRENCY_SYMBOL, FRANC_SYMBOL, GROUP_SIZE, SYMBOL_SEPARATOR } from './generated/data.ts';\nimport { MdgError } from './generated/errors.ts';\nimport { amountDigits } from './amount.ts';\nimport {\n assertOptionsObject,\n decimalFor,\n formatGroupingId,\n groupingFor,\n type AriarySeparatorOptions,\n} from './separators.ts';\n\n/**\n * Where the currency symbol goes: `before` (default, `Ar 1 500`) or `after` (`1 500 Ar`).\n *\n * @example\n * ```ts\n * const position: AriarySymbolPosition = 'after';\n * ```\n */\nexport type AriarySymbolPosition = 'before' | 'after';\n\n/**\n * Layout options for {@link formatAriary} and {@link formatFmg}.\n *\n * @example\n * ```ts\n * const options: AriaryFormatOptions = { grouping: 'dot', symbolPosition: 'after' };\n * ```\n */\nexport interface AriaryFormatOptions extends AriarySeparatorOptions {\n /** Symbol `before` (default) or `after` the amount. */\n readonly symbolPosition?: AriarySymbolPosition;\n}\n\nconst SYMBOL_POSITIONS: ReadonlySet<unknown> = new Set<AriarySymbolPosition>(['before', 'after']);\nconst DECIMAL_POINT = '.';\nconst DIGIT_GROUP_BOUNDARY = new RegExp(`\\\\B(?=(\\\\d{${String(GROUP_SIZE)}})+(?!\\\\d))`, 'g');\n\ninterface Layout {\n readonly grouping: string;\n readonly decimal: string;\n readonly symbolAfter: boolean;\n}\n\nfunction layoutFor(options: unknown): Layout {\n assertOptionsObject(options);\n const { symbolPosition = 'before' } = options as AriaryFormatOptions;\n if (!SYMBOL_POSITIONS.has(symbolPosition)) {\n throw new MdgError('INVALID_TYPE', 'symbolPosition is before or after.');\n }\n const decimal = decimalFor(options);\n const grouping = groupingFor(formatGroupingId(options), decimal);\n return { grouping, decimal, symbolAfter: symbolPosition === 'after' };\n}\n\n// Groups the whole part only; decimals follow a comma as they are, never grouped or rounded.\nfunction layOut(digits: string, symbol: string, options: AriaryFormatOptions): string {\n const layout = layoutFor(options);\n const [whole = '', decimals] = digits.split(DECIMAL_POINT);\n const grouped = whole.replace(DIGIT_GROUP_BOUNDARY, layout.grouping);\n const text = decimals === undefined ? grouped : `${grouped}${layout.decimal}${decimals}`;\n return layout.symbolAfter\n ? `${text}${SYMBOL_SEPARATOR}${symbol}`\n : `${symbol}${SYMBOL_SEPARATOR}${text}`;\n}\n\n/**\n * Writes an Ariary amount the Malagasy way: symbol `Ar`, digits grouped by no-break spaces.\n *\n * @param amount - Ariary from 0 to `Number.MAX_SAFE_INTEGER`, whole or decimal, or decimal\n * text such as `'1500.25'`, written exactly.\n * @param options - Optional `grouping` (`space`, `dot` or `comma`), `decimal` (`comma` or `dot`)\n * and `symbolPosition` (`before` or `after`). The defaults are the Malagasy way.\n * @returns The formatted amount, e.g. `Ar 1 500` or `Ar 1 500,5` (the spaces are U+00A0).\n * @throws {@link MdgError} `INVALID_TYPE` for a value that is not a finite number or text, or\n * unknown options; `INVALID_FORMAT` for text that is not plain decimal; `OUT_OF_RANGE` for a\n * number outside 0 to `Number.MAX_SAFE_INTEGER`.\n *\n * @example\n * ```ts\n * formatAriary(1500); // 'Ar 1 500'\n * formatAriary(1500, { grouping: 'dot', symbolPosition: 'after' }); // '1.500 Ar'\n * formatAriary(1500.5); // 'Ar 1 500,5'\n * ```\n */\nexport function formatAriary(amount: number | string, options: AriaryFormatOptions = {}): string {\n return layOut(amountDigits(amount), CURRENCY_SYMBOL, options);\n}\n\n/**\n * Writes an amount in old Malagasy francs, with the same layout as {@link formatAriary}.\n *\n * @param francs - Francs from 0 to `Number.MAX_SAFE_INTEGER`, whole or decimal, or decimal text.\n * @param options - Same options as {@link formatAriary}.\n * @returns The formatted amount, e.g. `Fmg 7 500`.\n * @throws {@link MdgError} as {@link formatAriary}.\n *\n * @example\n * ```ts\n * formatFmg(7500); // 'Fmg 7 500'\n * ```\n */\nexport function formatFmg(francs: number | string, options: AriaryFormatOptions = {}): string {\n return layOut(amountDigits(francs), FRANC_SYMBOL, options);\n}\n","// Reads the digits of an amount typed by a user: an optional currency token, then plain or\n// grouped digits, then optionally a decimal separator and the decimals.\nimport { CURRENCY_TOKENS, GROUP_SIZE, READABLE_SEPARATORS } from './generated/data.ts';\n\nconst SPACE = ' ';\nconst WHITESPACE = /\\s/;\nconst PLAIN_AMOUNT = /^(?:0|[1-9]\\d*)$/;\nconst DECIMALS = /^\\d+$/;\nconst NON_DIGITS = /\\D/g;\nconst REGEX_SPECIAL = /[\\\\^$.*+?()[\\]{}|-]/g;\nconst DECIMAL_POINT = '.';\n\n/** @internal What a reader accepts: grouping characters between digit groups, and the decimal one. */\nexport interface ReadSeparators {\n readonly grouping: readonly string[];\n readonly decimal: string;\n}\n\ntype Reader = (amount: string) => string | undefined;\n\nconst readers = new Map<string, Reader>();\n\nfunction isWhitespace(character: string): boolean {\n return WHITESPACE.test(character);\n}\n\nfunction escapeForClass(character: string): string {\n return character.replace(REGEX_SPECIAL, '\\\\$&');\n}\n\n// One digit group of three after the first, repeating the same separator: '1 500 000'.\nfunction groupedPattern(separatorClass: string): RegExp {\n const group = `\\\\d{${String(GROUP_SIZE)}}`;\n return new RegExp(\n `^[1-9]\\\\d{0,${String(GROUP_SIZE - 1)}}([${separatorClass}])${group}(?:\\\\1${group})*$`,\n );\n}\n\n// Spaces of every kind count as one separator: they are turned into a plain space first.\nfunction wholeReader(grouping: readonly string[]): Reader {\n const spaces = grouping.filter(isWhitespace);\n const normalizeSpaces = new RegExp(`[${spaces.map(escapeForClass).join('')}]`, 'g');\n const others = grouping.filter((character) => !isWhitespace(character));\n const separators = [...(spaces.length > 0 ? [SPACE] : []), ...others];\n const grouped = groupedPattern(separators.map(escapeForClass).join(''));\n return (whole) => {\n const normalized = spaces.length > 0 ? whole.replace(normalizeSpaces, SPACE) : whole;\n const isAmount = PLAIN_AMOUNT.test(normalized) || grouped.test(normalized);\n return isAmount ? normalized.replace(NON_DIGITS, '') : undefined;\n };\n}\n\nfunction makeReader({ grouping, decimal }: ReadSeparators): Reader {\n const wholeDigits = wholeReader(grouping);\n return (amount) => {\n const [whole = '', decimals, extra] = amount.split(decimal);\n if (extra !== undefined) return undefined;\n const digits = wholeDigits(whole);\n if (digits === undefined || decimals === undefined) return digits;\n return DECIMALS.test(decimals) ? `${digits}${DECIMAL_POINT}${decimals}` : undefined;\n };\n}\n\nfunction readerFor(separators: ReadSeparators): Reader {\n const key = `${separators.grouping.join('')}|${separators.decimal}`;\n const cached = readers.get(key);\n if (cached !== undefined) return cached;\n const reader = makeReader(separators);\n readers.set(key, reader);\n return reader;\n}\n\nfunction stripCurrency(text: string): string | undefined {\n const lower = text.toLowerCase();\n const prefix = CURRENCY_TOKENS.find((token) => lower.startsWith(token)) ?? '';\n const suffix = CURRENCY_TOKENS.find((token) => lower.endsWith(token)) ?? '';\n if (prefix !== '' && suffix !== '') return undefined;\n return text.slice(prefix.length, text.length - suffix.length).trim();\n}\n\n/**\n * @internal The grouping characters a reader accepts.\n *\n * @param grouping - The chosen grouping character, or undefined for every Malagasy one.\n * @param decimal - The decimal character, which never counts as grouping.\n * @returns Every Malagasy separator (spaces and dot) when none is chosen; else the chosen one,\n * a space standing for every kind of space.\n */\nexport function readableGrouping(grouping: string | undefined, decimal: string): string[] {\n if (grouping === undefined) return READABLE_SEPARATORS.filter((value) => value !== decimal);\n return isWhitespace(grouping) ? READABLE_SEPARATORS.filter(isWhitespace) : [grouping];\n}\n\n/**\n * Extracts the digits of an amount such as `Ar 1 500`, `1.500 Ar`, `MGA 1500` or `1 500,50`.\n *\n * @param text - An amount as typed by a user.\n * @param separators - The grouping and decimal characters to accept.\n * @returns The digits with a `.` before any decimals (`'1500'`, `'1500.50'`), or `undefined`\n * when the text is not an amount.\n *\n * @example\n * ```ts\n * readDigits('1 500,50', { grouping: [' ', '.'], decimal: ',' }); // '1500.50'\n * ```\n */\nexport function readDigits(text: string, separators: ReadSeparators): string | undefined {\n const amount = stripCurrency(text.trim());\n if (amount === undefined) return undefined;\n return readerFor(separators)(amount);\n}\n","import { canonical, exactNumber, type AmountResultKind, type AmountValue } from './amount.ts';\nimport { MAX_READ_LENGTH } from './generated/data.ts';\nimport { MdgError, type ErrorCode, type SafeParseResult } from './generated/errors.ts';\nimport { readableGrouping, readDigits, type ReadSeparators } from './read-digits.ts';\nimport {\n assertOptionsObject,\n decimalFor,\n groupingFor,\n type AriarySeparatorOptions,\n} from './separators.ts';\n\n/**\n * Options for reading amounts: which `grouping` and `decimal` separators the text uses, and\n * what to give back. Without `grouping`, every Malagasy one is accepted (spaces or dot);\n * `decimal` defaults to a comma. Say so for text in another convention:\n * `{ grouping: 'comma', decimal: 'dot' }`.\n *\n * @example\n * ```ts\n * const english: AriaryParseOptions = { grouping: 'comma', decimal: 'dot' };\n * ```\n */\nexport interface AriaryParseOptions extends AriarySeparatorOptions {\n /** `number` (default), or `text` for the exact decimal digits of any amount. */\n readonly as?: AmountResultKind;\n}\n\ninterface ReadOptions extends ReadSeparators {\n readonly kind: AmountResultKind;\n}\n\nconst PARSE_OPTION_KEYS: ReadonlySet<string> = new Set(['grouping', 'decimal', 'as']);\nconst RESULT_KINDS: ReadonlySet<unknown> = new Set<AmountResultKind>(['number', 'text']);\n\nfunction failure(code: ErrorCode, message: string): SafeParseResult<never> {\n return { success: false, error: new MdgError(code, message) };\n}\n\n// The parsers never throw for bad options either: the error comes back as a value.\nfunction safeReadOptions(options: unknown): ReadOptions | MdgError {\n try {\n return readOptionsFor(options);\n } catch (error) {\n return error as MdgError;\n }\n}\n\nfunction readOptionsFor(options: unknown): ReadOptions {\n assertOptionsObject(options);\n if (Object.keys(options).some((key) => !PARSE_OPTION_KEYS.has(key))) {\n throw new MdgError('INVALID_TYPE', 'Reading takes only the grouping, decimal and as options.');\n }\n const { as: kind = 'number', ...separators } = options as AriaryParseOptions;\n if (!RESULT_KINDS.has(kind)) throw new MdgError('INVALID_TYPE', \"as is 'number' or 'text'.\");\n const decimal = decimalFor(separators);\n const grouping =\n separators.grouping === undefined ? undefined : groupingFor(separators.grouping, decimal);\n return { grouping: readableGrouping(grouping, decimal), decimal, kind };\n}\n\n/**\n * Reads an Ariary amount without throwing.\n *\n * @param text - An amount such as `Ar 1 500`, `1.500 Ar`, `MGA 1500` or `1 500,50`.\n * @param options - Optional `grouping` and `decimal`; see {@link AriaryParseOptions}.\n * @returns `{ success: true, data }` with the amount, or `{ success: false, error }`.\n *\n * @example\n * ```ts\n * const result = safeParseAriary('1 500 Ar');\n * if (result.success) result.data; // 1500\n * ```\n */\nexport function safeParseAriary(\n text: unknown,\n options: AriaryParseOptions = {},\n): SafeParseResult<number | string> {\n if (typeof text !== 'string') return failure('INVALID_TYPE', 'Expected the amount as text.');\n const read = safeReadOptions(options);\n if (read instanceof MdgError) return { success: false, error: read };\n if (text.length > MAX_READ_LENGTH) {\n return failure('INVALID_FORMAT', `Amounts are at most ${String(MAX_READ_LENGTH)} characters.`);\n }\n const digits = readDigits(text, read);\n if (digits === undefined) {\n return failure('INVALID_FORMAT', 'Expected an amount such as Ar 1 500 or Ar 1 500,50.');\n }\n const exact = canonical(digits);\n return read.kind === 'text' ? { success: true, data: exact } : exactNumber(exact);\n}\n\n/**\n * Reads an Ariary amount written in any common way.\n *\n * @param text - An amount such as `Ar 1 500`, `1.500 Ar`, `MGA 1500` or `1 500,50`.\n * @param options - Optional `grouping` and `decimal`; see {@link AriaryParseOptions}.\n * @returns The amount, whole or decimal.\n * @throws {@link MdgError} `INVALID_TYPE` for non-strings or bad options, `INVALID_FORMAT` for text\n * that is not an amount (signs, a dot as decimal point by default), `PRECISION_LOSS` when a\n * number cannot hold the amount exactly (pass `{ as: 'text' }` for the exact digits).\n *\n * @example\n * ```ts\n * parseAriary('Ar 1 500'); // 1500\n * parseAriary('1.500 Ar'); // 1500\n * parseAriary('1 500,50 Ar'); // 1500.5\n * parseAriary('1,500.50', { grouping: 'comma', decimal: 'dot' }); // 1500.5\n * ```\n */\nexport function parseAriary<Kind extends AmountResultKind = 'number'>(\n text: string,\n options: AriarySeparatorOptions & { readonly as?: Kind } = {},\n): AmountValue<Kind> {\n const result = safeParseAriary(text, options);\n if (!result.success) throw result.error;\n return result.data as AmountValue<Kind>;\n}\n\n/**\n * Reads an Ariary amount, or gives `undefined` instead of throwing.\n *\n * Use {@link safeParseAriary} when you need to know why the text was rejected.\n *\n * @param text - An amount such as `Ar 1 500`, `1.500 Ar`, `MGA 1500` or `1 500,50`.\n * @param options - Optional `grouping` and `decimal`; see {@link AriaryParseOptions}.\n * @returns The amount, or `undefined` when {@link parseAriary} would throw.\n *\n * @example\n * ```ts\n * tryParseAriary('1.500 Ar'); // 1500\n * tryParseAriary('1.5'); // undefined\n * ```\n */\nexport function tryParseAriary(\n text: unknown,\n options: AriaryParseOptions = {},\n): number | string | undefined {\n const result = safeParseAriary(text, options);\n return result.success ? result.data : undefined;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mdgascar/ariary",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Malagasy Ariary amounts: format (Ar 1 500), parse, words and franc (FMG) conversion.",
5
5
  "license": "MIT",
6
6
  "author": "Mdgascar contributors",
@@ -49,7 +49,7 @@
49
49
  "provenance": true
50
50
  },
51
51
  "dependencies": {
52
- "@mdgascar/words": "^0.9.0"
52
+ "@mdgascar/words": "^0.10.0"
53
53
  },
54
54
  "scripts": {
55
55
  "build": "tsup",