@stripe/extensibility-sdk 0.22.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/LICENSE.md +19 -0
  2. package/dist/config-values/generate.cjs +262 -0
  3. package/dist/config-values/generate.d.ts +38 -0
  4. package/dist/config-values/generate.d.ts.map +1 -0
  5. package/dist/config-values/generate.js +232 -0
  6. package/dist/config-values/parse.d.ts +87 -0
  7. package/dist/config-values/parse.d.ts.map +1 -0
  8. package/dist/extensibility-sdk-alpha.d.ts +542 -0
  9. package/dist/extensibility-sdk-beta.d.ts +542 -0
  10. package/dist/extensibility-sdk-config-values-alpha.d.ts +27 -0
  11. package/dist/extensibility-sdk-config-values-beta.d.ts +27 -0
  12. package/dist/extensibility-sdk-config-values-internal.d.ts +118 -0
  13. package/dist/extensibility-sdk-config-values-public.d.ts +27 -0
  14. package/dist/extensibility-sdk-extensions-alpha.d.ts +1592 -0
  15. package/dist/extensibility-sdk-extensions-beta.d.ts +1592 -0
  16. package/dist/extensibility-sdk-extensions-internal.d.ts +1655 -0
  17. package/dist/extensibility-sdk-extensions-public.d.ts +1592 -0
  18. package/dist/extensibility-sdk-internal-alpha.d.ts +9 -0
  19. package/dist/extensibility-sdk-internal-beta.d.ts +9 -0
  20. package/dist/extensibility-sdk-internal-internal.d.ts +23 -0
  21. package/dist/extensibility-sdk-internal-public.d.ts +9 -0
  22. package/dist/extensibility-sdk-internal.d.ts +915 -0
  23. package/dist/extensibility-sdk-jsonschema-alpha.d.ts +3 -0
  24. package/dist/extensibility-sdk-jsonschema-beta.d.ts +3 -0
  25. package/dist/extensibility-sdk-jsonschema-internal.d.ts +15 -0
  26. package/dist/extensibility-sdk-jsonschema-public.d.ts +3 -0
  27. package/dist/extensibility-sdk-public.d.ts +542 -0
  28. package/dist/extensibility-sdk-stdlib-alpha.d.ts +531 -0
  29. package/dist/extensibility-sdk-stdlib-beta.d.ts +531 -0
  30. package/dist/extensibility-sdk-stdlib-internal.d.ts +904 -0
  31. package/dist/extensibility-sdk-stdlib-public.d.ts +531 -0
  32. package/dist/extensions/billing/bill/discount_calculation.d.ts +226 -0
  33. package/dist/extensions/billing/bill/discount_calculation.d.ts.map +1 -0
  34. package/dist/extensions/billing/bill/index.d.ts +2 -0
  35. package/dist/extensions/billing/bill/index.d.ts.map +1 -0
  36. package/dist/extensions/billing/customer_balance_application.d.ts +82 -0
  37. package/dist/extensions/billing/customer_balance_application.d.ts.map +1 -0
  38. package/dist/extensions/billing/index.d.ts +8 -0
  39. package/dist/extensions/billing/index.d.ts.map +1 -0
  40. package/dist/extensions/billing/invoice_collection_setting.d.ts +117 -0
  41. package/dist/extensions/billing/invoice_collection_setting.d.ts.map +1 -0
  42. package/dist/extensions/billing/prorations.d.ts +222 -0
  43. package/dist/extensions/billing/prorations.d.ts.map +1 -0
  44. package/dist/extensions/billing/recurring_billing_item_handling.d.ts +326 -0
  45. package/dist/extensions/billing/recurring_billing_item_handling.d.ts.map +1 -0
  46. package/dist/extensions/billing/types.d.ts +33 -0
  47. package/dist/extensions/billing/types.d.ts.map +1 -0
  48. package/dist/extensions/context.d.ts +9 -0
  49. package/dist/extensions/context.d.ts.map +1 -0
  50. package/dist/extensions/core/index.d.ts +3 -0
  51. package/dist/extensions/core/index.d.ts.map +1 -0
  52. package/dist/extensions/core/workflows/custom_action.d.ts +142 -0
  53. package/dist/extensions/core/workflows/custom_action.d.ts.map +1 -0
  54. package/dist/extensions/core/workflows/index.d.ts +2 -0
  55. package/dist/extensions/core/workflows/index.d.ts.map +1 -0
  56. package/dist/extensions/extend/index.d.ts +3 -0
  57. package/dist/extensions/extend/index.d.ts.map +1 -0
  58. package/dist/extensions/extend/workflows/custom_action.d.ts +142 -0
  59. package/dist/extensions/extend/workflows/custom_action.d.ts.map +1 -0
  60. package/dist/extensions/extend/workflows/index.d.ts +2 -0
  61. package/dist/extensions/extend/workflows/index.d.ts.map +1 -0
  62. package/dist/extensions/index.cjs +2356 -0
  63. package/dist/extensions/index.d.ts +9 -0
  64. package/dist/extensions/index.d.ts.map +1 -0
  65. package/dist/extensions/index.js +2435 -0
  66. package/dist/extensions/registry.d.ts +19 -0
  67. package/dist/extensions/registry.d.ts.map +1 -0
  68. package/dist/extensions/types.d.ts +10 -0
  69. package/dist/extensions/types.d.ts.map +1 -0
  70. package/dist/index.cjs +1519 -0
  71. package/dist/index.d.ts +12 -0
  72. package/dist/index.d.ts.map +1 -0
  73. package/dist/index.js +1460 -0
  74. package/dist/internal.cjs +156 -0
  75. package/dist/internal.d.ts +3 -0
  76. package/dist/internal.d.ts.map +1 -0
  77. package/dist/internal.js +128 -0
  78. package/dist/jsonschema.cjs +18 -0
  79. package/dist/jsonschema.d.ts +2 -0
  80. package/dist/jsonschema.d.ts.map +1 -0
  81. package/dist/jsonschema.js +0 -0
  82. package/dist/stdlib/brand.d.ts +27 -0
  83. package/dist/stdlib/brand.d.ts.map +1 -0
  84. package/dist/stdlib/decimal.d.ts +324 -0
  85. package/dist/stdlib/decimal.d.ts.map +1 -0
  86. package/dist/stdlib/extension-method.d.ts +27 -0
  87. package/dist/stdlib/extension-method.d.ts.map +1 -0
  88. package/dist/stdlib/generated.d.ts +15 -0
  89. package/dist/stdlib/generated.d.ts.map +1 -0
  90. package/dist/stdlib/index.cjs +1519 -0
  91. package/dist/stdlib/index.d.ts +18 -0
  92. package/dist/stdlib/index.d.ts.map +1 -0
  93. package/dist/stdlib/index.js +1460 -0
  94. package/dist/stdlib/refs.d.ts +62 -0
  95. package/dist/stdlib/refs.d.ts.map +1 -0
  96. package/dist/stdlib/scalars.d.ts +141 -0
  97. package/dist/stdlib/scalars.d.ts.map +1 -0
  98. package/dist/stdlib/transform-strategies.d.ts +74 -0
  99. package/dist/stdlib/transform-strategies.d.ts.map +1 -0
  100. package/dist/stdlib/transforms.d.ts +97 -0
  101. package/dist/stdlib/transforms.d.ts.map +1 -0
  102. package/dist/stdlib/type-utils.d.ts +9 -0
  103. package/dist/stdlib/type-utils.d.ts.map +1 -0
  104. package/dist/stdlib/types.d.ts +281 -0
  105. package/dist/stdlib/types.d.ts.map +1 -0
  106. package/dist/stdlib/utils.d.ts +7 -0
  107. package/dist/stdlib/utils.d.ts.map +1 -0
  108. package/dist/tsconfig.build.tsbuildinfo +1 -0
  109. package/package.json +111 -0
  110. package/tslibs/5.9.3/lib.es2022.egress.d.ts +4328 -0
  111. package/tslibs/5.9.3/lib.es2022.restricted.d.ts +4067 -0
  112. package/tslibs/lib.egress.globals.d.ts +112 -0
  113. package/tslibs/lib.restricted.globals.d.ts +1 -0
@@ -0,0 +1,1460 @@
1
+ // src/stdlib/scalars.ts
2
+ import "@formspec/core";
3
+ function roundToInteger(value, direction) {
4
+ switch (direction) {
5
+ case "ceil":
6
+ return Math.ceil(value);
7
+ case "floor":
8
+ return Math.floor(value);
9
+ case "round-down":
10
+ return Math.trunc(value);
11
+ case "round-up":
12
+ return value >= 0 ? Math.ceil(value) : Math.floor(value);
13
+ case "half-up":
14
+ return value >= 0 ? Math.floor(value + 0.5) : Math.ceil(value - 0.5);
15
+ default: {
16
+ const _exhaustive = direction;
17
+ throw new Error(`Unknown rounding direction: ${String(_exhaustive)}`);
18
+ }
19
+ }
20
+ }
21
+ var Integer = {
22
+ /**
23
+ * Type guard that narrows a `number` to {@link (Integer:type)}.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * const n: number = getCount();
28
+ * if (Integer.is(n)) {
29
+ * // n is Integer here
30
+ * config.retryCount = n;
31
+ * }
32
+ * ```
33
+ * @public
34
+ */
35
+ is: (value) => Number.isInteger(value),
36
+ /**
37
+ * Coerces a number to an {@link (Integer:type)} by rounding.
38
+ * Throws if the value is not finite.
39
+ *
40
+ * @example
41
+ * ```ts
42
+ * const price = 9.99;
43
+ * const rounded = Integer.from(price, 'floor'); // 9
44
+ * const ceiled = Integer.from(price, 'ceil'); // 10
45
+ * ```
46
+ * @public
47
+ */
48
+ from: (value, rounding) => {
49
+ if (!Number.isFinite(value)) {
50
+ throw new Error(`Cannot round non-finite value ${String(value)} to an integer`);
51
+ }
52
+ return roundToInteger(value, rounding);
53
+ }
54
+ };
55
+ var PositiveInteger = {
56
+ /**
57
+ * Type guard that narrows a `number` to {@link (PositiveInteger:type)}.
58
+ *
59
+ * @example
60
+ * ```ts
61
+ * const n: number = getRetryCount();
62
+ * if (PositiveInteger.is(n)) {
63
+ * // n is PositiveInteger here
64
+ * config.maxRetries = n;
65
+ * }
66
+ * ```
67
+ * @public
68
+ */
69
+ is: (value) => Number.isInteger(value) && value >= 0,
70
+ /**
71
+ * Coerces a number to a {@link (PositiveInteger:type)} by rounding.
72
+ * Throws if the value is not finite or the rounded result is negative.
73
+ *
74
+ * @example
75
+ * ```ts
76
+ * const ratio = 2.7;
77
+ * const count = PositiveInteger.from(ratio, 'floor'); // 2
78
+ * ```
79
+ * @public
80
+ */
81
+ from: (value, rounding) => {
82
+ if (!Number.isFinite(value)) {
83
+ throw new Error(`Cannot round non-finite value ${String(value)} to an integer`);
84
+ }
85
+ const rounded = roundToInteger(value, rounding) || 0;
86
+ if (rounded < 0) {
87
+ throw new Error(
88
+ `Value ${String(value)} rounds to ${String(rounded)}, which is negative`
89
+ );
90
+ }
91
+ return rounded;
92
+ }
93
+ };
94
+ var StreetAddress = {
95
+ create: (address) => {
96
+ return address;
97
+ }
98
+ };
99
+ var Timestamp = {
100
+ create: (value) => {
101
+ return value;
102
+ }
103
+ };
104
+
105
+ // src/stdlib/refs.ts
106
+ var Ref = {
107
+ create: (step) => {
108
+ return {
109
+ type: step.object,
110
+ id: step.id
111
+ };
112
+ }
113
+ };
114
+
115
+ // src/stdlib/decimal.ts
116
+ var PLAIN_NOTATION_DIGIT_LIMIT = 30;
117
+ var DecimalRoundingPresets = Object.freeze({
118
+ "ubb-usage-count": Object.freeze({
119
+ mode: "significant-figures",
120
+ value: 15
121
+ }),
122
+ "v1-api": Object.freeze({
123
+ mode: "decimal-places",
124
+ value: 12
125
+ })
126
+ });
127
+ var DEFAULT_DIV_PRECISION = 34;
128
+ var IMPLICIT_DECIMAL_COERCION_ERROR = "Implicit Decimal coercion is not allowed; use .add(), .sub(), .mul(), .div(), .toString(), or .toNumber() explicitly.";
129
+ var MAX_EXPONENT = Number.MAX_SAFE_INTEGER;
130
+ var DECIMAL_BRAND = /* @__PURE__ */ Symbol.for(
131
+ "stripe.apps-extensibility-sdk.Decimal"
132
+ );
133
+ var DecimalImpl = class _DecimalImpl {
134
+ /** @internal */
135
+ [DECIMAL_BRAND] = true;
136
+ /** @internal */
137
+ #coefficient;
138
+ /** @internal */
139
+ #exponent;
140
+ /**
141
+ * Construct and normalise a decimal value.
142
+ *
143
+ * @param coefficient - The unscaled integer value.
144
+ * @param exponent - The power-of-ten scale factor.
145
+ *
146
+ * @internal
147
+ */
148
+ constructor(coefficient, exponent) {
149
+ const [normalizedCoef, normalizedExp] = _DecimalImpl.normalize(coefficient, exponent);
150
+ this.#coefficient = normalizedCoef;
151
+ this.#exponent = normalizedExp;
152
+ Object.freeze(this);
153
+ }
154
+ /**
155
+ * Strip trailing zeros from `coefficient`, incrementing `exponent`
156
+ * for each zero removed. Zero always normalises to `(0n, 0)`.
157
+ *
158
+ * @param coefficient - Raw coefficient before normalisation.
159
+ * @param exponent - Raw exponent before normalisation.
160
+ * @returns A `[coefficient, exponent]` tuple with trailing zeros removed.
161
+ *
162
+ * @internal
163
+ */
164
+ static normalize(coefficient, exponent) {
165
+ if (coefficient === 0n) {
166
+ return [0n, 0];
167
+ }
168
+ let coef = coefficient;
169
+ let exp = exponent;
170
+ while (coef !== 0n && coef % 10n === 0n) {
171
+ coef = coef / 10n;
172
+ exp++;
173
+ }
174
+ return [coef, exp];
175
+ }
176
+ /**
177
+ * Apply rounding to the result of an integer division.
178
+ *
179
+ * @remarks
180
+ * BigInt division truncates toward zero. This helper inspects the
181
+ * `remainder` to decide whether to adjust the truncated `quotient`
182
+ * by ±1 according to the chosen {@link RoundDirection}.
183
+ *
184
+ * The rounding direction is derived from the signs of `remainder`
185
+ * and `divisor`: when they agree the exact fractional part is
186
+ * positive (the truncation point is below the true value, so +1
187
+ * rounds to nearest); when they disagree the fractional part is
188
+ * negative (−1 rounds to nearest).
189
+ *
190
+ * @param quotient - Truncated integer quotient (`dividend / divisor`).
191
+ * @param remainder - Division remainder (`dividend % divisor`).
192
+ * @param divisor - The divisor used in the division.
193
+ * @param direction - The rounding strategy to apply.
194
+ * @returns The rounded quotient.
195
+ *
196
+ * @internal
197
+ */
198
+ static roundDivision(quotient, remainder, divisor, direction) {
199
+ if (remainder === 0n) {
200
+ return quotient;
201
+ }
202
+ if (direction === "round-down") {
203
+ return quotient;
204
+ }
205
+ const roundDir = remainder > 0n === divisor > 0n ? 1n : -1n;
206
+ if (direction === "round-up") {
207
+ return quotient + roundDir;
208
+ }
209
+ if (direction === "ceil") {
210
+ return roundDir === 1n ? quotient + 1n : quotient;
211
+ }
212
+ if (direction === "floor") {
213
+ return roundDir === -1n ? quotient - 1n : quotient;
214
+ }
215
+ const absRemainder = remainder < 0n ? -remainder : remainder;
216
+ const absDivisor = divisor < 0n ? -divisor : divisor;
217
+ const doubled = absRemainder * 2n;
218
+ const cmp = doubled === absDivisor ? 0 : doubled < absDivisor ? -1 : 1;
219
+ if (cmp < 0) {
220
+ return quotient;
221
+ }
222
+ if (cmp > 0) {
223
+ return quotient + roundDir;
224
+ }
225
+ if (direction === "half-up") {
226
+ return quotient + roundDir;
227
+ }
228
+ if (direction === "half-down") {
229
+ return quotient;
230
+ }
231
+ if (quotient % 2n === 0n) {
232
+ return quotient;
233
+ } else {
234
+ return quotient + roundDir;
235
+ }
236
+ }
237
+ // -------------------------------------------------------------------
238
+ // Arithmetic
239
+ // -------------------------------------------------------------------
240
+ /**
241
+ * Return the sum of this value and `other`.
242
+ *
243
+ * @param other - The addend.
244
+ * @returns A new {@link Decimal} equal to `this + other`.
245
+ *
246
+ * @public
247
+ */
248
+ add(other) {
249
+ const otherImpl = toImpl(other);
250
+ if (this.#exponent === otherImpl.#exponent) {
251
+ return toDecimal(
252
+ new _DecimalImpl(this.#coefficient + otherImpl.#coefficient, this.#exponent)
253
+ );
254
+ }
255
+ if (this.#exponent < otherImpl.#exponent) {
256
+ const scale = 10n ** BigInt(otherImpl.#exponent - this.#exponent);
257
+ return toDecimal(
258
+ new _DecimalImpl(
259
+ this.#coefficient + otherImpl.#coefficient * scale,
260
+ this.#exponent
261
+ )
262
+ );
263
+ } else {
264
+ const scale = 10n ** BigInt(this.#exponent - otherImpl.#exponent);
265
+ return toDecimal(
266
+ new _DecimalImpl(
267
+ this.#coefficient * scale + otherImpl.#coefficient,
268
+ otherImpl.#exponent
269
+ )
270
+ );
271
+ }
272
+ }
273
+ /**
274
+ * Return the difference of this value and `other`.
275
+ *
276
+ * @param other - The subtrahend.
277
+ * @returns A new {@link Decimal} equal to `this - other`.
278
+ *
279
+ * @public
280
+ */
281
+ sub(other) {
282
+ const otherImpl = toImpl(other);
283
+ if (this.#exponent === otherImpl.#exponent) {
284
+ return toDecimal(
285
+ new _DecimalImpl(this.#coefficient - otherImpl.#coefficient, this.#exponent)
286
+ );
287
+ }
288
+ if (this.#exponent < otherImpl.#exponent) {
289
+ const scale = 10n ** BigInt(otherImpl.#exponent - this.#exponent);
290
+ return toDecimal(
291
+ new _DecimalImpl(
292
+ this.#coefficient - otherImpl.#coefficient * scale,
293
+ this.#exponent
294
+ )
295
+ );
296
+ } else {
297
+ const scale = 10n ** BigInt(this.#exponent - otherImpl.#exponent);
298
+ return toDecimal(
299
+ new _DecimalImpl(
300
+ this.#coefficient * scale - otherImpl.#coefficient,
301
+ otherImpl.#exponent
302
+ )
303
+ );
304
+ }
305
+ }
306
+ /**
307
+ * Return the product of this value and `other`.
308
+ *
309
+ * @param other - The multiplicand.
310
+ * @returns A new {@link Decimal} equal to `this × other`.
311
+ *
312
+ * @public
313
+ */
314
+ mul(other) {
315
+ const otherImpl = toImpl(other);
316
+ return toDecimal(
317
+ new _DecimalImpl(
318
+ this.#coefficient * otherImpl.#coefficient,
319
+ this.#exponent + otherImpl.#exponent
320
+ )
321
+ );
322
+ }
323
+ /**
324
+ * Return the quotient of this value divided by `other`.
325
+ *
326
+ * @remarks
327
+ * Division scales the dividend to produce `precision` decimal digits
328
+ * in the result, then applies integer division and rounds the
329
+ * remainder according to `direction`.
330
+ *
331
+ * Division requires explicit rounding control — no invisible defaults
332
+ * in financial code. For full precision use {@link DEFAULT_DIV_PRECISION}
333
+ * (34, matching the IEEE 754 decimal128 coefficient size).
334
+ *
335
+ * @example
336
+ * ```ts
337
+ * Decimal.from('1').div(Decimal.from('3'), 5, 'half-up'); // "0.33333"
338
+ * Decimal.from('5').div(Decimal.from('2'), 0, 'half-up'); // "3"
339
+ * Decimal.from('5').div(Decimal.from('2'), 0, 'half-even'); // "2"
340
+ * ```
341
+ *
342
+ * @param other - The divisor. Must not be zero.
343
+ * @param precision - Maximum number of decimal digits in the result.
344
+ * @param direction - How to round when the exact quotient cannot
345
+ * be represented at the requested precision.
346
+ * @returns A new {@link Decimal} equal to `this ÷ other`, rounded to
347
+ * `precision` decimal places.
348
+ * @throws Error if `other` is zero.
349
+ * @throws Error if `precision` is negative or non-integer.
350
+ *
351
+ * @public
352
+ */
353
+ div(other, precision, direction) {
354
+ if (precision < 0 || !Number.isInteger(precision)) {
355
+ throw new Error("precision must be a non-negative integer");
356
+ }
357
+ const otherImpl = toImpl(other);
358
+ if (otherImpl.#coefficient === 0n) {
359
+ throw new Error("Division by zero");
360
+ }
361
+ const scale = this.#exponent - otherImpl.#exponent + precision;
362
+ let quotient;
363
+ let remainder;
364
+ let roundingDivisor;
365
+ if (scale >= 0) {
366
+ const scaledDividend = this.#coefficient * 10n ** BigInt(scale);
367
+ quotient = scaledDividend / otherImpl.#coefficient;
368
+ remainder = scaledDividend % otherImpl.#coefficient;
369
+ roundingDivisor = otherImpl.#coefficient;
370
+ } else {
371
+ const scaledDivisor = otherImpl.#coefficient * 10n ** BigInt(-scale);
372
+ quotient = this.#coefficient / scaledDivisor;
373
+ remainder = this.#coefficient % scaledDivisor;
374
+ roundingDivisor = scaledDivisor;
375
+ }
376
+ const roundedQuotient = _DecimalImpl.roundDivision(
377
+ quotient,
378
+ remainder,
379
+ roundingDivisor,
380
+ direction
381
+ );
382
+ return toDecimal(new _DecimalImpl(roundedQuotient, -precision));
383
+ }
384
+ // -------------------------------------------------------------------
385
+ // Comparison
386
+ // -------------------------------------------------------------------
387
+ /**
388
+ * Three-way comparison of this value with `other`.
389
+ *
390
+ * @example
391
+ * ```ts
392
+ * const a = Decimal.from('1.5');
393
+ * const b = Decimal.from('2');
394
+ * a.cmp(b); // -1
395
+ * b.cmp(a); // 1
396
+ * a.cmp(a); // 0
397
+ * ```
398
+ *
399
+ * @param other - The value to compare against.
400
+ * @returns `-1` if `this < other`, `0` if equal, `1` if `this > other`.
401
+ *
402
+ * @public
403
+ */
404
+ cmp(other) {
405
+ const otherImpl = toImpl(other);
406
+ if (this.#exponent === otherImpl.#exponent) {
407
+ if (this.#coefficient < otherImpl.#coefficient) return -1;
408
+ if (this.#coefficient > otherImpl.#coefficient) return 1;
409
+ return 0;
410
+ }
411
+ if (this.#exponent < otherImpl.#exponent) {
412
+ const scale = 10n ** BigInt(otherImpl.#exponent - this.#exponent);
413
+ const scaledOther = otherImpl.#coefficient * scale;
414
+ if (this.#coefficient < scaledOther) return -1;
415
+ if (this.#coefficient > scaledOther) return 1;
416
+ return 0;
417
+ } else {
418
+ const scale = 10n ** BigInt(this.#exponent - otherImpl.#exponent);
419
+ const scaledThis = this.#coefficient * scale;
420
+ if (scaledThis < otherImpl.#coefficient) return -1;
421
+ if (scaledThis > otherImpl.#coefficient) return 1;
422
+ return 0;
423
+ }
424
+ }
425
+ /**
426
+ * Return `true` if this value is numerically equal to `other`.
427
+ *
428
+ * @param other - The value to compare against.
429
+ * @returns `true` if `this === other` in value, `false` otherwise.
430
+ *
431
+ * @public
432
+ */
433
+ eq(other) {
434
+ return this.cmp(other) === 0;
435
+ }
436
+ /**
437
+ * Return `true` if this value is strictly less than `other`.
438
+ *
439
+ * @param other - The value to compare against.
440
+ * @returns `true` if `this < other`, `false` otherwise.
441
+ *
442
+ * @public
443
+ */
444
+ lt(other) {
445
+ return this.cmp(other) === -1;
446
+ }
447
+ /**
448
+ * Return `true` if this value is less than or equal to `other`.
449
+ *
450
+ * @param other - The value to compare against.
451
+ * @returns `true` if `this ≤ other`, `false` otherwise.
452
+ *
453
+ * @public
454
+ */
455
+ lte(other) {
456
+ return this.cmp(other) <= 0;
457
+ }
458
+ /**
459
+ * Return `true` if this value is strictly greater than `other`.
460
+ *
461
+ * @param other - The value to compare against.
462
+ * @returns `true` if `this > other`, `false` otherwise.
463
+ *
464
+ * @public
465
+ */
466
+ gt(other) {
467
+ return this.cmp(other) === 1;
468
+ }
469
+ /**
470
+ * Return `true` if this value is greater than or equal to `other`.
471
+ *
472
+ * @param other - The value to compare against.
473
+ * @returns `true` if `this ≥ other`, `false` otherwise.
474
+ *
475
+ * @public
476
+ */
477
+ gte(other) {
478
+ return this.cmp(other) >= 0;
479
+ }
480
+ // -------------------------------------------------------------------
481
+ // Predicates
482
+ // -------------------------------------------------------------------
483
+ /**
484
+ * Return `true` if this value is exactly zero.
485
+ *
486
+ * @returns `true` if the value is zero, `false` otherwise.
487
+ *
488
+ * @public
489
+ */
490
+ isZero() {
491
+ return this.#coefficient === 0n;
492
+ }
493
+ /**
494
+ * Return `true` if this value is strictly less than zero.
495
+ *
496
+ * @returns `true` if negative, `false` if zero or positive.
497
+ *
498
+ * @public
499
+ */
500
+ isNegative() {
501
+ return this.#coefficient < 0n;
502
+ }
503
+ /**
504
+ * Return `true` if this value is strictly greater than zero.
505
+ *
506
+ * @returns `true` if positive, `false` if zero or negative.
507
+ *
508
+ * @public
509
+ */
510
+ isPositive() {
511
+ return this.#coefficient > 0n;
512
+ }
513
+ // -------------------------------------------------------------------
514
+ // Unary operations
515
+ // -------------------------------------------------------------------
516
+ /**
517
+ * Return the additive inverse of this value.
518
+ *
519
+ * @returns A new {@link Decimal} equal to `-this`.
520
+ *
521
+ * @public
522
+ */
523
+ neg() {
524
+ return toDecimal(new _DecimalImpl(-this.#coefficient, this.#exponent));
525
+ }
526
+ /**
527
+ * Return the absolute value.
528
+ *
529
+ * @returns A new {@link Decimal} equal to `|this|`. If this value is
530
+ * already non-negative, returns `this` (no allocation).
531
+ *
532
+ * @public
533
+ */
534
+ abs() {
535
+ if (this.#coefficient < 0n) {
536
+ return toDecimal(new _DecimalImpl(-this.#coefficient, this.#exponent));
537
+ }
538
+ return toDecimal(this);
539
+ }
540
+ // -------------------------------------------------------------------
541
+ // Rounding
542
+ // -------------------------------------------------------------------
543
+ /**
544
+ * Round this value to a specified precision.
545
+ *
546
+ * @remarks
547
+ * **Rounding directions** (IEEE 754-2019 §4.3):
548
+ *
549
+ * | Direction | Behavior |
550
+ * | -------------- | ---------------------------------------------- |
551
+ * | `'ceil'` | 1.1→2, -1.1→-1, 1.0→1 (toward +∞) |
552
+ * | `'floor'` | 1.9→1, -1.1→-2, 1.0→1 (toward -∞) |
553
+ * | `'round-down'` | 1.9→1, -1.9→-1 (toward zero / truncate) |
554
+ * | `'round-up'` | 1.1→2, -1.1→-2 (away from zero) |
555
+ * | `'half-up'` | 0.5→1, 1.5→2, -0.5→-1 (ties away from zero) |
556
+ * | `'half-down'` | 0.5→0, 1.5→1, -0.5→0 (ties toward zero) |
557
+ * | `'half-even'` | 0.5→0, 1.5→2, 2.5→2, 3.5→4 (ties to even) |
558
+ *
559
+ * **Precision** is specified as a {@link DecimalRoundingOptions} object
560
+ * or a built-in preset name from {@link DecimalRoundingPresets}:
561
+ *
562
+ * @example
563
+ * ```ts
564
+ * // Using a preset
565
+ * amount.round('half-even', 'v1-api');
566
+ *
567
+ * // Using explicit options
568
+ * amount.round('half-even', { mode: 'decimal-places', value: 2 });
569
+ * amount.round('half-up', { mode: 'significant-figures', value: 4 });
570
+ * ```
571
+ *
572
+ * @param direction - How to round.
573
+ * @param options - A {@link DecimalRoundingOptions} object or key of `typeof DecimalRoundingPresets`.
574
+ * @returns A new {@link Decimal} rounded to the specified precision.
575
+ * @throws Error if `options.value` is negative or non-integer.
576
+ * @throws Error if the preset name is not recognized.
577
+ *
578
+ * @public
579
+ */
580
+ round(direction, options) {
581
+ if (typeof options === "string") {
582
+ if (!Object.hasOwn(DecimalRoundingPresets, options)) {
583
+ throw new Error(`Unknown rounding preset: "${options}"`);
584
+ }
585
+ return this.#roundWithOptions(direction, DecimalRoundingPresets[options]);
586
+ }
587
+ return this.#roundWithOptions(direction, options);
588
+ }
589
+ /**
590
+ * Apply resolved {@link DecimalRoundingOptions} to this value.
591
+ *
592
+ * @param direction - How to round.
593
+ * @param resolved - Already-resolved options (never a preset name).
594
+ * @returns A new {@link Decimal} rounded to the specified precision.
595
+ *
596
+ * @internal
597
+ */
598
+ #roundWithOptions(direction, resolved) {
599
+ if (resolved.value < 0 || !Number.isInteger(resolved.value)) {
600
+ throw new Error("DecimalRoundingOptions.value must be a non-negative integer");
601
+ }
602
+ if (resolved.mode === "decimal-places") {
603
+ const fixed = this.toFixed(resolved.value, direction);
604
+ return Decimal.from(fixed);
605
+ }
606
+ if (this.#coefficient === 0n) {
607
+ return toDecimal(this);
608
+ }
609
+ const coeffStr = this.#coefficient < 0n ? (-this.#coefficient).toString() : this.#coefficient.toString();
610
+ const currentSigFigs = coeffStr.length;
611
+ if (resolved.value === 0) {
612
+ return Decimal.zero;
613
+ }
614
+ if (currentSigFigs <= resolved.value) {
615
+ return toDecimal(this);
616
+ }
617
+ const digitsToTrim = currentSigFigs - resolved.value;
618
+ const divisor = 10n ** BigInt(digitsToTrim);
619
+ const quotient = this.#coefficient / divisor;
620
+ const remainder = this.#coefficient % divisor;
621
+ const rounded = _DecimalImpl.roundDivision(quotient, remainder, divisor, direction);
622
+ return toDecimal(new _DecimalImpl(rounded, this.#exponent + digitsToTrim));
623
+ }
624
+ // -------------------------------------------------------------------
625
+ // Conversion / serialisation
626
+ // -------------------------------------------------------------------
627
+ /**
628
+ * Return a human-readable string representation.
629
+ *
630
+ * @remarks
631
+ * Plain notation for values whose digit count is at most 30, and
632
+ * scientific notation (`1.23E+40`) for larger values. Trailing zeros
633
+ * are never present because the internal representation is normalised.
634
+ *
635
+ * @public
636
+ */
637
+ toString() {
638
+ if (this.#coefficient === 0n) {
639
+ return "0";
640
+ }
641
+ const coeffStr = this.#coefficient.toString();
642
+ const isNeg = coeffStr.startsWith("-");
643
+ const absCoeffStr = isNeg ? coeffStr.slice(1) : coeffStr;
644
+ if (this.#exponent < 0) {
645
+ const decimalPlaces = -this.#exponent;
646
+ const leadingZeroCount = decimalPlaces >= absCoeffStr.length ? decimalPlaces - absCoeffStr.length : 0;
647
+ if (leadingZeroCount > PLAIN_NOTATION_DIGIT_LIMIT) {
648
+ if (absCoeffStr.length === 1) {
649
+ return `${coeffStr}E${String(this.#exponent)}`;
650
+ }
651
+ const intPart = absCoeffStr[0] ?? "";
652
+ const fracPart = absCoeffStr.slice(1);
653
+ const adjustedExp = this.#exponent + absCoeffStr.length - 1;
654
+ return `${isNeg ? "-" : ""}${intPart}.${fracPart}E${String(adjustedExp)}`;
655
+ }
656
+ if (decimalPlaces >= absCoeffStr.length) {
657
+ const leadingZeros = "0".repeat(decimalPlaces - absCoeffStr.length);
658
+ return `${isNeg ? "-" : ""}0.${leadingZeros}${absCoeffStr}`;
659
+ } else {
660
+ const integerPart = absCoeffStr.slice(0, absCoeffStr.length - decimalPlaces);
661
+ const fractionalPart = absCoeffStr.slice(absCoeffStr.length - decimalPlaces);
662
+ return `${isNeg ? "-" : ""}${integerPart}.${fractionalPart}`;
663
+ }
664
+ }
665
+ const plainLength = absCoeffStr.length + this.#exponent;
666
+ if (plainLength <= PLAIN_NOTATION_DIGIT_LIMIT) {
667
+ if (this.#exponent === 0) {
668
+ return coeffStr;
669
+ }
670
+ const trailingZeros = "0".repeat(this.#exponent);
671
+ return `${isNeg ? "-" : ""}${absCoeffStr}${trailingZeros}`;
672
+ } else {
673
+ if (absCoeffStr.length === 1) {
674
+ return `${coeffStr}E+${String(this.#exponent)}`;
675
+ }
676
+ const integerPart = absCoeffStr[0] ?? "";
677
+ const fractionalPart = absCoeffStr.slice(1);
678
+ const adjustedExponent = this.#exponent + absCoeffStr.length - 1;
679
+ return `${isNeg ? "-" : ""}${integerPart}.${fractionalPart}E+${String(adjustedExponent)}`;
680
+ }
681
+ }
682
+ /**
683
+ * Return the JSON-serialisable representation.
684
+ *
685
+ * @remarks
686
+ * Returns a plain string matching the Stripe API convention where
687
+ * decimal values are serialised as strings in JSON. Called
688
+ * automatically by `JSON.stringify`.
689
+ *
690
+ * @public
691
+ */
692
+ toJSON() {
693
+ return this.toString();
694
+ }
695
+ /**
696
+ * Convert to a JavaScript `number`.
697
+ *
698
+ * @remarks
699
+ * This is an explicit, intentionally lossy conversion. Use it only
700
+ * when you need a numeric value for display or interop with APIs
701
+ * that require `number`. Prefer {@link Decimal.toString | toString}
702
+ * or {@link Decimal.toFixed | toFixed} for lossless output.
703
+ *
704
+ * @public
705
+ */
706
+ toNumber() {
707
+ return Number(this.toString());
708
+ }
709
+ /**
710
+ * Format this value as a fixed-point string with exactly
711
+ * `decimalPlaces` digits after the decimal point.
712
+ *
713
+ * @remarks
714
+ * Values are rounded according to `direction` when the internal
715
+ * precision exceeds the requested number of decimal places.
716
+ * The rounding direction is always required — no invisible defaults
717
+ * in financial code.
718
+ *
719
+ * @example
720
+ * ```ts
721
+ * Decimal.from('1.235').toFixed(2, 'half-up'); // "1.24"
722
+ * Decimal.from('1.225').toFixed(2, 'half-even'); // "1.22"
723
+ * Decimal.from('42').toFixed(3, 'half-up'); // "42.000"
724
+ * ```
725
+ *
726
+ * @param decimalPlaces - Number of digits after the decimal point.
727
+ * Must be a non-negative integer.
728
+ * @param direction - How to round when truncating excess digits.
729
+ * @returns A string with exactly `decimalPlaces` fractional digits.
730
+ * @throws Error if `decimalPlaces` is negative or non-integer.
731
+ *
732
+ * @public
733
+ */
734
+ toFixed(decimalPlaces, direction) {
735
+ if (decimalPlaces < 0 || !Number.isInteger(decimalPlaces)) {
736
+ throw new Error("decimalPlaces must be a non-negative integer");
737
+ }
738
+ const formatFixed = (coef) => {
739
+ const coeffStr = coef.toString();
740
+ const isNeg = coeffStr.startsWith("-");
741
+ const absCoeffStr = isNeg ? coeffStr.slice(1) : coeffStr;
742
+ if (decimalPlaces === 0) {
743
+ return coeffStr;
744
+ }
745
+ if (decimalPlaces >= absCoeffStr.length) {
746
+ const leadingZeros = "0".repeat(decimalPlaces - absCoeffStr.length);
747
+ return `${isNeg ? "-" : ""}0.${leadingZeros}${absCoeffStr}`;
748
+ } else {
749
+ const integerPart = absCoeffStr.slice(0, absCoeffStr.length - decimalPlaces);
750
+ const fractionalPart = absCoeffStr.slice(absCoeffStr.length - decimalPlaces);
751
+ return `${isNeg ? "-" : ""}${integerPart}.${fractionalPart}`;
752
+ }
753
+ };
754
+ const targetExponent = -decimalPlaces;
755
+ if (this.#exponent === targetExponent) {
756
+ return formatFixed(this.#coefficient);
757
+ }
758
+ if (this.#exponent < targetExponent) {
759
+ const scaleDiff = targetExponent - this.#exponent;
760
+ const divisor = 10n ** BigInt(scaleDiff);
761
+ const quotient = this.#coefficient / divisor;
762
+ const remainder = this.#coefficient % divisor;
763
+ const rounded = _DecimalImpl.roundDivision(quotient, remainder, divisor, direction);
764
+ return formatFixed(rounded);
765
+ } else {
766
+ const scaleDiff = this.#exponent - targetExponent;
767
+ const scaled = this.#coefficient * 10n ** BigInt(scaleDiff);
768
+ return formatFixed(scaled);
769
+ }
770
+ }
771
+ /**
772
+ * Reject implicit arithmetic-style coercion while preserving explicit
773
+ * stringification.
774
+ *
775
+ * @remarks
776
+ * JavaScript cannot overload `+` to perform exact decimal arithmetic.
777
+ * The runtime only allows coercion hooks to return primitive values,
778
+ * which would either concatenate strings or lose precision by forcing
779
+ * the Decimal through IEEE 754 `number`. In financial code, that is
780
+ * less safe than rejecting the operation outright.
781
+ *
782
+ * `String(decimal)` and template-string interpolation still work
783
+ * because the string hint returns the canonical decimal string.
784
+ *
785
+ * @public
786
+ */
787
+ [Symbol.toPrimitive](hint) {
788
+ if (hint === "string") {
789
+ return this.toString();
790
+ }
791
+ throw new Error(IMPLICIT_DECIMAL_COERCION_ERROR);
792
+ }
793
+ /**
794
+ * Return the canonical string representation when called directly.
795
+ *
796
+ * @remarks
797
+ * JavaScript implicit coercion uses
798
+ * {@link Decimal.[Symbol.toPrimitive] | [Symbol.toPrimitive]} first, so
799
+ * this method is only reached via explicit direct calls such as
800
+ * `decimal.valueOf()`.
801
+ *
802
+ * @public
803
+ */
804
+ valueOf() {
805
+ return this.toString();
806
+ }
807
+ };
808
+ function toImpl(d) {
809
+ return d;
810
+ }
811
+ function toDecimal(impl) {
812
+ return impl;
813
+ }
814
+ function isDecimal(value) {
815
+ return typeof value === "object" && value !== null && DECIMAL_BRAND in value;
816
+ }
817
+ var Decimal = {
818
+ /**
819
+ * Create a `Decimal` from a string, number, or bigint.
820
+ *
821
+ * @remarks
822
+ * - **string**: Parsed as a decimal literal. Accepts an optional sign,
823
+ * integer digits, an optional fractional part, and an optional `e`/`E`
824
+ * exponent. Leading/trailing whitespace is trimmed.
825
+ * - **number**: Must be finite. Converted via `Number.prototype.toString()`
826
+ * then parsed, so `Decimal.from(0.1)` produces `"0.1"` (not the
827
+ * 53-bit binary approximation).
828
+ * - **bigint**: Treated as an integer with exponent 0.
829
+ *
830
+ * @example
831
+ * ```ts
832
+ * Decimal.from('1.23'); // string
833
+ * Decimal.from(42); // number
834
+ * Decimal.from(100n); // bigint
835
+ * Decimal.from('1.5e3'); // scientific notation → 1500
836
+ * ```
837
+ *
838
+ * @param value - The value to convert.
839
+ * @returns A new frozen `Decimal` instance.
840
+ * @throws Error if `value` is a non-finite number, an empty
841
+ * string, or a string that does not match the decimal literal grammar.
842
+ *
843
+ * @public
844
+ */
845
+ from(value) {
846
+ if (typeof value === "bigint") {
847
+ return toDecimal(new DecimalImpl(value, 0));
848
+ }
849
+ if (typeof value === "number") {
850
+ if (!Number.isFinite(value)) {
851
+ throw new Error("Number must be finite");
852
+ }
853
+ return Decimal.from(value.toString());
854
+ }
855
+ const trimmed = value.trim();
856
+ if (trimmed === "") {
857
+ throw new Error("Cannot parse empty string as Decimal");
858
+ }
859
+ const match = /^([+-]?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(trimmed);
860
+ if (!match) {
861
+ throw new Error(`Invalid decimal string: ${value}`);
862
+ }
863
+ const sign = match[1] === "-" ? -1n : 1n;
864
+ const integerPart = match[2] ?? "";
865
+ const fractionalPart = match[3] ?? "";
866
+ const exponentPart = match[4] ? Number(match[4]) : 0;
867
+ if (!Number.isSafeInteger(exponentPart) || exponentPart > MAX_EXPONENT || exponentPart < -MAX_EXPONENT) {
868
+ throw new Error(
869
+ `Exponent out of range: ${String(match[4])} exceeds safe integer bounds`
870
+ );
871
+ }
872
+ const coefficientStr = integerPart + fractionalPart;
873
+ const coefficient = sign * BigInt(coefficientStr);
874
+ const exponent = exponentPart - fractionalPart.length;
875
+ if (!Number.isSafeInteger(exponent) || exponent > MAX_EXPONENT || exponent < -MAX_EXPONENT) {
876
+ throw new Error(
877
+ `Computed exponent out of range: ${String(exponent)} exceeds safe integer bounds`
878
+ );
879
+ }
880
+ return toDecimal(new DecimalImpl(coefficient, exponent));
881
+ },
882
+ /**
883
+ * The `Decimal` value representing zero.
884
+ *
885
+ * @remarks
886
+ * Pre-allocated singleton — prefer `Decimal.zero` over
887
+ * `Decimal.from(0)` to avoid an unnecessary allocation.
888
+ *
889
+ * @public
890
+ */
891
+ zero: toDecimal(new DecimalImpl(0n, 0))
892
+ };
893
+
894
+ // src/stdlib/types.ts
895
+ var WireReadError = class extends Error {
896
+ /**
897
+ * Error class name for `instanceof`-free identification.
898
+ * @internal
899
+ */
900
+ name = "WireReadError";
901
+ };
902
+ var WireWriteError = class extends Error {
903
+ /**
904
+ * Error class name for `instanceof`-free identification.
905
+ * @internal
906
+ */
907
+ name = "WireWriteError";
908
+ };
909
+ var WireParseError = class extends Error {
910
+ name = "WireParseError";
911
+ };
912
+ var _ProtoEnum = class {
913
+ _from;
914
+ _to;
915
+ constructor(fromProto) {
916
+ this._from = new Map(Object.entries(fromProto));
917
+ const to = /* @__PURE__ */ new Map();
918
+ for (const [wire, sdk] of this._from) {
919
+ if (to.has(sdk)) {
920
+ throw new Error(`_ProtoEnum: duplicate SDK value '${sdk}' in fromProto map`);
921
+ }
922
+ to.set(sdk, wire);
923
+ }
924
+ this._to = to;
925
+ }
926
+ /**
927
+ * Convert a proto wire value to an SDK value, or `null` if unknown.
928
+ * @internal
929
+ */
930
+ fromWire(value) {
931
+ return this._from.get(value) ?? null;
932
+ }
933
+ /**
934
+ * Convert an SDK value to a proto wire value, or `null` if unknown.
935
+ * @internal
936
+ */
937
+ toWire(value) {
938
+ return this._to.get(value) ?? null;
939
+ }
940
+ };
941
+ var _ConfigEnum = class {
942
+ _values;
943
+ constructor(values) {
944
+ this._values = new Set(values);
945
+ }
946
+ /**
947
+ * Validate and return the wire value unchanged, or `null` if unknown.
948
+ * @internal
949
+ */
950
+ fromWire(value) {
951
+ return this._values.has(value) ? value : null;
952
+ }
953
+ /**
954
+ * Validate and return the SDK value unchanged, or `null` if unknown.
955
+ * @internal
956
+ */
957
+ toWire(value) {
958
+ return this._values.has(value) ? value : null;
959
+ }
960
+ };
961
+ var _ShapeDescriptor = class {
962
+ /** The type name, used in error messages. */
963
+ typeName;
964
+ /** The field descriptors for this shape. */
965
+ fields;
966
+ /** Optional oneof field descriptors (mixed messages with regular + oneof fields). */
967
+ oneofFields;
968
+ constructor(typeName, fields, oneofFields) {
969
+ this.typeName = typeName;
970
+ this.fields = fields;
971
+ if (oneofFields) {
972
+ this.oneofFields = oneofFields;
973
+ }
974
+ }
975
+ };
976
+ var _UnionDescriptor = class {
977
+ /** The type name, used in error messages. */
978
+ typeName;
979
+ /** The SDK-side discriminant field name (e.g. `'value'`, `'kind'`). */
980
+ discriminantFieldName;
981
+ /** The branch descriptors for this union. */
982
+ branches;
983
+ constructor(typeName, discriminantFieldName, branches) {
984
+ this.typeName = typeName;
985
+ this.discriminantFieldName = discriminantFieldName;
986
+ this.branches = branches;
987
+ }
988
+ };
989
+ function otherFieldNameFor(discriminantFieldName) {
990
+ return "other" + discriminantFieldName.charAt(0).toUpperCase() + discriminantFieldName.slice(1);
991
+ }
992
+ function _isPromiseLike(value) {
993
+ if (value !== null && (typeof value === "object" || typeof value === "function")) {
994
+ if ("then" in value) {
995
+ return typeof value.then === "function";
996
+ }
997
+ }
998
+ return false;
999
+ }
1000
+
1001
+ // src/stdlib/transforms.ts
1002
+ function _apply(descriptor, strategy, inputObject, typeName = descriptor.typeName) {
1003
+ if (inputObject === null || inputObject === void 0) {
1004
+ const loc = typeName || "object";
1005
+ const received = inputObject === null ? "null" : "undefined";
1006
+ throw strategy.createNotObjectError(loc, received);
1007
+ }
1008
+ if (typeof inputObject !== "object") {
1009
+ const loc = typeName || "object";
1010
+ throw strategy.createNotObjectError(loc, typeof inputObject);
1011
+ }
1012
+ const input = inputObject;
1013
+ const result = {};
1014
+ for (const desc of descriptor.fields) {
1015
+ const [key, value] = strategy.applyField(typeName, desc, input, strategy);
1016
+ if (value !== void 0) result[key] = value;
1017
+ }
1018
+ if (descriptor.oneofFields) {
1019
+ const regularWireKeys = descriptor.fields.map((f) => f.wire ?? f.type);
1020
+ const allOneofBranchKeys = descriptor.oneofFields.flatMap(
1021
+ (o) => o.branches.map((b) => b.wireKey)
1022
+ );
1023
+ const excludeKeys = /* @__PURE__ */ new Set([...regularWireKeys, ...allOneofBranchKeys]);
1024
+ for (const oneof of descriptor.oneofFields) {
1025
+ strategy.applyOneofField(typeName, oneof, input, strategy, result, excludeKeys);
1026
+ const otherField = otherFieldNameFor(oneof.discriminant);
1027
+ if (result[oneof.discriminant] === "other" && typeof result[otherField] === "string") {
1028
+ excludeKeys.add(result[otherField]);
1029
+ }
1030
+ }
1031
+ }
1032
+ return result;
1033
+ }
1034
+ var _identity = (_strategy, value) => value;
1035
+ function _required(fn = _identity) {
1036
+ return (strategy, value) => {
1037
+ const result = fn(strategy, value);
1038
+ if (result === null || result === void 0) {
1039
+ throw new WireParseError("Required field is missing");
1040
+ }
1041
+ return result;
1042
+ };
1043
+ }
1044
+ var _translateDecimal = (strategy, value) => strategy.translateDecimal(value);
1045
+ var _translateDateTime = (strategy, value) => strategy.translateDateTime(value);
1046
+ function _translateEnum(spec) {
1047
+ return (strategy, value) => strategy.translateEnum(spec, value);
1048
+ }
1049
+ function _translateShape(getDesc) {
1050
+ return (strategy, value) => {
1051
+ if (value === null || value === void 0) return void 0;
1052
+ return _apply(getDesc(), strategy, value);
1053
+ };
1054
+ }
1055
+ function _translateUnion(getDesc) {
1056
+ return (strategy, value) => {
1057
+ if (value === null || value === void 0) return void 0;
1058
+ return strategy.applyUnion(getDesc(), value);
1059
+ };
1060
+ }
1061
+ function _translateArray(elementFn) {
1062
+ return (strategy, value) => {
1063
+ if (value === null || value === void 0) return void 0;
1064
+ if (!Array.isArray(value)) {
1065
+ throw new WireParseError(`Expected array but received: ${typeof value}`);
1066
+ }
1067
+ return value.map((v) => elementFn(strategy, v));
1068
+ };
1069
+ }
1070
+ function _translateMap(keyFn, valueFn) {
1071
+ return (strategy, value) => {
1072
+ if (value === null || value === void 0) return void 0;
1073
+ if (typeof value !== "object" || Array.isArray(value)) {
1074
+ throw new WireParseError(
1075
+ `Expected object for translateMap but received: ${typeof value}`
1076
+ );
1077
+ }
1078
+ const entries = Object.entries(value);
1079
+ return Object.fromEntries(
1080
+ entries.map(([k, v]) => {
1081
+ const mappedKey = keyFn(strategy, k);
1082
+ if (typeof mappedKey !== "string") {
1083
+ throw new WireParseError(
1084
+ `translateMap: key transform returned ${typeof mappedKey} instead of string`
1085
+ );
1086
+ }
1087
+ return [mappedKey, valueFn(strategy, v)];
1088
+ })
1089
+ );
1090
+ };
1091
+ }
1092
+
1093
+ // src/stdlib/transform-strategies.ts
1094
+ function parseDateString(value) {
1095
+ const date = new Date(value);
1096
+ if (isNaN(date.getTime())) {
1097
+ throw new WireParseError(`Cannot parse '${value}' as Date`);
1098
+ }
1099
+ return date;
1100
+ }
1101
+ function enumLookup(spec, value, direction) {
1102
+ if (typeof value !== "string") {
1103
+ throw new WireParseError(`Expected string enum value but received ${typeof value}`);
1104
+ }
1105
+ const result = spec[direction](value);
1106
+ if (result === null) {
1107
+ throw new WireParseError(`Unknown enum value '${value}'`);
1108
+ }
1109
+ return result;
1110
+ }
1111
+ var _ProtoWireToType = {
1112
+ _brand: "ProtoWireToType",
1113
+ createNotObjectError(loc, received) {
1114
+ return new WireReadError(`${loc}: Expected an object but received ${received}`);
1115
+ },
1116
+ applyField(typeName, desc, input, strategy) {
1117
+ const from = desc.wire ?? desc.type;
1118
+ const to = desc.type;
1119
+ const raw = Object.hasOwn(input, from) ? input[from] : void 0;
1120
+ try {
1121
+ return [to, (desc.transform ?? _identity)(strategy, raw)];
1122
+ } catch (e) {
1123
+ if (e instanceof WireParseError)
1124
+ throw new WireReadError(`${typeName}.${desc.type}: ${e.message}`);
1125
+ throw e;
1126
+ }
1127
+ },
1128
+ translateDecimal(value) {
1129
+ if (value === null || value === void 0) return void 0;
1130
+ if (typeof value !== "object" || !("value" in value)) {
1131
+ throw new WireParseError(
1132
+ `Cannot parse ${typeof value} as Decimal \u2014 expected {value: string}`
1133
+ );
1134
+ }
1135
+ const raw = String(value.value);
1136
+ try {
1137
+ return Decimal.from(raw);
1138
+ } catch {
1139
+ throw new WireParseError(`Cannot parse '${raw}' as Decimal`);
1140
+ }
1141
+ },
1142
+ translateDateTime(value) {
1143
+ if (value === null || value === void 0) return void 0;
1144
+ if (typeof value !== "string") {
1145
+ throw new WireParseError(`Cannot parse ${typeof value} as Date \u2014 expected string`);
1146
+ }
1147
+ return parseDateString(value);
1148
+ },
1149
+ translateEnum(spec, value) {
1150
+ if (value === null || value === void 0) return void 0;
1151
+ return enumLookup(spec, value, "fromWire");
1152
+ },
1153
+ applyUnion(descriptor, input) {
1154
+ if (input === null || input === void 0) {
1155
+ throw this.createNotObjectError(descriptor.typeName || "union", String(input));
1156
+ }
1157
+ if (typeof input !== "object") {
1158
+ throw this.createNotObjectError(descriptor.typeName || "union", typeof input);
1159
+ }
1160
+ const wire = input;
1161
+ for (const branch of descriptor.branches) {
1162
+ if (Object.hasOwn(wire, branch.wireKey) && wire[branch.wireKey] !== null && wire[branch.wireKey] !== void 0) {
1163
+ const branchData = _apply(
1164
+ new _ShapeDescriptor(descriptor.typeName, branch.shape),
1165
+ this,
1166
+ wire[branch.wireKey]
1167
+ );
1168
+ return { [descriptor.discriminantFieldName]: branch.typeKey, ...branchData };
1169
+ }
1170
+ }
1171
+ const knownWireKeys = new Set(descriptor.branches.map((b) => b.wireKey));
1172
+ for (const key of Object.keys(wire)) {
1173
+ if (!knownWireKeys.has(key) && wire[key] !== null && wire[key] !== void 0) {
1174
+ const otherFieldName = otherFieldNameFor(descriptor.discriminantFieldName);
1175
+ return { [descriptor.discriminantFieldName]: "other", [otherFieldName]: key };
1176
+ }
1177
+ }
1178
+ const loc = descriptor.typeName || "union";
1179
+ throw new WireReadError(`${loc}: No variant set`);
1180
+ },
1181
+ applyOneofField(typeName, oneof, input, strategy, result, excludeWireKeys) {
1182
+ applyOneofFieldIncoming(typeName, oneof, input, strategy, result, excludeWireKeys);
1183
+ }
1184
+ };
1185
+ var _TypeToProtoWire = {
1186
+ _brand: "TypeToProtoWire",
1187
+ createNotObjectError(loc, received) {
1188
+ return new WireWriteError(`${loc}: Expected an object but received ${received}`);
1189
+ },
1190
+ applyField(typeName, desc, input, strategy) {
1191
+ const from = desc.type;
1192
+ const to = desc.wire ?? desc.type;
1193
+ const raw = Object.hasOwn(input, from) ? input[from] : void 0;
1194
+ try {
1195
+ return [to, (desc.transform ?? _identity)(strategy, raw)];
1196
+ } catch (e) {
1197
+ if (e instanceof WireParseError)
1198
+ throw new WireWriteError(`${typeName}.${desc.type}: ${e.message}`);
1199
+ throw e;
1200
+ }
1201
+ },
1202
+ translateDecimal(value) {
1203
+ if (value === null || value === void 0) return void 0;
1204
+ if (!isDecimal(value)) {
1205
+ throw new WireParseError(
1206
+ `Cannot serialize ${typeof value} as Decimal \u2014 expected Decimal instance`
1207
+ );
1208
+ }
1209
+ return { value: value.toString() };
1210
+ },
1211
+ translateDateTime(value) {
1212
+ if (value === null || value === void 0) return void 0;
1213
+ if (!(value instanceof Date)) {
1214
+ throw new WireParseError(
1215
+ `Cannot serialize ${typeof value} as Date \u2014 expected Date instance`
1216
+ );
1217
+ }
1218
+ if (isNaN(value.getTime())) {
1219
+ throw new WireParseError(`Cannot serialize invalid Date (NaN time value)`);
1220
+ }
1221
+ return value.toISOString();
1222
+ },
1223
+ translateEnum(spec, value) {
1224
+ if (value === null || value === void 0) return void 0;
1225
+ return enumLookup(spec, value, "toWire");
1226
+ },
1227
+ applyUnion(descriptor, input) {
1228
+ if (input === null || input === void 0) {
1229
+ throw this.createNotObjectError(descriptor.typeName || "union", String(input));
1230
+ }
1231
+ if (typeof input !== "object") {
1232
+ throw this.createNotObjectError(descriptor.typeName || "union", typeof input);
1233
+ }
1234
+ const sdk = input;
1235
+ const discriminant = sdk[descriptor.discriminantFieldName];
1236
+ if (typeof discriminant !== "string") {
1237
+ const loc = descriptor.typeName || "union";
1238
+ throw new WireWriteError(
1239
+ `${loc}: Expected a string '${descriptor.discriminantFieldName}' discriminant but received ${discriminant === void 0 ? "undefined" : typeof discriminant}`
1240
+ );
1241
+ }
1242
+ if (discriminant === "other") {
1243
+ const loc = descriptor.typeName || "union";
1244
+ throw new WireWriteError(
1245
+ `${loc}: Cannot serialize 'other' variant back to wire format`
1246
+ );
1247
+ }
1248
+ const branch = descriptor.branches.find((b) => b.typeKey === discriminant);
1249
+ if (!branch) {
1250
+ const loc = descriptor.typeName || "union";
1251
+ throw new WireWriteError(`${loc}: Unknown variant '${discriminant}'`);
1252
+ }
1253
+ const branchData = _apply(
1254
+ new _ShapeDescriptor(descriptor.typeName, branch.shape),
1255
+ this,
1256
+ sdk
1257
+ );
1258
+ return { [branch.wireKey]: branchData };
1259
+ },
1260
+ applyOneofField(typeName, oneof, input, strategy, result, _excludeWireKeys) {
1261
+ applyOneofFieldOutgoing(typeName, oneof, input, strategy, result);
1262
+ }
1263
+ };
1264
+ function _configAppContextFromContext(ctx) {
1265
+ if (typeof ctx !== "object" || ctx === null || !("clockTime" in ctx)) {
1266
+ return {};
1267
+ }
1268
+ const raw = ctx.clockTime;
1269
+ if (raw === void 0 || raw === null) return {};
1270
+ if (typeof raw !== "string") {
1271
+ throw new WireParseError(
1272
+ `Expected clockTime to be a string but received ${typeof raw}`
1273
+ );
1274
+ }
1275
+ return { clockTime: raw };
1276
+ }
1277
+ var _JsonWireToType = {
1278
+ _brand: "JsonWireToType",
1279
+ createNotObjectError(loc, received) {
1280
+ return new WireReadError(`${loc}: Expected an object but received ${received}`);
1281
+ },
1282
+ applyField(typeName, desc, input, strategy) {
1283
+ const key = desc.type;
1284
+ const raw = Object.hasOwn(input, key) ? input[key] : void 0;
1285
+ try {
1286
+ return [key, (desc.transform ?? _identity)(strategy, raw)];
1287
+ } catch (e) {
1288
+ if (e instanceof WireParseError)
1289
+ throw new WireReadError(`${typeName}.${desc.type}: ${e.message}`);
1290
+ throw e;
1291
+ }
1292
+ },
1293
+ translateDecimal(value) {
1294
+ if (value === null || value === void 0) return void 0;
1295
+ if (typeof value === "string") {
1296
+ try {
1297
+ return Decimal.from(value);
1298
+ } catch {
1299
+ throw new WireParseError(`Cannot parse '${value}' as Decimal`);
1300
+ }
1301
+ }
1302
+ if (typeof value === "number") {
1303
+ if (!isFinite(value)) {
1304
+ throw new WireParseError(
1305
+ `Expected a string or finite number but received ${typeof value}`
1306
+ );
1307
+ }
1308
+ return Decimal.from(value);
1309
+ }
1310
+ throw new WireParseError(
1311
+ `Expected a string or finite number but received ${typeof value}`
1312
+ );
1313
+ },
1314
+ translateDateTime(value) {
1315
+ if (value === null || value === void 0) return void 0;
1316
+ if (typeof value !== "string") {
1317
+ throw new WireParseError(`Cannot parse ${typeof value} as Date \u2014 expected string`);
1318
+ }
1319
+ return parseDateString(value);
1320
+ },
1321
+ translateEnum(spec, value) {
1322
+ if (value === null || value === void 0) return void 0;
1323
+ return enumLookup(spec, value, "fromWire");
1324
+ },
1325
+ applyUnion() {
1326
+ throw new Error("applyUnion is not supported for JsonWireToType");
1327
+ },
1328
+ applyOneofField() {
1329
+ throw new Error("applyOneofField is not supported for JsonWireToType");
1330
+ }
1331
+ };
1332
+ function applyOneofFieldIncoming(typeName, oneof, input, strategy, result, excludeWireKeys) {
1333
+ for (const branch of oneof.branches) {
1334
+ const raw = Object.hasOwn(input, branch.wireKey) ? input[branch.wireKey] : void 0;
1335
+ if (raw !== null && raw !== void 0) {
1336
+ result[oneof.discriminant] = branch.typeKey;
1337
+ try {
1338
+ const transformed = branch.transform ? branch.transform(strategy, raw) : raw;
1339
+ if (transformed !== void 0) {
1340
+ result[branch.typeKey] = transformed;
1341
+ }
1342
+ } catch (e) {
1343
+ if (e instanceof WireParseError) {
1344
+ throw new WireReadError(
1345
+ `${typeName}.${oneof.discriminant}(${branch.typeKey}): ${e.message}`
1346
+ );
1347
+ }
1348
+ throw e;
1349
+ }
1350
+ return;
1351
+ }
1352
+ }
1353
+ const knownWireKeys = new Set(oneof.branches.map((b) => b.wireKey));
1354
+ for (const key of Object.keys(input)) {
1355
+ if (!knownWireKeys.has(key) && !excludeWireKeys.has(key) && input[key] !== null && input[key] !== void 0) {
1356
+ result[oneof.discriminant] = "other";
1357
+ result[otherFieldNameFor(oneof.discriminant)] = key;
1358
+ return;
1359
+ }
1360
+ }
1361
+ if (!oneof.optional) {
1362
+ throw new WireReadError(`${typeName}.${oneof.discriminant}: no variant set`);
1363
+ }
1364
+ }
1365
+ function applyOneofFieldOutgoing(typeName, oneof, input, strategy, result) {
1366
+ const discriminant = Object.hasOwn(input, oneof.discriminant) ? input[oneof.discriminant] : void 0;
1367
+ if (discriminant === void 0 || discriminant === null) {
1368
+ if (!oneof.optional) {
1369
+ throw new WireWriteError(`${typeName}.${oneof.discriminant}: no variant set`);
1370
+ }
1371
+ return;
1372
+ }
1373
+ if (typeof discriminant !== "string") {
1374
+ throw new WireWriteError(
1375
+ `${typeName}.${oneof.discriminant}: expected string discriminant but received ${typeof discriminant}`
1376
+ );
1377
+ }
1378
+ if (discriminant === "other") {
1379
+ throw new WireWriteError(
1380
+ `${typeName}.${oneof.discriminant}: cannot serialize 'other' variant back to wire format`
1381
+ );
1382
+ }
1383
+ const branch = oneof.branches.find((b) => b.typeKey === discriminant);
1384
+ if (!branch) {
1385
+ throw new WireWriteError(
1386
+ `${typeName}.${oneof.discriminant}: unknown variant '${discriminant}'`
1387
+ );
1388
+ }
1389
+ const raw = Object.hasOwn(input, branch.typeKey) ? input[branch.typeKey] : void 0;
1390
+ try {
1391
+ const transformed = branch.transform ? branch.transform(strategy, raw) : raw;
1392
+ result[branch.wireKey] = transformed ?? {};
1393
+ } catch (e) {
1394
+ if (e instanceof WireParseError) {
1395
+ throw new WireWriteError(
1396
+ `${typeName}.${oneof.discriminant}(${branch.typeKey}): ${e.message}`
1397
+ );
1398
+ }
1399
+ throw e;
1400
+ }
1401
+ }
1402
+ function createJsonWireToType(appCtx) {
1403
+ return {
1404
+ ..._JsonWireToType,
1405
+ translateDateTime(value) {
1406
+ if (value === null || value === void 0) {
1407
+ if (appCtx.clockTime !== void 0) {
1408
+ return parseDateString(appCtx.clockTime);
1409
+ }
1410
+ return void 0;
1411
+ }
1412
+ return _JsonWireToType.translateDateTime(value);
1413
+ }
1414
+ };
1415
+ }
1416
+ function _applyIncoming(descriptor, inputObject) {
1417
+ return _apply(descriptor, _ProtoWireToType, inputObject);
1418
+ }
1419
+ function _applyOutgoing(descriptor, inputObject) {
1420
+ return _apply(descriptor, _TypeToProtoWire, inputObject);
1421
+ }
1422
+ function _applyConfig(descriptor, inputObject, appCtx) {
1423
+ const strategy = appCtx?.clockTime !== void 0 ? createJsonWireToType(appCtx) : _JsonWireToType;
1424
+ return _apply(descriptor, strategy, inputObject);
1425
+ }
1426
+ export {
1427
+ DEFAULT_DIV_PRECISION,
1428
+ Decimal,
1429
+ DecimalRoundingPresets,
1430
+ Integer,
1431
+ PositiveInteger,
1432
+ Ref,
1433
+ StreetAddress,
1434
+ Timestamp,
1435
+ WireReadError,
1436
+ WireWriteError,
1437
+ _ConfigEnum,
1438
+ _JsonWireToType,
1439
+ _ProtoEnum,
1440
+ _ProtoWireToType,
1441
+ _ShapeDescriptor,
1442
+ _TypeToProtoWire,
1443
+ _UnionDescriptor,
1444
+ _apply,
1445
+ _applyConfig,
1446
+ _applyIncoming,
1447
+ _applyOutgoing,
1448
+ _configAppContextFromContext,
1449
+ _identity,
1450
+ _isPromiseLike,
1451
+ _required,
1452
+ _translateArray,
1453
+ _translateDateTime,
1454
+ _translateDecimal,
1455
+ _translateEnum,
1456
+ _translateMap,
1457
+ _translateShape,
1458
+ _translateUnion,
1459
+ isDecimal
1460
+ };