@stll/money 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,23 +1,10 @@
1
- //#region src/index.d.ts
1
+ //#region src/cents.d.ts
2
2
  /**
3
- * Branded monetary amounts and minor-unit billing arithmetic.
4
- *
5
- * Money in this codebase is stored and computed in minor units
6
- * ("cents" for USD/EUR, halere for CZK, etc.). The `CentsAmount`
7
- * brand prevents the canonical 100x bug where a major-unit value
8
- * (12.50 dollars) is silently mixed with minor-unit math (1250 cents).
3
+ * The minor-unit brand and its constructors.
9
4
  *
10
- * The brand lives here, in a shared package, so it threads end to end:
11
- * the same `CentsAmount` flows from a Drizzle column declared with
12
- * `.$type<CentsAmount>()`, across the API boundary (Eden infers the
13
- * brand from the handler's return type), into browser previews and back.
14
- * A plain `number` is not assignable to `CentsAmount`; mint one with
15
- * `cents()` after validating minor-unit input, or `unsafeCents()` at a
16
- * documented boundary.
17
- *
18
- * Currency-agnostic: the currency code lives alongside the amount in the
19
- * schema (e.g. invoices.currency); pairing them is the call site's
20
- * responsibility.
5
+ * Separate from `index.ts` because `format.ts` mints amounts too: the
6
+ * conversion helpers there return a `CentsAmount`, and a module the package
7
+ * entry re-exports cannot import back from that entry without a cycle.
21
8
  */
22
9
  declare const __cents: unique symbol;
23
10
  type CentsAmount = number & {
@@ -26,11 +13,14 @@ type CentsAmount = number & {
26
13
  /**
27
14
  * Construct a CentsAmount from a value already known to be in minor
28
15
  * units. Use at boundaries where the input is validated as an integer
29
- * minor-unit value (e.g. after Elysia `t.Integer({ minimum: 0 })` or
30
- * after parsing user input that has been multiplied by 100).
16
+ * minor-unit value (e.g. after Elysia `tMinorUnitAmount(...)` or after
17
+ * scaling a typed major-unit amount by the currency's exponent).
31
18
  *
32
- * Throws on non-integer input — money math at the minor-unit level must
33
- * be exact.
19
+ * SAFE integer, not merely integer: `Number.isInteger` is true for 2^53 and
20
+ * everything above it, where the spacing between representable doubles is
21
+ * larger than one minor unit, so `x + 1 === x` and a total silently stops
22
+ * moving. An amount that far out is a caller defect rather than a runtime
23
+ * condition, like a fractional one, so it panics the same way.
34
24
  */
35
25
  declare const cents: (value: number) => CentsAmount;
36
26
  /**
@@ -40,6 +30,81 @@ declare const cents: (value: number) => CentsAmount;
40
30
  * comment naming why the value is already a valid minor-unit integer.
41
31
  */
42
32
  declare const unsafeCents: (value: number) => CentsAmount;
33
+ //#endregion
34
+ //#region src/format.d.ts
35
+ /**
36
+ * How many minor units make a major one, for this currency: 100 for CZK, 1 for
37
+ * JPY, 1000 for KWD. It is a property of the currency and not of the reader, so
38
+ * the lookup is deliberately locale-independent.
39
+ *
40
+ * A malformed code makes the `Intl.NumberFormat` constructor throw, before any
41
+ * `?? 2` on its result could help, so the fallback has to wrap the call.
42
+ */
43
+ declare const currencyMinorUnitDigits: (currency: string) => number;
44
+ type ToMinorUnitsParams = {
45
+ /**
46
+ * The amount in major units: the decimal text a form holds, or a number.
47
+ * Text is preferred where the caller has it, because it is what the person
48
+ * typed rather than the nearest double to it.
49
+ */
50
+ amount: number | string;
51
+ currency: string;
52
+ };
53
+ /**
54
+ * A typed major-unit amount as the minor units the currency actually counts:
55
+ * 12.5 USD is 1250, 1500 JPY is 1500, 12.5 KWD is 12500.
56
+ *
57
+ * The scaling is decimal, not a float multiply. `1.005 * 100` is
58
+ * 100.49999999999999 in binary floating point, so `Math.round` of it is 100
59
+ * and a $1.005 line item silently loses a cent; the same shortfall appears at
60
+ * a different decimal for every currency. Splitting the text on the point and
61
+ * moving the digits instead keeps the amount the person typed: the kept
62
+ * fraction digits are appended to the whole part, and the first digit dropped
63
+ * decides a half-up carry on the magnitude.
64
+ *
65
+ * Rounding is still the point -- a typed amount carries more places than the
66
+ * currency has -- and it happens on digits, exactly. Text this cannot parse,
67
+ * and a result outside the safe integer range, are caller defects: gate the
68
+ * text with `isDecimalAmount` first.
69
+ */
70
+ declare const toMinorUnits: (params: ToMinorUnitsParams) => CentsAmount;
71
+ /**
72
+ * The same conversion for text nobody has vouched for yet: null when the text
73
+ * is not a decimal amount, and null when the scaled value would leave the safe
74
+ * integer range, where a total silently stops adding up.
75
+ *
76
+ * A form holds whatever was typed and has to be able to decline it. Everything
77
+ * past that gate calls `toMinorUnits`, which panics, because by then the
78
+ * decision has been made.
79
+ */
80
+ declare const tryToMinorUnits: ({ amount, currency }: ToMinorUnitsParams) => CentsAmount | null;
81
+ type ToMajorUnitsParams = {
82
+ amountCents: number;
83
+ currency: string;
84
+ };
85
+ /** The inverse: a stored amount as the major-unit number a person reads. */
86
+ declare const toMajorUnits: ({ amountCents, currency }: ToMajorUnitsParams) => number;
87
+ type FormatMoneyCentsParams = {
88
+ amountCents: number;
89
+ currency: string;
90
+ locale: string;
91
+ /**
92
+ * Digits to show, minimum and maximum alike. Defaults to the currency's own
93
+ * exponent; pass 0 for a rounded summary that has no room for decimals.
94
+ */
95
+ fractionDigits?: number;
96
+ };
97
+ /**
98
+ * Money is stored in minor units, and how many of them make a major one is a
99
+ * property of the currency. Ask the currency rather than assuming a hundred.
100
+ *
101
+ * A code `Intl` rejects falls back to the amount beside the raw code: a column
102
+ * showing "15.00 A1C" is wrong-looking data, which is the truth, where a thrown
103
+ * RangeError would take the whole board down with it.
104
+ */
105
+ declare const formatMoneyCents: ({ amountCents, currency, locale, fractionDigits }: FormatMoneyCentsParams) => string;
106
+ //#endregion
107
+ //#region src/index.d.ts
43
108
  type ProrateHourlyCentsInput = {
44
109
  billedMinutes: number;
45
110
  hourlyRateCents: CentsAmount;
@@ -134,4 +199,4 @@ declare class MoneyTotals {
134
199
  entries(): MoneyTotalsEntry[];
135
200
  }
136
201
  //#endregion
137
- export { ApplyMarkupCentsInput, CentsAmount, CurrencyCents, MoneyTotals, MoneyTotalsEntry, ProrateHourlyCentsInput, addCents, applyMarkupCents, cents, currencyCents, prorateHourlyCents, unsafeCents };
202
+ export { ApplyMarkupCentsInput, type CentsAmount, CurrencyCents, type FormatMoneyCentsParams, MoneyTotals, MoneyTotalsEntry, ProrateHourlyCentsInput, type ToMajorUnitsParams, type ToMinorUnitsParams, addCents, applyMarkupCents, cents, currencyCents, currencyMinorUnitDigits, formatMoneyCents, prorateHourlyCents, toMajorUnits, toMinorUnits, tryToMinorUnits, unsafeCents };
package/dist/index.js CHANGED
@@ -1,15 +1,26 @@
1
- //#region src/index.ts
1
+ import { Result, panic } from "better-result";
2
+ //#region src/cents.ts
3
+ /**
4
+ * The minor-unit brand and its constructors.
5
+ *
6
+ * Separate from `index.ts` because `format.ts` mints amounts too: the
7
+ * conversion helpers there return a `CentsAmount`, and a module the package
8
+ * entry re-exports cannot import back from that entry without a cycle.
9
+ */
2
10
  /**
3
11
  * Construct a CentsAmount from a value already known to be in minor
4
12
  * units. Use at boundaries where the input is validated as an integer
5
- * minor-unit value (e.g. after Elysia `t.Integer({ minimum: 0 })` or
6
- * after parsing user input that has been multiplied by 100).
13
+ * minor-unit value (e.g. after Elysia `tMinorUnitAmount(...)` or after
14
+ * scaling a typed major-unit amount by the currency's exponent).
7
15
  *
8
- * Throws on non-integer input — money math at the minor-unit level must
9
- * be exact.
16
+ * SAFE integer, not merely integer: `Number.isInteger` is true for 2^53 and
17
+ * everything above it, where the spacing between representable doubles is
18
+ * larger than one minor unit, so `x + 1 === x` and a total silently stops
19
+ * moving. An amount that far out is a caller defect rather than a runtime
20
+ * condition, like a fractional one, so it panics the same way.
10
21
  */
11
22
  const cents = (value) => {
12
- if (!Number.isInteger(value)) throw new TypeError(`cents(${value}): money values must be integer minor units`);
23
+ if (!Number.isSafeInteger(value)) return panic(`cents(${value}): money values must be safe integer minor units`);
13
24
  return value;
14
25
  };
15
26
  /**
@@ -19,6 +30,180 @@ const cents = (value) => {
19
30
  * comment naming why the value is already a valid minor-unit integer.
20
31
  */
21
32
  const unsafeCents = (value) => value;
33
+ //#endregion
34
+ //#region src/format.ts
35
+ /**
36
+ * Moving between a stored minor-unit amount and the major-unit number a
37
+ * person types, and rendering either as text.
38
+ *
39
+ * The brand keeps the arithmetic honest; this keeps the scale honest. Both
40
+ * live here because "how many minor units make a major one" is a property of
41
+ * the currency, and every surface that touches money has to answer it the
42
+ * same way — a workspace column header, a billing form, an invoice line, an
43
+ * export row.
44
+ *
45
+ * The locale is always a parameter. A package cannot read the reader's
46
+ * formatting locale, and one that guessed would render a number differently
47
+ * from the app around it.
48
+ */
49
+ /**
50
+ * Two, the ISO 4217 default, used when a stored code is one `Intl` will not
51
+ * accept. Validation at the API boundary keeps those out, but a row written
52
+ * before that constraint existed must still render rather than throw.
53
+ */
54
+ const DEFAULT_MINOR_UNIT_DIGITS = 2;
55
+ /**
56
+ * How many minor units make a major one, for this currency: 100 for CZK, 1 for
57
+ * JPY, 1000 for KWD. It is a property of the currency and not of the reader, so
58
+ * the lookup is deliberately locale-independent.
59
+ *
60
+ * A malformed code makes the `Intl.NumberFormat` constructor throw, before any
61
+ * `?? 2` on its result could help, so the fallback has to wrap the call.
62
+ */
63
+ const currencyMinorUnitDigits = (currency) => {
64
+ const resolved = Result.try(() => new Intl.NumberFormat("en", {
65
+ style: "currency",
66
+ currency
67
+ }).resolvedOptions().maximumFractionDigits);
68
+ if (resolved.isErr()) return DEFAULT_MINOR_UNIT_DIGITS;
69
+ return resolved.value ?? DEFAULT_MINOR_UNIT_DIGITS;
70
+ };
71
+ /** A decimal amount in major units: an optional sign, digits, an optional point. */
72
+ const DECIMAL_AMOUNT = /^(?<sign>[+-]?)(?<whole>\d*)(?:\.(?<fraction>\d*))?$/u;
73
+ /** Scientific notation, which `String(1e21)` and `String(1e-7)` both produce. */
74
+ const EXPONENT_AMOUNT = /^(?<sign>[+-]?)(?<whole>\d+)(?:\.(?<fraction>\d+))?[eE](?<exponent>[+-]?\d+)$/u;
75
+ /**
76
+ * The widest exponent a finite double prints with (`5e-324`, `1.8e308`).
77
+ * Text past it names no amount any currency stores, and expanding it would
78
+ * mean materialising that many zeros.
79
+ */
80
+ const MAX_EXPONENT_MAGNITUDE = 324;
81
+ const expandExponent = (text) => {
82
+ const groups = EXPONENT_AMOUNT.exec(text)?.groups;
83
+ if (!groups) return null;
84
+ const exponent = Number(groups["exponent"]);
85
+ if (Math.abs(exponent) > MAX_EXPONENT_MAGNITUDE) return null;
86
+ const sign = groups["sign"] ?? "";
87
+ const digits = `${groups["whole"] ?? ""}${groups["fraction"] ?? ""}`;
88
+ const point = (groups["whole"] ?? "").length + exponent;
89
+ if (point <= 0) return `${sign}0.${"0".repeat(-point)}${digits}`;
90
+ if (point >= digits.length) return `${sign}${digits}${"0".repeat(point - digits.length)}`;
91
+ return `${sign}${digits.slice(0, point)}.${digits.slice(point)}`;
92
+ };
93
+ /**
94
+ * The amount as decimal text, or null when it is not a decimal amount.
95
+ *
96
+ * A number is rendered by `String`, which produces the SHORTEST text that
97
+ * round-trips back to the same double. That is what makes the number path
98
+ * exact: the double nearest 1.005 prints as "1.005", which is the amount the
99
+ * person typed, where multiplying that double by 100 yields 100.49999999999999.
100
+ */
101
+ const decimalText = (amount) => {
102
+ if (typeof amount === "number") {
103
+ if (!Number.isFinite(amount)) return null;
104
+ const rendered = String(amount);
105
+ return rendered.includes("e") ? expandExponent(rendered) : rendered;
106
+ }
107
+ const trimmed = amount.trim();
108
+ return /[eE]/u.test(trimmed) ? expandExponent(trimmed) : trimmed;
109
+ };
110
+ /** The digits of a decimal amount, or null when the text is not one. */
111
+ const amountDigits = (amount) => {
112
+ const text = decimalText(amount);
113
+ const groups = text === null ? void 0 : DECIMAL_AMOUNT.exec(text)?.groups;
114
+ if (groups === void 0) return null;
115
+ const whole = groups["whole"] ?? "";
116
+ const fraction = groups["fraction"] ?? "";
117
+ if (`${whole}${fraction}`.length === 0) return null;
118
+ return {
119
+ sign: groups["sign"] ?? "",
120
+ whole,
121
+ fraction
122
+ };
123
+ };
124
+ /**
125
+ * A typed major-unit amount as the minor units the currency actually counts:
126
+ * 12.5 USD is 1250, 1500 JPY is 1500, 12.5 KWD is 12500.
127
+ *
128
+ * The scaling is decimal, not a float multiply. `1.005 * 100` is
129
+ * 100.49999999999999 in binary floating point, so `Math.round` of it is 100
130
+ * and a $1.005 line item silently loses a cent; the same shortfall appears at
131
+ * a different decimal for every currency. Splitting the text on the point and
132
+ * moving the digits instead keeps the amount the person typed: the kept
133
+ * fraction digits are appended to the whole part, and the first digit dropped
134
+ * decides a half-up carry on the magnitude.
135
+ *
136
+ * Rounding is still the point -- a typed amount carries more places than the
137
+ * currency has -- and it happens on digits, exactly. Text this cannot parse,
138
+ * and a result outside the safe integer range, are caller defects: gate the
139
+ * text with `isDecimalAmount` first.
140
+ */
141
+ const toMinorUnits = (params) => tryToMinorUnits(params) ?? panic(`toMinorUnits(${JSON.stringify(params.amount)}): not an amount ${params.currency} can store`);
142
+ /**
143
+ * The same conversion for text nobody has vouched for yet: null when the text
144
+ * is not a decimal amount, and null when the scaled value would leave the safe
145
+ * integer range, where a total silently stops adding up.
146
+ *
147
+ * A form holds whatever was typed and has to be able to decline it. Everything
148
+ * past that gate calls `toMinorUnits`, which panics, because by then the
149
+ * decision has been made.
150
+ */
151
+ const tryToMinorUnits = ({ amount, currency }) => {
152
+ const parsed = amountDigits(amount);
153
+ if (parsed === null) return null;
154
+ const digits = currencyMinorUnitDigits(currency);
155
+ const kept = parsed.fraction.slice(0, digits).padEnd(digits, "0");
156
+ const dropped = parsed.fraction.charAt(digits);
157
+ const magnitude = BigInt(`${parsed.whole || "0"}${kept}`) + (dropped >= "5" ? 1n : 0n);
158
+ const value = Number(parsed.sign === "-" ? -magnitude : magnitude);
159
+ return Number.isSafeInteger(value) ? cents(value) : null;
160
+ };
161
+ /** The inverse: a stored amount as the major-unit number a person reads. */
162
+ const toMajorUnits = ({ amountCents, currency }) => amountCents / 10 ** currencyMinorUnitDigits(currency);
163
+ /**
164
+ * Money is stored in minor units, and how many of them make a major one is a
165
+ * property of the currency. Ask the currency rather than assuming a hundred.
166
+ *
167
+ * A code `Intl` rejects falls back to the amount beside the raw code: a column
168
+ * showing "15.00 A1C" is wrong-looking data, which is the truth, where a thrown
169
+ * RangeError would take the whole board down with it.
170
+ */
171
+ const formatMoneyCents = ({ amountCents, currency, locale, fractionDigits }) => {
172
+ const major = toMajorUnits({
173
+ amountCents,
174
+ currency
175
+ });
176
+ const digits = fractionDigits ?? currencyMinorUnitDigits(currency);
177
+ const formatted = Result.try(() => new Intl.NumberFormat(locale, {
178
+ style: "currency",
179
+ currency,
180
+ minimumFractionDigits: digits,
181
+ maximumFractionDigits: digits
182
+ }).format(major));
183
+ return formatted.isErr() ? `${major.toFixed(digits)} ${currency}` : formatted.value;
184
+ };
185
+ //#endregion
186
+ //#region src/index.ts
187
+ /**
188
+ * Branded monetary amounts and minor-unit billing arithmetic.
189
+ *
190
+ * Money in this codebase is stored and computed in minor units
191
+ * ("cents" for USD/EUR, halere for CZK, etc.). The `CentsAmount`
192
+ * brand prevents the canonical 100x bug where a major-unit value
193
+ * (12.50 dollars) is silently mixed with minor-unit math (1250 cents).
194
+ *
195
+ * The brand lives in this package, so it threads end to end:
196
+ * the same `CentsAmount` flows from a Drizzle column declared with
197
+ * `.$type<CentsAmount>()`, across the API boundary (Eden infers the
198
+ * brand from the handler's return type), into browser previews and back.
199
+ * A plain `number` is not assignable to `CentsAmount`; mint one with
200
+ * `cents()` after validating minor-unit input, or `unsafeCents()` at a
201
+ * documented boundary.
202
+ *
203
+ * Currency-agnostic: the currency code lives alongside the amount in the
204
+ * schema (e.g. invoices.currency); pairing them is the call site's
205
+ * responsibility.
206
+ */
22
207
  const prorateHourlyCents = ({ billedMinutes, hourlyRateCents }) => {
23
208
  assertNonNegativeInteger("billedMinutes", billedMinutes);
24
209
  assertNonNegativeInteger("hourlyRateCents", hourlyRateCents);
@@ -30,7 +215,7 @@ const applyMarkupCents = ({ amountCents, markupPercent }) => {
30
215
  return cents(Math.floor((amountCents * (100 + markupPercent) + 50) / 100));
31
216
  };
32
217
  function assertNonNegativeInteger(name, value) {
33
- if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0) throw new TypeError(`${name} must be a finite non-negative integer`);
218
+ if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0) panic(`${name} must be a finite non-negative integer`);
34
219
  }
35
220
  /**
36
221
  * Construct a `CurrencyCents<C>` from a currency code and a minor-unit
@@ -39,7 +224,7 @@ function assertNonNegativeInteger(name, value) {
39
224
  * infers `CurrencyCents<"USD">`).
40
225
  */
41
226
  const currencyCents = (currency, amount) => {
42
- if (!currency) throw new TypeError("currencyCents(): currency must be a non-empty code");
227
+ if (!currency) return panic("currencyCents(): currency must be a non-empty code");
43
228
  return cents(amount);
44
229
  };
45
230
  /**
@@ -68,7 +253,7 @@ var MoneyTotals = class {
68
253
  #totals = /* @__PURE__ */ new Map();
69
254
  /** Add `amountCents` to the running total for `currency`. */
70
255
  add(currency, amountCents) {
71
- if (!currency) throw new TypeError("MoneyTotals.add(): currency must be a non-empty code");
256
+ if (!currency) panic("MoneyTotals.add(): currency must be a non-empty code");
72
257
  const running = this.#totals.get(currency) ?? cents(0);
73
258
  this.#totals.set(currency, cents(running + amountCents));
74
259
  }
@@ -86,4 +271,4 @@ var MoneyTotals = class {
86
271
  }
87
272
  };
88
273
  //#endregion
89
- export { MoneyTotals, addCents, applyMarkupCents, cents, currencyCents, prorateHourlyCents, unsafeCents };
274
+ export { MoneyTotals, addCents, applyMarkupCents, cents, currencyCents, currencyMinorUnitDigits, formatMoneyCents, prorateHourlyCents, toMajorUnits, toMinorUnits, tryToMinorUnits, unsafeCents };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stll/money",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Branded minor-unit monetary amounts and currency-safe billing arithmetic.",
5
5
  "keywords": [
6
6
  "billing",
@@ -42,12 +42,15 @@
42
42
  "typecheck": "bun ../../packages/scripts/src/tsc-native.ts --noEmit",
43
43
  "lint": "cd ../.. && bun --bun oxlint -c oxlint.config.ts --report-unused-disable-directives-severity=error --deny-warnings --type-aware packages/money",
44
44
  "lint:fix": "cd ../.. && bun --bun oxlint -c oxlint.config.ts --type-aware --fix packages/money",
45
- "format": "oxfmt .",
45
+ "format": "bun ../../scripts/run-oxfmt.ts .",
46
46
  "prepack": "bun run build"
47
47
  },
48
+ "dependencies": {
49
+ "better-result": "3.0.0"
50
+ },
48
51
  "devDependencies": {
49
52
  "@stll/typescript-config": "0.0.0",
50
- "@types/bun": "1.3.14",
53
+ "bun-types": "1.4.2",
51
54
  "tsdown": "0.22.14"
52
55
  },
53
56
  "main": "./dist/index.js",