dsh-desktop-statusbar 3.0.1 → 3.0.3
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/LICENSE +21 -21
- package/README.en.md +145 -145
- package/README.md +142 -142
- package/cordis.patch.yml +14 -14
- package/docs/official-models.json +468 -0
- package/docs/official-models.md +190 -0
- package/docs/vendor-intelligence-order.json +124 -0
- package/docs/vendor-intelligence-order.md +77 -0
- package/icon.svg +10 -10
- package/lib/balance-api.js +516 -499
- package/lib/client.js +11436 -9203
- package/lib/exchange-rate.js +199 -0
- package/lib/holiday.js +128 -128
- package/lib/index.js +1975 -407
- package/lib/release-age.js +509 -509
- package/lib/self-update.js +913 -567
- package/locale/en.json +6 -6
- package/locale/zh.json +6 -6
- package/package.json +72 -72
- package/tools/plugin-dir.cjs +0 -4
- package/tools/shot.cjs +9 -10
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 每日汇率:北京时间每天 9:00 之后拉一次「1 USD = ? CNY」,缓存到本地。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要它:余额色条要把两种货币的余额折成同一口径算比例,底栏「本轮 / 总计」
|
|
5
|
+
* 也要一个合并数字。以前这个汇率是**从内置价格表反算出来的常量**(client.js 的
|
|
6
|
+
* REFERENCE_RATE),它只反映写代码那天的行情,之后一直不变。
|
|
7
|
+
*
|
|
8
|
+
* 为什么不用银联:银联没有面向公众的免费 API,只有网页查询页,抓页面随时会坏。
|
|
9
|
+
* 用户确认改用公开汇率源(open.er-api.com),它每天 UTC 00:00 左右更新一次,
|
|
10
|
+
* 换算成北京时间约 08:00,正好在 9:00 之前落地。
|
|
11
|
+
*
|
|
12
|
+
* 为什么失败要静默:汇率是显示用的辅助数据,拉不到不该打扰用户。
|
|
13
|
+
* 拉不到就用上次成功的那一份;从没成功过就返回 null,调用方退回内置常量。
|
|
14
|
+
*/
|
|
15
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
16
|
+
import { homedir } from 'node:os'
|
|
17
|
+
import { join } from 'node:path'
|
|
18
|
+
|
|
19
|
+
/** 汇率接口:基准货币是 CNY,返回里 rates.USD 是「1 CNY = ? USD」。 */
|
|
20
|
+
const RATE_URL = 'https://open.er-api.com/v6/latest/CNY'
|
|
21
|
+
/** 缓存文件路径(与台账同目录,都在 dsh-status-bar 下)。 */
|
|
22
|
+
const CACHE_FILE_NAME = 'exchange-rate.json'
|
|
23
|
+
/** 拉取超时:汇率是锦上添花的东西,不该拖住任何主流程。 */
|
|
24
|
+
const FETCH_TIMEOUT_MS = 8000
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* 缓存目录:与 usage-ledger.json 同一个 dsh-status-bar 目录。
|
|
28
|
+
*
|
|
29
|
+
* **必须跟着 `DSH_HOME` 走,不能用 `homedir()`**:台账那边一直读 `DSH_HOME`
|
|
30
|
+
* (见 index.js 的 ledgerPath),测试把它指到临时目录。早先这里硬编码 `homedir()`,
|
|
31
|
+
* 结果测试读到的是真实用户主目录里的缓存 —— 既让测试之间互相污染,也让
|
|
32
|
+
* 「预置一份缓存让测试不抓汇率」这种隔离手段完全失效(实测踩过)。
|
|
33
|
+
*/
|
|
34
|
+
function cacheDir() {
|
|
35
|
+
const home = process.env.DSH_HOME !== undefined && process.env.DSH_HOME !== null && String(process.env.DSH_HOME).length > 0
|
|
36
|
+
? String(process.env.DSH_HOME)
|
|
37
|
+
: join(homedir(), '.dsh')
|
|
38
|
+
return join(home, 'dsh-status-bar')
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 缓存文件的绝对路径。 */
|
|
42
|
+
export function cacheFilePath() {
|
|
43
|
+
return join(cacheDir(), CACHE_FILE_NAME)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 读缓存的汇率。
|
|
48
|
+
*
|
|
49
|
+
* 返回 `{ rate, fetchedAt, source }`;文件不存在 / 坏数据 / rate 不合理都返回 null。
|
|
50
|
+
* `rate` 的含义固定是「1 USD = rate CNY」,与 client.js 里 REFERENCE_RATE 同向,
|
|
51
|
+
* 调用方可以直接替换,不需要再做方向换算。
|
|
52
|
+
*
|
|
53
|
+
* @returns {{rate: number, fetchedAt: number, source: string}|null}
|
|
54
|
+
*/
|
|
55
|
+
export function readCachedRate() {
|
|
56
|
+
try {
|
|
57
|
+
const file = cacheFilePath()
|
|
58
|
+
if (existsSync(file) !== true) return null
|
|
59
|
+
const parsed = JSON.parse(readFileSync(file, 'utf8'))
|
|
60
|
+
if (parsed === null || typeof parsed !== 'object') return null
|
|
61
|
+
const rate = Number(parsed.rate)
|
|
62
|
+
if (Number.isFinite(rate) !== true || rate <= 0) return null
|
|
63
|
+
/* 合理性下限:人民币兑美元历史上没到过 1:1 以下,超出这个范围说明数据坏了,
|
|
64
|
+
宁可退回内置常量也不要拿一个荒谬的汇率去折算金额。 */
|
|
65
|
+
if (rate < 3 || rate > 20) return null
|
|
66
|
+
return {
|
|
67
|
+
rate: rate,
|
|
68
|
+
fetchedAt: Number.isFinite(Number(parsed.fetchedAt)) ? Number(parsed.fetchedAt) : 0,
|
|
69
|
+
source: typeof parsed.source === 'string' ? parsed.source : 'unknown',
|
|
70
|
+
}
|
|
71
|
+
} catch (error) {
|
|
72
|
+
return null
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* 把接口返回换算成「1 USD = ? CNY」。
|
|
78
|
+
*
|
|
79
|
+
* 接口给的是 `base_code: CNY` + `rates.USD`,即「1 CNY = X USD」,
|
|
80
|
+
* 所以取倒数。字段缺失 / 非数字 / 不合理都返回 null。
|
|
81
|
+
*
|
|
82
|
+
* @param {unknown} payload
|
|
83
|
+
* @returns {number|null}
|
|
84
|
+
*/
|
|
85
|
+
export function rateFromPayload(payload) {
|
|
86
|
+
if (payload === null || typeof payload !== 'object') return null
|
|
87
|
+
const body = payload
|
|
88
|
+
if (body.result !== undefined && body.result !== 'success') return null
|
|
89
|
+
if (body.base_code !== undefined && body.base_code !== 'CNY') return null
|
|
90
|
+
const rates = body.rates
|
|
91
|
+
if (rates === null || typeof rates !== 'object') return null
|
|
92
|
+
const usdPerCny = Number(rates.USD)
|
|
93
|
+
if (Number.isFinite(usdPerCny) !== true || usdPerCny <= 0) return null
|
|
94
|
+
const cnyPerUsd = 1 / usdPerCny
|
|
95
|
+
if (cnyPerUsd < 3 || cnyPerUsd > 20) return null
|
|
96
|
+
/* 保留 4 位:再多没有意义,还会让缓存文件里的数字看起来可疑。 */
|
|
97
|
+
return Math.round(cnyPerUsd * 10000) / 10000
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* 拉一次汇率并写缓存。**任何异常都静默**,只以结构化结果返回。
|
|
102
|
+
*
|
|
103
|
+
* @param {{logger?: Function, fetchImpl?: Function, now?: number}} [options]
|
|
104
|
+
* @returns {Promise<{ok: boolean, rate: number|null, fetchedAt: number, reason: string|null}>}
|
|
105
|
+
*/
|
|
106
|
+
export async function fetchAndCacheRate(options) {
|
|
107
|
+
const opts = options === null || typeof options !== 'object' ? {} : options
|
|
108
|
+
const log = typeof opts.logger === 'function' ? opts.logger : () => {}
|
|
109
|
+
const now = Number.isFinite(Number(opts.now)) ? Number(opts.now) : Date.now()
|
|
110
|
+
const doFetch = typeof opts.fetchImpl === 'function' ? opts.fetchImpl : fetch
|
|
111
|
+
try {
|
|
112
|
+
const response = await doFetch(RATE_URL, {
|
|
113
|
+
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
|
114
|
+
headers: { accept: 'application/json' },
|
|
115
|
+
})
|
|
116
|
+
if (response === null || typeof response !== 'object' || response.ok !== true) {
|
|
117
|
+
return { ok: false, rate: null, fetchedAt: now, reason: 'http-' + String(response === null || response === undefined ? 'unknown' : response.status) }
|
|
118
|
+
}
|
|
119
|
+
const payload = await response.json()
|
|
120
|
+
const rate = rateFromPayload(payload)
|
|
121
|
+
if (rate === null) {
|
|
122
|
+
return { ok: false, rate: null, fetchedAt: now, reason: 'bad-payload' }
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
const dir = cacheDir()
|
|
126
|
+
if (existsSync(dir) !== true) mkdirSync(dir, { recursive: true })
|
|
127
|
+
writeFileSync(cacheFilePath(), JSON.stringify({
|
|
128
|
+
rate: rate,
|
|
129
|
+
fetchedAt: now,
|
|
130
|
+
source: 'open.er-api.com',
|
|
131
|
+
}), 'utf8')
|
|
132
|
+
} catch (error) {
|
|
133
|
+
/* 写不进缓存不算失败:这一拍拿到了汇率,调用方照样能用 */
|
|
134
|
+
log('exchange-rate: 缓存写入失败 ' + String(error === null || error === undefined ? 'unknown' : error.message))
|
|
135
|
+
}
|
|
136
|
+
log('exchange-rate: 1 USD = ' + String(rate) + ' CNY')
|
|
137
|
+
return { ok: true, rate: rate, fetchedAt: now, reason: null }
|
|
138
|
+
} catch (error) {
|
|
139
|
+
return {
|
|
140
|
+
ok: false,
|
|
141
|
+
rate: null,
|
|
142
|
+
fetchedAt: now,
|
|
143
|
+
reason: 'request-failed',
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* 今天(本地时区)09:00 的时间戳。
|
|
150
|
+
*
|
|
151
|
+
* 用**本地时区**而不是硬编码 UTC+8:用户机器如果不在东八区,按本地 9 点拉也是对的
|
|
152
|
+
* —— 它要的是「今天开始上班之后拿一份当天的汇率」,不是「北京时间 9 点整」。
|
|
153
|
+
*
|
|
154
|
+
* @param {number} now 毫秒时间戳
|
|
155
|
+
* @returns {number}
|
|
156
|
+
*/
|
|
157
|
+
export function nineAmOf(now) {
|
|
158
|
+
const date = new Date(Number.isFinite(Number(now)) ? Number(now) : Date.now())
|
|
159
|
+
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 9, 0, 0, 0).getTime()
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* 此刻该不该去拉汇率。
|
|
164
|
+
*
|
|
165
|
+
* 判据三条,缺一不可:
|
|
166
|
+
* 1. **今天 9:00 之前一律不拉** —— 接口每天 UTC 00:00 左右才更新(北京约 08:00),
|
|
167
|
+
* 9 点前拉到的还是上一日的价。早先漏了这一条,早上 8 点打开就会白拉一次。
|
|
168
|
+
* 2. 缓存为空 ⇒ 拉。
|
|
169
|
+
* 3. 缓存的拉取时间早于**今天 9:00** ⇒ 拉(说明今天还没拉过)。
|
|
170
|
+
*
|
|
171
|
+
* 于是「一天最多拉一次」是**由缓存时间戳保证的**:9 点后第一拍拉完就写缓存,
|
|
172
|
+
* 之后无论被调用多少次(余额路由每 60 秒问一次、用户反复重启 DSH)都会命中第 3 条为假,
|
|
173
|
+
* 一次都不会再发请求。
|
|
174
|
+
*
|
|
175
|
+
* @param {{rate: number, fetchedAt: number}|null} cached
|
|
176
|
+
* @param {number} now
|
|
177
|
+
* @returns {boolean}
|
|
178
|
+
*/
|
|
179
|
+
export function shouldRefresh(cached, now) {
|
|
180
|
+
const today9 = nineAmOf(now)
|
|
181
|
+
/* 9 点之前:今天这一份还没到发布时间,一次都不拉(有缓存就继续用昨天的)。 */
|
|
182
|
+
if (Number(now) < today9) return false
|
|
183
|
+
if (cached === null || cached === undefined) return true
|
|
184
|
+
const fetchedAt = Number(cached.fetchedAt)
|
|
185
|
+
if (Number.isFinite(fetchedAt) !== true) return true
|
|
186
|
+
return fetchedAt < today9
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* 当前该用的汇率(「1 USD = ? CNY」)。
|
|
191
|
+
*
|
|
192
|
+
* 有缓存用缓存,没缓存返回 null —— 调用方据此退回 client.js 的 REFERENCE_RATE。
|
|
193
|
+
*
|
|
194
|
+
* @returns {number|null}
|
|
195
|
+
*/
|
|
196
|
+
export function currentRate() {
|
|
197
|
+
const cached = readCachedRate()
|
|
198
|
+
return cached === null ? null : cached.rate
|
|
199
|
+
}
|
package/lib/holiday.js
CHANGED
|
@@ -1,128 +1,128 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 节假日日历:把国务院办公厅放假通知的正文解析成"哪些放假日落在周一至周五"。
|
|
3
|
-
*
|
|
4
|
-
* 只在 host 侧用:客户端拿不到跨域页面,由 host 抓取 + 解析后把日期数组交给客户端。
|
|
5
|
-
*
|
|
6
|
-
* 通知里的四种写法(2023-2026 四年原文都覆盖到了):
|
|
7
|
-
* 一、元旦:1月1日(周四)至3日(周六)放假调休,共3天。
|
|
8
|
-
* 一、元旦:1月1日放假,与周末连休。
|
|
9
|
-
* 二、春节:1月28日(农历除夕、周二)至2月4日(农历正月初七、周二)放假调休,共8天。
|
|
10
|
-
* 一、元旦:2022年12月31日至2023年1月2日放假调休,共3天。
|
|
11
|
-
*
|
|
12
|
-
* 只返回周一至周五的放假日 —— 周末本来就整天空闲,调休上班的周末也一样空闲,列进来没用。
|
|
13
|
-
*/
|
|
14
|
-
|
|
15
|
-
/** 通知里的日期:年份与月份都可以省略,例 `2022年12月31日` / `1月2日` / `至6日` */
|
|
16
|
-
const NOTICE_DATE = /(?:(\d{4})年)?(?:(\d{1,2})月)?(\d{1,2})日/g
|
|
17
|
-
const DAY_MS = 86400000
|
|
18
|
-
/** 一段假期最长不会超过这个天数,防正则意外把超长区间展开 */
|
|
19
|
-
const MAX_RANGE_DAYS = 40
|
|
20
|
-
/** HTML 解析的体积上限(字符):真实通知页 100~300KB,2MB 已经非常宽松。
|
|
21
|
-
* 超过就只看前 2MB —— 宁可解析不全,也不能让 host 主线程卡住(见 holidayHtmlToText)。 */
|
|
22
|
-
const HOLIDAY_HTML_MAX = 2 * 1024 * 1024
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* 线性切掉成对标签里的整段内容(`<script ...>...</script>` 这类)。
|
|
26
|
-
* 用 indexOf 前进而不是懒惰量词:找不到闭合标签时直接放弃剩余部分,
|
|
27
|
-
* 复杂度严格 O(n);`/<script[\s\S]*?<\/script>/gi` 在缺闭合时会从每个 `<` 往后扫到文末,
|
|
28
|
-
* 实测 40 万个未闭合 `<script>` 要 6 秒(卡死 host 事件循环)。
|
|
29
|
-
*/
|
|
30
|
-
function stripBlocks(text, tag) {
|
|
31
|
-
const open = '<' + tag
|
|
32
|
-
const close = '</' + tag
|
|
33
|
-
const lower = text.toLowerCase()
|
|
34
|
-
let out = ''
|
|
35
|
-
let at = 0
|
|
36
|
-
for (;;) {
|
|
37
|
-
const start = lower.indexOf(open, at)
|
|
38
|
-
if (start === -1) return out + text.slice(at)
|
|
39
|
-
out += text.slice(at, start)
|
|
40
|
-
const end = lower.indexOf(close, start)
|
|
41
|
-
if (end === -1) return out /* 没有闭合:整段丢弃,不再往后扫 */
|
|
42
|
-
const gt = text.indexOf('>', end)
|
|
43
|
-
if (gt === -1) return out
|
|
44
|
-
at = gt + 1
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
/** HTML → 纯文本:去脚本、样式与标签,解常见实体。
|
|
49
|
-
*
|
|
50
|
-
* 这段处理的是**外部网页**(国务院通知),内容不受我们控制,所以两处做了防御:
|
|
51
|
-
* ① 先按长度截断,避免超大文档把主线程占满;
|
|
52
|
-
* ② `<[^<>]+>` 而不是 `<[^>]+>` —— 后者不排除 `<`,大量孤立 `<` 时会反复跨越大段文本,
|
|
53
|
-
* 实测 20 万字符要 12 秒。 */
|
|
54
|
-
export function holidayHtmlToText(html) {
|
|
55
|
-
const raw = String(html === null || html === undefined ? '' : html).slice(0, HOLIDAY_HTML_MAX)
|
|
56
|
-
return stripBlocks(stripBlocks(raw, 'script'), 'style')
|
|
57
|
-
.replace(/<br\s*\/?>/gi, '\n')
|
|
58
|
-
.replace(/<\/p>/gi, '\n')
|
|
59
|
-
.replace(/<[^<>]+>/g, '')
|
|
60
|
-
.replace(/ /g, ' ')
|
|
61
|
-
.replace(/&/g, '&')
|
|
62
|
-
.replace(/</g, '<')
|
|
63
|
-
.replace(/>/g, '>')
|
|
64
|
-
.replace(/"/g, '"')
|
|
65
|
-
.replace(/[ \t\u3000]+/g, ' ')
|
|
66
|
-
.split('\n')
|
|
67
|
-
.map((line) => line.trim())
|
|
68
|
-
.filter((line) => line.length > 0)
|
|
69
|
-
.join('\n')
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
const pad = (n) => (n < 10 ? '0' + String(n) : String(n))
|
|
73
|
-
|
|
74
|
-
/**
|
|
75
|
-
* 从通知正文里取出该年的放假日(只留周一至周五,升序)。
|
|
76
|
-
* @param {string} text 通知正文,纯文本或 HTML 都行(HTML 会自动剥标签)
|
|
77
|
-
* @param {number} year 通知对应的年份
|
|
78
|
-
* @returns {string[]} `YYYY-MM-DD` 数组
|
|
79
|
-
*/
|
|
80
|
-
export function parseHolidayNotice(text, year) {
|
|
81
|
-
const days = new Set()
|
|
82
|
-
const flat = String(text === null || text === undefined ? '' : text)
|
|
83
|
-
.slice(0, HOLIDAY_HTML_MAX)
|
|
84
|
-
/* `[^<>]` 而不是 `[^>]`:理由同 holidayHtmlToText —— 大量孤立 `<` 时会退化 */
|
|
85
|
-
.replace(/<[^<>]+>/g, ' ')
|
|
86
|
-
.replace(/\s+/g, ' ')
|
|
87
|
-
/* 只认含"放假"的句子;含"上班"的句子是调休上班日,不能算进空闲 */
|
|
88
|
-
flat.split(/[。;;\n]/).forEach((sentence) => {
|
|
89
|
-
if (sentence.indexOf('放假') === -1 || sentence.indexOf('上班') !== -1) return
|
|
90
|
-
NOTICE_DATE.lastIndex = 0
|
|
91
|
-
const hits = []
|
|
92
|
-
let hit = null
|
|
93
|
-
while ((hit = NOTICE_DATE.exec(sentence)) !== null) {
|
|
94
|
-
hits.push({
|
|
95
|
-
year: hit[1] === undefined ? null : Number(hit[1]),
|
|
96
|
-
month: hit[2] === undefined ? null : Number(hit[2]),
|
|
97
|
-
day: Number(hit[3]),
|
|
98
|
-
})
|
|
99
|
-
}
|
|
100
|
-
if (hits.length === 0) return
|
|
101
|
-
/* 句子里有"至"就是一段区间(取前两个日期当起止);否则每个日期各算一天 */
|
|
102
|
-
const ranges = sentence.indexOf('至') !== -1 && hits.length >= 2
|
|
103
|
-
? [[hits[0], hits[1]]]
|
|
104
|
-
: hits.map((one) => [one, one])
|
|
105
|
-
ranges.forEach((pair) => {
|
|
106
|
-
const from = pair[0]
|
|
107
|
-
const to = pair[1]
|
|
108
|
-
/* 区间终点常省略月份("4月4日至6日"),用起点的月份补上;孤立的"6日"没法定位,跳过 */
|
|
109
|
-
const startMonth = from.month
|
|
110
|
-
if (startMonth === null) return
|
|
111
|
-
const endMonth = to.month === null ? startMonth : to.month
|
|
112
|
-
const startYear = from.year === null ? year : from.year
|
|
113
|
-
let endYear = to.year === null ? startYear : to.year
|
|
114
|
-
/* 终点月份比起点小 = 跨年,例:12月31日至1月2日 */
|
|
115
|
-
if (to.year === null && endMonth < startMonth) endYear = startYear + 1
|
|
116
|
-
const last = Date.UTC(endYear, endMonth - 1, to.day)
|
|
117
|
-
let cursor = Date.UTC(startYear, startMonth - 1, from.day)
|
|
118
|
-
for (let i = 0; cursor <= last && i < MAX_RANGE_DAYS; i += 1, cursor += DAY_MS) {
|
|
119
|
-
const at = new Date(cursor)
|
|
120
|
-
if (at.getUTCFullYear() !== year) continue
|
|
121
|
-
const weekday = at.getUTCDay()
|
|
122
|
-
if (weekday === 0 || weekday === 6) continue
|
|
123
|
-
days.add(String(at.getUTCFullYear()) + '-' + pad(at.getUTCMonth() + 1) + '-' + pad(at.getUTCDate()))
|
|
124
|
-
}
|
|
125
|
-
})
|
|
126
|
-
})
|
|
127
|
-
return Array.from(days).sort()
|
|
128
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* 节假日日历:把国务院办公厅放假通知的正文解析成"哪些放假日落在周一至周五"。
|
|
3
|
+
*
|
|
4
|
+
* 只在 host 侧用:客户端拿不到跨域页面,由 host 抓取 + 解析后把日期数组交给客户端。
|
|
5
|
+
*
|
|
6
|
+
* 通知里的四种写法(2023-2026 四年原文都覆盖到了):
|
|
7
|
+
* 一、元旦:1月1日(周四)至3日(周六)放假调休,共3天。
|
|
8
|
+
* 一、元旦:1月1日放假,与周末连休。
|
|
9
|
+
* 二、春节:1月28日(农历除夕、周二)至2月4日(农历正月初七、周二)放假调休,共8天。
|
|
10
|
+
* 一、元旦:2022年12月31日至2023年1月2日放假调休,共3天。
|
|
11
|
+
*
|
|
12
|
+
* 只返回周一至周五的放假日 —— 周末本来就整天空闲,调休上班的周末也一样空闲,列进来没用。
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** 通知里的日期:年份与月份都可以省略,例 `2022年12月31日` / `1月2日` / `至6日` */
|
|
16
|
+
const NOTICE_DATE = /(?:(\d{4})年)?(?:(\d{1,2})月)?(\d{1,2})日/g
|
|
17
|
+
const DAY_MS = 86400000
|
|
18
|
+
/** 一段假期最长不会超过这个天数,防正则意外把超长区间展开 */
|
|
19
|
+
const MAX_RANGE_DAYS = 40
|
|
20
|
+
/** HTML 解析的体积上限(字符):真实通知页 100~300KB,2MB 已经非常宽松。
|
|
21
|
+
* 超过就只看前 2MB —— 宁可解析不全,也不能让 host 主线程卡住(见 holidayHtmlToText)。 */
|
|
22
|
+
const HOLIDAY_HTML_MAX = 2 * 1024 * 1024
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 线性切掉成对标签里的整段内容(`<script ...>...</script>` 这类)。
|
|
26
|
+
* 用 indexOf 前进而不是懒惰量词:找不到闭合标签时直接放弃剩余部分,
|
|
27
|
+
* 复杂度严格 O(n);`/<script[\s\S]*?<\/script>/gi` 在缺闭合时会从每个 `<` 往后扫到文末,
|
|
28
|
+
* 实测 40 万个未闭合 `<script>` 要 6 秒(卡死 host 事件循环)。
|
|
29
|
+
*/
|
|
30
|
+
function stripBlocks(text, tag) {
|
|
31
|
+
const open = '<' + tag
|
|
32
|
+
const close = '</' + tag
|
|
33
|
+
const lower = text.toLowerCase()
|
|
34
|
+
let out = ''
|
|
35
|
+
let at = 0
|
|
36
|
+
for (;;) {
|
|
37
|
+
const start = lower.indexOf(open, at)
|
|
38
|
+
if (start === -1) return out + text.slice(at)
|
|
39
|
+
out += text.slice(at, start)
|
|
40
|
+
const end = lower.indexOf(close, start)
|
|
41
|
+
if (end === -1) return out /* 没有闭合:整段丢弃,不再往后扫 */
|
|
42
|
+
const gt = text.indexOf('>', end)
|
|
43
|
+
if (gt === -1) return out
|
|
44
|
+
at = gt + 1
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** HTML → 纯文本:去脚本、样式与标签,解常见实体。
|
|
49
|
+
*
|
|
50
|
+
* 这段处理的是**外部网页**(国务院通知),内容不受我们控制,所以两处做了防御:
|
|
51
|
+
* ① 先按长度截断,避免超大文档把主线程占满;
|
|
52
|
+
* ② `<[^<>]+>` 而不是 `<[^>]+>` —— 后者不排除 `<`,大量孤立 `<` 时会反复跨越大段文本,
|
|
53
|
+
* 实测 20 万字符要 12 秒。 */
|
|
54
|
+
export function holidayHtmlToText(html) {
|
|
55
|
+
const raw = String(html === null || html === undefined ? '' : html).slice(0, HOLIDAY_HTML_MAX)
|
|
56
|
+
return stripBlocks(stripBlocks(raw, 'script'), 'style')
|
|
57
|
+
.replace(/<br\s*\/?>/gi, '\n')
|
|
58
|
+
.replace(/<\/p>/gi, '\n')
|
|
59
|
+
.replace(/<[^<>]+>/g, '')
|
|
60
|
+
.replace(/ /g, ' ')
|
|
61
|
+
.replace(/&/g, '&')
|
|
62
|
+
.replace(/</g, '<')
|
|
63
|
+
.replace(/>/g, '>')
|
|
64
|
+
.replace(/"/g, '"')
|
|
65
|
+
.replace(/[ \t\u3000]+/g, ' ')
|
|
66
|
+
.split('\n')
|
|
67
|
+
.map((line) => line.trim())
|
|
68
|
+
.filter((line) => line.length > 0)
|
|
69
|
+
.join('\n')
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const pad = (n) => (n < 10 ? '0' + String(n) : String(n))
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* 从通知正文里取出该年的放假日(只留周一至周五,升序)。
|
|
76
|
+
* @param {string} text 通知正文,纯文本或 HTML 都行(HTML 会自动剥标签)
|
|
77
|
+
* @param {number} year 通知对应的年份
|
|
78
|
+
* @returns {string[]} `YYYY-MM-DD` 数组
|
|
79
|
+
*/
|
|
80
|
+
export function parseHolidayNotice(text, year) {
|
|
81
|
+
const days = new Set()
|
|
82
|
+
const flat = String(text === null || text === undefined ? '' : text)
|
|
83
|
+
.slice(0, HOLIDAY_HTML_MAX)
|
|
84
|
+
/* `[^<>]` 而不是 `[^>]`:理由同 holidayHtmlToText —— 大量孤立 `<` 时会退化 */
|
|
85
|
+
.replace(/<[^<>]+>/g, ' ')
|
|
86
|
+
.replace(/\s+/g, ' ')
|
|
87
|
+
/* 只认含"放假"的句子;含"上班"的句子是调休上班日,不能算进空闲 */
|
|
88
|
+
flat.split(/[。;;\n]/).forEach((sentence) => {
|
|
89
|
+
if (sentence.indexOf('放假') === -1 || sentence.indexOf('上班') !== -1) return
|
|
90
|
+
NOTICE_DATE.lastIndex = 0
|
|
91
|
+
const hits = []
|
|
92
|
+
let hit = null
|
|
93
|
+
while ((hit = NOTICE_DATE.exec(sentence)) !== null) {
|
|
94
|
+
hits.push({
|
|
95
|
+
year: hit[1] === undefined ? null : Number(hit[1]),
|
|
96
|
+
month: hit[2] === undefined ? null : Number(hit[2]),
|
|
97
|
+
day: Number(hit[3]),
|
|
98
|
+
})
|
|
99
|
+
}
|
|
100
|
+
if (hits.length === 0) return
|
|
101
|
+
/* 句子里有"至"就是一段区间(取前两个日期当起止);否则每个日期各算一天 */
|
|
102
|
+
const ranges = sentence.indexOf('至') !== -1 && hits.length >= 2
|
|
103
|
+
? [[hits[0], hits[1]]]
|
|
104
|
+
: hits.map((one) => [one, one])
|
|
105
|
+
ranges.forEach((pair) => {
|
|
106
|
+
const from = pair[0]
|
|
107
|
+
const to = pair[1]
|
|
108
|
+
/* 区间终点常省略月份("4月4日至6日"),用起点的月份补上;孤立的"6日"没法定位,跳过 */
|
|
109
|
+
const startMonth = from.month
|
|
110
|
+
if (startMonth === null) return
|
|
111
|
+
const endMonth = to.month === null ? startMonth : to.month
|
|
112
|
+
const startYear = from.year === null ? year : from.year
|
|
113
|
+
let endYear = to.year === null ? startYear : to.year
|
|
114
|
+
/* 终点月份比起点小 = 跨年,例:12月31日至1月2日 */
|
|
115
|
+
if (to.year === null && endMonth < startMonth) endYear = startYear + 1
|
|
116
|
+
const last = Date.UTC(endYear, endMonth - 1, to.day)
|
|
117
|
+
let cursor = Date.UTC(startYear, startMonth - 1, from.day)
|
|
118
|
+
for (let i = 0; cursor <= last && i < MAX_RANGE_DAYS; i += 1, cursor += DAY_MS) {
|
|
119
|
+
const at = new Date(cursor)
|
|
120
|
+
if (at.getUTCFullYear() !== year) continue
|
|
121
|
+
const weekday = at.getUTCDay()
|
|
122
|
+
if (weekday === 0 || weekday === 6) continue
|
|
123
|
+
days.add(String(at.getUTCFullYear()) + '-' + pad(at.getUTCMonth() + 1) + '-' + pad(at.getUTCDate()))
|
|
124
|
+
}
|
|
125
|
+
})
|
|
126
|
+
})
|
|
127
|
+
return Array.from(days).sort()
|
|
128
|
+
}
|