@vielzeug/coins 3.0.0 → 26.10.1

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.
@@ -1 +1 @@
1
- {"version":3,"file":"currency.js","names":[],"sources":["../src/currency.ts"],"sourcesContent":["import { CoinsError, InvalidCurrencyError } from './errors';\nimport type { Currency, CurrencyCode } from './types';\n\nconst builtins = new Map<string, Currency>();\nconst canonicalCurrencies = new WeakSet<object>();\n\nfunction register<C extends string>(code: C, minorUnit: number): Currency<C> {\n validateDefinition(code, minorUnit);\n\n const definition = Object.freeze({ code: code as CurrencyCode<C>, minorUnit }) as Currency<C>;\n\n canonicalCurrencies.add(definition);\n\n return definition;\n}\n\nfunction builtin<C extends string>(code: C, minorUnit: number): Currency<C> {\n const definition = register(code, minorUnit);\n\n builtins.set(code, definition);\n\n return definition;\n}\n\nexport const USD = builtin('USD', 2);\nexport const EUR = builtin('EUR', 2);\nexport const GBP = builtin('GBP', 2);\nexport const JPY = builtin('JPY', 0);\nexport const KRW = builtin('KRW', 0);\nexport const BHD = builtin('BHD', 3);\nexport const KWD = builtin('KWD', 3);\n\n/** Resolve a built-in currency by code, or construct an immutable custom currency from a definition. */\nexport function currency<C extends string>(code: C): Currency<C>;\nexport function currency<C extends string>(definition: { code: C; minorUnit: number }): Currency<C>;\nexport function currency<C extends string>(input: C | { code: C; minorUnit: number }): Currency<C> {\n if (typeof input === 'string') {\n const definition = builtins.get(input);\n\n if (!definition) throw new InvalidCurrencyError(input);\n\n return definition as Currency<C>;\n }\n\n 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"}
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":"mEAGA,IAAM,EAAW,IAAI,IACf,EAAsB,IAAI,QAEhC,SAAS,SAA2B,EAAS,EAAgC,CAC3E,mBAAmB,EAAM,CAAS,EAElC,IAAM,EAAa,OAAO,OAAO,CAAQ,OAAyB,WAAU,CAAC,EAI7E,OAFA,EAAoB,IAAI,CAAU,EAE3B,CACT,CAEA,SAAS,QAA0B,EAAS,EAAgC,CAC1E,IAAM,EAAa,SAAS,EAAM,CAAS,EAI3C,OAFA,EAAS,IAAI,EAAM,CAAU,EAEtB,CACT,CAEA,IAAa,EAAM,QAAQ,MAAO,CAAC,EACtB,EAAM,QAAQ,MAAO,CAAC,EACtB,EAAM,QAAQ,MAAO,CAAC,EACtB,EAAM,QAAQ,MAAO,CAAC,EACtB,EAAM,QAAQ,MAAO,CAAC,EACtB,EAAM,QAAQ,MAAO,CAAC,EACtB,EAAM,QAAQ,MAAO,CAAC,EAKnC,SAAgB,SAA2B,EAAwD,CACjG,GAAI,OAAO,GAAU,SAAU,CAC7B,IAAM,EAAa,EAAS,IAAI,CAAK,EAErC,GAAI,CAAC,EAAY,MAAM,IAAI,EAAqB,CAAK,EAErD,OAAO,CACT,CAEA,GAAI,OAAO,GAAU,WAAY,EAC/B,MAAM,IAAI,EAAW,mBAAoB,uCAAuC,EAGlF,OAAO,SAAS,EAAM,KAAM,EAAM,SAAS,CAC7C,CAEA,SAAgB,WAAW,EAAmC,CAC5D,OAAO,OAAO,GAAU,YAAY,GAAkB,EAAoB,IAAI,CAAK,CACrF,CAEA,SAAS,mBAAmB,EAAc,EAAyB,CACjE,GAAI,CAAC,aAAa,KAAK,CAAI,EACzB,MAAM,IAAI,EAAW,mBAAoB,mDAAmD,EAAK,EAAE,EAGrG,GAAI,CAAC,OAAO,UAAU,CAAS,GAAK,EAAY,GAAK,EAAY,EAC/D,MAAM,IAAI,EAAW,mBAAoB,aAAa,EAAK,kCAAkC,CAEjG"}
package/dist/errors.cjs CHANGED
@@ -1,2 +1,2 @@
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;
1
+ var CoinsError=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)}},CurrencyMismatchError=class extends CoinsError{expected;received;constructor(e,t){super(`CURRENCY_MISMATCH`,`Currency mismatch: canonical ${e} and ${t} definitions differ`),this.expected=e,this.received=t}};function describe(e){try{return String(e)}catch{return`<unprintable>`}}var InvalidCurrencyError=class extends CoinsError{value;constructor(e){super(`INVALID_CURRENCY`,`Unsupported currency: "${describe(e)}"`),this.value=e}};exports.CoinsError=CoinsError,exports.CurrencyMismatchError=CurrencyMismatchError,exports.InvalidCurrencyError=InvalidCurrencyError;
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_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"}
1
+ {"version":3,"file":"errors.cjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["export type CoinsErrorCode =\n | 'CURRENCY_MISMATCH'\n | 'DIVISION_BY_ZERO'\n | 'FORMAT_ERROR'\n | 'INVALID_ALLOCATION'\n | 'INVALID_CURRENCY'\n | 'INVALID_DECIMAL'\n | 'INVALID_EXCHANGE_RATE'\n | 'INVALID_MONEY'\n | 'INVALID_RANGE'\n | 'INVALID_ROUNDING';\n\nexport class CoinsError extends Error {\n readonly code: CoinsErrorCode;\n\n constructor(code: CoinsErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n this.name = new.target.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: 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 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,WAAb,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,sBAAb,cAA2C,UAAW,CACpD,SACA,SAEA,YAAY,EAAkB,EAAkB,CAC9C,MAAM,oBAAqB,gCAAgC,EAAS,OAAO,EAAS,oBAAoB,EACxG,KAAK,SAAW,EAChB,KAAK,SAAW,CAClB,CACF,EAEA,SAAS,SAAS,EAAwB,CACxC,GAAI,CACF,OAAO,OAAO,CAAK,CACrB,MAAQ,CACN,MAAO,eACT,CACF,CAEA,IAAa,qBAAb,cAA0C,UAAW,CACnD,MAEA,YAAY,EAAgB,CAC1B,MAAM,mBAAoB,0BAA0B,SAAS,CAAK,EAAE,EAAE,EACtE,KAAK,MAAQ,CACf,CACF"}
package/dist/errors.d.ts CHANGED
@@ -1,17 +1,14 @@
1
1
  export type CoinsErrorCode = 'CURRENCY_MISMATCH' | 'DIVISION_BY_ZERO' | 'FORMAT_ERROR' | 'INVALID_ALLOCATION' | 'INVALID_CURRENCY' | 'INVALID_DECIMAL' | 'INVALID_EXCHANGE_RATE' | 'INVALID_MONEY' | 'INVALID_RANGE' | 'INVALID_ROUNDING';
2
2
  export declare class CoinsError extends Error {
3
- protected static readonly errorName: string;
4
3
  readonly code: CoinsErrorCode;
5
4
  constructor(code: CoinsErrorCode, message: string, options?: ErrorOptions);
6
5
  }
7
6
  export declare class CurrencyMismatchError extends CoinsError {
8
- protected static readonly errorName = "CurrencyMismatchError";
9
7
  readonly expected: string;
10
8
  readonly received: string;
11
9
  constructor(expected: string, received: string);
12
10
  }
13
11
  export declare class InvalidCurrencyError extends CoinsError {
14
- protected static readonly errorName = "InvalidCurrencyError";
15
12
  readonly value: unknown;
16
13
  constructor(value: unknown);
17
14
  }
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,cAAc,GACtB,mBAAmB,GACnB,kBAAkB,GAClB,cAAc,GACd,oBAAoB,GACpB,kBAAkB,GAClB,iBAAiB,GACjB,uBAAuB,GACvB,eAAe,GACf,eAAe,GACf,kBAAkB,CAAC;AAEvB,qBAAa,UAAW,SAAQ,KAAK;IACnC,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAgB;IAC3D,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAC;gBAElB,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY;CAM1E;AAED,qBAAa,qBAAsB,SAAQ,UAAU;IACnD,0BAAmC,SAAS,2BAA2B;IACvE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;gBAEd,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;CAK/C;AAUD,qBAAa,oBAAqB,SAAQ,UAAU;IAClD,0BAAmC,SAAS,0BAA0B;IACtE,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;gBAEZ,KAAK,EAAE,OAAO;CAI3B"}
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,cAAc,GACtB,mBAAmB,GACnB,kBAAkB,GAClB,cAAc,GACd,oBAAoB,GACpB,kBAAkB,GAClB,iBAAiB,GACjB,uBAAuB,GACvB,eAAe,GACf,eAAe,GACf,kBAAkB,CAAC;AAEvB,qBAAa,UAAW,SAAQ,KAAK;IACnC,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAC;gBAElB,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY;CAM1E;AAED,qBAAa,qBAAsB,SAAQ,UAAU;IACnD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;gBAEd,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;CAK/C;AAUD,qBAAa,oBAAqB,SAAQ,UAAU;IAClD,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;gBAEZ,KAAK,EAAE,OAAO;CAI3B"}
package/dist/errors.js CHANGED
@@ -1,33 +1,2 @@
1
- //#region src/errors.ts
2
- var e = class extends Error {
3
- static errorName = "CoinsError";
4
- code;
5
- constructor(e, t, n) {
6
- super(t, n), this.code = e, this.name = new.target.errorName, Object.setPrototypeOf(this, new.target.prototype);
7
- }
8
- }, t = class extends e {
9
- static errorName = "CurrencyMismatchError";
10
- expected;
11
- received;
12
- constructor(e, t) {
13
- super("CURRENCY_MISMATCH", `Currency mismatch: canonical ${e} and ${t} definitions differ`), this.expected = e, this.received = t;
14
- }
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";
25
- value;
26
- constructor(e) {
27
- super("INVALID_CURRENCY", `Unsupported currency: "${n(e)}"`), this.value = e;
28
- }
29
- };
30
- //#endregion
31
- export { e as CoinsError, t as CurrencyMismatchError, r as InvalidCurrencyError };
32
-
1
+ var CoinsError=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)}},CurrencyMismatchError=class extends CoinsError{expected;received;constructor(e,t){super(`CURRENCY_MISMATCH`,`Currency mismatch: canonical ${e} and ${t} definitions differ`),this.expected=e,this.received=t}};function describe(e){try{return String(e)}catch{return`<unprintable>`}}var InvalidCurrencyError=class extends CoinsError{value;constructor(e){super(`INVALID_CURRENCY`,`Unsupported currency: "${describe(e)}"`),this.value=e}};export{CoinsError,CurrencyMismatchError,InvalidCurrencyError};
33
2
  //# 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_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"}
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["export type CoinsErrorCode =\n | 'CURRENCY_MISMATCH'\n | 'DIVISION_BY_ZERO'\n | 'FORMAT_ERROR'\n | 'INVALID_ALLOCATION'\n | 'INVALID_CURRENCY'\n | 'INVALID_DECIMAL'\n | 'INVALID_EXCHANGE_RATE'\n | 'INVALID_MONEY'\n | 'INVALID_RANGE'\n | 'INVALID_ROUNDING';\n\nexport class CoinsError extends Error {\n readonly code: CoinsErrorCode;\n\n constructor(code: CoinsErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n this.name = new.target.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: 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 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,WAAb,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,sBAAb,cAA2C,UAAW,CACpD,SACA,SAEA,YAAY,EAAkB,EAAkB,CAC9C,MAAM,oBAAqB,gCAAgC,EAAS,OAAO,EAAS,oBAAoB,EACxG,KAAK,SAAW,EAChB,KAAK,SAAW,CAClB,CACF,EAEA,SAAS,SAAS,EAAwB,CACxC,GAAI,CACF,OAAO,OAAO,CAAK,CACrB,MAAQ,CACN,MAAO,eACT,CACF,CAEA,IAAa,qBAAb,cAA0C,UAAW,CACnD,MAEA,YAAY,EAAgB,CAC1B,MAAM,mBAAoB,0BAA0B,SAAS,CAAK,EAAE,EAAE,EACtE,KAAK,MAAQ,CACf,CACF"}
package/dist/exchange.cjs CHANGED
@@ -1,2 +1,2 @@
1
- const e=require("./errors.cjs"),t=require("./_decimal.cjs"),n=require("./currency.cjs"),r=require("./money.cjs");var i=new WeakSet;function a({from:r,to:a,value:o}){if(!n.isCurrency(r)||!n.isCurrency(a))throw new e.CoinsError(`INVALID_CURRENCY`,`Exchange rate requires registered currencies`);let s=t.decimal(o);if(s.numerator<=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;
1
+ const e=require("./errors.cjs"),t=require("./_decimal.cjs"),n=require("./currency.cjs"),r=require("./money.cjs");var i=new WeakSet;function exchangeRate({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 isExchangeRate(e){return typeof e==`object`&&!!e&&i.has(e)}function exchange(n,i,a={}){if(r.assertMoney(n),!isExchangeRate(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 o=n.amount*i.value.numerator*10n**BigInt(i.to.minorUnit),s=i.value.denominator*10n**BigInt(i.from.minorUnit);return r.createMoney(t.roundDivision(o,s,a.rounding??`halfAwayFromZero`),i.to)}exports.exchange=exchange,exports.exchangeRate=exchangeRate,exports.isExchangeRate=isExchangeRate;
2
2
  //# sourceMappingURL=exchange.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"exchange.cjs","names":[],"sources":["../src/exchange.ts"],"sourcesContent":["import { decimal, roundDivision } from './_decimal';\nimport { isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { assertMoney, createMoney } from './money';\nimport type { Currency, ExchangeRate, Money, RoundingMode } from './types';\n\nconst canonicalRates = new WeakSet<object>();\n\nexport function exchangeRate<From extends Currency, To extends Currency>({\n from,\n to,\n value,\n}: {\n from: From;\n to: To;\n value: string;\n}): ExchangeRate<From, To> {\n if (!isCurrency(from) || !isCurrency(to))\n throw new CoinsError('INVALID_CURRENCY', 'Exchange rate requires registered currencies');\n\n const parsed = decimal(value);\n\n if (parsed.numerator <= 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"}
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,aAAyD,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,SACd,EACA,EACA,EAAuC,CAAC,EAC7B,CAGX,GAFA,EAAA,YAAY,CAAK,EAEb,CAAC,eAAe,CAAI,EACtB,MAAM,IAAI,EAAA,WAAW,wBAAyB,6CAA6C,EAG7F,GAAI,EAAM,WAAa,EAAK,KAAM,MAAM,IAAI,EAAA,sBAAsB,EAAM,SAAS,KAAM,EAAK,KAAK,IAAI,EAErG,IAAM,EAAY,EAAM,OAAS,EAAK,MAAM,UAAY,KAAO,OAAO,EAAK,GAAG,SAAS,EACjF,EAAc,EAAK,MAAM,YAAc,KAAO,OAAO,EAAK,KAAK,SAAS,EAE9E,OAAO,EAAA,YAAY,EAAA,cAAc,EAAW,EAAa,EAAQ,UAAY,kBAAkB,EAAG,EAAK,EAAE,CAC3G"}
package/dist/exchange.js CHANGED
@@ -1,30 +1,2 @@
1
- import { CoinsError as e, CurrencyMismatchError as t } from "./errors.js";
2
- import { decimal as n, roundDivision as r } from "./_decimal.js";
3
- import { isCurrency as i } from "./currency.js";
4
- import { assertMoney as a, createMoney as o } from "./money.js";
5
- //#region src/exchange.ts
6
- var s = /* @__PURE__ */ new WeakSet();
7
- function c({ from: t, to: r, value: a }) {
8
- if (!i(t) || !i(r)) throw new e("INVALID_CURRENCY", "Exchange rate requires registered currencies");
9
- let o = n(a);
10
- if (o.numerator <= 0n) throw new e("INVALID_DECIMAL", "Exchange rates must be positive");
11
- let c = Object.freeze({
12
- from: t,
13
- to: r,
14
- value: o
15
- });
16
- return s.add(c), c;
17
- }
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");
23
- if (n.currency !== i.from) throw new t(n.currency.code, i.from.code);
24
- let c = n.amount * i.value.numerator * 10n ** BigInt(i.to.minorUnit), u = i.value.denominator * 10n ** BigInt(i.from.minorUnit);
25
- return o(r(c, u, s.rounding ?? "halfAwayFromZero"), i.to);
26
- }
27
- //#endregion
28
- export { u as exchange, c as exchangeRate, l as isExchangeRate };
29
-
1
+ import{CoinsError as e,CurrencyMismatchError as t}from"./errors.js";import{decimal as n,roundDivision as r}from"./_decimal.js";import{isCurrency as i}from"./currency.js";import{assertMoney as a,createMoney as o}from"./money.js";var s=new WeakSet;function exchangeRate({from:t,to:r,value:a}){if(!i(t)||!i(r))throw new e(`INVALID_CURRENCY`,`Exchange rate requires registered currencies`);let o=n(a);if(o.numerator<=0n)throw new e(`INVALID_DECIMAL`,`Exchange rates must be positive`);let c=Object.freeze({from:t,to:r,value:o});return s.add(c),c}function isExchangeRate(e){return typeof e==`object`&&!!e&&s.has(e)}function exchange(n,i,s={}){if(a(n),!isExchangeRate(i))throw new e(`INVALID_EXCHANGE_RATE`,`Exchange requires a canonical exchange rate`);if(n.currency!==i.from)throw new t(n.currency.code,i.from.code);let c=n.amount*i.value.numerator*10n**BigInt(i.to.minorUnit),l=i.value.denominator*10n**BigInt(i.from.minorUnit);return o(r(c,l,s.rounding??`halfAwayFromZero`),i.to)}export{exchange,exchangeRate,isExchangeRate};
30
2
  //# sourceMappingURL=exchange.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"exchange.js","names":[],"sources":["../src/exchange.ts"],"sourcesContent":["import { decimal, roundDivision } from './_decimal';\nimport { isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { assertMoney, createMoney } from './money';\nimport type { Currency, ExchangeRate, Money, RoundingMode } from './types';\n\nconst canonicalRates = new WeakSet<object>();\n\nexport function exchangeRate<From extends Currency, To extends Currency>({\n from,\n to,\n value,\n}: {\n from: From;\n to: To;\n value: string;\n}): ExchangeRate<From, To> {\n if (!isCurrency(from) || !isCurrency(to))\n throw new CoinsError('INVALID_CURRENCY', 'Exchange rate requires registered currencies');\n\n const parsed = decimal(value);\n\n if (parsed.numerator <= 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"}
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":"oOAMA,IAAM,EAAiB,IAAI,QAE3B,SAAgB,aAAyD,CACvE,OACA,KACA,SAKyB,CACzB,GAAI,CAAC,EAAW,CAAI,GAAK,CAAC,EAAW,CAAE,EACrC,MAAM,IAAI,EAAW,mBAAoB,8CAA8C,EAEzF,IAAM,EAAS,EAAQ,CAAK,EAE5B,GAAI,EAAO,WAAa,GAAI,MAAM,IAAI,EAAW,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,SACd,EACA,EACA,EAAuC,CAAC,EAC7B,CAGX,GAFA,EAAY,CAAK,EAEb,CAAC,eAAe,CAAI,EACtB,MAAM,IAAI,EAAW,wBAAyB,6CAA6C,EAG7F,GAAI,EAAM,WAAa,EAAK,KAAM,MAAM,IAAI,EAAsB,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,EAAY,EAAc,EAAW,EAAa,EAAQ,UAAY,kBAAkB,EAAG,EAAK,EAAE,CAC3G"}
package/dist/format.cjs CHANGED
@@ -1,2 +1,2 @@
1
- const e=require("./errors.cjs"),t=require("./_decimal.cjs"),n=require("./money.cjs");var r=20,i=`halfAwayFromZero`,a={awayFromZero:`expand`,ceil:`ceil`,floor:`floor`,halfAwayFromZero:`halfExpand`,halfEven:`halfEven`,towardZero:`trunc`};function o(e,t={}){return s(e,t).map(e=>e.value).join(``)}function s(r,o={}){n.assertMoney(r),t.assertRoundingMode(o.rounding??i);let{maximum:s,minimum:l}=c(r.currency.minorUnit,o),d=o.style??`symbol`;try{return u(new Intl.NumberFormat(o.locale??`en-US`,{currency:r.currency.code,currencyDisplay:d,maximumFractionDigits:s,minimumFractionDigits:l,roundingMode:a[o.rounding??i],style:`currency`,useGrouping:!0}).formatToParts(n.toDecimal(r)))}catch(t){throw t instanceof e.CoinsError?t:new e.CoinsError(`FORMAT_ERROR`,`Cannot format currency "${r.currency.code}" for locale "${o.locale??`en-US`}"`,{cause:t})}}function c(t,n){let r=n.maximumFractionDigits,i=n.minimumFractionDigits;l(`maximumFractionDigits`,r),l(`minimumFractionDigits`,i);let a=r??Math.max(t,i??t),o=i??Math.min(t,r??t);if(o>a)throw new e.CoinsError(`FORMAT_ERROR`,`minimumFractionDigits cannot exceed maximumFractionDigits`);return{maximum:a,minimum:o}}function l(t,n){if(n!==void 0&&(!Number.isInteger(n)||n<0||n>r))throw new e.CoinsError(`FORMAT_ERROR`,`Fraction digits must be integers satisfying 0 ≤ minimum ≤ maximum ≤ ${r} (${t})`)}function u(e){let t=[];for(let n of e)if(n.type===`integer`||n.type===`group`){let e=t.at(-1);e?.type===`integer`?t[t.length-1]={type:`integer`,value:e.value+n.value}:t.push({type:`integer`,value:n.value})}else n.type===`currency`||n.type===`decimal`||n.type===`fraction`||n.type===`literal`||n.type===`minusSign`||n.type===`plusSign`?t.push({type:n.type,value:n.value}):t.push({type:`literal`,value:n.value});return t}exports.format=o,exports.formatParts=s;
1
+ const e=require("./errors.cjs"),t=require("./_decimal.cjs"),n=require("./money.cjs");var r=20,i=`halfAwayFromZero`,a={awayFromZero:`expand`,ceil:`ceil`,floor:`floor`,halfAwayFromZero:`halfExpand`,halfEven:`halfEven`,towardZero:`trunc`};function format(e,t={}){return formatParts(e,t).map(e=>e.value).join(``)}function formatParts(r,o={}){n.assertMoney(r),t.assertRoundingMode(o.rounding??i);let{maximum:s,minimum:c}=fractionDigits(r.currency.minorUnit,o),l=o.style??`symbol`;try{return normalizeParts(new Intl.NumberFormat(o.locale??`en-US`,{currency:r.currency.code,currencyDisplay:l,maximumFractionDigits:s,minimumFractionDigits:c,roundingMode:a[o.rounding??i],style:`currency`,useGrouping:!0}).formatToParts(n.toDecimal(r)))}catch(t){throw t instanceof e.CoinsError?t:new e.CoinsError(`FORMAT_ERROR`,`Cannot format currency "${r.currency.code}" for locale "${o.locale??`en-US`}"`,{cause:t})}}function fractionDigits(t,n){let r=n.maximumFractionDigits,i=n.minimumFractionDigits;validateFractionDigit(`maximumFractionDigits`,r),validateFractionDigit(`minimumFractionDigits`,i);let a=r??Math.max(t,i??t),o=i??Math.min(t,r??t);if(o>a)throw new e.CoinsError(`FORMAT_ERROR`,`minimumFractionDigits cannot exceed maximumFractionDigits`);return{maximum:a,minimum:o}}function validateFractionDigit(t,n){if(n!==void 0&&(!Number.isInteger(n)||n<0||n>r))throw new e.CoinsError(`FORMAT_ERROR`,`Fraction digits must be integers satisfying 0 ≤ minimum ≤ maximum ≤ ${r} (${t})`)}function normalizeParts(e){let t=[];for(let n of e)if(n.type===`integer`||n.type===`group`){let e=t.at(-1);e?.type===`integer`?t[t.length-1]={type:`integer`,value:e.value+n.value}:t.push({type:`integer`,value:n.value})}else n.type===`currency`||n.type===`decimal`||n.type===`fraction`||n.type===`literal`||n.type===`minusSign`||n.type===`plusSign`?t.push({type:n.type,value:n.value}):t.push({type:`literal`,value:n.value});return t}exports.format=format,exports.formatParts=formatParts;
2
2
  //# sourceMappingURL=format.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"format.cjs","names":[],"sources":["../src/format.ts"],"sourcesContent":["import { assertRoundingMode } from './_decimal';\nimport { CoinsError } from './errors';\nimport { assertMoney, toDecimal } from './money';\nimport type { FormatOptions, Money, MoneyFormatPart, RoundingMode } from './types';\n\nconst MAX_FRACTION_DIGITS = 20;\nconst defaultFormatRounding: RoundingMode = 'halfAwayFromZero';\nconst intlRoundingModes: Record<RoundingMode, Intl.NumberFormatOptions['roundingMode']> = {\n awayFromZero: 'expand',\n ceil: 'ceil',\n floor: 'floor',\n halfAwayFromZero: 'halfExpand',\n halfEven: 'halfEven',\n towardZero: 'trunc',\n};\n\nexport function format(value: Money, options: FormatOptions = {}): string {\n return formatParts(value, options)\n .map((part) => part.value)\n .join('');\n}\n\nexport function formatParts(value: Money, options: FormatOptions = {}): MoneyFormatPart[] {\n assertMoney(value);\n assertRoundingMode(options.rounding ?? defaultFormatRounding);\n\n const { maximum, minimum } = fractionDigits(value.currency.minorUnit, options);\n const style = options.style ?? 'symbol';\n\n try {\n const formatter = new Intl.NumberFormat(options.locale ?? 'en-US', {\n currency: value.currency.code,\n currencyDisplay: style,\n maximumFractionDigits: maximum,\n minimumFractionDigits: minimum,\n roundingMode: intlRoundingModes[options.rounding ?? defaultFormatRounding],\n style: 'currency',\n useGrouping: true,\n });\n\n return normalizeParts(formatter.formatToParts(toDecimal(value) as unknown as number));\n } catch (error) {\n if (error instanceof CoinsError) throw error;\n\n throw new CoinsError(\n 'FORMAT_ERROR',\n `Cannot format currency \"${value.currency.code}\" for locale \"${options.locale ?? 'en-US'}\"`,\n { cause: error },\n );\n }\n}\n\nfunction fractionDigits(scale: number, options: FormatOptions): { maximum: number; minimum: number } {\n const requestedMaximum = options.maximumFractionDigits;\n const requestedMinimum = options.minimumFractionDigits;\n\n validateFractionDigit('maximumFractionDigits', requestedMaximum);\n validateFractionDigit('minimumFractionDigits', requestedMinimum);\n\n const maximum = requestedMaximum ?? Math.max(scale, requestedMinimum ?? scale);\n const minimum = requestedMinimum ?? Math.min(scale, requestedMaximum ?? scale);\n\n if (minimum > maximum) {\n throw new CoinsError('FORMAT_ERROR', 'minimumFractionDigits cannot exceed maximumFractionDigits');\n }\n\n return { maximum, minimum };\n}\n\nfunction validateFractionDigit(name: string, value: number | undefined): void {\n if (value !== undefined && (!Number.isInteger(value) || value < 0 || value > MAX_FRACTION_DIGITS)) {\n throw new CoinsError(\n 'FORMAT_ERROR',\n `Fraction digits must be integers satisfying 0 ≤ minimum ≤ maximum ≤ ${MAX_FRACTION_DIGITS} (${name})`,\n );\n }\n}\n\nfunction normalizeParts(raw: Intl.NumberFormatPart[]): MoneyFormatPart[] {\n const parts: MoneyFormatPart[] = [];\n\n for (const part of raw) {\n if (part.type === 'integer' || part.type === 'group') {\n const previous = parts.at(-1);\n\n if (previous?.type === 'integer') {\n parts[parts.length - 1] = { type: 'integer', value: previous.value + part.value };\n } else {\n parts.push({ type: 'integer', value: part.value });\n }\n } else if (\n part.type === 'currency' ||\n part.type === 'decimal' ||\n part.type === 'fraction' ||\n part.type === 'literal' ||\n part.type === 'minusSign' ||\n part.type === 'plusSign'\n ) {\n parts.push({ type: part.type, value: part.value });\n } else {\n parts.push({ type: 'literal', value: part.value });\n }\n }\n\n return parts;\n}\n"],"mappings":"qFAKA,IAAM,EAAsB,GACtB,EAAsC,mBACtC,EAAoF,CACxF,aAAc,SACd,KAAM,OACN,MAAO,QACP,iBAAkB,aAClB,SAAU,WACV,WAAY,OACd,EAEA,SAAgB,EAAO,EAAc,EAAyB,CAAC,EAAW,CACxE,OAAO,EAAY,EAAO,CAAO,CAAC,CAC/B,IAAK,GAAS,EAAK,KAAK,CAAC,CACzB,KAAK,EAAE,CACZ,CAEA,SAAgB,EAAY,EAAc,EAAyB,CAAC,EAAsB,CACxF,EAAA,YAAY,CAAK,EACjB,EAAA,mBAAmB,EAAQ,UAAY,CAAqB,EAE5D,GAAM,CAAE,UAAS,WAAY,EAAe,EAAM,SAAS,UAAW,CAAO,EACvE,EAAQ,EAAQ,OAAS,SAE/B,GAAI,CAWF,OAAO,EAAe,IAVA,KAAK,aAAa,EAAQ,QAAU,QAAS,CACjE,SAAU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S,YACd,EAAK,OAAS,WACd,EAAK,OAAS,YACd,EAAK,OAAS,WACd,EAAK,OAAS,aACd,EAAK,OAAS,WAEd,EAAM,KAAK,CAAE,KAAM,EAAK,KAAM,MAAO,EAAK,KAAM,CAAC,EAEjD,EAAM,KAAK,CAAE,KAAM,UAAW,MAAO,EAAK,KAAM,CAAC,EAIrD,OAAO,CACT"}
1
+ {"version":3,"file":"format.cjs","names":[],"sources":["../src/format.ts"],"sourcesContent":["import { assertRoundingMode } from './_decimal';\nimport { CoinsError } from './errors';\nimport { assertMoney, toDecimal } from './money';\nimport type { FormatOptions, Money, MoneyFormatPart, RoundingMode } from './types';\n\nconst MAX_FRACTION_DIGITS = 20;\nconst defaultFormatRounding: RoundingMode = 'halfAwayFromZero';\nconst intlRoundingModes: Record<RoundingMode, Intl.NumberFormatOptions['roundingMode']> = {\n awayFromZero: 'expand',\n ceil: 'ceil',\n floor: 'floor',\n halfAwayFromZero: 'halfExpand',\n halfEven: 'halfEven',\n towardZero: 'trunc',\n};\n\nexport function format(value: Money, options: FormatOptions = {}): string {\n return formatParts(value, options)\n .map((part) => part.value)\n .join('');\n}\n\nexport function formatParts(value: Money, options: FormatOptions = {}): MoneyFormatPart[] {\n assertMoney(value);\n assertRoundingMode(options.rounding ?? defaultFormatRounding);\n\n const { maximum, minimum } = fractionDigits(value.currency.minorUnit, options);\n const style = options.style ?? 'symbol';\n\n try {\n const formatter = new Intl.NumberFormat(options.locale ?? 'en-US', {\n currency: value.currency.code,\n currencyDisplay: style,\n maximumFractionDigits: maximum,\n minimumFractionDigits: minimum,\n roundingMode: intlRoundingModes[options.rounding ?? defaultFormatRounding],\n style: 'currency',\n useGrouping: true,\n });\n\n return normalizeParts(formatter.formatToParts(toDecimal(value) as unknown as number));\n } catch (error) {\n if (error instanceof CoinsError) throw error;\n\n throw new CoinsError(\n 'FORMAT_ERROR',\n `Cannot format currency \"${value.currency.code}\" for locale \"${options.locale ?? 'en-US'}\"`,\n { cause: error },\n );\n }\n}\n\nfunction fractionDigits(scale: number, options: FormatOptions): { maximum: number; minimum: number } {\n const requestedMaximum = options.maximumFractionDigits;\n const requestedMinimum = options.minimumFractionDigits;\n\n validateFractionDigit('maximumFractionDigits', requestedMaximum);\n validateFractionDigit('minimumFractionDigits', requestedMinimum);\n\n const maximum = requestedMaximum ?? Math.max(scale, requestedMinimum ?? scale);\n const minimum = requestedMinimum ?? Math.min(scale, requestedMaximum ?? scale);\n\n if (minimum > maximum) {\n throw new CoinsError('FORMAT_ERROR', 'minimumFractionDigits cannot exceed maximumFractionDigits');\n }\n\n return { maximum, minimum };\n}\n\nfunction validateFractionDigit(name: string, value: number | undefined): void {\n if (value !== undefined && (!Number.isInteger(value) || value < 0 || value > MAX_FRACTION_DIGITS)) {\n throw new CoinsError(\n 'FORMAT_ERROR',\n `Fraction digits must be integers satisfying 0 ≤ minimum ≤ maximum ≤ ${MAX_FRACTION_DIGITS} (${name})`,\n );\n }\n}\n\nfunction normalizeParts(raw: Intl.NumberFormatPart[]): MoneyFormatPart[] {\n const parts: MoneyFormatPart[] = [];\n\n for (const part of raw) {\n if (part.type === 'integer' || part.type === 'group') {\n const previous = parts.at(-1);\n\n if (previous?.type === 'integer') {\n parts[parts.length - 1] = { type: 'integer', value: previous.value + part.value };\n } else {\n parts.push({ type: 'integer', value: part.value });\n }\n } else if (\n part.type === 'currency' ||\n part.type === 'decimal' ||\n part.type === 'fraction' ||\n part.type === 'literal' ||\n part.type === 'minusSign' ||\n part.type === 'plusSign'\n ) {\n parts.push({ type: part.type, value: part.value });\n } else {\n parts.push({ type: 'literal', value: part.value });\n }\n }\n\n return parts;\n}\n"],"mappings":"qFAKA,IAAM,EAAsB,GACtB,EAAsC,mBACtC,EAAoF,CACxF,aAAc,SACd,KAAM,OACN,MAAO,QACP,iBAAkB,aAClB,SAAU,WACV,WAAY,OACd,EAEA,SAAgB,OAAO,EAAc,EAAyB,CAAC,EAAW,CACxE,OAAO,YAAY,EAAO,CAAO,CAAC,CAC/B,I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,SAAS,eAAe,EAAiD,CACvE,IAAM,EAA2B,CAAC,EAElC,IAAK,IAAM,KAAQ,EACjB,GAAI,EAAK,OAAS,WAAa,EAAK,OAAS,QAAS,CACpD,IAAM,EAAW,EAAM,GAAG,EAAE,EAExB,GAAU,OAAS,UACrB,EAAM,EAAM,OAAS,GAAK,CAAE,KAAM,UAAW,MAAO,EAAS,MAAQ,EAAK,KAAM,EAEhF,EAAM,KAAK,CAAE,KAAM,UAAW,MAAO,EAAK,KAAM,CAAC,CAErD,MACE,EAAK,OAAS,YACd,EAAK,OAAS,WACd,EAAK,OAAS,YACd,EAAK,OAAS,WACd,EAAK,OAAS,aACd,EAAK,OAAS,WAEd,EAAM,KAAK,CAAE,KAAM,EAAK,KAAM,MAAO,EAAK,KAAM,CAAC,EAEjD,EAAM,KAAK,CAAE,KAAM,UAAW,MAAO,EAAK,KAAM,CAAC,EAIrD,OAAO,CACT"}
package/dist/format.js CHANGED
@@ -1,69 +1,2 @@
1
- import { CoinsError as e } from "./errors.js";
2
- import { assertRoundingMode as t } from "./_decimal.js";
3
- import { assertMoney as n, toDecimal as r } from "./money.js";
4
- //#region src/format.ts
5
- var i = 20, a = "halfAwayFromZero", o = {
6
- awayFromZero: "expand",
7
- ceil: "ceil",
8
- floor: "floor",
9
- halfAwayFromZero: "halfExpand",
10
- halfEven: "halfEven",
11
- towardZero: "trunc"
12
- };
13
- function s(e, t = {}) {
14
- return c(e, t).map((e) => e.value).join("");
15
- }
16
- function c(i, s = {}) {
17
- n(i), t(s.rounding ?? a);
18
- let { maximum: c, minimum: u } = l(i.currency.minorUnit, s), f = s.style ?? "symbol";
19
- try {
20
- return d(new Intl.NumberFormat(s.locale ?? "en-US", {
21
- currency: i.currency.code,
22
- currencyDisplay: f,
23
- maximumFractionDigits: c,
24
- minimumFractionDigits: u,
25
- roundingMode: o[s.rounding ?? a],
26
- style: "currency",
27
- useGrouping: !0
28
- }).formatToParts(r(i)));
29
- } catch (t) {
30
- throw t instanceof e ? t : new e("FORMAT_ERROR", `Cannot format currency "${i.currency.code}" for locale "${s.locale ?? "en-US"}"`, { cause: t });
31
- }
32
- }
33
- function l(t, n) {
34
- let r = n.maximumFractionDigits, i = n.minimumFractionDigits;
35
- u("maximumFractionDigits", r), u("minimumFractionDigits", i);
36
- let a = r ?? Math.max(t, i ?? t), o = i ?? Math.min(t, r ?? t);
37
- if (o > a) throw new e("FORMAT_ERROR", "minimumFractionDigits cannot exceed maximumFractionDigits");
38
- return {
39
- maximum: a,
40
- minimum: o
41
- };
42
- }
43
- function u(t, n) {
44
- if (n !== void 0 && (!Number.isInteger(n) || n < 0 || n > i)) throw new e("FORMAT_ERROR", `Fraction digits must be integers satisfying 0 ≤ minimum ≤ maximum ≤ ${i} (${t})`);
45
- }
46
- function d(e) {
47
- let t = [];
48
- for (let n of e) if (n.type === "integer" || n.type === "group") {
49
- let e = t.at(-1);
50
- e?.type === "integer" ? t[t.length - 1] = {
51
- type: "integer",
52
- value: e.value + n.value
53
- } : t.push({
54
- type: "integer",
55
- value: n.value
56
- });
57
- } else n.type === "currency" || n.type === "decimal" || n.type === "fraction" || n.type === "literal" || n.type === "minusSign" || n.type === "plusSign" ? t.push({
58
- type: n.type,
59
- value: n.value
60
- }) : t.push({
61
- type: "literal",
62
- value: n.value
63
- });
64
- return t;
65
- }
66
- //#endregion
67
- export { s as format, c as formatParts };
68
-
1
+ import{CoinsError as e}from"./errors.js";import{assertRoundingMode as t}from"./_decimal.js";import{assertMoney as n,toDecimal as r}from"./money.js";var i=20,a=`halfAwayFromZero`,o={awayFromZero:`expand`,ceil:`ceil`,floor:`floor`,halfAwayFromZero:`halfExpand`,halfEven:`halfEven`,towardZero:`trunc`};function format(e,t={}){return formatParts(e,t).map(e=>e.value).join(``)}function formatParts(i,s={}){n(i),t(s.rounding??a);let{maximum:c,minimum:l}=fractionDigits(i.currency.minorUnit,s),u=s.style??`symbol`;try{return normalizeParts(new Intl.NumberFormat(s.locale??`en-US`,{currency:i.currency.code,currencyDisplay:u,maximumFractionDigits:c,minimumFractionDigits:l,roundingMode:o[s.rounding??a],style:`currency`,useGrouping:!0}).formatToParts(r(i)))}catch(t){throw t instanceof e?t:new e(`FORMAT_ERROR`,`Cannot format currency "${i.currency.code}" for locale "${s.locale??`en-US`}"`,{cause:t})}}function fractionDigits(t,n){let r=n.maximumFractionDigits,i=n.minimumFractionDigits;validateFractionDigit(`maximumFractionDigits`,r),validateFractionDigit(`minimumFractionDigits`,i);let a=r??Math.max(t,i??t),o=i??Math.min(t,r??t);if(o>a)throw new e(`FORMAT_ERROR`,`minimumFractionDigits cannot exceed maximumFractionDigits`);return{maximum:a,minimum:o}}function validateFractionDigit(t,n){if(n!==void 0&&(!Number.isInteger(n)||n<0||n>i))throw new e(`FORMAT_ERROR`,`Fraction digits must be integers satisfying 0 ≤ minimum ≤ maximum ≤ ${i} (${t})`)}function normalizeParts(e){let t=[];for(let n of e)if(n.type===`integer`||n.type===`group`){let e=t.at(-1);e?.type===`integer`?t[t.length-1]={type:`integer`,value:e.value+n.value}:t.push({type:`integer`,value:n.value})}else n.type===`currency`||n.type===`decimal`||n.type===`fraction`||n.type===`literal`||n.type===`minusSign`||n.type===`plusSign`?t.push({type:n.type,value:n.value}):t.push({type:`literal`,value:n.value});return t}export{format,formatParts};
69
2
  //# sourceMappingURL=format.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"format.js","names":[],"sources":["../src/format.ts"],"sourcesContent":["import { assertRoundingMode } from './_decimal';\nimport { CoinsError } from './errors';\nimport { assertMoney, toDecimal } from './money';\nimport type { FormatOptions, Money, MoneyFormatPart, RoundingMode } from './types';\n\nconst MAX_FRACTION_DIGITS = 20;\nconst defaultFormatRounding: RoundingMode = 'halfAwayFromZero';\nconst intlRoundingModes: Record<RoundingMode, Intl.NumberFormatOptions['roundingMode']> = {\n awayFromZero: 'expand',\n ceil: 'ceil',\n floor: 'floor',\n halfAwayFromZero: 'halfExpand',\n halfEven: 'halfEven',\n towardZero: 'trunc',\n};\n\nexport function format(value: Money, options: FormatOptions = {}): string {\n return formatParts(value, options)\n .map((part) => part.value)\n .join('');\n}\n\nexport function formatParts(value: Money, options: FormatOptions = {}): MoneyFormatPart[] {\n assertMoney(value);\n assertRoundingMode(options.rounding ?? defaultFormatRounding);\n\n const { maximum, minimum } = fractionDigits(value.currency.minorUnit, options);\n const style = options.style ?? 'symbol';\n\n try {\n const formatter = new Intl.NumberFormat(options.locale ?? 'en-US', {\n currency: value.currency.code,\n currencyDisplay: style,\n maximumFractionDigits: maximum,\n minimumFractionDigits: minimum,\n roundingMode: intlRoundingModes[options.rounding ?? defaultFormatRounding],\n style: 'currency',\n useGrouping: true,\n });\n\n return normalizeParts(formatter.formatToParts(toDecimal(value) as unknown as number));\n } catch (error) {\n if (error instanceof CoinsError) throw error;\n\n throw new CoinsError(\n 'FORMAT_ERROR',\n `Cannot format currency \"${value.currency.code}\" for locale \"${options.locale ?? 'en-US'}\"`,\n { cause: error },\n );\n }\n}\n\nfunction fractionDigits(scale: number, options: FormatOptions): { maximum: number; minimum: number } {\n const requestedMaximum = options.maximumFractionDigits;\n const requestedMinimum = options.minimumFractionDigits;\n\n validateFractionDigit('maximumFractionDigits', requestedMaximum);\n validateFractionDigit('minimumFractionDigits', requestedMinimum);\n\n const maximum = requestedMaximum ?? Math.max(scale, requestedMinimum ?? scale);\n const minimum = requestedMinimum ?? Math.min(scale, requestedMaximum ?? scale);\n\n if (minimum > maximum) {\n throw new CoinsError('FORMAT_ERROR', 'minimumFractionDigits cannot exceed maximumFractionDigits');\n }\n\n return { maximum, minimum };\n}\n\nfunction validateFractionDigit(name: string, value: number | undefined): void {\n if (value !== undefined && (!Number.isInteger(value) || value < 0 || value > MAX_FRACTION_DIGITS)) {\n throw new CoinsError(\n 'FORMAT_ERROR',\n `Fraction digits must be integers satisfying 0 ≤ minimum ≤ maximum ≤ ${MAX_FRACTION_DIGITS} (${name})`,\n );\n }\n}\n\nfunction normalizeParts(raw: Intl.NumberFormatPart[]): MoneyFormatPart[] {\n const parts: MoneyFormatPart[] = [];\n\n for (const part of raw) {\n if (part.type === 'integer' || part.type === 'group') {\n const previous = parts.at(-1);\n\n if (previous?.type === 'integer') {\n parts[parts.length - 1] = { type: 'integer', value: previous.value + part.value };\n } else {\n parts.push({ type: 'integer', value: part.value });\n }\n } else if (\n part.type === 'currency' ||\n part.type === 'decimal' ||\n part.type === 'fraction' ||\n part.type === 'literal' ||\n part.type === 'minusSign' ||\n part.type === 'plusSign'\n ) {\n parts.push({ type: part.type, value: part.value });\n } else {\n parts.push({ type: 'literal', value: part.value });\n }\n }\n\n return parts;\n}\n"],"mappings":";;;;AAKA,IAAM,IAAsB,IACtB,IAAsC,oBACtC,IAAoF;CACxF,cAAc;CACd,MAAM;CACN,OAAO;CACP,kBAAkB;CAClB,UAAU;CACV,YAAY;AACd;AAEA,SAAgB,EAAO,GAAc,IAAyB,CAAC,GAAW;CACxE,OAAO,EAAY,GAAO,CAAO,CAAC,CAC/B,KAAK,MAAS,EAAK,KAAK,CAAC,CACzB,KAAK,EAAE;AACZ;AAEA,SAAgB,EAAY,GAAc,IAAyB,CAAC,GAAsB;CAExF,AADA,EAAY,CAAK,GACjB,EAAmB,EAAQ,YAAY,CAAqB;CAE5D,IAAM,EAAE,YAAS,eAAY,EAAe,EAAM,SAAS,WAAW,CAAO,GACvE,IAAQ,EAAQ,SAAS;CAE/B,IAAI;EAWF,OAAO,EAAe,IAVA,KAAK,aAAa,EAAQ,UAAU,SAAS;GACjE,UAAU,EAAM,SAAS;GACzB,iBAAiB;GACjB,uBAAuB;GACvB,uBAAuB;GACvB,cAAc,EAAkB,EAAQ,YAAY;GACpD,OAAO;GACP,aAAa;EACf,CAEsB,CAAA,CAAU,cAAc,EAAU,CAAK,CAAsB,CAAC;CACtF,SAAS,GAAO;EAGd,MAFI,aAAiB,IAAkB,IAEjC,IAAI,EACR,gBACA,2BAA2B,EAAM,SAAS,KAAK,gBAAgB,EAAQ,UAAU,QAAQ,IACzF,EAAE,OAAO,EAAM,CACjB;CACF;AACF;AAEA,SAAS,EAAe,GAAe,GAA8D;CACnG,IAAM,IAAmB,EAAQ,uBAC3B,IAAmB,EAAQ;CAGjC,AADA,EAAsB,yBAAyB,CAAgB,GAC/D,EAAsB,yBAAyB,CAAgB;CAE/D,IAAM,IAAU,KAAoB,KAAK,IAAI,GAAO,KAAoB,CAAK,GACvE,IAAU,KAAoB,KAAK,IAAI,GAAO,KAAoB,CAAK;CAE7E,IAAI,IAAU,GACZ,MAAM,IAAI,EAAW,gBAAgB,2DAA2D;CAGlG,OAAO;EAAE;EAAS;CAAQ;AAC5B;AAEA,SAAS,EAAsB,GAAc,GAAiC;CAC5E,IAAI,MAAU,KAAA,MAAc,CAAC,OAAO,UAAU,CAAK,KAAK,IAAQ,KAAK,IAAQ,IAC3E,MAAM,IAAI,EACR,gBACA,uEAAuE,EAAoB,IAAI,EAAK,EACtG;AAEJ;AAEA,SAAS,EAAe,GAAiD;CACvE,IAAM,IAA2B,CAAC;CAElC,KAAK,IAAM,KAAQ,GACjB,IAAI,EAAK,SAAS,aAAa,EAAK,SAAS,SAAS;EACpD,IAAM,IAAW,EAAM,GAAG,EAAE;EAE5B,AAAI,GAAU,SAAS,YACrB,EAAM,EAAM,SAAS,KAAK;GAAE,MAAM;GAAW,OAAO,EAAS,QAAQ,EAAK;EAAM,IAEhF,EAAM,KAAK;GAAE,MAAM;GAAW,OAAO,EAAK;EAAM,CAAC;CAErD,OAAO,AACL,EAAK,SAAS,cACd,EAAK,SAAS,aACd,EAAK,SAAS,cACd,EAAK,SAAS,aACd,EAAK,SAAS,eACd,EAAK,SAAS,aAEd,EAAM,KAAK;EAAE,MAAM,EAAK;EAAM,OAAO,EAAK;CAAM,CAAC,IAEjD,EAAM,KAAK;EAAE,MAAM;EAAW,OAAO,EAAK;CAAM,CAAC;CAIrD,OAAO;AACT"}
1
+ {"version":3,"file":"format.js","names":[],"sources":["../src/format.ts"],"sourcesContent":["import { assertRoundingMode } from './_decimal';\nimport { CoinsError } from './errors';\nimport { assertMoney, toDecimal } from './money';\nimport type { FormatOptions, Money, MoneyFormatPart, RoundingMode } from './types';\n\nconst MAX_FRACTION_DIGITS = 20;\nconst defaultFormatRounding: RoundingMode = 'halfAwayFromZero';\nconst intlRoundingModes: Record<RoundingMode, Intl.NumberFormatOptions['roundingMode']> = {\n awayFromZero: 'expand',\n ceil: 'ceil',\n floor: 'floor',\n halfAwayFromZero: 'halfExpand',\n halfEven: 'halfEven',\n towardZero: 'trunc',\n};\n\nexport function format(value: Money, options: FormatOptions = {}): string {\n return formatParts(value, options)\n .map((part) => part.value)\n .join('');\n}\n\nexport function formatParts(value: Money, options: FormatOptions = {}): MoneyFormatPart[] {\n assertMoney(value);\n assertRoundingMode(options.rounding ?? defaultFormatRounding);\n\n const { maximum, minimum } = fractionDigits(value.currency.minorUnit, options);\n const style = options.style ?? 'symbol';\n\n try {\n const formatter = new Intl.NumberFormat(options.locale ?? 'en-US', {\n currency: value.currency.code,\n currencyDisplay: style,\n maximumFractionDigits: maximum,\n minimumFractionDigits: minimum,\n roundingMode: intlRoundingModes[options.rounding ?? defaultFormatRounding],\n style: 'currency',\n useGrouping: true,\n });\n\n return normalizeParts(formatter.formatToParts(toDecimal(value) as unknown as number));\n } catch (error) {\n if (error instanceof CoinsError) throw error;\n\n throw new CoinsError(\n 'FORMAT_ERROR',\n `Cannot format currency \"${value.currency.code}\" for locale \"${options.locale ?? 'en-US'}\"`,\n { cause: error },\n );\n }\n}\n\nfunction fractionDigits(scale: number, options: FormatOptions): { maximum: number; minimum: number } {\n const requestedMaximum = options.maximumFractionDigits;\n const requestedMinimum = options.minimumFractionDigits;\n\n validateFractionDigit('maximumFractionDigits', requestedMaximum);\n validateFractionDigit('minimumFractionDigits', requestedMinimum);\n\n const maximum = requestedMaximum ?? Math.max(scale, requestedMinimum ?? scale);\n const minimum = requestedMinimum ?? Math.min(scale, requestedMaximum ?? scale);\n\n if (minimum > maximum) {\n throw new CoinsError('FORMAT_ERROR', 'minimumFractionDigits cannot exceed maximumFractionDigits');\n }\n\n return { maximum, minimum };\n}\n\nfunction validateFractionDigit(name: string, value: number | undefined): void {\n if (value !== undefined && (!Number.isInteger(value) || value < 0 || value > MAX_FRACTION_DIGITS)) {\n throw new CoinsError(\n 'FORMAT_ERROR',\n `Fraction digits must be integers satisfying 0 ≤ minimum ≤ maximum ≤ ${MAX_FRACTION_DIGITS} (${name})`,\n );\n }\n}\n\nfunction normalizeParts(raw: Intl.NumberFormatPart[]): MoneyFormatPart[] {\n const parts: MoneyFormatPart[] = [];\n\n for (const part of raw) {\n if (part.type === 'integer' || part.type === 'group') {\n const previous = parts.at(-1);\n\n if (previous?.type === 'integer') {\n parts[parts.length - 1] = { type: 'integer', value: previous.value + part.value };\n } else {\n parts.push({ type: 'integer', value: part.value });\n }\n } else if (\n part.type === 'currency' ||\n part.type === 'decimal' ||\n part.type === 'fraction' ||\n part.type === 'literal' ||\n part.type === 'minusSign' ||\n part.type === 'plusSign'\n ) {\n parts.push({ type: part.type, value: part.value });\n } else {\n parts.push({ type: 'literal', value: part.value });\n }\n }\n\n return parts;\n}\n"],"mappings":"oJAKA,IAAM,EAAsB,GACtB,EAAsC,mBACtC,EAAoF,CACxF,aAAc,SACd,KAAM,OACN,MAAO,QACP,iBAAkB,aAClB,SAAU,WACV,WAAY,OACd,EAEA,SAAgB,OAAO,EAAc,EAAyB,CAAC,EAAW,CACxE,OAAO,YAAY,EAAO,CAAO,CAAC,CAC/B,IAAK,GAAS,EAAK,KAAK,CAAC,CACzB,KAAK,EAAE,CACZ,CAEA,SAAgB,YAAY,EAAc,EAAyB,CAAC,EAAsB,CACxF,EAAY,CAAK,EACjB,EAAmB,EAAQ,UAAY,CAAqB,EAE5D,GAAM,CAAE,UAAS,WAAY,eAAe,EAAM,SAAS,UAAW,CAAO,EACvE,EAAQ,EAAQ,OAAS,SAE/B,GAAI,CAWF,OAAO,eAAe,IAVA,KAAK,aAAa,EAAQ,QAAU,QAAS,CACjE,SAAU,EAAM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AS,YACd,EAAK,OAAS,WACd,EAAK,OAAS,aACd,EAAK,OAAS,WAEd,EAAM,KAAK,CAAE,KAAM,EAAK,KAAM,MAAO,EAAK,KAAM,CAAC,EAEjD,EAAM,KAAK,CAAE,KAAM,UAAW,MAAO,EAAK,KAAM,CAAC,EAIrD,OAAO,CACT"}
package/dist/index.js CHANGED
@@ -1,8 +1 @@
1
- import { CoinsError as e, CurrencyMismatchError as t, InvalidCurrencyError as n } from "./errors.js";
2
- import { BHD as r, EUR as i, GBP as a, JPY as o, KRW as s, KWD as c, USD as l, currency as u, isCurrency as d } from "./currency.js";
3
- import { abs as f, add as p, clamp as m, compare as h, decodeMoney as g, divide as _, isMoney as v, money as y, multiply as b, negate as x, round as S, subtract as C, toDecimal as w } from "./money.js";
4
- import { allocate as T, sum as E } from "./aggregate.js";
5
- import { exchange as D, exchangeRate as O, isExchangeRate as k } from "./exchange.js";
6
- import { format as A, formatParts as j } from "./format.js";
7
- import { toJSON as M } from "./serialization.js";
8
- export { r as BHD, e as CoinsError, t as CurrencyMismatchError, i as EUR, a as GBP, n as InvalidCurrencyError, o as JPY, s as KRW, c as KWD, l as USD, f as abs, p as add, T as allocate, m as clamp, h as compare, u as currency, g as decodeMoney, _ as divide, D as exchange, O as exchangeRate, A as format, j as formatParts, d as isCurrency, k as isExchangeRate, v as isMoney, y as money, b as multiply, x as negate, S as round, C as subtract, E as sum, w as toDecimal, M as toJSON };
1
+ import{CoinsError as e,CurrencyMismatchError as t,InvalidCurrencyError as n}from"./errors.js";import{BHD as r,EUR as i,GBP as a,JPY as o,KRW as s,KWD as c,USD as l,currency as u,isCurrency as d}from"./currency.js";import{abs as f,add as p,clamp as m,compare as h,decodeMoney as g,divide as _,isMoney as v,money as y,multiply as b,negate as x,round as S,subtract as C,toDecimal as w}from"./money.js";import{allocate as T,sum as E}from"./aggregate.js";import{exchange as D,exchangeRate as O,isExchangeRate as k}from"./exchange.js";import{format as A,formatParts as j}from"./format.js";import{toJSON as M}from"./serialization.js";export{r as BHD,e as CoinsError,t as CurrencyMismatchError,i as EUR,a as GBP,n as InvalidCurrencyError,o as JPY,s as KRW,c as KWD,l as USD,f as abs,p as add,T as allocate,m as clamp,h as compare,u as currency,g as decodeMoney,_ as divide,D as exchange,O as exchangeRate,A as format,j as formatParts,d as isCurrency,k as isExchangeRate,v as isMoney,y as money,b as multiply,x as negate,S as round,C as subtract,E as sum,w as toDecimal,M as toJSON};
package/dist/money.cjs CHANGED
@@ -1,2 +1,2 @@
1
- const e=require("./errors.cjs"),t=require("./_decimal.cjs"),n=require("./currency.cjs");var r=new WeakSet,i=`halfAwayFromZero`,a=/^(?:0|-[1-9]\d*|[1-9]\d*)$/,o=1e3;function s(n,r,a){if(C(r),typeof n==`bigint`){if(!a||!(`unit`in a)||a.unit!==`minor`)throw new e.CoinsError(`INVALID_MONEY`,`Bigint amounts require { unit: 'minor' }`);return b(n,r)}if(a&&`unit`in a)throw new e.CoinsError(`INVALID_MONEY`,`Decimal strings do not accept a unit option`);let o=t.decimal(n),s=o.numerator*10n**BigInt(r.minorUnit);if(s%o.denominator!==0n&&a?.rounding===void 0)throw new e.CoinsError(`INVALID_MONEY`,`Amount "${n}" exceeds ${r.code} precision; provide rounding`);return b(t.roundDivision(s,o.denominator,a?.rounding??i),r)}function c(t,r){if(!w(t))throw new e.CoinsError(`INVALID_MONEY`,`Money must be a plain data object`);let i=Object.getOwnPropertyDescriptors(t),c=i.amount,l=i.currency;if(!T(c)||!T(l))throw new e.CoinsError(`INVALID_MONEY`,`Money properties must be plain data values`);let u=Reflect.ownKeys(t);if(typeof c.value==`bigint`&&n.isCurrency(l.value)){if(u.length!==2)throw new e.CoinsError(`INVALID_MONEY`,`Plain money must have exactly the keys amount and currency`);return b(c.value,l.value)}let d=i.unit;if(typeof c.value==`string`&&typeof l.value==`string`&&T(d)&&d.value===`minor`){if(u.length!==3)throw new e.CoinsError(`INVALID_MONEY`,`MoneyJSON must have exactly the keys amount, currency, unit`);if(c.value.length>o)throw new e.CoinsError(`INVALID_MONEY`,`Money JSON amount is too long; maximum ${o} characters`);if(!a.test(c.value))throw new e.CoinsError(`INVALID_MONEY`,`Invalid Money JSON amount "${c.value}"`);let t=r?.currency??n.currency;try{let r=t(l.value);if(!n.isCurrency(r)||r.code!==l.value)throw new e.CoinsError(`INVALID_CURRENCY`,`Currency resolver must return the canonical "${l.value}" definition`);return s(BigInt(c.value),r,{unit:`minor`})}catch(t){throw new e.CoinsError(`INVALID_MONEY`,`Invalid Money JSON for currency "${l.value}"`,{cause:t})}}throw new e.CoinsError(`INVALID_MONEY`,`Money must contain bigint amount and a registered currency, or a valid MoneyJSON shape`)}function l(e){return typeof e==`object`&&!!e&&r.has(e)}function u(e,t){return S(e,t),b(e.amount+t.amount,e.currency)}function d(e,t){return S(e,t),b(e.amount-t.amount,e.currency)}function f(e,n,r={}){x(e);let a=t.decimal(n);return b(t.roundDivision(e.amount*a.numerator,a.denominator,r.rounding??i),e.currency)}function p(n,r,a={}){x(n);let o=t.decimal(r);if(o.numerator===0n)throw new e.CoinsError(`DIVISION_BY_ZERO`,`Cannot divide money by zero`);let s=o.numerator<0n?-o.numerator:o.numerator,c=n.amount*o.denominator;return b(t.roundDivision(o.numerator<0n?-c:c,s,a.rounding??i),n.currency)}function m(e,t){return S(e,t),e.amount===t.amount?0:e.amount<t.amount?-1:1}function h(t,n){if(m(n.min,n.max)===1)throw new e.CoinsError(`INVALID_RANGE`,`Clamp minimum cannot exceed maximum`);return m(t,n.min)===-1?n.min:m(t,n.max)===1?n.max:t}function g(e){return x(e),b(e.amount<0n?-e.amount:e.amount,e.currency)}function _(e){return x(e),b(-e.amount,e.currency)}function v(n,r){x(n);let{fractionDigits:a,rounding:o=i}=r;if(!Number.isInteger(a)||a<0||a>n.currency.minorUnit)throw new e.CoinsError(`INVALID_ROUNDING`,`fractionDigits must be an integer from 0 to ${n.currency.minorUnit}`);let s=10n**BigInt(n.currency.minorUnit-a);return b(t.roundDivision(n.amount,s,o)*s,n.currency)}function y(e){return x(e),t.toDecimalString(e.amount,e.currency.minorUnit)}function b(e,t){let n=Object.freeze({amount:e,currency:t});return r.add(n),n}function x(t){if(!l(t))throw new e.CoinsError(`INVALID_MONEY`,`Money must be a canonical @vielzeug/coins value`)}function S(t,n){if(x(t),x(n),t.currency!==n.currency)throw new e.CurrencyMismatchError(t.currency.code,n.currency.code)}function C(t){if(!n.isCurrency(t))throw new e.CoinsError(`INVALID_CURRENCY`,`Money requires a registered currency`)}function w(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function T(e){return e!==void 0&&`value`in e&&e.get===void 0&&e.set===void 0}exports.abs=g,exports.add=u,exports.assertMoney=x,exports.clamp=h,exports.compare=m,exports.createMoney=b,exports.decodeMoney=c,exports.divide=p,exports.isMoney=l,exports.money=s,exports.multiply=f,exports.negate=_,exports.round=v,exports.subtract=d,exports.toDecimal=y;
1
+ const e=require("./errors.cjs"),t=require("./_decimal.cjs"),n=require("./currency.cjs");var r=new WeakSet,i=`halfAwayFromZero`,a=/^(?:0|-[1-9]\d*|[1-9]\d*)$/,o=1e3;function money(n,r,a){if(assertCurrency(r),typeof n==`bigint`){if(!a||!(`unit`in a)||a.unit!==`minor`)throw new e.CoinsError(`INVALID_MONEY`,`Bigint amounts require { unit: 'minor' }`);return createMoney(n,r)}if(a&&`unit`in a)throw new e.CoinsError(`INVALID_MONEY`,`Decimal strings do not accept a unit option`);let o=t.decimal(n),s=o.numerator*10n**BigInt(r.minorUnit);if(s%o.denominator!==0n&&a?.rounding===void 0)throw new e.CoinsError(`INVALID_MONEY`,`Amount "${n}" exceeds ${r.code} precision; provide rounding`);return createMoney(t.roundDivision(s,o.denominator,a?.rounding??i),r)}function decodeMoney(t,r){if(!isPlainDataObject(t))throw new e.CoinsError(`INVALID_MONEY`,`Money must be a plain data object`);let i=Object.getOwnPropertyDescriptors(t),s=i.amount,c=i.currency;if(!isDataProperty(s)||!isDataProperty(c))throw new e.CoinsError(`INVALID_MONEY`,`Money properties must be plain data values`);let l=Reflect.ownKeys(t);if(typeof s.value==`bigint`&&n.isCurrency(c.value)){if(l.length!==2)throw new e.CoinsError(`INVALID_MONEY`,`Plain money must have exactly the keys amount and currency`);return createMoney(s.value,c.value)}let u=i.unit;if(typeof s.value==`string`&&typeof c.value==`string`&&isDataProperty(u)&&u.value===`minor`){if(l.length!==3)throw new e.CoinsError(`INVALID_MONEY`,`MoneyJSON must have exactly the keys amount, currency, unit`);if(s.value.length>o)throw new e.CoinsError(`INVALID_MONEY`,`Money JSON amount is too long; maximum ${o} characters`);if(!a.test(s.value))throw new e.CoinsError(`INVALID_MONEY`,`Invalid Money JSON amount "${s.value}"`);let t=r?.currency??n.currency;try{let r=t(c.value);if(!n.isCurrency(r)||r.code!==c.value)throw new e.CoinsError(`INVALID_CURRENCY`,`Currency resolver must return the canonical "${c.value}" definition`);return money(BigInt(s.value),r,{unit:`minor`})}catch(t){throw new e.CoinsError(`INVALID_MONEY`,`Invalid Money JSON for currency "${c.value}"`,{cause:t})}}throw new e.CoinsError(`INVALID_MONEY`,`Money must contain bigint amount and a registered currency, or a valid MoneyJSON shape`)}function isMoney(e){return typeof e==`object`&&!!e&&r.has(e)}function add(e,t){return assertSameCurrency(e,t),createMoney(e.amount+t.amount,e.currency)}function subtract(e,t){return assertSameCurrency(e,t),createMoney(e.amount-t.amount,e.currency)}function multiply(e,n,r={}){assertMoney(e);let a=t.decimal(n);return createMoney(t.roundDivision(e.amount*a.numerator,a.denominator,r.rounding??i),e.currency)}function divide(n,r,a={}){assertMoney(n);let o=t.decimal(r);if(o.numerator===0n)throw new e.CoinsError(`DIVISION_BY_ZERO`,`Cannot divide money by zero`);let s=o.numerator<0n?-o.numerator:o.numerator,c=n.amount*o.denominator;return createMoney(t.roundDivision(o.numerator<0n?-c:c,s,a.rounding??i),n.currency)}function compare(e,t){return assertSameCurrency(e,t),e.amount===t.amount?0:e.amount<t.amount?-1:1}function clamp(t,n){if(compare(n.min,n.max)===1)throw new e.CoinsError(`INVALID_RANGE`,`Clamp minimum cannot exceed maximum`);return compare(t,n.min)===-1?n.min:compare(t,n.max)===1?n.max:t}function abs(e){return assertMoney(e),createMoney(e.amount<0n?-e.amount:e.amount,e.currency)}function negate(e){return assertMoney(e),createMoney(-e.amount,e.currency)}function round(n,r){assertMoney(n);let{fractionDigits:a,rounding:o=i}=r;if(!Number.isInteger(a)||a<0||a>n.currency.minorUnit)throw new e.CoinsError(`INVALID_ROUNDING`,`fractionDigits must be an integer from 0 to ${n.currency.minorUnit}`);let s=10n**BigInt(n.currency.minorUnit-a);return createMoney(t.roundDivision(n.amount,s,o)*s,n.currency)}function toDecimal(e){return assertMoney(e),t.toDecimalString(e.amount,e.currency.minorUnit)}function createMoney(e,t){let n=Object.freeze({amount:e,currency:t});return r.add(n),n}function assertMoney(t){if(!isMoney(t))throw new e.CoinsError(`INVALID_MONEY`,`Money must be a canonical @vielzeug/coins value`)}function assertSameCurrency(t,n){if(assertMoney(t),assertMoney(n),t.currency!==n.currency)throw new e.CurrencyMismatchError(t.currency.code,n.currency.code)}function assertCurrency(t){if(!n.isCurrency(t))throw new e.CoinsError(`INVALID_CURRENCY`,`Money requires a registered currency`)}function isPlainDataObject(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function isDataProperty(e){return e!==void 0&&`value`in e&&e.get===void 0&&e.set===void 0}exports.abs=abs,exports.add=add,exports.assertMoney=assertMoney,exports.clamp=clamp,exports.compare=compare,exports.createMoney=createMoney,exports.decodeMoney=decodeMoney,exports.divide=divide,exports.isMoney=isMoney,exports.money=money,exports.multiply=multiply,exports.negate=negate,exports.round=round,exports.subtract=subtract,exports.toDecimal=toDecimal;
2
2
  //# sourceMappingURL=money.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"money.cjs","names":[],"sources":["../src/money.ts"],"sourcesContent":["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"],"mappings":"wFAKA,IAAM,EAA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ources":["../src/money.ts"],"sourcesContent":["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 } {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a,UAAW,GAAc,EAAW,MAAQ,IAAA,IAAa,EAAW,MAAQ,IAAA,EAE5G"}
package/dist/money.js CHANGED
@@ -1,112 +1,2 @@
1
- import { CoinsError as e, CurrencyMismatchError as t } from "./errors.js";
2
- import { decimal as n, roundDivision as r, toDecimalString as i } from "./_decimal.js";
3
- import { currency as a, isCurrency as o } from "./currency.js";
4
- //#region src/money.ts
5
- var s = /* @__PURE__ */ new WeakSet(), c = "halfAwayFromZero", l = /^(?:0|-[1-9]\d*|[1-9]\d*)$/, u = 1e3;
6
- function d(t, i, a) {
7
- if (D(i), typeof t == "bigint") {
8
- if (!a || !("unit" in a) || a.unit !== "minor") throw new e("INVALID_MONEY", "Bigint amounts require { unit: 'minor' }");
9
- return w(t, i);
10
- }
11
- if (a && "unit" in a) throw new e("INVALID_MONEY", "Decimal strings do not accept a unit option");
12
- let o = n(t), s = o.numerator * 10n ** BigInt(i.minorUnit);
13
- if (s % o.denominator !== 0n && a?.rounding === void 0) throw new e("INVALID_MONEY", `Amount "${t}" exceeds ${i.code} precision; provide rounding`);
14
- return w(r(s, o.denominator, a?.rounding ?? c), i);
15
- }
16
- function f(t, n) {
17
- if (!O(t)) throw new e("INVALID_MONEY", "Money must be a plain data object");
18
- let r = Object.getOwnPropertyDescriptors(t), i = r.amount, s = r.currency;
19
- if (!k(i) || !k(s)) throw new e("INVALID_MONEY", "Money properties must be plain data values");
20
- let c = Reflect.ownKeys(t);
21
- if (typeof i.value == "bigint" && o(s.value)) {
22
- if (c.length !== 2) throw new e("INVALID_MONEY", "Plain money must have exactly the keys amount and currency");
23
- return w(i.value, s.value);
24
- }
25
- let f = r.unit;
26
- if (typeof i.value == "string" && typeof s.value == "string" && k(f) && f.value === "minor") {
27
- if (c.length !== 3) throw new e("INVALID_MONEY", "MoneyJSON must have exactly the keys amount, currency, unit");
28
- if (i.value.length > u) throw new e("INVALID_MONEY", `Money JSON amount is too long; maximum ${u} characters`);
29
- if (!l.test(i.value)) throw new e("INVALID_MONEY", `Invalid Money JSON amount "${i.value}"`);
30
- let t = n?.currency ?? a;
31
- try {
32
- let n = t(s.value);
33
- if (!o(n) || n.code !== s.value) throw new e("INVALID_CURRENCY", `Currency resolver must return the canonical "${s.value}" definition`);
34
- return d(BigInt(i.value), n, { unit: "minor" });
35
- } catch (t) {
36
- throw new e("INVALID_MONEY", `Invalid Money JSON for currency "${s.value}"`, { cause: t });
37
- }
38
- }
39
- throw new e("INVALID_MONEY", "Money must contain bigint amount and a registered currency, or a valid MoneyJSON shape");
40
- }
41
- function p(e) {
42
- return typeof e == "object" && !!e && s.has(e);
43
- }
44
- function m(e, t) {
45
- return E(e, t), w(e.amount + t.amount, e.currency);
46
- }
47
- function h(e, t) {
48
- return E(e, t), w(e.amount - t.amount, e.currency);
49
- }
50
- function g(e, t, i = {}) {
51
- T(e);
52
- let a = n(t);
53
- return w(r(e.amount * a.numerator, a.denominator, i.rounding ?? c), e.currency);
54
- }
55
- function _(t, i, a = {}) {
56
- T(t);
57
- let o = n(i);
58
- if (o.numerator === 0n) throw new e("DIVISION_BY_ZERO", "Cannot divide money by zero");
59
- let s = o.numerator < 0n ? -o.numerator : o.numerator, l = t.amount * o.denominator;
60
- return w(r(o.numerator < 0n ? -l : l, s, a.rounding ?? c), t.currency);
61
- }
62
- function v(e, t) {
63
- return E(e, t), e.amount === t.amount ? 0 : e.amount < t.amount ? -1 : 1;
64
- }
65
- function y(t, n) {
66
- if (v(n.min, n.max) === 1) throw new e("INVALID_RANGE", "Clamp minimum cannot exceed maximum");
67
- return v(t, n.min) === -1 ? n.min : v(t, n.max) === 1 ? n.max : t;
68
- }
69
- function b(e) {
70
- return T(e), w(e.amount < 0n ? -e.amount : e.amount, e.currency);
71
- }
72
- function x(e) {
73
- return T(e), w(-e.amount, e.currency);
74
- }
75
- function S(t, n) {
76
- T(t);
77
- let { fractionDigits: i, rounding: a = c } = n;
78
- if (!Number.isInteger(i) || i < 0 || i > t.currency.minorUnit) throw new e("INVALID_ROUNDING", `fractionDigits must be an integer from 0 to ${t.currency.minorUnit}`);
79
- let o = 10n ** BigInt(t.currency.minorUnit - i);
80
- return w(r(t.amount, o, a) * o, t.currency);
81
- }
82
- function C(e) {
83
- return T(e), i(e.amount, e.currency.minorUnit);
84
- }
85
- function w(e, t) {
86
- let n = Object.freeze({
87
- amount: e,
88
- currency: t
89
- });
90
- return s.add(n), n;
91
- }
92
- function T(t) {
93
- if (!p(t)) throw new e("INVALID_MONEY", "Money must be a canonical @vielzeug/coins value");
94
- }
95
- function E(e, n) {
96
- if (T(e), T(n), e.currency !== n.currency) throw new t(e.currency.code, n.currency.code);
97
- }
98
- function D(t) {
99
- if (!o(t)) throw new e("INVALID_CURRENCY", "Money requires a registered currency");
100
- }
101
- function O(e) {
102
- if (typeof e != "object" || !e) return !1;
103
- let t = Object.getPrototypeOf(e);
104
- return t === Object.prototype || t === null;
105
- }
106
- function k(e) {
107
- return e !== void 0 && "value" in e && e.get === void 0 && e.set === void 0;
108
- }
109
- //#endregion
110
- export { b as abs, m as add, T as assertMoney, y as clamp, v as compare, w as createMoney, f as decodeMoney, _ as divide, p as isMoney, d as money, g as multiply, x as negate, S as round, h as subtract, C as toDecimal };
111
-
1
+ import{CoinsError as e,CurrencyMismatchError as t}from"./errors.js";import{decimal as n,roundDivision as r,toDecimalString as i}from"./_decimal.js";import{currency as a,isCurrency as o}from"./currency.js";var s=new WeakSet,c=`halfAwayFromZero`,l=/^(?:0|-[1-9]\d*|[1-9]\d*)$/,u=1e3;function money(t,i,a){if(assertCurrency(i),typeof t==`bigint`){if(!a||!(`unit`in a)||a.unit!==`minor`)throw new e(`INVALID_MONEY`,`Bigint amounts require { unit: 'minor' }`);return createMoney(t,i)}if(a&&`unit`in a)throw new e(`INVALID_MONEY`,`Decimal strings do not accept a unit option`);let o=n(t),s=o.numerator*10n**BigInt(i.minorUnit);if(s%o.denominator!==0n&&a?.rounding===void 0)throw new e(`INVALID_MONEY`,`Amount "${t}" exceeds ${i.code} precision; provide rounding`);return createMoney(r(s,o.denominator,a?.rounding??c),i)}function decodeMoney(t,n){if(!isPlainDataObject(t))throw new e(`INVALID_MONEY`,`Money must be a plain data object`);let r=Object.getOwnPropertyDescriptors(t),i=r.amount,s=r.currency;if(!isDataProperty(i)||!isDataProperty(s))throw new e(`INVALID_MONEY`,`Money properties must be plain data values`);let c=Reflect.ownKeys(t);if(typeof i.value==`bigint`&&o(s.value)){if(c.length!==2)throw new e(`INVALID_MONEY`,`Plain money must have exactly the keys amount and currency`);return createMoney(i.value,s.value)}let d=r.unit;if(typeof i.value==`string`&&typeof s.value==`string`&&isDataProperty(d)&&d.value===`minor`){if(c.length!==3)throw new e(`INVALID_MONEY`,`MoneyJSON must have exactly the keys amount, currency, unit`);if(i.value.length>u)throw new e(`INVALID_MONEY`,`Money JSON amount is too long; maximum ${u} characters`);if(!l.test(i.value))throw new e(`INVALID_MONEY`,`Invalid Money JSON amount "${i.value}"`);let t=n?.currency??a;try{let n=t(s.value);if(!o(n)||n.code!==s.value)throw new e(`INVALID_CURRENCY`,`Currency resolver must return the canonical "${s.value}" definition`);return money(BigInt(i.value),n,{unit:`minor`})}catch(t){throw new e(`INVALID_MONEY`,`Invalid Money JSON for currency "${s.value}"`,{cause:t})}}throw new e(`INVALID_MONEY`,`Money must contain bigint amount and a registered currency, or a valid MoneyJSON shape`)}function isMoney(e){return typeof e==`object`&&!!e&&s.has(e)}function add(e,t){return assertSameCurrency(e,t),createMoney(e.amount+t.amount,e.currency)}function subtract(e,t){return assertSameCurrency(e,t),createMoney(e.amount-t.amount,e.currency)}function multiply(e,t,i={}){assertMoney(e);let a=n(t);return createMoney(r(e.amount*a.numerator,a.denominator,i.rounding??c),e.currency)}function divide(t,i,a={}){assertMoney(t);let o=n(i);if(o.numerator===0n)throw new e(`DIVISION_BY_ZERO`,`Cannot divide money by zero`);let s=o.numerator<0n?-o.numerator:o.numerator,l=t.amount*o.denominator;return createMoney(r(o.numerator<0n?-l:l,s,a.rounding??c),t.currency)}function compare(e,t){return assertSameCurrency(e,t),e.amount===t.amount?0:e.amount<t.amount?-1:1}function clamp(t,n){if(compare(n.min,n.max)===1)throw new e(`INVALID_RANGE`,`Clamp minimum cannot exceed maximum`);return compare(t,n.min)===-1?n.min:compare(t,n.max)===1?n.max:t}function abs(e){return assertMoney(e),createMoney(e.amount<0n?-e.amount:e.amount,e.currency)}function negate(e){return assertMoney(e),createMoney(-e.amount,e.currency)}function round(t,n){assertMoney(t);let{fractionDigits:i,rounding:a=c}=n;if(!Number.isInteger(i)||i<0||i>t.currency.minorUnit)throw new e(`INVALID_ROUNDING`,`fractionDigits must be an integer from 0 to ${t.currency.minorUnit}`);let o=10n**BigInt(t.currency.minorUnit-i);return createMoney(r(t.amount,o,a)*o,t.currency)}function toDecimal(e){return assertMoney(e),i(e.amount,e.currency.minorUnit)}function createMoney(e,t){let n=Object.freeze({amount:e,currency:t});return s.add(n),n}function assertMoney(t){if(!isMoney(t))throw new e(`INVALID_MONEY`,`Money must be a canonical @vielzeug/coins value`)}function assertSameCurrency(e,n){if(assertMoney(e),assertMoney(n),e.currency!==n.currency)throw new t(e.currency.code,n.currency.code)}function assertCurrency(t){if(!o(t))throw new e(`INVALID_CURRENCY`,`Money requires a registered currency`)}function isPlainDataObject(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function isDataProperty(e){return e!==void 0&&`value`in e&&e.get===void 0&&e.set===void 0}export{abs,add,assertMoney,clamp,compare,createMoney,decodeMoney,divide,isMoney,money,multiply,negate,round,subtract,toDecimal};
112
2
  //# sourceMappingURL=money.js.map