@narumitw/pi-ticker 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/menu.ts ADDED
@@ -0,0 +1,241 @@
1
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+ import { parseSymbols } from "./settings.js";
3
+
4
+ type Screen = "tickers" | "order" | "move";
5
+ type Action =
6
+ | "toggle"
7
+ | "addCustom"
8
+ | "toggleWidget"
9
+ | "chooseTicker"
10
+ | "moveUp"
11
+ | "moveDown"
12
+ | "refresh";
13
+
14
+ export interface TickerMenuOptions {
15
+ signal: AbortSignal;
16
+ isCurrent(): boolean;
17
+ getSymbols(): readonly string[];
18
+ applySymbols(symbols: readonly string[], signal: AbortSignal): Promise<void>;
19
+ getWidgetEnabled(): boolean;
20
+ applyWidgetEnabled(widgetEnabled: boolean, signal: AbortSignal): Promise<void>;
21
+ refresh(): void;
22
+ }
23
+
24
+ export async function showTickerMenu(
25
+ ctx: ExtensionCommandContext,
26
+ options: TickerMenuOptions,
27
+ ): Promise<void> {
28
+ if (options.signal.aborted || !options.isCurrent()) return;
29
+ if (ctx.mode === "tui") {
30
+ const { showTickerTuiMenu } = await import("./tui-menu.js");
31
+ if (options.signal.aborted || !options.isCurrent()) return;
32
+ await showTickerTuiMenu(ctx, options);
33
+ return;
34
+ }
35
+
36
+ const { defineMenu, runMenu, sanitizeTerminalText } = await import("@narumitw/pi-tui-kit");
37
+ if (options.signal.aborted || !options.isCurrent()) return;
38
+ let menuCandidates = [...options.getSymbols()];
39
+ let movingSymbol: string | undefined;
40
+ const candidates = () => {
41
+ for (const symbol of options.getSymbols()) {
42
+ if (!menuCandidates.includes(symbol)) menuCandidates.push(symbol);
43
+ }
44
+ return menuCandidates;
45
+ };
46
+ const menu = defineMenu<undefined, Screen, Action, ExtensionCommandContext>({
47
+ start: "tickers",
48
+ screens: {
49
+ tickers: () => {
50
+ const selected = new Set(options.getSymbols());
51
+ return {
52
+ kind: "multiSelect",
53
+ title: "Manage tickers",
54
+ lines: [`${selected.size} selected · uncheck to remove · changes save immediately`],
55
+ items: candidates().map((symbol) => ({
56
+ id: symbol,
57
+ label: symbol,
58
+ description: "Display this Yahoo Finance symbol in the editor widget.",
59
+ selected: selected.has(symbol),
60
+ searchText: symbol.replaceAll("-", " "),
61
+ })),
62
+ action: "toggle",
63
+ enableSearch: true,
64
+ viewportSize: 10,
65
+ actions: [
66
+ {
67
+ id: "add-custom",
68
+ label: "Add custom ticker…",
69
+ description: "Add and select one Yahoo Finance symbol.",
70
+ action: "addCustom",
71
+ },
72
+ ...(selected.size > 1
73
+ ? [
74
+ {
75
+ id: "reorder",
76
+ label: "Reorder tickers…",
77
+ description: "Change the order shown in the editor widget.",
78
+ to: "order" as const,
79
+ },
80
+ ]
81
+ : []),
82
+ {
83
+ id: "widget-enabled",
84
+ label: `Widget: ${options.getWidgetEnabled() ? "On" : "Off"}`,
85
+ description: "Show or hide the editor widget and persist this setting.",
86
+ action: "toggleWidget",
87
+ },
88
+ {
89
+ id: "refresh",
90
+ label: "Refresh now",
91
+ description: options.getWidgetEnabled()
92
+ ? "Fetch the selected symbols immediately."
93
+ : "Enable the widget before refreshing.",
94
+ action: "refresh",
95
+ },
96
+ ],
97
+ hint: "close",
98
+ doneLabel: "Close",
99
+ };
100
+ },
101
+ order: () => ({
102
+ kind: "choice",
103
+ title: "Ticker order",
104
+ lines: ["Choose a ticker to move."],
105
+ items: options.getSymbols().map((symbol, index) => ({
106
+ id: symbol,
107
+ label: `${index + 1}. ${symbol}`,
108
+ description: "Select this ticker, then move it up or down.",
109
+ })),
110
+ action: "chooseTicker",
111
+ viewportSize: 10,
112
+ }),
113
+ move: () => {
114
+ const symbols = options.getSymbols();
115
+ const index = movingSymbol ? symbols.indexOf(movingSymbol) : -1;
116
+ const available = index >= 0;
117
+ return {
118
+ kind: "actions",
119
+ title: movingSymbol ? `Move ${movingSymbol}` : "Move ticker",
120
+ lines: [
121
+ available
122
+ ? `Position ${index + 1} of ${symbols.length}`
123
+ : "Ticker is no longer selected.",
124
+ `Order: ${symbols.join(" · ")}`,
125
+ ],
126
+ items: [
127
+ {
128
+ id: "move-up",
129
+ label: "Move up",
130
+ description: "Move this ticker one position toward the start.",
131
+ disabled: !available || index === 0,
132
+ disabledReason: !available
133
+ ? "Ticker is unavailable"
134
+ : index === 0
135
+ ? "Already first"
136
+ : undefined,
137
+ action: "moveUp",
138
+ },
139
+ {
140
+ id: "move-down",
141
+ label: "Move down",
142
+ description: "Move this ticker one position toward the end.",
143
+ disabled: !available || index === symbols.length - 1,
144
+ disabledReason: !available
145
+ ? "Ticker is unavailable"
146
+ : index === symbols.length - 1
147
+ ? "Already last"
148
+ : undefined,
149
+ action: "moveDown",
150
+ },
151
+ ],
152
+ };
153
+ },
154
+ },
155
+ actions: {
156
+ toggle: async ({ itemId, selected, signal }) => {
157
+ if (!candidates().includes(itemId)) return { kind: "rejected" };
158
+ const next = new Set(options.getSymbols());
159
+ if (selected) next.add(itemId);
160
+ else next.delete(itemId);
161
+ await options.applySymbols(orderedSymbols(next, candidates()), signal);
162
+ if (signal.aborted || !options.isCurrent()) return { kind: "stay" };
163
+ if (!selected) menuCandidates = menuCandidates.filter((symbol) => symbol !== itemId);
164
+ return { kind: "stay" };
165
+ },
166
+ addCustom: async ({ ctx: actionCtx, signal }) => {
167
+ const entered = await actionCtx.ui.input(
168
+ "Add custom ticker",
169
+ "Yahoo symbol, for example MSFT or SOL-USD",
170
+ { signal },
171
+ );
172
+ if (signal.aborted || !options.isCurrent()) return { kind: "stay" };
173
+ if (!entered?.trim()) return { kind: "stay" };
174
+ const parsed = parseSymbols([entered]);
175
+ if (parsed.length !== 1) throw new Error("Enter exactly one Yahoo Finance symbol.");
176
+ const symbol = parsed[0];
177
+ if (!symbol) return { kind: "stay" };
178
+ const selected = new Set(options.getSymbols());
179
+ if (selected.has(symbol)) {
180
+ actionCtx.ui.notify(`${symbol} is already selected.`, "info");
181
+ return { kind: "stay" };
182
+ }
183
+ selected.add(symbol);
184
+ await options.applySymbols([...selected], signal);
185
+ if (signal.aborted || !options.isCurrent()) return { kind: "stay" };
186
+ if (!menuCandidates.includes(symbol)) menuCandidates.push(symbol);
187
+ return { kind: "stay" };
188
+ },
189
+ toggleWidget: async ({ signal }) => {
190
+ await options.applyWidgetEnabled(!options.getWidgetEnabled(), signal);
191
+ if (signal.aborted || !options.isCurrent()) return { kind: "stay" };
192
+ return { kind: "stay" };
193
+ },
194
+ chooseTicker: ({ itemId }) => {
195
+ if (!options.getSymbols().includes(itemId)) return { kind: "rejected" };
196
+ movingSymbol = itemId;
197
+ return { kind: "to", screen: "move" };
198
+ },
199
+ moveUp: ({ signal }) => moveSelectedTicker(-1, signal),
200
+ moveDown: ({ signal }) => moveSelectedTicker(1, signal),
201
+ refresh: () => {
202
+ options.refresh();
203
+ return { kind: "stay" };
204
+ },
205
+ },
206
+ });
207
+
208
+ async function moveSelectedTicker(direction: -1 | 1, signal: AbortSignal) {
209
+ const current = options.getSymbols();
210
+ const from = movingSymbol ? current.indexOf(movingSymbol) : -1;
211
+ const to = from + direction;
212
+ if (from < 0 || to < 0 || to >= current.length) return { kind: "rejected" } as const;
213
+ const next = [...current];
214
+ const [symbol] = next.splice(from, 1);
215
+ if (!symbol) return { kind: "rejected" } as const;
216
+ next.splice(to, 0, symbol);
217
+ await options.applySymbols(next, signal);
218
+ if (signal.aborted || !options.isCurrent()) return { kind: "stay" } as const;
219
+ menuCandidates = [...next];
220
+ return { kind: "stay" } as const;
221
+ }
222
+
223
+ await runMenu(ctx, menu, {
224
+ getState: () => undefined,
225
+ signal: options.signal,
226
+ isCurrent: options.isCurrent,
227
+ onError: (menuCtx, error) => {
228
+ if (!menuCtx.hasUI) return;
229
+ const message = error instanceof Error ? error.message : String(error);
230
+ menuCtx.ui.notify(sanitizeTerminalText(message), "error");
231
+ },
232
+ onUnsupportedMode: (menuCtx, mode) => {
233
+ if (menuCtx.hasUI)
234
+ menuCtx.ui.notify(`Ticker menu is unavailable in ${mode} mode.`, "warning");
235
+ },
236
+ });
237
+ }
238
+
239
+ function orderedSymbols(selected: ReadonlySet<string>, candidates: readonly string[]): string[] {
240
+ return candidates.filter((symbol) => selected.has(symbol));
241
+ }
package/src/quotes.ts ADDED
@@ -0,0 +1,104 @@
1
+ export const QUOTE_ENDPOINT = "https://query1.finance.yahoo.com/v8/finance/chart";
2
+
3
+ export interface Quote {
4
+ symbol: string;
5
+ price: number;
6
+ previousClose: number;
7
+ change: number;
8
+ changePercent: number;
9
+ currency?: string;
10
+ marketTime?: number;
11
+ }
12
+
13
+ export interface QuoteResult {
14
+ symbol: string;
15
+ quote?: Quote;
16
+ error?: string;
17
+ }
18
+
19
+ export class QuoteRequestTimeoutError extends Error {
20
+ constructor() {
21
+ super("Quote request timed out.");
22
+ this.name = "QuoteRequestTimeoutError";
23
+ }
24
+ }
25
+
26
+ export async function fetchQuotes(
27
+ symbols: readonly string[],
28
+ signal: AbortSignal,
29
+ fetchImplementation: typeof fetch = fetch,
30
+ ): Promise<QuoteResult[]> {
31
+ return Promise.all(
32
+ symbols.map(async (symbol): Promise<QuoteResult> => {
33
+ try {
34
+ const quote = await fetchQuote(symbol, signal, fetchImplementation);
35
+ return { symbol, quote };
36
+ } catch (error) {
37
+ if (signal.aborted) {
38
+ if (!(signal.reason instanceof QuoteRequestTimeoutError)) throw error;
39
+ return { symbol, error: signal.reason.message };
40
+ }
41
+ return { symbol, error: errorMessage(error) };
42
+ }
43
+ }),
44
+ );
45
+ }
46
+
47
+ async function fetchQuote(
48
+ symbol: string,
49
+ signal: AbortSignal,
50
+ fetchImplementation: typeof fetch,
51
+ ): Promise<Quote> {
52
+ const url = `${QUOTE_ENDPOINT}/${encodeURIComponent(symbol)}?interval=1m&range=1d`;
53
+ const response = await fetchImplementation(url, {
54
+ headers: { "User-Agent": "pi-ticker/1.0" },
55
+ signal,
56
+ });
57
+ if (!response.ok) throw new Error(`Quote request failed with HTTP ${response.status}.`);
58
+ return parseQuote(symbol, await response.json());
59
+ }
60
+
61
+ export function parseQuote(requestedSymbol: string, payload: unknown): Quote {
62
+ const chart = asRecord(payload)?.chart;
63
+ const result = asRecord(chart)?.result;
64
+ const first = Array.isArray(result) ? asRecord(result[0]) : undefined;
65
+ const meta = asRecord(first?.meta);
66
+ const price = finiteNumber(meta?.regularMarketPrice);
67
+ const previousClose = finiteNumber(meta?.previousClose) ?? finiteNumber(meta?.chartPreviousClose);
68
+ if (price === undefined || previousClose === undefined || previousClose === 0) {
69
+ throw new Error("Quote response did not include a usable price and previous close.");
70
+ }
71
+ const change = price - previousClose;
72
+ const currency = safeCurrency(meta?.currency);
73
+ const marketTimeSeconds = finiteNumber(meta?.regularMarketTime);
74
+ return {
75
+ symbol: requestedSymbol,
76
+ price,
77
+ previousClose,
78
+ change,
79
+ changePercent: (change / previousClose) * 100,
80
+ ...(currency ? { currency } : {}),
81
+ ...(marketTimeSeconds === undefined ? {} : { marketTime: marketTimeSeconds * 1000 }),
82
+ };
83
+ }
84
+
85
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
86
+ return value && typeof value === "object" && !Array.isArray(value)
87
+ ? (value as Record<string, unknown>)
88
+ : undefined;
89
+ }
90
+
91
+ function finiteNumber(value: unknown): number | undefined {
92
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
93
+ }
94
+
95
+ function safeCurrency(value: unknown): string | undefined {
96
+ if (value === "GBp") return value;
97
+ if (typeof value !== "string") return undefined;
98
+ const normalized = value.toUpperCase();
99
+ return /^[A-Z]{3}$/.test(normalized) ? normalized : undefined;
100
+ }
101
+
102
+ function errorMessage(error: unknown): string {
103
+ return error instanceof Error ? error.message : String(error);
104
+ }
package/src/render.ts ADDED
@@ -0,0 +1,163 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+ import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
3
+ import type { Quote } from "./quotes.js";
4
+
5
+ export interface TickerItem {
6
+ symbol: string;
7
+ quote?: Quote;
8
+ error?: string;
9
+ stale?: boolean;
10
+ }
11
+
12
+ export interface TickerView {
13
+ items: TickerItem[];
14
+ loading: boolean;
15
+ updatedAt?: number;
16
+ }
17
+
18
+ export function renderTickerWidget(view: TickerView, theme: Theme, width: number): string[] {
19
+ const renderWidth = Math.max(0, width);
20
+ if (renderWidth === 0) return [""];
21
+ const heading = renderHeading(view, theme);
22
+ const separator = theme.fg("dim", " │ ");
23
+ const quotes = packItems(
24
+ view.items.map((item) => renderItem(item, theme)),
25
+ separator,
26
+ renderWidth,
27
+ );
28
+ return [
29
+ theme.fg("borderMuted", "─".repeat(renderWidth)),
30
+ ...fitLines(heading, renderWidth),
31
+ ...quotes,
32
+ ];
33
+ }
34
+
35
+ export function formatTickerPlain(view: TickerView): string[] {
36
+ const status = view.loading
37
+ ? "Stocks · updating"
38
+ : view.updatedAt
39
+ ? `Stocks · updated ${new Date(view.updatedAt).toLocaleTimeString()}`
40
+ : "Stocks";
41
+ return [status, ...view.items.map(formatItemPlain)];
42
+ }
43
+
44
+ export function mergeQuoteResults(
45
+ current: readonly TickerItem[],
46
+ results: ReadonlyArray<{ symbol: string; quote?: Quote; error?: string }>,
47
+ ): TickerItem[] {
48
+ const previous = new Map(current.map((item) => [item.symbol, item]));
49
+ return results.map((result) => {
50
+ if (result.quote) return { symbol: result.symbol, quote: result.quote };
51
+ const existing = previous.get(result.symbol);
52
+ return existing?.quote
53
+ ? { symbol: result.symbol, quote: existing.quote, error: result.error, stale: true }
54
+ : { symbol: result.symbol, error: result.error };
55
+ });
56
+ }
57
+
58
+ function renderHeading(view: TickerView, theme: Theme): string {
59
+ if (view.loading) return theme.fg("muted", "Stocks · updating…");
60
+ if (view.updatedAt) {
61
+ return theme.fg("muted", `Stocks · updated ${new Date(view.updatedAt).toLocaleTimeString()}`);
62
+ }
63
+ return theme.fg("muted", "Stocks");
64
+ }
65
+
66
+ function renderItem(item: TickerItem, theme: Theme): string {
67
+ const symbol = theme.fg("accent", theme.bold(item.symbol));
68
+ if (!item.quote) return `${symbol} ${theme.fg("error", "unavailable")}`;
69
+ const changeRole = item.quote.change >= 0 ? "success" : "error";
70
+ const content = `${symbol} ${theme.fg("text", formatPrice(item.quote))} ${theme.fg(
71
+ changeRole,
72
+ formatChange(item.quote),
73
+ )}`;
74
+ return item.stale ? `${content} ${theme.fg("warning", "stale")}` : content;
75
+ }
76
+
77
+ function formatItemPlain(item: TickerItem): string {
78
+ if (!item.quote) return `${item.symbol} unavailable`;
79
+ const content = `${item.symbol} ${formatPrice(item.quote)} ${formatChange(item.quote)}`;
80
+ return item.stale ? `${content} stale` : content;
81
+ }
82
+
83
+ function formatPrice(quote: Quote): string {
84
+ const value = formatMarketNumber(quote.price);
85
+ if (quote.currency === "GBp") return `${value}p`;
86
+ return `${currencyPrefix(quote.currency)}${value}`;
87
+ }
88
+
89
+ function formatChange(quote: Quote): string {
90
+ const sign = quote.change >= 0 ? "+" : "";
91
+ return `${sign}${formatMarketNumber(quote.change)} (${sign}${quote.changePercent.toFixed(2)}%)`;
92
+ }
93
+
94
+ function formatMarketNumber(value: number): string {
95
+ const absolute = Math.abs(value);
96
+ if (absolute === 0) return "0.00";
97
+ const magnitude = Math.floor(Math.log10(absolute));
98
+ const significantDecimals = 6 - magnitude - 1;
99
+ const formatted =
100
+ significantDecimals > 8
101
+ ? value.toPrecision(6)
102
+ : value.toFixed(Math.max(2, significantDecimals));
103
+ return trimNumericZeros(formatted);
104
+ }
105
+
106
+ function trimNumericZeros(value: string): string {
107
+ const [coefficient, exponent] = value.split("e");
108
+ const [integer = value, fraction = ""] = coefficient?.split(".") ?? [value, ""];
109
+ let trimmedFraction = fraction;
110
+ const minimumFractionDigits = exponent === undefined ? 2 : 0;
111
+ while (trimmedFraction.length > minimumFractionDigits && trimmedFraction.endsWith("0")) {
112
+ trimmedFraction = trimmedFraction.slice(0, -1);
113
+ }
114
+ const trimmed = trimmedFraction ? `${integer}.${trimmedFraction}` : integer;
115
+ return exponent === undefined ? trimmed : `${trimmed}e${exponent}`;
116
+ }
117
+
118
+ function currencyPrefix(currency: string | undefined): string {
119
+ switch (currency) {
120
+ case "USD":
121
+ return "$";
122
+ case "EUR":
123
+ return "€";
124
+ case "GBP":
125
+ return "£";
126
+ case "JPY":
127
+ return "¥";
128
+ case "CAD":
129
+ return "C$";
130
+ case "HKD":
131
+ return "HK$";
132
+ case "TWD":
133
+ return "NT$";
134
+ default:
135
+ return currency ? `${currency} ` : "";
136
+ }
137
+ }
138
+
139
+ function packItems(items: readonly string[], separator: string, width: number): string[] {
140
+ const rows: string[] = [];
141
+ let current = "";
142
+ for (const item of items) {
143
+ if (visibleWidth(item) > width) {
144
+ if (current) rows.push(current);
145
+ rows.push(...fitLines(item, width));
146
+ current = "";
147
+ continue;
148
+ }
149
+ const candidate = current ? `${current}${separator}${item}` : item;
150
+ if (visibleWidth(candidate) <= width) {
151
+ current = candidate;
152
+ continue;
153
+ }
154
+ rows.push(current);
155
+ current = item;
156
+ }
157
+ if (current) rows.push(current);
158
+ return rows;
159
+ }
160
+
161
+ function fitLines(content: string, width: number): string[] {
162
+ return wrapTextWithAnsi(content, width).map((line) => truncateToWidth(line, width, ""));
163
+ }
@@ -0,0 +1,172 @@
1
+ import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
2
+ import { basename, dirname, join } from "node:path";
3
+
4
+ export const MAX_SYMBOLS = 10;
5
+ export const DEFAULT_WIDGET_ENABLED = true;
6
+
7
+ export interface StockTickerSettings {
8
+ symbols: string[];
9
+ widgetEnabled: boolean;
10
+ }
11
+
12
+ export interface LoadedSettings {
13
+ settings: StockTickerSettings;
14
+ warning?: string;
15
+ }
16
+
17
+ export interface SettingsWriter {
18
+ save(path: string, symbols: readonly string[]): Promise<void>;
19
+ saveWidgetEnabled(path: string, widgetEnabled: boolean): Promise<void>;
20
+ flush(): Promise<void>;
21
+ }
22
+
23
+ const SYMBOL_PATTERN = /^[A-Z0-9.^=-]{1,15}$/;
24
+
25
+ export function parseSymbols(values: Iterable<string>): string[] {
26
+ return normalizeSymbols(values, false);
27
+ }
28
+
29
+ export function normalizeSymbols(values: Iterable<string>, allowEmpty: boolean): string[] {
30
+ const symbols = [...values]
31
+ .flatMap((value) => value.split(/[\s,]+/))
32
+ .map((value) => value.trim().toUpperCase())
33
+ .filter(Boolean);
34
+ const unique = [...new Set(symbols)];
35
+ if (!allowEmpty && unique.length === 0) throw new Error("Provide at least one stock symbol.");
36
+ if (unique.length > MAX_SYMBOLS) {
37
+ throw new Error(`At most ${MAX_SYMBOLS} stock symbols are supported.`);
38
+ }
39
+ const invalid = unique.find((symbol) => !SYMBOL_PATTERN.test(symbol));
40
+ if (invalid) throw new Error(`Invalid stock symbol: ${invalid}`);
41
+ return unique;
42
+ }
43
+
44
+ export async function loadSettings(path: string): Promise<LoadedSettings> {
45
+ let text: string;
46
+ try {
47
+ text = await readFile(path, "utf8");
48
+ } catch (error) {
49
+ if (isMissingFile(error)) return { settings: defaultSettings() };
50
+ return {
51
+ settings: defaultSettings(),
52
+ warning: `Could not read ${path}; using default ticker settings.`,
53
+ };
54
+ }
55
+
56
+ try {
57
+ const document = parseDocument(text);
58
+ const symbols = document.symbols === undefined ? [] : parseSymbolSetting(document.symbols);
59
+ const widgetEnabled =
60
+ document.widgetEnabled === undefined
61
+ ? DEFAULT_WIDGET_ENABLED
62
+ : parseWidgetEnabled(document.widgetEnabled);
63
+ return { settings: { symbols, widgetEnabled } };
64
+ } catch (error) {
65
+ return {
66
+ settings: defaultSettings(),
67
+ warning: `${errorMessage(error)} Using default ticker settings without changing ${path}.`,
68
+ };
69
+ }
70
+ }
71
+
72
+ export async function saveSymbols(path: string, symbols: readonly string[]): Promise<void> {
73
+ await saveSettingsPatch(path, { symbols: normalizeSymbols(symbols, true) });
74
+ }
75
+
76
+ export async function saveWidgetEnabled(path: string, widgetEnabled: boolean): Promise<void> {
77
+ await saveSettingsPatch(path, { widgetEnabled: parseWidgetEnabled(widgetEnabled) });
78
+ }
79
+
80
+ export function createSettingsWriter(): SettingsWriter {
81
+ let queue = Promise.resolve();
82
+ const enqueue = (operation: () => Promise<void>) => {
83
+ const running = queue.catch(() => undefined).then(operation);
84
+ queue = running.then(
85
+ () => undefined,
86
+ () => undefined,
87
+ );
88
+ return running;
89
+ };
90
+ return {
91
+ save: (path, symbols) => enqueue(() => saveSymbols(path, symbols)),
92
+ saveWidgetEnabled: (path, widgetEnabled) =>
93
+ enqueue(() => saveWidgetEnabled(path, widgetEnabled)),
94
+ flush: () => queue,
95
+ };
96
+ }
97
+
98
+ async function saveSettingsPatch(path: string, patch: Partial<StockTickerSettings>): Promise<void> {
99
+ let document: Record<string, unknown> = {};
100
+ try {
101
+ const text = await readFile(path, "utf8");
102
+ document = parseDocument(text);
103
+ validateKnownSettings(document);
104
+ } catch (error) {
105
+ if (!isMissingFile(error)) throw error;
106
+ }
107
+
108
+ const next = `${JSON.stringify({ ...document, ...patch }, null, 2)}\n`;
109
+ const directory = dirname(path);
110
+ await mkdir(directory, { recursive: true });
111
+ const temporaryPath = join(directory, `.${basename(path)}.${process.pid}.${Date.now()}.tmp`);
112
+ try {
113
+ await writeFile(temporaryPath, next, { encoding: "utf8", flag: "wx", mode: 0o600 });
114
+ await rename(temporaryPath, path);
115
+ } catch (error) {
116
+ await unlink(temporaryPath).catch(() => undefined);
117
+ throw error;
118
+ }
119
+ }
120
+
121
+ function defaultSettings(): StockTickerSettings {
122
+ return { symbols: [], widgetEnabled: DEFAULT_WIDGET_ENABLED };
123
+ }
124
+
125
+ function parseDocument(text: string): Record<string, unknown> {
126
+ let value: unknown;
127
+ try {
128
+ value = JSON.parse(text);
129
+ } catch {
130
+ throw new Error("Stock ticker settings must contain valid JSON.");
131
+ }
132
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
133
+ throw new Error("Stock ticker settings must be a JSON object.");
134
+ }
135
+ return value as Record<string, unknown>;
136
+ }
137
+
138
+ function validateKnownSettings(document: Record<string, unknown>): void {
139
+ if (document.symbols !== undefined) parseSymbolSetting(document.symbols);
140
+ if (document.widgetEnabled !== undefined) parseWidgetEnabled(document.widgetEnabled);
141
+ }
142
+
143
+ function parseSymbolSetting(value: unknown): string[] {
144
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
145
+ throw new Error("The stock ticker symbols setting must be an array of strings.");
146
+ }
147
+ return normalizeSymbols(value as string[], true);
148
+ }
149
+
150
+ function parseWidgetEnabled(value: unknown): boolean {
151
+ if (typeof value !== "boolean") {
152
+ throw new Error("The stock ticker widgetEnabled setting must be a boolean.");
153
+ }
154
+ return value;
155
+ }
156
+
157
+ function isMissingFile(error: unknown): boolean {
158
+ return hasErrorCode(error, "ENOENT");
159
+ }
160
+
161
+ function hasErrorCode(error: unknown, code: string): boolean {
162
+ return (
163
+ typeof error === "object" &&
164
+ error !== null &&
165
+ "code" in error &&
166
+ (error as NodeJS.ErrnoException).code === code
167
+ );
168
+ }
169
+
170
+ function errorMessage(error: unknown): string {
171
+ return error instanceof Error ? error.message : String(error);
172
+ }