@refactorlabs/recount 0.11.1 → 0.11.3

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/README.md CHANGED
@@ -140,6 +140,7 @@ Recording a trace never changes how your code behaves:
140
140
 
141
141
  - Without an API key, the SDK logs one warning and every call does nothing.
142
142
  - The SDK doesn't throw errors of its own, and errors from your code pass through unchanged.
143
+ - A span that can't be sent as JSON (such as one holding a cycle) or that's past a trace's 500 spans is dropped, and the rest of the trace is sent.
143
144
  - A trace that can't be sent, because of a network error, a rejected payload or a timeout, is dropped. Set `RECOUNT_DEBUG` to see why.
144
145
  - Rate-limited uploads are retried up to twice, within `timeoutMs` (30 seconds by default).
145
146
 
@@ -8,6 +8,14 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
8
8
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
9
9
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
10
10
  var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
11
+ var __privateWrapper = (obj, member, setter, getter) => ({
12
+ set _(value) {
13
+ __privateSet(obj, member, value, setter);
14
+ },
15
+ get _() {
16
+ return __privateGet(obj, member, getter);
17
+ }
18
+ });
11
19
  var _key = /* @__PURE__ */ Symbol.for("@refactorlabs/recount.storage");
12
20
  var _nameKey = /* @__PURE__ */ Symbol.for("@refactorlabs/recount.spanName");
13
21
  var _g = globalThis;
@@ -28,6 +36,6 @@ function runWithSpanName(name, fn) {
28
36
  return nameStorage.run(name, fn);
29
37
  }
30
38
 
31
- export { __privateAdd, __privateGet, __privateMethod, __privateSet, getActiveTrace, getNextSpanName, runWithSpanName, runWithTrace };
32
- //# sourceMappingURL=chunk-XKR3GXTH.js.map
33
- //# sourceMappingURL=chunk-XKR3GXTH.js.map
39
+ export { __privateAdd, __privateGet, __privateMethod, __privateSet, __privateWrapper, getActiveTrace, getNextSpanName, runWithSpanName, runWithTrace };
40
+ //# sourceMappingURL=chunk-GLYQDK5L.js.map
41
+ //# sourceMappingURL=chunk-GLYQDK5L.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/context.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAKA,IAAM,IAAA,mBAAO,MAAA,CAAO,GAAA,CAAI,+BAA+B,CAAA;AACvD,IAAM,QAAA,mBAAW,MAAA,CAAO,GAAA,CAAI,gCAAgC,CAAA;AAC5D,IAAM,EAAA,GAAK,UAAA;AACX,IAAI,CAAC,GAAG,IAAI,CAAA,KAAM,IAAI,CAAA,GAAI,IAAI,iBAAA,EAAyB;AACvD,IAAI,CAAC,GAAG,QAAQ,CAAA,KAAM,QAAQ,CAAA,GAAI,IAAI,iBAAA,EAA0B;AAChE,IAAM,OAAA,GAAU,GAAG,IAAI,CAAA;AACvB,IAAM,WAAA,GAAc,GAAG,QAAQ,CAAA;AAExB,SAAS,cAAA,GAAoC;AAClD,EAAA,OAAO,QAAQ,QAAA,EAAS;AAC1B;AAEO,SAAS,YAAA,CACd,OACA,EAAA,EACY;AACZ,EAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,KAAA,EAAO,EAAE,CAAA;AAC9B;AAEO,SAAS,eAAA,GAAsC;AACpD,EAAA,OAAO,YAAY,QAAA,EAAS;AAC9B;AAEO,SAAS,eAAA,CACd,MACA,EAAA,EACY;AACZ,EAAA,OAAO,WAAA,CAAY,GAAA,CAAI,IAAA,EAAM,EAAE,CAAA;AACjC","file":"chunk-GLYQDK5L.js","sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\n\nimport type { Trace } from '../trace.ts';\n\n// Global singleton ensures all CJS entry points share one AsyncLocalStorage instance.\nconst _key = Symbol.for('@refactorlabs/recount.storage');\nconst _nameKey = Symbol.for('@refactorlabs/recount.spanName');\nconst _g = globalThis as Record<symbol, AsyncLocalStorage<unknown>>;\nif (!_g[_key]) _g[_key] = new AsyncLocalStorage<Trace>();\nif (!_g[_nameKey]) _g[_nameKey] = new AsyncLocalStorage<string>();\nconst storage = _g[_key] as AsyncLocalStorage<Trace>;\nconst nameStorage = _g[_nameKey] as AsyncLocalStorage<string>;\n\nexport function getActiveTrace(): Trace | undefined {\n return storage.getStore();\n}\n\nexport function runWithTrace<T>(\n trace: Trace,\n fn: () => Promise<T>\n): Promise<T> {\n return storage.run(trace, fn);\n}\n\nexport function getNextSpanName(): string | undefined {\n return nameStorage.getStore();\n}\n\nexport function runWithSpanName<T>(\n name: string,\n fn: () => Promise<T>\n): Promise<T> {\n return nameStorage.run(name, fn);\n}\n"]}
package/dist/index.cjs CHANGED
@@ -12,6 +12,30 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
12
12
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
13
13
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
14
14
  var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
15
+ var __privateWrapper = (obj, member, setter, getter) => ({
16
+ set _(value) {
17
+ __privateSet(obj, member, value);
18
+ },
19
+ get _() {
20
+ return __privateGet(obj, member, getter);
21
+ }
22
+ });
23
+
24
+ // src/lib/error.ts
25
+ var RecountError = class extends Error {
26
+ constructor(status, message) {
27
+ super(message);
28
+ this.name = "RecountError";
29
+ this.status = status;
30
+ }
31
+ };
32
+ function errorText(err) {
33
+ try {
34
+ return err instanceof Error ? err.message : String(err);
35
+ } catch {
36
+ return "unknown error";
37
+ }
38
+ }
15
39
 
16
40
  // src/lib/http.ts
17
41
  var HTTP_METHODS = /* @__PURE__ */ new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
@@ -412,7 +436,7 @@ function isValidKey(key) {
412
436
  return KEY.test(key) && !RESERVED.has(key);
413
437
  }
414
438
  var _key, _options, _ops, _built, _CalculationBuilder_instances, push_fn, kindLine_fn;
415
- var CalculationBuilder = class {
439
+ var _CalculationBuilder = class _CalculationBuilder {
416
440
  constructor(key, options = {}) {
417
441
  __privateAdd(this, _CalculationBuilder_instances);
418
442
  __privateAdd(this, _key);
@@ -523,7 +547,20 @@ var CalculationBuilder = class {
523
547
  /** The calculation as it's sent. Attach calls build it for you. */
524
548
  build() {
525
549
  const { calculation: calculation2 } = this.compile();
526
- return calculation2 ? structuredClone(calculation2) : { version: 1, key: __privateGet(this, _key), lines: [] };
550
+ return calculation2 ? structuredClone(calculation2) : {
551
+ version: 1,
552
+ key: repairKey(__privateGet(this, _key), "calculation", /* @__PURE__ */ new Set(), [], ""),
553
+ lines: []
554
+ };
555
+ }
556
+ /**
557
+ * @internal A copy holding the steps so far, so adding to this builder
558
+ * doesn't change it. Cheap: nothing is built.
559
+ */
560
+ snapshot() {
561
+ const copy = new _CalculationBuilder(__privateGet(this, _key), copyData(__privateGet(this, _options)));
562
+ for (const op of __privateGet(this, _ops)) __privateGet(copy, _ops).push(copyData(op));
563
+ return copy;
527
564
  }
528
565
  /** @internal Builds once, never throws. */
529
566
  compile() {
@@ -534,7 +571,7 @@ var CalculationBuilder = class {
534
571
  __privateSet(this, _built, {
535
572
  calculation: void 0,
536
573
  problems: [
537
- `${String(__privateGet(this, _key))}: couldn't be built (${err instanceof Error ? err.message : String(err)})`
574
+ `${keyText(__privateGet(this, _key))}: couldn't be built (${errorText(err)})`
538
575
  ]
539
576
  });
540
577
  }
@@ -558,6 +595,28 @@ kindLine_fn = function(kind, key, label, formula, options) {
558
595
  spec: { key, label, kind, formula: formula ?? null, options }
559
596
  });
560
597
  };
598
+ var CalculationBuilder = _CalculationBuilder;
599
+ function copyData(value, seen = /* @__PURE__ */ new Set()) {
600
+ if (typeof value !== "object" || value === null || seen.has(value)) {
601
+ return value;
602
+ }
603
+ if (Array.isArray(value)) {
604
+ seen.add(value);
605
+ const out2 = value.map((v) => copyData(v, seen));
606
+ seen.delete(value);
607
+ return out2;
608
+ }
609
+ if (!isPlainObject(value)) return value;
610
+ seen.add(value);
611
+ const out = Object.fromEntries(
612
+ Object.entries(value).map(([k, v]) => [k, copyData(v, seen)])
613
+ );
614
+ seen.delete(value);
615
+ return out;
616
+ }
617
+ function isRedacted(value) {
618
+ return typeof value === "object" && value !== null && value.__redacted === true;
619
+ }
561
620
  function calculation(key, options) {
562
621
  return new CalculationBuilder(key, options);
563
622
  }
@@ -625,6 +684,14 @@ function compile(rawKey, options, ops) {
625
684
  for (const op of ops) {
626
685
  if (op.type === "input") addInput(s, op.key, op.value, op.options ?? {});
627
686
  }
687
+ if (s.inputs.length > MAX_INPUTS) {
688
+ problems.push(
689
+ `${key}: ${s.inputs.length} inputs; only the first ${MAX_INPUTS} are sent`
690
+ );
691
+ s.inputs.length = MAX_INPUTS;
692
+ s.inputKeys = new Set(s.inputs.map((input) => input.key));
693
+ s.taken = new Set(s.inputKeys);
694
+ }
628
695
  for (const op of ops) {
629
696
  switch (op.type) {
630
697
  case "line":
@@ -659,12 +726,6 @@ function compile(rawKey, options, ops) {
659
726
  }
660
727
  }
661
728
  }
662
- if (s.inputs.length > MAX_INPUTS) {
663
- problems.push(
664
- `${key}: ${s.inputs.length} inputs; only the first ${MAX_INPUTS} are sent`
665
- );
666
- s.inputs.length = MAX_INPUTS;
667
- }
668
729
  if (s.lines.length > MAX_LINES) {
669
730
  problems.push(
670
731
  `${key}: ${s.lines.length} lines; only the first ${MAX_LINES} are sent`
@@ -807,7 +868,10 @@ function addLine(s, spec) {
807
868
  s.problems
808
869
  );
809
870
  const expected = expectedOf(options.expected, at, s.problems);
810
- if (expected !== void 0) line.expected = expected;
871
+ if (expected !== void 0) {
872
+ if (isRedacted(line.value)) expected.value = REDACTED;
873
+ line.expected = expected;
874
+ }
811
875
  const tolerance = toleranceOf(
812
876
  options.tolerance,
813
877
  `${at}: tolerance`,
@@ -861,6 +925,9 @@ function addTiers(s, rawKey, options) {
861
925
  `${s.calcKey}: tiers`
862
926
  );
863
927
  const at = `${s.calcKey}.${key}`;
928
+ if (overflow !== void 0 && overflow !== "none" && overflow !== "last") {
929
+ s.problems.push(`${at}: overflow is 'none' or 'last'; using 'none'`);
930
+ }
864
931
  if (!Array.isArray(bands) || bands.length === 0) {
865
932
  s.problems.push(`${at}: tiers need at least one band`);
866
933
  s.taken.delete(key);
@@ -895,7 +962,13 @@ function addTiers(s, rawKey, options) {
895
962
  const formula = p === void 0 || p === 1 || p === "1" ? amount : `${amount} * ${operandText(p)}`;
896
963
  const range = size === null ? before === "0" ? `all${unitText}${perText}` : `over ${before}${unitText}${perText}` : i === 0 ? `first ${size}${unitText}${perText}` : `next ${size}${unitText}${perText}`;
897
964
  const bandLabel = band?.label ?? `${base} tier ${n} (${range})`;
898
- const bandKey = `${key}_${n}`;
965
+ const wanted = withSuffix(key, `_${n}`);
966
+ const bandKey = unique(wanted, s.taken);
967
+ if (bandKey !== wanted) {
968
+ s.problems.push(
969
+ `${at}: band ${n}'s key "${wanted}" is taken; sent as "${bandKey}"`
970
+ );
971
+ }
899
972
  const tooLong = formula.length > MAX_FORMULA;
900
973
  if (tooLong) {
901
974
  s.problems.push(
@@ -916,7 +989,11 @@ function addTiers(s, rawKey, options) {
916
989
  rateUnit: subtotalOptions.rateUnit
917
990
  },
918
991
  tags,
919
- taxFree
992
+ taxFree,
993
+ // A redacted subtotal would be the sum of the bands' values.
994
+ ...(subtotalOptions.redact || isRedacted(value)) && {
995
+ redact: true
996
+ }
920
997
  }
921
998
  })
922
999
  );
@@ -1110,7 +1187,9 @@ function cleanValue(value, at, problems) {
1110
1187
  }
1111
1188
  const decimal = decimalObjectText(value);
1112
1189
  if (decimal !== void 0) return decimal;
1113
- problems.push(`${at}: a ${typeof value} isn't a value; left out`);
1190
+ problems.push(
1191
+ `${at}: ${typeof value === "object" ? "an object" : `a ${typeof value}`} isn't a value; left out`
1192
+ );
1114
1193
  return void 0;
1115
1194
  }
1116
1195
  function operandOf(value, at, problems) {
@@ -1348,16 +1427,35 @@ function repairKey(given, label, taken, problems, at) {
1348
1427
  taken.add(key);
1349
1428
  return key;
1350
1429
  }
1430
+ function withSuffix(base, suffix) {
1431
+ const room = MAX_KEY - suffix.length;
1432
+ if (base.length <= room) return base + suffix;
1433
+ return base.slice(0, room).replace(/_+$/, "") + suffix;
1434
+ }
1435
+ var nextSuffix = /* @__PURE__ */ new WeakMap();
1351
1436
  function unique(base, taken) {
1352
1437
  if (!taken.has(base)) return base;
1353
- for (let n = 2; ; n++) {
1354
- const key = `${base}_${n}`;
1355
- if (!taken.has(key)) return key;
1438
+ let next = nextSuffix.get(taken);
1439
+ if (!next) {
1440
+ next = /* @__PURE__ */ new Map();
1441
+ nextSuffix.set(taken, next);
1442
+ }
1443
+ for (let n = next.get(base) ?? 2; ; n++) {
1444
+ const key = withSuffix(base, `_${n}`);
1445
+ if (!taken.has(key)) {
1446
+ next.set(base, n);
1447
+ return key;
1448
+ }
1356
1449
  }
1357
1450
  }
1358
1451
  function buildCalculations(calcs) {
1359
1452
  const problems = [];
1360
- const list = Array.isArray(calcs) ? calcs : [calcs];
1453
+ let list;
1454
+ try {
1455
+ list = itemsOf(calcs);
1456
+ } catch (err) {
1457
+ list = [failed(`the calculations couldn't be read (${errorText(err)})`)];
1458
+ }
1361
1459
  const calculations = [];
1362
1460
  const keys = /* @__PURE__ */ new Set();
1363
1461
  let rows = 0;
@@ -1369,7 +1467,7 @@ function buildCalculations(calcs) {
1369
1467
  problems.push("a calculation couldn't be built and was left out");
1370
1468
  continue;
1371
1469
  }
1372
- problems.push(...built.problems);
1470
+ for (const problem of built.problems) problems.push(problem);
1373
1471
  const calc = built.calculation;
1374
1472
  if (!calc) continue;
1375
1473
  if (calculations.length === MAX_CALCULATIONS) {
@@ -1400,6 +1498,56 @@ function buildCalculations(calcs) {
1400
1498
  }
1401
1499
  return { calculations, problems };
1402
1500
  }
1501
+ function itemsOf(calcs) {
1502
+ if (Array.isArray(calcs)) return calcs;
1503
+ if (calcs instanceof Map) return [...calcs.values()];
1504
+ if (!isBuilder(calcs) && typeof calcs === "object" && calcs !== null && typeof calcs[Symbol.iterator] === "function") {
1505
+ const items = [];
1506
+ try {
1507
+ for (const item of calcs) items.push(item);
1508
+ } catch (err) {
1509
+ items.push(
1510
+ failed(
1511
+ `the list of calculations couldn't be read to the end (${errorText(err)}); kept the ${items.length} read before it`
1512
+ )
1513
+ );
1514
+ }
1515
+ return items;
1516
+ }
1517
+ return [calcs];
1518
+ }
1519
+ function failed(problem) {
1520
+ return { compile: () => ({ calculation: void 0, problems: [problem] }) };
1521
+ }
1522
+ function keyText(key) {
1523
+ try {
1524
+ return String(key);
1525
+ } catch {
1526
+ return "calculation";
1527
+ }
1528
+ }
1529
+ function snapshotCalculations(calcs) {
1530
+ let items;
1531
+ try {
1532
+ items = itemsOf(calcs);
1533
+ } catch (err) {
1534
+ return [
1535
+ failed(
1536
+ `the calculations couldn't be read (${errorText(err)})`
1537
+ )
1538
+ ];
1539
+ }
1540
+ return items.map((item) => {
1541
+ try {
1542
+ if (!isBuilder(item)) {
1543
+ return fromPlain(item).snapshot();
1544
+ }
1545
+ return typeof item.snapshot === "function" ? item.snapshot() : item;
1546
+ } catch {
1547
+ return item;
1548
+ }
1549
+ });
1550
+ }
1403
1551
  function isBuilder(item) {
1404
1552
  return typeof item === "object" && item !== null && typeof item.compile === "function";
1405
1553
  }
@@ -1436,9 +1584,22 @@ var units = {
1436
1584
 
1437
1585
  // src/trace.ts
1438
1586
  var NOOP_RESULT = { traceId: "" };
1587
+ var MAX_SPANS = 500;
1588
+ function describe(value) {
1589
+ try {
1590
+ return typeof value === "string" ? JSON.stringify(value) : String(value);
1591
+ } catch {
1592
+ return "an unreadable value";
1593
+ }
1594
+ }
1439
1595
  function calculationSpanOptions(calcs, options, log, name) {
1440
1596
  const { side, ...rest } = options ?? {};
1441
1597
  const { calculations, problems } = buildCalculations(calcs);
1598
+ if (side !== void 0 && side !== "input" && side !== "output") {
1599
+ problems.push(
1600
+ `side is 'input' or 'output', not ${describe(side)}; using 'output'`
1601
+ );
1602
+ }
1442
1603
  for (const problem of problems) {
1443
1604
  log(`calculation span=${name} ${problem}`);
1444
1605
  }
@@ -1471,10 +1632,16 @@ var SpanGroup = class {
1471
1632
  }
1472
1633
  /** A table span holding these calculations, as a child of the group. */
1473
1634
  calculation(name, calcs, options) {
1635
+ const snapshot = snapshotCalculations(calcs);
1636
+ let opts = options;
1637
+ try {
1638
+ opts = options && { ...options };
1639
+ } catch {
1640
+ }
1474
1641
  const item = {
1475
1642
  type: "table",
1476
1643
  name,
1477
- calculations: (log) => calculationSpanOptions(calcs, options, log, name)
1644
+ calculations: (log) => calculationSpanOptions(snapshot, opts, log, name)
1478
1645
  };
1479
1646
  __privateGet(this, _buffer).push(item);
1480
1647
  __privateSet(this, _lastSpan, item);
@@ -1513,7 +1680,8 @@ var SpanGroup = class {
1513
1680
  let built = {};
1514
1681
  try {
1515
1682
  built = calculations(log);
1516
- } catch {
1683
+ } catch (err) {
1684
+ log(`calculation span=${name} couldn't be built (${errorText(err)})`);
1517
1685
  }
1518
1686
  push(type, name, {
1519
1687
  ...built,
@@ -1527,7 +1695,7 @@ var SpanGroup = class {
1527
1695
  };
1528
1696
  _buffer = new WeakMap();
1529
1697
  _lastSpan = new WeakMap();
1530
- var _client, _name, _options2, _spans, _startTime, _disabled, _log, _metadata, _environment, _lastSpan2, _Trace_instances, pushSpan_fn, applyRedaction_fn;
1698
+ var _client, _name, _options2, _spans, _startTime, _disabled, _log, _metadata, _environment, _lastSpan2, _nonGroupSpans, _Trace_instances, pushSpan_fn, makeSpan_fn, applyRedaction_fn;
1531
1699
  var Trace = class {
1532
1700
  constructor(client, name, options = {}, disabled = false, log = () => {
1533
1701
  }) {
@@ -1542,6 +1710,7 @@ var Trace = class {
1542
1710
  __privateAdd(this, _metadata);
1543
1711
  __privateAdd(this, _environment);
1544
1712
  __privateAdd(this, _lastSpan2);
1713
+ __privateAdd(this, _nonGroupSpans, 0);
1545
1714
  __privateSet(this, _client, client);
1546
1715
  __privateSet(this, _name, name);
1547
1716
  __privateSet(this, _options2, options);
@@ -1559,29 +1728,31 @@ var Trace = class {
1559
1728
  }
1560
1729
  group(name, builder, options) {
1561
1730
  if (!__privateGet(this, _disabled)) {
1562
- const groupOrder = __privateGet(this, _spans).length;
1563
1731
  __privateGet(this, _log).call(this, `span type=group name=${name}`);
1564
1732
  const g = new SpanGroup();
1565
1733
  try {
1566
1734
  builder(g);
1567
- } catch {
1735
+ } catch (err) {
1736
+ __privateGet(this, _log).call(this, `span type=group name=${name} builder threw (${errorText(err)}); sending what it added`);
1568
1737
  }
1569
- __privateGet(this, _spans).push({
1738
+ const groupOrder = __privateGet(this, _spans).length;
1739
+ const group = {
1570
1740
  type: "group",
1571
1741
  name,
1572
1742
  order: groupOrder,
1573
1743
  ...options?.description !== void 0 && {
1574
1744
  description: options.description
1575
1745
  }
1576
- });
1577
- const spanCountBeforeFlush = __privateGet(this, _spans).length;
1746
+ };
1747
+ __privateGet(this, _spans).push(group);
1578
1748
  g._flush(
1579
1749
  (type, spanName, opts) => __privateMethod(this, _Trace_instances, pushSpan_fn).call(this, type, spanName, opts, groupOrder),
1580
1750
  options,
1581
1751
  __privateGet(this, _log)
1582
1752
  );
1583
- if (__privateGet(this, _spans).length === spanCountBeforeFlush) {
1584
- __privateGet(this, _spans).splice(groupOrder, 1);
1753
+ if (__privateGet(this, _spans)[__privateGet(this, _spans).length - 1] === group) {
1754
+ __privateGet(this, _spans).pop();
1755
+ __privateSet(this, _lastSpan2, void 0);
1585
1756
  __privateGet(this, _log).call(this, `span type=group name=${name} dropped (no children)`);
1586
1757
  }
1587
1758
  }
@@ -1610,7 +1781,8 @@ var Trace = class {
1610
1781
  let opts;
1611
1782
  try {
1612
1783
  opts = calculationSpanOptions(calcs, options, __privateGet(this, _log), name);
1613
- } catch {
1784
+ } catch (err) {
1785
+ __privateGet(this, _log).call(this, `calculation span=${name} couldn't be built (${errorText(err)})`);
1614
1786
  return this;
1615
1787
  }
1616
1788
  return this.span("table", name, opts);
@@ -1665,14 +1837,35 @@ _log = new WeakMap();
1665
1837
  _metadata = new WeakMap();
1666
1838
  _environment = new WeakMap();
1667
1839
  _lastSpan2 = new WeakMap();
1840
+ _nonGroupSpans = new WeakMap();
1668
1841
  _Trace_instances = new WeakSet();
1669
1842
  pushSpan_fn = function(type, name, options, parentOrder) {
1670
1843
  if (type !== "group" && type !== "message") {
1671
1844
  if (options?.input === void 0 && options?.output === void 0) {
1672
1845
  __privateGet(this, _log).call(this, `span type=${type} name=${name} dropped (no input or output)`);
1846
+ __privateSet(this, _lastSpan2, void 0);
1673
1847
  return;
1674
1848
  }
1675
1849
  }
1850
+ if (type !== "group" && __privateGet(this, _nonGroupSpans) >= MAX_SPANS) {
1851
+ __privateGet(this, _log).call(this, `span type=${type} name=${name} dropped (a trace holds ${MAX_SPANS} spans)`);
1852
+ __privateSet(this, _lastSpan2, void 0);
1853
+ return;
1854
+ }
1855
+ let span;
1856
+ try {
1857
+ span = __privateMethod(this, _Trace_instances, makeSpan_fn).call(this, type, name, options, parentOrder);
1858
+ } catch (err) {
1859
+ __privateGet(this, _log).call(this, `span type=${type} name=${name} dropped (couldn't be recorded: ${errorText(err)})`);
1860
+ __privateSet(this, _lastSpan2, void 0);
1861
+ return;
1862
+ }
1863
+ __privateGet(this, _spans).push(span);
1864
+ if (type !== "group") __privateWrapper(this, _nonGroupSpans)._++;
1865
+ __privateSet(this, _lastSpan2, span);
1866
+ __privateGet(this, _log).call(this, `span type=${type} name=${name}`);
1867
+ };
1868
+ makeSpan_fn = function(type, name, options, parentOrder) {
1676
1869
  let span;
1677
1870
  if (type === "message") {
1678
1871
  span = {
@@ -1700,9 +1893,7 @@ pushSpan_fn = function(type, name, options, parentOrder) {
1700
1893
  ...__privateMethod(this, _Trace_instances, applyRedaction_fn).call(this, type, options)
1701
1894
  };
1702
1895
  }
1703
- __privateGet(this, _spans).push(span);
1704
- __privateSet(this, _lastSpan2, span);
1705
- __privateGet(this, _log).call(this, `span type=${type} name=${name}`);
1896
+ return span;
1706
1897
  };
1707
1898
  applyRedaction_fn = function(type, options) {
1708
1899
  if (!options) return {};
@@ -1746,15 +1937,6 @@ applyRedaction_fn = function(type, options) {
1746
1937
  return { ...rest, input, output };
1747
1938
  };
1748
1939
 
1749
- // src/lib/error.ts
1750
- var RecountError = class extends Error {
1751
- constructor(status, message) {
1752
- super(message);
1753
- this.name = "RecountError";
1754
- this.status = status;
1755
- }
1756
- };
1757
-
1758
1940
  // src/client.ts
1759
1941
  var DEFAULT_API_URL = "https://api.recount.refactor.gg";
1760
1942
  var NOOP_RESULT2 = { traceId: "" };
@@ -1780,6 +1962,59 @@ function retryDelayMs(res, attempt) {
1780
1962
  }
1781
1963
  return BASE_RETRY_MS * 2 ** (attempt - 1);
1782
1964
  }
1965
+ function bigintAsString(_key3, value) {
1966
+ return typeof value === "bigint" ? value.toString() : value;
1967
+ }
1968
+ function serialize(payload, log) {
1969
+ try {
1970
+ return JSON.stringify(payload);
1971
+ } catch {
1972
+ }
1973
+ try {
1974
+ return JSON.stringify(payload, bigintAsString);
1975
+ } catch {
1976
+ }
1977
+ const sendable = payload.spans.filter((span) => {
1978
+ try {
1979
+ JSON.stringify(span, bigintAsString);
1980
+ return true;
1981
+ } catch (err) {
1982
+ log(
1983
+ `span type=${span.type} name=${span.name} dropped (can't be sent as JSON: ${errorText(err)})`
1984
+ );
1985
+ return false;
1986
+ }
1987
+ });
1988
+ const spans = sendable.filter(
1989
+ (span) => span.type !== "group" || sendable.some((child) => child.parentOrder === span.order)
1990
+ );
1991
+ if (spans.length === 0) {
1992
+ log("ingest serialize error: no span can be sent as JSON");
1993
+ return void 0;
1994
+ }
1995
+ let error;
1996
+ try {
1997
+ return JSON.stringify({ ...payload, spans }, bigintAsString);
1998
+ } catch (err) {
1999
+ error = err;
2000
+ }
2001
+ if (payload.metadata !== void 0) {
2002
+ try {
2003
+ const body = JSON.stringify(
2004
+ { ...payload, spans, metadata: void 0 },
2005
+ bigintAsString
2006
+ );
2007
+ log(
2008
+ `ingest metadata dropped (can't be sent as JSON: ${errorText(error)})`
2009
+ );
2010
+ return body;
2011
+ } catch (err) {
2012
+ error = err;
2013
+ }
2014
+ }
2015
+ log(`ingest serialize error: ${errorText(error)}`);
2016
+ return void 0;
2017
+ }
1783
2018
  var _apiKey, _apiUrl, _environment2, _disabled2, _timeoutMs, _log2;
1784
2019
  var Recount = class {
1785
2020
  constructor(options = {}) {
@@ -1823,11 +2058,8 @@ var Recount = class {
1823
2058
  return NOOP_RESULT2;
1824
2059
  }
1825
2060
  __privateGet(this, _log2).call(this, `ingest name=${payload.name} spans=${payload.spans.length}`);
1826
- let body;
1827
- try {
1828
- body = JSON.stringify(payload);
1829
- } catch (err) {
1830
- __privateGet(this, _log2).call(this, `ingest serialize error: ${err instanceof Error ? err.message : String(err)}`);
2061
+ const body = serialize(payload, __privateGet(this, _log2));
2062
+ if (body === void 0) {
1831
2063
  return NOOP_RESULT2;
1832
2064
  }
1833
2065
  const headers = {
@@ -1860,7 +2092,8 @@ var Recount = class {
1860
2092
  }
1861
2093
  if (!res.ok) {
1862
2094
  const text2 = await res.text().catch(() => res.statusText);
1863
- __privateGet(this, _log2).call(this, `ingest error status=${res.status} message=${text2}`);
2095
+ const size = res.status === 413 ? ` bytes=${new TextEncoder().encode(body).length}` : "";
2096
+ __privateGet(this, _log2).call(this, `ingest error status=${res.status}${size} message=${text2}`);
1864
2097
  return NOOP_RESULT2;
1865
2098
  }
1866
2099
  let json;
@@ -1939,8 +2172,45 @@ function cleanCellValue(value) {
1939
2172
  }
1940
2173
  return value;
1941
2174
  }
1942
- function signOf(value, highlight) {
1943
- const n = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : NaN;
2175
+ function contentOf(value) {
2176
+ return typeof value === "object" && value !== null && (value.__cell === true || value.__cellSpan === true) ? value.value : value;
2177
+ }
2178
+ function numberOf(value) {
2179
+ if (typeof value === "number") return value;
2180
+ if (typeof value === "string" && value.trim() !== "") return Number(value);
2181
+ return NaN;
2182
+ }
2183
+ function shownAs(sent) {
2184
+ if (typeof sent !== "object" || sent === null || sent.__cell !== true) {
2185
+ return void 0;
2186
+ }
2187
+ const { format, currency, unit, places } = sent;
2188
+ const kind = format ?? (currency ? "money" : unit !== void 0 || places !== void 0 ? "number" : void 0);
2189
+ if (kind === void 0 || kind === "text") return void 0;
2190
+ return {
2191
+ places: kind === "integer" ? 0 : typeof places === "number" && Number.isInteger(places) && places >= 0 ? places : 2,
2192
+ percent: kind === "percent" || unit === "%" && !(kind === "money" && currency)
2193
+ };
2194
+ }
2195
+ function showsAsZero(n, places, percent) {
2196
+ const text2 = decimalText(n);
2197
+ if (text2 === void 0) return false;
2198
+ let [whole, fraction = ""] = text2.replace("-", "").split(".");
2199
+ if (percent) {
2200
+ whole += fraction.slice(0, 2).padEnd(2, "0");
2201
+ fraction = fraction.slice(2);
2202
+ }
2203
+ return /^0*$/.test(whole) && /^0*$/.test(fraction.slice(0, places)) && (fraction[places] ?? "0") < "5";
2204
+ }
2205
+ function signOf(sent, raw, highlight) {
2206
+ const shown = contentOf(sent);
2207
+ let n = numberOf(shown);
2208
+ const format = shownAs(sent);
2209
+ if (!Number.isNaN(n) && format && showsAsZero(n, format.places, format.percent)) {
2210
+ n = 0;
2211
+ }
2212
+ const fallsBack = shown !== null && shown !== void 0 && (typeof shown !== "string" || /\d/.test(shown));
2213
+ if (Number.isNaN(n) && fallsBack) n = numberOf(contentOf(raw));
1944
2214
  if (Number.isNaN(n)) return null;
1945
2215
  if (n > 0) return highlight.positive ?? null;
1946
2216
  if (n < 0) return highlight.negative ?? null;
@@ -2029,6 +2299,13 @@ var TableBuilder = class {
2029
2299
  /**
2030
2300
  * Colours a column's numbers (records) or a row (objects) by sign:
2031
2301
  * `.signHighlight('saving', { positive: 'success', negative: 'danger' })`.
2302
+ * A row takes the sign of the number shown, after `transformValues()`,
2303
+ * `.round()` and a format's places, as Recount shows it: money, number and
2304
+ * percent to 2 places unless given, an integer to none, and a percent times
2305
+ * 100. So -0.004 as money is zero, and 0.004 as a percent (0.40%) positive.
2306
+ * When what's shown is text with a number in it, such as `'$-5'`, it
2307
+ * takes the raw value's sign; a blank row, or text with no number such as
2308
+ * `'N/A'`, takes none.
2032
2309
  */
2033
2310
  signHighlight(key, highlight) {
2034
2311
  this._signHighlights[key] = highlight;
@@ -2153,24 +2430,25 @@ var TableBuilder = class {
2153
2430
  const order = this._pick;
2154
2431
  rows = order.filter((k) => rows.some(([rk]) => rk === k)).map((k) => rows.find(([rk]) => rk === k));
2155
2432
  }
2433
+ const sentValues = [];
2156
2434
  const finalRows = rows.map(([k, v]) => {
2157
2435
  const key = k;
2158
2436
  if (this._shouldRedact(key)) {
2437
+ sentValues.push(REDACTED);
2159
2438
  return [this._resolveLabel(key), REDACTED];
2160
2439
  }
2161
2440
  const transformed = this._valueTransforms[key] ? this._valueTransforms[key](v) : v;
2162
2441
  const format = this._formats[key];
2163
- if (format !== void 0 && isCellValue(transformed)) {
2164
- return [this._resolveLabel(key), cell(transformed, format)];
2165
- }
2166
- return [this._resolveLabel(key), this._finalValue(key, transformed)];
2442
+ const sent = format !== void 0 && isCellValue(transformed) ? cell(transformed, format) : this._finalValue(key, transformed);
2443
+ sentValues.push(sent);
2444
+ return [this._resolveLabel(key), sent];
2167
2445
  });
2168
2446
  const allRows = this._extraRows.length ? [...finalRows, ...this._extraRows.map((r) => r.cells)] : finalRows;
2169
2447
  const hasSigns = Object.keys(this._signHighlights).length > 0;
2170
- const rowHighlights = this._rowHighlightFn || hasSigns ? rows.map(([k, v]) => {
2448
+ const rowHighlights = this._rowHighlightFn || hasSigns ? rows.map(([k, v], i) => {
2171
2449
  const fromFn = this._rowHighlightFn ? this._rowHighlightFn({ [k]: v }) : null;
2172
2450
  const sign = this._signHighlights[k];
2173
- return fromFn ?? (sign && !this._shouldRedact(k) ? signOf(v, sign) : null);
2451
+ return fromFn ?? (sign && !this._shouldRedact(k) ? signOf(sentValues[i], v, sign) : null);
2174
2452
  }) : void 0;
2175
2453
  const allRowHighlights = this._mergeRowHighlights(
2176
2454
  rowHighlights,