@gloom-sh/terminal 0.20.17 → 0.20.18

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 (304) hide show
  1. package/package.json +3 -1
  2. package/src/account/auth-dialog.tsx +19 -1
  3. package/src/account/billing.ts +2 -1
  4. package/src/account/heard-from-question.tsx +235 -0
  5. package/src/account/heard-from.ts +97 -0
  6. package/src/api-client/data.ts +3 -2
  7. package/src/api-client/heard-from.ts +72 -0
  8. package/src/api-client/index.ts +63 -6
  9. package/src/api-client/mna.ts +18 -0
  10. package/src/api-client/supply-chain.ts +9 -0
  11. package/src/api-client/types/billing.ts +35 -1
  12. package/src/app/global-shortcuts.ts +5 -3
  13. package/src/app/pro-welcome/keys.ts +27 -0
  14. package/src/app/pro-welcome/model.ts +158 -0
  15. package/src/app/pro-welcome/row.tsx +176 -0
  16. package/src/app/pro-welcome/use-pro-welcome.ts +156 -0
  17. package/src/app/runtime/external-profile-changes.ts +135 -0
  18. package/src/app.tsx +33 -2
  19. package/src/architecture/core-builtin-allowlist.json +1 -1
  20. package/src/architecture/floating-promise-allowlist.json +0 -1
  21. package/src/architecture/shortcut-labels-allowlist.json +1 -0
  22. package/src/cli/alert-listing.ts +98 -0
  23. package/src/cli/commands/market.ts +138 -22
  24. package/src/cli/commands/overview.ts +7 -1
  25. package/src/cli/commands/plugins.ts +3 -2
  26. package/src/cli/commands/search.ts +30 -6
  27. package/src/cli/context.ts +16 -5
  28. package/src/cli/csv-export.ts +2 -1
  29. package/src/cli/desktop-pane-shot.ts +72 -9
  30. package/src/cli/glossary.ts +64 -10
  31. package/src/cli/history-demergers.ts +117 -0
  32. package/src/cli/history-rows.ts +6 -2
  33. package/src/cli/index.ts +1 -0
  34. package/src/cli/known-gaps.ts +16 -0
  35. package/src/cli/known-us-stocks.ts +18 -0
  36. package/src/cli/listing-arg.ts +105 -15
  37. package/src/cli/pane-functions/catalog-snapshot-build.ts +83 -0
  38. package/src/cli/pane-functions/catalog-snapshot.json +866 -0
  39. package/src/cli/pane-functions/catalog-snapshot.ts +62 -0
  40. package/src/cli/pane-functions/catalog.ts +50 -16
  41. package/src/cli/pane-functions/data.ts +16 -4
  42. package/src/cli/pane-functions/dom.ts +24 -6
  43. package/src/cli/pane-functions/freshness.ts +17 -1
  44. package/src/cli/pane-functions/index.ts +100 -42
  45. package/src/cli/pane-functions/resolver.ts +8 -5
  46. package/src/cli/pane-functions/screenshot-assessment.ts +30 -7
  47. package/src/cli/pane-functions/screenshot-payload.ts +21 -0
  48. package/src/cli/pane-functions/screenshot-render.ts +3 -1
  49. package/src/cli/quote-answer.ts +32 -16
  50. package/src/cli/registry.ts +22 -2
  51. package/src/cli/result.ts +5 -4
  52. package/src/cli/series-search.ts +45 -6
  53. package/src/cli/shot-temp-dir.ts +4 -9
  54. package/src/components/chart/composite/legend.tsx +43 -18
  55. package/src/components/chart/composite/panel-surface/panel-cursor.tsx +3 -3
  56. package/src/components/chart/composite/price-axis-labels.tsx +7 -5
  57. package/src/components/chart-table/header.tsx +9 -0
  58. package/src/components/chart-table/layout.ts +11 -11
  59. package/src/components/command-bar/pane-templates/items.ts +17 -1
  60. package/src/components/command-bar/routes/root/provider-search.ts +10 -1
  61. package/src/components/command-bar/routes/root/results.ts +34 -2
  62. package/src/components/command-bar/routes/root/runtime.ts +8 -1
  63. package/src/components/command-bar/routes/ticker-search/route.ts +5 -0
  64. package/src/components/command-bar/workflow/alert.ts +19 -8
  65. package/src/components/data-table/view.tsx +15 -2
  66. package/src/components/form-modal/content.tsx +9 -4
  67. package/src/components/index.ts +1 -1
  68. package/src/components/layout/header.tsx +9 -5
  69. package/src/components/layout/pane/capture-status.ts +6 -0
  70. package/src/components/layout/pane/footer/index.tsx +2 -0
  71. package/src/components/layout/pane/footer/model.ts +113 -15
  72. package/src/components/layout/pane/header.tsx +16 -2
  73. package/src/components/market-board/index.tsx +4 -2
  74. package/src/components/onboarding/onboarding-frame.tsx +6 -2
  75. package/src/components/onboarding/onboarding-keyboard.ts +7 -1
  76. package/src/components/onboarding/onboarding-wizard.tsx +3 -1
  77. package/src/components/onboarding/portfolio-step/positions-panel.tsx +24 -15
  78. package/src/components/onboarding/setup-cards.ts +36 -0
  79. package/src/components/onboarding/use-onboarding-progress.ts +22 -1
  80. package/src/components/onboarding/wizard-account.ts +6 -1
  81. package/src/components/onboarding/wizard-model.ts +32 -6
  82. package/src/components/onboarding/wizard-positions.ts +1 -1
  83. package/src/components/sign-in-gate.tsx +3 -1
  84. package/src/components/toggle-list.tsx +6 -8
  85. package/src/components/ui/confirm-dialog.tsx +47 -7
  86. package/src/components/ui/data-table/types.ts +8 -0
  87. package/src/components/ui/display.tsx +17 -2
  88. package/src/components/ui/index.ts +1 -1
  89. package/src/components/ui/stat-grid.tsx +4 -0
  90. package/src/components/ui/status.tsx +13 -1
  91. package/src/components/ui/table-layout.ts +2 -1
  92. package/src/components/use-pane-notice-footer.tsx +16 -3
  93. package/src/data/config/store/index.ts +31 -0
  94. package/src/data/config/store/node.ts +61 -11
  95. package/src/data/config/store/normalize.ts +4 -6
  96. package/src/data/config/store/shared-file.ts +309 -0
  97. package/src/data/profile-merge.ts +299 -0
  98. package/src/data/sqlite/checkpointer.ts +11 -1
  99. package/src/data/sqlite/database.ts +1 -1
  100. package/src/data/ticker-repository.ts +134 -10
  101. package/src/data/ticker-store.ts +67 -0
  102. package/src/data/ticker-writes.ts +5 -0
  103. package/src/i18n/es.ts +27 -0
  104. package/src/i18n/ja.ts +27 -0
  105. package/src/i18n/ko.ts +27 -0
  106. package/src/i18n/zh-cn.ts +27 -0
  107. package/src/i18n/zh-tw.ts +27 -0
  108. package/src/layout-marketplace/gallery-desktop.tsx +2 -2
  109. package/src/market-data/ah-pair.ts +103 -0
  110. package/src/market-data/depositary-pair.ts +6 -2
  111. package/src/market-data/hooks.tsx +33 -2
  112. package/src/market-data/market/change-basis.ts +2 -1
  113. package/src/market-data/market/header-market.ts +11 -0
  114. package/src/market-data/split-terms.ts +28 -0
  115. package/src/plugins/builtin/account-management/footer.ts +1 -1
  116. package/src/plugins/builtin/account-management/keyboard.ts +4 -0
  117. package/src/plugins/builtin/account-management/model.ts +1 -0
  118. package/src/plugins/builtin/account-management/pane.tsx +75 -7
  119. package/src/plugins/builtin/account-management/payment-recovery-row.tsx +12 -5
  120. package/src/plugins/builtin/account-management/pro-cancel.tsx +197 -0
  121. package/src/plugins/builtin/account-management/trial-cancel.ts +1 -1
  122. package/src/plugins/builtin/alerts/cli-move.ts +2 -2
  123. package/src/plugins/builtin/alerts/cli.ts +36 -30
  124. package/src/plugins/builtin/alerts/constants.ts +10 -0
  125. package/src/plugins/builtin/alerts/earnings-listing.ts +20 -0
  126. package/src/plugins/builtin/alerts/format.ts +24 -8
  127. package/src/plugins/builtin/alerts/index.tsx +38 -9
  128. package/src/plugins/builtin/alerts/move-checks.ts +7 -0
  129. package/src/plugins/builtin/alerts/pane.tsx +1 -1
  130. package/src/plugins/builtin/alerts/quotes.ts +26 -2
  131. package/src/plugins/builtin/alerts/scheduled.ts +6 -1
  132. package/src/plugins/builtin/alerts/types.ts +7 -0
  133. package/src/plugins/builtin/analytics/manual-value.ts +61 -0
  134. package/src/plugins/builtin/analytics/risk-book.ts +7 -7
  135. package/src/plugins/builtin/analytics/risk-client.ts +26 -13
  136. package/src/plugins/builtin/analytics/risk-headless.ts +13 -8
  137. package/src/plugins/builtin/analytics/risk-model.ts +92 -4
  138. package/src/plugins/builtin/analytics/risk-pane.tsx +85 -38
  139. package/src/plugins/builtin/awards/pane.tsx +1 -1
  140. package/src/plugins/builtin/broker-trading/orders.tsx +2 -2
  141. package/src/plugins/builtin/central-bank-rates/model.ts +8 -2
  142. package/src/plugins/builtin/central-bank-rates/pane.tsx +5 -3
  143. package/src/plugins/builtin/chart-composer/cli-options.ts +4 -2
  144. package/src/plugins/builtin/chart-composer/data-catalog-pane.tsx +2 -6
  145. package/src/plugins/builtin/chart-composer/pane.tsx +5 -2
  146. package/src/plugins/builtin/cloud/auth-actions.tsx +11 -6
  147. package/src/plugins/builtin/cloud/company-picker.tsx +5 -3
  148. package/src/plugins/builtin/cloud/upgrade-command.ts +1 -1
  149. package/src/plugins/builtin/company-kpis/headless.ts +9 -4
  150. package/src/plugins/builtin/company-kpis/latest.ts +45 -0
  151. package/src/plugins/builtin/company-kpis/model.ts +38 -8
  152. package/src/plugins/builtin/company-kpis/pane.tsx +22 -8
  153. package/src/plugins/builtin/composite/alt-data.ts +20 -0
  154. package/src/plugins/builtin/composite/application.ts +14 -0
  155. package/src/plugins/builtin/composite/broker.ts +12 -0
  156. package/src/plugins/builtin/composite/credit.ts +33 -0
  157. package/src/plugins/builtin/composite/crypto.ts +10 -0
  158. package/src/plugins/builtin/composite/earnings.ts +12 -0
  159. package/src/plugins/builtin/composite/filings.ts +13 -0
  160. package/src/plugins/builtin/composite/futures-commodities.ts +23 -0
  161. package/src/plugins/builtin/composite/global-markets.ts +12 -0
  162. package/src/plugins/builtin/composite/options-volatility.ts +23 -0
  163. package/src/plugins/builtin/composite/ownership.ts +23 -0
  164. package/src/plugins/builtin/composite/portfolio.ts +10 -0
  165. package/src/plugins/builtin/composite/quant.ts +15 -0
  166. package/src/plugins/builtin/composite/rates-macro.ts +30 -0
  167. package/src/plugins/builtin/composite/screeners.ts +11 -0
  168. package/src/plugins/builtin/composite/shared.ts +11 -0
  169. package/src/plugins/builtin/composite/ticker-core.ts +36 -0
  170. package/src/plugins/builtin/congress-trades/headless.ts +31 -3
  171. package/src/plugins/builtin/correlation/index.tsx +13 -17
  172. package/src/plugins/builtin/correlation/matrix/model.ts +18 -0
  173. package/src/plugins/builtin/dividend-yield/client.ts +57 -16
  174. package/src/plugins/builtin/dividend-yield/headless.ts +17 -11
  175. package/src/plugins/builtin/dividend-yield/model.ts +4 -3
  176. package/src/plugins/builtin/dividend-yield/pane.tsx +22 -18
  177. package/src/plugins/builtin/dividend-yield/ranking.ts +1 -1
  178. package/src/plugins/builtin/dividend-yield/types.ts +4 -0
  179. package/src/plugins/builtin/dividend-yield/view.ts +23 -12
  180. package/src/plugins/builtin/earnings/fiscal-quarter.ts +39 -0
  181. package/src/plugins/builtin/earnings/headless.ts +7 -4
  182. package/src/plugins/builtin/earnings/history-model.ts +6 -4
  183. package/src/plugins/builtin/earnings/history-table.ts +4 -3
  184. package/src/plugins/builtin/earnings-calls/pane.tsx +8 -2
  185. package/src/plugins/builtin/econ/calendar-model.ts +16 -0
  186. package/src/plugins/builtin/econ/index.tsx +3 -0
  187. package/src/plugins/builtin/equity-screener/headless.ts +4 -1
  188. package/src/plugins/builtin/equity-screener/model.ts +7 -6
  189. package/src/plugins/builtin/estimate-revisions/headless.ts +1 -1
  190. package/src/plugins/builtin/exposure/model.ts +10 -0
  191. package/src/plugins/builtin/exposure/pane.tsx +10 -3
  192. package/src/plugins/builtin/fx-matrix/amount.ts +15 -1
  193. package/src/plugins/builtin/fx-matrix/headless.ts +12 -6
  194. package/src/plugins/builtin/fx-matrix/index.tsx +23 -5
  195. package/src/plugins/builtin/fx-matrix/settings.ts +9 -4
  196. package/src/plugins/builtin/kelly-sizer/pane.tsx +9 -4
  197. package/src/plugins/builtin/market-valuation/pane.tsx +22 -10
  198. package/src/plugins/builtin/mna/detail.tsx +67 -6
  199. package/src/plugins/builtin/mna/headless.ts +128 -13
  200. package/src/plugins/builtin/mna/model.ts +219 -16
  201. package/src/plugins/builtin/mna/pane.tsx +34 -6
  202. package/src/plugins/builtin/money-markets/model.ts +14 -5
  203. package/src/plugins/builtin/money-markets/pane.tsx +4 -3
  204. package/src/plugins/builtin/news/wire/news/footer.ts +3 -8
  205. package/src/plugins/builtin/options-scenario/csp-screen-pane.tsx +22 -6
  206. package/src/plugins/builtin/options-scenario/csp-screen.ts +39 -12
  207. package/src/plugins/builtin/options-scenario/strategy-screen.ts +7 -5
  208. package/src/plugins/builtin/pe-band/client.ts +13 -1
  209. package/src/plugins/builtin/pe-band/headless.ts +2 -2
  210. package/src/plugins/builtin/pe-band/model.ts +63 -10
  211. package/src/plugins/builtin/pe-band/pane.tsx +5 -5
  212. package/src/plugins/builtin/portfolio-list/allocation-rows.ts +26 -7
  213. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +66 -13
  214. package/src/plugins/builtin/portfolio-list/cli/render.ts +76 -33
  215. package/src/plugins/builtin/portfolio-list/headless.ts +69 -22
  216. package/src/plugins/builtin/portfolio-list/pane/data.ts +3 -3
  217. package/src/plugins/builtin/portfolio-list/pane/index.tsx +29 -14
  218. package/src/plugins/builtin/portfolio-list/summary/index.tsx +2 -2
  219. package/src/plugins/builtin/relative-rotation/pane.tsx +2 -3
  220. package/src/plugins/builtin/research/corporate-actions-pane.tsx +5 -1
  221. package/src/plugins/builtin/research/event-model.ts +31 -13
  222. package/src/plugins/builtin/research/headless.ts +8 -1
  223. package/src/plugins/builtin/research/relative-valuation-pane.tsx +19 -17
  224. package/src/plugins/builtin/sectors/index.tsx +6 -9
  225. package/src/plugins/builtin/shared/cloud-upgrade.ts +1 -1
  226. package/src/plugins/builtin/shared/earnings-report.ts +19 -4
  227. package/src/plugins/builtin/shared/report-freshness.ts +2 -3
  228. package/src/plugins/builtin/supply-chain/client.ts +34 -9
  229. package/src/plugins/builtin/supply-chain/evidence.ts +3 -2
  230. package/src/plugins/builtin/supply-chain/flow.tsx +4 -3
  231. package/src/plugins/builtin/supply-chain/graph-model.ts +14 -7
  232. package/src/plugins/builtin/supply-chain/graph-pane.tsx +3 -1
  233. package/src/plugins/builtin/supply-chain/graph.tsx +6 -3
  234. package/src/plugins/builtin/supply-chain/headless.ts +19 -4
  235. package/src/plugins/builtin/supply-chain/model.ts +50 -6
  236. package/src/plugins/builtin/supply-chain/pane.tsx +76 -16
  237. package/src/plugins/builtin/ticker-detail/adr-pair/ah.ts +62 -0
  238. package/src/plugins/builtin/ticker-detail/adr-pair/headless.ts +119 -20
  239. package/src/plugins/builtin/ticker-detail/adr-pair/model.ts +51 -1
  240. package/src/plugins/builtin/ticker-detail/adr-pair/tab.tsx +25 -14
  241. package/src/plugins/builtin/ticker-detail/overview/model.ts +17 -1
  242. package/src/plugins/builtin/ticker-detail/overview/pane.tsx +4 -0
  243. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +9 -2
  244. package/src/plugins/builtin/ticker-detail/quote-monitor/card.tsx +9 -2
  245. package/src/plugins/builtin/ticker-detail/quote-monitor/index.tsx +5 -2
  246. package/src/plugins/builtin/volatility/model.ts +17 -0
  247. package/src/plugins/builtin/volatility/pane.tsx +13 -4
  248. package/src/plugins/builtin/world-indices/index.tsx +2 -0
  249. package/src/plugins/builtin/world-indices/table.tsx +15 -0
  250. package/src/plugins/builtin/world-venue-map/evidence.ts +3 -2
  251. package/src/plugins/builtin/world-venue-map/headless.ts +28 -16
  252. package/src/plugins/builtin/world-venue-map/index.ts +19 -6
  253. package/src/plugins/builtin/world-venue-map/layered-pane.tsx +9 -5
  254. package/src/plugins/builtin/world-venue-map/layers.ts +33 -11
  255. package/src/plugins/builtin/world-venue-map/map.tsx +12 -0
  256. package/src/plugins/builtin/world-venue-map/pane.tsx +35 -6
  257. package/src/plugins/builtin/world-venue-map/place.ts +119 -0
  258. package/src/plugins/catalog-data.ts +20 -0
  259. package/src/plugins/catalog-lazy.ts +51 -0
  260. package/src/plugins/catalog-ui.ts +16 -18
  261. package/src/plugins/host-smoke.ts +5 -2
  262. package/src/portfolio/allocation.ts +79 -19
  263. package/src/portfolio/cash-balances.ts +76 -0
  264. package/src/portfolio/mutations.ts +43 -8
  265. package/src/public/__snapshots__/public-api.test.ts.snap +1 -0
  266. package/src/renderers/desktop/window-layouts.ts +14 -0
  267. package/src/renderers/dom/data-table/row.tsx +2 -0
  268. package/src/renderers/dom/host/tabs.tsx +57 -8
  269. package/src/renderers/dom/styles.css +13 -5
  270. package/src/renderers/electrobun/bun/desktop/backend-requests.ts +4 -0
  271. package/src/renderers/electrobun/bun/desktop/backend.ts +22 -1
  272. package/src/renderers/electrobun/bun/window/native-min-size.ts +6 -1
  273. package/src/renderers/electrobun/shared/protocol.ts +4 -0
  274. package/src/renderers/electrobun/view/cli-pane-shot-frame.tsx +50 -12
  275. package/src/renderers/electrobun/view/remote/ticker-repository.ts +10 -0
  276. package/src/series/standalone-catalog.ts +5 -4
  277. package/src/series/standalone.ts +13 -7
  278. package/src/sources/gloomberb-cloud/index.ts +14 -3
  279. package/src/sources/gloomberb-cloud/perpetuals.ts +60 -3
  280. package/src/sources/provider-router/financials.ts +20 -13
  281. package/src/sources/provider-router/index.ts +4 -0
  282. package/src/sources/provider-router/search.ts +1 -0
  283. package/src/sync/collections-contributor.ts +3 -1
  284. package/src/sync/config-merge.ts +10 -1
  285. package/src/sync/sanitize.ts +26 -2
  286. package/src/tickers/company-name-listing.ts +16 -2
  287. package/src/tickers/listing-fate.ts +12 -8
  288. package/src/tickers/renamed-listings.ts +43 -10
  289. package/src/tickers/search/home-listing.ts +28 -0
  290. package/src/tickers/search/index.ts +19 -7
  291. package/src/tickers/terminal-codes.ts +11 -1
  292. package/src/time-series/resolve.ts +3 -1
  293. package/src/time-series/spec.ts +2 -2
  294. package/src/time-series/types.ts +1 -1
  295. package/src/types/data-provider.ts +11 -0
  296. package/src/types/financials.ts +39 -3
  297. package/src/types/ticker.ts +10 -2
  298. package/src/utils/cli-output.ts +1 -1
  299. package/src/utils/declared-dividends.ts +13 -1
  300. package/src/utils/dividend-cash.ts +5 -1
  301. package/src/utils/forward-dividend.ts +4 -3
  302. package/src/utils/remove-folder.ts +37 -0
  303. package/src/utils/trailing-dividend.ts +1 -1
  304. package/src/plugins/builtin/composite-plugins.ts +0 -285
@@ -1,3 +1,4 @@
1
+ import { splitShareTerms } from "../../market-data/split-terms";
1
2
  import { logFailure } from "../../utils/log-failure";
2
3
  import { isTransientFailure } from "../../api-client/errors";
3
4
  import { normalizeTickerSymbol } from "../../tickers/search/ranking";
@@ -14,10 +15,12 @@ import { shortStoryId } from "../../news/story-id";
14
15
  import type {
15
16
  AnalystResearchData,
16
17
  CorporateActionsData,
18
+ DemergerAction,
17
19
  HolderData,
18
20
  OptionsChain,
19
21
  PricePoint,
20
22
  Quote,
23
+ SplitAction,
21
24
  TickerFinancials,
22
25
  } from "../../types/financials";
23
26
  import { currencyPriceMinDigits, formatMarketPrice, formatMarketPriceWithCurrency, nearParCoinPriceDigits, penceFigure, quoteFormatOptions, withCurrencyMinorDigits } from "../../market-data/market/format";
@@ -125,7 +128,7 @@ import {
125
128
  } from "../../utils/exchange-announcements";
126
129
  import { dailyFxLeg, fxCloseOnDate, fxCloseOnOrBefore, loadDailyFxCloses, type FxCloseReading } from "../../market-data/fx-closes";
127
130
  import { zonedDateTimeParts } from "../../utils/zoned-date-time";
128
- import { declaredDividends } from "../../utils/declared-dividends";
131
+ import { declaredDividendCash, declaredDividends } from "../../utils/declared-dividends";
129
132
  import {
130
133
  DEFAULT_LEAPS_CRITERIA, LEAPS_EXTRA_COLUMNS, LEAPS_USAGE, parseLeapsCriteria, runLeapsScreen, takeLeapsOptions,
131
134
  } from "./options-leaps";
@@ -141,6 +144,7 @@ import {
141
144
  import { historyCoverageNotice, WindowBeforeFirstBarError } from "../../sources/history-coverage";
142
145
  import { fetchHistoryResult } from "../../sources/history-result";
143
146
  import { settleWithin } from "../../utils/async-deadline";
147
+ import { demergerRuns, demergerSuccessor, hasPriceBreak, historyDemergerNote, withDemergerFlags } from "../history-demergers";
144
148
  import type { FxInterventionsPayload } from "../../api-client/fx-interventions";
145
149
  import {
146
150
  fxInterventionLatestNote, fxInterventionPair, fxInterventionWindowNote, loadFxInterventions, type FxInterventionPair,
@@ -285,6 +289,7 @@ import {
285
289
  failUnchosenListing,
286
290
  futureByWordLine,
287
291
  loadBareVenues,
292
+ isMovedSymbolFailure,
288
293
  loadForListing,
289
294
  ownedCodeNotes,
290
295
  loadListingQuote,
@@ -331,7 +336,7 @@ import { secRegistrantMismatchMessage, SecRegistrantMismatchError, areDifferentC
331
336
  import { isCryptoPairSymbol, isRoundTheClockCoin } from "../../utils/crypto-pair";
332
337
  import { canonicalExchange, isUsListingExchange } from "../../utils/exchanges";
333
338
  import { listingSuffixVenue } from "../../sources/listing-symbols";
334
- import { resolveTickerInstrumentKind } from "../../tickers/instrument-kind";
339
+ import { classifyInstrumentType, resolveTickerInstrumentKind } from "../../tickers/instrument-kind";
335
340
  import {
336
341
  describeFormerIssuer, describeTickerChange, movedAwayChange, startTickerChangeLookup, tickerChangeLine, type FormerIssuer, type TickerChange,
337
342
  } from "../../tickers/ticker-changes";
@@ -1107,6 +1112,13 @@ function cleanDecimal(value: number | undefined): string {
1107
1112
  return value == null || !Number.isFinite(value) ? "" : String(Number(value.toFixed(6)));
1108
1113
  }
1109
1114
 
1115
+ /** "commercial vehicles into TMCV:NSE (Tata Motors Limited), 1 share per share, listed 2025-11-12". */
1116
+ function demergerDetail(event: DemergerAction): string {
1117
+ return [`${event.business ? `${event.business} ` : ""}into ${demergerSuccessor(event)}`,
1118
+ event.ratio ? `${cleanDecimal(event.ratio)} share per share` : null,
1119
+ event.successor.listedOn ? `listed ${event.successor.listedOn}` : "not yet listed"].filter(Boolean).join(", ");
1120
+ }
1121
+
1110
1122
  function corporateActionRows(data: CorporateActionsData) {
1111
1123
  const currency = /^[A-Z]{3}$/.test(data.currency ?? "") ? data.currency! : null;
1112
1124
  // EPS is in the reporting currency, which can differ from the listing's dividends (Tencent: CNY vs HKD).
@@ -1147,16 +1159,27 @@ function corporateActionRows(data: CorporateActionsData) {
1147
1159
  detail: currency ? formatDistributionAmount(event.amount, currency) : cleanDecimal(event.amount),
1148
1160
  })),
1149
1161
  // Declared and unpaid, at its ex-date beside the paid rows, never one of them.
1150
- ...declaredDividends(data).map((event) => ({
1151
- type: "dividend",
1152
- date: event.exDate,
1153
- detail: `declared ${event.special ? "special " : ""}${currency ? formatDistributionAmount(event.amount, currency) : cleanDecimal(event.amount)}`
1154
- + (event.payDate ? `, payable ${event.payDate}` : ""),
1155
- })),
1162
+ ...declaredDividends(data).map((event) => {
1163
+ const cash = declaredDividendCash(event, currency);
1164
+ return {
1165
+ type: "dividend",
1166
+ date: event.exDate,
1167
+ detail: `declared ${event.special ? "special " : ""}${currency || event.cashEstimate ? cash.amount : cleanDecimal(event.amount)}${cash.estimate ? `, ${cash.estimate}` : ""}`
1168
+ + (event.payDate ? `, payable ${event.payDate}` : ""),
1169
+ ...(event.cashEstimate ? { cashEstimate: event.cashEstimate } : {}),
1170
+ };
1171
+ }),
1172
+ // In share terms where the factor states them (11-for-10, 1 new share for every 10 held), else as its source writes it.
1156
1173
  ...data.splits.map((event) => ({
1157
1174
  type: "split",
1158
1175
  date: event.date,
1159
- detail: event.description ?? `${event.fromFactor ?? ""}:${event.toFactor ?? ""}`,
1176
+ detail: splitShareTerms(event) ?? event.description ?? `${event.toFactor ?? ""}:${event.fromFactor ?? ""}`,
1177
+ })),
1178
+ // A business demerged out of the listing: its price fell by that business's value on the day, no market move.
1179
+ ...(data.demergers ?? []).map((event) => ({
1180
+ type: "demerger",
1181
+ date: event.exDate,
1182
+ detail: demergerDetail(event),
1160
1183
  })),
1161
1184
  ].sort((left, right) => right.date.localeCompare(left.date));
1162
1185
  }
@@ -1874,6 +1897,8 @@ interface ListingHistory {
1874
1897
  fx?: HistoryConversion;
1875
1898
  /** A catalog series (`CAP:bond-yield:jp-10y`) read beside listings: its values are in `close`, and are no price. */
1876
1899
  catalogSeries?: true;
1900
+ /** The bars a business was demerged out of the listing at (flag `demerger`): a drawdown is measured within the runs between them. */
1901
+ demergers?: Array<{ date: string; action: DemergerAction }>;
1877
1902
  }
1878
1903
 
1879
1904
  /**
@@ -2162,7 +2187,10 @@ async function loadListingHistory(
2162
2187
  const identity = listingIdentity(listing, quote);
2163
2188
  // Without a quote currency, the listing metadata research reads (as `ticker` does) may still state it.
2164
2189
  const listed = quote?.currency ? quote : await market.dataProvider.getQuoteMetadata?.(symbol, exchange).catch(logFailure("cli.commands-market", "Read quote metadata for history failed", null));
2165
- const unit = historyUnit(listing.key, listed ?? quote, await priceUnit);
2190
+ // With neither, the currency the listing was saved with from search (TMPV on NSE trades in INR) still names the unit.
2191
+ const savedCurrency = listing.saved?.metadata.currency?.trim();
2192
+ const unit = historyUnit(listing.key, listed?.currency || quote?.currency || !savedCurrency ? listed ?? quote
2193
+ : { ...listed ?? quote ?? {}, currency: savedCurrency }, await priceUnit);
2166
2194
  const mostTraded = /=F$/i.test(listing.symbol) && (await futuresTerms)?.roll?.mostTraded === true;
2167
2195
  const traded = {
2168
2196
  listing: listing.key, exchange: quote?.listingExchangeName || exchange || undefined, instrumentType: quote?.instrumentType,
@@ -2191,7 +2219,15 @@ async function loadListingHistory(
2191
2219
  const forming = formingPeriodBar(served, venue);
2192
2220
  // A complete one is dated by the day its last session closed, the day its close is from.
2193
2221
  const closedDay = forming ? null : closedPeriodBarDay(served, venue);
2194
- const data = forming?.rows ?? served;
2222
+ // A close that falls a fifth or more below the one before can be a business demerged out of the listing (TMPV's
2223
+ // commercial vehicles on 2025-10-14): its corporate actions say, and that bar is flagged rather than read as a crash.
2224
+ // One read of the listing's corporate actions serves both, asked only for a share or a fund.
2225
+ const actions = shareActionsReader(market, listing, instrumentType);
2226
+ const demerged = await listingDemergerFlags(forming?.rows ?? served, actions);
2227
+ const data = demerged.rows;
2228
+ // NFLX's bars across its 10-for-1 split are in post-split shares, as META's FB-era bars say they were FB's. A long
2229
+ // list skips the read, as it skips the other lookups.
2230
+ const splitNote = lookups ? historySplitNote(listing.symbol, data, await actions.splits()) : null;
2195
2231
  const interval = data[0]?.interval ?? null;
2196
2232
  // Intraday bars print in UTC, as the charts and time and sales label them, not the host zone.
2197
2233
  const intraday = data.some((row) => row.date.length > 10);
@@ -2253,15 +2289,71 @@ async function loadListingHistory(
2253
2289
  historyVenueVolumeNote(data) ?? [],
2254
2290
  // NG=F's rows are November's to the 23rd and December's from the 26th: each roll named, and thin bars said.
2255
2291
  historyRollNote(listing.symbol, data, { mostTraded }) ?? [], historyThinNote(data) ?? [],
2292
+ historyDemergerNote(data, demerged.breaks, historyPrice(historyPriceDecimals(data, listing.saved?.metadata.assetCategory, priceDivisor))) ?? [],
2293
+ splitNote ?? [],
2256
2294
  historyBarStatusNote(forming ? served : data, { tradingDay: venueTradingDay(venue, Date.now()) }) ?? [],
2257
2295
  await interventionWindowNote(interventions, interventionPair, data) ?? [],
2258
2296
  ].flat();
2259
2297
  return {
2260
2298
  listing, identity, unit, data, resolution, interval, intraday, volume, freshness, notes, mostTraded,
2261
2299
  decimals: historyPriceDecimals(data, listing.saved?.metadata.assetCategory, priceDivisor),
2300
+ ...demerged.breaks.length > 0 ? { demergers: demerged.breaks } : {},
2262
2301
  };
2263
2302
  }
2264
2303
 
2304
+ /** How long a history waits for the corporate actions it reads beside a price break; the bars are served without them after. */
2305
+ const DEMERGER_READ_WAIT_MS = 3_000;
2306
+
2307
+ /**
2308
+ * A listing's corporate actions, read at most once and only for a share or a fund: a future, a pair or an index has
2309
+ * no business to split or demerge. `splits` reads them for the bars' splits; `demergers` only once a close has fallen
2310
+ * a fifth or more (hasPriceBreak). Fails soft, and waits no longer than DEMERGER_READ_WAIT_MS.
2311
+ */
2312
+ function shareActionsReader(market: MarketContext, listing: CliListing, instrumentType: string | undefined) {
2313
+ const kind = classifyInstrumentType(instrumentType ?? "");
2314
+ const share = (kind === "equity" || kind === "fund" || !instrumentType)
2315
+ && !isFuturesInstrument(listing.symbol, instrumentType ?? null) && !isCurrencyPairListing(listing.symbol, listing.request.exchange)
2316
+ && typeof market.dataProvider.getCorporateActions === "function";
2317
+ let read: Promise<CorporateActionsData | null> | null = null;
2318
+ const actions = () => read ??= settleWithin(Promise.resolve().then(() => market.dataProvider.getCorporateActions!(listing.request.symbol, listing.request.exchange))
2319
+ .catch(logFailure("cli.commands-market", "Read corporate actions for a history failed", null)), DEMERGER_READ_WAIT_MS)
2320
+ .then((value) => value ?? null);
2321
+ return {
2322
+ share,
2323
+ splits: async (): Promise<SplitAction[]> => share ? (await actions())?.splits ?? [] : [],
2324
+ demergers: async (): Promise<DemergerAction[]> => share ? (await actions())?.demergers ?? [] : [],
2325
+ };
2326
+ }
2327
+
2328
+ /** A share's bars with the bar each demerger falls in flagged (withDemergerFlags), read only when a close falls a fifth or more below the one before. */
2329
+ async function listingDemergerFlags(
2330
+ rows: HistoryRow[],
2331
+ actions: ReturnType<typeof shareActionsReader>,
2332
+ ): Promise<{ rows: HistoryRow[]; breaks: Array<{ date: string; action: DemergerAction }> }> {
2333
+ if (!actions.share || !hasPriceBreak(rows)) return { rows, breaks: [] };
2334
+ return withDemergerFlags(rows, await actions.demergers());
2335
+ }
2336
+
2337
+ /**
2338
+ * "Splits in range: NFLX 10-for-1 on 2025-11-17; bars before it are split-adjusted.": the splits that took effect
2339
+ * after the first bar shown and by the last, which the bars run across in post-split shares. Null with none, or for
2340
+ * a factor no share count states (a spinoff's price adjustment, which the demerger note covers).
2341
+ */
2342
+ function historySplitNote(symbol: string, rows: readonly HistoryRow[], splits: readonly SplitAction[]): string | null {
2343
+ const first = rows[0]?.date.slice(0, 10);
2344
+ const last = rows.at(-1)?.date.slice(0, 10);
2345
+ if (!first || !last || first === last) return null;
2346
+ const inside = splits
2347
+ .filter((split) => /^\d{4}-\d{2}-\d{2}/.test(split.date) && split.date.slice(0, 10) > first && split.date.slice(0, 10) <= last)
2348
+ .sort((left, right) => left.date.localeCompare(right.date))
2349
+ .flatMap((split) => {
2350
+ const terms = splitShareTerms(split);
2351
+ return terms ? [`${terms.split(",")[0]} on ${split.date.slice(0, 10)}`] : [];
2352
+ });
2353
+ if (inside.length === 0) return null;
2354
+ return `Splits in range: ${symbol} ${inside.join(" and ")}; bars before ${inside.length === 1 ? "it" : "each"} are split-adjusted.`;
2355
+ }
2356
+
2265
2357
  /**
2266
2358
  * A bare symbol with no quote whose US listing stopped trading is that
2267
2359
  * listing's history: a source can answer the bare symbol with a listing
@@ -2465,13 +2557,19 @@ async function runHistory(rawArgs: string[], ctx: Parameters<CliCommandDef["exec
2465
2557
  const closes = (interval === "1wk" || interval === "1mo"
2466
2558
  ? data.map((row) => ({ ...row, date: barCloseSession(interval, row.date, identity.exchange || undefined, Date.now()) }))
2467
2559
  : data).filter((row) => !row.flag?.split(",").includes(CLOSE_COPIED_FLAG));
2468
- const contractDrawdown = historyContractDrawdown(closes, yieldUnits ? "yield" : "return");
2560
+ // Nor from a close that held a business the listing demerged to one that did not (TMPV before 2025-10-14): split
2561
+ // before each bar flagged `demerger`, whatever date its close is given, and named by the demerger's own day.
2562
+ const demergedOn = history.demergers?.map((entry) => entry.action.exDate) ?? [];
2563
+ const contractDrawdown = demergedOn.length > 0
2564
+ ? deepestRunDrawdown(demergerRuns(closes).map((run) => historyContractDrawdown(run, yieldUnits ? "yield" : "return")))
2565
+ : historyContractDrawdown(closes, yieldUnits ? "yield" : "return");
2469
2566
  // A window's last week can close after the dates asked for (--to 2003, a week ending Fri 2 Jan 2004): measured to its end.
2470
2567
  const until = ask.window?.to;
2471
2568
  const drawdown = contractDrawdown ? measuredUntil(contractDrawdown.drawdown, until) : null;
2472
2569
  const rose = yieldUnits ? maxRunUp(closes) : null;
2473
2570
  const runUp = rose && measuredUntil(rose, until);
2474
- const moveText = interval ? { basis: `${BAR_INTERVAL_LABELS[interval]} closes${contractDrawdown?.contract ? `, ${contractDrawdown.contract}` : ""}`, price,
2571
+ const across = demergedOn.length > 0 ? `, not across the ${demergedOn.join(" and ")} ${demergedOn.length === 1 ? "demerger" : "demergers"}` : "";
2572
+ const moveText = interval ? { basis: `${BAR_INTERVAL_LABELS[interval]} closes${contractDrawdown?.contract ? `, ${contractDrawdown.contract}` : ""}${across}`, price,
2475
2573
  date: (text: string) => intraday ? formatUtcTime(text) : text.slice(0, 10) } : null;
2476
2574
  ctx.printResult({
2477
2575
  data,
@@ -2490,6 +2588,7 @@ async function runHistory(rawArgs: string[], ctx: Parameters<CliCommandDef["exec
2490
2588
  unbrokenFrom: historyUnbrokenFrom(data) ?? data[0]?.date ?? null,
2491
2589
  bars: data.length,
2492
2590
  maxDrawdown: drawdown && contractDrawdown?.contract ? { ...drawdown, contract: contractDrawdown.contract } : drawdown,
2591
+ ...(history.demergers ? { demergers: history.demergers.map(({ date, action }) => ({ bar: date, ...action })) } : {}),
2493
2592
  ...(runUp ? { maxRunUp: runUp } : {}),
2494
2593
  asOf: freshness?.asOf ?? null,
2495
2594
  ...(history.fx ? { converted: history.fx } : {}),
@@ -2514,6 +2613,12 @@ async function runHistory(rawArgs: string[], ctx: Parameters<CliCommandDef["exec
2514
2613
  });
2515
2614
  }
2516
2615
 
2616
+ /** The deepest of the drawdowns measured within each run between demergers. */
2617
+ function deepestRunDrawdown(runs: ReadonlyArray<ReturnType<typeof historyContractDrawdown>>): ReturnType<typeof historyContractDrawdown> {
2618
+ const depth = (entry: NonNullable<ReturnType<typeof historyContractDrawdown>>) => entry.drawdown.bp ?? entry.drawdown.drawdown;
2619
+ return runs.reduce<ReturnType<typeof historyContractDrawdown>>((deepest, run) => run && (!deepest || depth(run) < depth(deepest)) ? run : deepest, null);
2620
+ }
2621
+
2517
2622
  /** The window from `years` back to today. */
2518
2623
  function yearsBackWindow(years: number): PriceWindow | null {
2519
2624
  const from = new Date();
@@ -2992,9 +3097,15 @@ async function runFinancials(rawArgs: string[], ctx: Parameters<CliCommandDef["e
2992
3097
  await withMarketData(ctx, async (market) => {
2993
3098
  const listing = await requireCliListing(raw, exchangeOption, market, ctx);
2994
3099
  const venues = loadBareVenues(listing, market);
2995
- const loaded = await loadForListing(listing, market, ctx, () => market.dataProvider.getTickerFinancials(
3100
+ // The statements carry the listing's quote: what says whether the line can have moved, with no read of its own.
3101
+ const read = market.dataProvider.getTickerFinancials(
2996
3102
  listing.request.symbol, listing.request.exchange, { cacheMode: ctx.cliOptions.refresh ? "refresh" : "default" },
2997
- ), undefined, { command: commandName, noun: commandName === "valuation" ? "valuation data" : commandName });
3103
+ );
3104
+ const loaded = await loadForListing(listing, market, ctx, () => read, undefined,
3105
+ { command: commandName, noun: commandName === "valuation" ? "valuation data" : commandName, quote: read.then((found) => found.quote ?? null, () => {
3106
+ // Intentional ignore: this is the same read loadForListing awaits as the command's load, which reports its failure.
3107
+ return null;
3108
+ }) });
2998
3109
  // A converted TTM block at the rate `fx` reports, as `ticker` shows it; only the US dollar legs are read.
2999
3110
  // A withdrawn EV's bridge converts a balance sheet in another currency at our close on its date (withBalanceSheetRate).
3000
3111
  const financials = view === "statements" ? loaded
@@ -3478,7 +3589,7 @@ async function runFilings(rawArgs: string[], ctx: Parameters<CliCommandDef["exec
3478
3589
  hidden = shown.hidden;
3479
3590
  return shown.filings;
3480
3591
  }),
3481
- (found) => found.length === 0),
3592
+ (found) => found.length === 0, { command: form ? `filings --form ${form}` : "filings", noun: "SEC filings", quote: quotePromise }),
3482
3593
  quotePromise,
3483
3594
  ]);
3484
3595
  const hiddenNote = hidden ? hiddenFilingsNote(hidden) : null;
@@ -3706,7 +3817,8 @@ async function printBeneficialOwners(
3706
3817
  const abroad = nonUsSecListingVenue(symbol, exchange) ? listingIdentity(listing, await quotePromise) : null;
3707
3818
  const request = { form: beneficialRouteForm(form), history, listing: { exchange, name: abroad?.name ?? undefined } };
3708
3819
  const [payload, holders, quote, financials] = await Promise.all([
3709
- loadForListing(listing, market, ctx, () => fetchBeneficialOwners(symbol, request)),
3820
+ loadForListing(listing, market, ctx, () => fetchBeneficialOwners(symbol, request), undefined,
3821
+ { command: `holders --form ${form}${history ? " --history" : ""}`, noun: "beneficial owners", quote: quotePromise }),
3710
3822
  market.dataProvider.getHolders?.(symbol, exchange).catch(logFailure("cli.commands-market", "Read company holders failed", null)) ?? null,
3711
3823
  quotePromise,
3712
3824
  // Today's share count, which the filed percents are set against.
@@ -3790,8 +3902,10 @@ async function runHolders(
3790
3902
  listing, market, ctx,
3791
3903
  () => market.dataProvider.getHolders(listing.request.symbol, listing.request.exchange),
3792
3904
  (found) => found.holders.length === 0,
3793
- { command: commandName, noun: "holder data" },
3905
+ { command: commandName, noun: "holder data", quote: quoted },
3794
3906
  ).catch(async (error: unknown) => {
3907
+ // A symbol whose company moved names its new symbol, as every command does.
3908
+ if (isMovedSymbolFailure(error)) throw error;
3795
3909
  // A fund has no ownership breakdown, and a listing may have no holders on record: say so
3796
3910
  // (and what reads a fund) rather than the source's NO_DATA.
3797
3911
  const none = await noHoldersAnswer(listing.key, listing.request.exchange, error, await quoted, apiClient);
@@ -3923,13 +4037,14 @@ async function runAnalyst(rawArgs: string[], ctx: Parameters<CliCommandDef["exec
3923
4037
  await withMarketData(ctx, async (market) => {
3924
4038
  const listing = await requireCliListing(raw, exchangeOption, market, ctx);
3925
4039
  const venues = loadBareVenues(listing, market);
4040
+ const quoted = loadListingQuote(market.dataProvider, listing);
3926
4041
  const [data, quote] = await Promise.all([
3927
4042
  loadForListing(
3928
4043
  // A listing no analyst covers loads as research with nothing in it, said below rather than failed.
3929
4044
  listing, market, ctx, () => loadAnalystResearch(market.dataProvider, listing.request.symbol, listing.request.exchange),
3930
- undefined, { command: "analyst", noun: "analyst research" },
4045
+ undefined, { command: "analyst", noun: "analyst research", quote: quoted },
3931
4046
  ),
3932
- loadListingQuote(market.dataProvider, listing),
4047
+ quoted,
3933
4048
  ]);
3934
4049
  const identity = listingIdentity(listing, quote);
3935
4050
  const choice = await listingChoiceNotes(listing, market, quote, venues);
@@ -3980,12 +4095,13 @@ async function runEvents(rawArgs: string[], ctx: Parameters<CliCommandDef["execu
3980
4095
  // The earnings rows are resolved against the calendar `earnings` reads, so the next report is the same in both.
3981
4096
  const calendar = market.dataProvider.getEarningsCalendar?.([listing.key])
3982
4097
  .catch(logFailure("cli.commands-market", "Read the earnings calendar for events failed", [] as EarningsEvent[]));
4098
+ const quoted = loadListingQuote(market.dataProvider, listing);
3983
4099
  const [recorded, quote, events] = await Promise.all([
3984
4100
  loadForListing(
3985
4101
  listing, market, ctx, () => market.dataProvider.getCorporateActions(listing.request.symbol, listing.request.exchange),
3986
- undefined, { command: "events", noun: "corporate events" },
4102
+ undefined, { command: "events", noun: "corporate events", quote: quoted },
3987
4103
  ),
3988
- loadListingQuote(market.dataProvider, listing),
4104
+ quoted,
3989
4105
  calendar,
3990
4106
  ]);
3991
4107
  const data = withResolvedEarnings(recorded, calendarEventOf(events, listing.key), newYorkDay());
@@ -108,6 +108,7 @@ import {
108
108
  } from "./fred-series";
109
109
  import { fredProvenance, fredPublicationTime, notOnFredSource } from "../../sources/gloomberb-cloud/fred-attribution";
110
110
  import { followsUsBondMarket, usBondMarketClosedNote } from "../../market-data/us-bond-market";
111
+ import { commandWord } from "../../utils/shell-word";
111
112
 
112
113
  /** The Actual of a release its publisher could not compute; the notes say why. */
113
114
  const NOT_PUBLISHED_TEXT = "not published";
@@ -1091,10 +1092,15 @@ async function runCorrelation(rawArgs: string[], ctx: Parameters<CliCommandDef["
1091
1092
  const right = rightListing!.key;
1092
1093
  // Same daily-return model as the CORR pane: price levels of two trending
1093
1094
  // assets correlate spuriously, often with the opposite sign.
1095
+ // Each symbol's quote, read once: whether its line can have moved, and where its daily close is taken below.
1096
+ const quotes = new Map([leftListing!, rightListing!].map((listing) => [listing, loadListingQuote(services.dataProvider, listing)] as const));
1094
1097
  const loadSeries = async (listing: CliListing) => {
1098
+ // A symbol whose company moved is asked again under its new symbol, the other one kept.
1099
+ const retry = (key: string) => `gloom correlation ${listing === leftListing ? `${key} ${commandWord(right)}` : `${commandWord(left)} ${key}`}`;
1095
1100
  const bars = await loadForListing(
1096
1101
  listing, services, ctx,
1097
1102
  () => loadCorrelationHistory(services.dataProvider, listing.request.symbol, listing.request.exchange, "1Y"),
1103
+ undefined, { command: "correlation", noun: "history", retry, quote: quotes.get(listing)! },
1098
1104
  );
1099
1105
  return { ...buildCorrelationSeries(listing.key, bars), bars: bars.length };
1100
1106
  };
@@ -1109,7 +1115,7 @@ async function runCorrelation(rawArgs: string[], ctx: Parameters<CliCommandDef["
1109
1115
  .map((series) => series.rollNote ? `${series.symbol}: ${series.rollNote}` : null),
1110
1116
  ].filter((note) => note != null);
1111
1117
  // A bare symbol names no exchange; its quote says where it lists, which sets when its daily close is taken.
1112
- const [leftQuote, rightQuote] = await Promise.all([leftListing!, rightListing!].map((listing) => loadListingQuote(services.dataProvider, listing)));
1118
+ const [leftQuote, rightQuote] = await Promise.all([leftListing!, rightListing!].map((listing) => quotes.get(listing)!));
1113
1119
  const sessionNote = mixedSessionCloseNote(
1114
1120
  { symbol: leftListing!.symbol, exchange: listingIdentity(leftListing!, leftQuote).exchange, label: left },
1115
1121
  { symbol: rightListing!.symbol, exchange: listingIdentity(rightListing!, rightQuote).exchange, label: right },
@@ -1,5 +1,5 @@
1
1
  import { basename, join, resolve } from "path";
2
- import { existsSync, lstatSync, readFileSync, rmSync } from "fs";
2
+ import { existsSync, lstatSync, readFileSync } from "fs";
3
3
  import {
4
4
  DEPRECATED_HOST_EXPORTS,
5
5
  REMOVED_HOST_EXPORTS,
@@ -31,6 +31,7 @@ import {
31
31
  } from "../../plugins/installer";
32
32
  import { isReservedBuiltinPluginId } from "../../plugins/ownership";
33
33
  import { pluginFromModule, pluginSupportsTarget } from "../../plugins/plugin-export";
34
+ import { removeFolder } from "../../utils/remove-folder";
34
35
  import { formatVersion, requiredGloomberb } from "../../utils/semver";
35
36
  import { ALL_PLUGIN_TARGETS, type GloomPlugin, type PluginTarget } from "../../types/plugin";
36
37
  import {
@@ -311,7 +312,7 @@ async function doctorPlugin(nameOrPath: string): Promise<PluginDoctorReport> {
311
312
  const result = await bundleExternalPlugin(candidate, outDir, { define: { "process.env.NODE_ENV": "\"production\"" } });
312
313
  const size = Math.round(Bun.file(result.outputPath).size / 1024);
313
314
  add("browser-build", "ok", `${basename(browserEntry ?? entryFile)} compiles for the desktop view (${size}KB)`);
314
- rmSync(outDir, { recursive: true, force: true });
315
+ await removeFolder(outDir);
315
316
  } catch (error) {
316
317
  const message = error instanceof Error ? error.message : String(error);
317
318
  add("browser-build", "fail", `Desktop build failed: ${message.split("\n")[0]}. Ship an index.browser.ts without node:* imports, or set targets to ["cli", "tui"].`);
@@ -22,7 +22,7 @@ import {
22
22
  type TickerSearchCandidate,
23
23
  } from "../../tickers/search";
24
24
  import { initMarketData, withMarketData } from "../context";
25
- import { listingChangeLine, loadListingFate, loadNoQuoteEnding, noLongerListedNote, noQuoteLastTradeNote, type NoQuoteEnding } from "../../tickers/listing-fate";
25
+ import { listingChangeLine, loadListingFate, loadNoQuoteEnding, noLongerListedNote, noQuoteLastTradeNote, tradingListing, type NoQuoteEnding } from "../../tickers/listing-fate";
26
26
  import { formatMarketPriceWithCurrency, quoteFormatOptions, withCurrencyMinorDigits } from "../../market-data/market/format";
27
27
  import { formerIssuerLine, startTickerChangeLookup, type TickerChangeLookup } from "../../tickers/ticker-changes";
28
28
  import { fail, failRetryable, failWithError, isCliFailure, unreachableError } from "../errors";
@@ -48,6 +48,7 @@ import { hasNonLatinLetters } from "../../utils/typed-text";
48
48
  import { isKanjiOnlyName, japaneseNameReadAs, readExactJapaneseName, readJapaneseName, type JapaneseNameListing } from "../../tickers/search/japanese-names";
49
49
 
50
50
  interface SearchCommandDependencies {
51
+ limit?: number;
51
52
  initMarketData?: () => Promise<MarketContext>;
52
53
  fail?: (message: string, details?: string) => never;
53
54
  printResult?: CliCommandContext["printResult"];
@@ -128,7 +129,7 @@ export async function searchCandidatesForCli({
128
129
  localLimit,
129
130
  // Every company's listing of a symbol several use (CAR's ASX line is past the first ten), cut after ordering.
130
131
  totalLimit: Math.max(totalLimit, LISTING_SEARCH_LIMIT),
131
- searchContext: { limit: LISTING_SEARCH_LIMIT },
132
+ searchContext: { limit: Math.max(totalLimit, LISTING_SEARCH_LIMIT), perpetuals: "always" },
132
133
  });
133
134
  const symbol = trimmedQuery.toUpperCase();
134
135
  // A bare symbol search lists asks for the quote `quote SYM` reads, once, for its venue and its name:
@@ -139,7 +140,9 @@ export async function searchCandidatesForCli({
139
140
  : null;
140
141
  // A word written as a name (`Aeon`) whose company search leads with keeps it first, as `quote Aeon` reads it.
141
142
  const named = leadsWithNamedCompany(trimmedQuery, candidates, quote);
142
- const ordered = withQuotedNames(symbol, withUsLineOfPrimary(withHomeListingPrimary(trimmedQuery, withPrimaryListingFirst(symbol, candidates, named ? null : quote))), quote);
143
+ const ordered = withLiveCompanyPrimary(symbol,
144
+ withQuotedNames(symbol, withUsLineOfPrimary(withHomeListingPrimary(trimmedQuery, withPrimaryListingFirst(symbol, candidates, named ? null : quote))), quote),
145
+ quote);
143
146
  return cutKeepingCompanies(withOtherCompaniesApart(ordered, named ? trimmedQuery : null), totalLimit, symbol);
144
147
  } catch (error) {
145
148
  // Not "No matches found": a script or a reader would take that for a name nothing lists.
@@ -350,6 +353,26 @@ function withPrimaryListingFirst(
350
353
  ));
351
354
  }
352
355
 
356
+ /**
357
+ * A symbol whose own line stopped trading (DBS, the silver fund delisted in
358
+ * 2023) leads with the company the service marks by it that still trades
359
+ * (DBS Group Holdings' home line, D05 on SGX), as `quote DBS` asks after it;
360
+ * the stopped line is another match. A saved row is the user's choice and
361
+ * stays.
362
+ */
363
+ function withLiveCompanyPrimary(symbol: string, candidates: TickerSearchCandidate[], quote: Quote | null, now = Date.now()): TickerSearchCandidate[] {
364
+ const primary = candidates.find((candidate) => candidate.category === "Primary Listing");
365
+ if (!primary || primary.saved || primary.kind !== "search" || primary.symbol.toUpperCase() !== symbol) return candidates;
366
+ if (!primary.delisted && (!quote || tradingListing(quote, now))) return candidates;
367
+ const marked = (candidate: TickerSearchCandidate) => candidate !== primary && candidate.kind === "search" && !candidate.delisted
368
+ && candidate.symbol.toUpperCase() !== symbol && !!candidate.searchAliases?.some((alias) => alias.toUpperCase() === symbol);
369
+ const live = candidates.find((candidate) => marked(candidate) && candidate.homeListing === true) ?? candidates.find(marked);
370
+ if (!live) return candidates;
371
+ const rest = candidates.filter((candidate) => candidate !== live && candidate !== primary);
372
+ const at = Math.min(candidates.indexOf(primary), rest.length);
373
+ return [...rest.slice(0, at), { ...live, category: "Primary Listing" as const }, ...rest.slice(at), { ...primary, category: "Other Matches" as const }];
374
+ }
375
+
353
376
  /**
354
377
  * One company's lines of a symbol lead with the one the service marks as its
355
378
  * home, never a thin secondary line search ranked first: DHL is DHL Group's
@@ -426,11 +449,10 @@ function withHomeListingPrimary(query: string, candidates: TickerSearchCandidate
426
449
  function withUsLineOfPrimary(candidates: TickerSearchCandidate[]): TickerSearchCandidate[] {
427
450
  const primary = candidates.find((candidate) => candidate.category === "Primary Listing");
428
451
  if (!primary || primary.kind !== "search" || isUsListingExchange(candidateExchange(primary))) return candidates;
429
- const symbol = primary.symbol.toUpperCase();
430
452
  const company = resolveSearchName(primary);
431
453
  const us = candidates.find((candidate) => candidate !== primary && candidate.kind === "search" && !candidate.contractKey
432
- && candidate.category !== "Funds & Derivatives" && candidate.symbol.toUpperCase() === symbol
433
- && isUsListingExchange(candidateExchange(candidate)) && sameCompany(resolveSearchName(candidate), company));
454
+ && candidate.category !== "Funds & Derivatives"
455
+ && isUsListingExchange(candidateExchange(candidate)) && sameCompanyName(resolveSearchName(candidate), company));
434
456
  if (!us) return candidates;
435
457
  const rest = candidates.filter((candidate) => candidate !== us);
436
458
  const at = rest.indexOf(primary) + 1;
@@ -882,6 +904,7 @@ export async function search(query: string, dependencies: SearchCommandDependenc
882
904
  query: index?.symbol ?? trimmedQuery,
883
905
  tickers,
884
906
  dataProvider,
907
+ totalLimit: dependencies.limit,
885
908
  ...quote ? { quote } : {},
886
909
  }).catch((error: unknown) => failTickerLookup(error, trimmedQuery, !dependencies.printResult));
887
910
  // A name in kanji alone is the service's to read first (中電 is CLP in Hong Kong); a Tokyo company's whole name it
@@ -898,6 +921,7 @@ export async function search(query: string, dependencies: SearchCommandDependenc
898
921
  const bank = searchedCentralBank(trimmedQuery);
899
922
  // A query that names no ticker may name what a function does.
900
923
  const functions = await searchedFunctions(trimmedQuery, candidates, fate, dependencies.plugins, context);
924
+ if (!candidates.length && !fate.stopped && !series.length && !functions.length && !bank && !commandPointer(trimmedQuery)) process.exitCode = 1;
901
925
  if (dependencies.printResult) {
902
926
  const warnings = searchNotes(trimmedQuery, candidates, functions, fate);
903
927
  dependencies.printResult({
@@ -9,12 +9,13 @@ import { createAppServices } from "../core/app-services";
9
9
  import type { PluginCapability } from "../capabilities";
10
10
  import type { AppConfig } from "../types/config";
11
11
  import type { GloomPlugin } from "../types/plugin";
12
- import { standaloneSeriesCatalog, standaloneSeriesInvoker, standaloneSeriesNamed } from "../series/standalone";
12
+ import { standaloneSeriesCatalog, standaloneSeriesInvoker, standaloneSeriesNamed, type SeriesPlugins } from "../series/standalone";
13
13
  import { setStandaloneSeriesCatalog } from "../series/standalone-catalog";
14
14
  import type { PluginRegistry } from "../plugins/registry";
15
15
  import type { LoadedExternalPlugin } from "../plugins/loader";
16
16
  import { apiClient } from "../api-client";
17
17
  import { fail } from "./errors";
18
+ import { isKnownUsStock } from "./known-us-stocks";
18
19
  import { resolvePersistedCloudSessionToken } from "./pane-functions/cloud-session";
19
20
  import { cloudStatementReportSources } from "./statement-filings";
20
21
  import type { ConfigContext, MarketContext } from "./types";
@@ -22,7 +23,10 @@ import type { ConfigContext, MarketContext } from "./types";
22
23
  export { withCliServices, withConfigData, withMarketData } from "./scoped-context";
23
24
 
24
25
  interface CliContextOptions {
25
- plugins?: GloomPlugin[];
26
+ /** Every plugin that runs here. Read only once a series is looked up, so a command that never charts one loads none of them. */
27
+ plugins?: SeriesPlugins;
28
+ /** The plugins whose asset-data and news capabilities feed the data provider; every plugin when not given. */
29
+ dataPlugins?: GloomPlugin[];
26
30
  }
27
31
 
28
32
  interface CliServicesOptions {
@@ -41,7 +45,7 @@ export async function ensureCliServicesReady<T extends { ready: Promise<unknown>
41
45
  }
42
46
  }
43
47
 
44
- function resolveCliCapabilities(config: AppConfig, plugins: GloomPlugin[]): PluginCapability[] {
48
+ function resolveCliCapabilities(config: AppConfig, plugins: readonly GloomPlugin[]): PluginCapability[] {
45
49
  const disabledPlugins = new Set(config.disabledPlugins ?? []);
46
50
  const disabledSources = new Set(config.disabledSources ?? []);
47
51
  return plugins
@@ -115,8 +119,15 @@ function applyPersistedCloudSession(context: Pick<MarketContext, "persistence">)
115
119
  export async function initMarketData(options: CliContextOptions = {}): Promise<MarketContext> {
116
120
  const context = await initConfigData();
117
121
  applyPersistedCloudSession(context);
118
- const plugins = options.plugins ?? (require("../plugins/catalog") as typeof import("../plugins/catalog")).getLoadablePlugins();
119
- const capabilities = resolveCliCapabilities(context.config, plugins);
122
+ const plugins: SeriesPlugins = options.plugins ?? (() => (require("../plugins/catalog") as typeof import("../plugins/catalog")).getLoadablePlugins());
123
+ const capabilities = resolveCliCapabilities(context.config, options.dataPlugins ?? (typeof plugins === "function" ? plugins() : plugins));
124
+ // A lookup of a symbol the shipped listings show to be a US stock asks for no perpetual contracts.
125
+ const { GloomberbCloudProvider } = require("../sources/gloomberb-cloud") as typeof import("../sources/gloomberb-cloud");
126
+ for (const capability of capabilities) {
127
+ if (capability.kind === "asset-data" && "provider" in capability && capability.provider instanceof GloomberbCloudProvider) {
128
+ capability.provider.knownUsStock = isKnownUsStock;
129
+ }
130
+ }
120
131
  const dataProvider = new AssetDataRouter(null, [], context.persistence.resources);
121
132
  const registryAdapter: Pick<PluginRegistry, "brokers" | "getEnabledCapabilities"> = {
122
133
  brokers: new Map(),
@@ -1,3 +1,4 @@
1
+ import { cliText } from "../utils/cli-output";
1
2
  import { csvDecimal, serializeCsv } from "../utils/csv";
2
3
  import { splitCsvFooter } from "./report-tables";
3
4
 
@@ -58,7 +59,7 @@ export function portableCsv(text: string, warnings: readonly string[] = [], extr
58
59
  let sectionKey = "section", notesKey = "export_notes";
59
60
  while (usedNames.has(sectionKey)) sectionKey = `_${sectionKey}`;
60
61
  while (usedNames.has(notesKey)) notesKey = `_${notesKey}`;
61
- const notes = [...new Set([...footer, ...extraNotes.flatMap((note) => note.split(/\r\n?|\n/).filter(Boolean).map((line) => `note: ${line}`)), ...warnings.map((warning) => `warning: ${warning}`)].map((note) => note.replace(/\r\n?|\n/g, " | ")))].join(" | ");
62
+ const notes = [...new Set([...footer, ...extraNotes.flatMap((note) => note.split(/\r\n?|\n/).filter(Boolean).map((line) => `note: ${line}`)), ...warnings.map((warning) => `warning: ${warning}`)].map((note) => cliText(note.replace(/\r\n?|\n/g, " | "))))].join(" | ");
62
63
  const header = [...columns, ...tagged ? [sectionKey] : [], notesKey];
63
64
  const rows = tables.flatMap((table) => {
64
65
  const indices = columns.map((column) => table.columns.indexOf(column));