@mzzsfy/dsh-stock-assistant 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.js CHANGED
@@ -1,34 +1,41 @@
1
- export const name = 'dsh-stock-assistant'
2
- export const inject = ['webServer', 'storageDomain', 'credentials']
3
- import { setupCommonTools, createChangeNotifier } from '@mzzsfy/dsh-common-tools/host'
4
- import { createApplication } from './application.mjs'
5
- import { registerRoutes } from './routes.mjs'
6
- import { serveVendor, VENDOR_PREFIX, vendorReadable } from './serve-vendor.mjs'
7
- export async function apply(ctx) {
8
- if (typeof ctx.webServer?.register !== 'function' || typeof ctx.webServer?.registerUpgrade !== 'function' || typeof ctx.storageDomain?.open !== 'function') {
9
- ctx.logger?.warn?.('股票工具已禁用:缺少webServer或storageDomain能力')
10
- return
11
- }
12
- let disposed = false, application, stopRoutes, unsubscribe, notifier, bus
13
- ctx.effect(() => () => {
14
- disposed = true; stopRoutes?.(); unsubscribe?.(); notifier?.dispose()
15
- return application?.close()
16
- }, 'stock-assistant lifecycle')
17
- try {
18
- // vendor 可读性预判定先于应用构建: vendorAvailable=false 随快照下发→client 直接降级数字详情
19
- let vendorAvailable = true
20
- try { vendorAvailable = vendorReadable() } catch { vendorAvailable = false }
21
- // 凭据服务由宿主提供; 接口不全时应用层会整体退回进程环境变量, 不因此拒绝启动
22
- application = await createApplication({ storageDomain: ctx.storageDomain, credentials: ctx.credentials ?? null, publish: () => notifier?.refresh(), vendorAvailable })
23
- if (disposed) { await application.close(); return }
24
- bus = setupCommonTools(ctx)
25
- notifier = createChangeNotifier(() => bus.publish({ type: 'invalidate', serverEpoch: application.snapshot().serverEpoch, snapshotSeq: application.snapshot().snapshotSeq }))
26
- unsubscribe = bus.subscribe(message => { if (message?.type === 'watch-demand') application.demand(message) })
27
- stopRoutes = registerRoutes(ctx.webServer, application)
28
- // 注册异常仅告警: client ensureLwc 失败同样走降级路径
29
- try { ctx.webServer.register({ kind: 'prefix', path: VENDOR_PREFIX, handler: serveVendor }) } catch (e) { ctx.logger?.warn?.('图表组件路由注册失败,详情将降级为数字详情') }
30
- } catch (e) {
31
- stopRoutes?.(); unsubscribe?.(); notifier?.dispose(); await application?.close()
32
- ctx.logger?.warn?.('股票工具未激活:独立数据域或依赖初始化失败')
33
- }
34
- }
1
+ export const name = 'dsh-stock-assistant'
2
+ export const inject = ['webServer', 'storageDomain', 'credentials']
3
+ import { setupCommonTools, createChangeNotifier } from '@mzzsfy/dsh-common-tools/host'
4
+ import { createApplication } from './application.mjs'
5
+ import { registerRoutes } from './routes.mjs'
6
+ import { serveVendor, VENDOR_PREFIX, vendorReadable } from './serve-vendor.mjs'
7
+ export async function apply(ctx) {
8
+ if (typeof ctx.webServer?.register !== 'function' || typeof ctx.webServer?.registerUpgrade !== 'function' || typeof ctx.storageDomain?.open !== 'function') {
9
+ ctx.logger?.warn?.('股票工具已禁用:缺少webServer或storageDomain能力')
10
+ return
11
+ }
12
+ let disposed = false, application, stopRoutes, unsubscribe, notifier, bus
13
+ ctx.effect(() => () => {
14
+ disposed = true; stopRoutes?.(); unsubscribe?.(); notifier?.dispose()
15
+ return application?.close()
16
+ }, 'stock-assistant lifecycle')
17
+ try {
18
+ // vendor 可读性预判定先于应用构建: vendorAvailable=false 随快照下发→client 直接降级数字详情
19
+ let vendorAvailable = true
20
+ try { vendorAvailable = vendorReadable() } catch { vendorAvailable = false }
21
+ // 凭据服务由宿主提供; 接口不全时应用层会整体退回进程环境变量, 不因此拒绝启动
22
+ application = await createApplication({ storageDomain: ctx.storageDomain, credentials: ctx.credentials ?? null, publish: () => notifier?.refresh(), vendorAvailable })
23
+ if (disposed) { await application.close(); return }
24
+ bus = setupCommonTools(ctx)
25
+ notifier = createChangeNotifier(() => bus.publish({ type: 'invalidate', serverEpoch: application.snapshot().serverEpoch, snapshotSeq: application.snapshot().snapshotSeq }))
26
+ unsubscribe = bus.subscribe(message => { if (message?.type === 'watch-demand') application.demand(message) })
27
+ stopRoutes = registerRoutes(ctx.webServer, application, ctx)
28
+ // 注册异常仅告警: client ensureLwc 失败同样走降级路径
29
+ try { ctx.webServer.register({ kind: 'prefix', path: VENDOR_PREFIX, handler: serveVendor }) } catch (e) { ctx.logger?.warn?.('图表组件路由注册失败,详情将降级为数字详情') }
30
+ } catch (e) {
31
+ // 失败原因先落日志再清理: 清理自身抛错不能盖掉原始原因。
32
+ // 数据域的 invalid-record 只有表/键有用, 记录值不能进日志。
33
+ const location = e?.detail?.table === undefined ? '' : `,记录 ${e.detail.table}/${e.detail.key}`
34
+ const reason = e && typeof e === 'object' ? `${e.code ? `${e.code}: ` : ''}${e.message || String(e)}${location}` : String(e)
35
+ ctx.logger?.warn?.(`股票工具未激活:独立数据域或依赖初始化失败 (${reason})`)
36
+ // 逐步清理: 任一步抛错都不能跳过关闭应用, 否则数据域占位留在宿主里, 重载只会一直 already-open
37
+ for (const step of [() => stopRoutes?.(), () => unsubscribe?.(), () => notifier?.dispose(), () => application?.close()]) {
38
+ try { await step() } catch (cleanupError) { ctx.logger?.warn?.(`股票工具清理失败: ${cleanupError?.message || cleanupError}`) }
39
+ }
40
+ }
41
+ }
@@ -1,4 +1,4 @@
1
- // K线缓存: 复用 storageDomain.cache 表壳, key 命名空间隔离, TTL 与 routingRevision 双失效
1
+ // K线缓存: 只存内存(TTL 与 routingRevision 双失效)。键里的冒号是命名空间, 不落盘就没有文件名约束
2
2
  const HOUR = 60 * 60 * 1000
3
3
  const DAY = 24 * HOUR
4
4
  // TTL 唯一事实源(design.md 数据结构节): trend 0=不缓存, 其余按周期
@@ -2,20 +2,32 @@
2
2
  // sessions 是该市场连续竞价的时段(市场本地时间), 用来判断报价此刻处在交易中/午休/休市;
3
3
  // 只描述周内时点, 法定节假日仍以数据本身(最后一根K线的日期)为准。
4
4
  export const MARKET_META = {
5
- XSHG: { currency: 'CNY', timezone: 'Asia/Shanghai', priceScale: 2, codePattern: /^\d{6}$/, verifiedByDefault: true, sessions: [['09:30', '11:30'], ['13:00', '15:00']] },
6
- XSHE: { currency: 'CNY', timezone: 'Asia/Shanghai', priceScale: 2, codePattern: /^\d{6}$/, verifiedByDefault: true, sessions: [['09:30', '11:30'], ['13:00', '15:00']] },
7
- XHKG: { currency: 'HKD', timezone: 'Asia/Hong_Kong', priceScale: 2, codePattern: /^\d{4,5}$/, verifiedByDefault: true, sessions: [['09:30', '12:00'], ['13:00', '16:00']] },
8
- XNAS: { currency: 'USD', timezone: 'America/New_York', priceScale: 2, codePattern: /^[A-Z]{1,5}$/, verifiedByDefault: true, sessions: [['09:30', '16:00']] },
9
- XNYS: { currency: 'USD', timezone: 'America/New_York', priceScale: 2, codePattern: /^[A-Z]{1,5}$/, verifiedByDefault: true, sessions: [['09:30', '16:00']] },
10
- XJPX: { currency: 'JPY', timezone: 'Asia/Tokyo', priceScale: 0, codePattern: /^\d{4}$/, verifiedByDefault: true, sessions: [['09:00', '11:30'], ['12:30', '15:30']] },
11
- XKRX: { currency: 'KRW', timezone: 'Asia/Seoul', priceScale: 0, codePattern: /^\d{6}$/, verifiedByDefault: true, sessions: [['09:00', '15:30']] },
12
- XLON: { currency: 'GBP', timezone: 'Europe/London', priceScale: 2, codePattern: /^[A-Z0-9.]{1,10}$/, verifiedByDefault: true, sessions: [['08:00', '16:30']] },
5
+ XSHG: { currency: 'CNY', timezone: 'Asia/Shanghai', priceScale: 2, codePattern: /^\d{6}$/, verifiedByDefault: true, sessions: [['09:30', '11:30'], ['13:00', '15:00']], tag: '沪A' },
6
+ XSHE: { currency: 'CNY', timezone: 'Asia/Shanghai', priceScale: 2, codePattern: /^\d{6}$/, verifiedByDefault: true, sessions: [['09:30', '11:30'], ['13:00', '15:00']], tag: '深A' },
7
+ XHKG: { currency: 'HKD', timezone: 'Asia/Hong_Kong', priceScale: 2, codePattern: /^\d{4,5}$/, verifiedByDefault: true, sessions: [['09:30', '12:00'], ['13:00', '16:00']], tag: '港股' },
8
+ XNAS: { currency: 'USD', timezone: 'America/New_York', priceScale: 2, codePattern: /^[A-Z]{1,5}$/, verifiedByDefault: true, sessions: [['09:30', '16:00']], tag: '纳斯达克' },
9
+ XNYS: { currency: 'USD', timezone: 'America/New_York', priceScale: 2, codePattern: /^[A-Z]{1,5}$/, verifiedByDefault: true, sessions: [['09:30', '16:00']], tag: '纽交所' },
10
+ XJPX: { currency: 'JPY', timezone: 'Asia/Tokyo', priceScale: 0, codePattern: /^\d{4}$/, verifiedByDefault: true, sessions: [['09:00', '11:30'], ['12:30', '15:30']], tag: '日本' },
11
+ XKRX: { currency: 'KRW', timezone: 'Asia/Seoul', priceScale: 0, codePattern: /^\d{6}$/, verifiedByDefault: true, sessions: [['09:00', '15:30']], tag: '韩国' },
12
+ XLON: { currency: 'GBP', timezone: 'Europe/London', priceScale: 2, codePattern: /^[A-Z0-9.]{1,10}$/, verifiedByDefault: true, sessions: [['08:00', '16:30']], tag: '英国' },
13
13
  }
14
+ // 交易时段判定按市场时区复用格式化器:逐笔报价判定时新建 formatter 主导成本
15
+ const SESSION_FORMATTERS = new Map()
16
+
17
+ function sessionFormatter(timeZone) {
18
+ let formatter = SESSION_FORMATTERS.get(timeZone)
19
+ if (formatter === undefined) {
20
+ formatter = new Intl.DateTimeFormat('en-US', { timeZone, hour12: false, weekday: 'short', hour: '2-digit', minute: '2-digit' })
21
+ SESSION_FORMATTERS.set(timeZone, formatter)
22
+ }
23
+ return formatter
24
+ }
25
+
14
26
  // 报价此刻落在市场交易日的哪个阶段; 周末恒为休市, 节假日不做推断(没有日历能力时会误判)
15
27
  export function sessionStateOf(exchange, nowMs) {
16
28
  const meta = MARKET_META[exchange]
17
29
  if (!meta?.sessions?.length) return 'unknown'
18
- const parts = new Intl.DateTimeFormat('en-US', { timeZone: meta.timezone, hour12: false, weekday: 'short', hour: '2-digit', minute: '2-digit' }).formatToParts(new Date(nowMs))
30
+ const parts = sessionFormatter(meta.timezone).formatToParts(new Date(nowMs))
19
31
  const pick = type => parts.find(part => part.type === type)?.value
20
32
  if (pick('weekday') === 'Sat' || pick('weekday') === 'Sun') return 'closed'
21
33
  const minutes = (Number(pick('hour')) % 24) * 60 + Number(pick('minute'))
@@ -0,0 +1,19 @@
1
+ // 可重建的派生数据只放内存: K 线、目录、日历丢了重拉即可, 落盘只会把控制记录一起拖大
2
+ const CACHE_LIMIT = 512
3
+
4
+ // 与数据域 table 同形的最小实现: catalog 只遍历 entries, kline-cache 只 get/put/delete
5
+ export function createMemoryCache({ limit = CACHE_LIMIT } = {}) {
6
+ const records = new Map()
7
+ return {
8
+ get: key => records.get(key),
9
+ async put(key, value) {
10
+ records.delete(key)
11
+ records.set(key, value)
12
+ // 超限先丢最久未写的: 缓存的命门是内存, 不是命中率
13
+ while (records.size > limit) records.delete(records.keys().next().value)
14
+ },
15
+ async delete(key) { return records.delete(key) },
16
+ entries: () => records.entries(),
17
+ get size() { return records.size },
18
+ }
19
+ }
@@ -199,6 +199,21 @@ export const eastmoney = {
199
199
  function num_or_null(v) { const n = parseFloat(v); return Number.isFinite(n) ? n : null }
200
200
 
201
201
 
202
+ // 时区格式化器按来源时区复用:分时逐行换算时,新建 formatter 的成本主导解析
203
+ const ZONE_FORMATTERS = new Map()
204
+
205
+ function zoneFormatter(timeZone) {
206
+ let formatter = ZONE_FORMATTERS.get(timeZone)
207
+ if (formatter === undefined) {
208
+ formatter = new Intl.DateTimeFormat('en-US', {
209
+ timeZone, hour12: false,
210
+ year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit',
211
+ })
212
+ ZONE_FORMATTERS.set(timeZone, formatter)
213
+ }
214
+ return formatter
215
+ }
216
+
202
217
  // 把指定时区的"YYYY-MM-DD HH:MM"换算成 Unix 秒, 时刻属于哪个时区由调用方给定;
203
218
  // 无时区元数据或格式不符时返回 null, 调用方回退自造时间轴
204
219
  function zonedUnixSeconds(stamp, timeZone) {
@@ -206,10 +221,7 @@ function zonedUnixSeconds(stamp, timeZone) {
206
221
  if (!match || !timeZone) return null
207
222
  const [, y, mo, d, hh, mm] = match.map(Number)
208
223
  const localAsUtc = Date.UTC(y, mo - 1, d, hh, mm)
209
- const parts = new Intl.DateTimeFormat('en-US', {
210
- timeZone, hour12: false,
211
- year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit',
212
- }).formatToParts(new Date(localAsUtc))
224
+ const parts = zoneFormatter(timeZone).formatToParts(new Date(localAsUtc))
213
225
  const rendered = Object.fromEntries(parts.map((part) => [part.type, part.value]))
214
226
  const asUtc = Date.UTC(Number(rendered.year), Number(rendered.month) - 1, Number(rendered.day),
215
227
  Number(rendered.hour) % 24, Number(rendered.minute), Number(rendered.second))
@@ -0,0 +1,29 @@
1
+ /**
2
+ * 宿主闸门复用。宿主把认证挂在它自己的 `/api` prefix 路由里,而 responder 选择是
3
+ * 「exact 先、最长 prefix 后」——插件注册的 `/api/<pkg>` 更长,先命中,`connection.admit`
4
+ * 从不执行。所以插件路由必须自己回问一次宿主闸门,否则无 cookie 的调用直接进业务面。
5
+ *
6
+ * 服务缺失(非 web 传输、旧宿主)时放行:与原行为一致,不新增自有认证层。
7
+ */
8
+
9
+ export function rejectUnadmitted(ctx, req, res) {
10
+ let rejection
11
+ try {
12
+ const connection = typeof ctx?.get === 'function' ? ctx.get('connection') : undefined
13
+ rejection = connection?.requestRejection?.(req)
14
+ } catch {
15
+ // 闸门自身异常不放行:宁可拒绝,不把故障当认证通过
16
+ rejection = 403
17
+ }
18
+ if (rejection === undefined) return false
19
+ res.writeHead(rejection, { 'content-type': 'text/plain; charset=utf-8' })
20
+ res.end(rejection === 401 ? 'unauthorized' : 'forbidden')
21
+ return true
22
+ }
23
+
24
+ export function withHostGate(ctx, handler) {
25
+ return async (req, res) => {
26
+ if (rejectUnadmitted(ctx, req, res)) return
27
+ await handler(req, res)
28
+ }
29
+ }
package/src/routes.mjs CHANGED
@@ -1,66 +1,68 @@
1
- import { z } from 'zod'
2
- import { StockError, fail } from './market-model.mjs'
3
- const PREFIX = '/api/stock-assistant'
4
- const operationSchema = z.object({ operationId: z.uuid(), expectedRevision: z.number().int().nonnegative() })
5
- async function body(req) {
6
- const chunks = []; let size = 0
7
- for await (const chunk of req) {
8
- size += chunk.length
9
- if (size > 64 * 1024) fail('BODY_TOO_LARGE', '请求内容过大', 413)
10
- chunks.push(chunk)
11
- }
12
- try { return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}') }
13
- catch { fail('INVALID_JSON', '请求必须为JSON') }
14
- }
15
- function json(res, status, value) {
16
- if (res.destroyed || res.writableEnded) return
17
- res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(value))
18
- }
19
- export function registerRoutes(webServer, app) {
20
- const handlers = {
21
- snapshot: ['GET', () => app.snapshot()],
22
- search: ['GET', async (input, signal) => await app.search(input.q || '', input.phase === 'remote' ? 'remote' : 'local', signal)],
23
- browse: ['GET', input => app.browse(input)],
24
- watchlist: ['POST', input => { operationSchema.parse(input); return app.watchlist(input) }],
25
- preferences: ['POST', input => { operationSchema.parse(input); return app.preferences({ ...input, payload: input.patch }) }],
26
- configuration: ['POST', input => { operationSchema.parse(input); return app.configuration({ ...input, payload: { providers: input.providers, routes: input.routes } }) }],
27
- 'provider-check': ['POST', (input, signal) => app.providerCheck(input, signal)],
28
- credential: ['POST', input => app.credential(input)],
29
- 'catalog-sync': ['POST', input => app.sync(input)],
30
- 'route-selection': ['POST', (input, signal) => app.routeSelection(input, signal)],
31
- refresh: ['POST', (input, signal) => app.refresh(input, signal)],
32
- kline: ['GET', (input, signal) => app.kline(input, signal)],
33
- }
34
- const controllers = new Set(), disposers = []
35
- let stopped = false
36
- try {
37
- for (const [name, [method, action]] of Object.entries(handlers)) disposers.push(webServer.register({ kind: 'exact', path: `${PREFIX}/${name}`, async handler(req, res) {
38
- if (stopped) return json(res, 503, { ok: false, error: { code: 'STOPPED', message: '工具已停止' } })
39
- if (req.method !== method) { res.setHeader('Allow', method); return json(res, 405, { ok: false, error: { code: 'METHOD_NOT_ALLOWED', message: '请求方法不支持' } }) }
40
- const controller = new AbortController(); controllers.add(controller)
41
- const onClose = () => { if (!res.writableEnded) controller.abort() }
42
- res.on('close', onClose)
43
- const timeout = name === 'provider-check' ? 60 * 1000 : name === 'catalog-sync' ? 120 * 1000 : 10 * 1000
44
- let timer
45
- try {
46
- const input = method === 'GET' ? Object.fromEntries(new URL(req.url, 'http://local').searchParams) : await body(req)
47
- if (method === 'POST' && (input === null || typeof input !== 'object' || Array.isArray(input))) fail('INVALID_REQUEST', '请求内容必须为JSON对象')
48
- if (method === 'POST' && req.headers.origin) {
49
- let same = false
50
- try { same = new URL(req.headers.origin).host === req.headers.host } catch {}
51
- if (!same) fail('CROSS_ORIGIN', '不接受跨源写请求', 403)
52
- }
53
- const data = await Promise.race([
54
- Promise.resolve(action(input, controller.signal)),
55
- new Promise((_, reject) => { timer = setTimeout(() => { controller.abort(); reject(new StockError('TIMEOUT', '操作超时,请稍后重试', 504)) }, timeout) }),
56
- new Promise((_, reject) => controller.signal.addEventListener('abort', () => reject(new StockError('CANCELLED', '操作已取消', stopped ? 503 : 504)), { once: true })),
57
- ])
58
- json(res, 200, { ok: true, data })
59
- } catch (e) {
60
- const error = e instanceof StockError ? e : new StockError('INVALID_REQUEST', e instanceof z.ZodError ? '请求参数格式错误' : '股票工具请求失败', e instanceof z.ZodError ? 400 : 500)
61
- json(res, error.status, { ok: false, error: { code: error.code, message: error.message, retryable: error.retryable, retryAfterMs: error.retryAfterMs }, ...(error.revision === undefined ? {} : { revision: error.revision }), ...(e.snapshot ? { snapshot: e.snapshot } : {}) })
62
- } finally { clearTimeout(timer); controllers.delete(controller); res.removeListener('close', onClose) }
63
- } }))
64
- } catch (e) { for (const dispose of disposers.reverse()) dispose(); throw e }
65
- return () => { stopped = true; for (const dispose of disposers.reverse()) dispose(); for (const c of controllers) c.abort(); controllers.clear() }
66
- }
1
+ import { z } from 'zod'
2
+ import { StockError, fail } from './market-model.mjs'
3
+ import { rejectUnadmitted } from './route-gate.mjs'
4
+ const PREFIX = '/api/stock-assistant'
5
+ const operationSchema = z.object({ operationId: z.uuid(), expectedRevision: z.number().int().nonnegative() })
6
+ async function body(req) {
7
+ const chunks = []; let size = 0
8
+ for await (const chunk of req) {
9
+ size += chunk.length
10
+ if (size > 64 * 1024) fail('BODY_TOO_LARGE', '请求内容过大', 413)
11
+ chunks.push(chunk)
12
+ }
13
+ try { return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}') }
14
+ catch { fail('INVALID_JSON', '请求必须为JSON') }
15
+ }
16
+ function json(res, status, value) {
17
+ if (res.destroyed || res.writableEnded) return
18
+ res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(value))
19
+ }
20
+ export function registerRoutes(webServer, app, ctx) {
21
+ const handlers = {
22
+ snapshot: ['GET', () => app.snapshot()],
23
+ search: ['GET', async (input, signal) => await app.search(input.q || '', input.phase === 'remote' ? 'remote' : 'local', signal)],
24
+ browse: ['GET', input => app.browse(input)],
25
+ watchlist: ['POST', input => { operationSchema.parse(input); return app.watchlist(input) }],
26
+ preferences: ['POST', input => { operationSchema.parse(input); return app.preferences({ ...input, payload: input.patch }) }],
27
+ configuration: ['POST', input => { operationSchema.parse(input); return app.configuration({ ...input, payload: { providers: input.providers, routes: input.routes } }) }],
28
+ 'provider-check': ['POST', (input, signal) => app.providerCheck(input, signal)],
29
+ credential: ['POST', input => app.credential(input)],
30
+ 'catalog-sync': ['POST', input => app.sync(input)],
31
+ 'route-selection': ['POST', (input, signal) => app.routeSelection(input, signal)],
32
+ refresh: ['POST', (input, signal) => app.refresh(input, signal)],
33
+ kline: ['GET', (input, signal) => app.kline(input, signal)],
34
+ }
35
+ const controllers = new Set(), disposers = []
36
+ let stopped = false
37
+ try {
38
+ for (const [name, [method, action]] of Object.entries(handlers)) disposers.push(webServer.register({ kind: 'exact', path: `${PREFIX}/${name}`, async handler(req, res) {
39
+ if (rejectUnadmitted(ctx, req, res)) return
40
+ if (stopped) return json(res, 503, { ok: false, error: { code: 'STOPPED', message: '工具已停止' } })
41
+ if (req.method !== method) { res.setHeader('Allow', method); return json(res, 405, { ok: false, error: { code: 'METHOD_NOT_ALLOWED', message: '请求方法不支持' } }) }
42
+ const controller = new AbortController(); controllers.add(controller)
43
+ const onClose = () => { if (!res.writableEnded) controller.abort() }
44
+ res.on('close', onClose)
45
+ const timeout = name === 'provider-check' ? 60 * 1000 : name === 'catalog-sync' ? 120 * 1000 : 10 * 1000
46
+ let timer
47
+ try {
48
+ const input = method === 'GET' ? Object.fromEntries(new URL(req.url, 'http://local').searchParams) : await body(req)
49
+ if (method === 'POST' && (input === null || typeof input !== 'object' || Array.isArray(input))) fail('INVALID_REQUEST', '请求内容必须为JSON对象')
50
+ if (method === 'POST' && req.headers.origin) {
51
+ let same = false
52
+ try { same = new URL(req.headers.origin).host === req.headers.host } catch {}
53
+ if (!same) fail('CROSS_ORIGIN', '不接受跨源写请求', 403)
54
+ }
55
+ const data = await Promise.race([
56
+ Promise.resolve(action(input, controller.signal)),
57
+ new Promise((_, reject) => { timer = setTimeout(() => { controller.abort(); reject(new StockError('TIMEOUT', '操作超时,请稍后重试', 504)) }, timeout) }),
58
+ new Promise((_, reject) => controller.signal.addEventListener('abort', () => reject(new StockError('CANCELLED', '操作已取消', stopped ? 503 : 504)), { once: true })),
59
+ ])
60
+ json(res, 200, { ok: true, data })
61
+ } catch (e) {
62
+ const error = e instanceof StockError ? e : new StockError('INVALID_REQUEST', e instanceof z.ZodError ? '请求参数格式错误' : '股票工具请求失败', e instanceof z.ZodError ? 400 : 500)
63
+ json(res, error.status, { ok: false, error: { code: error.code, message: error.message, retryable: error.retryable, retryAfterMs: error.retryAfterMs }, ...(error.revision === undefined ? {} : { revision: error.revision }), ...(e.snapshot ? { snapshot: e.snapshot } : {}) })
64
+ } finally { clearTimeout(timer); controllers.delete(controller); res.removeListener('close', onClose) }
65
+ } }))
66
+ } catch (e) { for (const dispose of disposers.reverse()) dispose(); throw e }
67
+ return () => { stopped = true; for (const dispose of disposers.reverse()) dispose(); for (const c of controllers) c.abort(); controllers.clear() }
68
+ }
package/src/schemas.mjs CHANGED
@@ -10,6 +10,18 @@ export const marksSchema = z.array(markSchema).max(12).default([]).superRefine((
10
10
  if (new Set(list.map(mark => `${mark.kind}:${mark.price}`)).size !== list.length) ctx.addIssue({ code: 'custom', message: '同类型的价格不能重复' })
11
11
  })
12
12
  const rate = z.number().int().positive().max(100000)
13
+ // 每票可同时归属的分组上限: 标签是视图视角, 超过这个数量就该换一种组织方式
14
+ export const MAX_TAGS = 8
15
+ // 标签名即分组身份: 允许 1-12 字, 不允许首尾空白与控制字符(它们会让同名标签在界面上看起来一样)。
16
+ // C0/C1/DEL 之外还挡零宽与双向控制符: 它们不占宽度却能让两个不同的标签在 chips 与 tab 上完全同形
17
+ const TAG_CHARS_SOURCE = '\\u0000-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u202a-\\u202e'
18
+ const TAG_CHARS = new RegExp(`[${TAG_CHARS_SOURCE}]`), TAG_CHARS_ALL = new RegExp(`[${TAG_CHARS_SOURCE}]`, 'g')
19
+ // 旧版校验只挡 C0, 存量 group 里可能存在零宽/双向字符: 迁移必须先剥掉再判定, 否则一条旧记录会让插件整体不激活
20
+ export const stripTagChars = value => value.replace(TAG_CHARS_ALL, '')
21
+ export const tagName = z.string().refine(s => {
22
+ const trimmed = s.trim()
23
+ return trimmed !== '' && trimmed === s && [...trimmed].length <= 12 && !TAG_CHARS.test(trimmed)
24
+ }, '标签名需为 1-12 字, 不含首尾空白与控制字符')
13
25
  export const capability = z.enum(['quotes', 'catalog', 'search', 'calendar', 'kline'])
14
26
  export const marketSchema = z.enum(Object.keys(MARKET_META))
15
27
  export const providerSchema = z.strictObject({
@@ -33,7 +45,10 @@ export const klineQuerySchema = z.strictObject({
33
45
  })
34
46
  // 路由上限: 八市场×(quotes/catalog/search/calendar/kline) 全开 40 条封顶
35
47
  const configSchema = z.strictObject({ providers: z.array(providerSchema).max(8), routes: z.array(routeSchema).max(40) })
36
- export const preferencesSchema = z.strictObject({ refreshSeconds: z.union([z.literal(15), z.literal(30), z.literal(60)]), colorMode: z.enum(['red-up', 'green-up']) })
48
+ // 悬浮盯盘刷新间隔独立于列表: 窗口只要快慢, 与列表的 15/30/60 不共享档位
49
+ export const FLOAT_REFRESH_SECONDS = [3, 5, 10, 15, 30]
50
+ export const DEFAULT_FLOAT_REFRESH_SECONDS = 10
51
+ export const preferencesSchema = z.strictObject({ refreshSeconds: z.union([z.literal(15), z.literal(30), z.literal(60)]), colorMode: z.enum(['red-up', 'green-up']), floatRefreshSeconds: z.union(FLOAT_REFRESH_SECONDS.map(n => z.literal(n))).default(DEFAULT_FLOAT_REFRESH_SECONDS) })
37
52
  export const securitySchema = z.object({ id: z.string(), exchange: marketSchema, code: z.string(), officialName: z.string().min(1).max(100), instrument: z.literal('equity'), currency: z.string(), timezone: z.string(), priceScale: z.number().int(), listingStatus: z.string() }).superRefine((s, ctx) => {
38
53
  const meta = MARKET_META[s.exchange]
39
54
  if (!meta || !meta.codePattern.test(s.code) || s.id !== `${s.exchange}:equity:${s.code}`) { ctx.addIssue({ code: 'custom', message: '证券身份不一致' }); return }
@@ -62,14 +77,54 @@ export function parseConfiguration(value) {
62
77
  }
63
78
  return config
64
79
  }
65
- export const controlSchema = z.object({ revision: z.number().int().nonnegative(), routingRevision: z.number().int().nonnegative(), watchlist: z.object({ order: z.array(z.string()).max(100), items: z.record(z.string(), securitySchema.safeExtend({ alias: z.string(), pinned: z.boolean(), marks: marksSchema, group: z.string().refine(s => [...s.trim()].length <= 12 && !/[\u0000-\u001f]/.test(s)).default('') })) }), preferences: preferencesSchema, providers: z.array(providerSchema), routes: z.array(routeSchema), operations: z.array(z.object({ id: z.uuid(), hash: z.string(), at: z.number(), result: z.object({ revision: z.number() }).passthrough(), action: z.string(), payload: z.unknown() })).max(256) }).superRefine((control, ctx) => {
80
+ export const controlSchema = z.object({ revision: z.number().int().nonnegative(), routingRevision: z.number().int().nonnegative(), watchlist: z.object({ order: z.array(z.string()).max(100), items: z.record(z.string(), securitySchema.safeExtend({ alias: z.string(), pinned: z.boolean(), marks: marksSchema, tags: z.array(tagName).max(MAX_TAGS).refine(list => new Set(list).size === list.length, '标签不能重复').default([]) })) }), preferences: preferencesSchema, providers: z.array(providerSchema), routes: z.array(routeSchema), operations: z.array(z.object({ id: z.uuid(), hash: z.string(), at: z.number(), result: z.object({ revision: z.number() }).passthrough(), action: z.string(), payload: z.unknown() })).max(256) }).superRefine((control, ctx) => {
66
81
  const w = control.watchlist
67
82
  if (new Set(w.order).size !== w.order.length || w.order.length !== Object.keys(w.items).length || w.order.some(id => w.items[id]?.id !== id)) ctx.addIssue({ code: 'custom', message: '自选序列与证券不一致' })
68
83
  let unpinned = false
69
84
  for (const id of w.order) { if (!w.items[id]?.pinned) unpinned = true; else if (unpinned) ctx.addIssue({ code: 'custom', message: '置顶序列混乱' }) }
70
85
  try { parseConfiguration({ providers: control.providers, routes: control.routes }) } catch { ctx.addIssue({ code: 'custom', message: '来源配置不一致' }) }
71
86
  })
72
- export const domainSpec = { name: 'stock_assistant', version: 1, layout: 'single', invalidRecords: 'backup-and-skip', tables: { control: { valueSchema: controlSchema }, cache: { valueSchema: z.object({ kind: z.string(), source: z.string(), fetchedAt: z.number(), payload: z.unknown() }) } } }
87
+ // 存量记录归一: 数据源实例的凭据字段曾叫 credentialEnv(本来也只存引用名), 更名 credentialRef 后
88
+ // 旧记录要能在数据域打开时通过校验并就地改成新字段 —— 这次校验发生在 storageDomain.open,
89
+ // 早于插件应用层的任何迁移代码, 迁移写在这一层之外等于永远跑不到。
90
+ // 新旧字段并存时以新字段为准; 非对象条目原样交给 schema 去拒绝, 不在这里抛
91
+ const normalizeProvider = provider => {
92
+ if (!provider || typeof provider !== 'object' || !('credentialEnv' in provider)) return provider
93
+ const { credentialEnv, ...rest } = provider
94
+ return { ...rest, credentialRef: 'credentialRef' in rest ? rest.credentialRef : credentialEnv ?? null }
95
+ }
96
+ const normalizeCredentialField = root => {
97
+ if (!root || typeof root !== 'object' || !Array.isArray(root.providers)) return root
98
+ if (!root.providers.some(p => p && typeof p === 'object' && 'credentialEnv' in p)) return root
99
+ return { ...root, providers: root.providers.map(normalizeProvider) }
100
+ }
101
+ // 分组从单值 group 改为多标签 tags。与凭据改名同理, 归一必须在数据域 schema 上做,
102
+ // 否则存量记录通不过 storageDomain.open 的校验, 插件整体起不来。非字符串 group 也搬进 tags,
103
+ // 交给 tagName 校验报错, 不静默丢弃。
104
+ // 空分组说明用户没手工组织过: 按市场回填默认标签, 否则升级后所有存量票都落进未分组。
105
+ // 旧写路径会 trim, 但手工或外部写入可能带空白; 不 trim 会让一条旧记录直接锁死整个插件。
106
+ // tags 已存在时无论形态都原样保留: 让 schema 报错, 而不是用 group 静默覆盖用户标签。
107
+ const normalizeWatchlistTags = root => {
108
+ const items = root?.watchlist?.items
109
+ if (!items || typeof items !== 'object' || Array.isArray(items)) return root
110
+ if (!Object.values(items).some(item => item && typeof item === 'object' && 'group' in item)) return root
111
+ const next = Object.fromEntries(Object.entries(items).map(([id, item]) => {
112
+ if (!item || typeof item !== 'object' || !('group' in item)) return [id, item]
113
+ const { group, ...rest } = item
114
+ if ('tags' in rest) return [id, rest]
115
+ const marketTag = MARKET_META[rest.exchange]?.tag
116
+ if (typeof group !== 'string') return [id, { ...rest, tags: [group] }]
117
+ const text = stripTagChars(group).trim()
118
+ return [id, { ...rest, tags: text ? [text] : marketTag ? [marketTag] : [] }]
119
+ }))
120
+ return { ...root, watchlist: { ...root.watchlist, items: next } }
121
+ }
122
+ const normalizeStoredControl = root => normalizeWatchlistTags(normalizeCredentialField(root))
123
+ export const storedControlSchema = z.preprocess(normalizeStoredControl, controlSchema)
124
+ // 存储只有一条记录: 自选与路由。K 线/目录/日历都是可重建的派生数据, 只放内存 ——
125
+ // 把它们塞进同一个文件曾把文件撑到 3.3 MB, 每次改自选都要整体重写, 写坏一次全没。
126
+ // 旧文件同名同版本, 打开时只取声明过的 control 表, 缓存表被忽略, 下次写入自然缩到十几 KB。
127
+ export const domainSpec = { name: 'stock_assistant', version: 1, layout: 'single', tables: { control: { valueSchema: storedControlSchema } } }
73
128
  // 推荐配置:四个免凭据源,东财做八市场主力,其余按实测最强能力分派备份——公开源无SLA,能覆盖的市场都串上备源。
74
129
  export const defaultConfig = () => {
75
130
  const budget = (requestsPerMinute, capabilityLimits = {}) => ({ requestsPerMinute, dailyRequestLimit: null, billingUnit: 'request', symbolCreditsPerMinute: null, capabilityLimits })
@@ -95,4 +150,4 @@ export const defaultConfig = () => {
95
150
  ])
96
151
  return { providers, routes }
97
152
  }
98
- export const initialControl = () => ({ revision: 0, routingRevision: 0, watchlist: { order: [], items: {} }, preferences: { refreshSeconds: 15, colorMode: 'red-up' }, ...defaultConfig(), operations: [] })
153
+ export const initialControl = () => ({ revision: 0, routingRevision: 0, watchlist: { order: [], items: {} }, preferences: { refreshSeconds: 15, colorMode: 'red-up', floatRefreshSeconds: DEFAULT_FLOAT_REFRESH_SECONDS }, ...defaultConfig(), operations: [] })
package/src/service.mjs CHANGED
@@ -1,17 +1,26 @@
1
1
  import { z } from 'zod'
2
- import { fail, parseSecurityId } from './market-model.mjs'
3
- import { securitySchema, marksSchema } from './schemas.mjs'
2
+ import { fail, parseSecurityId, MARKET_META } from './market-model.mjs'
3
+ import { securitySchema, marksSchema, tagName, MAX_TAGS } from './schemas.mjs'
4
4
  // 自选身份八市场: parseSecurityId 是唯一事实源(市场/代码形态随 MARKET_META)
5
5
  const securityId = z.string().refine(v => { try { parseSecurityId(v); return true } catch { return false } })
6
+ // 标签输入先归一(trim/去空/去重), 再按存储规则校验: 空白条目等于没填, 不因输入框残留空格就拒绝整次操作
7
+ const tagValue = z.string().transform(value => value.trim()).refine(value => tagName.safeParse(value).success, '标签名需为 1-12 字, 不含控制字符')
8
+ const tagList = z.array(z.string()).transform(list => [...new Set(list.map(value => value.trim()).filter(Boolean))]).superRefine((list, ctx) => {
9
+ if (list.length > MAX_TAGS) ctx.addIssue({ code: 'custom', message: `每只最多 ${MAX_TAGS} 个标签` })
10
+ for (const tag of list) {
11
+ const result = tagName.safeParse(tag)
12
+ if (!result.success) ctx.addIssue({ code: 'custom', message: result.error.issues[0].message })
13
+ }
14
+ })
6
15
  const payloads = {
7
16
  add: z.strictObject({ securityId }), remove: z.strictObject({ securityId }),
8
17
  restore: z.strictObject({ removeOperationId: z.uuid() }),
9
18
  alias: z.strictObject({ securityId, alias: z.string().refine(s => [...s].length <= 30) }),
10
19
  marks: z.strictObject({ securityId, marks: marksSchema }),
11
- // 组名进来就是用户输入, 校验在入口做: 只靠 state 写入后的不变式兜底会把它报成 500 内部错误
12
- group: z.strictObject({ securityIds: z.array(securityId).min(1), group: z.string().refine(s => { const t = s.trim(); return [...t].length <= 12 && !/[\u0000-\u001f]/.test(t) }, '分组名最长 12 字且不能含控制字符') }),
13
- groupRename: z.strictObject({ from: z.string().min(1), to: z.string().refine(s => { const t = s.trim(); return t.length > 0 && [...t].length <= 12 && !/[\u0000-\u001f]/.test(t) }, '分组名最长 12 字且不能含控制字符') }),
14
- groupRemove: z.strictObject({ group: z.string().min(1) }),
20
+ // 标签整组替换: 与 marks 同一语义, 协议面只有一个操作, 不出现半更新的中间态
21
+ tags: z.strictObject({ securityId, tags: tagList }),
22
+ tagRename: z.strictObject({ from: tagValue, to: tagValue }),
23
+ tagRemove: z.strictObject({ tag: tagValue }),
15
24
  pin: z.strictObject({ securityId, pinned: z.boolean() }),
16
25
  move: z.strictObject({ securityId, beforeId: securityId.nullable() }),
17
26
  // 拖拽排序: 提交完整显示序, 前端算好顺序一次落库, 避免逐行 move 的中间态
@@ -40,7 +49,12 @@ export function createWatchlistService(state, resolveSecurity, now = Date.now) {
40
49
  if (w.order.length >= 100) fail('LIMIT_REACHED', '最多添加100只自选', 422)
41
50
  const security = resolveSecurity(p.securityId)
42
51
  if (!security || !securitySchema.safeParse(security).success) fail('CANDIDATE_EXPIRED', '候选已过期,请重新搜索', 409)
43
- w.items[p.securityId] = { ...security, alias: '', pinned: false, marks: [], group: '' }; w.order.push(p.securityId)
52
+ // 市场分组默认开: 该市场还没有自选时按市场归组; 该市场已无票持市场标签(解散/改名/逐票移除),
53
+ // 不再把新票塞回去; 手动加回市场标签即恢复
54
+ const marketTag = MARKET_META[security.exchange].tag
55
+ const marketPeers = w.order.filter(id => w.items[id].exchange === security.exchange)
56
+ const keepMarketTag = !marketPeers.length || marketPeers.some(id => w.items[id].tags.includes(marketTag))
57
+ w.items[p.securityId] = { ...security, alias: '', pinned: false, marks: [], tags: keepMarketTag ? [marketTag] : [] }; w.order.push(p.securityId)
44
58
  } else if (operation.action === 'restore') {
45
59
  const deleted = control.operations.find(o => o.id === p.removeOperationId && o.action === 'remove')
46
60
  const restore = deleted?.result.restore
@@ -53,9 +67,21 @@ export function createWatchlistService(state, resolveSecurity, now = Date.now) {
53
67
  const after = w.order.indexOf(restore.previousId) + 1; w.order.splice(after, 0, restored.id)
54
68
  } else if (restore.nextId && same(restore.nextId)) insert(restored.id, restore.nextId)
55
69
  else insert(restored.id, restored.pinned ? regionEnd(true) : null)
56
- } else if (operation.action === 'group') { for (const id of p.securityIds) { if (!w.items[id]) fail('NOT_FOUND', '证券已被移除', 404); w.items[id].group = p.group.trim() } }
57
- else if (operation.action === 'groupRename') { if (!w.order.some(id => w.items[id].group === p.from)) fail('NOT_FOUND', '分组不存在', 404); for (const id of w.order) if (w.items[id].group === p.from) w.items[id].group = p.to.trim() }
58
- else if (operation.action === 'groupRemove') { if (!w.order.some(id => w.items[id].group === p.group)) fail('NOT_FOUND', '分组不存在', 404); for (const id of w.order) if (w.items[id].group === p.group) w.items[id].group = '' }
70
+ } else if (operation.action === 'tags') {
71
+ if (!w.items[p.securityId]) fail('NOT_FOUND', '证券已被移除', 404)
72
+ w.items[p.securityId].tags = p.tags
73
+ }
74
+ // 标签是名称身份: 重命名即批量替换, 目标名已存在时合并去重而不是制造重复
75
+ else if (operation.action === 'tagRename') {
76
+ const holders = w.order.filter(id => w.items[id].tags.includes(p.from))
77
+ if (!holders.length) fail('NOT_FOUND', '标签不存在', 404)
78
+ for (const id of holders) w.items[id].tags = [...new Set(w.items[id].tags.map(tag => tag === p.from ? p.to : tag))]
79
+ }
80
+ else if (operation.action === 'tagRemove') {
81
+ const holders = w.order.filter(id => w.items[id].tags.includes(p.tag))
82
+ if (!holders.length) fail('NOT_FOUND', '标签不存在', 404)
83
+ for (const id of holders) w.items[id].tags = w.items[id].tags.filter(tag => tag !== p.tag)
84
+ }
59
85
  else {
60
86
  if (!item) fail('NOT_FOUND', '证券已被移除', 404)
61
87
  if (operation.action === 'remove') {
package/src/state.mjs CHANGED
@@ -1,27 +1,24 @@
1
1
  import { createHash } from 'node:crypto'
2
2
  import { domainSpec, initialControl, controlSchema } from './schemas.mjs'
3
+ import { createMemoryCache } from './memory-cache.mjs'
3
4
  import { fail } from './market-model.mjs'
4
5
  const DAY = 24 * 60 * 60 * 1000
6
+ // 目录/日历条数很少, 给独立小池: 与 K 线共用一个淘汰池时会被几十节 K 线挤掉, 挤掉后又要重新拉目录
7
+ const CATALOG_CACHE_LIMIT = 64, KLINE_CACHE_LIMIT = 512
5
8
  export const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex')
6
9
  export async function openState(storageDomain, changed = () => {}, now = Date.now) {
10
+ // 只有控制记录落盘; 派生数据放内存, 所以打开失败只可能是这一个文件
7
11
  const domain = await storageDomain.open(domainSpec)
8
- const table = domain.table('control'), cache = domain.table('cache')
9
- // 存量数据: 数据源实例的凭据字段曾叫 credentialEnv, 现在交给宿主的凭据服务保管, 更名 credentialRef。
10
- // 老数据里那一栏本来就只存引用名(值是环境变量里的), 改名即可, 不改语义。
11
- const renameCredentialField = root => {
12
- if (!root || !Array.isArray(root.providers)) return root
13
- if (!root.providers.some(p => p && 'credentialEnv' in p)) return root
14
- return { ...root, providers: root.providers.map(({ credentialEnv, ...rest }) => ({ ...rest, credentialRef: credentialEnv ?? null })) }
15
- }
12
+ const table = domain.table('control')
16
13
  try {
14
+ // 存量字段改名的归一发生在数据域的 valueSchema 上(storageDomain.open 阶段), 这里读到的已是新格式
17
15
  if (!table.get('root')) await table.put('root', initialControl())
18
- else if (renameCredentialField(table.get('root')) !== table.get('root')) await table.put('root', renameCredentialField(table.get('root')))
19
- controlSchema.parse(table.get('root'))
20
- } catch (e) { await domain.close(); throw e }
16
+ } catch (e) { await Promise.allSettled([domain.close()]); throw e }
17
+ const cache = createMemoryCache({ limit: CATALOG_CACHE_LIMIT }), klineCache = createMemoryCache({ limit: KLINE_CACHE_LIMIT })
21
18
  let tail = Promise.resolve(), stopped = false
22
19
  return {
23
20
  get: () => structuredClone(table.get('root')),
24
- cache,
21
+ cache, klineCache,
25
22
  replay(operation) {
26
23
  const prior = table.get('root').operations.find(o => o.id === operation.operationId && now() - o.at < DAY)
27
24
  if (!prior) return null
@@ -59,6 +56,10 @@ export async function openState(storageDomain, changed = () => {}, now = Date.no
59
56
  }
60
57
  const job = tail.then(run); tail = job.catch(() => {}); return job
61
58
  },
62
- async close() { stopped = true; await tail; await domain.close() },
59
+ async close() {
60
+ stopped = true
61
+ await tail
62
+ await domain.close()
63
+ },
63
64
  }
64
65
  }