@vielzeug/coins 2.2.0 → 3.0.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/README.md +12 -67
- package/dist/_decimal.cjs +1 -1
- package/dist/_decimal.cjs.map +1 -1
- package/dist/_decimal.d.ts +1 -0
- package/dist/_decimal.d.ts.map +1 -1
- package/dist/_decimal.js +30 -19
- package/dist/_decimal.js.map +1 -1
- package/dist/aggregate.cjs +1 -1
- package/dist/aggregate.cjs.map +1 -1
- package/dist/aggregate.d.ts.map +1 -1
- package/dist/aggregate.js +32 -26
- package/dist/aggregate.js.map +1 -1
- package/dist/coins.cjs +1 -1
- package/dist/coins.cjs.map +1 -1
- package/dist/coins.iife.js +1 -1
- package/dist/coins.iife.js.map +1 -1
- package/dist/coins.js +1 -1
- package/dist/coins.js.map +1 -1
- package/dist/currency.cjs +1 -1
- package/dist/currency.cjs.map +1 -1
- package/dist/currency.d.ts.map +1 -1
- package/dist/currency.js +7 -6
- package/dist/currency.js.map +1 -1
- package/dist/errors.cjs +1 -1
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.ts +3 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +16 -5
- package/dist/errors.js.map +1 -1
- package/dist/exchange.cjs +1 -1
- package/dist/exchange.cjs.map +1 -1
- package/dist/exchange.js +1 -1
- package/dist/exchange.js.map +1 -1
- package/dist/format.cjs +1 -1
- package/dist/format.cjs.map +1 -1
- package/dist/format.d.ts.map +1 -1
- package/dist/format.js +54 -52
- package/dist/format.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/dist/money.cjs +1 -1
- package/dist/money.cjs.map +1 -1
- package/dist/money.d.ts +9 -2
- package/dist/money.d.ts.map +1 -1
- package/dist/money.js +72 -54
- package/dist/money.js.map +1 -1
- package/dist/serialization.cjs +1 -1
- package/dist/serialization.cjs.map +1 -1
- package/dist/serialization.d.ts +1 -4
- package/dist/serialization.d.ts.map +1 -1
- package/dist/serialization.js +6 -38
- package/dist/serialization.js.map +1 -1
- package/package.json +8 -7
package/dist/coins.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"coins.js","names":[],"sources":["../src/errors.ts","../src/_decimal.ts","../src/currency.ts","../src/money.ts","../src/aggregate.ts","../src/exchange.ts","../src/format.ts","../src/serialization.ts"],"sourcesContent":["export type CoinsErrorCode =\n | 'CURRENCY_MISMATCH'\n | 'DIVISION_BY_ZERO'\n | 'FORMAT_ERROR'\n | 'INVALID_ALLOCATION'\n | 'INVALID_CURRENCY'\n | 'INVALID_DECIMAL'\n | 'INVALID_EXCHANGE_RATE'\n | 'INVALID_MONEY'\n | 'INVALID_RANGE'\n | 'INVALID_ROUNDING';\n\nexport class CoinsError extends Error {\n readonly code: CoinsErrorCode;\n\n constructor(code: CoinsErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class CurrencyMismatchError extends CoinsError {\n readonly expected: string;\n readonly received: string;\n\n constructor(expected: string, received: string) {\n super('CURRENCY_MISMATCH', `Currency mismatch: ${expected} and ${received}`);\n this.expected = expected;\n this.received = received;\n }\n}\n\nexport class InvalidCurrencyError extends CoinsError {\n readonly value: unknown;\n\n constructor(value: unknown) {\n super('INVALID_CURRENCY', `Unsupported currency: \"${String(value)}\"`);\n this.value = value;\n }\n}\n","import { CoinsError } from './errors';\nimport type { Decimal, RoundingMode } from './types';\n\nconst DECIMAL = /^(-?)(\\d+)(?:\\.(\\d+))?$/;\nconst MAX_DECIMAL_DIGITS = 1000;\nconst MAX_DECIMAL_PLACES = 100;\n\nexport function decimal(value: string): Decimal {\n if (value.length > MAX_DECIMAL_DIGITS) throw new CoinsError('INVALID_DECIMAL', 'Decimal input is too long');\n\n const match = DECIMAL.exec(value);\n\n if (!match) throw new CoinsError('INVALID_DECIMAL', `Invalid decimal: \"${value}\"`);\n\n const fraction = (match[3] ?? '').replace(/0+$/, '');\n\n if (fraction.length > MAX_DECIMAL_PLACES) {\n throw new CoinsError('INVALID_DECIMAL', `Decimal precision cannot exceed ${MAX_DECIMAL_PLACES} places`);\n }\n\n const denominator = 10n ** BigInt(fraction.length);\n const unsigned = BigInt(match[2]!) * denominator + BigInt(fraction || '0');\n const numerator = match[1] === '-' && unsigned !== 0n ? -unsigned : unsigned;\n const divisor = gcd(numerator < 0n ? -numerator : numerator, denominator);\n\n return Object.freeze({ denominator: denominator / divisor, numerator: numerator / divisor }) as Decimal;\n}\n\nexport function roundDivision(numerator: bigint, denominator: bigint, mode: RoundingMode): bigint {\n if (denominator <= 0n) throw new CoinsError('INVALID_DECIMAL', 'Decimal denominator must be positive');\n\n const negative = numerator < 0n;\n const absolute = negative ? -numerator : numerator;\n const quotient = absolute / denominator;\n const remainder = absolute % denominator;\n\n if (remainder === 0n) return negative ? -quotient : quotient;\n\n const increment = (() => {\n switch (mode) {\n case 'awayFromZero':\n return true;\n case 'ceil':\n return !negative;\n case 'floor':\n return negative;\n case 'halfAwayFromZero':\n return remainder * 2n >= denominator;\n case 'halfEven': {\n const doubled = remainder * 2n;\n\n return doubled > denominator || (doubled === denominator && quotient % 2n !== 0n);\n }\n case 'towardZero':\n return false;\n default:\n throw new CoinsError('INVALID_ROUNDING', `Unknown rounding mode: ${mode satisfies never}`);\n }\n })();\n\n const result = increment ? quotient + 1n : quotient;\n\n return negative ? -result : result;\n}\n\nexport function toDecimalString(amount: bigint, minorUnit: number): string {\n const negative = amount < 0n;\n const absolute = negative ? -amount : amount;\n const scale = 10n ** BigInt(minorUnit);\n const whole = absolute / scale;\n\n if (minorUnit === 0) return `${negative ? '-' : ''}${whole}`;\n\n const fraction = (absolute % scale).toString().padStart(minorUnit, '0');\n\n return `${negative ? '-' : ''}${whole}.${fraction}`;\n}\n\nexport function gcd(left: bigint, right: bigint): bigint {\n let a = left;\n let b = right;\n\n while (b !== 0n) [a, b] = [b, a % b];\n\n return a === 0n ? 1n : a;\n}\n\nexport function lcm(left: bigint, right: bigint): bigint {\n return (left / gcd(left, right)) * right;\n}\n","import { CoinsError, InvalidCurrencyError } from './errors';\nimport type { Currency, CurrencyCode } from './types';\n\nconst builtins = new Map<string, Currency>();\nconst canonicalCurrencies = new WeakSet<object>();\n\nfunction register<C extends string>(code: C, minorUnit: number): Currency<C> {\n validateDefinition(code, minorUnit);\n\n const definition = Object.freeze({ code: code as CurrencyCode<C>, minorUnit }) as Currency<C>;\n\n canonicalCurrencies.add(definition);\n\n return definition;\n}\n\nfunction builtin<C extends string>(code: C, minorUnit: number): Currency<C> {\n const definition = register(code, minorUnit);\n\n builtins.set(code, definition);\n\n return definition;\n}\n\nexport const USD = builtin('USD', 2);\nexport const EUR = builtin('EUR', 2);\nexport const GBP = builtin('GBP', 2);\nexport const JPY = builtin('JPY', 0);\nexport const KRW = builtin('KRW', 0);\nexport const BHD = builtin('BHD', 3);\nexport const KWD = builtin('KWD', 3);\n\n/** Resolve a built-in currency by code, or construct an immutable custom currency from a definition. */\nexport function currency<C extends string>(code: C): Currency<C>;\nexport function currency<C extends string>(definition: { code: C; minorUnit: number }): Currency<C>;\nexport function currency<C extends string>(input: C | { code: C; minorUnit: number }): Currency<C> {\n if (typeof input === 'string') {\n const definition = builtins.get(input);\n\n if (!definition) throw new InvalidCurrencyError(input);\n\n return definition as Currency<C>;\n }\n\n return register(input.code, input.minorUnit);\n}\n\nexport function isCurrency(value: unknown): value is Currency {\n return typeof value === 'object' && value !== null && canonicalCurrencies.has(value);\n}\n\nfunction validateDefinition(code: string, minorUnit: number): void {\n if (!/^[A-Z]{3}$/.test(code)) {\n throw new CoinsError('INVALID_CURRENCY', `Currency code must be three uppercase letters: \"${code}\"`);\n }\n\n if (!Number.isInteger(minorUnit) || minorUnit < 0 || minorUnit > 6) {\n throw new CoinsError('INVALID_CURRENCY', `Currency \"${code}\" must have 0–6 minor-unit digits`);\n }\n}\n","import { decimal, roundDivision, toDecimalString } from './_decimal';\nimport { isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport type { Currency, Money, RoundingMode } from './types';\n\nconst canonicalMoney = new WeakSet<object>();\n\nconst defaultRounding: RoundingMode = 'halfAwayFromZero';\n\nexport function money<C extends Currency>(amount: string, currency: C, options?: { rounding?: RoundingMode }): Money<C>;\nexport function money<C extends Currency>(amount: bigint, currency: C, options: { unit: 'minor' }): Money<C>;\nexport function money<C extends Currency>(\n amount: bigint | string,\n currency: C,\n options?: { rounding?: RoundingMode } | { unit: 'minor' },\n): Money<C> {\n assertCurrency(currency);\n\n if (typeof amount === 'bigint') {\n if (!options || !('unit' in options) || options.unit !== 'minor') {\n throw new CoinsError('INVALID_MONEY', \"Bigint amounts require { unit: 'minor' }\");\n }\n\n return createMoney(amount, currency);\n }\n\n if (options && 'unit' in options)\n throw new CoinsError('INVALID_MONEY', 'Decimal strings do not accept a unit option');\n\n const value = decimal(amount);\n const scaled = value.numerator * 10n ** BigInt(currency.minorUnit);\n const remainder = scaled % value.denominator;\n\n if (remainder !== 0n && options?.rounding === undefined) {\n throw new CoinsError('INVALID_MONEY', `Amount \"${amount}\" exceeds ${currency.code} precision; provide rounding`);\n }\n\n return createMoney(roundDivision(scaled, value.denominator, options?.rounding ?? defaultRounding), currency);\n}\n\n/** Validates a plain data object and returns canonical money. Use for untrusted input; use `isMoney()` for trusted values. */\nexport function parseMoney(value: unknown): Money {\n if (!isPlainDataObject(value)) throw new CoinsError('INVALID_MONEY', 'Money must be a plain data object');\n\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const amountDescriptor = descriptors.amount;\n const currencyDescriptor = descriptors.currency;\n\n if (!isDataProperty(amountDescriptor) || !isDataProperty(currencyDescriptor)) {\n throw new CoinsError('INVALID_MONEY', 'Money properties must be plain data values');\n }\n\n if (typeof amountDescriptor.value !== 'bigint' || !isCurrency(currencyDescriptor.value)) {\n throw new CoinsError('INVALID_MONEY', 'Money must contain bigint amount and a registered currency');\n }\n\n return createMoney(amountDescriptor.value, currencyDescriptor.value);\n}\n\nexport function isMoney(value: unknown): value is Money {\n return typeof value === 'object' && value !== null && canonicalMoney.has(value);\n}\n\nexport function add<C extends Currency>(left: Money<C>, right: Money<NoInfer<C>>): Money<C> {\n assertSameCurrency(left, right);\n\n return createMoney(left.amount + right.amount, left.currency);\n}\n\nexport function subtract<C extends Currency>(left: Money<C>, right: Money<NoInfer<C>>): Money<C> {\n assertSameCurrency(left, right);\n\n return createMoney(left.amount - right.amount, left.currency);\n}\n\nexport function multiply<C extends Currency>(\n value: Money<C>,\n factor: string,\n options: { rounding?: RoundingMode } = {},\n): Money<C> {\n assertMoney(value);\n\n const scalar = decimal(factor);\n\n return createMoney(\n roundDivision(value.amount * scalar.numerator, scalar.denominator, options.rounding ?? defaultRounding),\n value.currency,\n );\n}\n\nexport function divide<C extends Currency>(\n value: Money<C>,\n divisor: string,\n options: { rounding?: RoundingMode } = {},\n): Money<C> {\n assertMoney(value);\n\n const scalar = decimal(divisor);\n\n if (scalar.numerator === 0n) throw new CoinsError('DIVISION_BY_ZERO', 'Cannot divide money by zero');\n\n const divisorMagnitude = scalar.numerator < 0n ? -scalar.numerator : scalar.numerator;\n const dividend = value.amount * scalar.denominator;\n const quotient = roundDivision(\n scalar.numerator < 0n ? -dividend : dividend,\n divisorMagnitude,\n options.rounding ?? defaultRounding,\n );\n\n return createMoney(quotient, value.currency);\n}\n\nexport function compare<C extends Currency>(left: Money<C>, right: Money<NoInfer<C>>): -1 | 0 | 1 {\n assertSameCurrency(left, right);\n\n return left.amount === right.amount ? 0 : left.amount < right.amount ? -1 : 1;\n}\n\nexport function clamp<C extends Currency>(\n value: Money<C>,\n options: { max: Money<NoInfer<C>>; min: Money<NoInfer<C>> },\n): Money<C> {\n if (compare(options.min, options.max) === 1) {\n throw new CoinsError('INVALID_RANGE', 'Clamp minimum cannot exceed maximum');\n }\n\n return compare(value, options.min) === -1 ? options.min : compare(value, options.max) === 1 ? options.max : value;\n}\n\nexport function abs<C extends Currency>(value: Money<C>): Money<C> {\n assertMoney(value);\n\n return createMoney(value.amount < 0n ? -value.amount : value.amount, value.currency);\n}\n\nexport function negate<C extends Currency>(value: Money<C>): Money<C> {\n assertMoney(value);\n\n return createMoney(-value.amount, value.currency);\n}\n\nexport function round<C extends Currency>(\n value: Money<C>,\n options: { fractionDigits: number; rounding?: RoundingMode },\n): Money<C> {\n assertMoney(value);\n\n const { fractionDigits, rounding = defaultRounding } = options;\n\n if (!Number.isInteger(fractionDigits) || fractionDigits < 0 || fractionDigits > value.currency.minorUnit) {\n throw new CoinsError('INVALID_ROUNDING', `fractionDigits must be an integer from 0 to ${value.currency.minorUnit}`);\n }\n\n const factor = 10n ** BigInt(value.currency.minorUnit - fractionDigits);\n\n return createMoney(roundDivision(value.amount, factor, rounding) * factor, value.currency);\n}\n\nexport function toDecimal(value: Money): string {\n assertMoney(value);\n\n return toDecimalString(value.amount, value.currency.minorUnit);\n}\n\nexport function createMoney<C extends Currency>(amount: bigint, currency: C): Money<C> {\n const value = Object.freeze({ amount, currency }) as Money<C>;\n\n canonicalMoney.add(value);\n\n return value;\n}\n\nexport function assertMoney(value: unknown): asserts value is Money {\n if (!isMoney(value)) {\n throw new CoinsError('INVALID_MONEY', 'Money must be a canonical @vielzeug/coins value');\n }\n}\n\nfunction assertSameCurrency(left: Money, right: Money): void {\n assertMoney(left);\n assertMoney(right);\n\n if (left.currency !== right.currency) {\n throw new CurrencyMismatchError(left.currency.code, right.currency.code);\n }\n}\n\nfunction assertCurrency(value: unknown): asserts value is Currency {\n if (!isCurrency(value)) throw new CoinsError('INVALID_CURRENCY', 'Money requires a registered currency');\n}\n\nfunction isPlainDataObject(value: unknown): value is Record<PropertyKey, unknown> {\n if (typeof value !== 'object' || value === null) return false;\n\n const prototype = Object.getPrototypeOf(value);\n\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isDataProperty(\n descriptor: PropertyDescriptor | undefined,\n): descriptor is PropertyDescriptor & { value: unknown } {\n return (\n descriptor !== undefined && 'value' in descriptor && descriptor.get === undefined && descriptor.set === undefined\n );\n}\n","import { decimal, lcm } from './_decimal';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { assertMoney, createMoney } from './money';\nimport type { Currency, Money } from './types';\n\nexport function sum<C extends Currency>(values: readonly Money<C>[]): Money<C>;\nexport function sum<C extends Currency>(values: Iterable<Money<C>>, options: { currency: C }): Money<C>;\nexport function sum<C extends Currency>(values: Iterable<Money<C>>, options?: { currency: C }): Money<C> {\n let amount = 0n;\n let currency: C | undefined = options?.currency;\n\n for (const value of values) {\n assertMoney(value);\n\n if (currency === undefined) {\n currency = value.currency;\n } else if (value.currency !== currency) {\n throw new CurrencyMismatchError(currency.code, value.currency.code);\n }\n\n amount += value.amount;\n }\n\n if (currency === undefined) throw new CoinsError('INVALID_MONEY', 'sum() of empty iterable requires { currency }');\n\n return createMoney(amount, currency);\n}\n\nexport function allocate<C extends Currency>(value: Money<C>, count: number): Money<C>[];\nexport function allocate<C extends Currency>(value: Money<C>, weights: readonly string[]): Money<C>[];\nexport function allocate<C extends Currency>(value: Money<C>, weightsOrCount: number | readonly string[]): Money<C>[] {\n assertMoney(value);\n\n if (typeof weightsOrCount === 'number') return allocateEvenly(value, weightsOrCount);\n\n if (weightsOrCount.length === 0) throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot be empty');\n\n const weights = weightsOrCount.map(decimal);\n\n if (weights.some((weight) => weight.numerator < 0n)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot be negative');\n }\n\n const commonDenominator = weights.reduce((result, weight) => lcm(result, weight.denominator), 1n);\n const scaledWeights = weights.map((weight) => weight.numerator * (commonDenominator / weight.denominator));\n const totalWeight = scaledWeights.reduce((result, weight) => result + weight, 0n);\n\n if (totalWeight === 0n)\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights must include a positive value');\n\n const sign = value.amount < 0n ? -1n : 1n;\n const absolute = value.amount < 0n ? -value.amount : value.amount;\n const shares = scaledWeights.map((weight) => (absolute * weight) / totalWeight);\n let remainder = absolute - shares.reduce((result, amount) => result + amount, 0n);\n const ranked = scaledWeights\n .map((weight, index) => ({ index, remainder: (absolute * weight) % totalWeight }))\n .sort((left, right) =>\n left.remainder === right.remainder ? left.index - right.index : left.remainder > right.remainder ? -1 : 1,\n );\n\n for (const entry of ranked) {\n if (remainder === 0n) break;\n\n shares[entry.index]! += 1n;\n remainder -= 1n;\n }\n\n return shares.map((amount) => createMoney(amount * sign, value.currency));\n}\n\nfunction allocateEvenly<C extends Currency>(value: Money<C>, countValue: number): Money<C>[] {\n if (!Number.isInteger(countValue) || countValue < 1) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation count must be a positive integer');\n }\n\n const count = BigInt(countValue);\n const sign = value.amount < 0n ? -1n : 1n;\n const absolute = value.amount < 0n ? -value.amount : value.amount;\n const base = absolute / count;\n const remainder = absolute % count;\n\n return Array.from({ length: countValue }, (_, index) =>\n createMoney((base + (BigInt(index) < remainder ? 1n : 0n)) * sign, value.currency),\n );\n}\n","import { decimal, roundDivision } from './_decimal';\nimport { isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { assertMoney, createMoney } from './money';\nimport type { Currency, ExchangeRate, Money, RoundingMode } from './types';\n\nconst canonicalRates = new WeakSet<object>();\n\nexport function exchangeRate<From extends Currency, To extends Currency>({\n from,\n to,\n value,\n}: {\n from: From;\n to: To;\n value: string;\n}): ExchangeRate<From, To> {\n if (!isCurrency(from) || !isCurrency(to))\n throw new CoinsError('INVALID_CURRENCY', 'Exchange rate requires registered currencies');\n\n const parsed = decimal(value);\n\n if (parsed.numerator < 0n) throw new CoinsError('INVALID_DECIMAL', 'Exchange rates cannot be negative');\n\n const rate = Object.freeze({ from, to, value: parsed }) as ExchangeRate<From, To>;\n\n canonicalRates.add(rate);\n\n return rate;\n}\n\nexport function isExchangeRate(value: unknown): value is ExchangeRate {\n return typeof value === 'object' && value !== null && canonicalRates.has(value);\n}\n\nexport function exchange<From extends Currency, To extends Currency>(\n value: Money<From>,\n rate: ExchangeRate<From, To>,\n options: { rounding?: RoundingMode } = {},\n): Money<To> {\n assertMoney(value);\n\n if (!isExchangeRate(rate)) {\n throw new CoinsError('INVALID_EXCHANGE_RATE', 'Exchange requires a canonical exchange rate');\n }\n\n if (value.currency !== rate.from) throw new CurrencyMismatchError(value.currency.code, rate.from.code);\n\n const numerator = value.amount * rate.value.numerator * 10n ** BigInt(rate.to.minorUnit);\n const denominator = rate.value.denominator * 10n ** BigInt(rate.from.minorUnit);\n\n return createMoney(roundDivision(numerator, denominator, options.rounding ?? 'halfAwayFromZero'), rate.to);\n}\n","import { roundDivision } from './_decimal';\nimport { CoinsError } from './errors';\nimport { assertMoney } from './money';\nimport type { FormatOptions, Money, MoneyFormatPart, RoundingMode } from './types';\n\nconst MAX_FRACTION_DIGITS = 20;\nconst defaultFormatRounding: RoundingMode = 'halfAwayFromZero';\nconst integerFormatters = new Map<string, Intl.NumberFormat>();\nconst templates = new Map<string, Intl.NumberFormatPart[]>();\n\nexport function format(value: Money, options: FormatOptions = {}): string {\n return formatParts(value, options)\n .map((part) => part.value)\n .join('');\n}\n\nexport function formatParts(value: Money, options: FormatOptions = {}): MoneyFormatPart[] {\n assertMoney(value);\n\n const {\n locale = 'en-US',\n maximumFractionDigits = value.currency.minorUnit,\n minimumFractionDigits = value.currency.minorUnit,\n rounding = defaultFormatRounding,\n style = 'symbol',\n } = options;\n\n validateFractionDigits(minimumFractionDigits, maximumFractionDigits);\n\n const targetScale = 10n ** BigInt(maximumFractionDigits);\n const scaled =\n maximumFractionDigits >= value.currency.minorUnit\n ? value.amount * 10n ** BigInt(maximumFractionDigits - value.currency.minorUnit)\n : roundDivision(value.amount, 10n ** BigInt(value.currency.minorUnit - maximumFractionDigits), rounding);\n const negative = scaled < 0n;\n const absolute = negative ? -scaled : scaled;\n const integer = absolute / targetScale;\n const rawFraction =\n maximumFractionDigits === 0 ? '' : (absolute % targetScale).toString().padStart(maximumFractionDigits, '0');\n const fraction = rawFraction.replace(\n new RegExp(`0{0,${Math.max(0, maximumFractionDigits - minimumFractionDigits)}}$`),\n '',\n );\n const template = getTemplate(locale, value.currency.code, style, negative);\n const parts: MoneyFormatPart[] = [];\n let insertedInteger = false;\n\n for (const part of template) {\n if (part.type === 'group') continue;\n\n if (part.type === 'integer') {\n if (!insertedInteger) {\n parts.push({ type: 'integer', value: getIntegerFormatter(locale).format(integer) });\n insertedInteger = true;\n }\n } else if (part.type === 'decimal') {\n if (fraction) parts.push({ type: 'decimal', value: part.value });\n } else if (part.type === 'fraction') {\n if (fraction) parts.push({ type: 'fraction', value: fraction });\n } else if (part.type === 'currency' || part.type === 'minusSign' || part.type === 'plusSign') {\n parts.push({ type: part.type, value: part.value });\n } else {\n parts.push({ type: 'literal', value: part.value });\n }\n }\n\n return parts;\n}\n\nfunction validateFractionDigits(minimum: number, maximum: number): void {\n if (\n !Number.isInteger(maximum) ||\n !Number.isInteger(minimum) ||\n minimum < 0 ||\n maximum < minimum ||\n maximum > MAX_FRACTION_DIGITS\n ) {\n throw new CoinsError(\n 'FORMAT_ERROR',\n `Fraction digits must be integers satisfying 0 ≤ minimum ≤ maximum ≤ ${MAX_FRACTION_DIGITS}`,\n );\n }\n}\n\nfunction getTemplate(\n locale: string,\n currency: string,\n style: NonNullable<FormatOptions['style']>,\n negative: boolean,\n): Intl.NumberFormatPart[] {\n const key = `${locale}\\0${currency}\\0${style}\\0${negative}`;\n const cached = templates.get(key);\n\n if (cached) return cached;\n\n try {\n const template = new Intl.NumberFormat(locale, {\n currency,\n currencyDisplay: style,\n maximumFractionDigits: 1,\n minimumFractionDigits: 1,\n style: 'currency',\n }).formatToParts(negative ? -1.1 : 1.1);\n\n templates.set(key, template);\n\n return template;\n } catch (error) {\n throw new CoinsError('FORMAT_ERROR', `Cannot format currency \"${currency}\" for locale \"${locale}\"`, {\n cause: error,\n });\n }\n}\n\nfunction getIntegerFormatter(locale: string): Intl.NumberFormat {\n const cached = integerFormatters.get(locale);\n\n if (cached) return cached;\n\n try {\n const formatter = new Intl.NumberFormat(locale, { maximumFractionDigits: 0, useGrouping: true });\n\n integerFormatters.set(locale, formatter);\n\n return formatter;\n } catch (error) {\n throw new CoinsError('FORMAT_ERROR', `Cannot create number formatter for locale \"${locale}\"`, { cause: error });\n }\n}\n","import { currency } from './currency';\nimport { CoinsError } from './errors';\nimport { assertMoney, money } from './money';\nimport type { Currency, Money, MoneyJSON } from './types';\n\nconst INTEGER = /^(?:0|-[1-9]\\d*|[1-9]\\d*)$/;\nconst KEYS = ['amount', 'currency', 'unit'] as const;\n\nexport function toJSON(value: Money): MoneyJSON {\n assertMoney(value);\n\n return { amount: value.amount.toString(), currency: value.currency.code, unit: 'minor' };\n}\n\nexport function parseMoneyJSON(value: unknown, options: { currency?: (code: string) => Currency } = {}): Money {\n try {\n const payload = readPayload(value);\n const resolveCurrency = options.currency ?? currency;\n\n return money(BigInt(payload.amount), resolveCurrency(payload.currency), { unit: 'minor' });\n } catch (error) {\n throw new CoinsError('INVALID_MONEY', 'Invalid Money JSON', { cause: error });\n }\n}\n\nfunction readPayload(value: unknown): MoneyJSON {\n if (typeof value !== 'object' || value === null || Object.getPrototypeOf(value) !== Object.prototype) {\n throw new TypeError('Money JSON must be a plain object');\n }\n\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const ownKeys = Reflect.ownKeys(value);\n\n if (ownKeys.length !== KEYS.length || !KEYS.every((key) => ownKeys.includes(key))) {\n throw new TypeError('Money JSON must contain only amount, currency, and unit');\n }\n\n for (const key of KEYS) {\n const descriptor = descriptors[key];\n\n if (!descriptor || !('value' in descriptor) || descriptor.get || descriptor.set) {\n throw new TypeError(`Money JSON property \"${key}\" must be a data value`);\n }\n }\n\n const amount = descriptors.amount?.value;\n const currencyCode = descriptors.currency?.value;\n const unit = descriptors.unit?.value;\n\n if (typeof amount !== 'string' || !INTEGER.test(amount))\n throw new TypeError('Money JSON amount must be a canonical integer string');\n\n if (typeof currencyCode !== 'string' || unit !== 'minor') throw new TypeError('Money JSON currency/unit are invalid');\n\n return { amount, currency: currencyCode, unit };\n}\n"],"mappings":"AAYA,IAAa,EAAb,cAAgC,KAAM,CACpC,KAEA,YAAY,EAAsB,EAAiB,EAAwB,CACzE,MAAM,EAAS,CAAO,EACtB,KAAK,KAAO,EACZ,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAEa,EAAb,cAA2C,CAAW,CACpD,SACA,SAEA,YAAY,EAAkB,EAAkB,CAC9C,MAAM,oBAAqB,sBAAsB,EAAS,OAAO,GAAU,EAC3E,KAAK,SAAW,EAChB,KAAK,SAAW,CAClB,CACF,EAEa,EAAb,cAA0C,CAAW,CACnD,MAEA,YAAY,EAAgB,CAC1B,MAAM,mBAAoB,0BAA0B,OAAO,CAAK,EAAE,EAAE,EACpE,KAAK,MAAQ,CACf,CACF,ECtCM,EAAU,0BACV,EAAqB,IACrB,EAAqB,IAE3B,SAAgB,EAAQ,EAAwB,CAC9C,GAAI,EAAM,OAAS,EAAoB,MAAM,IAAI,EAAW,kBAAmB,2BAA2B,EAE1G,IAAM,EAAQ,EAAQ,KAAK,CAAK,EAEhC,GAAI,CAAC,EAAO,MAAM,IAAI,EAAW,kBAAmB,qBAAqB,EAAM,EAAE,EAEjF,IAAM,GAAY,EAAM,IAAM,GAAA,CAAI,QAAQ,MAAO,EAAE,EAEnD,GAAI,EAAS,OAAS,EACpB,MAAM,IAAI,EAAW,kBAAmB,mCAAmC,EAAmB,QAAQ,EAGxG,IAAM,EAAc,KAAO,OAAO,EAAS,MAAM,EAC3C,EAAW,OAAO,EAAM,EAAG,EAAI,EAAc,OAAO,GAAY,GAAG,EACnE,EAAY,EAAM,KAAO,KAAO,IAAa,GAAK,CAAC,EAAW,EAC9D,EAAU,EAAI,EAAY,GAAK,CAAC,EAAY,EAAW,CAAW,EAExE,OAAO,OAA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yDAAyD,EAG/E,IAAK,IAAM,KAAO,EAAM,CACtB,IAAM,EAAa,EAAY,GAE/B,GAAI,CAAC,GAAc,EAAE,UAAW,IAAe,EAAW,KAAO,EAAW,IAC1E,MAAU,UAAU,wBAAwB,EAAI,uBAAuB,CAE3E,CAEA,IAAM,EAAS,EAAY,QAAQ,MAC7B,EAAe,EAAY,UAAU,MACrC,EAAO,EAAY,MAAM,MAE/B,GAAI,OAAO,GAAW,UAAY,CAAC,GAAQ,KAAK,CAAM,EACpD,MAAU,UAAU,sDAAsD,EAE5E,GAAI,OAAO,GAAiB,UAAY,IAAS,QAAS,MAAU,UAAU,sCAAsC,EAEpH,MAAO,CAAE,SAAQ,SAAU,EAAc,MAAK,CAChD"}
|
|
1
|
+
{"version":3,"file":"coins.js","names":[],"sources":["../src/errors.ts","../src/_decimal.ts","../src/currency.ts","../src/money.ts","../src/aggregate.ts","../src/exchange.ts","../src/format.ts","../src/serialization.ts"],"sourcesContent":["export type CoinsErrorCode =\n | 'CURRENCY_MISMATCH'\n | 'DIVISION_BY_ZERO'\n | 'FORMAT_ERROR'\n | 'INVALID_ALLOCATION'\n | 'INVALID_CURRENCY'\n | 'INVALID_DECIMAL'\n | 'INVALID_EXCHANGE_RATE'\n | 'INVALID_MONEY'\n | 'INVALID_RANGE'\n | 'INVALID_ROUNDING';\n\nexport class CoinsError extends Error {\n protected static readonly errorName: string = 'CoinsError';\n readonly code: CoinsErrorCode;\n\n constructor(code: CoinsErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n this.name = (new.target as typeof CoinsError).errorName;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class CurrencyMismatchError extends CoinsError {\n protected static override readonly errorName = 'CurrencyMismatchError';\n readonly expected: string;\n readonly received: string;\n\n constructor(expected: string, received: string) {\n super('CURRENCY_MISMATCH', `Currency mismatch: canonical ${expected} and ${received} definitions differ`);\n this.expected = expected;\n this.received = received;\n }\n}\n\nfunction describe(value: unknown): string {\n try {\n return String(value);\n } catch {\n return '<unprintable>';\n }\n}\n\nexport class InvalidCurrencyError extends CoinsError {\n protected static override readonly errorName = 'InvalidCurrencyError';\n readonly value: unknown;\n\n constructor(value: unknown) {\n super('INVALID_CURRENCY', `Unsupported currency: \"${describe(value)}\"`);\n this.value = value;\n }\n}\n","import { CoinsError } from './errors';\nimport type { Decimal, RoundingMode } from './types';\n\nconst DECIMAL = /^(-?)(\\d+)(?:\\.(\\d+))?$/;\nconst MAX_DECIMAL_DIGITS = 1000;\nconst MAX_DECIMAL_PLACES = 100;\nconst ROUNDING_MODES = new Set<RoundingMode>([\n 'awayFromZero',\n 'ceil',\n 'floor',\n 'halfAwayFromZero',\n 'halfEven',\n 'towardZero',\n]);\n\nexport function assertRoundingMode(value: unknown): asserts value is RoundingMode {\n if (!ROUNDING_MODES.has(value as RoundingMode)) {\n throw new CoinsError('INVALID_ROUNDING', `Unknown rounding mode: ${String(value)}`);\n }\n}\n\nexport function decimal(value: string): Decimal {\n if (typeof value !== 'string') throw new CoinsError('INVALID_DECIMAL', 'Decimal input must be a string');\n if (value.length > MAX_DECIMAL_DIGITS) throw new CoinsError('INVALID_DECIMAL', 'Decimal input is too long');\n\n const match = DECIMAL.exec(value);\n\n if (!match) throw new CoinsError('INVALID_DECIMAL', `Invalid decimal: \"${value}\"`);\n\n const fraction = (match[3] ?? '').replace(/0+$/, '');\n\n if (fraction.length > MAX_DECIMAL_PLACES) {\n throw new CoinsError('INVALID_DECIMAL', `Decimal precision cannot exceed ${MAX_DECIMAL_PLACES} places`);\n }\n\n const denominator = 10n ** BigInt(fraction.length);\n const unsigned = BigInt(match[2]!) * denominator + BigInt(fraction || '0');\n const numerator = match[1] === '-' && unsigned !== 0n ? -unsigned : unsigned;\n const divisor = gcd(numerator < 0n ? -numerator : numerator, denominator);\n\n return Object.freeze({ denominator: denominator / divisor, numerator: numerator / divisor }) as Decimal;\n}\n\nexport function roundDivision(numerator: bigint, denominator: bigint, mode: RoundingMode): bigint {\n assertRoundingMode(mode);\n if (denominator <= 0n) throw new CoinsError('INVALID_DECIMAL', 'Decimal denominator must be positive');\n\n const negative = numerator < 0n;\n const absolute = negative ? -numerator : numerator;\n const quotient = absolute / denominator;\n const remainder = absolute % denominator;\n\n if (remainder === 0n) return negative ? -quotient : quotient;\n\n const increment = (() => {\n switch (mode) {\n case 'awayFromZero':\n return true;\n case 'ceil':\n return !negative;\n case 'floor':\n return negative;\n case 'halfAwayFromZero':\n return remainder * 2n >= denominator;\n case 'halfEven': {\n const doubled = remainder * 2n;\n\n return doubled > denominator || (doubled === denominator && quotient % 2n !== 0n);\n }\n case 'towardZero':\n return false;\n default:\n throw new CoinsError('INVALID_ROUNDING', `Unknown rounding mode: ${mode satisfies never}`);\n }\n })();\n\n const result = increment ? quotient + 1n : quotient;\n\n return negative ? -result : result;\n}\n\nexport function toDecimalString(amount: bigint, minorUnit: number): string {\n const negative = amount < 0n;\n const absolute = negative ? -amount : amount;\n const scale = 10n ** BigInt(minorUnit);\n const whole = absolute / scale;\n\n if (minorUnit === 0) return `${negative ? '-' : ''}${whole}`;\n\n const fraction = (absolute % scale).toString().padStart(minorUnit, '0');\n\n return `${negative ? '-' : ''}${whole}.${fraction}`;\n}\n\nexport function gcd(left: bigint, right: bigint): bigint {\n let a = left;\n let b = right;\n\n while (b !== 0n) [a, b] = [b, a % b];\n\n return a === 0n ? 1n : a;\n}\n\nexport function lcm(left: bigint, right: bigint): bigint {\n return (left / gcd(left, right)) * right;\n}\n","import { CoinsError, InvalidCurrencyError } from './errors';\nimport type { Currency, CurrencyCode } from './types';\n\nconst builtins = new Map<string, Currency>();\nconst canonicalCurrencies = new WeakSet<object>();\n\nfunction register<C extends string>(code: C, minorUnit: number): Currency<C> {\n validateDefinition(code, minorUnit);\n\n const definition = Object.freeze({ code: code as CurrencyCode<C>, minorUnit }) as Currency<C>;\n\n canonicalCurrencies.add(definition);\n\n return definition;\n}\n\nfunction builtin<C extends string>(code: C, minorUnit: number): Currency<C> {\n const definition = register(code, minorUnit);\n\n builtins.set(code, definition);\n\n return definition;\n}\n\nexport const USD = builtin('USD', 2);\nexport const EUR = builtin('EUR', 2);\nexport const GBP = builtin('GBP', 2);\nexport const JPY = builtin('JPY', 0);\nexport const KRW = builtin('KRW', 0);\nexport const BHD = builtin('BHD', 3);\nexport const KWD = builtin('KWD', 3);\n\n/** Resolve a built-in currency by code, or construct an immutable custom currency from a definition. */\nexport function currency<C extends string>(code: C): Currency<C>;\nexport function currency<C extends string>(definition: { code: C; minorUnit: number }): Currency<C>;\nexport function currency<C extends string>(input: C | { code: C; minorUnit: number }): Currency<C> {\n if (typeof input === 'string') {\n const definition = builtins.get(input);\n\n if (!definition) throw new InvalidCurrencyError(input);\n\n return definition as Currency<C>;\n }\n\n if (typeof input !== 'object' || input === null) {\n throw new CoinsError('INVALID_CURRENCY', 'Currency definition must be an object');\n }\n\n return register(input.code, input.minorUnit);\n}\n\nexport function isCurrency(value: unknown): value is Currency {\n return typeof value === 'object' && value !== null && canonicalCurrencies.has(value);\n}\n\nfunction validateDefinition(code: string, minorUnit: number): void {\n if (!/^[A-Z]{3}$/.test(code)) {\n throw new CoinsError('INVALID_CURRENCY', `Currency code must be three uppercase letters: \"${code}\"`);\n }\n\n if (!Number.isInteger(minorUnit) || minorUnit < 0 || minorUnit > 6) {\n throw new CoinsError('INVALID_CURRENCY', `Currency \"${code}\" must have 0–6 minor-unit digits`);\n }\n}\n","import { decimal, roundDivision, toDecimalString } from './_decimal';\nimport { currency, isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport type { Currency, Money, RoundingMode } from './types';\n\nconst canonicalMoney = new WeakSet<object>();\n\nconst defaultRounding: RoundingMode = 'halfAwayFromZero';\n\nconst INTEGER = /^(?:0|-[1-9]\\d*|[1-9]\\d*)$/;\nconst MAX_INTEGER_DIGITS = 1000;\n\nexport function money<C extends Currency>(amount: string, currency: C, options?: { rounding?: RoundingMode }): Money<C>;\nexport function money<C extends Currency>(amount: bigint, currency: C, options: { unit: 'minor' }): Money<C>;\nexport function money<C extends Currency>(\n amount: bigint | string,\n currency: C,\n options?: { rounding?: RoundingMode } | { unit: 'minor' },\n): Money<C> {\n assertCurrency(currency);\n\n if (typeof amount === 'bigint') {\n if (!options || !('unit' in options) || options.unit !== 'minor') {\n throw new CoinsError('INVALID_MONEY', \"Bigint amounts require { unit: 'minor' }\");\n }\n\n return createMoney(amount, currency);\n }\n\n if (options && 'unit' in options)\n throw new CoinsError('INVALID_MONEY', 'Decimal strings do not accept a unit option');\n\n const value = decimal(amount);\n const scaled = value.numerator * 10n ** BigInt(currency.minorUnit);\n const remainder = scaled % value.denominator;\n\n if (remainder !== 0n && options?.rounding === undefined) {\n throw new CoinsError('INVALID_MONEY', `Amount \"${amount}\" exceeds ${currency.code} precision; provide rounding`);\n }\n\n return createMoney(roundDivision(scaled, value.denominator, options?.rounding ?? defaultRounding), currency);\n}\n\n/**\n * Decodes untrusted/persisted data into canonical `Money`.\n * Accepts either a plain `Money`-shaped object (`{ amount: bigint, currency: Currency }`)\n * or a `MoneyJSON`-shaped object (`{ amount: string, currency: string, unit: 'minor' }`).\n * Use `money()` for trusted construction; use `decodeMoney()` for network/storage data.\n */\nexport function decodeMoney(value: unknown, options?: { currency?: (code: string) => Currency }): Money {\n if (!isPlainDataObject(value)) throw new CoinsError('INVALID_MONEY', 'Money must be a plain data object');\n\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const amountDescriptor = descriptors.amount;\n const currencyDescriptor = descriptors.currency;\n\n if (!isDataProperty(amountDescriptor) || !isDataProperty(currencyDescriptor)) {\n throw new CoinsError('INVALID_MONEY', 'Money properties must be plain data values');\n }\n\n const ownKeys = Reflect.ownKeys(value);\n\n // Plain Money: bigint amount + registered currency\n if (typeof amountDescriptor.value === 'bigint' && isCurrency(currencyDescriptor.value)) {\n if (ownKeys.length !== 2) {\n throw new CoinsError('INVALID_MONEY', 'Plain money must have exactly the keys amount and currency');\n }\n\n return createMoney(amountDescriptor.value, currencyDescriptor.value);\n }\n\n // MoneyJSON: string amount + string currency code + unit: 'minor'\n const unitDescriptor = descriptors.unit;\n if (\n typeof amountDescriptor.value === 'string' &&\n typeof currencyDescriptor.value === 'string' &&\n isDataProperty(unitDescriptor) &&\n unitDescriptor.value === 'minor'\n ) {\n if (ownKeys.length !== 3) {\n throw new CoinsError('INVALID_MONEY', 'MoneyJSON must have exactly the keys amount, currency, unit');\n }\n if (amountDescriptor.value.length > MAX_INTEGER_DIGITS) {\n throw new CoinsError('INVALID_MONEY', `Money JSON amount is too long; maximum ${MAX_INTEGER_DIGITS} characters`);\n }\n if (!INTEGER.test(amountDescriptor.value)) {\n throw new CoinsError('INVALID_MONEY', `Invalid Money JSON amount \"${amountDescriptor.value}\"`);\n }\n const resolveCurrency = options?.currency ?? currency;\n try {\n const resolvedCurrency = resolveCurrency(currencyDescriptor.value);\n\n if (!isCurrency(resolvedCurrency) || resolvedCurrency.code !== currencyDescriptor.value) {\n throw new CoinsError(\n 'INVALID_CURRENCY',\n `Currency resolver must return the canonical \"${currencyDescriptor.value}\" definition`,\n );\n }\n\n return money(BigInt(amountDescriptor.value), resolvedCurrency, { unit: 'minor' });\n } catch (error) {\n throw new CoinsError('INVALID_MONEY', `Invalid Money JSON for currency \"${currencyDescriptor.value}\"`, {\n cause: error,\n });\n }\n }\n\n throw new CoinsError(\n 'INVALID_MONEY',\n 'Money must contain bigint amount and a registered currency, or a valid MoneyJSON shape',\n );\n}\n\nexport function isMoney(value: unknown): value is Money {\n return typeof value === 'object' && value !== null && canonicalMoney.has(value);\n}\n\nexport function add<C extends Currency>(left: Money<C>, right: Money<NoInfer<C>>): Money<C> {\n assertSameCurrency(left, right);\n\n return createMoney(left.amount + right.amount, left.currency);\n}\n\nexport function subtract<C extends Currency>(left: Money<C>, right: Money<NoInfer<C>>): Money<C> {\n assertSameCurrency(left, right);\n\n return createMoney(left.amount - right.amount, left.currency);\n}\n\nexport function multiply<C extends Currency>(\n value: Money<C>,\n factor: string,\n options: { rounding?: RoundingMode } = {},\n): Money<C> {\n assertMoney(value);\n\n const scalar = decimal(factor);\n\n return createMoney(\n roundDivision(value.amount * scalar.numerator, scalar.denominator, options.rounding ?? defaultRounding),\n value.currency,\n );\n}\n\nexport function divide<C extends Currency>(\n value: Money<C>,\n divisor: string,\n options: { rounding?: RoundingMode } = {},\n): Money<C> {\n assertMoney(value);\n\n const scalar = decimal(divisor);\n\n if (scalar.numerator === 0n) throw new CoinsError('DIVISION_BY_ZERO', 'Cannot divide money by zero');\n\n const divisorMagnitude = scalar.numerator < 0n ? -scalar.numerator : scalar.numerator;\n const dividend = value.amount * scalar.denominator;\n const quotient = roundDivision(\n scalar.numerator < 0n ? -dividend : dividend,\n divisorMagnitude,\n options.rounding ?? defaultRounding,\n );\n\n return createMoney(quotient, value.currency);\n}\n\nexport function compare<C extends Currency>(left: Money<C>, right: Money<NoInfer<C>>): -1 | 0 | 1 {\n assertSameCurrency(left, right);\n\n return left.amount === right.amount ? 0 : left.amount < right.amount ? -1 : 1;\n}\n\nexport function clamp<C extends Currency>(\n value: Money<C>,\n options: { max: Money<NoInfer<C>>; min: Money<NoInfer<C>> },\n): Money<C> {\n if (compare(options.min, options.max) === 1) {\n throw new CoinsError('INVALID_RANGE', 'Clamp minimum cannot exceed maximum');\n }\n\n return compare(value, options.min) === -1 ? options.min : compare(value, options.max) === 1 ? options.max : value;\n}\n\nexport function abs<C extends Currency>(value: Money<C>): Money<C> {\n assertMoney(value);\n\n return createMoney(value.amount < 0n ? -value.amount : value.amount, value.currency);\n}\n\nexport function negate<C extends Currency>(value: Money<C>): Money<C> {\n assertMoney(value);\n\n return createMoney(-value.amount, value.currency);\n}\n\nexport function round<C extends Currency>(\n value: Money<C>,\n options: { fractionDigits: number; rounding?: RoundingMode },\n): Money<C> {\n assertMoney(value);\n\n const { fractionDigits, rounding = defaultRounding } = options;\n\n if (!Number.isInteger(fractionDigits) || fractionDigits < 0 || fractionDigits > value.currency.minorUnit) {\n throw new CoinsError('INVALID_ROUNDING', `fractionDigits must be an integer from 0 to ${value.currency.minorUnit}`);\n }\n\n const factor = 10n ** BigInt(value.currency.minorUnit - fractionDigits);\n\n return createMoney(roundDivision(value.amount, factor, rounding) * factor, value.currency);\n}\n\nexport function toDecimal(value: Money): string {\n assertMoney(value);\n\n return toDecimalString(value.amount, value.currency.minorUnit);\n}\n\nexport function createMoney<C extends Currency>(amount: bigint, currency: C): Money<C> {\n const value = Object.freeze({ amount, currency }) as Money<C>;\n\n canonicalMoney.add(value);\n\n return value;\n}\n\nexport function assertMoney(value: unknown): asserts value is Money {\n if (!isMoney(value)) {\n throw new CoinsError('INVALID_MONEY', 'Money must be a canonical @vielzeug/coins value');\n }\n}\n\nfunction assertSameCurrency(left: Money, right: Money): void {\n assertMoney(left);\n assertMoney(right);\n\n if (left.currency !== right.currency) {\n throw new CurrencyMismatchError(left.currency.code, right.currency.code);\n }\n}\n\nfunction assertCurrency(value: unknown): asserts value is Currency {\n if (!isCurrency(value)) throw new CoinsError('INVALID_CURRENCY', 'Money requires a registered currency');\n}\n\nfunction isPlainDataObject(value: unknown): value is Record<PropertyKey, unknown> {\n if (typeof value !== 'object' || value === null) return false;\n\n const prototype = Object.getPrototypeOf(value);\n\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isDataProperty(\n descriptor: PropertyDescriptor | undefined,\n): descriptor is PropertyDescriptor & { value: unknown } {\n return (\n descriptor !== undefined && 'value' in descriptor && descriptor.get === undefined && descriptor.set === undefined\n );\n}\n","import { decimal, lcm } from './_decimal';\nimport { isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { assertMoney, createMoney } from './money';\nimport type { Currency, Money } from './types';\n\nconst MAX_ALLOCATION_PARTS = 100_000;\n\nexport function sum<C extends Currency>(values: readonly Money<C>[]): Money<C>;\nexport function sum<C extends Currency>(values: Iterable<Money<C>>, options: { currency: C }): Money<C>;\nexport function sum<C extends Currency>(values: Iterable<Money<C>>, options?: { currency: C }): Money<C> {\n if (options && !isCurrency(options.currency)) {\n throw new CoinsError('INVALID_CURRENCY', 'sum() requires a canonical currency');\n }\n\n let amount = 0n;\n let currency: C | undefined = options?.currency;\n\n for (const value of values) {\n assertMoney(value);\n\n if (currency === undefined) {\n currency = value.currency;\n } else if (value.currency !== currency) {\n throw new CurrencyMismatchError(currency.code, value.currency.code);\n }\n\n amount += value.amount;\n }\n\n if (currency === undefined) throw new CoinsError('INVALID_MONEY', 'sum() of empty iterable requires { currency }');\n\n return createMoney(amount, currency);\n}\n\nexport function allocate<C extends Currency>(value: Money<C>, count: number): Money<C>[];\nexport function allocate<C extends Currency>(value: Money<C>, weights: readonly string[]): Money<C>[];\nexport function allocate<C extends Currency>(value: Money<C>, weightsOrCount: number | readonly string[]): Money<C>[] {\n assertMoney(value);\n\n if (typeof weightsOrCount === 'number') return allocateEvenly(value, weightsOrCount);\n\n if (!Array.isArray(weightsOrCount)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights must be an array');\n }\n if (weightsOrCount.length === 0) throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot be empty');\n if (weightsOrCount.length > MAX_ALLOCATION_PARTS) {\n throw new CoinsError('INVALID_ALLOCATION', `Allocation cannot exceed ${MAX_ALLOCATION_PARTS} parts`);\n }\n for (let index = 0; index < weightsOrCount.length; index++) {\n if (!Object.hasOwn(weightsOrCount, index)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot contain empty slots');\n }\n }\n\n const weights = weightsOrCount.map(decimal);\n\n if (weights.some((weight) => weight.numerator < 0n)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot be negative');\n }\n\n const commonDenominator = weights.reduce((result, weight) => lcm(result, weight.denominator), 1n);\n const scaledWeights = weights.map((weight) => weight.numerator * (commonDenominator / weight.denominator));\n const totalWeight = scaledWeights.reduce((result, weight) => result + weight, 0n);\n\n if (totalWeight === 0n)\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights must include a positive value');\n\n const sign = value.amount < 0n ? -1n : 1n;\n const absolute = value.amount < 0n ? -value.amount : value.amount;\n const shares = scaledWeights.map((weight) => (absolute * weight) / totalWeight);\n let remainder = absolute - shares.reduce((result, amount) => result + amount, 0n);\n const ranked = scaledWeights\n .map((weight, index) => ({ index, remainder: (absolute * weight) % totalWeight }))\n .sort((left, right) =>\n left.remainder === right.remainder ? left.index - right.index : left.remainder > right.remainder ? -1 : 1,\n );\n\n for (const entry of ranked) {\n if (remainder === 0n) break;\n\n shares[entry.index]! += 1n;\n remainder -= 1n;\n }\n\n return shares.map((amount) => createMoney(amount * sign, value.currency));\n}\n\nfunction allocateEvenly<C extends Currency>(value: Money<C>, countValue: number): Money<C>[] {\n if (!Number.isSafeInteger(countValue) || countValue < 1 || countValue > MAX_ALLOCATION_PARTS) {\n throw new CoinsError(\n 'INVALID_ALLOCATION',\n `Allocation count must be a positive safe integer no greater than ${MAX_ALLOCATION_PARTS}`,\n );\n }\n\n const count = BigInt(countValue);\n const sign = value.amount < 0n ? -1n : 1n;\n const absolute = value.amount < 0n ? -value.amount : value.amount;\n const base = absolute / count;\n const remainder = absolute % count;\n\n return Array.from({ length: countValue }, (_, index) =>\n createMoney((base + (BigInt(index) < remainder ? 1n : 0n)) * sign, value.currency),\n );\n}\n","import { decimal, roundDivision } from './_decimal';\nimport { isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { assertMoney, createMoney } from './money';\nimport type { Currency, ExchangeRate, Money, RoundingMode } from './types';\n\nconst canonicalRates = new WeakSet<object>();\n\nexport function exchangeRate<From extends Currency, To extends Currency>({\n from,\n to,\n value,\n}: {\n from: From;\n to: To;\n value: string;\n}): ExchangeRate<From, To> {\n if (!isCurrency(from) || !isCurrency(to))\n throw new CoinsError('INVALID_CURRENCY', 'Exchange rate requires registered currencies');\n\n const parsed = decimal(value);\n\n if (parsed.numerator <= 0n) throw new CoinsError('INVALID_DECIMAL', 'Exchange rates must be positive');\n\n const rate = Object.freeze({ from, to, value: parsed }) as ExchangeRate<From, To>;\n\n canonicalRates.add(rate);\n\n return rate;\n}\n\nexport function isExchangeRate(value: unknown): value is ExchangeRate {\n return typeof value === 'object' && value !== null && canonicalRates.has(value);\n}\n\nexport function exchange<From extends Currency, To extends Currency>(\n value: Money<From>,\n rate: ExchangeRate<From, To>,\n options: { rounding?: RoundingMode } = {},\n): Money<To> {\n assertMoney(value);\n\n if (!isExchangeRate(rate)) {\n throw new CoinsError('INVALID_EXCHANGE_RATE', 'Exchange requires a canonical exchange rate');\n }\n\n if (value.currency !== rate.from) throw new CurrencyMismatchError(value.currency.code, rate.from.code);\n\n const numerator = value.amount * rate.value.numerator * 10n ** BigInt(rate.to.minorUnit);\n const denominator = rate.value.denominator * 10n ** BigInt(rate.from.minorUnit);\n\n return createMoney(roundDivision(numerator, denominator, options.rounding ?? 'halfAwayFromZero'), rate.to);\n}\n","import { assertRoundingMode } from './_decimal';\nimport { CoinsError } from './errors';\nimport { assertMoney, toDecimal } from './money';\nimport type { FormatOptions, Money, MoneyFormatPart, RoundingMode } from './types';\n\nconst MAX_FRACTION_DIGITS = 20;\nconst defaultFormatRounding: RoundingMode = 'halfAwayFromZero';\nconst intlRoundingModes: Record<RoundingMode, Intl.NumberFormatOptions['roundingMode']> = {\n awayFromZero: 'expand',\n ceil: 'ceil',\n floor: 'floor',\n halfAwayFromZero: 'halfExpand',\n halfEven: 'halfEven',\n towardZero: 'trunc',\n};\n\nexport function format(value: Money, options: FormatOptions = {}): string {\n return formatParts(value, options)\n .map((part) => part.value)\n .join('');\n}\n\nexport function formatParts(value: Money, options: FormatOptions = {}): MoneyFormatPart[] {\n assertMoney(value);\n assertRoundingMode(options.rounding ?? defaultFormatRounding);\n\n const { maximum, minimum } = fractionDigits(value.currency.minorUnit, options);\n const style = options.style ?? 'symbol';\n\n try {\n const formatter = new Intl.NumberFormat(options.locale ?? 'en-US', {\n currency: value.currency.code,\n currencyDisplay: style,\n maximumFractionDigits: maximum,\n minimumFractionDigits: minimum,\n roundingMode: intlRoundingModes[options.rounding ?? defaultFormatRounding],\n style: 'currency',\n useGrouping: true,\n });\n\n return normalizeParts(formatter.formatToParts(toDecimal(value) as unknown as number));\n } catch (error) {\n if (error instanceof CoinsError) throw error;\n\n throw new CoinsError(\n 'FORMAT_ERROR',\n `Cannot format currency \"${value.currency.code}\" for locale \"${options.locale ?? 'en-US'}\"`,\n { cause: error },\n );\n }\n}\n\nfunction fractionDigits(scale: number, options: FormatOptions): { maximum: number; minimum: number } {\n const requestedMaximum = options.maximumFractionDigits;\n const requestedMinimum = options.minimumFractionDigits;\n\n validateFractionDigit('maximumFractionDigits', requestedMaximum);\n validateFractionDigit('minimumFractionDigits', requestedMinimum);\n\n const maximum = requestedMaximum ?? Math.max(scale, requestedMinimum ?? scale);\n const minimum = requestedMinimum ?? Math.min(scale, requestedMaximum ?? scale);\n\n if (minimum > maximum) {\n throw new CoinsError('FORMAT_ERROR', 'minimumFractionDigits cannot exceed maximumFractionDigits');\n }\n\n return { maximum, minimum };\n}\n\nfunction validateFractionDigit(name: string, value: number | undefined): void {\n if (value !== undefined && (!Number.isInteger(value) || value < 0 || value > MAX_FRACTION_DIGITS)) {\n throw new CoinsError(\n 'FORMAT_ERROR',\n `Fraction digits must be integers satisfying 0 ≤ minimum ≤ maximum ≤ ${MAX_FRACTION_DIGITS} (${name})`,\n );\n }\n}\n\nfunction normalizeParts(raw: Intl.NumberFormatPart[]): MoneyFormatPart[] {\n const parts: MoneyFormatPart[] = [];\n\n for (const part of raw) {\n if (part.type === 'integer' || part.type === 'group') {\n const previous = parts.at(-1);\n\n if (previous?.type === 'integer') {\n parts[parts.length - 1] = { type: 'integer', value: previous.value + part.value };\n } else {\n parts.push({ type: 'integer', value: part.value });\n }\n } else if (\n part.type === 'currency' ||\n part.type === 'decimal' ||\n part.type === 'fraction' ||\n part.type === 'literal' ||\n part.type === 'minusSign' ||\n part.type === 'plusSign'\n ) {\n parts.push({ type: part.type, value: part.value });\n } else {\n parts.push({ type: 'literal', value: part.value });\n }\n }\n\n return parts;\n}\n","import { assertMoney } from './money';\nimport type { Money, MoneyJSON } from './types';\n\nexport function toJSON(value: Money): MoneyJSON {\n assertMoney(value);\n\n return { amount: value.amount.toString(), currency: value.currency.code, unit: 'minor' };\n}\n"],"mappings":"AAYA,IAAa,EAAb,cAAgC,KAAM,CACpC,OAA0B,UAAoB,aAC9C,KAEA,YAAY,EAAsB,EAAiB,EAAwB,CACzE,MAAM,EAAS,CAAO,EACtB,KAAK,KAAO,EACZ,KAAK,KAAQ,WAAiC,UAC9C,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAEa,EAAb,cAA2C,CAAW,CACpD,OAAmC,UAAY,wBAC/C,SACA,SAEA,YAAY,EAAkB,EAAkB,CAC9C,MAAM,oBAAqB,gCAAgC,EAAS,OAAO,EAAS,oBAAoB,EACxG,KAAK,SAAW,EAChB,KAAK,SAAW,CAClB,CACF,EAEA,SAAS,EAAS,EAAwB,CACxC,GAAI,CACF,OAAO,OAAO,CAAK,CACrB,MAAQ,CACN,MAAO,eACT,CACF,CAEA,IAAa,EAAb,cAA0C,CAAW,CACnD,OAAmC,UAAY,uBAC/C,MAEA,YAAY,EAAgB,CAC1B,MAAM,mBAAoB,0BAA0B,EAAS,CAAK,EAAE,EAAE,EACtE,KAAK,MAAQ,CACf,CACF,ECjDM,EAAU,0BACV,EAAqB,IACrB,EAAqB,IACrB,EAAiB,IAAI,IAAkB,CAC3C,eACA,OACA,QACA,mBACA,WACA,YACF,CAAC,EAED,SAAgB,EAAmB,EAA+C,CAChF,GAAI,CAAC,EAAe,IAAI,CAAqB,EAC3C,MAAM,IAAI,EAAW,mBAAoB,0BAA0B,OAAO,CAAK,GAAG,CAEtF,CAEA,SAAgB,EAAQ,EAAwB,CAC9C,GAAI,OAAO,GAAU,SAAU,MAAM,IAAI,EAAW,kBAAmB,gCAAgC,EACvG,GAAI,EAAM,OAAS,EAAoB,MAAM,IAAI,EAAW,kBAAmB,2BAA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EAAK,EACtG,CAEJ,CAEA,SAAS,GAAe,EAAiD,CACvE,IAAM,EAA2B,CAAC,EAElC,IAAK,IAAM,KAAQ,EACjB,GAAI,EAAK,OAAS,WAAa,EAAK,OAAS,QAAS,CACpD,IAAM,EAAW,EAAM,GAAG,EAAE,EAExB,GAAU,OAAS,UACrB,EAAM,EAAM,OAAS,GAAK,CAAE,KAAM,UAAW,MAAO,EAAS,MAAQ,EAAK,KAAM,EAEhF,EAAM,KAAK,CAAE,KAAM,UAAW,MAAO,EAAK,KAAM,CAAC,CAErD,MACE,EAAK,OAAS,YACd,EAAK,OAAS,WACd,EAAK,OAAS,YACd,EAAK,OAAS,WACd,EAAK,OAAS,aACd,EAAK,OAAS,WAEd,EAAM,KAAK,CAAE,KAAM,EAAK,KAAM,MAAO,EAAK,KAAM,CAAC,EAEjD,EAAM,KAAK,CAAE,KAAM,UAAW,MAAO,EAAK,KAAM,CAAC,EAIrD,OAAO,CACT,CCtGA,SAAgB,GAAO,EAAyB,CAG9C,OAFA,EAAY,CAAK,EAEV,CAAE,OAAQ,EAAM,OAAO,SAAS,EAAG,SAAU,EAAM,SAAS,KAAM,KAAM,OAAQ,CACzF"}
|
package/dist/currency.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./errors.cjs");var t=new Map,n=new WeakSet;function r(e,t){m(e,t);let r=Object.freeze({code:e,minorUnit:t});return n.add(r),r}function i(e,n){let i=r(e,n);return t.set(e,i),i}var a=i(`USD`,2),o=i(`EUR`,2),s=i(`GBP`,2),c=i(`JPY`,0),l=i(`KRW`,0),u=i(`BHD`,3),d=i(`KWD`,3);function f(n){if(typeof n==`string`){let r=t.get(n);if(!r)throw new e.InvalidCurrencyError(n);return r}return r(n.code,n.minorUnit)}function p(e){return typeof e==`object`&&!!e&&n.has(e)}function m(t,n){if(!/^[A-Z]{3}$/.test(t))throw new e.CoinsError(`INVALID_CURRENCY`,`Currency code must be three uppercase letters: "${t}"`);if(!Number.isInteger(n)||n<0||n>6)throw new e.CoinsError(`INVALID_CURRENCY`,`Currency "${t}" must have 0–6 minor-unit digits`)}exports.BHD=u,exports.EUR=o,exports.GBP=s,exports.JPY=c,exports.KRW=l,exports.KWD=d,exports.USD=a,exports.currency=f,exports.isCurrency=p;
|
|
1
|
+
const e=require("./errors.cjs");var t=new Map,n=new WeakSet;function r(e,t){m(e,t);let r=Object.freeze({code:e,minorUnit:t});return n.add(r),r}function i(e,n){let i=r(e,n);return t.set(e,i),i}var a=i(`USD`,2),o=i(`EUR`,2),s=i(`GBP`,2),c=i(`JPY`,0),l=i(`KRW`,0),u=i(`BHD`,3),d=i(`KWD`,3);function f(n){if(typeof n==`string`){let r=t.get(n);if(!r)throw new e.InvalidCurrencyError(n);return r}if(typeof n!=`object`||!n)throw new e.CoinsError(`INVALID_CURRENCY`,`Currency definition must be an object`);return r(n.code,n.minorUnit)}function p(e){return typeof e==`object`&&!!e&&n.has(e)}function m(t,n){if(!/^[A-Z]{3}$/.test(t))throw new e.CoinsError(`INVALID_CURRENCY`,`Currency code must be three uppercase letters: "${t}"`);if(!Number.isInteger(n)||n<0||n>6)throw new e.CoinsError(`INVALID_CURRENCY`,`Currency "${t}" must have 0–6 minor-unit digits`)}exports.BHD=u,exports.EUR=o,exports.GBP=s,exports.JPY=c,exports.KRW=l,exports.KWD=d,exports.USD=a,exports.currency=f,exports.isCurrency=p;
|
|
2
2
|
//# sourceMappingURL=currency.cjs.map
|
package/dist/currency.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"currency.cjs","names":[],"sources":["../src/currency.ts"],"sourcesContent":["import { CoinsError, InvalidCurrencyError } from './errors';\nimport type { Currency, CurrencyCode } from './types';\n\nconst builtins = new Map<string, Currency>();\nconst canonicalCurrencies = new WeakSet<object>();\n\nfunction register<C extends string>(code: C, minorUnit: number): Currency<C> {\n validateDefinition(code, minorUnit);\n\n const definition = Object.freeze({ code: code as CurrencyCode<C>, minorUnit }) as Currency<C>;\n\n canonicalCurrencies.add(definition);\n\n return definition;\n}\n\nfunction builtin<C extends string>(code: C, minorUnit: number): Currency<C> {\n const definition = register(code, minorUnit);\n\n builtins.set(code, definition);\n\n return definition;\n}\n\nexport const USD = builtin('USD', 2);\nexport const EUR = builtin('EUR', 2);\nexport const GBP = builtin('GBP', 2);\nexport const JPY = builtin('JPY', 0);\nexport const KRW = builtin('KRW', 0);\nexport const BHD = builtin('BHD', 3);\nexport const KWD = builtin('KWD', 3);\n\n/** Resolve a built-in currency by code, or construct an immutable custom currency from a definition. */\nexport function currency<C extends string>(code: C): Currency<C>;\nexport function currency<C extends string>(definition: { code: C; minorUnit: number }): Currency<C>;\nexport function currency<C extends string>(input: C | { code: C; minorUnit: number }): Currency<C> {\n if (typeof input === 'string') {\n const definition = builtins.get(input);\n\n if (!definition) throw new InvalidCurrencyError(input);\n\n return definition as Currency<C>;\n }\n\n return register(input.code, input.minorUnit);\n}\n\nexport function isCurrency(value: unknown): value is Currency {\n return typeof value === 'object' && value !== null && canonicalCurrencies.has(value);\n}\n\nfunction validateDefinition(code: string, minorUnit: number): void {\n if (!/^[A-Z]{3}$/.test(code)) {\n throw new CoinsError('INVALID_CURRENCY', `Currency code must be three uppercase letters: \"${code}\"`);\n }\n\n if (!Number.isInteger(minorUnit) || minorUnit < 0 || minorUnit > 6) {\n throw new CoinsError('INVALID_CURRENCY', `Currency \"${code}\" must have 0–6 minor-unit digits`);\n }\n}\n"],"mappings":"gCAGA,IAAM,EAAW,IAAI,IACf,EAAsB,IAAI,QAEhC,SAAS,EAA2B,EAAS,EAAgC,CAC3E,EAAmB,EAAM,CAAS,EAElC,IAAM,EAAa,OAAO,OAAO,CAAQ,OAAyB,WAAU,CAAC,EAI7E,OAFA,EAAoB,IAAI,CAAU,EAE3B,CACT,CAEA,SAAS,EAA0B,EAAS,EAAgC,CAC1E,IAAM,EAAa,EAAS,EAAM,CAAS,EAI3C,OAFA,EAAS,IAAI,EAAM,CAAU,EAEtB,CACT,CAEA,IAAa,EAAM,EAAQ,MAAO,CAAC,EACtB,EAAM,EAAQ,MAAO,CAAC,EACtB,EAAM,EAAQ,MAAO,CAAC,EACtB,EAAM,EAAQ,MAAO,CAAC,EACtB,EAAM,EAAQ,MAAO,CAAC,EACtB,EAAM,EAAQ,MAAO,CAAC,EACtB,EAAM,EAAQ,MAAO,CAAC,EAKnC,SAAgB,EAA2B,EAAwD,CACjG,GAAI,OAAO,GAAU,SAAU,CAC7B,IAAM,EAAa,EAAS,IAAI,CAAK,EAErC,GAAI,CAAC,EAAY,MAAM,IAAI,EAAA,qBAAqB,CAAK,EAErD,OAAO,CACT,CAEA,OAAO,EAAS,EAAM,KAAM,EAAM,SAAS,CAC7C,CAEA,SAAgB,EAAW,EAAmC,CAC5D,OAAO,OAAO,GAAU,YAAY,GAAkB,EAAoB,IAAI,CAAK,CACrF,CAEA,SAAS,EAAmB,EAAc,EAAyB,CACjE,GAAI,CAAC,aAAa,KAAK,CAAI,EACzB,MAAM,IAAI,EAAA,WAAW,mBAAoB,mDAAmD,EAAK,EAAE,EAGrG,GAAI,CAAC,OAAO,UAAU,CAAS,GAAK,EAAY,GAAK,EAAY,EAC/D,MAAM,IAAI,EAAA,WAAW,mBAAoB,aAAa,EAAK,kCAAkC,CAEjG"}
|
|
1
|
+
{"version":3,"file":"currency.cjs","names":[],"sources":["../src/currency.ts"],"sourcesContent":["import { CoinsError, InvalidCurrencyError } from './errors';\nimport type { Currency, CurrencyCode } from './types';\n\nconst builtins = new Map<string, Currency>();\nconst canonicalCurrencies = new WeakSet<object>();\n\nfunction register<C extends string>(code: C, minorUnit: number): Currency<C> {\n validateDefinition(code, minorUnit);\n\n const definition = Object.freeze({ code: code as CurrencyCode<C>, minorUnit }) as Currency<C>;\n\n canonicalCurrencies.add(definition);\n\n return definition;\n}\n\nfunction builtin<C extends string>(code: C, minorUnit: number): Currency<C> {\n const definition = register(code, minorUnit);\n\n builtins.set(code, definition);\n\n return definition;\n}\n\nexport const USD = builtin('USD', 2);\nexport const EUR = builtin('EUR', 2);\nexport const GBP = builtin('GBP', 2);\nexport const JPY = builtin('JPY', 0);\nexport const KRW = builtin('KRW', 0);\nexport const BHD = builtin('BHD', 3);\nexport const KWD = builtin('KWD', 3);\n\n/** Resolve a built-in currency by code, or construct an immutable custom currency from a definition. */\nexport function currency<C extends string>(code: C): Currency<C>;\nexport function currency<C extends string>(definition: { code: C; minorUnit: number }): Currency<C>;\nexport function currency<C extends string>(input: C | { code: C; minorUnit: number }): Currency<C> {\n if (typeof input === 'string') {\n const definition = builtins.get(input);\n\n if (!definition) throw new InvalidCurrencyError(input);\n\n return definition as Currency<C>;\n }\n\n if (typeof input !== 'object' || input === null) {\n throw new CoinsError('INVALID_CURRENCY', 'Currency definition must be an object');\n }\n\n return register(input.code, input.minorUnit);\n}\n\nexport function isCurrency(value: unknown): value is Currency {\n return typeof value === 'object' && value !== null && canonicalCurrencies.has(value);\n}\n\nfunction validateDefinition(code: string, minorUnit: number): void {\n if (!/^[A-Z]{3}$/.test(code)) {\n throw new CoinsError('INVALID_CURRENCY', `Currency code must be three uppercase letters: \"${code}\"`);\n }\n\n if (!Number.isInteger(minorUnit) || minorUnit < 0 || minorUnit > 6) {\n throw new CoinsError('INVALID_CURRENCY', `Currency \"${code}\" must have 0–6 minor-unit digits`);\n }\n}\n"],"mappings":"gCAGA,IAAM,EAAW,IAAI,IACf,EAAsB,IAAI,QAEhC,SAAS,EAA2B,EAAS,EAAgC,CAC3E,EAAmB,EAAM,CAAS,EAElC,IAAM,EAAa,OAAO,OAAO,CAAQ,OAAyB,WAAU,CAAC,EAI7E,OAFA,EAAoB,IAAI,CAAU,EAE3B,CACT,CAEA,SAAS,EAA0B,EAAS,EAAgC,CAC1E,IAAM,EAAa,EAAS,EAAM,CAAS,EAI3C,OAFA,EAAS,IAAI,EAAM,CAAU,EAEtB,CACT,CAEA,IAAa,EAAM,EAAQ,MAAO,CAAC,EACtB,EAAM,EAAQ,MAAO,CAAC,EACtB,EAAM,E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AAM,GAAG;;;EAAoB,CAAC;AAErC,wGAAwG;AACxG,wBAAgB,QAAQ,CAAC,CAAC,SAAS,MAAM,EAAE,IAAI,EAAE,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;AACjE,wBAAgB,QAAQ,CAAC,CAAC,SAAS,MAAM,EAAE,UAAU,EAAE;IAAE,IAAI,EAAE,CAAC,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"currency.d.ts","sourceRoot":"","sources":["../src/currency.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAuBtD,eAAO,MAAM,GAAG;;;EAAoB,CAAC;AACrC,eAAO,MAAM,GAAG;;;EAAoB,CAAC;AACrC,eAAO,MAAM,GAAG;;;EAAoB,CAAC;AACrC,eAAO,MAAM,GAAG;;;EAAoB,CAAC;AACrC,eAAO,MAAM,GAAG;;;EAAoB,CAAC;AACrC,eAAO,MAAM,GAAG;;;EAAoB,CAAC;AACrC,eAAO,MAAM,GAAG;;;EAAoB,CAAC;AAErC,wGAAwG;AACxG,wBAAgB,QAAQ,CAAC,CAAC,SAAS,MAAM,EAAE,IAAI,EAAE,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;AACjE,wBAAgB,QAAQ,CAAC,CAAC,SAAS,MAAM,EAAE,UAAU,EAAE;IAAE,IAAI,EAAE,CAAC,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;AAiBpG,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,QAAQ,CAE5D"}
|
package/dist/currency.js
CHANGED
|
@@ -14,13 +14,14 @@ function a(e, t) {
|
|
|
14
14
|
return n.set(e, r), r;
|
|
15
15
|
}
|
|
16
16
|
var o = a("USD", 2), s = a("EUR", 2), c = a("GBP", 2), l = a("JPY", 0), u = a("KRW", 0), d = a("BHD", 3), f = a("KWD", 3);
|
|
17
|
-
function p(
|
|
18
|
-
if (typeof
|
|
19
|
-
let
|
|
20
|
-
if (!
|
|
21
|
-
return
|
|
17
|
+
function p(r) {
|
|
18
|
+
if (typeof r == "string") {
|
|
19
|
+
let e = n.get(r);
|
|
20
|
+
if (!e) throw new t(r);
|
|
21
|
+
return e;
|
|
22
22
|
}
|
|
23
|
-
|
|
23
|
+
if (typeof r != "object" || !r) throw new e("INVALID_CURRENCY", "Currency definition must be an object");
|
|
24
|
+
return i(r.code, r.minorUnit);
|
|
24
25
|
}
|
|
25
26
|
function m(e) {
|
|
26
27
|
return typeof e == "object" && !!e && r.has(e);
|
package/dist/currency.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"currency.js","names":[],"sources":["../src/currency.ts"],"sourcesContent":["import { CoinsError, InvalidCurrencyError } from './errors';\nimport type { Currency, CurrencyCode } from './types';\n\nconst builtins = new Map<string, Currency>();\nconst canonicalCurrencies = new WeakSet<object>();\n\nfunction register<C extends string>(code: C, minorUnit: number): Currency<C> {\n validateDefinition(code, minorUnit);\n\n const definition = Object.freeze({ code: code as CurrencyCode<C>, minorUnit }) as Currency<C>;\n\n canonicalCurrencies.add(definition);\n\n return definition;\n}\n\nfunction builtin<C extends string>(code: C, minorUnit: number): Currency<C> {\n const definition = register(code, minorUnit);\n\n builtins.set(code, definition);\n\n return definition;\n}\n\nexport const USD = builtin('USD', 2);\nexport const EUR = builtin('EUR', 2);\nexport const GBP = builtin('GBP', 2);\nexport const JPY = builtin('JPY', 0);\nexport const KRW = builtin('KRW', 0);\nexport const BHD = builtin('BHD', 3);\nexport const KWD = builtin('KWD', 3);\n\n/** Resolve a built-in currency by code, or construct an immutable custom currency from a definition. */\nexport function currency<C extends string>(code: C): Currency<C>;\nexport function currency<C extends string>(definition: { code: C; minorUnit: number }): Currency<C>;\nexport function currency<C extends string>(input: C | { code: C; minorUnit: number }): Currency<C> {\n if (typeof input === 'string') {\n const definition = builtins.get(input);\n\n if (!definition) throw new InvalidCurrencyError(input);\n\n return definition as Currency<C>;\n }\n\n return register(input.code, input.minorUnit);\n}\n\nexport function isCurrency(value: unknown): value is Currency {\n return typeof value === 'object' && value !== null && canonicalCurrencies.has(value);\n}\n\nfunction validateDefinition(code: string, minorUnit: number): void {\n if (!/^[A-Z]{3}$/.test(code)) {\n throw new CoinsError('INVALID_CURRENCY', `Currency code must be three uppercase letters: \"${code}\"`);\n }\n\n if (!Number.isInteger(minorUnit) || minorUnit < 0 || minorUnit > 6) {\n throw new CoinsError('INVALID_CURRENCY', `Currency \"${code}\" must have 0–6 minor-unit digits`);\n }\n}\n"],"mappings":";;AAGA,IAAM,oBAAW,IAAI,IAAsB,GACrC,oBAAsB,IAAI,QAAgB;AAEhD,SAAS,EAA2B,GAAS,GAAgC;CAC3E,EAAmB,GAAM,CAAS;CAElC,IAAM,IAAa,OAAO,OAAO;EAAQ;EAAyB;CAAU,CAAC;CAI7E,OAFA,EAAoB,IAAI,CAAU,GAE3B;AACT;AAEA,SAAS,EAA0B,GAAS,GAAgC;CAC1E,IAAM,IAAa,EAAS,GAAM,CAAS;CAI3C,OAFA,EAAS,IAAI,GAAM,CAAU,GAEtB;AACT;AAEA,IAAa,IAAM,EAAQ,OAAO,CAAC,GACtB,IAAM,EAAQ,OAAO,CAAC,GACtB,IAAM,EAAQ,OAAO,CAAC,GACtB,IAAM,EAAQ,OAAO,CAAC,GACtB,IAAM,EAAQ,OAAO,CAAC,GACtB,IAAM,EAAQ,OAAO,CAAC,GACtB,IAAM,EAAQ,OAAO,CAAC;AAKnC,SAAgB,EAA2B,GAAwD;CACjG,IAAI,OAAO,KAAU,UAAU;EAC7B,IAAM,IAAa,EAAS,IAAI,CAAK;EAErC,IAAI,CAAC,GAAY,MAAM,IAAI,EAAqB,CAAK;EAErD,OAAO;CACT;CAEA,OAAO,EAAS,EAAM,MAAM,EAAM,SAAS;AAC7C;AAEA,SAAgB,EAAW,GAAmC;CAC5D,OAAO,OAAO,KAAU,cAAY,KAAkB,EAAoB,IAAI,CAAK;AACrF;AAEA,SAAS,EAAmB,GAAc,GAAyB;CACjE,IAAI,CAAC,aAAa,KAAK,CAAI,GACzB,MAAM,IAAI,EAAW,oBAAoB,mDAAmD,EAAK,EAAE;CAGrG,IAAI,CAAC,OAAO,UAAU,CAAS,KAAK,IAAY,KAAK,IAAY,GAC/D,MAAM,IAAI,EAAW,oBAAoB,aAAa,EAAK,kCAAkC;AAEjG"}
|
|
1
|
+
{"version":3,"file":"currency.js","names":[],"sources":["../src/currency.ts"],"sourcesContent":["import { CoinsError, InvalidCurrencyError } from './errors';\nimport type { Currency, CurrencyCode } from './types';\n\nconst builtins = new Map<string, Currency>();\nconst canonicalCurrencies = new WeakSet<object>();\n\nfunction register<C extends string>(code: C, minorUnit: number): Currency<C> {\n validateDefinition(code, minorUnit);\n\n const definition = Object.freeze({ code: code as CurrencyCode<C>, minorUnit }) as Currency<C>;\n\n canonicalCurrencies.add(definition);\n\n return definition;\n}\n\nfunction builtin<C extends string>(code: C, minorUnit: number): Currency<C> {\n const definition = register(code, minorUnit);\n\n builtins.set(code, definition);\n\n return definition;\n}\n\nexport const USD = builtin('USD', 2);\nexport const EUR = builtin('EUR', 2);\nexport const GBP = builtin('GBP', 2);\nexport const JPY = builtin('JPY', 0);\nexport const KRW = builtin('KRW', 0);\nexport const BHD = builtin('BHD', 3);\nexport const KWD = builtin('KWD', 3);\n\n/** Resolve a built-in currency by code, or construct an immutable custom currency from a definition. */\nexport function currency<C extends string>(code: C): Currency<C>;\nexport function currency<C extends string>(definition: { code: C; minorUnit: number }): Currency<C>;\nexport function currency<C extends string>(input: C | { code: C; minorUnit: number }): Currency<C> {\n if (typeof input === 'string') {\n const definition = builtins.get(input);\n\n if (!definition) throw new InvalidCurrencyError(input);\n\n return definition as Currency<C>;\n }\n\n if (typeof input !== 'object' || input === null) {\n throw new CoinsError('INVALID_CURRENCY', 'Currency definition must be an object');\n }\n\n return register(input.code, input.minorUnit);\n}\n\nexport function isCurrency(value: unknown): value is Currency {\n return typeof value === 'object' && value !== null && canonicalCurrencies.has(value);\n}\n\nfunction validateDefinition(code: string, minorUnit: number): void {\n if (!/^[A-Z]{3}$/.test(code)) {\n throw new CoinsError('INVALID_CURRENCY', `Currency code must be three uppercase letters: \"${code}\"`);\n }\n\n if (!Number.isInteger(minorUnit) || minorUnit < 0 || minorUnit > 6) {\n throw new CoinsError('INVALID_CURRENCY', `Currency \"${code}\" must have 0–6 minor-unit digits`);\n }\n}\n"],"mappings":";;AAGA,IAAM,oBAAW,IAAI,IAAsB,GACrC,oBAAsB,IAAI,QAAgB;AAEhD,SAAS,EAA2B,GAAS,GAAgC;CAC3E,EAAmB,GAAM,CAAS;CAElC,IAAM,IAAa,OAAO,OAAO;EAAQ;EAAyB;CAAU,CAAC;CAI7E,OAFA,EAAoB,IAAI,CAAU,GAE3B;AACT;AAEA,SAAS,EAA0B,GAAS,GAAgC;CAC1E,IAAM,IAAa,EAAS,GAAM,CAAS;CAI3C,OAFA,EAAS,IAAI,GAAM,CAAU,GAEtB;AACT;AAEA,IAAa,IAAM,EAAQ,OAAO,CAAC,GACtB,IAAM,EAAQ,OAAO,CAAC,GACtB,IAAM,EAAQ,OAAO,CAAC,GACtB,IAAM,EAAQ,OAAO,CAAC,GACtB,IAAM,EAAQ,OAAO,CAAC,GACtB,IAAM,EAAQ,OAAO,CAAC,GACtB,IAAM,EAAQ,OAAO,CAAC;AAKnC,SAAgB,EAA2B,GAAwD;CACjG,IAAI,OAAO,KAAU,UAAU;EAC7B,IAAM,IAAa,EAAS,IAAI,CAAK;EAErC,IAAI,CAAC,GAAY,MAAM,IAAI,EAAqB,CAAK;EAErD,OAAO;CACT;CAEA,IAAI,OAAO,KAAU,aAAY,GAC/B,MAAM,IAAI,EAAW,oBAAoB,uCAAuC;CAGlF,OAAO,EAAS,EAAM,MAAM,EAAM,SAAS;AAC7C;AAEA,SAAgB,EAAW,GAAmC;CAC5D,OAAO,OAAO,KAAU,cAAY,KAAkB,EAAoB,IAAI,CAAK;AACrF;AAEA,SAAS,EAAmB,GAAc,GAAyB;CACjE,IAAI,CAAC,aAAa,KAAK,CAAI,GACzB,MAAM,IAAI,EAAW,oBAAoB,mDAAmD,EAAK,EAAE;CAGrG,IAAI,CAAC,OAAO,UAAU,CAAS,KAAK,IAAY,KAAK,IAAY,GAC/D,MAAM,IAAI,EAAW,oBAAoB,aAAa,EAAK,kCAAkC;AAEjG"}
|
package/dist/errors.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=new.target.
|
|
1
|
+
var e=class extends Error{static errorName=`CoinsError`;code;constructor(e,t,n){super(t,n),this.code=e,this.name=new.target.errorName,Object.setPrototypeOf(this,new.target.prototype)}},t=class extends e{static errorName=`CurrencyMismatchError`;expected;received;constructor(e,t){super(`CURRENCY_MISMATCH`,`Currency mismatch: canonical ${e} and ${t} definitions differ`),this.expected=e,this.received=t}};function n(e){try{return String(e)}catch{return`<unprintable>`}}var r=class extends e{static errorName=`InvalidCurrencyError`;value;constructor(e){super(`INVALID_CURRENCY`,`Unsupported currency: "${n(e)}"`),this.value=e}};exports.CoinsError=e,exports.CurrencyMismatchError=t,exports.InvalidCurrencyError=r;
|
|
2
2
|
//# sourceMappingURL=errors.cjs.map
|
package/dist/errors.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.cjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["export type CoinsErrorCode =\n | 'CURRENCY_MISMATCH'\n | 'DIVISION_BY_ZERO'\n | 'FORMAT_ERROR'\n | 'INVALID_ALLOCATION'\n | 'INVALID_CURRENCY'\n | 'INVALID_DECIMAL'\n | 'INVALID_EXCHANGE_RATE'\n | 'INVALID_MONEY'\n | 'INVALID_RANGE'\n | 'INVALID_ROUNDING';\n\nexport class CoinsError extends Error {\n readonly code: CoinsErrorCode;\n\n constructor(code: CoinsErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n this.name = new.target.
|
|
1
|
+
{"version":3,"file":"errors.cjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["export type CoinsErrorCode =\n | 'CURRENCY_MISMATCH'\n | 'DIVISION_BY_ZERO'\n | 'FORMAT_ERROR'\n | 'INVALID_ALLOCATION'\n | 'INVALID_CURRENCY'\n | 'INVALID_DECIMAL'\n | 'INVALID_EXCHANGE_RATE'\n | 'INVALID_MONEY'\n | 'INVALID_RANGE'\n | 'INVALID_ROUNDING';\n\nexport class CoinsError extends Error {\n protected static readonly errorName: string = 'CoinsError';\n readonly code: CoinsErrorCode;\n\n constructor(code: CoinsErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n this.name = (new.target as typeof CoinsError).errorName;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class CurrencyMismatchError extends CoinsError {\n protected static override readonly errorName = 'CurrencyMismatchError';\n readonly expected: string;\n readonly received: string;\n\n constructor(expected: string, received: string) {\n super('CURRENCY_MISMATCH', `Currency mismatch: canonical ${expected} and ${received} definitions differ`);\n this.expected = expected;\n this.received = received;\n }\n}\n\nfunction describe(value: unknown): string {\n try {\n return String(value);\n } catch {\n return '<unprintable>';\n }\n}\n\nexport class InvalidCurrencyError extends CoinsError {\n protected static override readonly errorName = 'InvalidCurrencyError';\n readonly value: unknown;\n\n constructor(value: unknown) {\n super('INVALID_CURRENCY', `Unsupported currency: \"${describe(value)}\"`);\n this.value = value;\n }\n}\n"],"mappings":"AAYA,IAAa,EAAb,cAAgC,KAAM,CACpC,OAA0B,UAAoB,aAC9C,KAEA,YAAY,EAAsB,EAAiB,EAAwB,CACzE,MAAM,EAAS,CAAO,EACtB,KAAK,KAAO,EACZ,KAAK,KAAQ,WAAiC,UAC9C,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAEa,EAAb,cAA2C,CAAW,CACpD,OAAmC,UAAY,wBAC/C,SACA,SAEA,YAAY,EAAkB,EAAkB,CAC9C,MAAM,oBAAqB,gCAAgC,EAAS,OAAO,EAAS,oBAAoB,EACxG,KAAK,SAAW,EAChB,KAAK,SAAW,CAClB,CACF,EAEA,SAAS,EAAS,EAAwB,CACxC,GAAI,CACF,OAAO,OAAO,CAAK,CACrB,MAAQ,CACN,MAAO,eACT,CACF,CAEA,IAAa,EAAb,cAA0C,CAAW,CACnD,OAAmC,UAAY,uBAC/C,MAEA,YAAY,EAAgB,CAC1B,MAAM,mBAAoB,0BAA0B,EAAS,CAAK,EAAE,EAAE,EACtE,KAAK,MAAQ,CACf,CACF"}
|
package/dist/errors.d.ts
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
export type CoinsErrorCode = 'CURRENCY_MISMATCH' | 'DIVISION_BY_ZERO' | 'FORMAT_ERROR' | 'INVALID_ALLOCATION' | 'INVALID_CURRENCY' | 'INVALID_DECIMAL' | 'INVALID_EXCHANGE_RATE' | 'INVALID_MONEY' | 'INVALID_RANGE' | 'INVALID_ROUNDING';
|
|
2
2
|
export declare class CoinsError extends Error {
|
|
3
|
+
protected static readonly errorName: string;
|
|
3
4
|
readonly code: CoinsErrorCode;
|
|
4
5
|
constructor(code: CoinsErrorCode, message: string, options?: ErrorOptions);
|
|
5
6
|
}
|
|
6
7
|
export declare class CurrencyMismatchError extends CoinsError {
|
|
8
|
+
protected static readonly errorName = "CurrencyMismatchError";
|
|
7
9
|
readonly expected: string;
|
|
8
10
|
readonly received: string;
|
|
9
11
|
constructor(expected: string, received: string);
|
|
10
12
|
}
|
|
11
13
|
export declare class InvalidCurrencyError extends CoinsError {
|
|
14
|
+
protected static readonly errorName = "InvalidCurrencyError";
|
|
12
15
|
readonly value: unknown;
|
|
13
16
|
constructor(value: unknown);
|
|
14
17
|
}
|
package/dist/errors.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,cAAc,GACtB,mBAAmB,GACnB,kBAAkB,GAClB,cAAc,GACd,oBAAoB,GACpB,kBAAkB,GAClB,iBAAiB,GACjB,uBAAuB,GACvB,eAAe,GACf,eAAe,GACf,kBAAkB,CAAC;AAEvB,qBAAa,UAAW,SAAQ,KAAK;IACnC,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAC;gBAElB,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY;CAM1E;AAED,qBAAa,qBAAsB,SAAQ,UAAU;IACnD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;gBAEd,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;CAK/C;
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,cAAc,GACtB,mBAAmB,GACnB,kBAAkB,GAClB,cAAc,GACd,oBAAoB,GACpB,kBAAkB,GAClB,iBAAiB,GACjB,uBAAuB,GACvB,eAAe,GACf,eAAe,GACf,kBAAkB,CAAC;AAEvB,qBAAa,UAAW,SAAQ,KAAK;IACnC,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAgB;IAC3D,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAC;gBAElB,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY;CAM1E;AAED,qBAAa,qBAAsB,SAAQ,UAAU;IACnD,0BAAmC,SAAS,2BAA2B;IACvE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;gBAEd,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;CAK/C;AAUD,qBAAa,oBAAqB,SAAQ,UAAU;IAClD,0BAAmC,SAAS,0BAA0B;IACtE,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;gBAEZ,KAAK,EAAE,OAAO;CAI3B"}
|
package/dist/errors.js
CHANGED
|
@@ -1,22 +1,33 @@
|
|
|
1
1
|
//#region src/errors.ts
|
|
2
2
|
var e = class extends Error {
|
|
3
|
+
static errorName = "CoinsError";
|
|
3
4
|
code;
|
|
4
5
|
constructor(e, t, n) {
|
|
5
|
-
super(t, n), this.code = e, this.name = new.target.
|
|
6
|
+
super(t, n), this.code = e, this.name = new.target.errorName, Object.setPrototypeOf(this, new.target.prototype);
|
|
6
7
|
}
|
|
7
8
|
}, t = class extends e {
|
|
9
|
+
static errorName = "CurrencyMismatchError";
|
|
8
10
|
expected;
|
|
9
11
|
received;
|
|
10
12
|
constructor(e, t) {
|
|
11
|
-
super("CURRENCY_MISMATCH", `Currency mismatch: ${e} and ${t}`), this.expected = e, this.received = t;
|
|
13
|
+
super("CURRENCY_MISMATCH", `Currency mismatch: canonical ${e} and ${t} definitions differ`), this.expected = e, this.received = t;
|
|
12
14
|
}
|
|
13
|
-
}
|
|
15
|
+
};
|
|
16
|
+
function n(e) {
|
|
17
|
+
try {
|
|
18
|
+
return String(e);
|
|
19
|
+
} catch {
|
|
20
|
+
return "<unprintable>";
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
var r = class extends e {
|
|
24
|
+
static errorName = "InvalidCurrencyError";
|
|
14
25
|
value;
|
|
15
26
|
constructor(e) {
|
|
16
|
-
super("INVALID_CURRENCY", `Unsupported currency: "${
|
|
27
|
+
super("INVALID_CURRENCY", `Unsupported currency: "${n(e)}"`), this.value = e;
|
|
17
28
|
}
|
|
18
29
|
};
|
|
19
30
|
//#endregion
|
|
20
|
-
export { e as CoinsError, t as CurrencyMismatchError,
|
|
31
|
+
export { e as CoinsError, t as CurrencyMismatchError, r as InvalidCurrencyError };
|
|
21
32
|
|
|
22
33
|
//# sourceMappingURL=errors.js.map
|
package/dist/errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["export type CoinsErrorCode =\n | 'CURRENCY_MISMATCH'\n | 'DIVISION_BY_ZERO'\n | 'FORMAT_ERROR'\n | 'INVALID_ALLOCATION'\n | 'INVALID_CURRENCY'\n | 'INVALID_DECIMAL'\n | 'INVALID_EXCHANGE_RATE'\n | 'INVALID_MONEY'\n | 'INVALID_RANGE'\n | 'INVALID_ROUNDING';\n\nexport class CoinsError extends Error {\n readonly code: CoinsErrorCode;\n\n constructor(code: CoinsErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n this.name = new.target.
|
|
1
|
+
{"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["export type CoinsErrorCode =\n | 'CURRENCY_MISMATCH'\n | 'DIVISION_BY_ZERO'\n | 'FORMAT_ERROR'\n | 'INVALID_ALLOCATION'\n | 'INVALID_CURRENCY'\n | 'INVALID_DECIMAL'\n | 'INVALID_EXCHANGE_RATE'\n | 'INVALID_MONEY'\n | 'INVALID_RANGE'\n | 'INVALID_ROUNDING';\n\nexport class CoinsError extends Error {\n protected static readonly errorName: string = 'CoinsError';\n readonly code: CoinsErrorCode;\n\n constructor(code: CoinsErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n this.name = (new.target as typeof CoinsError).errorName;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class CurrencyMismatchError extends CoinsError {\n protected static override readonly errorName = 'CurrencyMismatchError';\n readonly expected: string;\n readonly received: string;\n\n constructor(expected: string, received: string) {\n super('CURRENCY_MISMATCH', `Currency mismatch: canonical ${expected} and ${received} definitions differ`);\n this.expected = expected;\n this.received = received;\n }\n}\n\nfunction describe(value: unknown): string {\n try {\n return String(value);\n } catch {\n return '<unprintable>';\n }\n}\n\nexport class InvalidCurrencyError extends CoinsError {\n protected static override readonly errorName = 'InvalidCurrencyError';\n readonly value: unknown;\n\n constructor(value: unknown) {\n super('INVALID_CURRENCY', `Unsupported currency: \"${describe(value)}\"`);\n this.value = value;\n }\n}\n"],"mappings":";AAYA,IAAa,IAAb,cAAgC,MAAM;CACpC,OAA0B,YAAoB;CAC9C;CAEA,YAAY,GAAsB,GAAiB,GAAwB;EAIzE,AAHA,MAAM,GAAS,CAAO,GACtB,KAAK,OAAO,GACZ,KAAK,OAAQ,WAAiC,WAC9C,OAAO,eAAe,MAAM,WAAW,SAAS;CAClD;AACF,GAEa,IAAb,cAA2C,EAAW;CACpD,OAAmC,YAAY;CAC/C;CACA;CAEA,YAAY,GAAkB,GAAkB;EAG9C,AAFA,MAAM,qBAAqB,gCAAgC,EAAS,OAAO,EAAS,oBAAoB,GACxG,KAAK,WAAW,GAChB,KAAK,WAAW;CAClB;AACF;AAEA,SAAS,EAAS,GAAwB;CACxC,IAAI;EACF,OAAO,OAAO,CAAK;CACrB,QAAQ;EACN,OAAO;CACT;AACF;AAEA,IAAa,IAAb,cAA0C,EAAW;CACnD,OAAmC,YAAY;CAC/C;CAEA,YAAY,GAAgB;EAE1B,AADA,MAAM,oBAAoB,0BAA0B,EAAS,CAAK,EAAE,EAAE,GACtE,KAAK,QAAQ;CACf;AACF"}
|
package/dist/exchange.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./errors.cjs"),t=require("./_decimal.cjs"),n=require("./currency.cjs"),r=require("./money.cjs");var i=new WeakSet;function a({from:r,to:a,value:o}){if(!n.isCurrency(r)||!n.isCurrency(a))throw new e.CoinsError(`INVALID_CURRENCY`,`Exchange rate requires registered currencies`);let s=t.decimal(o);if(s.numerator
|
|
1
|
+
const e=require("./errors.cjs"),t=require("./_decimal.cjs"),n=require("./currency.cjs"),r=require("./money.cjs");var i=new WeakSet;function a({from:r,to:a,value:o}){if(!n.isCurrency(r)||!n.isCurrency(a))throw new e.CoinsError(`INVALID_CURRENCY`,`Exchange rate requires registered currencies`);let s=t.decimal(o);if(s.numerator<=0n)throw new e.CoinsError(`INVALID_DECIMAL`,`Exchange rates must be positive`);let c=Object.freeze({from:r,to:a,value:s});return i.add(c),c}function o(e){return typeof e==`object`&&!!e&&i.has(e)}function s(n,i,a={}){if(r.assertMoney(n),!o(i))throw new e.CoinsError(`INVALID_EXCHANGE_RATE`,`Exchange requires a canonical exchange rate`);if(n.currency!==i.from)throw new e.CurrencyMismatchError(n.currency.code,i.from.code);let s=n.amount*i.value.numerator*10n**BigInt(i.to.minorUnit),c=i.value.denominator*10n**BigInt(i.from.minorUnit);return r.createMoney(t.roundDivision(s,c,a.rounding??`halfAwayFromZero`),i.to)}exports.exchange=s,exports.exchangeRate=a,exports.isExchangeRate=o;
|
|
2
2
|
//# sourceMappingURL=exchange.cjs.map
|
package/dist/exchange.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"exchange.cjs","names":[],"sources":["../src/exchange.ts"],"sourcesContent":["import { decimal, roundDivision } from './_decimal';\nimport { isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { assertMoney, createMoney } from './money';\nimport type { Currency, ExchangeRate, Money, RoundingMode } from './types';\n\nconst canonicalRates = new WeakSet<object>();\n\nexport function exchangeRate<From extends Currency, To extends Currency>({\n from,\n to,\n value,\n}: {\n from: From;\n to: To;\n value: string;\n}): ExchangeRate<From, To> {\n if (!isCurrency(from) || !isCurrency(to))\n throw new CoinsError('INVALID_CURRENCY', 'Exchange rate requires registered currencies');\n\n const parsed = decimal(value);\n\n if (parsed.numerator
|
|
1
|
+
{"version":3,"file":"exchange.cjs","names":[],"sources":["../src/exchange.ts"],"sourcesContent":["import { decimal, roundDivision } from './_decimal';\nimport { isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { assertMoney, createMoney } from './money';\nimport type { Currency, ExchangeRate, Money, RoundingMode } from './types';\n\nconst canonicalRates = new WeakSet<object>();\n\nexport function exchangeRate<From extends Currency, To extends Currency>({\n from,\n to,\n value,\n}: {\n from: From;\n to: To;\n value: string;\n}): ExchangeRate<From, To> {\n if (!isCurrency(from) || !isCurrency(to))\n throw new CoinsError('INVALID_CURRENCY', 'Exchange rate requires registered currencies');\n\n const parsed = decimal(value);\n\n if (parsed.numerator <= 0n) throw new CoinsError('INVALID_DECIMAL', 'Exchange rates must be positive');\n\n const rate = Object.freeze({ from, to, value: parsed }) as ExchangeRate<From, To>;\n\n canonicalRates.add(rate);\n\n return rate;\n}\n\nexport function isExchangeRate(value: unknown): value is ExchangeRate {\n return typeof value === 'object' && value !== null && canonicalRates.has(value);\n}\n\nexport function exchange<From extends Currency, To extends Currency>(\n value: Money<From>,\n rate: ExchangeRate<From, To>,\n options: { rounding?: RoundingMode } = {},\n): Money<To> {\n assertMoney(value);\n\n if (!isExchangeRate(rate)) {\n throw new CoinsError('INVALID_EXCHANGE_RATE', 'Exchange requires a canonical exchange rate');\n }\n\n if (value.currency !== rate.from) throw new CurrencyMismatchError(value.currency.code, rate.from.code);\n\n const numerator = value.amount * rate.value.numerator * 10n ** BigInt(rate.to.minorUnit);\n const denominator = rate.value.denominator * 10n ** BigInt(rate.from.minorUnit);\n\n return createMoney(roundDivision(numerator, denominator, options.rounding ?? 'halfAwayFromZero'), rate.to);\n}\n"],"mappings":"iHAMA,IAAM,EAAiB,IAAI,QAE3B,SAAgB,EAAyD,CACvE,OACA,KACA,SAKyB,CACzB,GAAI,CAAC,EAAA,WAAW,CAAI,GAAK,CAAC,EAAA,WAAW,CAAE,EACrC,MAAM,IAAI,EAAA,WAAW,mBAAoB,8CAA8C,EAEzF,IAAM,EAAS,EAAA,QAAQ,CAAK,EAE5B,GAAI,EAAO,WAAa,GAAI,MAAM,IAAI,EAAA,WAAW,kBAAmB,iCAAiC,EAErG,IAAM,EAAO,OAAO,OAAO,CAAE,OAAM,KAAI,MAAO,CAAO,CAAC,EAItD,OAFA,EAAe,IAAI,CAAI,EAEhB,CACT,CAEA,SAAgB,EAAe,EAAuC,CACpE,OAAO,OAAO,GAAU,YAAY,GAAkB,EAAe,IAAI,CAAK,CAChF,CAEA,SAAgB,EACd,EACA,EACA,EAAuC,CAAC,EAC7B,CAGX,GAFA,EAAA,YAAY,CAAK,EAEb,CAAC,EAAe,CAAI,EACtB,MAAM,IAAI,EAAA,WAAW,wBAAyB,6CAA6C,EAG7F,GAAI,EAAM,WAAa,EAAK,KAAM,MAAM,IAAI,EAAA,sBAAsB,EAAM,SAAS,KAAM,EAAK,KAAK,IAAI,EAErG,IAAM,EAAY,EAAM,OAAS,EAAK,MAAM,UAAY,KAAO,OAAO,EAAK,GAAG,SAAS,EACjF,EAAc,EAAK,MAAM,YAAc,KAAO,OAAO,EAAK,KAAK,SAAS,EAE9E,OAAO,EAAA,YAAY,EAAA,cAAc,EAAW,EAAa,EAAQ,UAAY,kBAAkB,EAAG,EAAK,EAAE,CAC3G"}
|
package/dist/exchange.js
CHANGED
|
@@ -7,7 +7,7 @@ var s = /* @__PURE__ */ new WeakSet();
|
|
|
7
7
|
function c({ from: t, to: r, value: a }) {
|
|
8
8
|
if (!i(t) || !i(r)) throw new e("INVALID_CURRENCY", "Exchange rate requires registered currencies");
|
|
9
9
|
let o = n(a);
|
|
10
|
-
if (o.numerator
|
|
10
|
+
if (o.numerator <= 0n) throw new e("INVALID_DECIMAL", "Exchange rates must be positive");
|
|
11
11
|
let c = Object.freeze({
|
|
12
12
|
from: t,
|
|
13
13
|
to: r,
|
package/dist/exchange.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"exchange.js","names":[],"sources":["../src/exchange.ts"],"sourcesContent":["import { decimal, roundDivision } from './_decimal';\nimport { isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { assertMoney, createMoney } from './money';\nimport type { Currency, ExchangeRate, Money, RoundingMode } from './types';\n\nconst canonicalRates = new WeakSet<object>();\n\nexport function exchangeRate<From extends Currency, To extends Currency>({\n from,\n to,\n value,\n}: {\n from: From;\n to: To;\n value: string;\n}): ExchangeRate<From, To> {\n if (!isCurrency(from) || !isCurrency(to))\n throw new CoinsError('INVALID_CURRENCY', 'Exchange rate requires registered currencies');\n\n const parsed = decimal(value);\n\n if (parsed.numerator
|
|
1
|
+
{"version":3,"file":"exchange.js","names":[],"sources":["../src/exchange.ts"],"sourcesContent":["import { decimal, roundDivision } from './_decimal';\nimport { isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { assertMoney, createMoney } from './money';\nimport type { Currency, ExchangeRate, Money, RoundingMode } from './types';\n\nconst canonicalRates = new WeakSet<object>();\n\nexport function exchangeRate<From extends Currency, To extends Currency>({\n from,\n to,\n value,\n}: {\n from: From;\n to: To;\n value: string;\n}): ExchangeRate<From, To> {\n if (!isCurrency(from) || !isCurrency(to))\n throw new CoinsError('INVALID_CURRENCY', 'Exchange rate requires registered currencies');\n\n const parsed = decimal(value);\n\n if (parsed.numerator <= 0n) throw new CoinsError('INVALID_DECIMAL', 'Exchange rates must be positive');\n\n const rate = Object.freeze({ from, to, value: parsed }) as ExchangeRate<From, To>;\n\n canonicalRates.add(rate);\n\n return rate;\n}\n\nexport function isExchangeRate(value: unknown): value is ExchangeRate {\n return typeof value === 'object' && value !== null && canonicalRates.has(value);\n}\n\nexport function exchange<From extends Currency, To extends Currency>(\n value: Money<From>,\n rate: ExchangeRate<From, To>,\n options: { rounding?: RoundingMode } = {},\n): Money<To> {\n assertMoney(value);\n\n if (!isExchangeRate(rate)) {\n throw new CoinsError('INVALID_EXCHANGE_RATE', 'Exchange requires a canonical exchange rate');\n }\n\n if (value.currency !== rate.from) throw new CurrencyMismatchError(value.currency.code, rate.from.code);\n\n const numerator = value.amount * rate.value.numerator * 10n ** BigInt(rate.to.minorUnit);\n const denominator = rate.value.denominator * 10n ** BigInt(rate.from.minorUnit);\n\n return createMoney(roundDivision(numerator, denominator, options.rounding ?? 'halfAwayFromZero'), rate.to);\n}\n"],"mappings":";;;;;AAMA,IAAM,oBAAiB,IAAI,QAAgB;AAE3C,SAAgB,EAAyD,EACvE,SACA,OACA,YAKyB;CACzB,IAAI,CAAC,EAAW,CAAI,KAAK,CAAC,EAAW,CAAE,GACrC,MAAM,IAAI,EAAW,oBAAoB,8CAA8C;CAEzF,IAAM,IAAS,EAAQ,CAAK;CAE5B,IAAI,EAAO,aAAa,IAAI,MAAM,IAAI,EAAW,mBAAmB,iCAAiC;CAErG,IAAM,IAAO,OAAO,OAAO;EAAE;EAAM;EAAI,OAAO;CAAO,CAAC;CAItD,OAFA,EAAe,IAAI,CAAI,GAEhB;AACT;AAEA,SAAgB,EAAe,GAAuC;CACpE,OAAO,OAAO,KAAU,cAAY,KAAkB,EAAe,IAAI,CAAK;AAChF;AAEA,SAAgB,EACd,GACA,GACA,IAAuC,CAAC,GAC7B;CAGX,IAFA,EAAY,CAAK,GAEb,CAAC,EAAe,CAAI,GACtB,MAAM,IAAI,EAAW,yBAAyB,6CAA6C;CAG7F,IAAI,EAAM,aAAa,EAAK,MAAM,MAAM,IAAI,EAAsB,EAAM,SAAS,MAAM,EAAK,KAAK,IAAI;CAErG,IAAM,IAAY,EAAM,SAAS,EAAK,MAAM,YAAY,OAAO,OAAO,EAAK,GAAG,SAAS,GACjF,IAAc,EAAK,MAAM,cAAc,OAAO,OAAO,EAAK,KAAK,SAAS;CAE9E,OAAO,EAAY,EAAc,GAAW,GAAa,EAAQ,YAAY,kBAAkB,GAAG,EAAK,EAAE;AAC3G"}
|
package/dist/format.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./errors.cjs"),t=require("./_decimal.cjs"),n=require("./money.cjs");var r=20,i=`halfAwayFromZero`,a=
|
|
1
|
+
const e=require("./errors.cjs"),t=require("./_decimal.cjs"),n=require("./money.cjs");var r=20,i=`halfAwayFromZero`,a={awayFromZero:`expand`,ceil:`ceil`,floor:`floor`,halfAwayFromZero:`halfExpand`,halfEven:`halfEven`,towardZero:`trunc`};function o(e,t={}){return s(e,t).map(e=>e.value).join(``)}function s(r,o={}){n.assertMoney(r),t.assertRoundingMode(o.rounding??i);let{maximum:s,minimum:l}=c(r.currency.minorUnit,o),d=o.style??`symbol`;try{return u(new Intl.NumberFormat(o.locale??`en-US`,{currency:r.currency.code,currencyDisplay:d,maximumFractionDigits:s,minimumFractionDigits:l,roundingMode:a[o.rounding??i],style:`currency`,useGrouping:!0}).formatToParts(n.toDecimal(r)))}catch(t){throw t instanceof e.CoinsError?t:new e.CoinsError(`FORMAT_ERROR`,`Cannot format currency "${r.currency.code}" for locale "${o.locale??`en-US`}"`,{cause:t})}}function c(t,n){let r=n.maximumFractionDigits,i=n.minimumFractionDigits;l(`maximumFractionDigits`,r),l(`minimumFractionDigits`,i);let a=r??Math.max(t,i??t),o=i??Math.min(t,r??t);if(o>a)throw new e.CoinsError(`FORMAT_ERROR`,`minimumFractionDigits cannot exceed maximumFractionDigits`);return{maximum:a,minimum:o}}function l(t,n){if(n!==void 0&&(!Number.isInteger(n)||n<0||n>r))throw new e.CoinsError(`FORMAT_ERROR`,`Fraction digits must be integers satisfying 0 ≤ minimum ≤ maximum ≤ ${r} (${t})`)}function u(e){let t=[];for(let n of e)if(n.type===`integer`||n.type===`group`){let e=t.at(-1);e?.type===`integer`?t[t.length-1]={type:`integer`,value:e.value+n.value}:t.push({type:`integer`,value:n.value})}else n.type===`currency`||n.type===`decimal`||n.type===`fraction`||n.type===`literal`||n.type===`minusSign`||n.type===`plusSign`?t.push({type:n.type,value:n.value}):t.push({type:`literal`,value:n.value});return t}exports.format=o,exports.formatParts=s;
|
|
2
2
|
//# sourceMappingURL=format.cjs.map
|
package/dist/format.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format.cjs","names":[],"sources":["../src/format.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"format.cjs","names":[],"sources":["../src/format.ts"],"sourcesContent":["import { assertRoundingMode } from './_decimal';\nimport { CoinsError } from './errors';\nimport { assertMoney, toDecimal } from './money';\nimport type { FormatOptions, Money, MoneyFormatPart, RoundingMode } from './types';\n\nconst MAX_FRACTION_DIGITS = 20;\nconst defaultFormatRounding: RoundingMode = 'halfAwayFromZero';\nconst intlRoundingModes: Record<RoundingMode, Intl.NumberFormatOptions['roundingMode']> = {\n awayFromZero: 'expand',\n ceil: 'ceil',\n floor: 'floor',\n halfAwayFromZero: 'halfExpand',\n halfEven: 'halfEven',\n towardZero: 'trunc',\n};\n\nexport function format(value: Money, options: FormatOptions = {}): string {\n return formatParts(value, options)\n .map((part) => part.value)\n .join('');\n}\n\nexport function formatParts(value: Money, options: FormatOptions = {}): MoneyFormatPart[] {\n assertMoney(value);\n assertRoundingMode(options.rounding ?? defaultFormatRounding);\n\n const { maximum, minimum } = fractionDigits(value.currency.minorUnit, options);\n const style = options.style ?? 'symbol';\n\n try {\n const formatter = new Intl.NumberFormat(options.locale ?? 'en-US', {\n currency: value.currency.code,\n currencyDisplay: style,\n maximumFractionDigits: maximum,\n minimumFractionDigits: minimum,\n roundingMode: intlRoundingModes[options.rounding ?? defaultFormatRounding],\n style: 'currency',\n useGrouping: true,\n });\n\n return normalizeParts(formatter.formatToParts(toDecimal(value) as unknown as number));\n } catch (error) {\n if (error instanceof CoinsError) throw error;\n\n throw new CoinsError(\n 'FORMAT_ERROR',\n `Cannot format currency \"${value.currency.code}\" for locale \"${options.locale ?? 'en-US'}\"`,\n { cause: error },\n );\n }\n}\n\nfunction fractionDigits(scale: number, options: FormatOptions): { maximum: number; minimum: number } {\n const requestedMaximum = options.maximumFractionDigits;\n const requestedMinimum = options.minimumFractionDigits;\n\n validateFractionDigit('maximumFractionDigits', requestedMaximum);\n validateFractionDigit('minimumFractionDigits', requestedMinimum);\n\n const maximum = requestedMaximum ?? Math.max(scale, requestedMinimum ?? scale);\n const minimum = requestedMinimum ?? Math.min(scale, requestedMaximum ?? scale);\n\n if (minimum > maximum) {\n throw new CoinsError('FORMAT_ERROR', 'minimumFractionDigits cannot exceed maximumFractionDigits');\n }\n\n return { maximum, minimum };\n}\n\nfunction validateFractionDigit(name: string, value: number | undefined): void {\n if (value !== undefined && (!Number.isInteger(value) || value < 0 || value > MAX_FRACTION_DIGITS)) {\n throw new CoinsError(\n 'FORMAT_ERROR',\n `Fraction digits must be integers satisfying 0 ≤ minimum ≤ maximum ≤ ${MAX_FRACTION_DIGITS} (${name})`,\n );\n }\n}\n\nfunction normalizeParts(raw: Intl.NumberFormatPart[]): MoneyFormatPart[] {\n const parts: MoneyFormatPart[] = [];\n\n for (const part of raw) {\n if (part.type === 'integer' || part.type === 'group') {\n const previous = parts.at(-1);\n\n if (previous?.type === 'integer') {\n parts[parts.length - 1] = { type: 'integer', value: previous.value + part.value };\n } else {\n parts.push({ type: 'integer', value: part.value });\n }\n } else if (\n part.type === 'currency' ||\n part.type === 'decimal' ||\n part.type === 'fraction' ||\n part.type === 'literal' ||\n part.type === 'minusSign' ||\n part.type === 'plusSign'\n ) {\n parts.push({ type: part.type, value: part.value });\n } else {\n parts.push({ type: 'literal', value: part.value });\n }\n }\n\n return parts;\n}\n"],"mappings":"qFAKA,IAAM,EAAsB,GACtB,EAAsC,mBACtC,EAAoF,CACxF,aAAc,SACd,KAAM,OACN,MAAO,QACP,iBAAkB,aAClB,SAAU,WACV,WAAY,OACd,EAEA,SAAgB,EAAO,EAAc,EAAyB,CAAC,EAAW,CACxE,OAAO,EAAY,EAAO,CAAO,CAAC,CAC/B,IAAK,GAAS,EAAK,KAAK,CAAC,CACzB,KAAK,EAAE,CACZ,CAEA,SAAgB,EAAY,EAAc,EAAyB,CAAC,EAAsB,CACxF,EAAA,YAAY,CAAK,EACjB,EAAA,mBAAmB,EAAQ,UAAY,CAAqB,EAE5D,GAAM,CAAE,UAAS,WAAY,EAAe,EAAM,SAAS,UAAW,CAAO,EACvE,EAAQ,EAAQ,OAAS,SAE/B,GAAI,CAWF,OAAO,EAA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UAAW,MAAO,EAAK,KAAM,CAAC,CAErD,MACE,EAAK,OAAS,YACd,EAAK,OAAS,WACd,EAAK,OAAS,YACd,EAAK,OAAS,WACd,EAAK,OAAS,aACd,EAAK,OAAS,WAEd,EAAM,KAAK,CAAE,KAAM,EAAK,KAAM,MAAO,EAAK,KAAM,CAAC,EAEjD,EAAM,KAAK,CAAE,KAAM,UAAW,MAAO,EAAK,KAAM,CAAC,EAIrD,OAAO,CACT"}
|
package/dist/format.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format.d.ts","sourceRoot":"","sources":["../src/format.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,KAAK,EAAE,eAAe,EAAgB,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"format.d.ts","sourceRoot":"","sources":["../src/format.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,KAAK,EAAE,eAAe,EAAgB,MAAM,SAAS,CAAC;AAanF,wBAAgB,MAAM,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,GAAE,aAAkB,GAAG,MAAM,CAIxE;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,GAAE,aAAkB,GAAG,eAAe,EAAE,CA4BxF"}
|