@vielzeug/coins 26.10.15 → 26.10.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Helmuth Saatkamp
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1 +1 @@
1
- {"version":3,"file":"_decimal.cjs","names":[],"sources":["../src/_decimal.ts"],"sourcesContent":["import { CoinsError } from './errors';\nimport type { Decimal, RoundingMode } from './types';\n\nconst DECIMAL = /^(-?)(\\d+)(?:\\.(\\d+))?$/;\nconst MAX_DECIMAL_DIGITS = 1000;\nconst MAX_DECIMAL_PLACES = 100;\nconst ROUNDING_MODES = new Set<RoundingMode>([\n 'awayFromZero',\n 'ceil',\n 'floor',\n 'halfAwayFromZero',\n 'halfEven',\n 'towardZero',\n]);\n\nexport function assertRoundingMode(value: unknown): asserts value is RoundingMode {\n if (!ROUNDING_MODES.has(value as RoundingMode)) {\n throw new CoinsError('INVALID_ROUNDING', `Unknown rounding mode: ${String(value)}`);\n }\n}\n\nexport function decimal(value: string): Decimal {\n if (typeof value !== 'string') throw new CoinsError('INVALID_DECIMAL', 'Decimal input must be a string');\n if (value.length > MAX_DECIMAL_DIGITS) throw new CoinsError('INVALID_DECIMAL', 'Decimal input is too long');\n\n const match = DECIMAL.exec(value);\n\n if (!match) throw new CoinsError('INVALID_DECIMAL', `Invalid decimal: \"${value}\"`);\n\n const fraction = (match[3] ?? '').replace(/0+$/, '');\n\n if (fraction.length > MAX_DECIMAL_PLACES) {\n throw new CoinsError('INVALID_DECIMAL', `Decimal precision cannot exceed ${MAX_DECIMAL_PLACES} places`);\n }\n\n const denominator = 10n ** BigInt(fraction.length);\n const unsigned = BigInt(match[2]!) * denominator + BigInt(fraction || '0');\n const numerator = match[1] === '-' && unsigned !== 0n ? -unsigned : unsigned;\n const divisor = gcd(numerator < 0n ? -numerator : numerator, denominator);\n\n return Object.freeze({ denominator: denominator / divisor, numerator: numerator / divisor }) as Decimal;\n}\n\nexport function roundDivision(numerator: bigint, denominator: bigint, mode: RoundingMode): bigint {\n assertRoundingMode(mode);\n if (denominator <= 0n) throw new CoinsError('INVALID_DECIMAL', 'Decimal denominator must be positive');\n\n const negative = numerator < 0n;\n const absolute = negative ? -numerator : numerator;\n const quotient = absolute / denominator;\n const remainder = absolute % denominator;\n\n if (remainder === 0n) return negative ? -quotient : quotient;\n\n const increment = (() => {\n switch (mode) {\n case 'awayFromZero':\n return true;\n case 'ceil':\n return !negative;\n case 'floor':\n return negative;\n case 'halfAwayFromZero':\n return remainder * 2n >= denominator;\n case 'halfEven': {\n const doubled = remainder * 2n;\n\n return doubled > denominator || (doubled === denominator && quotient % 2n !== 0n);\n }\n case 'towardZero':\n return false;\n default:\n throw new CoinsError('INVALID_ROUNDING', `Unknown rounding mode: ${mode satisfies never}`);\n }\n })();\n\n const result = increment ? quotient + 1n : quotient;\n\n return negative ? -result : result;\n}\n\nexport function toDecimalString(amount: bigint, minorUnit: number): string {\n const negative = amount < 0n;\n const absolute = negative ? -amount : amount;\n const scale = 10n ** BigInt(minorUnit);\n const whole = absolute / scale;\n\n if (minorUnit === 0) return `${negative ? '-' : ''}${whole}`;\n\n const fraction = (absolute % scale).toString().padStart(minorUnit, '0');\n\n return `${negative ? '-' : ''}${whole}.${fraction}`;\n}\n\nexport function gcd(left: bigint, right: bigint): bigint {\n let a = left;\n let b = right;\n\n while (b !== 0n) [a, b] = [b, a % b];\n\n return a === 0n ? 1n : a;\n}\n\nexport function lcm(left: bigint, right: bigint): bigint {\n return (left / gcd(left, right)) * right;\n}\n"],"mappings":"gCAGA,IAAM,EAAU,0BACV,EAAqB,IACrB,EAAqB,IACrB,EAAiB,IAAI,IAAkB,CAC3C,eACA,OACA,QACA,mBACA,WACA,YACF,CAAC,EAED,SAAgB,mBAAmB,EAA+C,CAChF,GAAI,CAAC,EAAe,IAAI,CAAqB,EAC3C,MAAM,IAAI,EAAA,WAAW,mBAAoB,0BAA0B,OAAO,CAAK,GAAG,CAEtF,CAEA,SAAgB,QAAQ,EAAwB,CAC9C,GAAI,OAAO,GAAU,SAAU,MAAM,IAAI,EAAA,WAAW,kBAAmB,gCAAgC,EACvG,GAAI,EAAM,OAAS,EAAoB,MAAM,IAAI,EAAA,WAAW,kBAAmB,2BAA2B,EAE1G,IAAM,EAAQ,EAAQ,KAAK,CAAK,EAEhC,GAAI,CAAC,EAAO,MAAM,IAAI,EAAA,WAAW,kBAAmB,qBAAqB,EAAM,EAAE,EAEjF,IAAM,GAAY,EAAM,IAAM,GAAA,CAAI,QAAQ,MAAO,EAAE,EAEnD,GAAI,EAAS,OAAS,EACpB,MAAM,IAAI,EAAA,WAAW,kBAAmB,mCAAmC,EAAmB,QAAQ,EAGxG,IAAM,EAAc,KAAO,OAAO,EAAS,MAAM,EAC3C,EAAW,OAAO,EAAM,EAAG,EAAI,EAAc,OAAO,GAAY,G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IAAI,EAAI,EACJ,EAAI,EAER,KAAO,IAAM,IAAI,CAAC,EAAG,GAAK,CAAC,EAAG,EAAI,CAAC,EAEnC,OAAO,IAAM,GAAK,GAAK,CACzB,CAEA,SAAgB,IAAI,EAAc,EAAuB,CACvD,OAAQ,EAAO,IAAI,EAAM,CAAK,EAAK,CACrC"}
1
+ {"version":3,"file":"_decimal.cjs","names":["CoinsError","require_errors","DECIMAL","MAX_DECIMAL_DIGITS","MAX_DECIMAL_PLACES","ROUNDING_MODES","value","match","fraction","denominator","unsigned","numerator","divisor","mode","negative","absolute","quotient","remainder","result","doubled","amount","scale","minorUnit","whole","a","left","b","right"],"sources":["../src/_decimal.ts"],"sourcesContent":["import { CoinsError } from './errors';\nimport type { Decimal, RoundingMode } from './types';\n\nconst DECIMAL = /^(-?)(\\d+)(?:\\.(\\d+))?$/;\nconst MAX_DECIMAL_DIGITS = 1000;\nconst MAX_DECIMAL_PLACES = 100;\nconst ROUNDING_MODES = new Set<RoundingMode>([\n 'awayFromZero',\n 'ceil',\n 'floor',\n 'halfAwayFromZero',\n 'halfEven',\n 'towardZero',\n]);\n\nexport function assertRoundingMode(value: unknown): asserts value is RoundingMode {\n if (!ROUNDING_MODES.has(value as RoundingMode)) {\n throw new CoinsError('INVALID_ROUNDING', `Unknown rounding mode: ${String(value)}`);\n }\n}\n\nexport function decimal(value: string): Decimal {\n if (typeof value !== 'string') throw new CoinsError('INVALID_DECIMAL', 'Decimal input must be a string');\n if (value.length > MAX_DECIMAL_DIGITS) throw new CoinsError('INVALID_DECIMAL', 'Decimal input is too long');\n\n const match = DECIMAL.exec(value);\n\n if (!match) throw new CoinsError('INVALID_DECIMAL', `Invalid decimal: \"${value}\"`);\n\n const fraction = (match[3] ?? '').replace(/0+$/, '');\n\n if (fraction.length > MAX_DECIMAL_PLACES) {\n throw new CoinsError('INVALID_DECIMAL', `Decimal precision cannot exceed ${MAX_DECIMAL_PLACES} places`);\n }\n\n const denominator = 10n ** BigInt(fraction.length);\n const unsigned = BigInt(match[2]!) * denominator + BigInt(fraction || '0');\n const numerator = match[1] === '-' && unsigned !== 0n ? -unsigned : unsigned;\n const divisor = gcd(numerator < 0n ? -numerator : numerator, denominator);\n\n return Object.freeze({ denominator: denominator / divisor, numerator: numerator / divisor }) as Decimal;\n}\n\nexport function roundDivision(numerator: bigint, denominator: bigint, mode: RoundingMode): bigint {\n assertRoundingMode(mode);\n if (denominator <= 0n) throw new CoinsError('INVALID_DECIMAL', 'Decimal denominator must be positive');\n\n const negative = numerator < 0n;\n const absolute = negative ? -numerator : numerator;\n const quotient = absolute / denominator;\n const remainder = absolute % denominator;\n\n if (remainder === 0n) return negative ? -quotient : quotient;\n\n const increment = (() => {\n switch (mode) {\n case 'awayFromZero':\n return true;\n case 'ceil':\n return !negative;\n case 'floor':\n return negative;\n case 'halfAwayFromZero':\n return remainder * 2n >= denominator;\n case 'halfEven': {\n const doubled = remainder * 2n;\n\n return doubled > denominator || (doubled === denominator && quotient % 2n !== 0n);\n }\n case 'towardZero':\n return false;\n default:\n throw new CoinsError('INVALID_ROUNDING', `Unknown rounding mode: ${mode satisfies never}`);\n }\n })();\n\n const result = increment ? quotient + 1n : quotient;\n\n return negative ? -result : result;\n}\n\nexport function toDecimalString(amount: bigint, minorUnit: number): string {\n const negative = amount < 0n;\n const absolute = negative ? -amount : amount;\n const scale = 10n ** BigInt(minorUnit);\n const whole = absolute / scale;\n\n if (minorUnit === 0) return `${negative ? '-' : ''}${whole}`;\n\n const fraction = (absolute % scale).toString().padStart(minorUnit, '0');\n\n return `${negative ? '-' : ''}${whole}.${fraction}`;\n}\n\nexport function gcd(left: bigint, right: bigint): bigint {\n let a = left;\n let b = right;\n\n while (b !== 0n) [a, b] = [b, a % b];\n\n return a === 0n ? 1n : a;\n}\n\nexport function lcm(left: bigint, right: bigint): bigint {\n return (left / gcd(left, right)) * right;\n}\n"],"mappings":"A,gCAGA,IAAME,EAAU,0BACVC,EAAqB,IACrBC,EAAqB,IACrBC,EAAiB,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Ac,GAAI,OAAOH,EAAW,CAACE,EAAWA,EAwBpD,IAAME,OAtBmB,CACvB,OAAQL,EAAR,CACE,IAAK,eACH,MAAO,GACT,IAAK,OACH,MAAO,CAACC,EACV,IAAK,QACH,OAAOA,EACT,IAAK,mBACH,OAAOG,EAAY,IAAMR,EAC3B,IAAK,WAAY,CACf,IAAMU,EAAUF,EAAY,GAE5B,OAAOE,EAAUV,GAAgBU,IAAYV,GAAeO,EAAW,IAAO,EAChF,CACA,IAAK,aACH,MAAO,GACT,QACE,MAAM,IAAIhB,EAAAA,WAAW,mBAAoB,0BAA0Ba,GAAsB,CAC7F,CACF,EAAA,CAEe,EAAYG,EAAW,GAAKA,EAE3C,OAAOF,EAAW,CAACI,EAASA,CAC9B,CAEA,SAAgB,gBAAgB,EAAgB,EAA2B,CACzE,IAAMJ,EAAWM,EAAS,GACpBL,EAAWD,EAAW,CAACM,EAASA,EAChCC,EAAQ,KAAO,OAAOC,CAAS,EAC/BC,EAAQR,EAAWM,EAEzB,GAAIC,IAAc,EAAG,MAAO,GAAGR,EAAW,IAAM,KAAKS,IAErD,IAAMf,GAAYO,EAAWM,EAAA,CAAO,SAAS,CAAC,CAAC,SAASC,EAAW,GAAG,EAEtE,MAAO,GAAGR,EAAW,IAAM,KAAKS,EAAM,GAAGf,GAC3C,CAEA,SAAgB,IAAI,EAAc,EAAuB,CACvD,IAAIgB,EAAIC,EACJC,EAAIC,EAER,KAAOD,IAAM,IAAI,CAACF,EAAGE,GAAK,CAACA,EAAGF,EAAIE,CAAC,EAEnC,OAAOF,IAAM,GAAK,GAAKA,CACzB,CAEA,SAAgB,IAAI,EAAc,EAAuB,CACvD,OAAQC,EAAO,IAAIA,EAAME,CAAK,EAAKA,CACrC,C"}
package/dist/_decimal.js CHANGED
@@ -1,2 +1,64 @@
1
- import{CoinsError as e}from"./errors.js";var t=/^(-?)(\d+)(?:\.(\d+))?$/,n=1e3,r=100,i=new Set([`awayFromZero`,`ceil`,`floor`,`halfAwayFromZero`,`halfEven`,`towardZero`]);function assertRoundingMode(t){if(!i.has(t))throw new e(`INVALID_ROUNDING`,`Unknown rounding mode: ${String(t)}`)}function decimal(i){if(typeof i!=`string`)throw new e(`INVALID_DECIMAL`,`Decimal input must be a string`);if(i.length>n)throw new e(`INVALID_DECIMAL`,`Decimal input is too long`);let a=t.exec(i);if(!a)throw new e(`INVALID_DECIMAL`,`Invalid decimal: "${i}"`);let o=(a[3]??``).replace(/0+$/,``);if(o.length>r)throw new e(`INVALID_DECIMAL`,`Decimal precision cannot exceed ${r} places`);let s=10n**BigInt(o.length),c=BigInt(a[2])*s+BigInt(o||`0`),l=a[1]===`-`&&c!==0n?-c:c,u=gcd(l<0n?-l:l,s);return Object.freeze({denominator:s/u,numerator:l/u})}function roundDivision(t,n,r){if(assertRoundingMode(r),n<=0n)throw new e(`INVALID_DECIMAL`,`Decimal denominator must be positive`);let i=t<0n,a=i?-t:t,o=a/n,s=a%n;if(s===0n)return i?-o:o;let c=(()=>{switch(r){case`awayFromZero`:return!0;case`ceil`:return!i;case`floor`:return i;case`halfAwayFromZero`:return s*2n>=n;case`halfEven`:{let e=s*2n;return e>n||e===n&&o%2n!=0n}case`towardZero`:return!1;default:throw new e(`INVALID_ROUNDING`,`Unknown rounding mode: ${r}`)}})()?o+1n:o;return i?-c:c}function toDecimalString(e,t){let n=e<0n,r=n?-e:e,i=10n**BigInt(t),a=r/i;if(t===0)return`${n?`-`:``}${a}`;let o=(r%i).toString().padStart(t,`0`);return`${n?`-`:``}${a}.${o}`}function gcd(e,t){let n=e,r=t;for(;r!==0n;)[n,r]=[r,n%r];return n===0n?1n:n}function lcm(e,t){return e/gcd(e,t)*t}export{assertRoundingMode,decimal,gcd,lcm,roundDivision,toDecimalString};
1
+ import { CoinsError as e } from "./errors.js";
2
+ //#region src/_decimal.ts
3
+ var t = /^(-?)(\d+)(?:\.(\d+))?$/, n = 1e3, r = 100, i = /* @__PURE__ */ new Set([
4
+ "awayFromZero",
5
+ "ceil",
6
+ "floor",
7
+ "halfAwayFromZero",
8
+ "halfEven",
9
+ "towardZero"
10
+ ]);
11
+ function assertRoundingMode(t) {
12
+ if (!i.has(t)) throw new e("INVALID_ROUNDING", `Unknown rounding mode: ${String(t)}`);
13
+ }
14
+ function decimal(i) {
15
+ if (typeof i != "string") throw new e("INVALID_DECIMAL", "Decimal input must be a string");
16
+ if (i.length > n) throw new e("INVALID_DECIMAL", "Decimal input is too long");
17
+ let a = t.exec(i);
18
+ if (!a) throw new e("INVALID_DECIMAL", `Invalid decimal: "${i}"`);
19
+ let o = (a[3] ?? "").replace(/0+$/, "");
20
+ if (o.length > r) throw new e("INVALID_DECIMAL", `Decimal precision cannot exceed ${r} places`);
21
+ let s = 10n ** BigInt(o.length), c = BigInt(a[2]) * s + BigInt(o || "0"), l = a[1] === "-" && c !== 0n ? -c : c, u = gcd(l < 0n ? -l : l, s);
22
+ return Object.freeze({
23
+ denominator: s / u,
24
+ numerator: l / u
25
+ });
26
+ }
27
+ function roundDivision(t, n, r) {
28
+ if (assertRoundingMode(r), n <= 0n) throw new e("INVALID_DECIMAL", "Decimal denominator must be positive");
29
+ let i = t < 0n, a = i ? -t : t, o = a / n, s = a % n;
30
+ if (s === 0n) return i ? -o : o;
31
+ let c = (() => {
32
+ switch (r) {
33
+ case "awayFromZero": return !0;
34
+ case "ceil": return !i;
35
+ case "floor": return i;
36
+ case "halfAwayFromZero": return s * 2n >= n;
37
+ case "halfEven": {
38
+ let e = s * 2n;
39
+ return e > n || e === n && o % 2n != 0n;
40
+ }
41
+ case "towardZero": return !1;
42
+ default: throw new e("INVALID_ROUNDING", `Unknown rounding mode: ${r}`);
43
+ }
44
+ })() ? o + 1n : o;
45
+ return i ? -c : c;
46
+ }
47
+ function toDecimalString(e, t) {
48
+ let n = e < 0n, r = n ? -e : e, i = 10n ** BigInt(t), a = r / i;
49
+ if (t === 0) return `${n ? "-" : ""}${a}`;
50
+ let o = (r % i).toString().padStart(t, "0");
51
+ return `${n ? "-" : ""}${a}.${o}`;
52
+ }
53
+ function gcd(e, t) {
54
+ let n = e, r = t;
55
+ for (; r !== 0n;) [n, r] = [r, n % r];
56
+ return n === 0n ? 1n : n;
57
+ }
58
+ function lcm(e, t) {
59
+ return e / gcd(e, t) * t;
60
+ }
61
+ //#endregion
62
+ export { assertRoundingMode, decimal, gcd, lcm, roundDivision, toDecimalString };
63
+
2
64
  //# sourceMappingURL=_decimal.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"_decimal.js","names":[],"sources":["../src/_decimal.ts"],"sourcesContent":["import { CoinsError } from './errors';\nimport type { Decimal, RoundingMode } from './types';\n\nconst DECIMAL = /^(-?)(\\d+)(?:\\.(\\d+))?$/;\nconst MAX_DECIMAL_DIGITS = 1000;\nconst MAX_DECIMAL_PLACES = 100;\nconst ROUNDING_MODES = new Set<RoundingMode>([\n 'awayFromZero',\n 'ceil',\n 'floor',\n 'halfAwayFromZero',\n 'halfEven',\n 'towardZero',\n]);\n\nexport function assertRoundingMode(value: unknown): asserts value is RoundingMode {\n if (!ROUNDING_MODES.has(value as RoundingMode)) {\n throw new CoinsError('INVALID_ROUNDING', `Unknown rounding mode: ${String(value)}`);\n }\n}\n\nexport function decimal(value: string): Decimal {\n if (typeof value !== 'string') throw new CoinsError('INVALID_DECIMAL', 'Decimal input must be a string');\n if (value.length > MAX_DECIMAL_DIGITS) throw new CoinsError('INVALID_DECIMAL', 'Decimal input is too long');\n\n const match = DECIMAL.exec(value);\n\n if (!match) throw new CoinsError('INVALID_DECIMAL', `Invalid decimal: \"${value}\"`);\n\n const fraction = (match[3] ?? '').replace(/0+$/, '');\n\n if (fraction.length > MAX_DECIMAL_PLACES) {\n throw new CoinsError('INVALID_DECIMAL', `Decimal precision cannot exceed ${MAX_DECIMAL_PLACES} places`);\n }\n\n const denominator = 10n ** BigInt(fraction.length);\n const unsigned = BigInt(match[2]!) * denominator + BigInt(fraction || '0');\n const numerator = match[1] === '-' && unsigned !== 0n ? -unsigned : unsigned;\n const divisor = gcd(numerator < 0n ? -numerator : numerator, denominator);\n\n return Object.freeze({ denominator: denominator / divisor, numerator: numerator / divisor }) as Decimal;\n}\n\nexport function roundDivision(numerator: bigint, denominator: bigint, mode: RoundingMode): bigint {\n assertRoundingMode(mode);\n if (denominator <= 0n) throw new CoinsError('INVALID_DECIMAL', 'Decimal denominator must be positive');\n\n const negative = numerator < 0n;\n const absolute = negative ? -numerator : numerator;\n const quotient = absolute / denominator;\n const remainder = absolute % denominator;\n\n if (remainder === 0n) return negative ? -quotient : quotient;\n\n const increment = (() => {\n switch (mode) {\n case 'awayFromZero':\n return true;\n case 'ceil':\n return !negative;\n case 'floor':\n return negative;\n case 'halfAwayFromZero':\n return remainder * 2n >= denominator;\n case 'halfEven': {\n const doubled = remainder * 2n;\n\n return doubled > denominator || (doubled === denominator && quotient % 2n !== 0n);\n }\n case 'towardZero':\n return false;\n default:\n throw new CoinsError('INVALID_ROUNDING', `Unknown rounding mode: ${mode satisfies never}`);\n }\n })();\n\n const result = increment ? quotient + 1n : quotient;\n\n return negative ? -result : result;\n}\n\nexport function toDecimalString(amount: bigint, minorUnit: number): string {\n const negative = amount < 0n;\n const absolute = negative ? -amount : amount;\n const scale = 10n ** BigInt(minorUnit);\n const whole = absolute / scale;\n\n if (minorUnit === 0) return `${negative ? '-' : ''}${whole}`;\n\n const fraction = (absolute % scale).toString().padStart(minorUnit, '0');\n\n return `${negative ? '-' : ''}${whole}.${fraction}`;\n}\n\nexport function gcd(left: bigint, right: bigint): bigint {\n let a = left;\n let b = right;\n\n while (b !== 0n) [a, b] = [b, a % b];\n\n return a === 0n ? 1n : a;\n}\n\nexport function lcm(left: bigint, right: bigint): bigint {\n return (left / gcd(left, right)) * right;\n}\n"],"mappings":"yCAGA,IAAM,EAAU,0BACV,EAAqB,IACrB,EAAqB,IACrB,EAAiB,IAAI,IAAkB,CAC3C,eACA,OACA,QACA,mBACA,WACA,YACF,CAAC,EAED,SAAgB,mBAAmB,EAA+C,CAChF,GAAI,CAAC,EAA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AAU,EAAY,GAE5B,OAAO,EAAU,GAAgB,IAAY,GAAe,EAAW,IAAO,EAChF,CACA,IAAK,aACH,MAAO,GACT,QACE,MAAM,IAAI,EAAW,mBAAoB,0BAA0B,GAAsB,CAC7F,CACF,EAAA,CAEe,EAAY,EAAW,GAAK,EAE3C,OAAO,EAAW,CAAC,EAAS,CAC9B,CAEA,SAAgB,gBAAgB,EAAgB,EAA2B,CACzE,IAAM,EAAW,EAAS,GACpB,EAAW,EAAW,CAAC,EAAS,EAChC,EAAQ,KAAO,OAAO,CAAS,EAC/B,EAAQ,EAAW,EAEzB,GAAI,IAAc,EAAG,MAAO,GAAG,EAAW,IAAM,KAAK,IAErD,IAAM,GAAY,EAAW,EAAA,CAAO,SAAS,CAAC,CAAC,SAAS,EAAW,GAAG,EAEtE,MAAO,GAAG,EAAW,IAAM,KAAK,EAAM,GAAG,GAC3C,CAEA,SAAgB,IAAI,EAAc,EAAuB,CACvD,IAAI,EAAI,EACJ,EAAI,EAER,KAAO,IAAM,IAAI,CAAC,EAAG,GAAK,CAAC,EAAG,EAAI,CAAC,EAEnC,OAAO,IAAM,GAAK,GAAK,CACzB,CAEA,SAAgB,IAAI,EAAc,EAAuB,CACvD,OAAQ,EAAO,IAAI,EAAM,CAAK,EAAK,CACrC"}
1
+ {"version":3,"file":"_decimal.js","names":["DECIMAL","MAX_DECIMAL_DIGITS","MAX_DECIMAL_PLACES","ROUNDING_MODES","value","CoinsError","match","fraction","denominator","unsigned","numerator","divisor","mode","negative","absolute","quotient","remainder","result","doubled","amount","scale","minorUnit","whole","a","left","b","right"],"sources":["../src/_decimal.ts"],"sourcesContent":["import { CoinsError } from './errors';\nimport type { Decimal, RoundingMode } from './types';\n\nconst DECIMAL = /^(-?)(\\d+)(?:\\.(\\d+))?$/;\nconst MAX_DECIMAL_DIGITS = 1000;\nconst MAX_DECIMAL_PLACES = 100;\nconst ROUNDING_MODES = new Set<RoundingMode>([\n 'awayFromZero',\n 'ceil',\n 'floor',\n 'halfAwayFromZero',\n 'halfEven',\n 'towardZero',\n]);\n\nexport function assertRoundingMode(value: unknown): asserts value is RoundingMode {\n if (!ROUNDING_MODES.has(value as RoundingMode)) {\n throw new CoinsError('INVALID_ROUNDING', `Unknown rounding mode: ${String(value)}`);\n }\n}\n\nexport function decimal(value: string): Decimal {\n if (typeof value !== 'string') throw new CoinsError('INVALID_DECIMAL', 'Decimal input must be a string');\n if (value.length > MAX_DECIMAL_DIGITS) throw new CoinsError('INVALID_DECIMAL', 'Decimal input is too long');\n\n const match = DECIMAL.exec(value);\n\n if (!match) throw new CoinsError('INVALID_DECIMAL', `Invalid decimal: \"${value}\"`);\n\n const fraction = (match[3] ?? '').replace(/0+$/, '');\n\n if (fraction.length > MAX_DECIMAL_PLACES) {\n throw new CoinsError('INVALID_DECIMAL', `Decimal precision cannot exceed ${MAX_DECIMAL_PLACES} places`);\n }\n\n const denominator = 10n ** BigInt(fraction.length);\n const unsigned = BigInt(match[2]!) * denominator + BigInt(fraction || '0');\n const numerator = match[1] === '-' && unsigned !== 0n ? -unsigned : unsigned;\n const divisor = gcd(numerator < 0n ? -numerator : numerator, denominator);\n\n return Object.freeze({ denominator: denominator / divisor, numerator: numerator / divisor }) as Decimal;\n}\n\nexport function roundDivision(numerator: bigint, denominator: bigint, mode: RoundingMode): bigint {\n assertRoundingMode(mode);\n if (denominator <= 0n) throw new CoinsError('INVALID_DECIMAL', 'Decimal denominator must be positive');\n\n const negative = numerator < 0n;\n const absolute = negative ? -numerator : numerator;\n const quotient = absolute / denominator;\n const remainder = absolute % denominator;\n\n if (remainder === 0n) return negative ? -quotient : quotient;\n\n const increment = (() => {\n switch (mode) {\n case 'awayFromZero':\n return true;\n case 'ceil':\n return !negative;\n case 'floor':\n return negative;\n case 'halfAwayFromZero':\n return remainder * 2n >= denominator;\n case 'halfEven': {\n const doubled = remainder * 2n;\n\n return doubled > denominator || (doubled === denominator && quotient % 2n !== 0n);\n }\n case 'towardZero':\n return false;\n default:\n throw new CoinsError('INVALID_ROUNDING', `Unknown rounding mode: ${mode satisfies never}`);\n }\n })();\n\n const result = increment ? quotient + 1n : quotient;\n\n return negative ? -result : result;\n}\n\nexport function toDecimalString(amount: bigint, minorUnit: number): string {\n const negative = amount < 0n;\n const absolute = negative ? -amount : amount;\n const scale = 10n ** BigInt(minorUnit);\n const whole = absolute / scale;\n\n if (minorUnit === 0) return `${negative ? '-' : ''}${whole}`;\n\n const fraction = (absolute % scale).toString().padStart(minorUnit, '0');\n\n return `${negative ? '-' : ''}${whole}.${fraction}`;\n}\n\nexport function gcd(left: bigint, right: bigint): bigint {\n let a = left;\n let b = right;\n\n while (b !== 0n) [a, b] = [b, a % b];\n\n return a === 0n ? 1n : a;\n}\n\nexport function lcm(left: bigint, right: bigint): bigint {\n return (left / gcd(left, right)) * right;\n}\n"],"mappings":";;AAGA,IAAMA,IAAU,2BACVC,IAAqB,KACrBC,IAAqB,KACrBC,oBAAiB,IAAI,IAAkB;CAC3C;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAgB,mBAAmB,GAA+C;CAChF,IAAI,CAACA,EAAe,IAAIC,CAAqB,GAC3C,MAAM,IAAIC,EAAW,oBAAoB,0BAA0B,OAAOD,CAAK,GAAG;AAEtF;AAEA,SAAgB,QAAQ,GAAwB;CAC9C,IAAI,OAAOA,KAAU,UAAU,MAAM,IAAIC,EAAW,mBAAmB,gCAAgC;CACvG,IAAID,EAAM,SAASH,GAAoB,MAAM,IAAII,EAAW,mBAAmB,2BAA2B;CAE1G,IAAMC,IAAQN,EAAQ,KAAKI,CAAK;CAEhC,IAAI,CAACE,GAAO,MAAM,IAAID,EAAW,mBAAmB,qBAAqBD,EAAM,EAAE;CAEjF,IAAMG,KAAYD,EAAM,MAAM,GAAA,CAAI,QAAQ,OAAO,EAAE;CAEnD,IAAIC,EAAS,SAASL,GACpB,MAAM,IAAIG,EAAW,mBAAmB,mCAAmCH,EAAmB,QAAQ;CAGxG,IAAMM,IAAc,OAAO,OAAOD,EA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AAO,SAAS,CAAC,CAAC,SAASC,GAAW,GAAG;CAEtE,OAAO,GAAGR,IAAW,MAAM,KAAKS,EAAM,GAAGf;AAC3C;AAEA,SAAgB,IAAI,GAAc,GAAuB;CACvD,IAAIgB,IAAIC,GACJC,IAAIC;CAER,OAAOD,MAAM,KAAI,CAACF,GAAGE,KAAK,CAACA,GAAGF,IAAIE,CAAC;CAEnC,OAAOF,MAAM,KAAK,KAAKA;AACzB;AAEA,SAAgB,IAAI,GAAc,GAAuB;CACvD,OAAQC,IAAO,IAAIA,GAAME,CAAK,IAAKA;AACrC"}
@@ -1 +1 @@
1
- {"version":3,"file":"aggregate.cjs","names":[],"sources":["../src/aggregate.ts"],"sourcesContent":["import { decimal, lcm } from './_decimal';\nimport { isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { assertMoney, createMoney } from './money';\nimport type { Currency, Money } from './types';\n\nconst MAX_ALLOCATION_PARTS = 100_000;\n\nexport function sum<C extends Currency>(values: readonly Money<C>[]): Money<C>;\nexport function sum<C extends Currency>(values: Iterable<Money<C>>, options: { currency: C }): Money<C>;\nexport function sum<C extends Currency>(values: Iterable<Money<C>>, options?: { currency: C }): Money<C> {\n if (options && !isCurrency(options.currency)) {\n throw new CoinsError('INVALID_CURRENCY', 'sum() requires a canonical currency');\n }\n\n let amount = 0n;\n let currency: C | undefined = options?.currency;\n\n for (const value of values) {\n assertMoney(value);\n\n if (currency === undefined) {\n currency = value.currency;\n } else if (value.currency !== currency) {\n throw new CurrencyMismatchError(currency.code, value.currency.code);\n }\n\n amount += value.amount;\n }\n\n if (currency === undefined) throw new CoinsError('INVALID_MONEY', 'sum() of empty iterable requires { currency }');\n\n return createMoney(amount, currency);\n}\n\nexport function allocate<C extends Currency>(value: Money<C>, count: number): Money<C>[];\nexport function allocate<C extends Currency>(value: Money<C>, weights: readonly string[]): Money<C>[];\nexport function allocate<C extends Currency>(value: Money<C>, weightsOrCount: number | readonly string[]): Money<C>[] {\n assertMoney(value);\n\n if (typeof weightsOrCount === 'number') return allocateEvenly(value, weightsOrCount);\n\n if (!Array.isArray(weightsOrCount)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights must be an array');\n }\n if (weightsOrCount.length === 0) throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot be empty');\n if (weightsOrCount.length > MAX_ALLOCATION_PARTS) {\n throw new CoinsError('INVALID_ALLOCATION', `Allocation cannot exceed ${MAX_ALLOCATION_PARTS} parts`);\n }\n for (let index = 0; index < weightsOrCount.length; index++) {\n if (!Object.hasOwn(weightsOrCount, index)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot contain empty slots');\n }\n }\n\n const weights = weightsOrCount.map(decimal);\n\n if (weights.some((weight) => weight.numerator < 0n)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot be negative');\n }\n\n const commonDenominator = weights.reduce((result, weight) => lcm(result, weight.denominator), 1n);\n const scaledWeights = weights.map((weight) => weight.numerator * (commonDenominator / weight.denominator));\n const totalWeight = scaledWeights.reduce((result, weight) => result + weight, 0n);\n\n if (totalWeight === 0n)\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights must include a positive value');\n\n const sign = value.amount < 0n ? -1n : 1n;\n const absolute = value.amount < 0n ? -value.amount : value.amount;\n const shares = scaledWeights.map((weight) => (absolute * weight) / totalWeight);\n let remainder = absolute - shares.reduce((result, amount) => result + amount, 0n);\n const ranked = scaledWeights\n .map((weight, index) => ({ index, remainder: (absolute * weight) % totalWeight }))\n .sort((left, right) =>\n left.remainder === right.remainder ? left.index - right.index : left.remainder > right.remainder ? -1 : 1,\n );\n\n for (const entry of ranked) {\n if (remainder === 0n) break;\n\n shares[entry.index]! += 1n;\n remainder -= 1n;\n }\n\n return shares.map((amount) => createMoney(amount * sign, value.currency));\n}\n\nfunction allocateEvenly<C extends Currency>(value: Money<C>, countValue: number): Money<C>[] {\n if (!Number.isSafeInteger(countValue) || countValue < 1 || countValue > MAX_ALLOCATION_PARTS) {\n throw new CoinsError(\n 'INVALID_ALLOCATION',\n `Allocation count must be a positive safe integer no greater than ${MAX_ALLOCATION_PARTS}`,\n );\n }\n\n const count = BigInt(countValue);\n const sign = value.amount < 0n ? -1n : 1n;\n const absolute = value.amount < 0n ? -value.amount : value.amount;\n const base = absolute / count;\n const remainder = absolute % count;\n\n return Array.from({ length: countValue }, (_, index) =>\n createMoney((base + (BigInt(index) < remainder ? 1n : 0n)) * sign, value.currency),\n );\n}\n"],"mappings":"iHAMA,IAAM,EAAuB,IAI7B,SAAgB,IAAwB,EAA4B,EAAqC,CACvG,GAAI,GAAW,CAAC,EAAA,WAAW,EAAQ,QAAQ,EACzC,MAAM,IAAI,EAAA,WAAW,mBAAoB,qCAAqC,EAGhF,IAAI,EAAS,GACT,EAA0B,GAAS,SAEvC,IAAK,IAAM,KAAS,EAAQ,CAG1B,GAFA,EAAA,YAAY,CAAK,EAEb,IAAa,IAAA,GACf,EAAW,EAAM,cACZ,GAAI,EAAM,WAAa,EAC5B,MAAM,IAAI,EAAA,sBAAsB,EAAS,KAAM,EAAM,SAAS,IAAI,EAGpE,GAAU,EAAM,MAClB,CAEA,GAAI,IAAa,IAAA,GAAW,MAAM,IAAI,EAAA,WAAW,gBAAiB,+CAA+C,EAEjH,OAAO,EAAA,YAAY,EAAQ,CAAQ,CACrC,CAIA,SAAgB,SAA6B,EAAiB,EAAwD,CAGpH,GAFA,EAAA,YAAY,CAAK,EAEb,OAAO,GAAmB,SAAU,OAAO,eAAe,EAAO,CAAc,EAEnF,GAAI,CAAC,MAAM,QAAQ,CAAc,EAC/B,MAAM,IAAI,EAAA,WAAW,qBAAsB,qCAAqC,EAElF,GAAI,EAAe,SAAW,EAAG,MAAM,IAAI,EAAA,WAAW,qBAAsB,oCAAoC,EAChH,GAAI,EAAe,OAAS,EAC1B,MAAM,IAAI,EAAA,WAAW,qBAAsB,4BAA4B,EAAqB,OAAO,EAErG,IAAK,IAAI,EAAQ,EAAG,EAAQ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,EAAA,WACR,qBACA,oEAAoE,GACtE,EAGF,IAAM,EAAQ,OAAO,CAAU,EACzB,EAAO,EAAM,OAAS,GAAK,CAAC,GAAK,GACjC,EAAW,EAAM,OAAS,GAAK,CAAC,EAAM,OAAS,EAAM,OACrD,EAAO,EAAW,EAClB,EAAY,EAAW,EAE7B,OAAO,MAAM,KAAK,CAAE,OAAQ,CAAW,GAAI,EAAG,IAC5C,EAAA,aAAa,GAAQ,OAAO,CAAK,EAAI,EAAY,GAAK,KAAO,EAAM,EAAM,QAAQ,CACnF,CACF"}
1
+ {"version":3,"file":"aggregate.cjs","names":["isCurrency","CoinsError","CurrencyMismatchError","createMoney","decimal","lcm","require_errors","require__decimal","require_currency","require_money","MAX_ALLOCATION_PARTS","options","amount","currency","value","values","weightsOrCount","index","weights","weight","commonDenominator","result","scaledWeights","totalWeight","sign","absolute","shares","remainder","ranked","left","right","entry","countValue","count","base"],"sources":["../src/aggregate.ts"],"sourcesContent":["import { decimal, lcm } from './_decimal';\nimport { isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { assertMoney, createMoney } from './money';\nimport type { Currency, Money } from './types';\n\nconst MAX_ALLOCATION_PARTS = 100_000;\n\nexport function sum<C extends Currency>(values: readonly Money<C>[]): Money<C>;\nexport function sum<C extends Currency>(values: Iterable<Money<C>>, options: { currency: C }): Money<C>;\nexport function sum<C extends Currency>(values: Iterable<Money<C>>, options?: { currency: C }): Money<C> {\n if (options && !isCurrency(options.currency)) {\n throw new CoinsError('INVALID_CURRENCY', 'sum() requires a canonical currency');\n }\n\n let amount = 0n;\n let currency: C | undefined = options?.currency;\n\n for (const value of values) {\n assertMoney(value);\n\n if (currency === undefined) {\n currency = value.currency;\n } else if (value.currency !== currency) {\n throw new CurrencyMismatchError(currency.code, value.currency.code);\n }\n\n amount += value.amount;\n }\n\n if (currency === undefined) throw new CoinsError('INVALID_MONEY', 'sum() of empty iterable requires { currency }');\n\n return createMoney(amount, currency);\n}\n\nexport function allocate<C extends Currency>(value: Money<C>, count: number): Money<C>[];\nexport function allocate<C extends Currency>(value: Money<C>, weights: readonly string[]): Money<C>[];\nexport function allocate<C extends Currency>(value: Money<C>, weightsOrCount: number | readonly string[]): Money<C>[] {\n assertMoney(value);\n\n if (typeof weightsOrCount === 'number') return allocateEvenly(value, weightsOrCount);\n\n if (!Array.isArray(weightsOrCount)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights must be an array');\n }\n if (weightsOrCount.length === 0) throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot be empty');\n if (weightsOrCount.length > MAX_ALLOCATION_PARTS) {\n throw new CoinsError('INVALID_ALLOCATION', `Allocation cannot exceed ${MAX_ALLOCATION_PARTS} parts`);\n }\n for (let index = 0; index < weightsOrCount.length; index++) {\n if (!Object.hasOwn(weightsOrCount, index)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot contain empty slots');\n }\n }\n\n const weights = weightsOrCount.map(decimal);\n\n if (weights.some((weight) => weight.numerator < 0n)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot be negative');\n }\n\n const commonDenominator = weights.reduce((result, weight) => lcm(result, weight.denominator), 1n);\n const scaledWeights = weights.map((weight) => weight.numerator * (commonDenominator / weight.denominator));\n const totalWeight = scaledWeights.reduce((result, weight) => result + weight, 0n);\n\n if (totalWeight === 0n)\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights must include a positive value');\n\n const sign = value.amount < 0n ? -1n : 1n;\n const absolute = value.amount < 0n ? -value.amount : value.amount;\n const shares = scaledWeights.map((weight) => (absolute * weight) / totalWeight);\n let remainder = absolute - shares.reduce((result, amount) => result + amount, 0n);\n const ranked = scaledWeights\n .map((weight, index) => ({ index, remainder: (absolute * weight) % totalWeight }))\n .sort((left, right) =>\n left.remainder === right.remainder ? left.index - right.index : left.remainder > right.remainder ? -1 : 1,\n );\n\n for (const entry of ranked) {\n if (remainder === 0n) break;\n\n shares[entry.index]! += 1n;\n remainder -= 1n;\n }\n\n return shares.map((amount) => createMoney(amount * sign, value.currency));\n}\n\nfunction allocateEvenly<C extends Currency>(value: Money<C>, countValue: number): Money<C>[] {\n if (!Number.isSafeInteger(countValue) || countValue < 1 || countValue > MAX_ALLOCATION_PARTS) {\n throw new CoinsError(\n 'INVALID_ALLOCATION',\n `Allocation count must be a positive safe integer no greater than ${MAX_ALLOCATION_PARTS}`,\n );\n }\n\n const count = BigInt(countValue);\n const sign = value.amount < 0n ? -1n : 1n;\n const absolute = value.amount < 0n ? -value.amount : value.amount;\n const base = absolute / count;\n const remainder = absolute % count;\n\n return Array.from({ length: countValue }, (_, index) =>\n createMoney((base + (BigInt(index) < remainder ? 1n : 0n)) * sign, value.currency),\n );\n}\n"],"mappings":"A,iHAMA,IAAMU,EAAuB,IAI7B,SAAgB,IAAwB,EAA4B,EAAqC,CACvG,GAAIC,GAAW,CAACX,EAAAA,WAAWW,EAAQ,QAAQ,EACzC,MAAM,IAAIV,EAAAA,WAAW,mBAAoB,qCAAqC,EAGhF,IAAIW,EAAS,GACTC,EAA0BF,GAAS,SAEvC,IAAK,IAAMG,KAASC,EAAQ,CAG1B,GAFAN,EAAA,YAAYK,CAAK,EAEbD,IAAa,IAAA,GACf,EAAWC,EAAM,cACZ,GAAIA,EAAM,WAAaD,EAC5B,MAAM,IAAIX,EAAAA,sBAAsBW,EAAS,KAAMC,EAAM,SAAS,IAAI,EAGpE,GAAUA,EAAM,MAClB,CAEA,GAAID,IAAa,IAAA,GAAW,MAAM,IAAIZ,EAAAA,WAAW,gBAAiB,+CAA+C,EAEjH,OAAOE,EAAAA,YAAYS,EAAQC,CAAQ,CACrC,CAIA,SAAgB,SAA6B,EAAiB,EAAwD,CAGpH,GAFAJ,EAAA,YAAYK,CAAK,EAEb,OAAOE,GAAmB,SAAU,OAAO,eAAeF,EAAOE,CAAc,EAEnF,GAAI,CAAC,MAAM,QAAQA,CAAc,EAC/B,MAAM,IAAIf,EAAAA,WAAW,qBAAsB,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K,IAAMC,KAASH,EAAQ,CAC1B,GAAID,IAAc,GAAI,MAEtB,EAAOI,EAAM,QAAW,GACxB,GAAa,EACf,CAEA,OAAOL,EAAO,IAAK,GAAWvB,EAAAA,YAAYS,EAASY,EAAMV,EAAM,QAAQ,CAAC,CAC1E,CAEA,SAAS,eAAmC,EAAiB,EAAgC,CAC3F,GAAI,CAAC,OAAO,cAAckB,CAAU,GAAKA,EAAa,GAAKA,EAAatB,EACtE,MAAM,IAAIT,EAAAA,WACR,qBACA,oEAAoES,GACtE,EAGF,IAAMuB,EAAQ,OAAOD,CAAU,EACzBR,EAAOV,EAAM,OAAS,GAAK,CAAC,GAAK,GACjCW,EAAWX,EAAM,OAAS,GAAK,CAACA,EAAM,OAASA,EAAM,OACrDoB,EAAOT,EAAWQ,EAClBN,EAAYF,EAAWQ,EAE7B,OAAO,MAAM,KAAK,CAAE,OAAQD,CAAW,GAAI,EAAG,IAC5C7B,EAAAA,aAAa+B,GAAQ,OAAOjB,CAAK,EAAIU,EAAY,GAAK,KAAOH,EAAMV,EAAM,QAAQ,CACnF,CACF,C"}
package/dist/aggregate.js CHANGED
@@ -1,2 +1,46 @@
1
- import{CoinsError as e,CurrencyMismatchError as t}from"./errors.js";import{decimal as n,lcm as r}from"./_decimal.js";import{isCurrency as i}from"./currency.js";import{assertMoney as a,createMoney as o}from"./money.js";var s=1e5;function sum(n,r){if(r&&!i(r.currency))throw new e(`INVALID_CURRENCY`,`sum() requires a canonical currency`);let s=0n,c=r?.currency;for(let e of n){if(a(e),c===void 0)c=e.currency;else if(e.currency!==c)throw new t(c.code,e.currency.code);s+=e.amount}if(c===void 0)throw new e(`INVALID_MONEY`,`sum() of empty iterable requires { currency }`);return o(s,c)}function allocate(t,i){if(a(t),typeof i==`number`)return allocateEvenly(t,i);if(!Array.isArray(i))throw new e(`INVALID_ALLOCATION`,`Allocation weights must be an array`);if(i.length===0)throw new e(`INVALID_ALLOCATION`,`Allocation weights cannot be empty`);if(i.length>s)throw new e(`INVALID_ALLOCATION`,`Allocation cannot exceed ${s} parts`);for(let t=0;t<i.length;t++)if(!Object.hasOwn(i,t))throw new e(`INVALID_ALLOCATION`,`Allocation weights cannot contain empty slots`);let c=i.map(n);if(c.some(e=>e.numerator<0n))throw new e(`INVALID_ALLOCATION`,`Allocation weights cannot be negative`);let l=c.reduce((e,t)=>r(e,t.denominator),1n),u=c.map(e=>e.numerator*(l/e.denominator)),d=u.reduce((e,t)=>e+t,0n);if(d===0n)throw new e(`INVALID_ALLOCATION`,`Allocation weights must include a positive value`);let f=t.amount<0n?-1n:1n,p=t.amount<0n?-t.amount:t.amount,m=u.map(e=>p*e/d),h=p-m.reduce((e,t)=>e+t,0n),g=u.map((e,t)=>({index:t,remainder:p*e%d})).sort((e,t)=>e.remainder===t.remainder?e.index-t.index:e.remainder>t.remainder?-1:1);for(let e of g){if(h===0n)break;m[e.index]+=1n,h-=1n}return m.map(e=>o(e*f,t.currency))}function allocateEvenly(t,n){if(!Number.isSafeInteger(n)||n<1||n>s)throw new e(`INVALID_ALLOCATION`,`Allocation count must be a positive safe integer no greater than ${s}`);let r=BigInt(n),i=t.amount<0n?-1n:1n,a=t.amount<0n?-t.amount:t.amount,c=a/r,l=a%r;return Array.from({length:n},(e,n)=>o((c+(BigInt(n)<l?1n:0n))*i,t.currency))}export{allocate,sum};
1
+ import { CoinsError as e, CurrencyMismatchError as t } from "./errors.js";
2
+ import { decimal as n, lcm 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/aggregate.ts
6
+ var s = 1e5;
7
+ function sum(n, r) {
8
+ if (r && !i(r.currency)) throw new e("INVALID_CURRENCY", "sum() requires a canonical currency");
9
+ let s = 0n, c = r?.currency;
10
+ for (let e of n) {
11
+ if (a(e), c === void 0) c = e.currency;
12
+ else if (e.currency !== c) throw new t(c.code, e.currency.code);
13
+ s += e.amount;
14
+ }
15
+ if (c === void 0) throw new e("INVALID_MONEY", "sum() of empty iterable requires { currency }");
16
+ return o(s, c);
17
+ }
18
+ function allocate(t, i) {
19
+ if (a(t), typeof i == "number") return allocateEvenly(t, i);
20
+ if (!Array.isArray(i)) throw new e("INVALID_ALLOCATION", "Allocation weights must be an array");
21
+ if (i.length === 0) throw new e("INVALID_ALLOCATION", "Allocation weights cannot be empty");
22
+ if (i.length > s) throw new e("INVALID_ALLOCATION", `Allocation cannot exceed ${s} parts`);
23
+ for (let t = 0; t < i.length; t++) if (!Object.hasOwn(i, t)) throw new e("INVALID_ALLOCATION", "Allocation weights cannot contain empty slots");
24
+ let c = i.map(n);
25
+ if (c.some((e) => e.numerator < 0n)) throw new e("INVALID_ALLOCATION", "Allocation weights cannot be negative");
26
+ let l = c.reduce((e, t) => r(e, t.denominator), 1n), u = c.map((e) => e.numerator * (l / e.denominator)), d = u.reduce((e, t) => e + t, 0n);
27
+ if (d === 0n) throw new e("INVALID_ALLOCATION", "Allocation weights must include a positive value");
28
+ let f = t.amount < 0n ? -1n : 1n, p = t.amount < 0n ? -t.amount : t.amount, m = u.map((e) => p * e / d), h = p - m.reduce((e, t) => e + t, 0n), g = u.map((e, t) => ({
29
+ index: t,
30
+ remainder: p * e % d
31
+ })).sort((e, t) => e.remainder === t.remainder ? e.index - t.index : e.remainder > t.remainder ? -1 : 1);
32
+ for (let e of g) {
33
+ if (h === 0n) break;
34
+ m[e.index] += 1n, h -= 1n;
35
+ }
36
+ return m.map((e) => o(e * f, t.currency));
37
+ }
38
+ function allocateEvenly(t, n) {
39
+ if (!Number.isSafeInteger(n) || n < 1 || n > s) throw new e("INVALID_ALLOCATION", `Allocation count must be a positive safe integer no greater than ${s}`);
40
+ let r = BigInt(n), i = t.amount < 0n ? -1n : 1n, a = t.amount < 0n ? -t.amount : t.amount, c = a / r, l = a % r;
41
+ return Array.from({ length: n }, (e, n) => o((c + (BigInt(n) < l ? 1n : 0n)) * i, t.currency));
42
+ }
43
+ //#endregion
44
+ export { allocate, sum };
45
+
2
46
  //# sourceMappingURL=aggregate.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"aggregate.js","names":[],"sources":["../src/aggregate.ts"],"sourcesContent":["import { decimal, lcm } from './_decimal';\nimport { isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { assertMoney, createMoney } from './money';\nimport type { Currency, Money } from './types';\n\nconst MAX_ALLOCATION_PARTS = 100_000;\n\nexport function sum<C extends Currency>(values: readonly Money<C>[]): Money<C>;\nexport function sum<C extends Currency>(values: Iterable<Money<C>>, options: { currency: C }): Money<C>;\nexport function sum<C extends Currency>(values: Iterable<Money<C>>, options?: { currency: C }): Money<C> {\n if (options && !isCurrency(options.currency)) {\n throw new CoinsError('INVALID_CURRENCY', 'sum() requires a canonical currency');\n }\n\n let amount = 0n;\n let currency: C | undefined = options?.currency;\n\n for (const value of values) {\n assertMoney(value);\n\n if (currency === undefined) {\n currency = value.currency;\n } else if (value.currency !== currency) {\n throw new CurrencyMismatchError(currency.code, value.currency.code);\n }\n\n amount += value.amount;\n }\n\n if (currency === undefined) throw new CoinsError('INVALID_MONEY', 'sum() of empty iterable requires { currency }');\n\n return createMoney(amount, currency);\n}\n\nexport function allocate<C extends Currency>(value: Money<C>, count: number): Money<C>[];\nexport function allocate<C extends Currency>(value: Money<C>, weights: readonly string[]): Money<C>[];\nexport function allocate<C extends Currency>(value: Money<C>, weightsOrCount: number | readonly string[]): Money<C>[] {\n assertMoney(value);\n\n if (typeof weightsOrCount === 'number') return allocateEvenly(value, weightsOrCount);\n\n if (!Array.isArray(weightsOrCount)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights must be an array');\n }\n if (weightsOrCount.length === 0) throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot be empty');\n if (weightsOrCount.length > MAX_ALLOCATION_PARTS) {\n throw new CoinsError('INVALID_ALLOCATION', `Allocation cannot exceed ${MAX_ALLOCATION_PARTS} parts`);\n }\n for (let index = 0; index < weightsOrCount.length; index++) {\n if (!Object.hasOwn(weightsOrCount, index)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot contain empty slots');\n }\n }\n\n const weights = weightsOrCount.map(decimal);\n\n if (weights.some((weight) => weight.numerator < 0n)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot be negative');\n }\n\n const commonDenominator = weights.reduce((result, weight) => lcm(result, weight.denominator), 1n);\n const scaledWeights = weights.map((weight) => weight.numerator * (commonDenominator / weight.denominator));\n const totalWeight = scaledWeights.reduce((result, weight) => result + weight, 0n);\n\n if (totalWeight === 0n)\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights must include a positive value');\n\n const sign = value.amount < 0n ? -1n : 1n;\n const absolute = value.amount < 0n ? -value.amount : value.amount;\n const shares = scaledWeights.map((weight) => (absolute * weight) / totalWeight);\n let remainder = absolute - shares.reduce((result, amount) => result + amount, 0n);\n const ranked = scaledWeights\n .map((weight, index) => ({ index, remainder: (absolute * weight) % totalWeight }))\n .sort((left, right) =>\n left.remainder === right.remainder ? left.index - right.index : left.remainder > right.remainder ? -1 : 1,\n );\n\n for (const entry of ranked) {\n if (remainder === 0n) break;\n\n shares[entry.index]! += 1n;\n remainder -= 1n;\n }\n\n return shares.map((amount) => createMoney(amount * sign, value.currency));\n}\n\nfunction allocateEvenly<C extends Currency>(value: Money<C>, countValue: number): Money<C>[] {\n if (!Number.isSafeInteger(countValue) || countValue < 1 || countValue > MAX_ALLOCATION_PARTS) {\n throw new CoinsError(\n 'INVALID_ALLOCATION',\n `Allocation count must be a positive safe integer no greater than ${MAX_ALLOCATION_PARTS}`,\n );\n }\n\n const count = BigInt(countValue);\n const sign = value.amount < 0n ? -1n : 1n;\n const absolute = value.amount < 0n ? -value.amount : value.amount;\n const base = absolute / count;\n const remainder = absolute % count;\n\n return Array.from({ length: countValue }, (_, index) =>\n createMoney((base + (BigInt(index) < remainder ? 1n : 0n)) * sign, value.currency),\n );\n}\n"],"mappings":"0NAMA,IAAM,EAAuB,IAI7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EAAQ,IAAW,EAAS,EAAQ,EAAE,EAEhF,GAAI,IAAgB,GAClB,MAAM,IAAI,EAAW,qBAAsB,kDAAkD,EAE/F,IAAM,EAAO,EAAM,OAAS,GAAK,CAAC,GAAK,GACjC,EAAW,EAAM,OAAS,GAAK,CAAC,EAAM,OAAS,EAAM,OACrD,EAAS,EAAc,IAAK,GAAY,EAAW,EAAU,CAAW,EAC1E,EAAY,EAAW,EAAO,QAAQ,EAAQ,IAAW,EAAS,EAAQ,EAAE,EAC1E,EAAS,EACZ,KAAK,EAAQ,KAAW,CAAE,QAAO,UAAY,EAAW,EAAU,CAAY,EAAE,CAAC,CACjF,MAAM,EAAM,IACX,EAAK,YAAc,EAAM,UAAY,EAAK,MAAQ,EAAM,MAAQ,EAAK,UAAY,EAAM,UAAY,GAAK,CAC1G,EAEF,IAAK,IAAM,KAAS,EAAQ,CAC1B,GAAI,IAAc,GAAI,MAEtB,EAAO,EAAM,QAAW,GACxB,GAAa,EACf,CAEA,OAAO,EAAO,IAAK,GAAW,EAAY,EAAS,EAAM,EAAM,QAAQ,CAAC,CAC1E,CAEA,SAAS,eAAmC,EAAiB,EAAgC,CAC3F,GAAI,CAAC,OAAO,cAAc,CAAU,GAAK,EAAa,GAAK,EAAa,EACtE,MAAM,IAAI,EACR,qBACA,oEAAoE,GACtE,EAGF,IAAM,EAAQ,OAAO,CAAU,EACzB,EAAO,EAAM,OAAS,GAAK,CAAC,GAAK,GACjC,EAAW,EAAM,OAAS,GAAK,CAAC,EAAM,OAAS,EAAM,OACrD,EAAO,EAAW,EAClB,EAAY,EAAW,EAE7B,OAAO,MAAM,KAAK,CAAE,OAAQ,CAAW,GAAI,EAAG,IAC5C,GAAa,GAAQ,OAAO,CAAK,EAAI,EAAY,GAAK,KAAO,EAAM,EAAM,QAAQ,CACnF,CACF"}
1
+ {"version":3,"file":"aggregate.js","names":["MAX_ALLOCATION_PARTS","options","isCurrency","CoinsError","amount","currency","value","values","assertMoney","CurrencyMismatchError","createMoney","weightsOrCount","index","weights","decimal","weight","commonDenominator","lcm","result","scaledWeights","totalWeight","sign","absolute","shares","remainder","ranked","left","right","entry","countValue","count","base"],"sources":["../src/aggregate.ts"],"sourcesContent":["import { decimal, lcm } from './_decimal';\nimport { isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { assertMoney, createMoney } from './money';\nimport type { Currency, Money } from './types';\n\nconst MAX_ALLOCATION_PARTS = 100_000;\n\nexport function sum<C extends Currency>(values: readonly Money<C>[]): Money<C>;\nexport function sum<C extends Currency>(values: Iterable<Money<C>>, options: { currency: C }): Money<C>;\nexport function sum<C extends Currency>(values: Iterable<Money<C>>, options?: { currency: C }): Money<C> {\n if (options && !isCurrency(options.currency)) {\n throw new CoinsError('INVALID_CURRENCY', 'sum() requires a canonical currency');\n }\n\n let amount = 0n;\n let currency: C | undefined = options?.currency;\n\n for (const value of values) {\n assertMoney(value);\n\n if (currency === undefined) {\n currency = value.currency;\n } else if (value.currency !== currency) {\n throw new CurrencyMismatchError(currency.code, value.currency.code);\n }\n\n amount += value.amount;\n }\n\n if (currency === undefined) throw new CoinsError('INVALID_MONEY', 'sum() of empty iterable requires { currency }');\n\n return createMoney(amount, currency);\n}\n\nexport function allocate<C extends Currency>(value: Money<C>, count: number): Money<C>[];\nexport function allocate<C extends Currency>(value: Money<C>, weights: readonly string[]): Money<C>[];\nexport function allocate<C extends Currency>(value: Money<C>, weightsOrCount: number | readonly string[]): Money<C>[] {\n assertMoney(value);\n\n if (typeof weightsOrCount === 'number') return allocateEvenly(value, weightsOrCount);\n\n if (!Array.isArray(weightsOrCount)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights must be an array');\n }\n if (weightsOrCount.length === 0) throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot be empty');\n if (weightsOrCount.length > MAX_ALLOCATION_PARTS) {\n throw new CoinsError('INVALID_ALLOCATION', `Allocation cannot exceed ${MAX_ALLOCATION_PARTS} parts`);\n }\n for (let index = 0; index < weightsOrCount.length; index++) {\n if (!Object.hasOwn(weightsOrCount, index)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot contain empty slots');\n }\n }\n\n const weights = weightsOrCount.map(decimal);\n\n if (weights.some((weight) => weight.numerator < 0n)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot be negative');\n }\n\n const commonDenominator = weights.reduce((result, weight) => lcm(result, weight.denominator), 1n);\n const scaledWeights = weights.map((weight) => weight.numerator * (commonDenominator / weight.denominator));\n const totalWeight = scaledWeights.reduce((result, weight) => result + weight, 0n);\n\n if (totalWeight === 0n)\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights must include a positive value');\n\n const sign = value.amount < 0n ? -1n : 1n;\n const absolute = value.amount < 0n ? -value.amount : value.amount;\n const shares = scaledWeights.map((weight) => (absolute * weight) / totalWeight);\n let remainder = absolute - shares.reduce((result, amount) => result + amount, 0n);\n const ranked = scaledWeights\n .map((weight, index) => ({ index, remainder: (absolute * weight) % totalWeight }))\n .sort((left, right) =>\n left.remainder === right.remainder ? left.index - right.index : left.remainder > right.remainder ? -1 : 1,\n );\n\n for (const entry of ranked) {\n if (remainder === 0n) break;\n\n shares[entry.index]! += 1n;\n remainder -= 1n;\n }\n\n return shares.map((amount) => createMoney(amount * sign, value.currency));\n}\n\nfunction allocateEvenly<C extends Currency>(value: Money<C>, countValue: number): Money<C>[] {\n if (!Number.isSafeInteger(countValue) || countValue < 1 || countValue > MAX_ALLOCATION_PARTS) {\n throw new CoinsError(\n 'INVALID_ALLOCATION',\n `Allocation count must be a positive safe integer no greater than ${MAX_ALLOCATION_PARTS}`,\n );\n }\n\n const count = BigInt(countValue);\n const sign = value.amount < 0n ? -1n : 1n;\n const absolute = value.amount < 0n ? -value.amount : value.amount;\n const base = absolute / count;\n const remainder = absolute % count;\n\n return Array.from({ length: countValue }, (_, index) =>\n createMoney((base + (BigInt(index) < remainder ? 1n : 0n)) * sign, value.currency),\n );\n}\n"],"mapp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AAaqB,KAAQ,OAAOnB,CAAK,IAAIY,IAAY,KAAK,OAAOH,GAAMf,EAAM,QAAQ,CACnF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"coins.cjs","names":[],"sources":["../src/errors.ts","../src/_decimal.ts","../src/currency.ts","../src/money.ts","../src/aggregate.ts","../src/exchange.ts","../src/format.ts","../src/serialization.ts"],"sourcesContent":["export type CoinsErrorCode =\n | 'CURRENCY_MISMATCH'\n | 'DIVISION_BY_ZERO'\n | 'FORMAT_ERROR'\n | 'INVALID_ALLOCATION'\n | 'INVALID_CURRENCY'\n | 'INVALID_DECIMAL'\n | 'INVALID_EXCHANGE_RATE'\n | 'INVALID_MONEY'\n | 'INVALID_RANGE'\n | 'INVALID_ROUNDING';\n\nexport class CoinsError extends Error {\n readonly code: CoinsErrorCode;\n\n constructor(code: CoinsErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class CurrencyMismatchError extends CoinsError {\n readonly expected: string;\n readonly received: string;\n\n constructor(expected: string, received: string) {\n super('CURRENCY_MISMATCH', `Currency mismatch: 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","import { CoinsError } from './errors';\nimport type { Decimal, RoundingMode } from './types';\n\nconst DECIMAL = /^(-?)(\\d+)(?:\\.(\\d+))?$/;\nconst MAX_DECIMAL_DIGITS = 1000;\nconst MAX_DECIMAL_PLACES = 100;\nconst ROUNDING_MODES = new Set<RoundingMode>([\n 'awayFromZero',\n 'ceil',\n 'floor',\n 'halfAwayFromZero',\n 'halfEven',\n 'towardZero',\n]);\n\nexport function assertRoundingMode(value: unknown): asserts value is RoundingMode {\n if (!ROUNDING_MODES.has(value as RoundingMode)) {\n throw new CoinsError('INVALID_ROUNDING', `Unknown rounding mode: ${String(value)}`);\n }\n}\n\nexport function decimal(value: string): Decimal {\n if (typeof value !== 'string') throw new CoinsError('INVALID_DECIMAL', 'Decimal input must be a string');\n if (value.length > MAX_DECIMAL_DIGITS) throw new CoinsError('INVALID_DECIMAL', 'Decimal input is too long');\n\n const match = DECIMAL.exec(value);\n\n if (!match) throw new CoinsError('INVALID_DECIMAL', `Invalid decimal: \"${value}\"`);\n\n const fraction = (match[3] ?? '').replace(/0+$/, '');\n\n if (fraction.length > MAX_DECIMAL_PLACES) {\n throw new CoinsError('INVALID_DECIMAL', `Decimal precision cannot exceed ${MAX_DECIMAL_PLACES} places`);\n }\n\n const denominator = 10n ** BigInt(fraction.length);\n const unsigned = BigInt(match[2]!) * denominator + BigInt(fraction || '0');\n const numerator = match[1] === '-' && unsigned !== 0n ? -unsigned : unsigned;\n const divisor = gcd(numerator < 0n ? -numerator : numerator, denominator);\n\n return Object.freeze({ denominator: denominator / divisor, numerator: numerator / divisor }) as Decimal;\n}\n\nexport function roundDivision(numerator: bigint, denominator: bigint, mode: RoundingMode): bigint {\n assertRoundingMode(mode);\n if (denominator <= 0n) throw new CoinsError('INVALID_DECIMAL', 'Decimal denominator must be positive');\n\n const negative = numerator < 0n;\n const absolute = negative ? -numerator : numerator;\n const quotient = absolute / denominator;\n const remainder = absolute % denominator;\n\n if (remainder === 0n) return negative ? -quotient : quotient;\n\n const increment = (() => {\n switch (mode) {\n case 'awayFromZero':\n return true;\n case 'ceil':\n return !negative;\n case 'floor':\n return negative;\n case 'halfAwayFromZero':\n return remainder * 2n >= denominator;\n case 'halfEven': {\n const doubled = remainder * 2n;\n\n return doubled > denominator || (doubled === denominator && quotient % 2n !== 0n);\n }\n case 'towardZero':\n return false;\n default:\n throw new CoinsError('INVALID_ROUNDING', `Unknown rounding mode: ${mode satisfies never}`);\n }\n })();\n\n const result = increment ? quotient + 1n : quotient;\n\n return negative ? -result : result;\n}\n\nexport function toDecimalString(amount: bigint, minorUnit: number): string {\n const negative = amount < 0n;\n const absolute = negative ? -amount : amount;\n const scale = 10n ** BigInt(minorUnit);\n const whole = absolute / scale;\n\n if (minorUnit === 0) return `${negative ? '-' : ''}${whole}`;\n\n const fraction = (absolute % scale).toString().padStart(minorUnit, '0');\n\n return `${negative ? '-' : ''}${whole}.${fraction}`;\n}\n\nexport function gcd(left: bigint, right: bigint): bigint {\n let a = left;\n let b = right;\n\n while (b !== 0n) [a, b] = [b, a % b];\n\n return a === 0n ? 1n : a;\n}\n\nexport function lcm(left: bigint, right: bigint): bigint {\n return (left / gcd(left, right)) * right;\n}\n","import { CoinsError, InvalidCurrencyError } from './errors';\nimport type { Currency, CurrencyCode } from './types';\n\nconst builtins = new Map<string, Currency>();\nconst canonicalCurrencies = new WeakSet<object>();\n\nfunction register<C extends string>(code: C, minorUnit: number): Currency<C> {\n validateDefinition(code, minorUnit);\n\n const definition = Object.freeze({ code: code as CurrencyCode<C>, minorUnit }) as Currency<C>;\n\n canonicalCurrencies.add(definition);\n\n return definition;\n}\n\nfunction builtin<C extends string>(code: C, minorUnit: number): Currency<C> {\n const definition = register(code, minorUnit);\n\n builtins.set(code, definition);\n\n return definition;\n}\n\nexport const USD = builtin('USD', 2);\nexport const EUR = builtin('EUR', 2);\nexport const GBP = builtin('GBP', 2);\nexport const JPY = builtin('JPY', 0);\nexport const KRW = builtin('KRW', 0);\nexport const BHD = builtin('BHD', 3);\nexport const KWD = builtin('KWD', 3);\n\n/** Resolve a built-in currency by code, or construct an immutable custom currency from a definition. */\nexport function currency<C extends string>(code: C): Currency<C>;\nexport function currency<C extends string>(definition: { code: C; minorUnit: number }): Currency<C>;\nexport function currency<C extends string>(input: C | { code: C; minorUnit: number }): Currency<C> {\n if (typeof input === 'string') {\n const definition = builtins.get(input);\n\n if (!definition) throw new InvalidCurrencyError(input);\n\n return definition as Currency<C>;\n }\n\n if (typeof input !== 'object' || input === null) {\n throw new CoinsError('INVALID_CURRENCY', 'Currency definition must be an object');\n }\n\n return register(input.code, input.minorUnit);\n}\n\nexport function isCurrency(value: unknown): value is Currency {\n return typeof value === 'object' && value !== null && canonicalCurrencies.has(value);\n}\n\nfunction validateDefinition(code: string, minorUnit: number): void {\n if (!/^[A-Z]{3}$/.test(code)) {\n throw new CoinsError('INVALID_CURRENCY', `Currency code must be three uppercase letters: \"${code}\"`);\n }\n\n if (!Number.isInteger(minorUnit) || minorUnit < 0 || minorUnit > 6) {\n throw new CoinsError('INVALID_CURRENCY', `Currency \"${code}\" must have 0–6 minor-unit digits`);\n }\n}\n","import { decimal, roundDivision, toDecimalString } from './_decimal';\nimport { currency, isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport type { Currency, Money, RoundingMode } from './types';\n\nconst canonicalMoney = new WeakSet<object>();\n\nconst defaultRounding: RoundingMode = 'halfAwayFromZero';\n\nconst INTEGER = /^(?:0|-[1-9]\\d*|[1-9]\\d*)$/;\nconst MAX_INTEGER_DIGITS = 1000;\n\nexport function money<C extends Currency>(amount: string, currency: C, options?: { rounding?: RoundingMode }): Money<C>;\nexport function money<C extends Currency>(amount: bigint, currency: C, options: { unit: 'minor' }): Money<C>;\nexport function money<C extends Currency>(\n amount: bigint | string,\n currency: C,\n options?: { rounding?: RoundingMode } | { unit: 'minor' },\n): Money<C> {\n assertCurrency(currency);\n\n if (typeof amount === 'bigint') {\n if (!options || !('unit' in options) || options.unit !== 'minor') {\n throw new CoinsError('INVALID_MONEY', \"Bigint amounts require { unit: 'minor' }\");\n }\n\n return createMoney(amount, currency);\n }\n\n if (options && 'unit' in options)\n throw new CoinsError('INVALID_MONEY', 'Decimal strings do not accept a unit option');\n\n const value = decimal(amount);\n const scaled = value.numerator * 10n ** BigInt(currency.minorUnit);\n const remainder = scaled % value.denominator;\n\n if (remainder !== 0n && options?.rounding === undefined) {\n throw new CoinsError('INVALID_MONEY', `Amount \"${amount}\" exceeds ${currency.code} precision; provide rounding`);\n }\n\n return createMoney(roundDivision(scaled, value.denominator, options?.rounding ?? defaultRounding), currency);\n}\n\n/**\n * Decodes untrusted/persisted data into canonical `Money`.\n * Accepts either a plain `Money`-shaped object (`{ amount: bigint, currency: Currency }`)\n * or a `MoneyJSON`-shaped object (`{ amount: string, currency: string, unit: 'minor' }`).\n * Use `money()` for trusted construction; use `decodeMoney()` for network/storage data.\n */\nexport function decodeMoney(value: unknown, options?: { currency?: (code: string) => Currency }): Money {\n if (!isPlainDataObject(value)) throw new CoinsError('INVALID_MONEY', 'Money must be a plain data object');\n\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const amountDescriptor = descriptors.amount;\n const currencyDescriptor = descriptors.currency;\n\n if (!isDataProperty(amountDescriptor) || !isDataProperty(currencyDescriptor)) {\n throw new CoinsError('INVALID_MONEY', 'Money properties must be plain data values');\n }\n\n const ownKeys = Reflect.ownKeys(value);\n\n // Plain Money: bigint amount + registered currency\n if (typeof amountDescriptor.value === 'bigint' && isCurrency(currencyDescriptor.value)) {\n if (ownKeys.length !== 2) {\n throw new CoinsError('INVALID_MONEY', 'Plain money must have exactly the keys amount and currency');\n }\n\n return createMoney(amountDescriptor.value, currencyDescriptor.value);\n }\n\n // MoneyJSON: string amount + string currency code + unit: 'minor'\n const unitDescriptor = descriptors.unit;\n if (\n typeof amountDescriptor.value === 'string' &&\n typeof currencyDescriptor.value === 'string' &&\n isDataProperty(unitDescriptor) &&\n unitDescriptor.value === 'minor'\n ) {\n if (ownKeys.length !== 3) {\n throw new CoinsError('INVALID_MONEY', 'MoneyJSON must have exactly the keys amount, currency, unit');\n }\n if (amountDescriptor.value.length > MAX_INTEGER_DIGITS) {\n throw new CoinsError('INVALID_MONEY', `Money JSON amount is too long; maximum ${MAX_INTEGER_DIGITS} characters`);\n }\n if (!INTEGER.test(amountDescriptor.value)) {\n throw new CoinsError('INVALID_MONEY', `Invalid Money JSON amount \"${amountDescriptor.value}\"`);\n }\n const resolveCurrency = options?.currency ?? currency;\n try {\n const resolvedCurrency = resolveCurrency(currencyDescriptor.value);\n\n if (!isCurrency(resolvedCurrency) || resolvedCurrency.code !== currencyDescriptor.value) {\n throw new CoinsError(\n 'INVALID_CURRENCY',\n `Currency resolver must return the canonical \"${currencyDescriptor.value}\" definition`,\n );\n }\n\n return money(BigInt(amountDescriptor.value), resolvedCurrency, { unit: 'minor' });\n } catch (error) {\n throw new CoinsError('INVALID_MONEY', `Invalid Money JSON for currency \"${currencyDescriptor.value}\"`, {\n cause: error,\n });\n }\n }\n\n throw new CoinsError(\n 'INVALID_MONEY',\n 'Money must contain bigint amount and a registered currency, or a valid MoneyJSON shape',\n );\n}\n\nexport function isMoney(value: unknown): value is Money {\n return typeof value === 'object' && value !== null && canonicalMoney.has(value);\n}\n\nexport function add<C extends Currency>(left: Money<C>, right: Money<NoInfer<C>>): Money<C> {\n assertSameCurrency(left, right);\n\n return createMoney(left.amount + right.amount, left.currency);\n}\n\nexport function subtract<C extends Currency>(left: Money<C>, right: Money<NoInfer<C>>): Money<C> {\n assertSameCurrency(left, right);\n\n return createMoney(left.amount - right.amount, left.currency);\n}\n\nexport function multiply<C extends Currency>(\n value: Money<C>,\n factor: string,\n options: { rounding?: RoundingMode } = {},\n): Money<C> {\n assertMoney(value);\n\n const scalar = decimal(factor);\n\n return createMoney(\n roundDivision(value.amount * scalar.numerator, scalar.denominator, options.rounding ?? defaultRounding),\n value.currency,\n );\n}\n\nexport function divide<C extends Currency>(\n value: Money<C>,\n divisor: string,\n options: { rounding?: RoundingMode } = {},\n): Money<C> {\n assertMoney(value);\n\n const scalar = decimal(divisor);\n\n if (scalar.numerator === 0n) throw new CoinsError('DIVISION_BY_ZERO', 'Cannot divide money by zero');\n\n const divisorMagnitude = scalar.numerator < 0n ? -scalar.numerator : scalar.numerator;\n const dividend = value.amount * scalar.denominator;\n const quotient = roundDivision(\n scalar.numerator < 0n ? -dividend : dividend,\n divisorMagnitude,\n options.rounding ?? defaultRounding,\n );\n\n return createMoney(quotient, value.currency);\n}\n\nexport function compare<C extends Currency>(left: Money<C>, right: Money<NoInfer<C>>): -1 | 0 | 1 {\n assertSameCurrency(left, right);\n\n return left.amount === right.amount ? 0 : left.amount < right.amount ? -1 : 1;\n}\n\nexport function clamp<C extends Currency>(\n value: Money<C>,\n options: { max: Money<NoInfer<C>>; min: Money<NoInfer<C>> },\n): Money<C> {\n if (compare(options.min, options.max) === 1) {\n throw new CoinsError('INVALID_RANGE', 'Clamp minimum cannot exceed maximum');\n }\n\n return compare(value, options.min) === -1 ? options.min : compare(value, options.max) === 1 ? options.max : value;\n}\n\nexport function abs<C extends Currency>(value: Money<C>): Money<C> {\n assertMoney(value);\n\n return createMoney(value.amount < 0n ? -value.amount : value.amount, value.currency);\n}\n\nexport function negate<C extends Currency>(value: Money<C>): Money<C> {\n assertMoney(value);\n\n return createMoney(-value.amount, value.currency);\n}\n\nexport function round<C extends Currency>(\n value: Money<C>,\n options: { fractionDigits: number; rounding?: RoundingMode },\n): Money<C> {\n assertMoney(value);\n\n const { fractionDigits, rounding = defaultRounding } = options;\n\n if (!Number.isInteger(fractionDigits) || fractionDigits < 0 || fractionDigits > value.currency.minorUnit) {\n throw new CoinsError('INVALID_ROUNDING', `fractionDigits must be an integer from 0 to ${value.currency.minorUnit}`);\n }\n\n const factor = 10n ** BigInt(value.currency.minorUnit - fractionDigits);\n\n return createMoney(roundDivision(value.amount, factor, rounding) * factor, value.currency);\n}\n\nexport function toDecimal(value: Money): string {\n assertMoney(value);\n\n return toDecimalString(value.amount, value.currency.minorUnit);\n}\n\nexport function createMoney<C extends Currency>(amount: bigint, currency: C): Money<C> {\n const value = Object.freeze({ amount, currency }) as Money<C>;\n\n canonicalMoney.add(value);\n\n return value;\n}\n\nexport function assertMoney(value: unknown): asserts value is Money {\n if (!isMoney(value)) {\n throw new CoinsError('INVALID_MONEY', 'Money must be a canonical @vielzeug/coins value');\n }\n}\n\nfunction assertSameCurrency(left: Money, right: Money): void {\n assertMoney(left);\n assertMoney(right);\n\n if (left.currency !== right.currency) {\n throw new CurrencyMismatchError(left.currency.code, right.currency.code);\n }\n}\n\nfunction assertCurrency(value: unknown): asserts value is Currency {\n if (!isCurrency(value)) throw new CoinsError('INVALID_CURRENCY', 'Money requires a registered currency');\n}\n\nfunction isPlainDataObject(value: unknown): value is Record<PropertyKey, unknown> {\n if (typeof value !== 'object' || value === null) return false;\n\n const prototype = Object.getPrototypeOf(value);\n\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isDataProperty(\n descriptor: PropertyDescriptor | undefined,\n): descriptor is PropertyDescriptor & { value: unknown } {\n return (\n descriptor !== undefined && 'value' in descriptor && descriptor.get === undefined && descriptor.set === undefined\n );\n}\n","import { decimal, lcm } from './_decimal';\nimport { isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { assertMoney, createMoney } from './money';\nimport type { Currency, Money } from './types';\n\nconst MAX_ALLOCATION_PARTS = 100_000;\n\nexport function sum<C extends Currency>(values: readonly Money<C>[]): Money<C>;\nexport function sum<C extends Currency>(values: Iterable<Money<C>>, options: { currency: C }): Money<C>;\nexport function sum<C extends Currency>(values: Iterable<Money<C>>, options?: { currency: C }): Money<C> {\n if (options && !isCurrency(options.currency)) {\n throw new CoinsError('INVALID_CURRENCY', 'sum() requires a canonical currency');\n }\n\n let amount = 0n;\n let currency: C | undefined = options?.currency;\n\n for (const value of values) {\n assertMoney(value);\n\n if (currency === undefined) {\n currency = value.currency;\n } else if (value.currency !== currency) {\n throw new CurrencyMismatchError(currency.code, value.currency.code);\n }\n\n amount += value.amount;\n }\n\n if (currency === undefined) throw new CoinsError('INVALID_MONEY', 'sum() of empty iterable requires { currency }');\n\n return createMoney(amount, currency);\n}\n\nexport function allocate<C extends Currency>(value: Money<C>, count: number): Money<C>[];\nexport function allocate<C extends Currency>(value: Money<C>, weights: readonly string[]): Money<C>[];\nexport function allocate<C extends Currency>(value: Money<C>, weightsOrCount: number | readonly string[]): Money<C>[] {\n assertMoney(value);\n\n if (typeof weightsOrCount === 'number') return allocateEvenly(value, weightsOrCount);\n\n if (!Array.isArray(weightsOrCount)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights must be an array');\n }\n if (weightsOrCount.length === 0) throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot be empty');\n if (weightsOrCount.length > MAX_ALLOCATION_PARTS) {\n throw new CoinsError('INVALID_ALLOCATION', `Allocation cannot exceed ${MAX_ALLOCATION_PARTS} parts`);\n }\n for (let index = 0; index < weightsOrCount.length; index++) {\n if (!Object.hasOwn(weightsOrCount, index)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot contain empty slots');\n }\n }\n\n const weights = weightsOrCount.map(decimal);\n\n if (weights.some((weight) => weight.numerator < 0n)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot be negative');\n }\n\n const commonDenominator = weights.reduce((result, weight) => lcm(result, weight.denominator), 1n);\n const scaledWeights = weights.map((weight) => weight.numerator * (commonDenominator / weight.denominator));\n const totalWeight = scaledWeights.reduce((result, weight) => result + weight, 0n);\n\n if (totalWeight === 0n)\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights must include a positive value');\n\n const sign = value.amount < 0n ? -1n : 1n;\n const absolute = value.amount < 0n ? -value.amount : value.amount;\n const shares = scaledWeights.map((weight) => (absolute * weight) / totalWeight);\n let remainder = absolute - shares.reduce((result, amount) => result + amount, 0n);\n const ranked = scaledWeights\n .map((weight, index) => ({ index, remainder: (absolute * weight) % totalWeight }))\n .sort((left, right) =>\n left.remainder === right.remainder ? left.index - right.index : left.remainder > right.remainder ? -1 : 1,\n );\n\n for (const entry of ranked) {\n if (remainder === 0n) break;\n\n shares[entry.index]! += 1n;\n remainder -= 1n;\n }\n\n return shares.map((amount) => createMoney(amount * sign, value.currency));\n}\n\nfunction allocateEvenly<C extends Currency>(value: Money<C>, countValue: number): Money<C>[] {\n if (!Number.isSafeInteger(countValue) || countValue < 1 || countValue > MAX_ALLOCATION_PARTS) {\n throw new CoinsError(\n 'INVALID_ALLOCATION',\n `Allocation count must be a positive safe integer no greater than ${MAX_ALLOCATION_PARTS}`,\n );\n }\n\n const count = BigInt(countValue);\n const sign = value.amount < 0n ? -1n : 1n;\n const absolute = value.amount < 0n ? -value.amount : value.amount;\n const base = absolute / count;\n const remainder = absolute % count;\n\n return Array.from({ length: countValue }, (_, index) =>\n createMoney((base + (BigInt(index) < remainder ? 1n : 0n)) * sign, value.currency),\n );\n}\n","import { decimal, roundDivision } from './_decimal';\nimport { isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { assertMoney, createMoney } from './money';\nimport type { Currency, ExchangeRate, Money, RoundingMode } from './types';\n\nconst canonicalRates = new WeakSet<object>();\n\nexport function exchangeRate<From extends Currency, To extends Currency>({\n from,\n to,\n value,\n}: {\n from: From;\n to: To;\n value: string;\n}): ExchangeRate<From, To> {\n if (!isCurrency(from) || !isCurrency(to))\n throw new CoinsError('INVALID_CURRENCY', 'Exchange rate requires registered currencies');\n\n const parsed = decimal(value);\n\n if (parsed.numerator <= 0n) throw new CoinsError('INVALID_DECIMAL', 'Exchange rates must be positive');\n\n const rate = Object.freeze({ from, to, value: parsed }) as ExchangeRate<From, To>;\n\n canonicalRates.add(rate);\n\n return rate;\n}\n\nexport function isExchangeRate(value: unknown): value is ExchangeRate {\n return typeof value === 'object' && value !== null && canonicalRates.has(value);\n}\n\nexport function exchange<From extends Currency, To extends Currency>(\n value: Money<From>,\n rate: ExchangeRate<From, To>,\n options: { rounding?: RoundingMode } = {},\n): Money<To> {\n assertMoney(value);\n\n if (!isExchangeRate(rate)) {\n throw new CoinsError('INVALID_EXCHANGE_RATE', 'Exchange requires a canonical exchange rate');\n }\n\n if (value.currency !== rate.from) throw new CurrencyMismatchError(value.currency.code, rate.from.code);\n\n const numerator = value.amount * rate.value.numerator * 10n ** BigInt(rate.to.minorUnit);\n const denominator = rate.value.denominator * 10n ** BigInt(rate.from.minorUnit);\n\n return createMoney(roundDivision(numerator, denominator, options.rounding ?? 'halfAwayFromZero'), rate.to);\n}\n","import { assertRoundingMode } from './_decimal';\nimport { CoinsError } from './errors';\nimport { assertMoney, toDecimal } from './money';\nimport type { FormatOptions, Money, MoneyFormatPart, RoundingMode } from './types';\n\nconst MAX_FRACTION_DIGITS = 20;\nconst defaultFormatRounding: RoundingMode = 'halfAwayFromZero';\nconst intlRoundingModes: Record<RoundingMode, Intl.NumberFormatOptions['roundingMode']> = {\n awayFromZero: 'expand',\n ceil: 'ceil',\n floor: 'floor',\n halfAwayFromZero: 'halfExpand',\n halfEven: 'halfEven',\n towardZero: 'trunc',\n};\n\nexport function format(value: Money, options: FormatOptions = {}): string {\n return formatParts(value, options)\n .map((part) => part.value)\n .join('');\n}\n\nexport function formatParts(value: Money, options: FormatOptions = {}): MoneyFormatPart[] {\n assertMoney(value);\n assertRoundingMode(options.rounding ?? defaultFormatRounding);\n\n const { maximum, minimum } = fractionDigits(value.currency.minorUnit, options);\n const style = options.style ?? 'symbol';\n\n try {\n const formatter = new Intl.NumberFormat(options.locale ?? 'en-US', {\n currency: value.currency.code,\n currencyDisplay: style,\n maximumFractionDigits: maximum,\n minimumFractionDigits: minimum,\n roundingMode: intlRoundingModes[options.rounding ?? defaultFormatRounding],\n style: 'currency',\n useGrouping: true,\n });\n\n return normalizeParts(formatter.formatToParts(toDecimal(value) as unknown as number));\n } catch (error) {\n if (error instanceof CoinsError) throw error;\n\n throw new CoinsError(\n 'FORMAT_ERROR',\n `Cannot format currency \"${value.currency.code}\" for locale \"${options.locale ?? 'en-US'}\"`,\n { cause: error },\n );\n }\n}\n\nfunction fractionDigits(scale: number, options: FormatOptions): { maximum: number; minimum: number } {\n const requestedMaximum = options.maximumFractionDigits;\n const requestedMinimum = options.minimumFractionDigits;\n\n validateFractionDigit('maximumFractionDigits', requestedMaximum);\n validateFractionDigit('minimumFractionDigits', requestedMinimum);\n\n const maximum = requestedMaximum ?? Math.max(scale, requestedMinimum ?? scale);\n const minimum = requestedMinimum ?? Math.min(scale, requestedMaximum ?? scale);\n\n if (minimum > maximum) {\n throw new CoinsError('FORMAT_ERROR', 'minimumFractionDigits cannot exceed maximumFractionDigits');\n }\n\n return { maximum, minimum };\n}\n\nfunction validateFractionDigit(name: string, value: number | undefined): void {\n if (value !== undefined && (!Number.isInteger(value) || value < 0 || value > MAX_FRACTION_DIGITS)) {\n throw new CoinsError(\n 'FORMAT_ERROR',\n `Fraction digits must be integers satisfying 0 ≤ minimum ≤ maximum ≤ ${MAX_FRACTION_DIGITS} (${name})`,\n );\n }\n}\n\nfunction normalizeParts(raw: Intl.NumberFormatPart[]): MoneyFormatPart[] {\n const parts: MoneyFormatPart[] = [];\n\n for (const part of raw) {\n if (part.type === 'integer' || part.type === 'group') {\n const previous = parts.at(-1);\n\n if (previous?.type === 'integer') {\n parts[parts.length - 1] = { type: 'integer', value: previous.value + part.value };\n } else {\n parts.push({ type: 'integer', value: part.value });\n }\n } else if (\n part.type === 'currency' ||\n part.type === 'decimal' ||\n part.type === 'fraction' ||\n part.type === 'literal' ||\n part.type === 'minusSign' ||\n part.type === 'plusSign'\n ) {\n parts.push({ type: part.type, value: part.value });\n } else {\n parts.push({ type: 'literal', value: part.value });\n }\n }\n\n return parts;\n}\n","import { assertMoney } from './money';\nimport type { Money, MoneyJSON } from './types';\n\nexport function toJSON(value: Money): MoneyJSON {\n assertMoney(value);\n\n return { amount: value.amount.toString(), currency: value.currency.code, unit: 'minor' };\n}\n"],"mappings":"mEAYA,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,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M,CAAC,EAEjD,EAAM,KAAK,CAAE,KAAM,UAAW,MAAO,EAAK,KAAM,CAAC,EAIrD,OAAO,CACT,CCtGA,SAAgB,OAAO,EAAyB,CAG9C,OAFA,YAAY,CAAK,EAEV,CAAE,OAAQ,EAAM,OAAO,SAAS,EAAG,SAAU,EAAM,SAAS,KAAM,KAAM,OAAQ,CACzF"}
1
+ {"version":3,"file":"coins.cjs","names":["message","options","code","expected","received","value","DECIMAL","MAX_DECIMAL_DIGITS","MAX_DECIMAL_PLACES","ROUNDING_MODES","match","fraction","denominator","unsigned","numerator","divisor","mode","negative","absolute","quotient","remainder","result","doubled","amount","scale","minorUnit","whole","a","left","b","right","builtins","canonicalCurrencies","definition","USD","EUR","GBP","JPY","KRW","BHD","KWD","input","canonicalMoney","defaultRounding","INTEGER","MAX_INTEGER_DIGITS","currency","scaled","descriptors","amountDescriptor","currencyDescriptor","ownKeys","unitDescriptor","resolveCurrency","resolvedCurrency","error","scalar","factor","divisorMagnitude","dividend","fractionDigits","rounding","prototype","descriptor","MAX_ALLOCATION_PARTS","values","weightsOrCount","index","weights","weight","commonDenominator","scaledWeights","totalWeight","sign","shares","ranked","entry","countValue","count","base","canonicalRates","from","to","parsed","rate","MAX_FRACTION_DIGITS","defaultFormatRounding","intlRoundingModes","part","style","maximum","minimum","requestedMaximum","requestedMinimum","name","parts","raw","previous"],"sources":["../src/errors.ts","../src/_decimal.ts","../src/currency.ts","../src/money.ts","../src/aggregate.ts","../src/exchange.ts","../src/format.ts","../src/serialization.ts"],"sourcesContent":["export type CoinsErrorCode =\n | 'CURRENCY_MISMATCH'\n | 'DIVISION_BY_ZERO'\n | 'FORMAT_ERROR'\n | 'INVALID_ALLOCATION'\n | 'INVALID_CURRENCY'\n | 'INVALID_DECIMAL'\n | 'INVALID_EXCHANGE_RATE'\n | 'INVALID_MONEY'\n | 'INVALID_RANGE'\n | 'INVALID_ROUNDING';\n\nexport class CoinsError extends Error {\n readonly code: CoinsErrorCode;\n\n constructor(code: CoinsErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class CurrencyMismatchError extends CoinsError {\n readonly expected: string;\n readonly received: string;\n\n constructor(expected: string, received: string) {\n super('CURRENCY_MISMATCH', `Currency mismatch: 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","import { CoinsError } from './errors';\nimport type { Decimal, RoundingMode } from './types';\n\nconst DECIMAL = /^(-?)(\\d+)(?:\\.(\\d+))?$/;\nconst MAX_DECIMAL_DIGITS = 1000;\nconst MAX_DECIMAL_PLACES = 100;\nconst ROUNDING_MODES = new Set<RoundingMode>([\n 'awayFromZero',\n 'ceil',\n 'floor',\n 'halfAwayFromZero',\n 'halfEven',\n 'towardZero',\n]);\n\nexport function assertRoundingMode(value: unknown): asserts value is RoundingMode {\n if (!ROUNDING_MODES.has(value as RoundingMode)) {\n throw new CoinsError('INVALID_ROUNDING', `Unknown rounding mode: ${String(value)}`);\n }\n}\n\nexport function decimal(value: string): Decimal {\n if (typeof value !== 'string') throw new CoinsError('INVALID_DECIMAL', 'Decimal input must be a string');\n if (value.length > MAX_DECIMAL_DIGITS) throw new CoinsError('INVALID_DECIMAL', 'Decimal input is too long');\n\n const match = DECIMAL.exec(value);\n\n if (!match) throw new CoinsError('INVALID_DECIMAL', `Invalid decimal: \"${value}\"`);\n\n const fraction = (match[3] ?? '').replace(/0+$/, '');\n\n if (fraction.length > MAX_DECIMAL_PLACES) {\n throw new CoinsError('INVALID_DECIMAL', `Decimal precision cannot exceed ${MAX_DECIMAL_PLACES} places`);\n }\n\n const denominator = 10n ** BigInt(fraction.length);\n const unsigned = BigInt(match[2]!) * denominator + BigInt(fraction || '0');\n const numerator = match[1] === '-' && unsigned !== 0n ? -unsigned : unsigned;\n const divisor = gcd(numerator < 0n ? -numerator : numerator, denominator);\n\n return Object.freeze({ denominator: denominator / divisor, numerator: numerator / divisor }) as Decimal;\n}\n\nexport function roundDivision(numerator: bigint, denominator: bigint, mode: RoundingMode): bigint {\n assertRoundingMode(mode);\n if (denominator <= 0n) throw new CoinsError('INVALID_DECIMAL', 'Decimal denominator must be positive');\n\n const negative = numerator < 0n;\n const absolute = negative ? -numerator : numerator;\n const quotient = absolute / denominator;\n const remainder = absolute % denominator;\n\n if (remainder === 0n) return negative ? -quotient : quotient;\n\n const increment = (() => {\n switch (mode) {\n case 'awayFromZero':\n return true;\n case 'ceil':\n return !negative;\n case 'floor':\n return negative;\n case 'halfAwayFromZero':\n return remainder * 2n >= denominator;\n case 'halfEven': {\n const doubled = remainder * 2n;\n\n return doubled > denominator || (doubled === denominator && quotient % 2n !== 0n);\n }\n case 'towardZero':\n return false;\n default:\n throw new CoinsError('INVALID_ROUNDING', `Unknown rounding mode: ${mode satisfies never}`);\n }\n })();\n\n const result = increment ? quotient + 1n : quotient;\n\n return negative ? -result : result;\n}\n\nexport function toDecimalString(amount: bigint, minorUnit: number): string {\n const negative = amount < 0n;\n const absolute = negative ? -amount : amount;\n const scale = 10n ** BigInt(minorUnit);\n const whole = absolute / scale;\n\n if (minorUnit === 0) return `${negative ? '-' : ''}${whole}`;\n\n const fraction = (absolute % scale).toString().padStart(minorUnit, '0');\n\n return `${negative ? '-' : ''}${whole}.${fraction}`;\n}\n\nexport function gcd(left: bigint, right: bigint): bigint {\n let a = left;\n let b = right;\n\n while (b !== 0n) [a, b] = [b, a % b];\n\n return a === 0n ? 1n : a;\n}\n\nexport function lcm(left: bigint, right: bigint): bigint {\n return (left / gcd(left, right)) * right;\n}\n","import { CoinsError, InvalidCurrencyError } from './errors';\nimport type { Currency, CurrencyCode } from './types';\n\nconst builtins = new Map<string, Currency>();\nconst canonicalCurrencies = new WeakSet<object>();\n\nfunction register<C extends string>(code: C, minorUnit: number): Currency<C> {\n validateDefinition(code, minorUnit);\n\n const definition = Object.freeze({ code: code as CurrencyCode<C>, minorUnit }) as Currency<C>;\n\n canonicalCurrencies.add(definition);\n\n return definition;\n}\n\nfunction builtin<C extends string>(code: C, minorUnit: number): Currency<C> {\n const definition = register(code, minorUnit);\n\n builtins.set(code, definition);\n\n return definition;\n}\n\nexport const USD = builtin('USD', 2);\nexport const EUR = builtin('EUR', 2);\nexport const GBP = builtin('GBP', 2);\nexport const JPY = builtin('JPY', 0);\nexport const KRW = builtin('KRW', 0);\nexport const BHD = builtin('BHD', 3);\nexport const KWD = builtin('KWD', 3);\n\n/** Resolve a built-in currency by code, or construct an immutable custom currency from a definition. */\nexport function currency<C extends string>(code: C): Currency<C>;\nexport function currency<C extends string>(definition: { code: C; minorUnit: number }): Currency<C>;\nexport function currency<C extends string>(input: C | { code: C; minorUnit: number }): Currency<C> {\n if (typeof input === 'string') {\n const definition = builtins.get(input);\n\n if (!definition) throw new InvalidCurrencyError(input);\n\n return definition as Currency<C>;\n }\n\n if (typeof input !== 'object' || input === null) {\n throw new CoinsError('INVALID_CURRENCY', 'Currency definition must be an object');\n }\n\n return register(input.code, input.minorUnit);\n}\n\nexport function isCurrency(value: unknown): value is Currency {\n return typeof value === 'object' && value !== null && canonicalCurrencies.has(value);\n}\n\nfunction validateDefinition(code: string, minorUnit: number): void {\n if (!/^[A-Z]{3}$/.test(code)) {\n throw new CoinsError('INVALID_CURRENCY', `Currency code must be three uppercase letters: \"${code}\"`);\n }\n\n if (!Number.isInteger(minorUnit) || minorUnit < 0 || minorUnit > 6) {\n throw new CoinsError('INVALID_CURRENCY', `Currency \"${code}\" must have 0–6 minor-unit digits`);\n }\n}\n","import { decimal, roundDivision, toDecimalString } from './_decimal';\nimport { currency, isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport type { Currency, Money, RoundingMode } from './types';\n\nconst canonicalMoney = new WeakSet<object>();\n\nconst defaultRounding: RoundingMode = 'halfAwayFromZero';\n\nconst INTEGER = /^(?:0|-[1-9]\\d*|[1-9]\\d*)$/;\nconst MAX_INTEGER_DIGITS = 1000;\n\nexport function money<C extends Currency>(amount: string, currency: C, options?: { rounding?: RoundingMode }): Money<C>;\nexport function money<C extends Currency>(amount: bigint, currency: C, options: { unit: 'minor' }): Money<C>;\nexport function money<C extends Currency>(\n amount: bigint | string,\n currency: C,\n options?: { rounding?: RoundingMode } | { unit: 'minor' },\n): Money<C> {\n assertCurrency(currency);\n\n if (typeof amount === 'bigint') {\n if (!options || !('unit' in options) || options.unit !== 'minor') {\n throw new CoinsError('INVALID_MONEY', \"Bigint amounts require { unit: 'minor' }\");\n }\n\n return createMoney(amount, currency);\n }\n\n if (options && 'unit' in options)\n throw new CoinsError('INVALID_MONEY', 'Decimal strings do not accept a unit option');\n\n const value = decimal(amount);\n const scaled = value.numerator * 10n ** BigInt(currency.minorUnit);\n const remainder = scaled % value.denominator;\n\n if (remainder !== 0n && options?.rounding === undefined) {\n throw new CoinsError('INVALID_MONEY', `Amount \"${amount}\" exceeds ${currency.code} precision; provide rounding`);\n }\n\n return createMoney(roundDivision(scaled, value.denominator, options?.rounding ?? defaultRounding), currency);\n}\n\n/**\n * Decodes untrusted/persisted data into canonical `Money`.\n * Accepts either a plain `Money`-shaped object (`{ amount: bigint, currency: Currency }`)\n * or a `MoneyJSON`-shaped object (`{ amount: string, currency: string, unit: 'minor' }`).\n * Use `money()` for trusted construction; use `decodeMoney()` for network/storage data.\n */\nexport function decodeMoney(value: unknown, options?: { currency?: (code: string) => Currency }): Money {\n if (!isPlainDataObject(value)) throw new CoinsError('INVALID_MONEY', 'Money must be a plain data object');\n\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const amountDescriptor = descriptors.amount;\n const currencyDescriptor = descriptors.currency;\n\n if (!isDataProperty(amountDescriptor) || !isDataProperty(currencyDescriptor)) {\n throw new CoinsError('INVALID_MONEY', 'Money properties must be plain data values');\n }\n\n const ownKeys = Reflect.ownKeys(value);\n\n // Plain Money: bigint amount + registered currency\n if (typeof amountDescriptor.value === 'bigint' && isCurrency(currencyDescriptor.value)) {\n if (ownKeys.length !== 2) {\n throw new CoinsError('INVALID_MONEY', 'Plain money must have exactly the keys amount and currency');\n }\n\n return createMoney(amountDescriptor.value, currencyDescriptor.value);\n }\n\n // MoneyJSON: string amount + string currency code + unit: 'minor'\n const unitDescriptor = descriptors.unit;\n if (\n typeof amountDescriptor.value === 'string' &&\n typeof currencyDescriptor.value === 'string' &&\n isDataProperty(unitDescriptor) &&\n unitDescriptor.value === 'minor'\n ) {\n if (ownKeys.length !== 3) {\n throw new CoinsError('INVALID_MONEY', 'MoneyJSON must have exactly the keys amount, currency, unit');\n }\n if (amountDescriptor.value.length > MAX_INTEGER_DIGITS) {\n throw new CoinsError('INVALID_MONEY', `Money JSON amount is too long; maximum ${MAX_INTEGER_DIGITS} characters`);\n }\n if (!INTEGER.test(amountDescriptor.value)) {\n throw new CoinsError('INVALID_MONEY', `Invalid Money JSON amount \"${amountDescriptor.value}\"`);\n }\n const resolveCurrency = options?.currency ?? currency;\n try {\n const resolvedCurrency = resolveCurrency(currencyDescriptor.value);\n\n if (!isCurrency(resolvedCurrency) || resolvedCurrency.code !== currencyDescriptor.value) {\n throw new CoinsError(\n 'INVALID_CURRENCY',\n `Currency resolver must return the canonical \"${currencyDescriptor.value}\" definition`,\n );\n }\n\n return money(BigInt(amountDescriptor.value), resolvedCurrency, { unit: 'minor' });\n } catch (error) {\n throw new CoinsError('INVALID_MONEY', `Invalid Money JSON for currency \"${currencyDescriptor.value}\"`, {\n cause: error,\n });\n }\n }\n\n throw new CoinsError(\n 'INVALID_MONEY',\n 'Money must contain bigint amount and a registered currency, or a valid MoneyJSON shape',\n );\n}\n\nexport function isMoney(value: unknown): value is Money {\n return typeof value === 'object' && value !== null && canonicalMoney.has(value);\n}\n\nexport function add<C extends Currency>(left: Money<C>, right: Money<NoInfer<C>>): Money<C> {\n assertSameCurrency(left, right);\n\n return createMoney(left.amount + right.amount, left.currency);\n}\n\nexport function subtract<C extends Currency>(left: Money<C>, right: Money<NoInfer<C>>): Money<C> {\n assertSameCurrency(left, right);\n\n return createMoney(left.amount - right.amount, left.currency);\n}\n\nexport function multiply<C extends Currency>(\n value: Money<C>,\n factor: string,\n options: { rounding?: RoundingMode } = {},\n): Money<C> {\n assertMoney(value);\n\n const scalar = decimal(factor);\n\n return createMoney(\n roundDivision(value.amount * scalar.numerator, scalar.denominator, options.rounding ?? defaultRounding),\n value.currency,\n );\n}\n\nexport function divide<C extends Currency>(\n value: Money<C>,\n divisor: string,\n options: { rounding?: RoundingMode } = {},\n): Money<C> {\n assertMoney(value);\n\n const scalar = decimal(divisor);\n\n if (scalar.numerator === 0n) throw new CoinsError('DIVISION_BY_ZERO', 'Cannot divide money by zero');\n\n const divisorMagnitude = scalar.numerator < 0n ? -scalar.numerator : scalar.numerator;\n const dividend = value.amount * scalar.denominator;\n const quotient = roundDivision(\n scalar.numerator < 0n ? -dividend : dividend,\n divisorMagnitude,\n options.rounding ?? defaultRounding,\n );\n\n return createMoney(quotient, value.currency);\n}\n\nexport function compare<C extends Currency>(left: Money<C>, right: Money<NoInfer<C>>): -1 | 0 | 1 {\n assertSameCurrency(left, right);\n\n return left.amount === right.amount ? 0 : left.amount < right.amount ? -1 : 1;\n}\n\nexport function clamp<C extends Currency>(\n value: Money<C>,\n options: { max: Money<NoInfer<C>>; min: Money<NoInfer<C>> },\n): Money<C> {\n if (compare(options.min, options.max) === 1) {\n throw new CoinsError('INVALID_RANGE', 'Clamp minimum cannot exceed maximum');\n }\n\n return compare(value, options.min) === -1 ? options.min : compare(value, options.max) === 1 ? options.max : value;\n}\n\nexport function abs<C extends Currency>(value: Money<C>): Money<C> {\n assertMoney(value);\n\n return createMoney(value.amount < 0n ? -value.amount : value.amount, value.currency);\n}\n\nexport function negate<C extends Currency>(value: Money<C>): Money<C> {\n assertMoney(value);\n\n return createMoney(-value.amount, value.currency);\n}\n\nexport function round<C extends Currency>(\n value: Money<C>,\n options: { fractionDigits: number; rounding?: RoundingMode },\n): Money<C> {\n assertMoney(value);\n\n const { fractionDigits, rounding = defaultRounding } = options;\n\n if (!Number.isInteger(fractionDigits) || fractionDigits < 0 || fractionDigits > value.currency.minorUnit) {\n throw new CoinsError('INVALID_ROUNDING', `fractionDigits must be an integer from 0 to ${value.currency.minorUnit}`);\n }\n\n const factor = 10n ** BigInt(value.currency.minorUnit - fractionDigits);\n\n return createMoney(roundDivision(value.amount, factor, rounding) * factor, value.currency);\n}\n\nexport function toDecimal(value: Money): string {\n assertMoney(value);\n\n return toDecimalString(value.amount, value.currency.minorUnit);\n}\n\nexport function createMoney<C extends Currency>(amount: bigint, currency: C): Money<C> {\n const value = Object.freeze({ amount, currency }) as Money<C>;\n\n canonicalMoney.add(value);\n\n return value;\n}\n\nexport function assertMoney(value: unknown): asserts value is Money {\n if (!isMoney(value)) {\n throw new CoinsError('INVALID_MONEY', 'Money must be a canonical @vielzeug/coins value');\n }\n}\n\nfunction assertSameCurrency(left: Money, right: Money): void {\n assertMoney(left);\n assertMoney(right);\n\n if (left.currency !== right.currency) {\n throw new CurrencyMismatchError(left.currency.code, right.currency.code);\n }\n}\n\nfunction assertCurrency(value: unknown): asserts value is Currency {\n if (!isCurrency(value)) throw new CoinsError('INVALID_CURRENCY', 'Money requires a registered currency');\n}\n\nfunction isPlainDataObject(value: unknown): value is Record<PropertyKey, unknown> {\n if (typeof value !== 'object' || value === null) return false;\n\n const prototype = Object.getPrototypeOf(value);\n\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isDataProperty(\n descriptor: PropertyDescriptor | undefined,\n): descriptor is PropertyDescriptor & { value: unknown } {\n return (\n descriptor !== undefined && 'value' in descriptor && descriptor.get === undefined && descriptor.set === undefined\n );\n}\n","import { decimal, lcm } from './_decimal';\nimport { isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { assertMoney, createMoney } from './money';\nimport type { Currency, Money } from './types';\n\nconst MAX_ALLOCATION_PARTS = 100_000;\n\nexport function sum<C extends Currency>(values: readonly Money<C>[]): Money<C>;\nexport function sum<C extends Currency>(values: Iterable<Money<C>>, options: { currency: C }): Money<C>;\nexport function sum<C extends Currency>(values: Iterable<Money<C>>, options?: { currency: C }): Money<C> {\n if (options && !isCurrency(options.currency)) {\n throw new CoinsError('INVALID_CURRENCY', 'sum() requires a canonical currency');\n }\n\n let amount = 0n;\n let currency: C | undefined = options?.currency;\n\n for (const value of values) {\n assertMoney(value);\n\n if (currency === undefined) {\n currency = value.currency;\n } else if (value.currency !== currency) {\n throw new CurrencyMismatchError(currency.code, value.currency.code);\n }\n\n amount += value.amount;\n }\n\n if (currency === undefined) throw new CoinsError('INVALID_MONEY', 'sum() of empty iterable requires { currency }');\n\n return createMoney(amount, currency);\n}\n\nexport function allocate<C extends Currency>(value: Money<C>, count: number): Money<C>[];\nexport function allocate<C extends Currency>(value: Money<C>, weights: readonly string[]): Money<C>[];\nexport function allocate<C extends Currency>(value: Money<C>, weightsOrCount: number | readonly string[]): Money<C>[] {\n assertMoney(value);\n\n if (typeof weightsOrCount === 'number') return allocateEvenly(value, weightsOrCount);\n\n if (!Array.isArray(weightsOrCount)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights must be an array');\n }\n if (weightsOrCount.length === 0) throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot be empty');\n if (weightsOrCount.length > MAX_ALLOCATION_PARTS) {\n throw new CoinsError('INVALID_ALLOCATION', `Allocation cannot exceed ${MAX_ALLOCATION_PARTS} parts`);\n }\n for (let index = 0; index < weightsOrCount.length; index++) {\n if (!Object.hasOwn(weightsOrCount, index)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot contain empty slots');\n }\n }\n\n const weights = weightsOrCount.map(decimal);\n\n if (weights.some((weight) => weight.numerator < 0n)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot be negative');\n }\n\n const commonDenominator = weights.reduce((result, weight) => lcm(result, weight.denominator), 1n);\n const scaledWeights = weights.map((weight) => weight.numerator * (commonDenominator / weight.denominator));\n const totalWeight = scaledWeights.reduce((result, weight) => result + weight, 0n);\n\n if (totalWeight === 0n)\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights must include a positive value');\n\n const sign = value.amount < 0n ? -1n : 1n;\n const absolute = value.amount < 0n ? -value.amount : value.amount;\n const shares = scaledWeights.map((weight) => (absolute * weight) / totalWeight);\n let remainder = absolute - shares.reduce((result, amount) => result + amount, 0n);\n const ranked = scaledWeights\n .map((weight, index) => ({ index, remainder: (absolute * weight) % totalWeight }))\n .sort((left, right) =>\n left.remainder === right.remainder ? left.index - right.index : left.remainder > right.remainder ? -1 : 1,\n );\n\n for (const entry of ranked) {\n if (remainder === 0n) break;\n\n shares[entry.index]! += 1n;\n remainder -= 1n;\n }\n\n return shares.map((amount) => createMoney(amount * sign, value.currency));\n}\n\nfunction allocateEvenly<C extends Currency>(value: Money<C>, countValue: number): Money<C>[] {\n if (!Number.isSafeInteger(countValue) || countValue < 1 || countValue > MAX_ALLOCATION_PARTS) {\n throw new CoinsError(\n 'INVALID_ALLOCATION',\n `Allocation count must be a positive safe integer no greater than ${MAX_ALLOCATION_PARTS}`,\n );\n }\n\n const count = BigInt(countValue);\n const sign = value.amount < 0n ? -1n : 1n;\n const absolute = value.amount < 0n ? -value.amount : value.amount;\n const base = absolute / count;\n const remainder = absolute % count;\n\n return Array.from({ length: countValue }, (_, index) =>\n createMoney((base + (BigInt(index) < remainder ? 1n : 0n)) * sign, value.currency),\n );\n}\n","import { decimal, roundDivision } from './_decimal';\nimport { isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { assertMoney, createMoney } from './money';\nimport type { Currency, ExchangeRate, Money, RoundingMode } from './types';\n\nconst canonicalRates = new WeakSet<object>();\n\nexport function exchangeRate<From extends Currency, To extends Currency>({\n from,\n to,\n value,\n}: {\n from: From;\n to: To;\n value: string;\n}): ExchangeRate<From, To> {\n if (!isCurrency(from) || !isCurrency(to))\n throw new CoinsError('INVALID_CURRENCY', 'Exchange rate requires registered currencies');\n\n const parsed = decimal(value);\n\n if (parsed.numerator <= 0n) throw new CoinsError('INVALID_DECIMAL', 'Exchange rates must be positive');\n\n const rate = Object.freeze({ from, to, value: parsed }) as ExchangeRate<From, To>;\n\n canonicalRates.add(rate);\n\n return rate;\n}\n\nexport function isExchangeRate(value: unknown): value is ExchangeRate {\n return typeof value === 'object' && value !== null && canonicalRates.has(value);\n}\n\nexport function exchange<From extends Currency, To extends Currency>(\n value: Money<From>,\n rate: ExchangeRate<From, To>,\n options: { rounding?: RoundingMode } = {},\n): Money<To> {\n assertMoney(value);\n\n if (!isExchangeRate(rate)) {\n throw new CoinsError('INVALID_EXCHANGE_RATE', 'Exchange requires a canonical exchange rate');\n }\n\n if (value.currency !== rate.from) throw new CurrencyMismatchError(value.currency.code, rate.from.code);\n\n const numerator = value.amount * rate.value.numerator * 10n ** BigInt(rate.to.minorUnit);\n const denominator = rate.value.denominator * 10n ** BigInt(rate.from.minorUnit);\n\n return createMoney(roundDivision(numerator, denominator, options.rounding ?? 'halfAwayFromZero'), rate.to);\n}\n","import { assertRoundingMode } from './_decimal';\nimport { CoinsError } from './errors';\nimport { assertMoney, toDecimal } from './money';\nimport type { FormatOptions, Money, MoneyFormatPart, RoundingMode } from './types';\n\nconst MAX_FRACTION_DIGITS = 20;\nconst defaultFormatRounding: RoundingMode = 'halfAwayFromZero';\nconst intlRoundingModes: Record<RoundingMode, Intl.NumberFormatOptions['roundingMode']> = {\n awayFromZero: 'expand',\n ceil: 'ceil',\n floor: 'floor',\n halfAwayFromZero: 'halfExpand',\n halfEven: 'halfEven',\n towardZero: 'trunc',\n};\n\nexport function format(value: Money, options: FormatOptions = {}): string {\n return formatParts(value, options)\n .map((part) => part.value)\n .join('');\n}\n\nexport function formatParts(value: Money, options: FormatOptions = {}): MoneyFormatPart[] {\n assertMoney(value);\n assertRoundingMode(options.rounding ?? defaultFormatRounding);\n\n const { maximum, minimum } = fractionDigits(value.currency.minorUnit, options);\n const style = options.style ?? 'symbol';\n\n try {\n const formatter = new Intl.NumberFormat(options.locale ?? 'en-US', {\n currency: value.currency.code,\n currencyDisplay: style,\n maximumFractionDigits: maximum,\n minimumFractionDigits: minimum,\n roundingMode: intlRoundingModes[options.rounding ?? defaultFormatRounding],\n style: 'currency',\n useGrouping: true,\n });\n\n return normalizeParts(formatter.formatToParts(toDecimal(value) as unknown as number));\n } catch (error) {\n if (error instanceof CoinsError) throw error;\n\n throw new CoinsError(\n 'FORMAT_ERROR',\n `Cannot format currency \"${value.currency.code}\" for locale \"${options.locale ?? 'en-US'}\"`,\n { cause: error },\n );\n }\n}\n\nfunction fractionDigits(scale: number, options: FormatOptions): { maximum: number; minimum: number } {\n const requestedMaximum = options.maximumFractionDigits;\n const requestedMinimum = options.minimumFractionDigits;\n\n validateFractionDigit('maximumFractionDigits', requestedMaximum);\n validateFractionDigit('minimumFractionDigits', requestedMinimum);\n\n const maximum = requestedMaximum ?? Math.max(scale, requestedMinimum ?? scale);\n const minimum = requestedMinimum ?? Math.min(scale, requestedMaximum ?? scale);\n\n if (minimum > maximum) {\n throw new CoinsError('FORMAT_ERROR', 'minimumFractionDigits cannot exceed maximumFractionDigits');\n }\n\n return { maximum, minimum };\n}\n\nfunction validateFractionDigit(name: string, value: number | undefined): void {\n if (value !== undefined && (!Number.isInteger(value) || value < 0 || value > MAX_FRACTION_DIGITS)) {\n throw new CoinsError(\n 'FORMAT_ERROR',\n `Fraction digits must be integers satisfying 0 ≤ minimum ≤ maximum ≤ ${MAX_FRACTION_DIGITS} (${name})`,\n );\n }\n}\n\nfunction normalizeParts(raw: Intl.NumberFormatPart[]): MoneyFormatPart[] {\n const parts: MoneyFormatPart[] = [];\n\n for (const part of raw) {\n if (part.type === 'integer' || part.type === 'group') {\n const previous = parts.at(-1);\n\n if (previous?.type === 'integer') {\n parts[parts.length - 1] = { type: 'integer', value: previous.value + part.value };\n } else {\n parts.push({ type: 'integer', value: part.value });\n }\n } else if (\n part.type === 'currency' ||\n part.type === 'decimal' ||\n part.type === 'fraction' ||\n part.type === 'literal' ||\n part.type === 'minusSign' ||\n part.type === 'plusSign'\n ) {\n parts.push({ type: part.type, value: part.value });\n } else {\n parts.push({ type: 'literal', value: part.value });\n }\n }\n\n return parts;\n}\n","import { assertMoney } from './money';\nimport type { Money, MoneyJSON } from './types';\n\nexport function toJSON(value: Money): MoneyJSON {\n assertMoney(value);\n\n return { amount: value.amount.toString(), currency: value.currency.code, unit: 'minor' };\n}\n"],"mappings":"A,mEAYA,IAAa,WAAb,cAAgC,KAAM,CACpC,KAEA,YAAY,EAAsB,EAAiB,EAAwB,CACzE,MAAMA,EAASC,CAAO,EACtB,KAAK,KAAOC,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,gCAAgCC,EAAS,OAAOC,EAAS,oBAAoB,EACxG,KAAK,SAAWD,EAChB,KAAK,SAAWC,CAClB,CACF,EAEA,SAAS,SAAS,EAAwB,CACxC,GAAI,CACF,OAAO,OAAOC,CAAK,CACrB,MAAQ,CACN,MAAO,eACT,CACF,CAEA,IAAa,qBAAb,cAA0C,UAAW,CACnD,MAEA,YAAY,EAAgB,CAC1B,MAAM,mBAAoB,0BAA0B,SAASA,CAAK,EAAE,EAAE,EACtE,KAAK,MAAQA,CACf,CACF,EC9CMC,EAAU,0BACVC,EAAqB,IACrBC,EAAqB,IACrBC,EAAiB,IAAI,IAAkB,CAC3C,eACA,OACA,QACA,mBACA,WACA,YACF,CAAC,EAED,SAAgB,mBAAmB,EAA+C,CAChF,GAAI,CAACA,EAAe,IAAIJ,CAAqB,EAC3C,MAAM,IAAI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