dsh-market-radar 0.2.0 → 0.2.1

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 (4) hide show
  1. package/README.md +72 -36
  2. package/lib/client.js +164 -66
  3. package/lib/index.js +143 -40
  4. package/package.json +72 -21
package/README.md CHANGED
@@ -1,77 +1,113 @@
1
1
  # 行情雷达 · dsh-market-radar
2
2
 
3
- 在 DeepSeek Harness 桌面端查看黄金、A 股和美股行情。底部行情条可固定最多三只自选,点开看板即可查看走势、设置提醒,或把行情快照放入对话草稿。
3
+ 在 DeepSeek Harness 桌面端查看黄金、A 股和美股行情。底部行情条最多固定 3 只自选,点开看板即可查看多周期走势、市场事件与经济数据、配置阈值提醒,或把行情快照写入对话草稿。
4
4
 
5
- [English](#english) · [插件目录](https://github.com/awesome-dsh-plugin/awesome-dsh-plugin/blob/main/data/plugins/alwayXXX__dsh-market-radar.yml) · [npm](https://www.npmjs.com/package/dsh-market-radar)
5
+ [English](#english) · [插件目录](https://github.com/awesome-dsh-plugin/awesome-dsh-plugin/blob/main/data/plugins/alwayXXX__dsh-market-radar.yml) · [npm](https://www.npmjs.com/package/dsh-market-radar) · [GitHub Releases](https://github.com/alwayXXX/dsh-market-radar/releases)
6
+
7
+ ## 功能概览
8
+
9
+ - **多市场自选与底栏常驻**:支持黄金(`XAU`、`AU9999`)、A 股与美股;底部行情条最多固定 3 只标的,底栏被占用时自动回退到右上角入口。
10
+ - **多周期价格走势**:提供 1 天、5 天、1 个月、半年、年初至今(YTD)、1 年、5 年与 Max 走势图,支持鼠标悬停和方向键读数。
11
+ - **市场事件与经济数据**:按市场展示官方发布的近期事件与美国非农就业、CPI 同比数据,并可按需调用 DSH 可用模型生成解读。
12
+ - **提醒与对话协作**:支持价格及涨跌幅方向提醒、全局快捷键一键隐藏并静音、JSON 配置导入导出,以及一键将行情快照写入对话草稿。
6
13
 
7
14
  ## 安装
8
15
 
9
- 此包的宿主版本范围为 **DSH `>=0.2.1-rc.1 <0.3.0-0`**,要求 Node.js 24.9.0 或更高版本。可从 [GitHub Releases](https://github.com/alwayXXX/dsh-market-radar/releases) 下载适配当前宿主的 `.tgz`,在桌面端的「插件」页选择本地文件。也可以用桌面端自带的 CLI 从 npm 安装兼容的发行版。
16
+ 宿主要求 **DSH `>=0.2.1-rc.1 <0.3.0-0`**、**Node.js `>=24.9.0`**。
10
17
 
11
- 使用 CLI 前,请完整退出 DSH(包括托盘)。把示例中的安装目录换成你电脑上的实际路径,执行后重新打开 DSH。
18
+ - **桌面端安装**:在 DSH「插件」页直接搜索安装,或从 [GitHub Releases](https://github.com/alwayXXX/dsh-market-radar/releases) 下载适配当前宿主的 `.tgz` 后在「插件」页选择本地安装。
19
+ - **CLI 安装**:先完整退出 DSH(包括托盘),将下面示例中的安装目录替换为实际路径,执行后重新打开 DSH:
12
20
 
13
21
  ```powershell
14
22
  & '你的安装目录\resources\runtime\cli\bin\dsh.cmd' plugin --profile desktop add 'dsh-market-radar'
15
23
  ```
16
24
 
17
- 用 CLI 安装本地包时,把 `dsh-market-radar` 换成下载的 `.tgz` 文件的绝对路径。指定 npm 版本时,在包名后加 `@版本号`。
25
+ 安装本地包时,把 `dsh-market-radar` 替换为 `.tgz` 文件的绝对路径;指定版本时写 `dsh-market-radar@版本号`。
26
+
27
+ ## 使用指南
28
+
29
+ 1. **管理自选**
30
+ 点击底部行情条(或右上角回退入口)打开看板,点 `+` 添加标的,点图钉固定到底栏,通过行尾 `···` 菜单调整顺序、进入提醒或移出自选(点击看板其他区域会自动收起行菜单)。
31
+ - **黄金**:`XAU`(美元/盎司)、`AU9999`(人民币/克)。
32
+ - **A 股**:支持输入 6 位代码检索交易所候选,也可直接输入带前缀代码(如 `sh600519`、`sz000001`、`sh000001`)。
33
+ - **美股**:支持个股与 ETF(如 `AAPL`、`VOO`)、带点股类(如 `BRK.B`)以及主要指数(`.INX`、`.DJI`、`.IXIC`、`.NDX`)。
34
+
35
+ 2. **查看价格走势与报价时间**
36
+ 点击任一自选进入详情页,可切换 1 天至 Max 区间。图表标明实际覆盖时间与数据粒度,缺失交易时段留空,被间隔分开的孤立数据点保留圆点标记。详情页与底栏悬浮提示按对应市场本地时区显示源站时间(美股为纽约时间,A 股与黄金为北京时间)。
18
37
 
19
- ## 使用
38
+ 3. **查看市场事件**
39
+ 在标的详情图表下方展开「市场事件」(默认折叠,展开时按市场加载并独立缓存):
40
+ - **A 股**:显示国家统计局近期数据发布(CPI、PPI、PMI、GDP、工业与消费等)。
41
+ - **美股与黄金**:显示近期美联储货币政策公告,以及下一次美国 CPI 计划发布时间。
42
+ - 列表时间统一以北京时间显示。点击可预览的事件可按需调用 DSH 模型生成摘要、市场关注与潜在影响(A 股事件评估黄金与 A 股,美股事件评估黄金与美股);国家统计局正文不可读时仅保留官方原文入口。
20
43
 
21
- 1. **管理自选。** 点击底部行情条打开看板。底部被占用时,可从右上角进入。用 `+` 添加标的,点图钉固定到底栏,行尾菜单可排序、设置提醒或移出自选。
22
- 2. **查看价格走势。** 点击标的,选择 1 天、5 天、1 个月、半年、年初至今(YTD)、1 年、5 年或 Max。可用鼠标或方向键查看读数。`XAU` 使用美元/金衡盎司,`AU9999` 使用人民币/克。
23
- 3. **查看市场事件。** 在 A 股、美股或黄金标的的图表下展开「市场事件」。A 股显示国家统计局近期数据发布(如 CPI、PPI、PMI、GDP、工业与消费数据);美股和黄金显示近期美联储货币政策公告与下一次美国 CPI 计划发布时间。点击可预览的事件,使用 DSH 可用模型生成摘要、市场关注及潜在影响判断;A 股事件只判断黄金和 A 股,美股事件只判断黄金和美股。日期与时间采用北京时间。国家统计局正文暂不可读时只保留官方原文入口,不生成 AI 判断。
24
- 4. **设置提醒。** 选择目标价或当日涨跌幅阈值。首条有效报价建立基线,之后报价从阈值外进入触发范围时,才会出现应用内提醒。默认冷却 15 分钟。涨跌幅填正数,例如「当日跌幅达到」填 `3`,表示跌至 −3% 或更低。
25
- 5. **把行情放入对话。** 打开一个可编辑的 DSH 对话,在标的详情中点「准备行情快照」,或在自选列表中点「准备重点自选快照」合并底栏固定的标的。预览后点「放入对话」。快照会加入当前草稿,已有文字与附件保留,由你决定何时发送。
26
- 6. **查看经济数据。** 在自选看板展开「经济数据」,查看美国非农就业月度变化和 CPI 同比。卡片显示最新月份、前值和最近八个月,点击来源可查看官方信息;数据可用时可以按需生成 AI 解读和潜在影响判断。
44
+ 4. **查看经济数据**
45
+ 在自选看板展开「经济数据」,查看美国非农就业月度变化(季调就业总量相邻月差)与美国 CPI 同比(未季调指数与去年同月对比,基期缺失时显示暂无)。两项指标按需拉取并各自独立缓存 4 小时,单项失败时重试仅重拉失败项,底部展示对应指标的北京时间获取时间(或区间)。数据有效时可按需生成 AI 解读。
27
46
 
28
- A 股可输入六位代码查候选,也可直接输入带交易所前缀的代码,例如 `sh600519`。`sh000001` 是上证指数,`sz000001` 是平安银行。美股可输入 `AAPL`、`VOO` 等代码。在「设置」中可以更改涨跌配色,或导入、导出 JSON 自选配置。
47
+ 5. **设置提醒**
48
+ 支持「价格高于/低于」与「当日涨幅/跌幅/涨跌幅绝对值达到」五类条件;涨跌幅填正数(例如「当日跌幅达到」填 `3` 表示跌至 −3% 或更低)。首条有效报价建立基线,后续价格从阈值外穿越时触发应用内提醒,冷却时间可设 1–1440 分钟(默认 15 分钟)。从标的详情进入提醒页后,切换顶部「标的」下拉框会同步筛选下方规则列表。
29
49
 
30
- ### 隐藏与提醒
50
+ 6. **行情快照与设置**
51
+ 打开可编辑的 DSH 对话后,可在详情页点「准备行情快照」,或在列表点「准备重点自选快照」(合并底栏固定的标的),预览后点「放入对话」加入草稿。已有文字与附件会保留,由你决定何时发送。在「设置」中可切换红涨绿跌 / 绿涨红跌配色,并导入或导出 JSON 自选配置。
31
52
 
32
- DSH 获得焦点时,按 **Ctrl+Shift+F9**(Windows)或 **Command+Shift+F9**(macOS)隐藏行情条和看板、静音提醒,再按一次恢复。可在宿主的快捷键设置中搜索「行情雷达:隐藏或恢复」修改组合键。监测在 DSH 运行且电脑保持唤醒时进行,恢复界面时不会补发隐藏期间的提醒。
53
+ ### 隐藏与快捷键
33
54
 
34
- ## 数据来源与范围
55
+ DSH 获得焦点时,按 **Ctrl+Shift+F9**(Windows)或 **Command+Shift+F9**(macOS)可立即隐藏行情条与看板并静音提醒,再按一次恢复。可在 DSH 快捷键设置中搜索「行情雷达:隐藏或恢复」自定义组合键。提醒监测仅在 DSH 运行且设备保持唤醒时生效,恢复显示时不会补发隐藏期间的触发事件。
56
+
57
+ ## 数据来源与机制
35
58
 
36
59
  | 用途 | 来源 |
37
60
  | --- | --- |
38
- | A 股、美股报价及当日分时,A 股五日分时和日线 | 腾讯财经(`qt.gtimg.cn`、`web.ifzq.gtimg.cn`) |
39
- | 黄金报价、XAU 分时和日线 | 新浪财经(`hq.sinajs.cn`、`stock2.finance.sina.com.cn`) |
61
+ | A 股、美股报价及当日分时;A 股五日分时和日线 | 腾讯财经(`qt.gtimg.cn`、`web.ifzq.gtimg.cn`) |
62
+ | 黄金报价、`XAU` 分时和日线 | 新浪财经(`hq.sinajs.cn`、`stock2.finance.sina.com.cn`) |
40
63
  | 美股五日及日线 | Yahoo Finance(`query1.finance.yahoo.com`) |
41
- | Au99.99 日线 | 上海黄金交易所(`www.sge.com.cn`) |
64
+ | `Au99.99` 日线 | 上海黄金交易所(`www.sge.com.cn`) |
42
65
  | A 股市场事件 | 国家统计局数据发布 RSS(`www.stats.gov.cn`) |
43
- | 美股及黄金市场事件 | 美联储(`www.federalreserve.gov`)、美国劳工统计局(`www.bls.gov`)和纽约联储(`www.newyorkfed.org`) |
44
- | 经济数据 | 美国劳工统计局公开数据 API(`api.bls.gov`) |
66
+ | 美股及黄金市场事件 | 美联储(`www.federalreserve.gov`)、美国劳工统计局(`www.bls.gov`)、纽约联储(`www.newyorkfed.org`) |
67
+ | 经济数据 | 美国劳工统计局公开 API(`api.bls.gov`) |
45
68
 
46
- - 看板打开或有提醒规则启用时,报价通常每 15 秒刷新一次,其余时间通常每 60 秒刷新一次。过期报价不触发提醒。节假日或提前收市可能显示为「报价已延迟」。
47
- - 走势图标明实际覆盖区间与数据粒度,缺失时段留空。Au99.99 的日内走势使用插件运行期间的采样,其他标的在分时数据不可用时也可能回退到采样。较长区间使用日线收盘点,Max 取决于数据源可提供的范围。A 股日线未复权,美股使用来源的 `close` 字段。
48
- - 经济数据按需读取并缓存四小时。非农就业变化以季调后就业总量的相邻月份差计算,历史数字可能修订;CPI 同比以未季调指数和去年同月指数计算,基期缺失时显示暂无。卡片显示数据月份和获取时间。
49
- - 市场事件仅在区块展开时按市场加载,A 股与美股分别缓存,来源故障互不影响。A 股事件读取国家统计局数据发布 RSS 的正文;已发布的美股事件读取美联储原文,中国事件不会交给只解析美联储正文的解析器。A 股来源失败时保留国家统计局数据发布入口;美股来源失败时保留美联储、美国劳工统计局或纽约联储的官方入口。
50
- - 点击可预览事件后,插件会把对应原文或数据发送给 DSH 中可用的模型以生成预览;A 股事件判断黄金和 A 股,美股事件判断黄金和美股。模型优先选择官方 DeepSeek 路由及其模型列表的第一项;否则使用第一个列出模型的路由,模型服务可能产生用量。影响判断是有条件的 AI 推测,不包含市场预期或实时行情,也不是投资建议,请核实信息并谨慎操作。CPI 日程显示发布时间与关注事项,具体数据在发布后才可确认,不生成方向判断;CPI 优先使用美国劳工统计局日历,数据源不可用时尝试纽约联储。两处都不可用时,可显示最近 24 小时内获取、且尚未到点的缓存日程,并提供查看官方日历的入口。
51
- - 请求由本机 DSH 宿主发出,无需为行情或事件单独配置账户或 API Key。数据服务方可能收到查询代码和网络地址。自选、提醒和显示设置保存在本机当前 profile。对话快照由用户添加,发送后按 DSH 的模型配置处理。
69
+ - **刷新与状态**:看板打开或有提醒规则启用时,行情通常每 15 秒刷新一次,其余时间每 60 秒刷新一次;过期报价不触发提醒。`XAU` 常规交易时段遵循纽约夏令时并包含每日美东 17:00–18:00 休市维护窗口;节假日或提前收市可能显示为「报价已延迟」。
70
+ - **走势数据**:`Au99.99` 当日走势使用插件运行期间的实时采样,其他标的在分时不可用时也可能回退采样。较长区间使用日线收盘点,Max 取决于数据源范围;A 股日线未复权,美股使用源站 `close` 字段。
71
+ - **市场事件与 AI 解读**:仅在点击生成时将对应官方原文或统计数据发送给 DSH 可用模型(优先官方 DeepSeek 路由首个模型,否则取首个可用路由模型),可能产生模型用量。CPI 日程优先读取美国劳工统计局,不可用时回退纽约联储或 24 小时内未过期的缓存日程,且只提供时间与关注点、不生成方向判断。AI 影响判断不含市场预期或实时行情,请自行核实原文。
72
+ - **本地与隐私**:行情、事件与经济数据均由本机 DSH 宿主直连官方/公开接口,无需单独配置账户或 API Key;外部接口会收到查询代码与本机网络地址。自选、提醒与显示设置保存在本机当前 profile,对话快照仅在你主动发送后按 DSH 模型配置处理。
52
73
 
53
74
  ## 卸载
54
75
 
55
- 在 DSH 的「插件」页卸载,或退出桌面端后,用安装时的 CLI 和 profile 执行 `plugin --profile desktop remove dsh-market-radar`。需要备份时可先在「设置」导出配置。
76
+ 在 DSH「插件」页直接卸载,或完整退出桌面端后用安装时的 CLI 执行:
77
+
78
+ ```powershell
79
+ & '你的安装目录\resources\runtime\cli\bin\dsh.cmd' plugin --profile desktop remove 'dsh-market-radar'
80
+ ```
81
+
82
+ 卸载前如需保留自选和提醒规则,可先在「设置」中导出 JSON 备份。
56
83
 
57
84
  ## 免责声明
58
85
 
59
- 本插件仅供个人查看行情和信息参考,不构成投资建议、交易建议或收益承诺。行情由第三方提供,可能存在延迟、错误、中断或缺失;提醒也可能因网络、设备休眠、软件故障或数据源问题而延迟或未触发。本插件不保证数据和提醒的准确性、完整性或实时性,请以交易所及相关服务机构的信息为准。投资决策由使用者独立作出,并自行承担相应风险。
86
+ 本插件仅供个人查看行情与公开信息参考,不构成投资建议、交易建议或收益承诺。第三方行情与官方接口可能存在延迟、错误、中断或缺失,提醒也可能因网络、设备休眠、软件故障或数据源异常而延迟或未触发。请以交易所及相关官方机构信息为准,投资决策由使用者独立作出并自行承担风险。
60
87
 
61
88
  [问题反馈](https://github.com/alwayXXX/dsh-market-radar/issues) · [MIT 许可证](https://github.com/alwayXXX/dsh-market-radar/blob/main/LICENSE)
62
89
 
63
90
  ## English
64
91
 
65
- DSH Market Radar brings gold, China A-share and US quotes to the DeepSeek Harness desktop app. Pin up to three symbols to the bottom ticker, open charts from 1 day to Max, set price or percent-change alerts, and insert quote snapshots into an editable chat draft. Expand **市场事件** below an A-share, US or gold chart. A-share events come from the National Bureau of Statistics' recent data-release RSS; US and gold events show recent Federal Reserve policy announcements and the next scheduled US CPI release (Beijing time). Select a previewable event for an AI summary and the original source. Chinese events are summarized only from the National Bureau of Statistics RSS body and assess gold and China A-shares; US events assess gold and US stocks. Events without a reliable body keep the original link and are clearly marked as unavailable for AI summary.
92
+ DSH Market Radar brings gold, China A-share, and US market quotes to the DeepSeek Harness desktop app. Pin up to three symbols to the bottom ticker, open charts from 1 day to Max, review official market events and US macro indicators, configure price or percent-change alerts, and insert quote snapshots into an editable chat draft.
66
93
 
67
- Expand **经济数据** on the watchlist for US nonfarm payroll changes and year-over-year CPI from the Bureau of Labor Statistics. Payroll changes use revised seasonally adjusted employment levels. CPI uses unadjusted index levels and shows unavailable when the prior-year base is missing. The cards display the observation period and fetch time.
94
+ ### Install & Uninstall
68
95
 
69
- On demand, available DSH models can summarize published events or economic data and assess potential effects on gold and the relevant stock market. A-share events are assessed for gold and China A-shares; US events are assessed for gold and US stocks. This sends the selected source content or observations to the configured model and may incur usage. AI judgments may be wrong, do not include market expectations or real-time prices, and are not investment advice; verify sources and use caution.
96
+ - **Requirements**: DSH `>=0.2.1-rc.1 <0.3.0-0` and Node.js `>=24.9.0`.
97
+ - **Install**: Search and install in the DSH Plugins page, select a `.tgz` from [GitHub Releases](https://github.com/alwayXXX/dsh-market-radar/releases), or quit DSH completely and install via the bundled CLI shown in the Chinese installation section above.
98
+ - **Uninstall**: Remove from the Plugins page, or quit DSH and run `plugin --profile desktop remove dsh-market-radar` with the same CLI. Export your JSON config from Settings first if you want a backup.
70
99
 
71
- **Install.** This package requires DSH `>=0.2.1-rc.1 <0.3.0-0` and Node.js 24.9.0 or later. Select a compatible `.tgz` from [GitHub Releases](https://github.com/alwayXXX/dsh-market-radar/releases) in the desktop Plugins page. To use the bundled CLI, quit DSH completely and run the command in the installation section above with your actual DSH installation path. Reopen DSH after installing. To uninstall, use the Plugins page or run `plugin --profile desktop remove dsh-market-radar` with the same CLI.
100
+ ### Usage
72
101
 
73
- **Use.** Open the panel from the bottom ticker or, when its slot is occupied, from the top right. Use `+` to add symbols such as `sh600519` or `VOO`. Alerts establish a baseline on the first valid quote and fire on a subsequent threshold crossing. Press **Ctrl+Shift+F9** on Windows or **Command+Shift+F9** on macOS to hide the panel and mute alerts. Press it again to restore the panel.
102
+ - **Watchlist & symbols**: Open the panel from the bottom ticker (or the top-right fallback button). Use `+` to add gold (`XAU`, `AU9999`), A-shares (6-digit lookup or prefixed codes such as `sh600519`, `sz000001`), or US symbols including equities/ETFs (`AAPL`, `VOO`), dot share classes (`BRK.B`), and major indices (`.INX`, `.DJI`, `.IXIC`, `.NDX`).
103
+ - **Charts & timezones**: Inspect 1D through Max charts with pointer or arrow keys; missing sessions remain gapped and isolated points show explicit markers. Quote timestamps use local market time (New York time for US; Beijing time for A-shares and gold).
104
+ - **Market events**: Expand **市场事件** under a chart to load cached events per market (Beijing time): National Bureau of Statistics releases for A-shares; Federal Reserve policy announcements and the next scheduled US CPI release for US and gold.
105
+ - **Economic data**: Expand **经济数据** on the watchlist for BLS US nonfarm payroll changes (month-over-month revised seasonally adjusted levels) and year-over-year unadjusted CPI. Each indicator caches independently for 4 hours and retries independently on failure.
106
+ - **AI previews**: On demand, clicking a previewable event or available indicator sends the official text or data to an available DSH model (potentially incurring usage). A-share events assess gold and A-shares; US events assess gold and US stocks. Events without a reliable body keep only the official link.
107
+ - **Alerts, snapshots & shortcut**: Alerts baseline on the first valid quote and fire on subsequent crossings (1–1440 min cooldown). Press **Ctrl+Shift+F9** (Windows) or **Command+Shift+F9** (macOS) to hide the UI and mute alerts without replaying missed crossings on restore.
74
108
 
75
- **Data and privacy.** Market data comes from Tencent Finance, Sina Finance, Yahoo Finance and the Shanghai Gold Exchange. A-share event links and event text come from the National Bureau of Statistics' public RSS. US event links point to the Federal Reserve, US Bureau of Labor Statistics and New York Fed. The DSH host requests data directly, so providers may receive the requested symbols and network address. Watchlists, alerts and display settings are stored locally per profile. A snapshot reaches your configured model when you send its draft.
109
+ ### Data, Privacy & Disclaimer
76
110
 
77
- **Disclaimer.** Market Radar is for personal information only and does not provide investment or trading advice. Data and alerts may be delayed, inaccurate or unavailable. Refer to the relevant exchanges and providers for authoritative information. You are responsible for your investment decisions.
111
+ - **Sources**: Tencent Finance, Sina Finance, Yahoo Finance, Shanghai Gold Exchange, National Bureau of Statistics (RSS), Federal Reserve, US Bureau of Labor Statistics, and New York Fed.
112
+ - **Privacy**: Requests go directly from your local DSH host without extra API keys; providers receive requested symbols and your network address. Watchlists, alerts, and settings stay local to your DSH profile.
113
+ - **Disclaimer**: For personal informational reference only—not investment or trading advice. Quotes, AI judgments, and alerts may be delayed, inaccurate, or unavailable. Verify official sources and take responsibility for your own decisions.
package/lib/client.js CHANGED
@@ -98,6 +98,9 @@ var RadarController = class {
98
98
  pendingSaves = 0;
99
99
  toggleSequence = 0;
100
100
  retiredAlertEpochs = /* @__PURE__ */ new Set();
101
+ lastAckVisible = false;
102
+ visibilityInFlight = null;
103
+ visibilityPending = null;
101
104
  clientId = `radar-${crypto.randomUUID()}`;
102
105
  getSnapshot = () => this.state;
103
106
  subscribe = (fn) => {
@@ -114,6 +117,47 @@ var RadarController = class {
114
117
  get hidden() {
115
118
  return this.state.localHidden ?? this.state.snapshot.config.hidden;
116
119
  }
120
+ syncVisibility(forceHeartbeat = false) {
121
+ if (this.stopped) return Promise.resolve();
122
+ const visible = this.state.open && !this.hidden;
123
+ if (!visible && !this.lastAckVisible && !this.visibilityInFlight) return Promise.resolve();
124
+ if (this.visibilityInFlight) {
125
+ this.visibilityPending = { visible, forceHeartbeat: forceHeartbeat || (this.visibilityPending?.forceHeartbeat ?? false) };
126
+ return this.visibilityInFlight;
127
+ }
128
+ this.visibilityInFlight = this.flushVisibility(visible, forceHeartbeat);
129
+ return this.visibilityInFlight;
130
+ }
131
+ async flushVisibility(visible, forceHeartbeat) {
132
+ let targetVisible = visible;
133
+ let sendHeartbeat = forceHeartbeat;
134
+ try {
135
+ while (!this.stopped) {
136
+ if (!targetVisible && !this.lastAckVisible || targetVisible && this.lastAckVisible && !sendHeartbeat) {
137
+ const skippedNext = this.visibilityPending;
138
+ this.visibilityPending = null;
139
+ if (!skippedNext) break;
140
+ targetVisible = skippedNext.visible;
141
+ sendHeartbeat = skippedNext.forceHeartbeat;
142
+ continue;
143
+ }
144
+ try {
145
+ await this.api.visibility(this.clientId, targetVisible);
146
+ this.lastAckVisible = targetVisible;
147
+ } catch {
148
+ this.visibilityPending = null;
149
+ break;
150
+ }
151
+ const next = this.visibilityPending;
152
+ this.visibilityPending = null;
153
+ if (!next) break;
154
+ targetVisible = next.visible;
155
+ sendHeartbeat = next.forceHeartbeat;
156
+ }
157
+ } finally {
158
+ this.visibilityInFlight = null;
159
+ }
160
+ }
117
161
  accept(snapshot) {
118
162
  if (snapshot.config.revision < this.state.snapshot.config.revision) return;
119
163
  const currentEpoch = this.state.snapshot.alertsEpoch;
@@ -122,28 +166,31 @@ var RadarController = class {
122
166
  if (currentEpoch) this.retiredAlertEpochs.add(currentEpoch);
123
167
  }
124
168
  if (snapshot.alertsEpoch === this.state.snapshot.alertsEpoch && (snapshot.alertsRevision ?? 0) < (this.state.snapshot.alertsRevision ?? 0)) snapshot = { ...snapshot, alerts: this.state.snapshot.alerts, alertsRevision: this.state.snapshot.alertsRevision };
169
+ if (this.state.connected && JSON.stringify(this.state.snapshot) === JSON.stringify(snapshot)) return;
125
170
  if (!this.state.connected) this.patch({ error: "" });
126
171
  this.patch({ snapshot, connected: true });
127
172
  }
128
173
  async poll() {
129
174
  if (this.stopped || this.polling) return;
175
+ clearTimeout(this.timer);
130
176
  this.polling = true;
131
177
  try {
132
178
  this.accept(await this.api.snapshot());
133
- await this.api.visibility(this.clientId, this.state.open && !this.hidden);
134
179
  } catch (error) {
135
180
  this.patch({ connected: false, error: error instanceof Error ? error.message : "\u4E0E\u884C\u60C5\u670D\u52A1\u7684\u8FDE\u63A5\u5DF2\u4E2D\u65AD" });
136
181
  } finally {
182
+ await this.syncVisibility(true);
137
183
  this.polling = false;
138
184
  if (!this.stopped) this.timer = setTimeout(() => {
139
185
  void this.poll();
140
- }, 3e3);
186
+ }, this.hidden ? 15e3 : this.state.open ? 3e3 : 5e3);
141
187
  }
142
188
  }
143
189
  setOpen(open) {
144
190
  this.patch({ open, error: "", notice: "" });
145
- void this.api.visibility(this.clientId, open && !this.hidden).catch(() => {
191
+ void this.syncVisibility().catch(() => {
146
192
  });
193
+ if (open && !this.hidden) void this.poll();
147
194
  }
148
195
  async save(change) {
149
196
  this.pendingSaves++;
@@ -170,6 +217,9 @@ var RadarController = class {
170
217
  const sequence = ++this.toggleSequence;
171
218
  const hidden = !this.hidden;
172
219
  this.patch({ localHidden: hidden, open: false, notice: "", error: "" });
220
+ void this.syncVisibility().catch(() => {
221
+ });
222
+ if (!hidden) void this.poll();
173
223
  try {
174
224
  await this.save((config) => {
175
225
  config.hidden = hidden;
@@ -217,10 +267,18 @@ var RadarController = class {
217
267
  }
218
268
  dispose() {
219
269
  this.stopped = true;
270
+ this.visibilityPending = null;
220
271
  clearTimeout(this.timer);
221
272
  clearTimeout(this.noticeTimer);
222
- void this.api.visibility(this.clientId, false).catch(() => {
223
- });
273
+ if (this.lastAckVisible || this.visibilityInFlight) {
274
+ const sendClose = () => {
275
+ this.lastAckVisible = false;
276
+ void this.api.visibility(this.clientId, false).catch(() => {
277
+ });
278
+ };
279
+ if (this.visibilityInFlight) void this.visibilityInFlight.then(sendClose, sendClose);
280
+ else sendClose();
281
+ }
224
282
  this.listeners.clear();
225
283
  this.writer = null;
226
284
  }
@@ -231,14 +289,18 @@ var import_react = require("react");
231
289
 
232
290
  // src/snapshot.ts
233
291
  var STATUS_LABEL = { live: "\u6700\u65B0\u62A5\u4EF7", closed: "\u5E38\u89C4\u4F11\u5E02\u65F6\u6BB5", delayed: "\u62A5\u4EF7\u5DF2\u5EF6\u8FDF", error: "\u8FDE\u63A5\u5931\u8D25", unknown: "\u72B6\u6001\u672A\u77E5" };
292
+ function formatQuoteTime(instrument, asOf) {
293
+ const stamp = asOf ? Date.parse(asOf) : NaN;
294
+ if (!Number.isFinite(stamp)) return null;
295
+ const zone = instrument.market === "us" ? "America/New_York" : "Asia/Shanghai";
296
+ const formatted = new Intl.DateTimeFormat("zh-CN", { timeZone: zone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" }).format(stamp);
297
+ return `${formatted}${zone === "America/New_York" ? "\uFF08\u7EBD\u7EA6\u65F6\u95F4\uFF09" : "\uFF08\u5317\u4EAC\u65F6\u95F4\uFF09"}`;
298
+ }
234
299
  function quoteTooltip(name2, quote, error) {
235
300
  if (!quote) return `${name2} \xB7 ${error ? "\u8FDE\u63A5\u5931\u8D25" : "\u7B49\u5F85\u62A5\u4EF7"}`;
236
- const zone = quote.instrument.market === "us" ? "America/New_York" : "Asia/Shanghai";
237
- const stamp = quote.asOf ? Date.parse(quote.asOf) : NaN;
238
- const asOf = Number.isFinite(stamp) ? new Intl.DateTimeFormat("zh-CN", { timeZone: zone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" }).format(stamp) : "\u672A\u77E5";
239
301
  return `${name2} \xB7 ${STATUS_LABEL[quote.status]}
240
302
  \u6765\u6E90\uFF1A${quote.source}
241
- \u6E90\u7AD9\u65F6\u95F4\uFF1A${asOf}${Number.isFinite(stamp) ? zone === "America/New_York" ? "\uFF08\u7EBD\u7EA6\u65F6\u95F4\uFF09" : "\uFF08\u5317\u4EAC\u65F6\u95F4\uFF09" : ""}`;
303
+ \u6E90\u7AD9\u65F6\u95F4\uFF1A${formatQuoteTime(quote.instrument, quote.asOf) ?? "\u672A\u77E5"}`;
242
304
  }
243
305
  function snapshotText(quotes) {
244
306
  const rows = quotes.map((q) => [
@@ -274,7 +336,8 @@ function PriceChart({ series, instrument }) {
274
336
  const x = (time) => 12 + (time - begin2) / (end2 - begin2) * 596;
275
337
  const y = (price) => 14 + (max - price) / (max - min) * 170;
276
338
  const path = points.map((p, index2) => `${index2 === 0 || p.breakBefore ? "M" : "L"}${x(p.time).toFixed(2)},${y(p.price).toFixed(2)}`).join(" ");
277
- return { min, max, x, y, path };
339
+ const isolated = points.filter((p, index2) => (index2 === 0 || p.breakBefore) && (index2 === points.length - 1 || points[index2 + 1].breakBefore));
340
+ return { min, max, x, y, path, isolated };
278
341
  }, [points, series.previousClose]);
279
342
  if (!points.length || !geometry) return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "mr-chart-empty", children: [
280
343
  "\u6682\u65E0\u8D70\u52BF\u6570\u636E",
@@ -303,6 +366,7 @@ function PriceChart({ series, instrument }) {
303
366
  setHover(Math.max(0, Math.min(points.length - 1, index + (e.key === "ArrowLeft" ? -1 : 1))));
304
367
  }, onMouseLeave: () => setHover(null), onMouseMove: (e) => {
305
368
  const box = e.currentTarget.getBoundingClientRect();
369
+ if (!box.width) return;
306
370
  const ratio = Math.max(0, Math.min(1, ((e.clientX - box.left) / box.width * 620 - 12) / 596));
307
371
  const target = points[0].time + ratio * (points.at(-1).time - points[0].time);
308
372
  let lo = 0, hi = points.length - 1;
@@ -317,7 +381,7 @@ function PriceChart({ series, instrument }) {
317
381
  [0, 1, 2, 3].map((n) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("line", { x1: "12", x2: "608", y1: 14 + n * 170 / 3, y2: 14 + n * 170 / 3, className: "mr-chart-grid" }, n)),
318
382
  series.previousClose !== null && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("line", { x1: "12", x2: "608", y1: geometry.y(series.previousClose), y2: geometry.y(series.previousClose), className: "mr-chart-close" }),
319
383
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)("path", { d: geometry.path, className: "mr-chart-line" }),
320
- points.length === 1 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("circle", { cx: geometry.x(points[0].time), cy: geometry.y(points[0].price), r: "3", className: "mr-chart-dot" }),
384
+ geometry.isolated.map((p) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("circle", { cx: geometry.x(p.time), cy: geometry.y(p.price), r: "3", className: "mr-chart-dot" }, p.time)),
321
385
  hover !== null && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
322
386
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)("line", { x1: geometry.x(point.time), x2: geometry.x(point.time), y1: "10", y2: "188", className: "mr-chart-cursor" }),
323
387
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)("circle", { cx: geometry.x(point.time), cy: geometry.y(point.price), r: "4", className: "mr-chart-dot" })
@@ -352,8 +416,8 @@ ${text}
352
416
  }
353
417
 
354
418
  // src/styles.css
355
- var styles_default = `.mr-root { --mr-bg:#fff; --mr-soft:#f6f7f9; --mr-hover:#eff2f6; --mr-text:#1b2435; --mr-muted:#7b8493; --mr-line:#e9ecf1; --mr-accent:#3159ad; --mr-accent-soft:#edf2fc; --mr-positive:#c84b4b; --mr-negative:#24816b; --mr-gold:#9e782e; font-family:inherit; font-size:12px; line-height:1.5; color:var(--mr-text); font-variant-numeric:tabular-nums; text-align:left; }
356
- body[data-ds-dark-theme] .mr-root, [data-theme="dark"] .mr-root { --mr-bg:#20232a; --mr-soft:#262a33; --mr-hover:#303541; --mr-text:#e7eaf0; --mr-muted:#9aa3b3; --mr-line:#343943; --mr-accent:#93b3f6; --mr-accent-soft:#2c3750; --mr-positive:#f28c8c; --mr-negative:#7ec4ab; --mr-gold:#d5b573; }
419
+ var styles_default = `.mr-root { --mr-bg:#fff; --mr-soft:#f6f7f9; --mr-hover:#eff2f6; --mr-text:#1b2435; --mr-muted:#7b8493; --mr-line:#e9ecf1; --mr-accent:#3159ad; --mr-accent-soft:#edf2fc; --mr-positive:#c84b4b; --mr-negative:#24816b; --mr-danger:#c84b4b; --mr-live:#24816b; --mr-gold:#9e782e; font-family:inherit; font-size:12px; line-height:1.5; color:var(--mr-text); font-variant-numeric:tabular-nums; text-align:left; }
420
+ body[data-ds-dark-theme] .mr-root, [data-theme="dark"] .mr-root { --mr-bg:#20232a; --mr-soft:#262a33; --mr-hover:#303541; --mr-text:#e7eaf0; --mr-muted:#9aa3b3; --mr-line:#343943; --mr-accent:#93b3f6; --mr-accent-soft:#2c3750; --mr-positive:#f28c8c; --mr-negative:#7ec4ab; --mr-danger:#f28c8c; --mr-live:#7ec4ab; --mr-gold:#d5b573; }
357
421
  .mr-root[data-colors="green-up"] { --mr-positive:#24816b; --mr-negative:#c84b4b; }
358
422
  body[data-ds-dark-theme] .mr-root[data-colors="green-up"], [data-theme="dark"] .mr-root[data-colors="green-up"] { --mr-positive:#7ec4ab; --mr-negative:#f28c8c; }
359
423
  .mr-root *, .mr-root *::before, .mr-root *::after { box-sizing:border-box; }
@@ -450,7 +514,7 @@ body[data-ds-dark-theme] .mr-root[data-colors="green-up"], [data-theme="dark"] .
450
514
  .mr-row-menu>div { position:absolute; right:0; top:28px; min-width:114px; padding:4px; z-index:2; border:1px solid var(--mr-line); background:var(--mr-bg); box-shadow:0 6px 20px #00000015; border-radius:6px; }
451
515
  .mr-row-menu button { display:block; text-align:left; width:100%; padding:6px 10px; font-size:11px; }
452
516
  .mr-row-menu button:hover { background:var(--mr-soft); }
453
- .mr-danger-text { color:var(--mr-negative)!important; }
517
+ .mr-danger-text { color:var(--mr-danger)!important; }
454
518
  .mr-add-row { display:flex; justify-content:center; align-items:center; gap:6px; margin:14px 20px 0; width:calc(100% - 40px); padding:10px!important; color:var(--mr-muted)!important; border:1px dashed var(--mr-line)!important; font-size:11px!important; }
455
519
  .mr-add-row:hover { background:var(--mr-soft); color:var(--mr-accent)!important; }
456
520
  .mr-list-tip { display:flex; gap:6px; align-items:center; justify-content:center; color:var(--mr-muted); font-size:10px; margin:13px 16px 18px; }
@@ -473,7 +537,7 @@ body[data-ds-dark-theme] .mr-root[data-colors="green-up"], [data-theme="dark"] .
473
537
  .mr-candidate { margin-top:18px; border:1px solid var(--mr-line); border-radius:7px; padding:12px; display:flex; align-items:center; justify-content:space-between; gap:10px; }
474
538
  .mr-candidate>div { display:flex; flex-direction:column; gap:4px; }
475
539
  .mr-candidate span { font-size:10px; color:var(--mr-muted); }
476
- .mr-error { font-size:11px; color:var(--mr-negative); line-height:1.7; margin:10px 0!important; overflow-wrap:anywhere; }
540
+ .mr-error { font-size:11px; color:var(--mr-danger); line-height:1.7; margin:10px 0!important; overflow-wrap:anywhere; }
477
541
  .mr-banner,.mr-success { font-size:11px; padding:9px 20px; background:var(--mr-soft); color:var(--mr-muted); border-bottom:1px solid var(--mr-line); overflow-wrap:anywhere; }
478
542
  .mr-success { color:var(--mr-accent); background:var(--mr-accent-soft); }
479
543
  .mr-footer { display:flex; align-items:center; justify-content:space-between; gap:8px; padding:10px 16px; border-top:1px solid var(--mr-line); color:var(--mr-muted); font-size:9px; background:var(--mr-bg); }
@@ -507,7 +571,7 @@ body[data-ds-dark-theme] .mr-root[data-colors="green-up"], [data-theme="dark"] .
507
571
  .mr-detail-price { display:flex; align-items:baseline; gap:12px; margin:16px 0 4px; }
508
572
  .mr-detail-price>strong { font-size:30px; line-height:1.3; letter-spacing:-.025em; font-weight:550; }
509
573
  .mr-detail-status { display:flex; gap:10px; align-items:center; color:var(--mr-muted); font-size:9px; }
510
- .mr-status-live { color:var(--mr-negative); }
574
+ .mr-status-live { color:var(--mr-live); }
511
575
  .mr-chart-title { display:flex; justify-content:space-between; align-items:center; margin-top:26px; }
512
576
  .mr-chart-title h4 { font-size:11px; font-weight:550; }
513
577
  .mr-chart-title span { font-size:9px; color:var(--mr-muted); }
@@ -612,6 +676,7 @@ function useRadar(radar) {
612
676
  function IconButton({ icon, label, onClick, disabled, active }) {
613
677
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { type: "button", className: `mr-icon-button ${active ? "mr-active" : ""}`, "aria-label": label, title: label, disabled, onClick, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Icon, { name: icon }) });
614
678
  }
679
+ var displayName = (i, quote) => quote?.instrument.name ?? i.name;
615
680
  function Change({ quote }) {
616
681
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: `mr-change ${(quote?.changePercent ?? 0) >= 0 ? "mr-up" : "mr-down"}`, children: formatPercent(quote?.changePercent) });
617
682
  }
@@ -637,11 +702,12 @@ function BottomBar({ radar }) {
637
702
  if (!i) return null;
638
703
  const original = quotes[id];
639
704
  const q = original && !state.connected ? { ...original, status: "error" } : original;
705
+ const name2 = displayName(i, q);
640
706
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("button", { className: "mr-ticker", onClick: () => {
641
707
  window.dispatchEvent(new CustomEvent("market-radar-select", { detail: id }));
642
708
  radar.setOpen(true);
643
- }, title: quoteTooltip(i.name, q, state.connected ? state.snapshot.errors?.[id] : "\u8FDE\u63A5\u5931\u8D25"), children: [
644
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "mr-ticker-name", children: i.market === "gold" ? i.symbol : i.name }),
709
+ }, title: quoteTooltip(name2, q, state.connected ? state.snapshot.errors?.[id] : "\u8FDE\u63A5\u5931\u8D25"), children: [
710
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "mr-ticker-name", children: i.market === "gold" ? i.symbol : name2 }),
645
711
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("strong", { children: formatPrice(q?.price) }),
646
712
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Change, { quote: q }),
647
713
  (!state.connected || state.snapshot.errors?.[id] || q && q.status !== "live") && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "mr-stale-dot", "aria-label": !state.connected || state.snapshot.errors?.[id] ? "\u8FDE\u63A5\u5931\u8D25" : STATUS_LABEL[q.status] })
@@ -770,24 +836,26 @@ function Rules({ radar, instrumentId }) {
770
836
  const [value, setValue] = (0, import_react2.useState)("");
771
837
  const [cooldown, setCooldown] = (0, import_react2.useState)("15");
772
838
  const [error, setError] = (0, import_react2.useState)("");
773
- const rules = config.alerts.filter((a) => !instrumentId || a.instrumentId === instrumentId);
839
+ const selectedId = config.instruments.some((i) => i.id === id) ? id : config.instruments[0]?.id ?? "";
840
+ const rules = config.alerts.filter((a) => !instrumentId || a.instrumentId === selectedId);
774
841
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("section", { className: "mr-section", children: [
775
842
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("h3", { children: "\u63D0\u9192\u89C4\u5219" }),
776
843
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { className: "mr-muted", children: "\u4EE5\u6700\u65B0\u6709\u6548\u62A5\u4EF7\u5224\u65AD\uFF1B\u5148\u5EFA\u7ACB\u57FA\u7EBF\uFF0C\u518D\u5728\u7A7F\u8D8A\u9608\u503C\u65F6\u63D0\u9192\u3002\u9690\u85CF\u6A21\u5F0F\u4E0B\u9759\u97F3\u3002" }),
777
844
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("form", { onSubmit: (e) => {
778
845
  e.preventDefault();
779
846
  setError("");
847
+ if (!selectedId) return;
780
848
  if (!Number.isFinite(Number(value)) || Number(value) <= 0 || !Number.isInteger(Number(cooldown)) || Number(cooldown) < 1 || Number(cooldown) > 1440) {
781
849
  setError("\u8BF7\u8F93\u5165\u6B63\u6570\u9608\u503C\u53CA 1\u20131440 \u5206\u949F\u51B7\u5374\u65F6\u95F4");
782
850
  return;
783
851
  }
784
- void radar.save((c) => c.alerts.push({ id: crypto.randomUUID(), instrumentId: id, kind, value: Number(value), cooldownMinutes: Number(cooldown), enabled: true })).then(() => setValue("")).catch(() => {
852
+ void radar.save((c) => c.alerts.push({ id: crypto.randomUUID(), instrumentId: selectedId, kind, value: Number(value), cooldownMinutes: Number(cooldown), enabled: true })).then(() => setValue("")).catch(() => {
785
853
  });
786
854
  }, children: [
787
855
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("label", { children: [
788
856
  "\u6807\u7684",
789
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("select", { value: id, onChange: (e) => setId(e.target.value), children: config.instruments.map((i) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("option", { value: i.id, children: [
790
- i.name,
857
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("select", { value: selectedId, onChange: (e) => setId(e.target.value), children: config.instruments.map((i) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("option", { value: i.id, children: [
858
+ displayName(i, state.snapshot.quotes[i.id]),
791
859
  " \xB7 ",
792
860
  i.symbol
793
861
  ] }, i.id)) })
@@ -818,39 +886,43 @@ function Rules({ radar, instrumentId }) {
818
886
  "\u51B7\u5374\u65F6\u95F4\uFF08\u5206\u949F\uFF09",
819
887
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("input", { type: "number", min: "1", max: "1440", value: cooldown, onChange: (e) => setCooldown(e.target.value), required: true })
820
888
  ] }),
821
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { className: "mr-button mr-primary", disabled: state.busy || !id || !value || !state.connected, children: "\u6DFB\u52A0\u63D0\u9192" })
889
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { className: "mr-button mr-primary", disabled: state.busy || !selectedId || !value || !state.connected, children: "\u6DFB\u52A0\u63D0\u9192" })
822
890
  ] }),
823
891
  error && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { className: "mr-error", children: error }),
824
892
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "mr-rule-list", children: [
825
- rules.map((rule) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "mr-rule", children: [
826
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("label", { className: "mr-switch", children: [
827
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("input", { type: "checkbox", checked: rule.enabled, disabled: state.busy, onChange: (e) => {
828
- const enabled = e.target.checked;
893
+ rules.map((rule) => {
894
+ const inst = config.instruments.find((i) => i.id === rule.instrumentId);
895
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "mr-rule", children: [
896
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("label", { className: "mr-switch", children: [
897
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("input", { type: "checkbox", checked: rule.enabled, disabled: state.busy, onChange: (e) => {
898
+ const enabled = e.target.checked;
899
+ void radar.save((c) => {
900
+ const target = c.alerts.find((a) => a.id === rule.id);
901
+ if (target) target.enabled = enabled;
902
+ }).catch(() => {
903
+ });
904
+ } }),
905
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { children: [
906
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("strong", { children: inst ? displayName(inst, state.snapshot.quotes[rule.instrumentId]) : rule.instrumentId }),
907
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("small", { children: [
908
+ rule.kind === "above" ? "\u4EF7\u683C \u2265" : rule.kind === "below" ? "\u4EF7\u683C \u2264" : rule.kind === "move_up" ? "\u5F53\u65E5\u6DA8\u5E45 \u2265" : rule.kind === "move_down" ? "\u5F53\u65E5\u8DCC\u5E45 \u2265" : "|\u5F53\u65E5\u6DA8\u8DCC\u5E45| \u2265",
909
+ " ",
910
+ rule.value,
911
+ rule.kind.startsWith("move") ? "%" : "",
912
+ " \xB7 \u51B7\u5374 ",
913
+ rule.cooldownMinutes,
914
+ " \u5206\u949F"
915
+ ] })
916
+ ] })
917
+ ] }),
918
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(IconButton, { icon: "trash", label: "\u5220\u9664\u63D0\u9192", disabled: state.busy, onClick: () => {
829
919
  void radar.save((c) => {
830
- c.alerts.find((a) => a.id === rule.id).enabled = enabled;
920
+ c.alerts = c.alerts.filter((a) => a.id !== rule.id);
831
921
  }).catch(() => {
832
922
  });
833
- } }),
834
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { children: [
835
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("strong", { children: config.instruments.find((i) => i.id === rule.instrumentId)?.name }),
836
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("small", { children: [
837
- rule.kind === "above" ? "\u4EF7\u683C \u2265" : rule.kind === "below" ? "\u4EF7\u683C \u2264" : rule.kind === "move_up" ? "\u5F53\u65E5\u6DA8\u5E45 \u2265" : rule.kind === "move_down" ? "\u5F53\u65E5\u8DCC\u5E45 \u2265" : "|\u5F53\u65E5\u6DA8\u8DCC\u5E45| \u2265",
838
- " ",
839
- rule.value,
840
- rule.kind.startsWith("move") ? "%" : "",
841
- " \xB7 \u51B7\u5374 ",
842
- rule.cooldownMinutes,
843
- " \u5206\u949F"
844
- ] })
845
- ] })
846
- ] }),
847
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(IconButton, { icon: "trash", label: "\u5220\u9664\u63D0\u9192", disabled: state.busy, onClick: () => {
848
- void radar.save((c) => {
849
- c.alerts = c.alerts.filter((a) => a.id !== rule.id);
850
- }).catch(() => {
851
- });
852
- } })
853
- ] }, rule.id)),
923
+ } })
924
+ ] }, rule.id);
925
+ }),
854
926
  !rules.length && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { className: "mr-empty-small", children: "\u5C1A\u672A\u8BBE\u7F6E\u63D0\u9192" })
855
927
  ] }),
856
928
  !instrumentId && state.snapshot.alerts.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
@@ -903,7 +975,7 @@ function Settings({ radar }) {
903
975
  link.href = url;
904
976
  link.download = `dsh-market-radar-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.json`;
905
977
  link.click();
906
- setTimeout(() => URL.revokeObjectURL(url), 1e3);
978
+ setTimeout(() => URL.revokeObjectURL(url), 1e4);
907
979
  }, children: [
908
980
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Icon, { name: "download" }),
909
981
  "\u5BFC\u51FA\u914D\u7F6E"
@@ -952,7 +1024,7 @@ function Settings({ radar }) {
952
1024
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("h3", { children: "\u6570\u636E\u4E0E\u8FD0\u884C" }),
953
1025
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { children: "\u80A1\u7968\u62A5\u4EF7\u6765\u81EA\u817E\u8BAF\u8D22\u7ECF\uFF0C\u9EC4\u91D1\u62A5\u4EF7\u6765\u81EA\u65B0\u6D6A\u8D22\u7ECF\uFF1B\u5386\u53F2\u8D70\u52BF\u8FD8\u53EF\u80FD\u6765\u81EA Yahoo Finance \u6216\u4E0A\u6D77\u9EC4\u91D1\u4EA4\u6613\u6240\uFF0C\u56FE\u8868\u4E0B\u65B9\u6807\u660E\u5B9E\u9645\u6765\u6E90\u3002\u514D\u8D39\u6570\u636E\u53EF\u80FD\u5B58\u5728\u5EF6\u8FDF\u6216\u6682\u65F6\u4E0D\u53EF\u7528\u3002" }),
954
1026
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { children: "\u76D1\u6D4B\u5728 DSH \u8FD0\u884C\u4E14\u7535\u8111\u4FDD\u6301\u5524\u9192\u65F6\u8FDB\u884C\u3002\u81EA\u9009\u548C\u63D0\u9192\u4FDD\u5B58\u5728\u672C\u673A\u5F53\u524D profile\u3002" }),
955
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { children: "\u9996\u7248\u4F7F\u7528\u5E38\u89C4\u4EA4\u6613\u65F6\u6BB5\u5224\u65AD\u4F11\u5E02\uFF0C\u8282\u5047\u65E5\u53CA\u4E34\u65F6\u4F11\u5E02\u53EF\u80FD\u663E\u793A\u4E3A\u201C\u62A5\u4EF7\u5DF2\u5EF6\u8FDF\u201D\u3002" })
1027
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { children: "\u4F7F\u7528\u5E38\u89C4\u4EA4\u6613\u65F6\u6BB5\u5224\u65AD\u4F11\u5E02\uFF0C\u8282\u5047\u65E5\u53CA\u4E34\u65F6\u4F11\u5E02\u53EF\u80FD\u663E\u793A\u4E3A\u201C\u62A5\u4EF7\u5DF2\u5EF6\u8FDF\u201D\u3002" })
956
1028
  ] })
957
1029
  ] });
958
1030
  }
@@ -1064,11 +1136,18 @@ function MarketEventCard({ event, market, preview }) {
1064
1136
  }
1065
1137
  function MarketEventList({ market, load, preview }) {
1066
1138
  const eventMarket = market === "cn" ? "cn" : "us";
1139
+ const prevMarket = (0, import_react2.useRef)(eventMarket);
1140
+ const [attempt, setAttempt] = (0, import_react2.useState)(0);
1067
1141
  const [result, setResult] = (0, import_react2.useState)(null);
1068
1142
  const [failed, setFailed] = (0, import_react2.useState)(false);
1069
1143
  (0, import_react2.useEffect)(() => {
1070
1144
  let active = true;
1071
1145
  let timer;
1146
+ if (prevMarket.current !== eventMarket) {
1147
+ prevMarket.current = eventMarket;
1148
+ setResult(null);
1149
+ }
1150
+ setFailed(false);
1072
1151
  const withoutElapsedSchedule = (value, now) => ({
1073
1152
  ...value,
1074
1153
  events: value.events.filter((event) => event.kind !== "scheduled" || scheduleExpiresAt(event) > now)
@@ -1096,11 +1175,12 @@ function MarketEventList({ market, load, preview }) {
1096
1175
  active = false;
1097
1176
  clearTimeout(timer);
1098
1177
  };
1099
- }, [load, eventMarket]);
1178
+ }, [load, eventMarket, attempt]);
1100
1179
  if (failed) return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("p", { className: "mr-event-status", role: "status", children: [
1101
1180
  "\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6",
1102
1181
  MARKET_LABEL[market],
1103
- "\u5E02\u573A\u4E8B\u4EF6"
1182
+ "\u5E02\u573A\u4E8B\u4EF6 ",
1183
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { className: "mr-text-button", onClick: () => setAttempt((value) => value + 1), children: "\u91CD\u8BD5" })
1104
1184
  ] });
1105
1185
  if (!result) return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { className: "mr-event-status", role: "status", children: "\u6B63\u5728\u8BFB\u53D6\u5E02\u573A\u4E8B\u4EF6\u2026" });
1106
1186
  const { events, unavailable } = result;
@@ -1126,7 +1206,9 @@ function MarketEventList({ market, load, preview }) {
1126
1206
  [...fallbackLinks.values()].map((link) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { children: [
1127
1207
  " \xB7 ",
1128
1208
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("a", { href: link.href, target: "_blank", rel: "noopener noreferrer", children: link.label })
1129
- ] }, link.href))
1209
+ ] }, link.href)),
1210
+ " ",
1211
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { className: "mr-text-button", onClick: () => setAttempt((value) => value + 1), children: "\u91CD\u8BD5" })
1130
1212
  ] }),
1131
1213
  !events.length && !unavailable.length && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("p", { className: "mr-event-status", role: "status", children: [
1132
1214
  "\u8FD1\u671F\u6682\u65E0\u53EF\u663E\u793A\u7684",
@@ -1230,6 +1312,9 @@ function EconomicIndicators({ load, preview }) {
1230
1312
  active = false;
1231
1313
  };
1232
1314
  }, [expanded, load, attempt]);
1315
+ const earliestFetched = result?.indicators.reduce((earliest, item) => !earliest || item.fetchedAt < earliest ? item.fetchedAt : earliest, "") ?? "";
1316
+ const latestFetched = result?.indicators.reduce((latest, item) => item.fetchedAt > latest ? item.fetchedAt : latest, "") ?? "";
1317
+ const fetchedLabel = latestFetched ? earliestFetched === latestFetched ? EVENT_TIME.format(new Date(latestFetched)) : `${EVENT_TIME.format(new Date(earliestFetched))} \u2014 ${EVENT_TIME.format(new Date(latestFetched))}` : "";
1233
1318
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("details", { className: "mr-economics", onToggle: (event) => setExpanded(event.currentTarget.open), children: [
1234
1319
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("summary", { children: [
1235
1320
  "\u7ECF\u6D4E\u6570\u636E",
@@ -1244,9 +1329,9 @@ function EconomicIndicators({ load, preview }) {
1244
1329
  " ",
1245
1330
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { className: "mr-text-button", onClick: () => setAttempt((value) => value + 1), children: "\u91CD\u8BD5" })
1246
1331
  ] }),
1247
- result?.indicators[0] && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("p", { className: "mr-economic-updated", children: [
1332
+ fetchedLabel && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("p", { className: "mr-economic-updated", children: [
1248
1333
  "\u6570\u636E\u83B7\u53D6\u4E8E ",
1249
- EVENT_TIME.format(new Date(result.indicators[0].fetchedAt)),
1334
+ fetchedLabel,
1250
1335
  "\uFF08\u5317\u4EAC\u65F6\u95F4\uFF09"
1251
1336
  ] })
1252
1337
  ] })
@@ -1301,7 +1386,8 @@ function InstrumentDetail({ radar, instrument, onBack, onRules }) {
1301
1386
  clearTimeout(timer);
1302
1387
  };
1303
1388
  }, [radar, instrument.id, range]);
1304
- const quote = state.snapshot.quotes[instrument.id];
1389
+ const original = state.snapshot.quotes[instrument.id];
1390
+ const quote = original && !state.connected ? { ...original, status: "error" } : original;
1305
1391
  const displayInstrument = quote?.instrument ?? instrument;
1306
1392
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("section", { className: "mr-detail", children: [
1307
1393
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("button", { className: "mr-text-button mr-back", onClick: onBack, children: [
@@ -1328,7 +1414,7 @@ function InstrumentDetail({ radar, instrument, onBack, onRules }) {
1328
1414
  ] }),
1329
1415
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "mr-detail-status", children: [
1330
1416
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: `mr-status mr-status-${quote?.status ?? "unknown"}`, children: quote ? STATUS_LABEL[quote.status] : "\u7B49\u5F85\u62A5\u4EF7" }),
1331
- quote?.asOf && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: new Date(quote.asOf).toLocaleString("zh-CN", { hour12: false }) })
1417
+ quote?.asOf && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: formatQuoteTime(displayInstrument, quote.asOf) ?? "\u65F6\u95F4\u672A\u77E5" })
1332
1418
  ] }),
1333
1419
  state.snapshot.errors?.[instrument.id] && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { className: "mr-error", children: state.snapshot.errors[instrument.id] }),
1334
1420
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "mr-chart-title", children: [
@@ -1352,7 +1438,7 @@ function InstrumentDetail({ radar, instrument, onBack, onRules }) {
1352
1438
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("strong", { children: quote?.source ?? "\u2014" })
1353
1439
  ] })
1354
1440
  ] }),
1355
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("button", { className: "mr-button mr-primary mr-full", disabled: !quote, onClick: () => {
1441
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("button", { className: "mr-button mr-primary mr-full", disabled: !quote || !state.connected || quote.status === "error", onClick: () => {
1356
1442
  if (quote) setPreview(snapshotText([quote]));
1357
1443
  }, children: [
1358
1444
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Icon, { name: "chat" }),
@@ -1413,7 +1499,9 @@ function Dashboard({ radar }) {
1413
1499
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Icon, {}),
1414
1500
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: "\u884C\u60C5" })
1415
1501
  ] }),
1416
- state.open && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("aside", { className: "mr-panel", ref: panel, role: "dialog", "aria-modal": "false", "aria-label": "\u884C\u60C5\u96F7\u8FBE", children: [
1502
+ state.open && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("aside", { className: "mr-panel", ref: panel, role: "dialog", "aria-modal": "false", "aria-label": "\u884C\u60C5\u96F7\u8FBE", onPointerDown: (e) => {
1503
+ if (!(e.target instanceof Element && e.target.closest("details.mr-row-menu"))) for (const el of panel.current?.querySelectorAll("details.mr-row-menu[open]") ?? []) el.removeAttribute("open");
1504
+ }, children: [
1417
1505
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("header", { className: "mr-header", children: [
1418
1506
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "mr-header-title", children: [
1419
1507
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "mr-logo", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Icon, { size: 20 }) }),
@@ -1470,13 +1558,17 @@ function Dashboard({ radar }) {
1470
1558
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: "mr-watchlist", children: list.map((i) => {
1471
1559
  const original = state.snapshot.quotes[i.id];
1472
1560
  const quote = original && !state.connected ? { ...original, status: "error" } : original;
1561
+ const name2 = displayName(i, quote);
1473
1562
  const pinned = config.pinned.includes(i.id);
1563
+ const closeMenus = (current) => {
1564
+ for (const el of panel.current?.querySelectorAll("details.mr-row-menu[open]") ?? []) if (el !== current) el.removeAttribute("open");
1565
+ };
1474
1566
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "mr-quote-row", children: [
1475
1567
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("button", { className: "mr-quote-main", onClick: () => setSelected(i.id), children: [
1476
1568
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "mr-quote-label", children: [
1477
1569
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: `mr-market-letter mr-tag-${i.market}`, children: i.market === "gold" ? "\u91D1" : i.market === "cn" ? "A" : "US" }),
1478
1570
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { children: [
1479
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("strong", { children: quote?.instrument.name ?? i.name }),
1571
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("strong", { children: name2 }),
1480
1572
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { children: [
1481
1573
  i.symbol,
1482
1574
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "mr-inline-dot", children: "\xB7" }),
@@ -1489,7 +1581,7 @@ function Dashboard({ radar }) {
1489
1581
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Change, { quote })
1490
1582
  ] })
1491
1583
  ] }),
1492
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(IconButton, { icon: "pin", label: pinned ? `\u53D6\u6D88\u56FA\u5B9A ${i.name}` : `\u56FA\u5B9A ${i.name} \u5230\u884C\u60C5\u6761`, active: pinned, disabled: state.busy, onClick: () => {
1584
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(IconButton, { icon: "pin", label: pinned ? `\u53D6\u6D88\u56FA\u5B9A ${name2}` : `\u56FA\u5B9A ${name2} \u5230\u884C\u60C5\u6761`, active: pinned, disabled: state.busy, onClick: () => {
1493
1585
  void radar.save((c) => {
1494
1586
  if (pinned) c.pinned = c.pinned.filter((id) => id !== i.id);
1495
1587
  else {
@@ -1499,28 +1591,34 @@ function Dashboard({ radar }) {
1499
1591
  }).catch(() => {
1500
1592
  });
1501
1593
  } }),
1502
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("details", { className: "mr-row-menu", children: [
1503
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("summary", { "aria-label": `\u7BA1\u7406 ${i.name}`, children: "\xB7\xB7\xB7" }),
1594
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("details", { className: "mr-row-menu", onToggle: (e) => {
1595
+ if (e.currentTarget.open) closeMenus(e.currentTarget);
1596
+ }, children: [
1597
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("summary", { "aria-label": `\u7BA1\u7406 ${name2}`, children: "\xB7\xB7\xB7" }),
1504
1598
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { children: [
1505
1599
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { disabled: state.busy || config.instruments[0]?.id === i.id, onClick: () => {
1600
+ closeMenus();
1506
1601
  void radar.save((c) => {
1507
1602
  const at = c.instruments.findIndex((v) => v.id === i.id);
1508
- [c.instruments[at - 1], c.instruments[at]] = [c.instruments[at], c.instruments[at - 1]];
1603
+ if (at > 0) [c.instruments[at - 1], c.instruments[at]] = [c.instruments[at], c.instruments[at - 1]];
1509
1604
  }).catch(() => {
1510
1605
  });
1511
1606
  }, children: "\u4E0A\u79FB" }),
1512
1607
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { disabled: state.busy || config.instruments.at(-1)?.id === i.id, onClick: () => {
1608
+ closeMenus();
1513
1609
  void radar.save((c) => {
1514
1610
  const at = c.instruments.findIndex((v) => v.id === i.id);
1515
- [c.instruments[at], c.instruments[at + 1]] = [c.instruments[at + 1], c.instruments[at]];
1611
+ if (at >= 0 && at < c.instruments.length - 1) [c.instruments[at], c.instruments[at + 1]] = [c.instruments[at + 1], c.instruments[at]];
1516
1612
  }).catch(() => {
1517
1613
  });
1518
1614
  }, children: "\u4E0B\u79FB" }),
1519
1615
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { onClick: () => {
1616
+ closeMenus();
1520
1617
  rulesFor.current = i.id;
1521
1618
  setPage("rules");
1522
1619
  }, children: "\u8BBE\u7F6E\u63D0\u9192" }),
1523
1620
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { className: "mr-danger-text", disabled: state.busy, onClick: () => {
1621
+ closeMenus();
1524
1622
  void radar.save((c) => {
1525
1623
  c.instruments = c.instruments.filter((v) => v.id !== i.id);
1526
1624
  c.pinned = c.pinned.filter((id) => id !== i.id);
package/lib/index.js CHANGED
@@ -170,13 +170,16 @@ function sourceTime(value, zone) {
170
170
  return new Date(utc).toISOString();
171
171
  }
172
172
  function scheduledClosed(instrument, now) {
173
- const zone = instrument.market === "us" ? "America/New_York" : "Asia/Shanghai";
173
+ const zone = instrument.market === "us" || instrument.symbol === "XAU" ? "America/New_York" : "Asia/Shanghai";
174
174
  const p = zonedParts(now, zone);
175
175
  const weekday = new Date(Date.UTC(p.year, p.month - 1, p.day)).getUTCDay();
176
176
  const minute = p.hour * 60 + p.minute;
177
177
  if (instrument.market === "us") return weekday === 0 || weekday === 6 || minute < 570 || minute >= 960;
178
178
  if (instrument.market === "cn") return weekday === 0 || weekday === 6 || minute < 570 || minute >= 690 && minute < 780 || minute >= 900;
179
- if (instrument.symbol === "XAU") return weekday === 0 || weekday === 6 && minute >= 360 || weekday === 1 && minute < 420;
179
+ if (instrument.symbol === "XAU") {
180
+ if (weekday === 6 || weekday === 0 && minute < 1080 || weekday === 5 && minute >= 1020) return true;
181
+ return minute >= 1020 && minute < 1080;
182
+ }
180
183
  const day = weekday >= 1 && weekday <= 5 && (minute >= 540 && minute < 690 || minute >= 810 && minute < 930);
181
184
  const night = weekday >= 1 && weekday <= 5 && minute >= 1200;
182
185
  const early = weekday >= 2 && weekday <= 6 && minute < 150;
@@ -513,7 +516,7 @@ ${article}`, "\u57FA\u4E8E\u56FD\u5BB6\u7EDF\u8BA1\u5C40\u6570\u636E\u53D1\u5E03
513
516
  }
514
517
  async previewIndicator(indicator) {
515
518
  if (indicator.value === null) throw new Error("\u5F53\u524D\u6570\u636E\u4E0D\u8DB3\uFF0C\u6682\u65E0\u6CD5\u751F\u6210\u5224\u65AD");
516
- const key = `indicator:${JSON.stringify(indicator)}`;
519
+ const key = `indicator:${JSON.stringify({ id: indicator.id, period: indicator.period, value: indicator.value, previous: indicator.previous, history: indicator.history })}`;
517
520
  const cached = this.cache.get(key);
518
521
  if (cached) return cached;
519
522
  const existing = this.pending.get(key);
@@ -595,7 +598,7 @@ ${article}`, coverage, "us");
595
598
  let output = "";
596
599
  let finished = false;
597
600
  try {
598
- for await (const chunk of llm.stream({ provider: provider.id, model: model.id, system, messages, maxTokens: 800, signal: AbortSignal.any([this.signal, AbortSignal.timeout(6e4)]) })) {
601
+ for await (const chunk of llm.stream({ provider: provider.id, model: model.id, system, messages, maxTokens: 1200, signal: AbortSignal.any([this.signal, AbortSignal.timeout(6e4)]) })) {
599
602
  if (chunk.type === "text-delta") output += chunk.text ?? "";
600
603
  if (output.length > 5e3) throw new Error("\u6A21\u578B\u8FD4\u56DE\u5185\u5BB9\u8FC7\u957F");
601
604
  if (chunk.type === "finish") {
@@ -604,7 +607,7 @@ ${article}`, coverage, "us");
604
607
  }
605
608
  }
606
609
  if (!finished) throw new Error("\u6A21\u578B\u672A\u80FD\u5B8C\u6210\u6458\u8981");
607
- const parsed = JSON.parse(output.trim().replace(/^```(?:json)?\s*|\s*```$/gi, ""));
610
+ const parsed = parseJsonObject(output);
608
611
  if (!parsed || typeof parsed !== "object") throw new Error("\u6A21\u578B\u8FD4\u56DE\u683C\u5F0F\u65E0\u6548");
609
612
  const result = parsed;
610
613
  if (typeof result.summary !== "string" || !result.summary.trim() || result.summary.length > 600 || typeof result.outlook !== "string" || !result.outlook.trim() || result.outlook.length > 600) throw new Error("\u6A21\u578B\u8FD4\u56DE\u683C\u5F0F\u65E0\u6548");
@@ -619,11 +622,31 @@ ${article}`, coverage, "us");
619
622
  const stock = parseImpact(impacts?.[stockKey]);
620
623
  const parsedImpacts = impactMarket === "cn" ? { gold, cnStocks: stock } : { gold, usStocks: stock };
621
624
  return { summary: result.summary.trim(), outlook: result.outlook.trim(), impacts: parsedImpacts, model: `${provider.name} / ${model.name}`, coverage };
622
- } catch {
625
+ } catch (error) {
626
+ if (this.signal.aborted) throw new Error("\u4E8B\u4EF6\u6458\u8981\u751F\u6210\u5DF2\u53D6\u6D88");
627
+ if (error?.name === "TimeoutError") throw new Error("\u4E8B\u4EF6\u6458\u8981\u751F\u6210\u5931\u8D25\uFF1A\u6A21\u578B\u54CD\u5E94\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
628
+ if (error instanceof Error && ["\u6A21\u578B\u8FD4\u56DE\u5185\u5BB9\u8FC7\u957F", "\u6A21\u578B\u672A\u80FD\u5B8C\u6210\u6458\u8981", "\u6A21\u578B\u8FD4\u56DE\u683C\u5F0F\u65E0\u6548"].includes(error.message)) {
629
+ throw new Error(`\u4E8B\u4EF6\u6458\u8981\u751F\u6210\u5931\u8D25\uFF1A${error.message}`);
630
+ }
623
631
  throw new Error("\u4E8B\u4EF6\u6458\u8981\u751F\u6210\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6A21\u578B\u8FDE\u63A5\u540E\u91CD\u8BD5");
624
632
  }
625
633
  }
626
634
  };
635
+ function parseJsonObject(raw) {
636
+ const cleaned = raw.trim().replace(/^```(?:json)?\s*|\s*```$/gi, "");
637
+ try {
638
+ return JSON.parse(cleaned);
639
+ } catch {
640
+ const start = cleaned.indexOf("{"), end = cleaned.lastIndexOf("}");
641
+ if (start >= 0 && end > start) {
642
+ try {
643
+ return JSON.parse(cleaned.slice(start, end + 1));
644
+ } catch {
645
+ }
646
+ }
647
+ throw new Error("\u6A21\u578B\u8FD4\u56DE\u683C\u5F0F\u65E0\u6548");
648
+ }
649
+ }
627
650
 
628
651
  // src/economic-indicators.ts
629
652
  var SERIES = { payroll: "CES0000000001", cpi: "CUUR0000SA0" };
@@ -663,6 +686,7 @@ function parseBlsIndicator(raw, id, fetchedAt) {
663
686
  });
664
687
  return { id, period: latest, value: calculate(latest), previous: calculate(monthKey(year, month - 1)), history, fetchedAt };
665
688
  }
689
+ var INDICATOR_IDS = ["payroll", "cpi"];
666
690
  var EconomicIndicatorsFeed = class {
667
691
  constructor(signal, fetcher = fetch, now = Date.now) {
668
692
  this.signal = signal;
@@ -673,26 +697,42 @@ var EconomicIndicatorsFeed = class {
673
697
  fetcher;
674
698
  now;
675
699
  pending;
676
- cached;
700
+ cached = /* @__PURE__ */ new Map();
677
701
  load() {
678
- if (this.cached && this.now() < this.cached.expires) return Promise.resolve(this.cached.value);
702
+ const now = this.now();
703
+ const hit = INDICATOR_IDS.map((id) => this.cached.get(id)).filter((entry) => entry && now < entry.expires);
704
+ if (hit.length === INDICATOR_IDS.length) {
705
+ return Promise.resolve({ indicators: hit.map((entry) => entry.value), unavailable: [] });
706
+ }
679
707
  return this.pending ??= this.refresh().finally(() => {
680
708
  this.pending = void 0;
681
709
  });
682
710
  }
683
711
  async refresh() {
684
- const ids = ["payroll", "cpi"];
685
- const fetchedAt = new Date(this.now()).toISOString();
686
- const results = await Promise.allSettled(ids.map(async (id) => {
712
+ const now = this.now();
713
+ const missing = INDICATOR_IDS.filter((id) => {
714
+ const entry = this.cached.get(id);
715
+ return !entry || now >= entry.expires;
716
+ });
717
+ const fetchedAt = new Date(now).toISOString();
718
+ const results = await Promise.allSettled(missing.map(async (id) => {
687
719
  const url = `https://api.bls.gov/publicAPI/v1/timeseries/data/${SERIES[id]}`;
688
720
  return parseBlsIndicator(await fetchFeed(this.fetcher, url, this.signal), id, fetchedAt);
689
721
  }));
722
+ const unavailableSet = /* @__PURE__ */ new Set();
723
+ results.forEach((result, index) => {
724
+ const id = missing[index];
725
+ if (result.status === "fulfilled") this.cached.set(id, { value: result.value, expires: this.now() + 4 * 36e5 });
726
+ else unavailableSet.add(id);
727
+ });
690
728
  const indicators = [];
691
729
  const unavailable = [];
692
- results.forEach((result, index) => result.status === "fulfilled" ? indicators.push(result.value) : unavailable.push(ids[index]));
693
- const value = { indicators, unavailable };
694
- this.cached = unavailable.length ? void 0 : { value, expires: this.now() + 4 * 36e5 };
695
- return value;
730
+ for (const id of INDICATOR_IDS) {
731
+ const entry = this.cached.get(id);
732
+ if (entry && !unavailableSet.has(id)) indicators.push(entry.value);
733
+ else unavailable.push(id);
734
+ }
735
+ return { indicators, unavailable };
696
736
  }
697
737
  };
698
738
 
@@ -844,10 +884,13 @@ function parseSgeDaily(raw) {
844
884
  return time !== null && price !== null ? [{ time, price }] : [];
845
885
  });
846
886
  }
887
+ var YAHOO_INDEX = { ".INX": "^GSPC", ".DJI": "^DJI", ".IXIC": "^IXIC", ".NDX": "^NDX" };
847
888
  function yahooSymbol(i) {
848
889
  if (i.market !== "us") return null;
849
- if (i.symbol === ".INX") return "^GSPC";
850
- return /^[A-Z][A-Z0-9-]*$/.test(i.symbol) ? i.symbol : null;
890
+ if (Object.hasOwn(YAHOO_INDEX, i.symbol)) return YAHOO_INDEX[i.symbol];
891
+ if (/^[A-Z][A-Z0-9-]*$/.test(i.symbol)) return i.symbol;
892
+ if (/^[A-Z][A-Z0-9-]*\.[A-Z]{1,3}$/.test(i.symbol)) return i.symbol.replace(".", "-");
893
+ return null;
851
894
  }
852
895
  function parseYahooSeries(raw, symbol, daily) {
853
896
  const result = raw?.chart?.result?.[0];
@@ -875,9 +918,13 @@ var PublicMarketProvider = class {
875
918
  }
876
919
  fetcher;
877
920
  now;
921
+ goldDaily = /* @__PURE__ */ new Map();
922
+ goldDailyPending = /* @__PURE__ */ new Map();
878
923
  async text(url, signal, body, maxBytes = 2e6) {
879
- if (!NETWORK_DOMAINS.includes(new URL(url).hostname)) throw new Error("\u884C\u60C5\u5730\u5740\u4E0D\u5728\u5141\u8BB8\u5217\u8868");
880
- const response = await this.fetcher(url, { method: body === void 0 ? "GET" : "POST", body, headers: { Referer: url.includes("sge.com.cn") ? "https://www.sge.com.cn/" : "https://finance.sina.com.cn/", "User-Agent": "DSH-Market-Radar/0.1", ...body === void 0 ? {} : { "Content-Type": "application/x-www-form-urlencoded" } }, signal: AbortSignal.any([signal, AbortSignal.timeout(1e4)]), redirect: "error" });
924
+ const hostname = new URL(url).hostname;
925
+ if (!NETWORK_DOMAINS.includes(hostname)) throw new Error("\u884C\u60C5\u5730\u5740\u4E0D\u5728\u5141\u8BB8\u5217\u8868");
926
+ const referer = hostname === "www.sge.com.cn" ? "https://www.sge.com.cn/" : hostname.endsWith(".sinajs.cn") || hostname.endsWith(".sina.com.cn") ? "https://finance.sina.com.cn/" : void 0;
927
+ const response = await this.fetcher(url, { method: body === void 0 ? "GET" : "POST", body, headers: { ...referer ? { Referer: referer } : {}, "User-Agent": "DSH-Market-Radar/0.2", ...body === void 0 ? {} : { "Content-Type": "application/x-www-form-urlencoded" } }, signal: AbortSignal.any([signal, AbortSignal.timeout(1e4)]), redirect: "error" });
881
928
  if (!response.ok) throw new Error(`\u884C\u60C5\u670D\u52A1\u6682\u4E0D\u53EF\u7528\uFF08HTTP ${response.status}\uFF09`);
882
929
  const reader = response.body?.getReader();
883
930
  if (!reader) throw new Error("\u884C\u60C5\u670D\u52A1\u8FD4\u56DE\u7A7A\u54CD\u5E94");
@@ -902,7 +949,7 @@ var PublicMarketProvider = class {
902
949
  bytes.set(chunk, offset);
903
950
  offset += chunk.byteLength;
904
951
  }
905
- const utf8 = /utf-?8/i.test(response.headers.get("content-type") ?? "") || /(?:yahoo|sge)\.com/.test(new URL(url).hostname);
952
+ const utf8 = /utf-?8/i.test(response.headers.get("content-type") ?? "") || /(?:yahoo|sge)\.com/.test(hostname);
906
953
  return new TextDecoder(utf8 ? "utf-8" : "gb18030").decode(bytes);
907
954
  }
908
955
  async quotes(instruments, signal) {
@@ -911,7 +958,7 @@ var PublicMarketProvider = class {
911
958
  const query = gold ? instruments.map((i) => i.symbol === "XAU" ? "hf_XAU" : "gds_AU9999").join(",") : instruments.map(tencentCode).join(",");
912
959
  const url = gold ? `https://hq.sinajs.cn/list=${query}` : `https://qt.gtimg.cn/q=${query}`;
913
960
  const body = await this.text(url, signal);
914
- return gold ? parseSina(body, instruments) : parseTencent(body, instruments);
961
+ return gold ? parseSina(body, instruments, this.now()) : parseTencent(body, instruments, this.now());
915
962
  }
916
963
  async series(i, signal) {
917
964
  if (i.market === "gold") {
@@ -922,6 +969,29 @@ var PublicMarketProvider = class {
922
969
  const text = await this.text(`https://web.ifzq.gtimg.cn/appstock/app/${method}/query?code=${tencentCode(i)}`, signal);
923
970
  return parseTencentSeries(JSON.parse(text), i).filter((p) => p.time <= this.now());
924
971
  }
972
+ async loadGoldDaily(symbol, range, signal) {
973
+ const ttl = range === "5d" ? 6e4 : 6e5;
974
+ const cached = this.goldDaily.get(symbol);
975
+ if (cached && this.now() - cached.at < ttl) return cached.points;
976
+ let request = this.goldDailyPending.get(symbol);
977
+ if (!request) {
978
+ request = (async () => {
979
+ if (symbol === "XAU") {
980
+ const body2 = await this.text("https://stock2.finance.sina.com.cn/futures/api/jsonp.php/var%20_data=/GlobalFuturesService.getGlobalFuturesDailyKLine?symbol=XAU", signal);
981
+ return parseSinaGoldDaily(body2);
982
+ }
983
+ const body = await this.text("https://www.sge.com.cn/graph/Dailyhq", signal, "instid=Au99.99");
984
+ return parseSgeDaily(JSON.parse(body));
985
+ })().then((points) => {
986
+ if (points.length) this.goldDaily.set(symbol, { points, at: this.now() });
987
+ return points;
988
+ }).finally(() => {
989
+ if (this.goldDailyPending.get(symbol) === request) this.goldDailyPending.delete(symbol);
990
+ });
991
+ this.goldDailyPending.set(symbol, request);
992
+ }
993
+ return request;
994
+ }
925
995
  async history(i, range, signal) {
926
996
  if (i.market === "cn") {
927
997
  if (range === "5d") {
@@ -930,26 +1000,27 @@ var PublicMarketProvider = class {
930
1000
  }
931
1001
  const count = range === "max" ? 2e3 : range === "5y" ? 1500 : 320;
932
1002
  const all = [];
933
- let end = "", partial = false;
1003
+ let end = "", partial = false, earliest = Infinity;
934
1004
  for (let page = 0; page < (range === "max" ? 8 : 1); page++) {
935
1005
  try {
936
1006
  const raw = await this.text(`https://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param=${tencentCode(i)},day,,${end},${count},none`, signal);
937
- const points = sanitizePoints(parseTencentDaily(JSON.parse(raw), i), 8 * DAY, 3e4);
938
- if (!points.length) {
1007
+ const points2 = sanitizePoints(parseTencentDaily(JSON.parse(raw), i), 8 * DAY, 3e4);
1008
+ if (!points2.length) {
939
1009
  if (page > 0) partial = true;
940
1010
  break;
941
1011
  }
942
- if (all.length && points[0].time >= Math.min(...all.map((p2) => p2.time))) {
1012
+ if (points2[0].time >= earliest) {
943
1013
  partial = true;
944
1014
  break;
945
1015
  }
946
- all.push(...points);
947
- if (range !== "max" || points.length < count) break;
1016
+ earliest = points2[0].time;
1017
+ all.push(...points2);
1018
+ if (range !== "max" || points2.length < count) break;
948
1019
  if (page === 7) {
949
1020
  partial = true;
950
1021
  break;
951
1022
  }
952
- const p = zonedParts(points[0].time, "Asia/Shanghai");
1023
+ const p = zonedParts(points2[0].time, "Asia/Shanghai");
953
1024
  end = new Date(Date.UTC(p.year, p.month - 1, p.day - 1)).toISOString().slice(0, 10);
954
1025
  } catch (error) {
955
1026
  if (!all.length || signal.aborted) throw error;
@@ -969,12 +1040,9 @@ var PublicMarketProvider = class {
969
1040
  const parsed = parseYahooSeries(JSON.parse(raw), symbol, daily);
970
1041
  return { points: daily ? selectDailyRange(parsed, range, "America/New_York", this.now()) : parsed.filter((p) => p.time <= this.now()), source: "Yahoo Finance", granularity: daily ? "daily" : "five-minute", note: daily ? "\u65E5\u7EBF close \xB7 \u590D\u6743\u53E3\u5F84\u4EE5\u6765\u6E90\u4E3A\u51C6\uFF1B\u5F53\u65E5\u6570\u636E\u53EF\u80FD\u672A\u6536\u76D8" : "\u6700\u8FD1 5 \u4E2A\u4EA4\u6613\u65E5 \xB7 5 \u5206\u949F\u91C7\u6837" };
971
1042
  }
972
- if (i.symbol === "XAU") {
973
- const body2 = await this.text("https://stock2.finance.sina.com.cn/futures/api/jsonp.php/var%20_data=/GlobalFuturesService.getGlobalFuturesDailyKLine?symbol=XAU", signal);
974
- return { points: selectDailyRange(parseSinaGoldDaily(body2), range, "Asia/Shanghai", this.now()), source: "\u65B0\u6D6A\u8D22\u7ECF XAU", granularity: "daily", note: "\u65E5\u7EBF\u6536\u76D8\u70B9\uFF1B\u5F53\u65E5\u6570\u636E\u53EF\u80FD\u672A\u6536\u76D8" };
975
- }
976
- const body = await this.text("https://www.sge.com.cn/graph/Dailyhq", signal, "instid=Au99.99");
977
- return { points: selectDailyRange(parseSgeDaily(JSON.parse(body)), range, "Asia/Shanghai", this.now()), source: "\u4E0A\u6D77\u9EC4\u91D1\u4EA4\u6613\u6240 Au99.99", granularity: "daily", note: "\u65E5\u7EBF\u6536\u76D8\u70B9\uFF1B\u5F53\u65E5\u6570\u636E\u53EF\u80FD\u672A\u6536\u76D8" };
1043
+ const points = await this.loadGoldDaily(i.symbol, range, signal);
1044
+ const source = i.symbol === "XAU" ? "\u65B0\u6D6A\u8D22\u7ECF XAU" : "\u4E0A\u6D77\u9EC4\u91D1\u4EA4\u6613\u6240 Au99.99";
1045
+ return { points: selectDailyRange(points, range, "Asia/Shanghai", this.now()), source, granularity: "daily", note: "\u65E5\u7EBF\u6536\u76D8\u70B9\uFF1B\u5F53\u65E5\u6570\u636E\u53EF\u80FD\u672A\u6536\u76D8" };
978
1046
  }
979
1047
  async resolve(market, symbol, signal) {
980
1048
  const instrument = instrumentFor(market, symbol);
@@ -983,8 +1051,8 @@ var PublicMarketProvider = class {
983
1051
  return q.instrument;
984
1052
  }
985
1053
  };
986
- function sampledSeries(i, points, quote) {
987
- return { instrumentId: i.id, range: "1d", points: sanitizePoints(points), previousClose: quote?.previousClose ?? null, source: quote?.source ?? "\u8FD0\u884C\u671F\u95F4\u91C7\u6837", coverage: "sampled", granularity: "sampled", updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
1054
+ function sampledSeries(i, points, quote, now = Date.now()) {
1055
+ return { instrumentId: i.id, range: "1d", points: sanitizePoints(points), previousClose: quote?.previousClose ?? null, source: quote?.source ?? "\u8FD0\u884C\u671F\u95F4\u91C7\u6837", coverage: "sampled", granularity: "sampled", updatedAt: new Date(now).toISOString() };
988
1056
  }
989
1057
 
990
1058
  // src/engine.ts
@@ -1005,6 +1073,7 @@ var RadarEngine = class {
1005
1073
  alertEngine = new AlertEngine();
1006
1074
  samples = /* @__PURE__ */ new Map();
1007
1075
  history = /* @__PURE__ */ new Map();
1076
+ seriesPending = /* @__PURE__ */ new Map();
1008
1077
  clients = /* @__PURE__ */ new Map();
1009
1078
  failures = /* @__PURE__ */ new Map();
1010
1079
  timer;
@@ -1013,6 +1082,9 @@ var RadarEngine = class {
1013
1082
  eventPreviewer = new MarketEventPreviewer(this.marketEventFeed, this.controller.signal);
1014
1083
  economicFeed = new EconomicIndicatorsFeed(this.controller.signal);
1015
1084
  inFlight;
1085
+ inFlightForce = false;
1086
+ inFlightInstrumentsKey = "";
1087
+ queuedForceRefresh;
1016
1088
  mutation = Promise.resolve();
1017
1089
  disposed = false;
1018
1090
  ready;
@@ -1129,12 +1201,33 @@ var RadarEngine = class {
1129
1201
  if (changed) this.state.alertsRevision++;
1130
1202
  return this.snapshot();
1131
1203
  }
1204
+ instrumentsKey() {
1205
+ return this.state.config.instruments.map((i) => i.id).join(",");
1206
+ }
1132
1207
  async refresh(force = false) {
1133
1208
  await this.ready;
1134
1209
  if (this.disposed) return this.snapshot();
1135
- if (this.inFlight) return this.inFlight;
1210
+ if (this.inFlight) {
1211
+ if (force && (!this.inFlightForce || this.inFlightInstrumentsKey !== this.instrumentsKey())) {
1212
+ return this.queuedForceRefresh ??= this.inFlight.then(
1213
+ () => {
1214
+ this.queuedForceRefresh = void 0;
1215
+ return this.refresh(true);
1216
+ },
1217
+ () => {
1218
+ this.queuedForceRefresh = void 0;
1219
+ return this.refresh(true);
1220
+ }
1221
+ );
1222
+ }
1223
+ return this.inFlight;
1224
+ }
1225
+ this.inFlightForce = force;
1226
+ this.inFlightInstrumentsKey = this.instrumentsKey();
1136
1227
  this.inFlight = this.fetchQuotes(force).finally(() => {
1137
1228
  this.inFlight = void 0;
1229
+ this.inFlightForce = false;
1230
+ this.inFlightInstrumentsKey = "";
1138
1231
  });
1139
1232
  return this.inFlight;
1140
1233
  }
@@ -1194,8 +1287,17 @@ var RadarEngine = class {
1194
1287
  if (!i) throw new Error("\u6807\u7684\u4E0D\u5728\u81EA\u9009\u4E2D");
1195
1288
  const key = `${id}|${range}`;
1196
1289
  const cached = this.history.get(key);
1197
- if (cached && this.now() - cached.at < (range === "1d" || range === "5d" ? 6e4 : 6e5)) return structuredClone(cached.series);
1198
- const fallback = sampledSeries(i, this.samples.get(id) ?? [], this.state.quotes[id]);
1290
+ if (cached && cached.series.coverage !== "sampled" && this.now() - cached.at < (range === "1d" || range === "5d" ? 6e4 : 6e5)) return structuredClone(cached.series);
1291
+ const pending = this.seriesPending.get(key);
1292
+ if (pending) return pending.then((result) => structuredClone(result));
1293
+ const request = this.loadSeries(i, id, range, key).finally(() => {
1294
+ if (this.seriesPending.get(key) === request) this.seriesPending.delete(key);
1295
+ });
1296
+ this.seriesPending.set(key, request);
1297
+ return request.then((result) => structuredClone(result));
1298
+ }
1299
+ async loadSeries(i, id, range, key) {
1300
+ const fallback = sampledSeries(i, this.samples.get(id) ?? [], this.state.quotes[id], this.now());
1199
1301
  try {
1200
1302
  let series;
1201
1303
  if (range === "1d") {
@@ -1206,7 +1308,7 @@ var RadarEngine = class {
1206
1308
  const data = await this.provider.history(i, range, this.controller.signal);
1207
1309
  series = { ...fallback, range, points: data.points, previousClose: null, coverage: "provider", source: data.source, granularity: data.granularity, note: data.note, ...!data.points.length ? { error: "\u8BE5\u65F6\u95F4\u8303\u56F4\u6682\u65E0\u53EF\u7528\u6570\u636E" } : {} };
1208
1310
  }
1209
- if (!this.disposed && this.state.config.instruments.some((item) => item.id === id)) this.history.set(key, { at: this.now(), series });
1311
+ if (!this.disposed && series.coverage !== "sampled" && this.state.config.instruments.some((item) => item.id === id)) this.history.set(key, { at: this.now(), series });
1210
1312
  return series;
1211
1313
  } catch (error) {
1212
1314
  if (range === "1d") return { ...fallback, error: "\u5386\u53F2\u8D70\u52BF\u6682\u4E0D\u53EF\u7528\uFF0C\u663E\u793A\u5DF2\u91C7\u6837\u533A\u95F4" };
@@ -1220,6 +1322,7 @@ var RadarEngine = class {
1220
1322
  this.clients.clear();
1221
1323
  this.samples.clear();
1222
1324
  this.history.clear();
1325
+ this.seriesPending.clear();
1223
1326
  this.alertEngine.reset();
1224
1327
  }
1225
1328
  };
package/package.json CHANGED
@@ -1,37 +1,88 @@
1
1
  {
2
2
  "name": "dsh-market-radar",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "在 DeepSeek Harness 查看黄金、A 股和美股行情,支持自选、价格走势、阈值提醒、按市场展示的市场事件与对话草稿快照。",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "main": "./lib/index.js",
8
- "exports": { ".": "./lib/index.js", "./client": "./lib/client.js", "./package.json": "./package.json" },
9
- "files": ["lib/index.js", "lib/client.js", "assets/icon.svg", "cordis.patch.yml", "README.md", "LICENSE"],
10
- "repository": { "type": "git", "url": "git+https://github.com/alwayXXX/dsh-market-radar.git" },
8
+ "exports": {
9
+ ".": "./lib/index.js",
10
+ "./client": "./lib/client.js",
11
+ "./package.json": "./package.json"
12
+ },
13
+ "files": [
14
+ "lib/index.js",
15
+ "lib/client.js",
16
+ "assets/icon.svg",
17
+ "cordis.patch.yml",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/alwayXXX/dsh-market-radar.git"
24
+ },
11
25
  "homepage": "https://github.com/alwayXXX/dsh-market-radar#readme",
12
- "bugs": { "url": "https://github.com/alwayXXX/dsh-market-radar/issues" },
13
- "engines": { "node": ">=24.9.0", "dsh": ">=0.2.1-rc.1 <0.3.0-0" },
14
- "packageManager": "pnpm@11.22.0",
15
- "keywords": ["dsh-plugin", "deepseek-harness", "stocks", "gold", "market-data", "ticker", "watchlist", "price-alerts", "economic-calendar"],
26
+ "bugs": {
27
+ "url": "https://github.com/alwayXXX/dsh-market-radar/issues"
28
+ },
29
+ "engines": {
30
+ "node": ">=24.9.0",
31
+ "dsh": ">=0.2.1-rc.1 <0.3.0-0"
32
+ },
33
+ "keywords": [
34
+ "dsh-plugin",
35
+ "deepseek-harness",
36
+ "stocks",
37
+ "gold",
38
+ "market-data",
39
+ "ticker",
40
+ "watchlist",
41
+ "price-alerts",
42
+ "economic-calendar"
43
+ ],
16
44
  "icon": "./assets/icon.svg",
17
45
  "dsh": {
18
- "bundle": { "patch": "./cordis.patch.yml" },
19
- "client": { "platform": "web", "inject": ["@deepseek-ai/dsh-client-ui-slots", "@deepseek-ai/dsh-client-connection", "@deepseek-ai/dsh-client-shortcuts"], "immediately": true }
46
+ "bundle": {
47
+ "patch": "./cordis.patch.yml"
48
+ },
49
+ "client": {
50
+ "platform": "web",
51
+ "inject": [
52
+ "@deepseek-ai/dsh-client-ui-slots",
53
+ "@deepseek-ai/dsh-client-connection",
54
+ "@deepseek-ai/dsh-client-shortcuts"
55
+ ],
56
+ "immediately": true
57
+ }
58
+ },
59
+ "dependencies": {
60
+ "@deepseek-ai/dsh-typert-protocol": ">=0.2.1-rc.1 <0.2.2-0 || >=0.2.2-rc.1 <0.3.0-0"
61
+ },
62
+ "peerDependencies": {
63
+ "react": ">=18.2.0 <20"
64
+ },
65
+ "peerDependenciesMeta": {
66
+ "react": {
67
+ "optional": true
68
+ }
69
+ },
70
+ "devDependencies": {
71
+ "@deepseek-ai/cordis": "^4.0.0",
72
+ "@types/node": "^26.6.6",
73
+ "@types/react": "^19.3.0",
74
+ "@types/react-dom": "^19.3.0",
75
+ "esbuild": "^0.28.2",
76
+ "react": "^19.3.1",
77
+ "react-dom": "^19.3.1",
78
+ "tsx": "^4.23.15",
79
+ "typescript": "^7.0.2"
20
80
  },
21
81
  "scripts": {
22
82
  "build": "node scripts/build.mjs",
23
83
  "typecheck": "tsc --noEmit",
24
84
  "test": "node --import tsx --test test/*.test.ts",
25
85
  "check": "pnpm typecheck && pnpm test && pnpm build",
26
- "smoke:package": "node scripts/package-smoke.mjs",
27
- "prepack": "pnpm build"
28
- },
29
- "dependencies": { "@deepseek-ai/dsh-typert-protocol": ">=0.2.1-rc.1 <0.2.2-0 || >=0.2.2-rc.1 <0.3.0-0" },
30
- "peerDependencies": { "react": ">=18.2.0 <20" },
31
- "peerDependenciesMeta": { "react": { "optional": true } },
32
- "devDependencies": {
33
- "@deepseek-ai/cordis": "^4.0.0",
34
- "@types/node": "^26.6.6", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0",
35
- "esbuild": "^0.28.2", "react": "^19.3.1", "react-dom": "^19.3.1", "tsx": "^4.23.15", "typescript": "^7.0.2"
86
+ "smoke:package": "node scripts/package-smoke.mjs"
36
87
  }
37
- }
88
+ }