@refactorlabs/recount 0.11.0 → 0.11.2

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.js CHANGED
@@ -1,4 +1,20 @@
1
- import { __privateAdd, __privateGet, __privateSet, runWithTrace, getActiveTrace, runWithSpanName, __privateMethod } from './chunk-XKR3GXTH.js';
1
+ import { __privateAdd, __privateGet, __privateSet, runWithTrace, getActiveTrace, runWithSpanName, __privateMethod, __privateWrapper } from './chunk-GLYQDK5L.js';
2
+
3
+ // src/lib/error.ts
4
+ var RecountError = class extends Error {
5
+ constructor(status, message) {
6
+ super(message);
7
+ this.name = "RecountError";
8
+ this.status = status;
9
+ }
10
+ };
11
+ function errorText(err) {
12
+ try {
13
+ return err instanceof Error ? err.message : String(err);
14
+ } catch {
15
+ return "unknown error";
16
+ }
17
+ }
2
18
 
3
19
  // src/lib/http.ts
4
20
  var HTTP_METHODS = /* @__PURE__ */ new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
@@ -227,6 +243,11 @@ async function executeFetch(input, init2, recordSpan) {
227
243
 
228
244
  // src/lib/decimal.ts
229
245
  var DECIMAL = /^-?(\d+(\.\d+)?|\.\d+)$/;
246
+ var SIGNIFICANT_DIGITS = 15;
247
+ function withoutFloatNoise(n) {
248
+ if (!Number.isFinite(n) || Number.isInteger(n)) return n === 0 ? 0 : n;
249
+ return Number(n.toPrecision(SIGNIFICANT_DIGITS));
250
+ }
230
251
  function decimalText(n) {
231
252
  if (!Number.isFinite(n)) return void 0;
232
253
  if (Object.is(n, -0) || n === 0) return "0";
@@ -394,7 +415,7 @@ function isValidKey(key) {
394
415
  return KEY.test(key) && !RESERVED.has(key);
395
416
  }
396
417
  var _key, _options, _ops, _built, _CalculationBuilder_instances, push_fn, kindLine_fn;
397
- var CalculationBuilder = class {
418
+ var _CalculationBuilder = class _CalculationBuilder {
398
419
  constructor(key, options = {}) {
399
420
  __privateAdd(this, _CalculationBuilder_instances);
400
421
  __privateAdd(this, _key);
@@ -505,7 +526,20 @@ var CalculationBuilder = class {
505
526
  /** The calculation as it's sent. Attach calls build it for you. */
506
527
  build() {
507
528
  const { calculation: calculation2 } = this.compile();
508
- return calculation2 ? structuredClone(calculation2) : { version: 1, key: __privateGet(this, _key), lines: [] };
529
+ return calculation2 ? structuredClone(calculation2) : {
530
+ version: 1,
531
+ key: repairKey(__privateGet(this, _key), "calculation", /* @__PURE__ */ new Set(), [], ""),
532
+ lines: []
533
+ };
534
+ }
535
+ /**
536
+ * @internal A copy holding the steps so far, so adding to this builder
537
+ * doesn't change it. Cheap: nothing is built.
538
+ */
539
+ snapshot() {
540
+ const copy = new _CalculationBuilder(__privateGet(this, _key), copyData(__privateGet(this, _options)));
541
+ for (const op of __privateGet(this, _ops)) __privateGet(copy, _ops).push(copyData(op));
542
+ return copy;
509
543
  }
510
544
  /** @internal Builds once, never throws. */
511
545
  compile() {
@@ -516,7 +550,7 @@ var CalculationBuilder = class {
516
550
  __privateSet(this, _built, {
517
551
  calculation: void 0,
518
552
  problems: [
519
- `${String(__privateGet(this, _key))}: couldn't be built (${err instanceof Error ? err.message : String(err)})`
553
+ `${keyText(__privateGet(this, _key))}: couldn't be built (${errorText(err)})`
520
554
  ]
521
555
  });
522
556
  }
@@ -540,6 +574,28 @@ kindLine_fn = function(kind, key, label, formula, options) {
540
574
  spec: { key, label, kind, formula: formula ?? null, options }
541
575
  });
542
576
  };
577
+ var CalculationBuilder = _CalculationBuilder;
578
+ function copyData(value, seen = /* @__PURE__ */ new Set()) {
579
+ if (typeof value !== "object" || value === null || seen.has(value)) {
580
+ return value;
581
+ }
582
+ if (Array.isArray(value)) {
583
+ seen.add(value);
584
+ const out2 = value.map((v) => copyData(v, seen));
585
+ seen.delete(value);
586
+ return out2;
587
+ }
588
+ if (!isPlainObject(value)) return value;
589
+ seen.add(value);
590
+ const out = Object.fromEntries(
591
+ Object.entries(value).map(([k, v]) => [k, copyData(v, seen)])
592
+ );
593
+ seen.delete(value);
594
+ return out;
595
+ }
596
+ function isRedacted(value) {
597
+ return typeof value === "object" && value !== null && value.__redacted === true;
598
+ }
543
599
  function calculation(key, options) {
544
600
  return new CalculationBuilder(key, options);
545
601
  }
@@ -607,6 +663,14 @@ function compile(rawKey, options, ops) {
607
663
  for (const op of ops) {
608
664
  if (op.type === "input") addInput(s, op.key, op.value, op.options ?? {});
609
665
  }
666
+ if (s.inputs.length > MAX_INPUTS) {
667
+ problems.push(
668
+ `${key}: ${s.inputs.length} inputs; only the first ${MAX_INPUTS} are sent`
669
+ );
670
+ s.inputs.length = MAX_INPUTS;
671
+ s.inputKeys = new Set(s.inputs.map((input) => input.key));
672
+ s.taken = new Set(s.inputKeys);
673
+ }
610
674
  for (const op of ops) {
611
675
  switch (op.type) {
612
676
  case "line":
@@ -641,12 +705,6 @@ function compile(rawKey, options, ops) {
641
705
  }
642
706
  }
643
707
  }
644
- if (s.inputs.length > MAX_INPUTS) {
645
- problems.push(
646
- `${key}: ${s.inputs.length} inputs; only the first ${MAX_INPUTS} are sent`
647
- );
648
- s.inputs.length = MAX_INPUTS;
649
- }
650
708
  if (s.lines.length > MAX_LINES) {
651
709
  problems.push(
652
710
  `${key}: ${s.lines.length} lines; only the first ${MAX_LINES} are sent`
@@ -789,7 +847,10 @@ function addLine(s, spec) {
789
847
  s.problems
790
848
  );
791
849
  const expected = expectedOf(options.expected, at, s.problems);
792
- if (expected !== void 0) line.expected = expected;
850
+ if (expected !== void 0) {
851
+ if (isRedacted(line.value)) expected.value = REDACTED;
852
+ line.expected = expected;
853
+ }
793
854
  const tolerance = toleranceOf(
794
855
  options.tolerance,
795
856
  `${at}: tolerance`,
@@ -843,6 +904,9 @@ function addTiers(s, rawKey, options) {
843
904
  `${s.calcKey}: tiers`
844
905
  );
845
906
  const at = `${s.calcKey}.${key}`;
907
+ if (overflow !== void 0 && overflow !== "none" && overflow !== "last") {
908
+ s.problems.push(`${at}: overflow is 'none' or 'last'; using 'none'`);
909
+ }
846
910
  if (!Array.isArray(bands) || bands.length === 0) {
847
911
  s.problems.push(`${at}: tiers need at least one band`);
848
912
  s.taken.delete(key);
@@ -877,7 +941,13 @@ function addTiers(s, rawKey, options) {
877
941
  const formula = p === void 0 || p === 1 || p === "1" ? amount : `${amount} * ${operandText(p)}`;
878
942
  const range = size === null ? before === "0" ? `all${unitText}${perText}` : `over ${before}${unitText}${perText}` : i === 0 ? `first ${size}${unitText}${perText}` : `next ${size}${unitText}${perText}`;
879
943
  const bandLabel = band?.label ?? `${base} tier ${n} (${range})`;
880
- const bandKey = `${key}_${n}`;
944
+ const wanted = withSuffix(key, `_${n}`);
945
+ const bandKey = unique(wanted, s.taken);
946
+ if (bandKey !== wanted) {
947
+ s.problems.push(
948
+ `${at}: band ${n}'s key "${wanted}" is taken; sent as "${bandKey}"`
949
+ );
950
+ }
881
951
  const tooLong = formula.length > MAX_FORMULA;
882
952
  if (tooLong) {
883
953
  s.problems.push(
@@ -898,7 +968,11 @@ function addTiers(s, rawKey, options) {
898
968
  rateUnit: subtotalOptions.rateUnit
899
969
  },
900
970
  tags,
901
- taxFree
971
+ taxFree,
972
+ // A redacted subtotal would be the sum of the bands' values.
973
+ ...(subtotalOptions.redact || isRedacted(value)) && {
974
+ redact: true
975
+ }
902
976
  }
903
977
  })
904
978
  );
@@ -1080,7 +1154,7 @@ function cleanValue(value, at, problems) {
1080
1154
  );
1081
1155
  return null;
1082
1156
  }
1083
- return Object.is(value, -0) ? 0 : value;
1157
+ return withoutFloatNoise(value);
1084
1158
  }
1085
1159
  if (typeof value === "string") {
1086
1160
  return text(value, MAX_TEXT_VALUE, at, problems);
@@ -1092,7 +1166,9 @@ function cleanValue(value, at, problems) {
1092
1166
  }
1093
1167
  const decimal = decimalObjectText(value);
1094
1168
  if (decimal !== void 0) return decimal;
1095
- problems.push(`${at}: a ${typeof value} isn't a value; left out`);
1169
+ problems.push(
1170
+ `${at}: ${typeof value === "object" ? "an object" : `a ${typeof value}`} isn't a value; left out`
1171
+ );
1096
1172
  return void 0;
1097
1173
  }
1098
1174
  function operandOf(value, at, problems) {
@@ -1104,7 +1180,7 @@ function operandOf(value, at, problems) {
1104
1180
  problems.push(`${at}: ${value} can't be sent; sent as not calculated`);
1105
1181
  return null;
1106
1182
  }
1107
- return Object.is(value, -0) ? 0 : value;
1183
+ return withoutFloatNoise(value);
1108
1184
  }
1109
1185
  if (typeof value === "string") return formulaText(value, at, problems);
1110
1186
  const decimal = decimalObjectText(value);
@@ -1128,7 +1204,7 @@ function formulaText(formula, at, problems) {
1128
1204
  }
1129
1205
  function sizeText(value, at, problems) {
1130
1206
  if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
1131
- return decimalText(value);
1207
+ return decimalText(withoutFloatNoise(value));
1132
1208
  }
1133
1209
  const text2 = typeof value === "string" ? value.trim() : decimalObjectText(value);
1134
1210
  if (text2 !== void 0 && isDecimalText(text2) && !text2.startsWith("-")) {
@@ -1330,16 +1406,35 @@ function repairKey(given, label, taken, problems, at) {
1330
1406
  taken.add(key);
1331
1407
  return key;
1332
1408
  }
1409
+ function withSuffix(base, suffix) {
1410
+ const room = MAX_KEY - suffix.length;
1411
+ if (base.length <= room) return base + suffix;
1412
+ return base.slice(0, room).replace(/_+$/, "") + suffix;
1413
+ }
1414
+ var nextSuffix = /* @__PURE__ */ new WeakMap();
1333
1415
  function unique(base, taken) {
1334
1416
  if (!taken.has(base)) return base;
1335
- for (let n = 2; ; n++) {
1336
- const key = `${base}_${n}`;
1337
- if (!taken.has(key)) return key;
1417
+ let next = nextSuffix.get(taken);
1418
+ if (!next) {
1419
+ next = /* @__PURE__ */ new Map();
1420
+ nextSuffix.set(taken, next);
1421
+ }
1422
+ for (let n = next.get(base) ?? 2; ; n++) {
1423
+ const key = withSuffix(base, `_${n}`);
1424
+ if (!taken.has(key)) {
1425
+ next.set(base, n);
1426
+ return key;
1427
+ }
1338
1428
  }
1339
1429
  }
1340
1430
  function buildCalculations(calcs) {
1341
1431
  const problems = [];
1342
- const list = Array.isArray(calcs) ? calcs : [calcs];
1432
+ let list;
1433
+ try {
1434
+ list = itemsOf(calcs);
1435
+ } catch (err) {
1436
+ list = [failed(`the calculations couldn't be read (${errorText(err)})`)];
1437
+ }
1343
1438
  const calculations = [];
1344
1439
  const keys = /* @__PURE__ */ new Set();
1345
1440
  let rows = 0;
@@ -1351,7 +1446,7 @@ function buildCalculations(calcs) {
1351
1446
  problems.push("a calculation couldn't be built and was left out");
1352
1447
  continue;
1353
1448
  }
1354
- problems.push(...built.problems);
1449
+ for (const problem of built.problems) problems.push(problem);
1355
1450
  const calc = built.calculation;
1356
1451
  if (!calc) continue;
1357
1452
  if (calculations.length === MAX_CALCULATIONS) {
@@ -1382,6 +1477,56 @@ function buildCalculations(calcs) {
1382
1477
  }
1383
1478
  return { calculations, problems };
1384
1479
  }
1480
+ function itemsOf(calcs) {
1481
+ if (Array.isArray(calcs)) return calcs;
1482
+ if (calcs instanceof Map) return [...calcs.values()];
1483
+ if (!isBuilder(calcs) && typeof calcs === "object" && calcs !== null && typeof calcs[Symbol.iterator] === "function") {
1484
+ const items = [];
1485
+ try {
1486
+ for (const item of calcs) items.push(item);
1487
+ } catch (err) {
1488
+ items.push(
1489
+ failed(
1490
+ `the list of calculations couldn't be read to the end (${errorText(err)}); kept the ${items.length} read before it`
1491
+ )
1492
+ );
1493
+ }
1494
+ return items;
1495
+ }
1496
+ return [calcs];
1497
+ }
1498
+ function failed(problem) {
1499
+ return { compile: () => ({ calculation: void 0, problems: [problem] }) };
1500
+ }
1501
+ function keyText(key) {
1502
+ try {
1503
+ return String(key);
1504
+ } catch {
1505
+ return "calculation";
1506
+ }
1507
+ }
1508
+ function snapshotCalculations(calcs) {
1509
+ let items;
1510
+ try {
1511
+ items = itemsOf(calcs);
1512
+ } catch (err) {
1513
+ return [
1514
+ failed(
1515
+ `the calculations couldn't be read (${errorText(err)})`
1516
+ )
1517
+ ];
1518
+ }
1519
+ return items.map((item) => {
1520
+ try {
1521
+ if (!isBuilder(item)) {
1522
+ return fromPlain(item).snapshot();
1523
+ }
1524
+ return typeof item.snapshot === "function" ? item.snapshot() : item;
1525
+ } catch {
1526
+ return item;
1527
+ }
1528
+ });
1529
+ }
1385
1530
  function isBuilder(item) {
1386
1531
  return typeof item === "object" && item !== null && typeof item.compile === "function";
1387
1532
  }
@@ -1418,9 +1563,22 @@ var units = {
1418
1563
 
1419
1564
  // src/trace.ts
1420
1565
  var NOOP_RESULT = { traceId: "" };
1566
+ var MAX_SPANS = 500;
1567
+ function describe(value) {
1568
+ try {
1569
+ return typeof value === "string" ? JSON.stringify(value) : String(value);
1570
+ } catch {
1571
+ return "an unreadable value";
1572
+ }
1573
+ }
1421
1574
  function calculationSpanOptions(calcs, options, log, name) {
1422
1575
  const { side, ...rest } = options ?? {};
1423
1576
  const { calculations, problems } = buildCalculations(calcs);
1577
+ if (side !== void 0 && side !== "input" && side !== "output") {
1578
+ problems.push(
1579
+ `side is 'input' or 'output', not ${describe(side)}; using 'output'`
1580
+ );
1581
+ }
1424
1582
  for (const problem of problems) {
1425
1583
  log(`calculation span=${name} ${problem}`);
1426
1584
  }
@@ -1453,10 +1611,16 @@ var SpanGroup = class {
1453
1611
  }
1454
1612
  /** A table span holding these calculations, as a child of the group. */
1455
1613
  calculation(name, calcs, options) {
1614
+ const snapshot = snapshotCalculations(calcs);
1615
+ let opts = options;
1616
+ try {
1617
+ opts = options && { ...options };
1618
+ } catch {
1619
+ }
1456
1620
  const item = {
1457
1621
  type: "table",
1458
1622
  name,
1459
- calculations: (log) => calculationSpanOptions(calcs, options, log, name)
1623
+ calculations: (log) => calculationSpanOptions(snapshot, opts, log, name)
1460
1624
  };
1461
1625
  __privateGet(this, _buffer).push(item);
1462
1626
  __privateSet(this, _lastSpan, item);
@@ -1495,7 +1659,8 @@ var SpanGroup = class {
1495
1659
  let built = {};
1496
1660
  try {
1497
1661
  built = calculations(log);
1498
- } catch {
1662
+ } catch (err) {
1663
+ log(`calculation span=${name} couldn't be built (${errorText(err)})`);
1499
1664
  }
1500
1665
  push(type, name, {
1501
1666
  ...built,
@@ -1509,7 +1674,7 @@ var SpanGroup = class {
1509
1674
  };
1510
1675
  _buffer = new WeakMap();
1511
1676
  _lastSpan = new WeakMap();
1512
- var _client, _name, _options2, _spans, _startTime, _disabled, _log, _metadata, _environment, _lastSpan2, _Trace_instances, pushSpan_fn, applyRedaction_fn;
1677
+ var _client, _name, _options2, _spans, _startTime, _disabled, _log, _metadata, _environment, _lastSpan2, _nonGroupSpans, _Trace_instances, pushSpan_fn, makeSpan_fn, applyRedaction_fn;
1513
1678
  var Trace = class {
1514
1679
  constructor(client, name, options = {}, disabled = false, log = () => {
1515
1680
  }) {
@@ -1524,6 +1689,7 @@ var Trace = class {
1524
1689
  __privateAdd(this, _metadata);
1525
1690
  __privateAdd(this, _environment);
1526
1691
  __privateAdd(this, _lastSpan2);
1692
+ __privateAdd(this, _nonGroupSpans, 0);
1527
1693
  __privateSet(this, _client, client);
1528
1694
  __privateSet(this, _name, name);
1529
1695
  __privateSet(this, _options2, options);
@@ -1541,29 +1707,30 @@ var Trace = class {
1541
1707
  }
1542
1708
  group(name, builder, options) {
1543
1709
  if (!__privateGet(this, _disabled)) {
1544
- const groupOrder = __privateGet(this, _spans).length;
1545
1710
  __privateGet(this, _log).call(this, `span type=group name=${name}`);
1546
1711
  const g = new SpanGroup();
1547
1712
  try {
1548
1713
  builder(g);
1549
- } catch {
1714
+ } catch (err) {
1715
+ __privateGet(this, _log).call(this, `span type=group name=${name} builder threw (${errorText(err)}); sending what it added`);
1550
1716
  }
1551
- __privateGet(this, _spans).push({
1717
+ const groupOrder = __privateGet(this, _spans).length;
1718
+ const group = {
1552
1719
  type: "group",
1553
1720
  name,
1554
1721
  order: groupOrder,
1555
1722
  ...options?.description !== void 0 && {
1556
1723
  description: options.description
1557
1724
  }
1558
- });
1559
- const spanCountBeforeFlush = __privateGet(this, _spans).length;
1725
+ };
1726
+ __privateGet(this, _spans).push(group);
1560
1727
  g._flush(
1561
1728
  (type, spanName, opts) => __privateMethod(this, _Trace_instances, pushSpan_fn).call(this, type, spanName, opts, groupOrder),
1562
1729
  options,
1563
1730
  __privateGet(this, _log)
1564
1731
  );
1565
- if (__privateGet(this, _spans).length === spanCountBeforeFlush) {
1566
- __privateGet(this, _spans).splice(groupOrder, 1);
1732
+ if (__privateGet(this, _spans)[__privateGet(this, _spans).length - 1] === group) {
1733
+ __privateGet(this, _spans).pop();
1567
1734
  __privateGet(this, _log).call(this, `span type=group name=${name} dropped (no children)`);
1568
1735
  }
1569
1736
  }
@@ -1592,7 +1759,8 @@ var Trace = class {
1592
1759
  let opts;
1593
1760
  try {
1594
1761
  opts = calculationSpanOptions(calcs, options, __privateGet(this, _log), name);
1595
- } catch {
1762
+ } catch (err) {
1763
+ __privateGet(this, _log).call(this, `calculation span=${name} couldn't be built (${errorText(err)})`);
1596
1764
  return this;
1597
1765
  }
1598
1766
  return this.span("table", name, opts);
@@ -1647,6 +1815,7 @@ _log = new WeakMap();
1647
1815
  _metadata = new WeakMap();
1648
1816
  _environment = new WeakMap();
1649
1817
  _lastSpan2 = new WeakMap();
1818
+ _nonGroupSpans = new WeakMap();
1650
1819
  _Trace_instances = new WeakSet();
1651
1820
  pushSpan_fn = function(type, name, options, parentOrder) {
1652
1821
  if (type !== "group" && type !== "message") {
@@ -1655,6 +1824,25 @@ pushSpan_fn = function(type, name, options, parentOrder) {
1655
1824
  return;
1656
1825
  }
1657
1826
  }
1827
+ if (type !== "group" && __privateGet(this, _nonGroupSpans) >= MAX_SPANS) {
1828
+ __privateGet(this, _log).call(this, `span type=${type} name=${name} dropped (a trace holds ${MAX_SPANS} spans)`);
1829
+ __privateSet(this, _lastSpan2, void 0);
1830
+ return;
1831
+ }
1832
+ let span;
1833
+ try {
1834
+ span = __privateMethod(this, _Trace_instances, makeSpan_fn).call(this, type, name, options, parentOrder);
1835
+ } catch (err) {
1836
+ __privateGet(this, _log).call(this, `span type=${type} name=${name} dropped (couldn't be recorded: ${errorText(err)})`);
1837
+ __privateSet(this, _lastSpan2, void 0);
1838
+ return;
1839
+ }
1840
+ __privateGet(this, _spans).push(span);
1841
+ if (type !== "group") __privateWrapper(this, _nonGroupSpans)._++;
1842
+ __privateSet(this, _lastSpan2, span);
1843
+ __privateGet(this, _log).call(this, `span type=${type} name=${name}`);
1844
+ };
1845
+ makeSpan_fn = function(type, name, options, parentOrder) {
1658
1846
  let span;
1659
1847
  if (type === "message") {
1660
1848
  span = {
@@ -1682,9 +1870,7 @@ pushSpan_fn = function(type, name, options, parentOrder) {
1682
1870
  ...__privateMethod(this, _Trace_instances, applyRedaction_fn).call(this, type, options)
1683
1871
  };
1684
1872
  }
1685
- __privateGet(this, _spans).push(span);
1686
- __privateSet(this, _lastSpan2, span);
1687
- __privateGet(this, _log).call(this, `span type=${type} name=${name}`);
1873
+ return span;
1688
1874
  };
1689
1875
  applyRedaction_fn = function(type, options) {
1690
1876
  if (!options) return {};
@@ -1728,15 +1914,6 @@ applyRedaction_fn = function(type, options) {
1728
1914
  return { ...rest, input, output };
1729
1915
  };
1730
1916
 
1731
- // src/lib/error.ts
1732
- var RecountError = class extends Error {
1733
- constructor(status, message) {
1734
- super(message);
1735
- this.name = "RecountError";
1736
- this.status = status;
1737
- }
1738
- };
1739
-
1740
1917
  // src/client.ts
1741
1918
  var DEFAULT_API_URL = "https://api.recount.refactor.gg";
1742
1919
  var NOOP_RESULT2 = { traceId: "" };
@@ -1762,6 +1939,59 @@ function retryDelayMs(res, attempt) {
1762
1939
  }
1763
1940
  return BASE_RETRY_MS * 2 ** (attempt - 1);
1764
1941
  }
1942
+ function bigintAsString(_key2, value) {
1943
+ return typeof value === "bigint" ? value.toString() : value;
1944
+ }
1945
+ function serialize(payload, log) {
1946
+ try {
1947
+ return JSON.stringify(payload);
1948
+ } catch {
1949
+ }
1950
+ try {
1951
+ return JSON.stringify(payload, bigintAsString);
1952
+ } catch {
1953
+ }
1954
+ const sendable = payload.spans.filter((span) => {
1955
+ try {
1956
+ JSON.stringify(span, bigintAsString);
1957
+ return true;
1958
+ } catch (err) {
1959
+ log(
1960
+ `span type=${span.type} name=${span.name} dropped (can't be sent as JSON: ${errorText(err)})`
1961
+ );
1962
+ return false;
1963
+ }
1964
+ });
1965
+ const spans = sendable.filter(
1966
+ (span) => span.type !== "group" || sendable.some((child) => child.parentOrder === span.order)
1967
+ );
1968
+ if (spans.length === 0) {
1969
+ log("ingest serialize error: no span can be sent as JSON");
1970
+ return void 0;
1971
+ }
1972
+ let error;
1973
+ try {
1974
+ return JSON.stringify({ ...payload, spans }, bigintAsString);
1975
+ } catch (err) {
1976
+ error = err;
1977
+ }
1978
+ if (payload.metadata !== void 0) {
1979
+ try {
1980
+ const body = JSON.stringify(
1981
+ { ...payload, spans, metadata: void 0 },
1982
+ bigintAsString
1983
+ );
1984
+ log(
1985
+ `ingest metadata dropped (can't be sent as JSON: ${errorText(error)})`
1986
+ );
1987
+ return body;
1988
+ } catch (err) {
1989
+ error = err;
1990
+ }
1991
+ }
1992
+ log(`ingest serialize error: ${errorText(error)}`);
1993
+ return void 0;
1994
+ }
1765
1995
  var _apiKey, _apiUrl, _environment2, _disabled2, _timeoutMs, _log2;
1766
1996
  var Recount = class {
1767
1997
  constructor(options = {}) {
@@ -1805,11 +2035,8 @@ var Recount = class {
1805
2035
  return NOOP_RESULT2;
1806
2036
  }
1807
2037
  __privateGet(this, _log2).call(this, `ingest name=${payload.name} spans=${payload.spans.length}`);
1808
- let body;
1809
- try {
1810
- body = JSON.stringify(payload);
1811
- } catch (err) {
1812
- __privateGet(this, _log2).call(this, `ingest serialize error: ${err instanceof Error ? err.message : String(err)}`);
2038
+ const body = serialize(payload, __privateGet(this, _log2));
2039
+ if (body === void 0) {
1813
2040
  return NOOP_RESULT2;
1814
2041
  }
1815
2042
  const headers = {
@@ -1842,7 +2069,8 @@ var Recount = class {
1842
2069
  }
1843
2070
  if (!res.ok) {
1844
2071
  const text2 = await res.text().catch(() => res.statusText);
1845
- __privateGet(this, _log2).call(this, `ingest error status=${res.status} message=${text2}`);
2072
+ const size = res.status === 413 ? ` bytes=${new TextEncoder().encode(body).length}` : "";
2073
+ __privateGet(this, _log2).call(this, `ingest error status=${res.status}${size} message=${text2}`);
1846
2074
  return NOOP_RESULT2;
1847
2075
  }
1848
2076
  let json;
@@ -1905,8 +2133,45 @@ function cleanCellValue(value) {
1905
2133
  }
1906
2134
  return value;
1907
2135
  }
1908
- function signOf(value, highlight) {
1909
- const n = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : NaN;
2136
+ function contentOf(value) {
2137
+ return typeof value === "object" && value !== null && (value.__cell === true || value.__cellSpan === true) ? value.value : value;
2138
+ }
2139
+ function numberOf(value) {
2140
+ if (typeof value === "number") return value;
2141
+ if (typeof value === "string" && value.trim() !== "") return Number(value);
2142
+ return NaN;
2143
+ }
2144
+ function shownAs(sent) {
2145
+ if (typeof sent !== "object" || sent === null || sent.__cell !== true) {
2146
+ return void 0;
2147
+ }
2148
+ const { format, currency, unit, places } = sent;
2149
+ const kind = format ?? (currency ? "money" : unit !== void 0 || places !== void 0 ? "number" : void 0);
2150
+ if (kind === void 0 || kind === "text") return void 0;
2151
+ return {
2152
+ places: kind === "integer" ? 0 : typeof places === "number" && Number.isInteger(places) && places >= 0 ? places : 2,
2153
+ percent: kind === "percent" || unit === "%" && !(kind === "money" && currency)
2154
+ };
2155
+ }
2156
+ function showsAsZero(n, places, percent) {
2157
+ const text2 = decimalText(n);
2158
+ if (text2 === void 0) return false;
2159
+ let [whole, fraction = ""] = text2.replace("-", "").split(".");
2160
+ if (percent) {
2161
+ whole += fraction.slice(0, 2).padEnd(2, "0");
2162
+ fraction = fraction.slice(2);
2163
+ }
2164
+ return /^0*$/.test(whole) && /^0*$/.test(fraction.slice(0, places)) && (fraction[places] ?? "0") < "5";
2165
+ }
2166
+ function signOf(sent, raw, highlight) {
2167
+ const shown = contentOf(sent);
2168
+ let n = numberOf(shown);
2169
+ const format = shownAs(sent);
2170
+ if (!Number.isNaN(n) && format && showsAsZero(n, format.places, format.percent)) {
2171
+ n = 0;
2172
+ }
2173
+ const fallsBack = shown !== null && shown !== void 0 && (typeof shown !== "string" || /\d/.test(shown));
2174
+ if (Number.isNaN(n) && fallsBack) n = numberOf(contentOf(raw));
1910
2175
  if (Number.isNaN(n)) return null;
1911
2176
  if (n > 0) return highlight.positive ?? null;
1912
2177
  if (n < 0) return highlight.negative ?? null;
@@ -1995,6 +2260,13 @@ var TableBuilder = class {
1995
2260
  /**
1996
2261
  * Colours a column's numbers (records) or a row (objects) by sign:
1997
2262
  * `.signHighlight('saving', { positive: 'success', negative: 'danger' })`.
2263
+ * A row takes the sign of the number shown, after `transformValues()`,
2264
+ * `.round()` and a format's places, as Recount shows it: money, number and
2265
+ * percent to 2 places unless given, an integer to none, and a percent times
2266
+ * 100. So -0.004 as money is zero, and 0.004 as a percent (0.40%) positive.
2267
+ * When what's shown is text with a number in it, such as `'$-5'`, it
2268
+ * takes the raw value's sign; a blank row, or text with no number such as
2269
+ * `'N/A'`, takes none.
1998
2270
  */
1999
2271
  signHighlight(key, highlight) {
2000
2272
  this._signHighlights[key] = highlight;
@@ -2119,24 +2391,25 @@ var TableBuilder = class {
2119
2391
  const order = this._pick;
2120
2392
  rows = order.filter((k) => rows.some(([rk]) => rk === k)).map((k) => rows.find(([rk]) => rk === k));
2121
2393
  }
2394
+ const sentValues = [];
2122
2395
  const finalRows = rows.map(([k, v]) => {
2123
2396
  const key = k;
2124
2397
  if (this._shouldRedact(key)) {
2398
+ sentValues.push(REDACTED);
2125
2399
  return [this._resolveLabel(key), REDACTED];
2126
2400
  }
2127
2401
  const transformed = this._valueTransforms[key] ? this._valueTransforms[key](v) : v;
2128
2402
  const format = this._formats[key];
2129
- if (format !== void 0 && isCellValue(transformed)) {
2130
- return [this._resolveLabel(key), cell(transformed, format)];
2131
- }
2132
- return [this._resolveLabel(key), this._finalValue(key, transformed)];
2403
+ const sent = format !== void 0 && isCellValue(transformed) ? cell(transformed, format) : this._finalValue(key, transformed);
2404
+ sentValues.push(sent);
2405
+ return [this._resolveLabel(key), sent];
2133
2406
  });
2134
2407
  const allRows = this._extraRows.length ? [...finalRows, ...this._extraRows.map((r) => r.cells)] : finalRows;
2135
2408
  const hasSigns = Object.keys(this._signHighlights).length > 0;
2136
- const rowHighlights = this._rowHighlightFn || hasSigns ? rows.map(([k, v]) => {
2409
+ const rowHighlights = this._rowHighlightFn || hasSigns ? rows.map(([k, v], i) => {
2137
2410
  const fromFn = this._rowHighlightFn ? this._rowHighlightFn({ [k]: v }) : null;
2138
2411
  const sign = this._signHighlights[k];
2139
- return fromFn ?? (sign && !this._shouldRedact(k) ? signOf(v, sign) : null);
2412
+ return fromFn ?? (sign && !this._shouldRedact(k) ? signOf(sentValues[i], v, sign) : null);
2140
2413
  }) : void 0;
2141
2414
  const allRowHighlights = this._mergeRowHighlights(
2142
2415
  rowHighlights,