@gloom-sh/terminal 0.20.8 → 0.20.10

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 (165) hide show
  1. package/package.json +1 -1
  2. package/src/api-client/auth.ts +6 -0
  3. package/src/api-client/data.ts +1 -0
  4. package/src/api-client/earnings.ts +15 -0
  5. package/src/api-client/futures-curve.ts +5 -1
  6. package/src/api-client/index.ts +14 -3
  7. package/src/api-client/types/account.ts +10 -0
  8. package/src/api-client/types/billing.ts +10 -0
  9. package/src/api-client/types/econ.ts +19 -7
  10. package/src/api-client/types/market.ts +7 -0
  11. package/src/api-client/types/screener.ts +2 -0
  12. package/src/cli/commands/market.ts +18 -8
  13. package/src/cli/commands/overview.ts +28 -7
  14. package/src/cli/commands/ticker.ts +40 -15
  15. package/src/cli/desktop-pane-shot.ts +39 -0
  16. package/src/cli/errors.ts +20 -3
  17. package/src/cli/fx-pair.ts +11 -2
  18. package/src/cli/history-rows.ts +34 -3
  19. package/src/cli/index.ts +1 -1
  20. package/src/cli/listing-arg.ts +51 -13
  21. package/src/cli/pane-functions/data.ts +3 -2
  22. package/src/cli/pane-functions/headless.ts +5 -2
  23. package/src/cli/pane-functions/index.ts +1 -0
  24. package/src/cli/pane-functions/resolver.ts +2 -1
  25. package/src/cli/pane-functions/screenshot-assessment.ts +73 -5
  26. package/src/cli/pane-functions/screenshot-types.ts +4 -0
  27. package/src/cli/symbol-cells.ts +6 -0
  28. package/src/cli/symbol-list.ts +14 -6
  29. package/src/cli/symbol-rows.ts +12 -5
  30. package/src/components/chart/composite/chart-layout.ts +7 -4
  31. package/src/components/chart/composite/composite-chart.tsx +6 -16
  32. package/src/components/chart/composite/toolbar.tsx +258 -82
  33. package/src/components/chart/composite/use-composite-chart-keyboard.ts +5 -6
  34. package/src/components/command-bar/list/model.ts +13 -0
  35. package/src/components/command-bar/routes/ticker-search/actions.ts +2 -0
  36. package/src/components/command-bar/routes/ticker-search/results.ts +15 -8
  37. package/src/components/command-bar/surface/index.tsx +10 -5
  38. package/src/components/command-bar/workflow/alert.ts +21 -7
  39. package/src/components/data-table/table-pane.ts +3 -1
  40. package/src/components/layout/pane/footer/model.ts +26 -1
  41. package/src/components/metric-treemap/heat-surface.tsx +2 -1
  42. package/src/components/metric-treemap/index.tsx +3 -2
  43. package/src/components/ui/confirm-dialog.tsx +253 -7
  44. package/src/components/ui/data-table/index.tsx +1 -1
  45. package/src/components/ui/data-table/types.ts +7 -0
  46. package/src/components/ui/list-view.tsx +4 -3
  47. package/src/components/ui/page-stack-view.tsx +24 -6
  48. package/src/components/ui/status.tsx +9 -6
  49. package/src/docs/snapshot.json +36 -0
  50. package/src/i18n/es.ts +12 -0
  51. package/src/i18n/ja.ts +12 -0
  52. package/src/i18n/ko.ts +12 -0
  53. package/src/i18n/zh-cn.ts +12 -0
  54. package/src/i18n/zh-tw.ts +12 -0
  55. package/src/market-data/futures-roll-returns.ts +226 -0
  56. package/src/market-data/fx-closes.ts +14 -2
  57. package/src/market-data/market/change-basis.ts +35 -1
  58. package/src/market-data/market/session-close-note.ts +41 -4
  59. package/src/market-data/market/status.ts +37 -0
  60. package/src/market-data/performance.ts +4 -1
  61. package/src/market-data/quotes/listing-enterprise-value.ts +8 -4
  62. package/src/market-data/quotes/live-valuation.ts +25 -2
  63. package/src/market-data/realized-volatility.ts +3 -0
  64. package/src/market-data/us-bond-market.ts +115 -0
  65. package/src/plugins/builtin/account-management/invite-row.tsx +54 -0
  66. package/src/plugins/builtin/account-management/keyboard.ts +3 -0
  67. package/src/plugins/builtin/account-management/model.ts +1 -0
  68. package/src/plugins/builtin/account-management/pane.tsx +51 -5
  69. package/src/plugins/builtin/account-management/trial-cancel.ts +32 -7
  70. package/src/plugins/builtin/backtest/client.ts +9 -2
  71. package/src/plugins/builtin/backtest/pane.tsx +1 -1
  72. package/src/plugins/builtin/backtest/report.ts +22 -6
  73. package/src/plugins/builtin/backtest/window.ts +17 -9
  74. package/src/plugins/builtin/cloud/askg/pane-session.ts +94 -0
  75. package/src/plugins/builtin/cloud/askg/pane.tsx +40 -83
  76. package/src/plugins/builtin/congress-trades/pane.tsx +8 -2
  77. package/src/plugins/builtin/correlation/compute.ts +4 -3
  78. package/src/plugins/builtin/correlation/headless.ts +6 -2
  79. package/src/plugins/builtin/correlation/index.tsx +7 -3
  80. package/src/plugins/builtin/correlation/matrix/model.ts +15 -1
  81. package/src/plugins/builtin/correlation/relationship/model.ts +15 -1
  82. package/src/plugins/builtin/correlation/relationship/pane.tsx +4 -2
  83. package/src/plugins/builtin/earnings/board-model.ts +33 -0
  84. package/src/plugins/builtin/earnings/board-table.ts +50 -11
  85. package/src/plugins/builtin/earnings/board.tsx +29 -13
  86. package/src/plugins/builtin/earnings/calendar.tsx +15 -3
  87. package/src/plugins/builtin/earnings/client.ts +4 -1
  88. package/src/plugins/builtin/earnings/headless.ts +27 -14
  89. package/src/plugins/builtin/econ/calendar-source.ts +3 -0
  90. package/src/plugins/builtin/futures-curve/headless.ts +4 -1
  91. package/src/plugins/builtin/futures-curve/model.ts +24 -0
  92. package/src/plugins/builtin/help/index.tsx +1 -1
  93. package/src/plugins/builtin/ipo-calendar/model.ts +3 -3
  94. package/src/plugins/builtin/iv-history/headless.ts +12 -10
  95. package/src/plugins/builtin/kelly-sizer/headless.ts +2 -2
  96. package/src/plugins/builtin/kelly-sizer/history.ts +10 -3
  97. package/src/plugins/builtin/kelly-sizer/pane.tsx +2 -2
  98. package/src/plugins/builtin/kelly-sizer/sections.tsx +1 -1
  99. package/src/plugins/builtin/macro-day/headless.ts +15 -5
  100. package/src/plugins/builtin/macro-day/model.ts +17 -4
  101. package/src/plugins/builtin/macro-day/releases.ts +36 -15
  102. package/src/plugins/builtin/market-halts/model.ts +3 -2
  103. package/src/plugins/builtin/market-movers/headless.ts +2 -1
  104. package/src/plugins/builtin/market-movers/index.tsx +3 -2
  105. package/src/plugins/builtin/market-movers/model.ts +75 -22
  106. package/src/plugins/builtin/market-movers/screener.ts +2 -1
  107. package/src/plugins/builtin/market-movers/table.ts +7 -5
  108. package/src/plugins/builtin/pe-band/model.ts +4 -0
  109. package/src/plugins/builtin/portfolio-list/cell-version.ts +4 -4
  110. package/src/plugins/builtin/portfolio-list/cli/render.ts +9 -4
  111. package/src/plugins/builtin/portfolio-list/pane/index.tsx +2 -1
  112. package/src/plugins/builtin/portfolio-list/summary/index.tsx +24 -7
  113. package/src/plugins/builtin/portfolio-list/summary/totals.ts +40 -11
  114. package/src/plugins/builtin/portfolio-list/table.tsx +13 -1
  115. package/src/plugins/builtin/realized-vol/headless.ts +11 -6
  116. package/src/plugins/builtin/realized-vol/model.ts +14 -6
  117. package/src/plugins/builtin/realized-vol/pane.tsx +2 -1
  118. package/src/plugins/builtin/realized-vol/settings.ts +2 -1
  119. package/src/plugins/builtin/research/analyst-headless.ts +9 -1
  120. package/src/plugins/builtin/research/analyst-pane.tsx +10 -4
  121. package/src/plugins/builtin/research/client.ts +25 -1
  122. package/src/plugins/builtin/research/corporate-actions-pane.tsx +2 -1
  123. package/src/plugins/builtin/research/event-model.ts +3 -13
  124. package/src/plugins/builtin/research/event-sources.ts +3 -1
  125. package/src/plugins/builtin/seasonality/client.ts +66 -17
  126. package/src/plugins/builtin/seasonality/headless.ts +7 -2
  127. package/src/plugins/builtin/seasonality/model.ts +12 -3
  128. package/src/plugins/builtin/seasonality/pane.tsx +4 -2
  129. package/src/plugins/builtin/shared/use-quote-board.ts +28 -6
  130. package/src/plugins/builtin/short-interest/headless.ts +2 -0
  131. package/src/plugins/builtin/short-interest/publications-headless.ts +2 -0
  132. package/src/plugins/builtin/short-interest/watch-headless.ts +1 -0
  133. package/src/plugins/builtin/yield-curve/headless.ts +5 -1
  134. package/src/plugins/builtin/yield-curve/index.tsx +5 -0
  135. package/src/portfolio/column-values.ts +47 -14
  136. package/src/portfolio/return-metrics.ts +4 -2
  137. package/src/renderers/dom/desktop/controls.tsx +1 -1
  138. package/src/renderers/dom/host/image-surface.tsx +19 -9
  139. package/src/renderers/dom/host/input.tsx +4 -0
  140. package/src/renderers/dom/styles.css +7 -4
  141. package/src/renderers/electrobun/view/cli-pane-shot-entry.tsx +23 -1
  142. package/src/renderers/opentui/box-width.ts +30 -0
  143. package/src/sources/gloomberb-cloud/normalizers.ts +2 -0
  144. package/src/sources/provider-errors.ts +12 -0
  145. package/src/sources/provider-router/index.ts +12 -4
  146. package/src/state/pane-session.ts +145 -0
  147. package/src/tickers/search/home-listing.ts +44 -1
  148. package/src/tickers/search/index.ts +5 -2
  149. package/src/tickers/search/ranking.ts +7 -7
  150. package/src/tickers/us-listing.ts +11 -5
  151. package/src/time-series/base-series.ts +7 -1
  152. package/src/time-series/fundamentals/current-valuation.ts +8 -0
  153. package/src/time-series/fundamentals/series.ts +6 -0
  154. package/src/time-series/resolve.ts +1 -0
  155. package/src/types/financials.ts +36 -3
  156. package/src/types/headless.ts +15 -0
  157. package/src/ui/host.tsx +2 -0
  158. package/src/utils/exchanges.ts +13 -8
  159. package/src/utils/fundamentals.ts +49 -8
  160. package/src/utils/price-earnings.ts +17 -10
  161. package/src/utils/price-history-integrity.ts +15 -0
  162. package/src/utils/reason-codes.ts +79 -0
  163. package/src/utils/share-multiples.cases.json +889 -0
  164. package/src/utils/share-multiples.ts +254 -0
  165. package/src/utils/untrusted-text.ts +11 -0
@@ -215,6 +215,8 @@ export function enterpriseValueComputed(
215
215
  */
216
216
  export function enterpriseValueGapIsLarge(fundamentals: Parameters<typeof enterpriseValueCheck>[0]): boolean {
217
217
  const check = enterpriseValueCheck(fundamentals);
218
+ // The provider's figure shown as it is: what the note says of its inputs is a detail for `ticker`.
219
+ if (check?.status === "matches" || check?.status === "unchecked") return false;
218
220
  const bridge = check ? bridgeEnterpriseValue(check) : undefined;
219
221
  if (check?.status !== "differs" || !finiteNumber(check.source) || bridge === undefined || bridge <= 0) return true;
220
222
  return Math.abs(check.source / bridge - 1) > OVERVIEW_ENTERPRISE_VALUE_GAP;
@@ -227,7 +229,9 @@ const OVERVIEW_ENTERPRISE_VALUE_GAP = 0.1;
227
229
  * and short-term investments 1.25B (balance sheet 2026-06-30), in place of the provider's 61.75B.", "EV N/M: cash and short-term investments
228
230
  * exceed market cap + total debt (balance sheet 2026-06-30)." A balance sheet in another currency names the rate it
229
231
  * was converted at ("balance sheet 2026-06-30, EUR at 0.8614 GBP"). A withdrawn EV no balance sheet checked gives
230
- * Gloom Cloud's reason; one withdrawn without a check, that the source failed validation. Undefined when the EV matches, is unchecked or computed, or has no check. Read it from the
232
+ * Gloom Cloud's reason; one withdrawn without a check, that the source failed validation. A provider's EV that
233
+ * matches or is unchecked has a line only where the balance sheet's minority interest is not on its lines
234
+ * (providerEnterpriseValueNote). Undefined when the EV is computed, or has no check. Read it from the
231
235
  * fundamentals the rows show (atRegularSessionPrice moves the check with the EV and the market cap), so its figures
232
236
  * are theirs.
233
237
  */
@@ -247,8 +251,12 @@ export function enterpriseValueReconciliationNote(
247
251
  if (check?.status === "withdrawn" && !finiteNumber(check.computed) && reason) {
248
252
  return `EV unavailable: ${reason.charAt(0).toLowerCase()}${reason.slice(1)}.`;
249
253
  }
250
- if (!check || !finiteNumber(check.computed) || !finiteNumber(check.source)
251
- || (check.status !== "differs" && check.status !== "withdrawn")) return undefined;
254
+ if (!check || !finiteNumber(check.computed) || !finiteNumber(check.source)) return undefined;
255
+ const otherCurrency = !!currency && !!check.currency && check.currency !== currency;
256
+ if ((check.status === "matches" || check.status === "unchecked") && !otherCurrency) {
257
+ return providerEnterpriseValueNote({ ...check, computed: check.computed, source: check.source }, currency, statements);
258
+ }
259
+ if (check.status !== "differs" && check.status !== "withdrawn") return undefined;
252
260
  const source = `${formatCompact(check.source)} ${check.currency}`;
253
261
  const computed = formatCompact(check.computed);
254
262
  const leases = finiteNumber(check.leases) && check.leases > 0 ? " + leases" : "";
@@ -266,6 +274,30 @@ export function enterpriseValueReconciliationNote(
266
274
  return `EV unavailable: the provider's ${source}${ratio} the ${computed} computed from ${basis}${twice}.`;
267
275
  }
268
276
 
277
+ /**
278
+ * The line under a provider's EV the bridge did not replace, where the balance sheet's minority interest is not on
279
+ * its lines: "EV 26.41B USD is the provider's, within 5% of 27.28B: market cap 6.04B + total debt 9.92B - cash 880M +
280
+ * minority interest and preferred equity 12.21B from the company's filing (balance sheet 2026-09-30).", and where
281
+ * neither the sheet nor its filing gives one, why the provider's figure stands. Undefined for any other check.
282
+ */
283
+ function providerEnterpriseValueNote(
284
+ check: EnterpriseValueCheck & { computed: number; source: number },
285
+ currency: string | undefined,
286
+ statements: BalanceSheets | undefined,
287
+ ): string | undefined {
288
+ const fx = check.fx && finiteNumber(check.fx.rate) ? `, ${check.fx.from} at ${check.fx.rate.toPrecision(4)} ${check.currency}` : "";
289
+ const sheet = check.balanceSheetDate ? ` (balance sheet ${check.balanceSheetDate}${fx})` : "";
290
+ const inputs = enterpriseValueInputs(check, sheet, checkCashBasis(check, statements));
291
+ const provider = `EV ${formatCompact(check.source)} ${check.currency} is the provider's`;
292
+ if (check.status === "matches" && check.minorityFiled && !bridgeStandsIn(check, currency)) {
293
+ return `${provider}, within 5% of ${formatCompact(bridgeEnterpriseValue(check)!)}: ${inputs}.`;
294
+ }
295
+ const earlier = check.minorityUnreported;
296
+ if (check.status !== "unchecked" || !earlier || !finiteNumber(earlier.value)) return undefined;
297
+ return `${provider}: ${inputs} is ${formatCompact(check.computed)} with no minority interest, which that balance sheet does not`
298
+ + ` report (${formatCompact(earlier.value)} on ${earlier.balanceSheetDate}), so the provider's figure stands.`;
299
+ }
300
+
269
301
  /** The balance sheets a note reads to say what a check's cash holds. */
270
302
  type BalanceSheets = Partial<Pick<TickerFinancials, "annualStatements" | "quarterlyStatements">>;
271
303
 
@@ -287,16 +319,25 @@ export function checkCashBasis(
287
319
 
288
320
  /**
289
321
  * "EV 7.48B USD is market cap 8.22B + total debt 864.07M - cash and short-term investments 1.6B (balance sheet
290
- * 2026-06-30)": the bridge with its inputs, each where the check carries it, minority interest and preferred equity
291
- * among them where the balance sheet shows any, and its cash as checkCashBasis reads it.
322
+ * 2026-06-30)": the bridge with its inputs (enterpriseValueInputs).
292
323
  */
293
324
  function computedEnterpriseValueInputs(check: EnterpriseValueCheck, sheet: string, cashBasis: ReturnType<typeof checkCashBasis>): string {
325
+ return `EV ${formatCompact(bridgeEnterpriseValue(check)!)} ${check.currency} is ${enterpriseValueInputs(check, sheet, cashBasis)}`;
326
+ }
327
+
328
+ /**
329
+ * "market cap 8.22B + total debt 864.07M - cash and short-term investments 1.6B (balance sheet 2026-06-30)": what the
330
+ * bridge adds up, each where the check carries it, minority interest and preferred equity among them where the balance
331
+ * sheet shows any (named as the company's filing's where the sheet has no equity lines), and its cash as
332
+ * checkCashBasis reads it.
333
+ */
334
+ function enterpriseValueInputs(check: EnterpriseValueCheck, sheet: string, cashBasis: ReturnType<typeof checkCashBasis>): string {
294
335
  const part = (label: string, value: number | undefined) => finiteNumber(value) ? `${label} ${formatCompact(value)}` : label;
295
336
  const leases = finiteNumber(check.leases) && check.leases > 0 ? ` + ${part("leases", check.leases)}` : "";
296
337
  const minority = minorityAndPreferred(check);
297
- const equity = minority > 0 ? ` + ${part("minority interest and preferred equity", minority)}` : "";
298
- return `EV ${formatCompact(bridgeEnterpriseValue(check)!)} ${check.currency} is ${part("market cap", check.marketCap)} + ${part("total debt", check.totalDebt)}${leases}`
299
- + ` - ${part(cashBasis, check.cash)}${equity}${sheet}`;
338
+ const filed = check.minorityFiled ? " from the company's filing" : "";
339
+ const equity = minority > 0 ? ` + ${part("minority interest and preferred equity", minority)}${filed}` : "";
340
+ return `${part("market cap", check.marketCap)} + ${part("total debt", check.totalDebt)}${leases} - ${part(cashBasis, check.cash)}${equity}${sheet}`;
300
341
  }
301
342
 
302
343
  /**
@@ -61,20 +61,27 @@ type PriceEarningsField = "trailingPE" | "forwardPE" | "pegRatio";
61
61
 
62
62
  /**
63
63
  * Why each earnings multiple of a fundamentals block is not meaningful, if it
64
- * is not: a trailing or forward EPS at or below zero, or a multiple that is
65
- * itself at or below zero. Forward P/E is judged on its own estimate only, so
66
- * a trailing loss leaves a positive forward multiple alone.
64
+ * is not: one withdrawn as no multiple of the share (`notMeaningful`,
65
+ * utils/share-multiples: a warrant, a receipt with no ratio, an EPS that is
66
+ * not net income over the shares), a trailing or forward EPS at or below
67
+ * zero, or a multiple that is itself at or below zero. Forward P/E is judged
68
+ * on its own estimate only, so a trailing loss leaves a positive forward
69
+ * multiple alone.
67
70
  */
68
71
  export function notMeaningfulMultiples(
69
- fundamentals: Pick<Fundamentals, PriceEarningsField | "eps" | "forwardEps"> | undefined,
72
+ fundamentals: Pick<Fundamentals, PriceEarningsField | "eps" | "forwardEps" | "notMeaningful"> | undefined,
70
73
  ): Partial<Record<PriceEarningsField, string>> {
71
- const reasons: Partial<Record<PriceEarningsField, string>> = {};
74
+ const reasons: Partial<Record<PriceEarningsField, string>> = { ...fundamentals?.notMeaningful };
72
75
  if (!fundamentals) return reasons;
73
- if (nonPositive(fundamentals.eps)) reasons.trailingPE = "trailing EPS is not positive";
74
- else if (nonPositive(fundamentals.trailingPE)) reasons.trailingPE = "trailing earnings are not positive";
75
- if (nonPositive(fundamentals.forwardEps)) reasons.forwardPE = "forward EPS is not positive";
76
- else if (nonPositive(fundamentals.forwardPE)) reasons.forwardPE = "forward earnings are not positive";
77
- if (nonPositive(fundamentals.pegRatio)) reasons.pegRatio = "P/E or expected growth is not positive";
76
+ if (!reasons.trailingPE) {
77
+ if (nonPositive(fundamentals.eps)) reasons.trailingPE = "trailing EPS is not positive";
78
+ else if (nonPositive(fundamentals.trailingPE)) reasons.trailingPE = "trailing earnings are not positive";
79
+ }
80
+ if (!reasons.forwardPE) {
81
+ if (nonPositive(fundamentals.forwardEps)) reasons.forwardPE = "forward EPS is not positive";
82
+ else if (nonPositive(fundamentals.forwardPE)) reasons.forwardPE = "forward earnings are not positive";
83
+ }
84
+ if (!reasons.pegRatio && nonPositive(fundamentals.pegRatio)) reasons.pegRatio = "P/E or expected growth is not positive";
78
85
  return reasons;
79
86
  }
80
87
 
@@ -61,6 +61,21 @@ export function pricePointIntegrityFlags(point: PricePoint): string[] {
61
61
  /** What a bar whose open alone contradicts its range is flagged with, in `history` and HP. */
62
62
  export const OPEN_WITHHELD_FLAG = "open withheld";
63
63
 
64
+ /** A currency pair's bar whose close the server rebuilt from the next session's open: the source repeated its open as its close. */
65
+ export const CLOSE_REBUILT_FLAG = "close rebuilt";
66
+ /** A currency pair's bar whose source repeated its open as its close, which no next open in its week rebuilds. */
67
+ export const CLOSE_COPIED_FLAG = "close copied";
68
+
69
+ /**
70
+ * Whether a bar's close is its source's copy of its open, which no next open
71
+ * in its week rebuilds (a Friday's, or one the next open is outside the range
72
+ * of): no day's close. A return into or out of it is no day's move, so
73
+ * return-based functions leave the bar out.
74
+ */
75
+ export function pricePointCloseCopied(point: Pick<PricePoint, "closeCopied">): boolean {
76
+ return point.closeCopied === true;
77
+ }
78
+
64
79
  /**
65
80
  * Whether a bar's open alone contradicts its range: above its high or under
66
81
  * its low, while the high, low and close agree. MTN on the JSE, 30 Oct 2026:
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Reason codes are a data service's words for a machine: why it has nothing
3
+ * (NO_DATA, NOT_FOUND) or could not answer (UPSTREAM_ERROR, TIMEOUT). An
4
+ * error built from such an answer often carries one as its whole message, or
5
+ * after a symbol ("AAPL: UPSTREAM_ERROR"). Nothing shows one as it is: the
6
+ * shared states, table bodies, pane footers and the CLI read text through
7
+ * here, the one place a code becomes words.
8
+ */
9
+
10
+ const BUSY = "the source is busy, try again shortly";
11
+ const NO_ANSWER = "the source did not answer";
12
+
13
+ /** What each code the data service sends means, as a clause. */
14
+ const CLAUSES: Readonly<Record<string, string>> = {
15
+ UPSTREAM_ERROR: NO_ANSWER,
16
+ SOURCE_REFUSED_STORED_COPY: NO_ANSWER,
17
+ TIMEOUT: "the source timed out",
18
+ RATE_LIMITED: BUSY,
19
+ UPSTREAM_RATE_LIMIT: BUSY,
20
+ NO_DATA: "no data",
21
+ NOT_FOUND: "nothing found",
22
+ BAD_MAPPING: "nothing found",
23
+ UNSUPPORTED_RANGE: "not available for this range",
24
+ PRO_REQUIRED: "needs Gloom Pro",
25
+ STALE_HISTORY: "the source's history is behind",
26
+ MALFORMED_HISTORY: "the source's history could not be read",
27
+ HISTORY_RETENTION: "older than the history kept",
28
+ AMBIGUOUS_TICKER: "the symbol is listed in several places, name the exchange",
29
+ AMBIGUOUS_EXCHANGE: "the symbol is listed in several places, name the exchange",
30
+ };
31
+
32
+ // Capitals joined by underscores, the shape of every code the service sends but TIMEOUT.
33
+ const CODE_SHAPE = /^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/;
34
+ // A known code, or a source's failure (YAHOO_RATE_LIMIT, ..._ERROR), inside a longer text.
35
+ const EMBEDDED_CODE = /\b[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+\b/g;
36
+
37
+ /** Whether `text` is a reason code on its own (UPSTREAM_ERROR), not words. */
38
+ export function isReasonCode(text: string | null | undefined): boolean {
39
+ const trimmed = text?.trim() ?? "";
40
+ return Object.hasOwn(CLAUSES, trimmed) || CODE_SHAPE.test(trimmed);
41
+ }
42
+
43
+ /**
44
+ * What a reason code says happened, as a clause to follow a colon or stand in
45
+ * a footer: "the source did not answer". An unknown code reads as a failure.
46
+ */
47
+ function reasonCodeClause(code: string): string {
48
+ const trimmed = code.trim();
49
+ if (Object.hasOwn(CLAUSES, trimmed)) return CLAUSES[trimmed]!;
50
+ if (/RATE_?LIMIT/.test(trimmed)) return BUSY;
51
+ if (/TIMEOUT|TIMED_OUT/.test(trimmed)) return CLAUSES.TIMEOUT!;
52
+ if (/NOT_FOUND$/.test(trimmed)) return CLAUSES.NOT_FOUND!;
53
+ return NO_ANSWER;
54
+ }
55
+
56
+ function embeddedCode(token: string): boolean {
57
+ return Object.hasOwn(CLAUSES, token) || /(?:_ERROR|RATE_?LIMIT)$/.test(token);
58
+ }
59
+
60
+ function withEmbeddedCodes(text: string): string {
61
+ return text.replace(EMBEDDED_CODE, (token) => embeddedCode(token) ? reasonCodeClause(token) : token);
62
+ }
63
+
64
+ /**
65
+ * Text fit to show as a state's title or a CLI error: a bare reason code as
66
+ * a sentence ("The source did not answer."), a known code inside a longer
67
+ * text as its clause ("AAPL: the source did not answer"), anything else as
68
+ * it is.
69
+ */
70
+ export function readableError(text: string): string {
71
+ if (!isReasonCode(text)) return withEmbeddedCodes(text);
72
+ const clause = reasonCodeClause(text);
73
+ return `${clause.charAt(0).toUpperCase()}${clause.slice(1)}.`;
74
+ }
75
+
76
+ /** The same for a footer status, which reads as a clause: "the source did not answer". */
77
+ export function readableStatus(text: string): string {
78
+ return isReasonCode(text) ? reasonCodeClause(text) : withEmbeddedCodes(text);
79
+ }