@gloom-sh/terminal 0.20.14 → 0.20.16

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 (144) hide show
  1. package/package.json +1 -1
  2. package/src/api-client/index.ts +54 -0
  3. package/src/api-client/install-experiments.ts +8 -7
  4. package/src/api-client/paths.ts +2 -1
  5. package/src/api-client/product-waitlist.ts +63 -0
  6. package/src/api-client/request.ts +4 -2
  7. package/src/api-client/types/billing.ts +45 -0
  8. package/src/api-client/yearly-plan.ts +132 -0
  9. package/src/app/global-shortcuts.ts +5 -3
  10. package/src/app/pane-runtime/index.tsx +2 -2
  11. package/src/app/pane-runtime/plugin-bindings.ts +3 -1
  12. package/src/app/pane-runtime/ticker-open-runtime.ts +6 -1
  13. package/src/app/since-last-visit/keys.ts +26 -0
  14. package/src/app/since-last-visit/model.ts +266 -0
  15. package/src/app/since-last-visit/strip.tsx +193 -0
  16. package/src/app/since-last-visit/use-since-last-visit.ts +289 -0
  17. package/src/app/since-last-visit/visit-tracker.ts +191 -0
  18. package/src/app.tsx +15 -0
  19. package/src/cli/commands/market.ts +8 -4
  20. package/src/cli/commands/system.ts +29 -1
  21. package/src/cli/commands/ticker.ts +12 -5
  22. package/src/cli/desktop-pane-shot-api-policy.ts +4 -1
  23. package/src/cli/desktop-pane-shot-browser.ts +2 -1
  24. package/src/cli/desktop-pane-shot-view.ts +3 -7
  25. package/src/cli/desktop-pane-shot.ts +26 -28
  26. package/src/cli/help.ts +1 -0
  27. package/src/cli/history-rows.ts +24 -0
  28. package/src/cli/index.ts +4 -0
  29. package/src/cli/options.ts +29 -1
  30. package/src/cli/pane-functions/catalog.ts +41 -4
  31. package/src/cli/pane-functions/function-help.ts +1 -1
  32. package/src/cli/pane-functions/headless.ts +63 -1
  33. package/src/cli/pane-functions/index.ts +2 -2
  34. package/src/cli/pane-functions/resolver.ts +43 -0
  35. package/src/cli/pane-functions/screenshot-payload.ts +3 -0
  36. package/src/cli/report-tables.ts +20 -5
  37. package/src/cli/shot-temp-dir.ts +30 -0
  38. package/src/cli/suffixed-listing-rows.ts +11 -0
  39. package/src/components/chart/composite/composite-chart.tsx +3 -3
  40. package/src/components/command-bar/commands/direct/index.ts +31 -8
  41. package/src/components/command-bar/commands/registry.ts +7 -0
  42. package/src/components/command-bar/routes/root/command-items.ts +8 -0
  43. package/src/components/command-bar/routes/root/results.ts +16 -0
  44. package/src/components/company-logo.tsx +10 -3
  45. package/src/components/data-table/sections.ts +6 -1
  46. package/src/components/layout/pane/title.ts +6 -2
  47. package/src/components/layout/shell/index.tsx +5 -1
  48. package/src/components/layout/shell/ticker-link-menu.ts +12 -9
  49. package/src/components/ticker/badge/format.ts +12 -3
  50. package/src/components/ticker/badge/index.tsx +9 -3
  51. package/src/components/ticker/list-table-view.tsx +119 -17
  52. package/src/components/ui/data-table/display-columns.ts +16 -0
  53. package/src/components/ui/data-table/index.tsx +40 -9
  54. package/src/components/ui/data-table/types.ts +14 -0
  55. package/src/core/state/app/layout-reducer.ts +3 -1
  56. package/src/core/state/app/layout.ts +2 -2
  57. package/src/data/config/layout.ts +14 -0
  58. package/src/data/config/store/normalize.ts +11 -1
  59. package/src/i18n/es.ts +38 -0
  60. package/src/i18n/ja.ts +38 -0
  61. package/src/i18n/ko.ts +38 -0
  62. package/src/i18n/zh-cn.ts +38 -0
  63. package/src/i18n/zh-tw.ts +38 -0
  64. package/src/layout/pane-follow.ts +141 -4
  65. package/src/layout/pane-layout-move.ts +10 -7
  66. package/src/layout/ticker-navigation.ts +13 -19
  67. package/src/layout/ticker-retarget.ts +3 -2
  68. package/src/market-data/market/index-level.ts +19 -0
  69. package/src/plugins/builtin/account-management/keyboard.ts +14 -0
  70. package/src/plugins/builtin/account-management/model.ts +2 -0
  71. package/src/plugins/builtin/account-management/pane.tsx +79 -7
  72. package/src/plugins/builtin/account-management/payment-recovery-row.tsx +97 -0
  73. package/src/plugins/builtin/account-management/yearly-plan-row.tsx +359 -0
  74. package/src/plugins/builtin/awards/pane.tsx +6 -8
  75. package/src/plugins/builtin/changelog/index.tsx +6 -44
  76. package/src/plugins/builtin/changelog/versions.ts +17 -68
  77. package/src/plugins/builtin/cloud/askg/executor.ts +2 -1
  78. package/src/plugins/builtin/cloud/askg/sources.ts +2 -1
  79. package/src/plugins/builtin/cpi/pane.tsx +1 -1
  80. package/src/plugins/builtin/debt-maturities/model.ts +1 -1
  81. package/src/plugins/builtin/earnings/board-table.ts +1 -1
  82. package/src/plugins/builtin/earnings/board.tsx +36 -16
  83. package/src/plugins/builtin/earnings/highlight.ts +47 -0
  84. package/src/plugins/builtin/earnings/history-table.ts +1 -1
  85. package/src/plugins/builtin/earnings/index.tsx +1 -1
  86. package/src/plugins/builtin/earnings-calls/pane.tsx +2 -2
  87. package/src/plugins/builtin/estimate-revisions/model.ts +1 -1
  88. package/src/plugins/builtin/exposure/index.tsx +1 -1
  89. package/src/plugins/builtin/macro-day/model.ts +6 -4
  90. package/src/plugins/builtin/market-valuation/detail.tsx +3 -3
  91. package/src/plugins/builtin/market-valuation/headless.ts +11 -4
  92. package/src/plugins/builtin/market-valuation/pane.tsx +3 -1
  93. package/src/plugins/builtin/market-valuation/view.ts +14 -0
  94. package/src/plugins/builtin/news/wire/news/detail-view.tsx +20 -8
  95. package/src/plugins/builtin/pe-band/pane.tsx +1 -1
  96. package/src/plugins/builtin/portfolio-list/cli/render.ts +8 -1
  97. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +176 -17
  98. package/src/plugins/builtin/portfolio-list/pane/groups.tsx +220 -0
  99. package/src/plugins/builtin/portfolio-list/pane/index.tsx +90 -15
  100. package/src/plugins/builtin/portfolio-list/table.tsx +13 -1
  101. package/src/plugins/builtin/research/corporate-actions-pane.tsx +4 -2
  102. package/src/plugins/builtin/research/relative-valuation-headless.ts +15 -5
  103. package/src/plugins/builtin/research/relative-valuation-model.ts +7 -1
  104. package/src/plugins/builtin/research/relative-valuation-pane.tsx +7 -4
  105. package/src/plugins/builtin/shared/headless-options.ts +1 -1
  106. package/src/plugins/builtin/social-mentions/model.ts +2 -2
  107. package/src/plugins/builtin/thirteenf/pane.tsx +1 -1
  108. package/src/plugins/builtin/ticker-detail/financials/model.ts +51 -16
  109. package/src/plugins/builtin/ticker-detail/financials/nopat.ts +16 -0
  110. package/src/plugins/builtin/ticker-detail/financials/ratios.ts +44 -13
  111. package/src/plugins/builtin/ticker-detail/financials/schema.ts +33 -2
  112. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +4 -2
  113. package/src/plugins/builtin/ticker-detail/headless-schema.ts +30 -4
  114. package/src/plugins/builtin/ticker-detail/headless.ts +254 -34
  115. package/src/plugins/builtin/ticker-detail/overview/model.ts +7 -3
  116. package/src/plugins/builtin/ticker-detail/pharma-signals/eligibility.ts +32 -0
  117. package/src/plugins/builtin/ticker-detail/pharma-signals/tab.tsx +162 -0
  118. package/src/plugins/builtin/ticker-detail/pharma-signals/waitlist.ts +126 -0
  119. package/src/plugins/builtin/ticker-detail/research-groups.ts +6 -4
  120. package/src/plugins/builtin/ticker-detail/research-tabs.ts +11 -0
  121. package/src/portfolio/column-values.ts +20 -8
  122. package/src/portfolio/suffixed-listings.ts +3 -1
  123. package/src/portfolio/watchlist-groups.ts +212 -0
  124. package/src/react/ticker-source.ts +3 -1
  125. package/src/renderers/dom/styles.css +7 -0
  126. package/src/state/app/bootstrap.ts +11 -0
  127. package/src/state/app/context/index.tsx +6 -0
  128. package/src/sync/collections-contributor.ts +5 -2
  129. package/src/sync/config-merge.ts +10 -2
  130. package/src/sync/sanitize.ts +28 -0
  131. package/src/telemetry/usage-counts.ts +17 -0
  132. package/src/time-series/chart-seed.ts +1 -1
  133. package/src/time-series/financial-period-coverage.ts +4 -12
  134. package/src/time-series/parsed-history-cache.ts +1 -1
  135. package/src/time-series/resolve.ts +1 -1
  136. package/src/time-series/use-chart-resolution.ts +6 -1
  137. package/src/types/config.ts +32 -0
  138. package/src/types/headless.ts +5 -0
  139. package/src/types/plugin-context.ts +5 -0
  140. package/src/types/ticker.ts +14 -0
  141. package/src/ui/ascii-font.ts +1 -4
  142. package/src/utils/async-deadline.ts +2 -2
  143. package/src/utils/csv.ts +44 -5
  144. package/src/utils/futures-generic.ts +3 -0
@@ -1,6 +1,7 @@
1
1
  import type { AppConfig, BrokerInstanceConfig } from "../types/config";
2
2
  import type { Portfolio, TickerPosition, Watchlist } from "../types/ticker";
3
3
  import { isRecord } from "../utils/guards";
4
+ import { normalizeWatchlistGroups } from "../portfolio/watchlist-groups";
4
5
 
5
6
  const SENSITIVE_KEY_PATTERN = /(token|secret|password|credential|private|api[_-]?key|access[_-]?key|refresh[_-]?key|session|cookie|dataDir|path|directory|localPath)/i;
6
7
 
@@ -77,11 +78,38 @@ export function sanitizePortfolio(portfolio: Portfolio): Portfolio {
77
78
  };
78
79
  }
79
80
 
81
+ /**
82
+ * Set on every payload this build pushes with watchlists: its lists carry their
83
+ * groups, so one without `groups` has none. An older build's lists never carry
84
+ * them, and taken as they came they would erase the groups here and then
85
+ * everywhere this device pushes to.
86
+ */
87
+ export const WATCHLISTS_CARRY_GROUPS = "watchlistsCarryGroups";
88
+
89
+ /**
90
+ * Pulled watchlists, each list an older build pushed (no `WATCHLISTS_CARRY_GROUPS`)
91
+ * keeping the groups it has here; a build that sends groups is taken as it
92
+ * came, so a group removed there is removed here.
93
+ */
94
+ export function withLocalWatchlistGroups(pulled: unknown[], local: readonly Watchlist[], carriesGroups: boolean): Watchlist[] {
95
+ if (carriesGroups) return pulled as Watchlist[];
96
+ return pulled.map((entry) => {
97
+ if (!isRecord(entry) || entry.groups !== undefined) return entry as unknown as Watchlist;
98
+ const groups = local.find((watchlist) => watchlist.id === entry.id)?.groups;
99
+ return (groups ? { ...entry, groups } : entry) as unknown as Watchlist;
100
+ });
101
+ }
102
+
80
103
  export function sanitizeWatchlist(watchlist: Watchlist): Watchlist {
104
+ // The user's own sections: a pulled list without them would erase them on this device. A list
105
+ // without groups goes as before. They are an array, never keyed by a name or symbol, which
106
+ // `sanitizeUnknown` would drop for reading like a secret (a Private group, the PATH ticker).
107
+ const groups = normalizeWatchlistGroups(watchlist.groups);
81
108
  return {
82
109
  id: watchlist.id,
83
110
  name: watchlist.name,
84
111
  description: watchlist.description,
112
+ ...(groups ? { groups } : {}),
85
113
  };
86
114
  }
87
115
 
@@ -241,6 +241,23 @@ export function recordRestoredFunctions(fns: readonly UsageFunction[]): void {
241
241
  }
242
242
  }
243
243
 
244
+ /**
245
+ * Counts a function that put itself on screen at launch, with nothing opened
246
+ * by the user (the since-last-visit strip): in `restored`, never `opened`, and
247
+ * no open listener hears of it. Unlike `recordRestoredFunctions` it can be
248
+ * called on its own, once the function knows it showed. Never throws.
249
+ */
250
+ export function recordFunctionShown(fn: UsageFunction): void {
251
+ try {
252
+ if (automationDepth > 0) return;
253
+ if (host && !host.isEnabled()) return;
254
+ count(fn, "restored");
255
+ scheduleFlush();
256
+ } catch (error) {
257
+ logFailure("telemetry-usage-counts", "Could not record a function shown at launch")(error);
258
+ }
259
+ }
260
+
244
261
  /** The install as its usage counts name it: the random install id, the surface and the OS. */
245
262
  export interface UsageInstall {
246
263
  installId: string;
@@ -85,7 +85,7 @@ export function seedChartResolutionResult(
85
85
  const facts = readSeedListingFacts(seriesSpec.source.instrument);
86
86
  const { symbol, exchange } = seriesSpec.source.instrument;
87
87
  const bars = builtBarSize ? aggregatePriceBars(history, builtBarSize, { symbol, exchange }) : history;
88
- const base = baseSecuritySeries(seriesSpec, emptyFinancials(bars), index, resolution, facts?.quoteMetadata, facts?.contractUnit);
88
+ const base = baseSecuritySeries(seriesSpec, emptyFinancials(bars), index, resolution, facts?.quoteMetadata ?? undefined, facts?.contractUnit);
89
89
  const resolved = base && builtBarSize ? withBuiltBarSize(base, builtBarSize) : base;
90
90
  if (!resolved?.points.length) return;
91
91
  if (hidden) {
@@ -15,19 +15,11 @@ export function limitSeriesObservations(spec: ChartSpec, series: ResolvedSeries)
15
15
  if (!isFinancialSeries(definition)) {
16
16
  return { ...series, points: series.points.slice(-spec.viewport.maxPoints) };
17
17
  }
18
+ // The latest N periods, a missing one among them, so `--periods 5` reads the last five fiscal years and never reaches
19
+ // back past a gap for older ones; the gap stays a point so a chart cannot draw through it, and the coverage counts
20
+ // how many of the N have a value.
18
21
  const points = series.points.filter((point) => point.periodLabel !== "Current");
19
- let remaining = spec.viewport.maxPoints;
20
- let start = points.length;
21
- for (let index = points.length - 1; index >= 0; index--) {
22
- if (!isUsableFinancialObservation(points[index]!)) continue;
23
- start = index;
24
- if (--remaining <= 0) break;
25
- }
26
- // Count usable observations, but retain missing periods within the selected
27
- // history and at its end so charts cannot draw through absent financial data.
28
- // If coverage is short, retain leading gaps too: they explain which requested
29
- // periods failed, including the case where every observation is unavailable.
30
- return { ...series, points: points.slice(remaining > 0 ? 0 : start) };
22
+ return { ...series, points: points.slice(-spec.viewport.maxPoints) };
31
23
  }
32
24
 
33
25
  export interface FinancialPeriodCoverage {
@@ -33,7 +33,7 @@ export function parsedPriceHistoryKey(
33
33
  * moment later moves the plot and redraws every label.
34
34
  */
35
35
  interface SeedListingFacts {
36
- quoteMetadata?: QuoteMetadata;
36
+ quoteMetadata?: QuoteMetadata | null;
37
37
  /** What a future's price counts ("USD / gallon"), so a seed states the unit the settled chart will. */
38
38
  contractUnit?: string;
39
39
  resolutionSupport?: ChartResolutionSupport[];
@@ -991,7 +991,7 @@ async function resolveChartSpecPass(
991
991
  if (marketField) {
992
992
  // Same precedence as baseSecuritySeries: the quote's own facts first.
993
993
  const listingFacts = mergeQuoteMetadata(merged.quote ? quoteMetadataFromQuote(merged.quote) : undefined, quoteMetadata);
994
- if (listingFacts?.currency || listingFacts?.instrumentType) rememberSeedListingFacts(source.instrument, { quoteMetadata: listingFacts });
994
+ rememberSeedListingFacts(source.instrument, { quoteMetadata: listingFacts ?? null });
995
995
  if (contractUnit) rememberSeedListingFacts(source.instrument, { contractUnit });
996
996
  }
997
997
  if (history) {
@@ -33,6 +33,7 @@ import { withFormulaNextMonths } from "./formula-months";
33
33
  import {
34
34
  parsedPriceHistoryKey,
35
35
  readParsedHistoryResult,
36
+ readSeedListingFacts,
36
37
  } from "./parsed-history-cache";
37
38
 
38
39
  export interface UseChartResolutionResult extends ChartResolutionResult {
@@ -223,7 +224,11 @@ export function useChartResolution(
223
224
  const now = sources.now ?? new Date();
224
225
  // The first paint prices a formula's legs in one month as the settled chart does, from the next months it read.
225
226
  const seedSpec = withFormulaNextMonths(spec);
226
- return seedChartResolutionResult(seedSpec, collectSeedHistory(seedSpec, now, options), now, options);
227
+ const history = collectSeedHistory(seedSpec, now, options);
228
+ if (seedSpec.series.some(({ source }) => source.kind === "security"
229
+ && history.has(chartQuoteOverrideKeyForSource(source))
230
+ && readSeedListingFacts(source.instrument)?.quoteMetadata === undefined)) return null;
231
+ return seedChartResolutionResult(seedSpec, history, now, options);
227
232
  };
228
233
  const [state, setState] = useState(() => ({
229
234
  key: specKey,
@@ -103,6 +103,25 @@ export interface PaneInstanceConfig {
103
103
  locked?: boolean;
104
104
  /** Set by Move to New Layout and cleared by Move Back; never published. */
105
105
  movedFrom?: PaneMovedFrom;
106
+ /** Set when a follower was pinned on its ticker; read only while it follows nothing. Never published. */
107
+ unlinkedFrom?: PaneUnlinkedFrom;
108
+ }
109
+
110
+ /**
111
+ * The link a follower left when it was pinned on the ticker it showed. Its title says so
112
+ * (`AAPL ⧉ Unlinked`) until it is linked again.
113
+ */
114
+ export interface PaneUnlinkedFrom {
115
+ /** The pane it followed. */
116
+ instanceId: string;
117
+ /** That pane's kind (`portfolio-list`), so a research pane can follow a new one of it. */
118
+ paneId?: string;
119
+ /**
120
+ * The app cut the link, not the user: the source closed or left the layout, or another
121
+ * research pane took it. A research pane pinned this way follows again once its source, or
122
+ * one of that kind, is in the layout with no research pane of its own (`relinkPinnedResearchPanes`).
123
+ */
124
+ auto?: true;
106
125
  }
107
126
 
108
127
  interface DockPaneNode {
@@ -380,6 +399,13 @@ export interface AppConfig {
380
399
  * are never shifted by it.
381
400
  */
382
401
  timezone?: string;
402
+ /**
403
+ * The decimal mark CSV exports write numbers with, the CLI's and the app's:
404
+ * `comma` writes `17,2` with cells split by `;`, as a spreadsheet in a
405
+ * decimal-comma locale reads them. Absent is the dot. Text and JSON keep
406
+ * the dot. Kept on this machine only.
407
+ */
408
+ csvDecimal?: "comma" | "dot";
383
409
  /**
384
410
  * Presentation mode: the panes fill the window, without the header or the
385
411
  * status bar, for a screen that is shown rather than worked at. Absent is off.
@@ -390,6 +416,12 @@ export interface AppConfig {
390
416
  * benchmark of this machine's time zone. Kept on this machine only.
391
417
  */
392
418
  headerMarket?: HeaderMarketChoice;
419
+ /**
420
+ * The strip above the layout that says what moved in the user's portfolios
421
+ * and watchlists since their last visit. `false` turns it off; absent means
422
+ * on. Kept on this machine only.
423
+ */
424
+ sinceLastVisit?: boolean;
393
425
  }
394
426
 
395
427
  /** A benchmark the header offers, by its id (`hang-seng`), or any listing the user searched for. */
@@ -240,6 +240,11 @@ export interface HeadlessPaneColumn {
240
240
  * screen; JSON keeps the row's figure whole.
241
241
  */
242
242
  exportAsShown?: boolean;
243
+ /**
244
+ * A column the export gained after its others were set (RV's `Fwd P/E period`): CSV and NDJSON write it last,
245
+ * after the fixed columns and `retrieved_at`, so no column an earlier export had moves.
246
+ */
247
+ exportLast?: boolean;
243
248
  /**
244
249
  * The text report prints the value on its own lines under the row instead
245
250
  * of in a column, for a footnote that belongs to that row; an empty value
@@ -53,6 +53,11 @@ export interface PinTickerOptions {
53
53
  tabId?: string;
54
54
  /** Merge this state into the resolved research pane when selecting `tabId`. */
55
55
  tabState?: Record<string, unknown>;
56
+ /**
57
+ * A pinned pane of `paneType` that shows the ticker instead of a new one, when no pane shows
58
+ * it yet: Enter on a list row with no research pane of its own.
59
+ */
60
+ reusePaneId?: string;
56
61
  }
57
62
 
58
63
  export interface GloomPluginContext {
@@ -117,10 +117,24 @@ export interface PortfolioCash {
117
117
  currency: string;
118
118
  }
119
119
 
120
+ /** A named section of a watchlist's tickers (`Watchlist.groups`). */
121
+ export interface WatchlistGroup {
122
+ name: string;
123
+ /** The tickers' keys (`TickerMetadata.ticker`); a ticker is in one group of a list at most. */
124
+ symbols: string[];
125
+ }
126
+
120
127
  export interface Watchlist {
121
128
  id: string;
122
129
  name: string;
123
130
  description?: string;
124
131
  /** Set on watchlists shared with a team; the server holds the items. */
125
132
  teamId?: string;
133
+ /**
134
+ * Sections the user put the list's tickers in, in the order they show; a
135
+ * ticker in none shows under Ungrouped. Kept on the list, not the ticker, so
136
+ * a ticker on two lists can sit in a different group on each. Absent on a
137
+ * list without groups, which shows and syncs as it did before groups.
138
+ */
139
+ groups?: WatchlistGroup[];
126
140
  }
@@ -72,10 +72,7 @@ const GLOOMBERB_WORDMARK = [
72
72
  /** The first five letters of the wordmark above. */
73
73
  const GLOOM_WORDMARK = GLOOMBERB_WORDMARK.map((line) => line.slice(0, 15));
74
74
 
75
- /**
76
- * The drawn wordmarks, by the text they spell. The app is Gloom; chart
77
- * screenshots keep the Gloomberb watermark.
78
- */
75
+ /** The drawn wordmarks, by the text they spell. */
79
76
  const WORDMARKS = new Map<string, string[]>([
80
77
  ["gloom", GLOOM_WORDMARK],
81
78
  ["gloomberb", GLOOMBERB_WORDMARK],
@@ -53,8 +53,8 @@ export function abortable<T>(promise: Promise<T>, signal: AbortSignal | undefine
53
53
  if (!signal) return promise;
54
54
  return new Promise<T>((resolve, reject) => {
55
55
  const abort = () => reject(abortError(message));
56
- if (signal.aborted) { abort(); return; }
57
- signal.addEventListener("abort", abort, { once: true });
56
+ if (signal.aborted) abort();
57
+ else signal.addEventListener("abort", abort, { once: true });
58
58
  promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
59
59
  });
60
60
  }
package/src/utils/csv.ts CHANGED
@@ -23,22 +23,61 @@ function normalizeCsvCell(value: unknown): string {
23
23
  return String(value);
24
24
  }
25
25
 
26
- function escapeCsvCell(value: unknown, excelCompatible: boolean): string {
26
+ /**
27
+ * The decimal mark a CSV writes its numbers with. `comma` is what a
28
+ * spreadsheet set to a decimal-comma locale (German, French, Brazilian) reads
29
+ * as a number: `17,2`, never the date `17.2` becomes. Its cells are then
30
+ * separated by `;`, as those spreadsheets read them, so a decimal comma never
31
+ * splits a cell. Text, dates and JSON are never changed.
32
+ */
33
+ export type CsvDecimal = "dot" | "comma";
34
+
35
+ let defaultDecimal: CsvDecimal = "dot";
36
+
37
+ /**
38
+ * The decimal mark every CSV is written with unless the caller names one:
39
+ * the `csvDecimal` setting, or `--decimal` for one command. Null or absent is
40
+ * the dot.
41
+ */
42
+ export function setCsvDecimal(decimal: CsvDecimal | null | undefined): void {
43
+ defaultDecimal = decimal === "comma" ? "comma" : "dot";
44
+ }
45
+
46
+ /** The decimal mark CSVs are written with now (setCsvDecimal). */
47
+ export function csvDecimal(): CsvDecimal {
48
+ return defaultDecimal;
49
+ }
50
+
51
+ /** The cell separator that goes with a decimal mark: `;` beside a decimal comma, `,` beside a dot. */
52
+ function csvSeparator(decimal: CsvDecimal = defaultDecimal): string {
53
+ return decimal === "comma" ? ";" : ",";
54
+ }
55
+
56
+ /** `1,234.5` and `-0.07%` as a decimal-comma spreadsheet reads them: `1234,5` and `-0,07%`. Other text stays. */
57
+ function withDecimalComma(text: string): string {
58
+ if (!isNumericCsvText(text)) return text;
59
+ return text.trim().replace(/,/g, "").replace(".", ",");
60
+ }
61
+
62
+ function escapeCsvCell(value: unknown, excelCompatible: boolean, decimal: CsvDecimal): string {
27
63
  const normalized = normalizeCsvCell(value);
28
64
  // A signed number is data, not a formula: "-2.10" must stay a number.
29
- const text = excelCompatible && FORMULA_START.test(normalized) && !isNumericCsvText(normalized)
65
+ const guarded = excelCompatible && FORMULA_START.test(normalized) && !isNumericCsvText(normalized)
30
66
  ? `'${normalized}`
31
67
  : normalized;
32
- if (!/[",\n\r]/.test(text)) return text;
68
+ const text = decimal === "comma" && (typeof value === "number" || typeof value === "string") ? withDecimalComma(guarded) : guarded;
69
+ const separator = csvSeparator(decimal);
70
+ if (!text.includes(separator) && !/["\n\r]/.test(text)) return text;
33
71
  return `"${text.replace(/"/g, '""')}"`;
34
72
  }
35
73
 
36
74
  export function serializeCsv(
37
75
  rows: readonly (readonly unknown[])[],
38
- options: { excelCompatible?: boolean } = {},
76
+ options: { excelCompatible?: boolean; decimal?: CsvDecimal } = {},
39
77
  ): string {
40
78
  const excelCompatible = options.excelCompatible === true;
41
- const csv = rows.map((row) => row.map((cell) => escapeCsvCell(cell, excelCompatible)).join(",")).join("\n");
79
+ const decimal = options.decimal ?? defaultDecimal;
80
+ const csv = rows.map((row) => row.map((cell) => escapeCsvCell(cell, excelCompatible, decimal)).join(csvSeparator(decimal))).join("\n");
42
81
  return excelCompatible ? `${EXCEL_CSV_BOM}${csv}` : csv;
43
82
  }
44
83
 
@@ -240,6 +240,9 @@ export function futuresContractMonth(code: string): { root: string; month: numbe
240
240
  export function venueOfDatedContract(code: string): string | null {
241
241
  const match = /^([A-Z0-9]{1,4}?)([FGHJKMNQUVXZ])(\d{2})$/.exec(code.trim().toUpperCase());
242
242
  if (!match) return null;
243
+ const year = 2000 + Number(match[3]);
244
+ const currentYear = new Date().getUTCFullYear();
245
+ if (year < currentYear - 1 || year > currentYear + 10) return null;
243
246
  const root = ALIASES[match[1]!] ?? match[1]!;
244
247
  const venue = ROOT_VENUES[root];
245
248
  return venue ? `${root}${match[2]}${match[3]}.${venue}` : null;