@vielzeug/coins 2.1.1 → 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.
Files changed (63) hide show
  1. package/README.md +12 -67
  2. package/dist/_decimal.cjs +2 -0
  3. package/dist/_decimal.cjs.map +1 -0
  4. package/dist/{decimal.d.ts → _decimal.d.ts} +2 -1
  5. package/dist/_decimal.d.ts.map +1 -0
  6. package/dist/_decimal.js +64 -0
  7. package/dist/_decimal.js.map +1 -0
  8. package/dist/aggregate.cjs +1 -1
  9. package/dist/aggregate.cjs.map +1 -1
  10. package/dist/aggregate.d.ts.map +1 -1
  11. package/dist/aggregate.js +34 -30
  12. package/dist/aggregate.js.map +1 -1
  13. package/dist/coins.cjs +1 -1
  14. package/dist/coins.cjs.map +1 -1
  15. package/dist/coins.iife.js +1 -1
  16. package/dist/coins.iife.js.map +1 -1
  17. package/dist/coins.js +1 -1
  18. package/dist/coins.js.map +1 -1
  19. package/dist/currency.cjs +1 -1
  20. package/dist/currency.cjs.map +1 -1
  21. package/dist/currency.d.ts +3 -4
  22. package/dist/currency.d.ts.map +1 -1
  23. package/dist/currency.js +21 -40
  24. package/dist/currency.js.map +1 -1
  25. package/dist/errors.cjs +1 -1
  26. package/dist/errors.cjs.map +1 -1
  27. package/dist/errors.d.ts +4 -1
  28. package/dist/errors.d.ts.map +1 -1
  29. package/dist/errors.js +16 -5
  30. package/dist/errors.js.map +1 -1
  31. package/dist/exchange.cjs +1 -1
  32. package/dist/exchange.cjs.map +1 -1
  33. package/dist/exchange.d.ts +1 -0
  34. package/dist/exchange.d.ts.map +1 -1
  35. package/dist/exchange.js +13 -13
  36. package/dist/exchange.js.map +1 -1
  37. package/dist/format.cjs +1 -1
  38. package/dist/format.cjs.map +1 -1
  39. package/dist/format.d.ts.map +1 -1
  40. package/dist/format.js +54 -52
  41. package/dist/format.js.map +1 -1
  42. package/dist/index.cjs +1 -1
  43. package/dist/index.d.ts +4 -4
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +6 -6
  46. package/dist/money.cjs +1 -1
  47. package/dist/money.cjs.map +1 -1
  48. package/dist/money.d.ts +13 -5
  49. package/dist/money.d.ts.map +1 -1
  50. package/dist/money.js +77 -65
  51. package/dist/money.js.map +1 -1
  52. package/dist/serialization.cjs +1 -1
  53. package/dist/serialization.cjs.map +1 -1
  54. package/dist/serialization.d.ts +1 -4
  55. package/dist/serialization.d.ts.map +1 -1
  56. package/dist/serialization.js +6 -38
  57. package/dist/serialization.js.map +1 -1
  58. package/package.json +8 -7
  59. package/dist/decimal.cjs +0 -2
  60. package/dist/decimal.cjs.map +0 -1
  61. package/dist/decimal.d.ts.map +0 -1
  62. package/dist/decimal.js +0 -52
  63. package/dist/decimal.js.map +0 -1
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_MONEY'\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 }\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 custom = new Map<string, Currency>();\n\nfunction builtin<C extends string>(code: C, minorUnit: number): Currency<C> {\n const definition = createDefinition(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/** Custom definitions are explicit process configuration; built-ins remain immutable and separate. */\nexport function defineCurrency<C extends string>({ code, minorUnit }: { code: C; minorUnit: number }): Currency<C> {\n validateDefinition(code, minorUnit);\n\n const builtinDefinition = builtins.get(code);\n\n if (builtinDefinition) {\n if (builtinDefinition.minorUnit !== minorUnit) throw duplicateScaleError(code, builtinDefinition.minorUnit);\n\n return builtinDefinition as Currency<C>;\n }\n\n const existing = custom.get(code);\n\n if (existing) {\n if (existing.minorUnit !== minorUnit) throw duplicateScaleError(code, existing.minorUnit);\n\n return existing as Currency<C>;\n }\n\n const definition = createDefinition(code, minorUnit);\n\n custom.set(code, definition);\n\n return definition;\n}\n\nexport function currency(code: string): Currency {\n const definition = builtins.get(code) ?? custom.get(code);\n\n if (!definition) throw new InvalidCurrencyError(code);\n\n return definition;\n}\n\nexport function isCurrency(value: unknown): value is Currency {\n if (typeof value !== 'object' || value === null) return false;\n\n const candidate = value as Partial<Currency>;\n\n return (\n typeof candidate.code === 'string' &&\n (builtins.get(candidate.code) === value || custom.get(candidate.code) === value)\n );\n}\n\nexport function resolveBuiltinCurrency(code: string): Currency {\n const definition = builtins.get(code);\n\n if (!definition) throw new InvalidCurrencyError(code);\n\n return definition;\n}\n\nfunction createDefinition<C extends string>(code: C, minorUnit: number): Currency<C> {\n validateDefinition(code, minorUnit);\n\n return Object.freeze({ code: code as CurrencyCode<C>, minorUnit }) as Currency<C>;\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\nfunction duplicateScaleError(code: string, minorUnit: number): CoinsError {\n return new CoinsError('INVALID_CURRENCY', `Currency \"${code}\" already has ${minorUnit} minor-unit digits`);\n}\n","import { isCurrency } from './currency';\nimport { decimal, roundDivision, toDecimalString } from './decimal';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport type { Currency, Money, RoundingMode } from './types';\n\nconst defaultRounding: RoundingMode = 'halfAwayFromZero';\n\nexport function money<C extends Currency>(amount: string, currency: C): Money<C>;\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) {\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\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 try {\n parseMoney(value);\n\n return true;\n } catch {\n return false;\n }\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 negative = scalar.numerator < 0n;\n const absoluteDivisor = negative ? -scalar.numerator : scalar.numerator;\n const quotient = roundDivision(\n value.amount * scalar.denominator,\n absoluteDivisor,\n options.rounding ?? defaultRounding,\n );\n\n return createMoney(negative ? -quotient : 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_MONEY', '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 withMinor<C extends Currency>(amount: bigint, currency: C): Money<C> {\n assertCurrency(currency);\n\n return createMoney(amount, currency);\n}\n\nfunction createMoney<C extends Currency>(amount: bigint, currency: C): Money<C> {\n return Object.freeze({ amount, currency }) as Money<C>;\n}\n\nfunction assertMoney(value: Money): void {\n if (!Object.isFrozen(value) || !isCurrency(value.currency)) {\n throw new CoinsError('INVALID_MONEY', 'Money must be a canonical 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: Currency): void {\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 { isMoney, withMinor } 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 if (!isMoney(value)) throw new CoinsError('INVALID_MONEY', 'sum() requires canonical money values');\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 withMinor(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 if (!isMoney(value)) throw new CoinsError('INVALID_MONEY', 'allocate() requires canonical money');\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) => withMinor(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 withMinor((base + (BigInt(index) < remainder ? 1n : 0n)) * sign, value.currency),\n );\n}\n","import { isCurrency } from './currency';\nimport { decimal, roundDivision } from './decimal';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { isMoney, withMinor } from './money';\nimport type { Currency, ExchangeRate, Money, RoundingMode } from './types';\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 return Object.freeze({ from, to, value: parsed });\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 if (!isMoney(value) || !isValidRate(rate))\n throw new CoinsError('INVALID_MONEY', 'Exchange requires canonical money and rate values');\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 withMinor(roundDivision(numerator, denominator, options.rounding ?? 'halfAwayFromZero'), rate.to);\n}\n\nfunction isValidRate(value: unknown): value is ExchangeRate {\n if (typeof value !== 'object' || value === null || !Object.isFrozen(value)) return false;\n\n const rate = value as Partial<ExchangeRate>;\n\n return (\n isCurrency(rate.from) &&\n isCurrency(rate.to) &&\n typeof rate.value === 'object' &&\n rate.value !== null &&\n Object.isFrozen(rate.value) &&\n typeof rate.value.numerator === 'bigint' &&\n rate.value.numerator >= 0n &&\n typeof rate.value.denominator === 'bigint' &&\n rate.value.denominator > 0n\n );\n}\n","import { roundDivision } from './decimal';\nimport { CoinsError } from './errors';\nimport { isMoney } 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 if (!isMoney(value)) throw new CoinsError('INVALID_MONEY', 'format() requires canonical money');\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 { resolveBuiltinCurrency } from './currency';\nimport { CoinsError } from './errors';\nimport { 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 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 ?? resolveBuiltinCurrency;\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 currency = 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 currency !== 'string' || unit !== 'minor') throw new TypeError('Money JSON currency/unit are invalid');\n\n return { amount, currency, unit };\n}\n"],"mappings":"AAUA,IAAa,EAAb,cAAgC,KAAM,CACpC,KAEA,YAAY,EAAsB,EAAiB,EAAwB,CACzE,MAAM,EAAS,CAAO,EACtB,KAAK,KAAO,EACZ,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,K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/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,g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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 Map;function r(e,n){let r=h(e,n);return t.set(e,r),r}var i=r(`USD`,2),a=r(`EUR`,2),o=r(`GBP`,2),s=r(`JPY`,0),c=r(`KRW`,0),l=r(`BHD`,3),u=r(`KWD`,3);function d({code:e,minorUnit:r}){g(e,r);let i=t.get(e);if(i){if(i.minorUnit!==r)throw _(e,i.minorUnit);return i}let a=n.get(e);if(a){if(a.minorUnit!==r)throw _(e,a.minorUnit);return a}let o=h(e,r);return n.set(e,o),o}function f(r){let i=t.get(r)??n.get(r);if(!i)throw new e.InvalidCurrencyError(r);return i}function p(e){if(typeof e!=`object`||!e)return!1;let r=e;return typeof r.code==`string`&&(t.get(r.code)===e||n.get(r.code)===e)}function m(n){let r=t.get(n);if(!r)throw new e.InvalidCurrencyError(n);return r}function h(e,t){return g(e,t),Object.freeze({code:e,minorUnit:t})}function g(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`)}function _(t,n){return new e.CoinsError(`INVALID_CURRENCY`,`Currency "${t}" already has ${n} minor-unit digits`)}exports.BHD=l,exports.EUR=a,exports.GBP=o,exports.JPY=s,exports.KRW=c,exports.KWD=u,exports.USD=i,exports.currency=f,exports.defineCurrency=d,exports.isCurrency=p,exports.resolveBuiltinCurrency=m;
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
@@ -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 custom = new Map<string, Currency>();\n\nfunction builtin<C extends string>(code: C, minorUnit: number): Currency<C> {\n const definition = createDefinition(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/** Custom definitions are explicit process configuration; built-ins remain immutable and separate. */\nexport function defineCurrency<C extends string>({ code, minorUnit }: { code: C; minorUnit: number }): Currency<C> {\n validateDefinition(code, minorUnit);\n\n const builtinDefinition = builtins.get(code);\n\n if (builtinDefinition) {\n if (builtinDefinition.minorUnit !== minorUnit) throw duplicateScaleError(code, builtinDefinition.minorUnit);\n\n return builtinDefinition as Currency<C>;\n }\n\n const existing = custom.get(code);\n\n if (existing) {\n if (existing.minorUnit !== minorUnit) throw duplicateScaleError(code, existing.minorUnit);\n\n return existing as Currency<C>;\n }\n\n const definition = createDefinition(code, minorUnit);\n\n custom.set(code, definition);\n\n return definition;\n}\n\nexport function currency(code: string): Currency {\n const definition = builtins.get(code) ?? custom.get(code);\n\n if (!definition) throw new InvalidCurrencyError(code);\n\n return definition;\n}\n\nexport function isCurrency(value: unknown): value is Currency {\n if (typeof value !== 'object' || value === null) return false;\n\n const candidate = value as Partial<Currency>;\n\n return (\n typeof candidate.code === 'string' &&\n (builtins.get(candidate.code) === value || custom.get(candidate.code) === value)\n );\n}\n\nexport function resolveBuiltinCurrency(code: string): Currency {\n const definition = builtins.get(code);\n\n if (!definition) throw new InvalidCurrencyError(code);\n\n return definition;\n}\n\nfunction createDefinition<C extends string>(code: C, minorUnit: number): Currency<C> {\n validateDefinition(code, minorUnit);\n\n return Object.freeze({ code: code as CurrencyCode<C>, minorUnit }) as Currency<C>;\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\nfunction duplicateScaleError(code: string, minorUnit: number): CoinsError {\n return new CoinsError('INVALID_CURRENCY', `Currency \"${code}\" already has ${minorUnit} minor-unit digits`);\n}\n"],"mappings":"gCAGA,IAAM,EAAW,IAAI,IACf,EAAS,IAAI,IAEnB,SAAS,EAA0B,EAAS,EAAgC,CAC1E,IAAM,EAAa,EAAiB,E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S,EAAgC,CAGnF,OAFA,EAAmB,EAAM,CAAS,EAE3B,OAAO,OAAO,CAAQ,OAAyB,WAAU,CAAC,CACnE,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,CAEA,SAAS,EAAoB,EAAc,EAA+B,CACxE,OAAO,IAAI,EAAA,WAAW,mBAAoB,aAAa,EAAK,gBAAgB,EAAU,mBAAmB,CAC3G"}
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,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,GAAI,OAAO,GAAU,WAAY,EAC/B,MAAM,IAAI,EAAA,WAAW,mBAAoB,uCAAuC,EAGlF,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"}
@@ -27,12 +27,11 @@ export declare const KWD: Readonly<{
27
27
  code: CurrencyCode<"KWD">;
28
28
  minorUnit: number;
29
29
  }>;
30
- /** Custom definitions are explicit process configuration; built-ins remain immutable and separate. */
31
- export declare function defineCurrency<C extends string>({ code, minorUnit }: {
30
+ /** Resolve a built-in currency by code, or construct an immutable custom currency from a definition. */
31
+ export declare function currency<C extends string>(code: C): Currency<C>;
32
+ export declare function currency<C extends string>(definition: {
32
33
  code: C;
33
34
  minorUnit: number;
34
35
  }): Currency<C>;
35
- export declare function currency(code: string): Currency;
36
36
  export declare function isCurrency(value: unknown): value is Currency;
37
- export declare function resolveBuiltinCurrency(code: string): Currency;
38
37
  //# sourceMappingURL=currency.d.ts.map
@@ -1 +1 @@
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;AAatD,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,GA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B,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,QAAQ,CAE5D"}
package/dist/currency.js CHANGED
@@ -1,55 +1,36 @@
1
1
  import { CoinsError as e, InvalidCurrencyError as t } from "./errors.js";
2
2
  //#region src/currency.ts
3
- var n = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Map();
3
+ var n = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new WeakSet();
4
4
  function i(e, t) {
5
- let r = g(e, t);
5
+ h(e, t);
6
+ let n = Object.freeze({
7
+ code: e,
8
+ minorUnit: t
9
+ });
10
+ return r.add(n), n;
11
+ }
12
+ function a(e, t) {
13
+ let r = i(e, t);
6
14
  return n.set(e, r), r;
7
15
  }
8
- 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);
9
- function f({ code: e, minorUnit: t }) {
10
- _(e, t);
11
- let i = n.get(e);
12
- if (i) {
13
- if (i.minorUnit !== t) throw v(e, i.minorUnit);
14
- return i;
15
- }
16
- let a = r.get(e);
17
- if (a) {
18
- if (a.minorUnit !== t) throw v(e, a.minorUnit);
19
- return a;
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(r) {
18
+ if (typeof r == "string") {
19
+ let e = n.get(r);
20
+ if (!e) throw new t(r);
21
+ return e;
20
22
  }
21
- let o = g(e, t);
22
- return r.set(e, o), o;
23
- }
24
- function p(e) {
25
- let i = n.get(e) ?? r.get(e);
26
- if (!i) throw new t(e);
27
- return i;
23
+ if (typeof r != "object" || !r) throw new e("INVALID_CURRENCY", "Currency definition must be an object");
24
+ return i(r.code, r.minorUnit);
28
25
  }
29
26
  function m(e) {
30
- if (typeof e != "object" || !e) return !1;
31
- let t = e;
32
- return typeof t.code == "string" && (n.get(t.code) === e || r.get(t.code) === e);
27
+ return typeof e == "object" && !!e && r.has(e);
33
28
  }
34
- function h(e) {
35
- let r = n.get(e);
36
- if (!r) throw new t(e);
37
- return r;
38
- }
39
- function g(e, t) {
40
- return _(e, t), Object.freeze({
41
- code: e,
42
- minorUnit: t
43
- });
44
- }
45
- function _(t, n) {
29
+ function h(t, n) {
46
30
  if (!/^[A-Z]{3}$/.test(t)) throw new e("INVALID_CURRENCY", `Currency code must be three uppercase letters: "${t}"`);
47
31
  if (!Number.isInteger(n) || n < 0 || n > 6) throw new e("INVALID_CURRENCY", `Currency "${t}" must have 0–6 minor-unit digits`);
48
32
  }
49
- function v(t, n) {
50
- return new e("INVALID_CURRENCY", `Currency "${t}" already has ${n} minor-unit digits`);
51
- }
52
33
  //#endregion
53
- export { u as BHD, o as EUR, s as GBP, c as JPY, l as KRW, d as KWD, a as USD, p as currency, f as defineCurrency, m as isCurrency, h as resolveBuiltinCurrency };
34
+ export { d as BHD, s as EUR, c as GBP, l as JPY, u as KRW, f as KWD, o as USD, p as currency, m as isCurrency };
54
35
 
55
36
  //# sourceMappingURL=currency.js.map
@@ -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 custom = new Map<string, Currency>();\n\nfunction builtin<C extends string>(code: C, minorUnit: number): Currency<C> {\n const definition = createDefinition(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/** Custom definitions are explicit process configuration; built-ins remain immutable and separate. */\nexport function defineCurrency<C extends string>({ code, minorUnit }: { code: C; minorUnit: number }): Currency<C> {\n validateDefinition(code, minorUnit);\n\n const builtinDefinition = builtins.get(code);\n\n if (builtinDefinition) {\n if (builtinDefinition.minorUnit !== minorUnit) throw duplicateScaleError(code, builtinDefinition.minorUnit);\n\n return builtinDefinition as Currency<C>;\n }\n\n const existing = custom.get(code);\n\n if (existing) {\n if (existing.minorUnit !== minorUnit) throw duplicateScaleError(code, existing.minorUnit);\n\n return existing as Currency<C>;\n }\n\n const definition = createDefinition(code, minorUnit);\n\n custom.set(code, definition);\n\n return definition;\n}\n\nexport function currency(code: string): Currency {\n const definition = builtins.get(code) ?? custom.get(code);\n\n if (!definition) throw new InvalidCurrencyError(code);\n\n return definition;\n}\n\nexport function isCurrency(value: unknown): value is Currency {\n if (typeof value !== 'object' || value === null) return false;\n\n const candidate = value as Partial<Currency>;\n\n return (\n typeof candidate.code === 'string' &&\n (builtins.get(candidate.code) === value || custom.get(candidate.code) === value)\n );\n}\n\nexport function resolveBuiltinCurrency(code: string): Currency {\n const definition = builtins.get(code);\n\n if (!definition) throw new InvalidCurrencyError(code);\n\n return definition;\n}\n\nfunction createDefinition<C extends string>(code: C, minorUnit: number): Currency<C> {\n validateDefinition(code, minorUnit);\n\n return Object.freeze({ code: code as CurrencyCode<C>, minorUnit }) as Currency<C>;\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\nfunction duplicateScaleError(code: string, minorUnit: number): CoinsError {\n return new CoinsError('INVALID_CURRENCY', `Currency \"${code}\" already has ${minorUnit} minor-unit digits`);\n}\n"],"mappings":";;AAGA,IAAM,oBAAW,IAAI,IAAsB,GACrC,oBAAS,IAAI,IAAsB;AAEzC,SAAS,EAA0B,GAAS,GAAgC;CAC1E,IAAM,IAAa,EAAiB,GAAM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OAFA,EAAmB,GAAM,CAAS,GAE3B,OAAO,OAAO;EAAQ;EAAyB;CAAU,CAAC;AACnE;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;AAEA,SAAS,EAAoB,GAAc,GAA+B;CACxE,OAAO,IAAI,EAAW,oBAAoB,aAAa,EAAK,gBAAgB,EAAU,mBAAmB;AAC3G"}
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.name,Object.setPrototypeOf(this,new.target.prototype)}},t=class extends e{expected;received;constructor(e,t){super(`CURRENCY_MISMATCH`,`Currency mismatch: ${e} and ${t}`),this.expected=e,this.received=t}},n=class extends e{value;constructor(e){super(`INVALID_CURRENCY`,`Unsupported currency: "${String(e)}"`),this.value=e}};exports.CoinsError=e,exports.CurrencyMismatchError=t,exports.InvalidCurrencyError=n;
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
@@ -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_MONEY'\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"],"mappings":"AAUA,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"}
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
- export type CoinsErrorCode = 'CURRENCY_MISMATCH' | 'DIVISION_BY_ZERO' | 'FORMAT_ERROR' | 'INVALID_ALLOCATION' | 'INVALID_CURRENCY' | 'INVALID_DECIMAL' | 'INVALID_MONEY' | 'INVALID_ROUNDING';
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
  }
@@ -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,eAAe,GACf,kBAAkB,CAAC;AAEvB,qBAAa,UAAW,SAAQ,KAAK;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AO;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.name, Object.setPrototypeOf(this, new.target.prototype);
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
- }, n = class extends e {
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: "${String(e)}"`), this.value = e;
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, n as InvalidCurrencyError };
31
+ export { e as CoinsError, t as CurrencyMismatchError, r as InvalidCurrencyError };
21
32
 
22
33
  //# sourceMappingURL=errors.js.map
@@ -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_MONEY'\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"],"mappings":";AAUA,IAAa,IAAb,cAAgC,MAAM;CACpC;CAEA,YAAY,GAAsB,GAAiB,GAAwB;EAIzE,AAHA,MAAM,GAAS,CAAO,GACtB,KAAK,OAAO,GACZ,KAAK,OAAO,WAAW,MACvB,OAAO,eAAe,MAAM,WAAW,SAAS;CAClD;AACF,GAEa,IAAb,cAA2C,EAAW;CACpD;CACA;CAEA,YAAY,GAAkB,GAAkB;EAG9C,AAFA,MAAM,qBAAqB,sBAAsB,EAAS,OAAO,GAAU,GAC3E,KAAK,WAAW,GAChB,KAAK,WAAW;CAClB;AACF,GAEa,IAAb,cAA0C,EAAW;CACnD;CAEA,YAAY,GAAgB;EAE1B,AADA,MAAM,oBAAoB,0BAA0B,OAAO,CAAK,EAAE,EAAE,GACpE,KAAK,QAAQ;CACf;AACF"}
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");function i({from:r,to:i,value:a}){if(!n.isCurrency(r)||!n.isCurrency(i))throw new e.CoinsError(`INVALID_CURRENCY`,`Exchange rate requires registered currencies`);let o=t.decimal(a);if(o.numerator<0n)throw new e.CoinsError(`INVALID_DECIMAL`,`Exchange rates cannot be negative`);return Object.freeze({from:r,to:i,value:o})}function a(n,i,a={}){if(!r.isMoney(n)||!o(i))throw new e.CoinsError(`INVALID_MONEY`,`Exchange requires canonical money and rate values`);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.withMinor(t.roundDivision(s,c,a.rounding??`halfAwayFromZero`),i.to)}function o(e){if(typeof e!=`object`||!e||!Object.isFrozen(e))return!1;let t=e;return n.isCurrency(t.from)&&n.isCurrency(t.to)&&typeof t.value==`object`&&t.value!==null&&Object.isFrozen(t.value)&&typeof t.value.numerator==`bigint`&&t.value.numerator>=0n&&typeof t.value.denominator==`bigint`&&t.value.denominator>0n}exports.exchange=a,exports.exchangeRate=i;
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
@@ -1 +1 @@
1
- {"version":3,"file":"exchange.cjs","names":[],"sources":["../src/exchange.ts"],"sourcesContent":["import { isCurrency } from './currency';\nimport { decimal, roundDivision } from './decimal';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { isMoney, withMinor } from './money';\nimport type { Currency, ExchangeRate, Money, RoundingMode } from './types';\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 return Object.freeze({ from, to, value: parsed });\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 if (!isMoney(value) || !isValidRate(rate))\n throw new CoinsError('INVALID_MONEY', 'Exchange requires canonical money and rate values');\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 withMinor(roundDivision(numerator, denominator, options.rounding ?? 'halfAwayFromZero'), rate.to);\n}\n\nfunction isValidRate(value: unknown): value is ExchangeRate {\n if (typeof value !== 'object' || value === null || !Object.isFrozen(value)) return false;\n\n const rate = value as Partial<ExchangeRate>;\n\n return (\n isCurrency(rate.from) &&\n isCurrency(rate.to) &&\n typeof rate.value === 'object' &&\n rate.value !== null &&\n Object.isFrozen(rate.value) &&\n typeof rate.value.numerator === 'bigint' &&\n rate.value.numerator >= 0n &&\n typeof rate.value.denominator === 'bigint' &&\n rate.value.denominator > 0n\n );\n}\n"],"mappings":"gHAMA,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,UAAY,GAAI,MAAM,IAAI,EAAA,WAAW,kBAAmB,mCAAmC,EAEtG,OAAO,OAAO,OAAO,CAAE,OAAM,KAAI,MAAO,CAAO,CAAC,CAClD,CAEA,SAAgB,EACd,EACA,EACA,EAAuC,CAAC,EAC7B,CACX,GAAI,CAAC,EAAA,QAAQ,CAAK,GAAK,CAAC,EAAY,CAAI,EACtC,MAAM,IAAI,EAAA,WAAW,gBAAiB,mDAAmD,EAE3F,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,UAAU,EAAA,cAAc,EAAW,EAAa,EAAQ,UAAY,kBAAkB,EAAG,EAAK,EAAE,CACzG,CAEA,SAAS,EAAY,EAAuC,CAC1D,GAAI,OAAO,GAAU,WAAY,GAAkB,CAAC,OAAO,SAAS,CAAK,EAAG,MAAO,GAEnF,IAAM,EAAO,EAEb,OACE,EAAA,WAAW,EAAK,IAAI,GACpB,EAAA,WAAW,EAAK,EAAE,GAClB,OAAO,EAAK,OAAU,UACtB,EAAK,QAAU,MACf,OAAO,SAAS,EAAK,KAAK,GAC1B,OAAO,EAAK,MAAM,WAAc,UAChC,EAAK,MAAM,WAAa,IACxB,OAAO,EAAK,MAAM,aAAgB,UAClC,EAAK,MAAM,YAAc,EAE7B"}
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"}
@@ -4,6 +4,7 @@ export declare function exchangeRate<From extends Currency, To extends Currency>
4
4
  to: To;
5
5
  value: string;
6
6
  }): ExchangeRate<From, To>;
7
+ export declare function isExchangeRate(value: unknown): value is ExchangeRate;
7
8
  export declare function exchange<From extends Currency, To extends Currency>(value: Money<From>, rate: ExchangeRate<From, To>, options?: {
8
9
  rounding?: RoundingMode;
9
10
  }): Money<To>;
@@ -1 +1 @@
1
- {"version":3,"file":"exchange.d.ts","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Q,EACjE,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,IAAI,EAAE,YAAY,CAAC,IAAI,EAAE,EAAE,CAAC,EAC5B,OAAO,GAAE;IAAE,QAAQ,CAAC,EAAE,YAAY,CAAA;CAAO,GACxC,KAAK,CAAC,EAAE,CAAC,CAaX"}
package/dist/exchange.js CHANGED
@@ -1,30 +1,30 @@
1
1
  import { CoinsError as e, CurrencyMismatchError as t } from "./errors.js";
2
- import { decimal as n, roundDivision as r } from "./decimal.js";
2
+ import { decimal as n, roundDivision as r } from "./_decimal.js";
3
3
  import { isCurrency as i } from "./currency.js";
4
- import { isMoney as a, withMinor as o } from "./money.js";
4
+ import { assertMoney as a, createMoney as o } from "./money.js";
5
5
  //#region src/exchange.ts
6
- function s({ from: t, to: r, value: a }) {
6
+ var s = /* @__PURE__ */ new WeakSet();
7
+ function c({ from: t, to: r, value: a }) {
7
8
  if (!i(t) || !i(r)) throw new e("INVALID_CURRENCY", "Exchange rate requires registered currencies");
8
9
  let o = n(a);
9
- if (o.numerator < 0n) throw new e("INVALID_DECIMAL", "Exchange rates cannot be negative");
10
- return Object.freeze({
10
+ if (o.numerator <= 0n) throw new e("INVALID_DECIMAL", "Exchange rates must be positive");
11
+ let c = Object.freeze({
11
12
  from: t,
12
13
  to: r,
13
14
  value: o
14
15
  });
16
+ return s.add(c), c;
15
17
  }
16
- function c(n, i, s = {}) {
17
- if (!a(n) || !l(i)) throw new e("INVALID_MONEY", "Exchange requires canonical money and rate values");
18
+ function l(e) {
19
+ return typeof e == "object" && !!e && s.has(e);
20
+ }
21
+ function u(n, i, s = {}) {
22
+ if (a(n), !l(i)) throw new e("INVALID_EXCHANGE_RATE", "Exchange requires a canonical exchange rate");
18
23
  if (n.currency !== i.from) throw new t(n.currency.code, i.from.code);
19
24
  let c = n.amount * i.value.numerator * 10n ** BigInt(i.to.minorUnit), u = i.value.denominator * 10n ** BigInt(i.from.minorUnit);
20
25
  return o(r(c, u, s.rounding ?? "halfAwayFromZero"), i.to);
21
26
  }
22
- function l(e) {
23
- if (typeof e != "object" || !e || !Object.isFrozen(e)) return !1;
24
- let t = e;
25
- return i(t.from) && i(t.to) && typeof t.value == "object" && t.value !== null && Object.isFrozen(t.value) && typeof t.value.numerator == "bigint" && t.value.numerator >= 0n && typeof t.value.denominator == "bigint" && t.value.denominator > 0n;
26
- }
27
27
  //#endregion
28
- export { c as exchange, s as exchangeRate };
28
+ export { u as exchange, c as exchangeRate, l as isExchangeRate };
29
29
 
30
30
  //# sourceMappingURL=exchange.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"exchange.js","names":[],"sources":["../src/exchange.ts"],"sourcesContent":["import { isCurrency } from './currency';\nimport { decimal, roundDivision } from './decimal';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { isMoney, withMinor } from './money';\nimport type { Currency, ExchangeRate, Money, RoundingMode } from './types';\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 return Object.freeze({ from, to, value: parsed });\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 if (!isMoney(value) || !isValidRate(rate))\n throw new CoinsError('INVALID_MONEY', 'Exchange requires canonical money and rate values');\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 withMinor(roundDivision(numerator, denominator, options.rounding ?? 'halfAwayFromZero'), rate.to);\n}\n\nfunction isValidRate(value: unknown): value is ExchangeRate {\n if (typeof value !== 'object' || value === null || !Object.isFrozen(value)) return false;\n\n const rate = value as Partial<ExchangeRate>;\n\n return (\n isCurrency(rate.from) &&\n isCurrency(rate.to) &&\n typeof rate.value === 'object' &&\n rate.value !== null &&\n Object.isFrozen(rate.value) &&\n typeof rate.value.numerator === 'bigint' &&\n rate.value.numerator >= 0n &&\n typeof rate.value.denominator === 'bigint' &&\n rate.value.denominator > 0n\n );\n}\n"],"mappings":";;;;;AAMA,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,YAAY,IAAI,MAAM,IAAI,EAAW,mBAAmB,mCAAmC;CAEtG,OAAO,OAAO,OAAO;EAAE;EAAM;EAAI,OAAO;CAAO,CAAC;AAClD;AAEA,SAAgB,EACd,GACA,GACA,IAAuC,CAAC,GAC7B;CACX,IAAI,CAAC,EAAQ,CAAK,KAAK,CAAC,EAAY,CAAI,GACtC,MAAM,IAAI,EAAW,iBAAiB,mDAAmD;CAE3F,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,EAAU,EAAc,GAAW,GAAa,EAAQ,YAAY,kBAAkB,GAAG,EAAK,EAAE;AACzG;AAEA,SAAS,EAAY,GAAuC;CAC1D,IAAI,OAAO,KAAU,aAAY,KAAkB,CAAC,OAAO,SAAS,CAAK,GAAG,OAAO;CAEnF,IAAM,IAAO;CAEb,OACE,EAAW,EAAK,IAAI,KACpB,EAAW,EAAK,EAAE,KAClB,OAAO,EAAK,SAAU,YACtB,EAAK,UAAU,QACf,OAAO,SAAS,EAAK,KAAK,KAC1B,OAAO,EAAK,MAAM,aAAc,YAChC,EAAK,MAAM,aAAa,MACxB,OAAO,EAAK,MAAM,eAAgB,YAClC,EAAK,MAAM,cAAc;AAE7B"}
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"}