@t2b2c/agent-stock-sdk 0.1.0 → 0.1.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.
package/README.md CHANGED
@@ -121,9 +121,12 @@ pnpm --filter @t2b2c/agent-stock-sdk example:market-kline-shot
121
121
  pnpm --filter @t2b2c/agent-stock-sdk example:market-kline-shot -- \
122
122
  --symbols=cyb,sse,nasdaq,gold,us:AAPL \
123
123
  --years=2.5 \
124
+ --stock-app=http://localhost:9311 \
124
125
  --out=./tmp/market-kline-exports
125
126
  ```
126
127
 
128
+ > 市场截图默认 `layout=per-symbol`,并用 CDP 固定视口 + 裁剪卡片(不再依赖 WebBridge `screenshot`+selector,避免错位/超宽压扁)。
129
+
127
130
  ### 代码调用
128
131
 
129
132
  ```ts
@@ -1 +1 @@
1
- {"version":3,"file":"capture-kline-screenshots.d.ts","sourceRoot":"","sources":["../../src/kline/capture-kline-screenshots.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EACV,8BAA8B,EAC9B,6BAA6B,EAG9B,MAAM,8BAA8B,CAAA;AAuFrC;;;;;;GAMG;AACH,wBAAsB,uBAAuB,CAC3C,OAAO,EAAE,8BAA8B,GACtC,OAAO,CAAC,6BAA6B,CAAC,CA+FxC"}
1
+ {"version":3,"file":"capture-kline-screenshots.d.ts","sourceRoot":"","sources":["../../src/kline/capture-kline-screenshots.ts"],"names":[],"mappings":"AAoBA,OAAO,KAAK,EACV,8BAA8B,EAC9B,6BAA6B,EAG9B,MAAM,8BAA8B,CAAA;AA8DrC;;;;;;GAMG;AACH,wBAAsB,uBAAuB,CAC3C,OAAO,EAAE,8BAA8B,GACtC,OAAO,CAAC,6BAA6B,CAAC,CA8FxC"}
@@ -3,6 +3,7 @@ import { join } from 'node:path';
3
3
  import { tmpdir } from 'node:os';
4
4
  import { DEFAULT_STOCK_APP_BASE_URL, DEFAULT_WEBBRIDGE_BASE_URL, } from '../config.js';
5
5
  import { buildKlineListUrl, DEFAULT_KLINE_SCREENSHOT_YEARS, estimateVisibleBarsForYears, normalizeStockCodes, } from './kline-list-url.js';
6
+ import { captureSelectorPngViaCdp, prepareScreenshotViewport, sleep, unwrapEvaluateValue, } from './screenshot-helpers.js';
6
7
  import { createWebbridgeClient, WebbridgeError } from './webbridge-client.js';
7
8
  const READY_EVAL_CODE = `(() => {
8
9
  const cards = document.querySelectorAll('[data-kline-card]');
@@ -17,19 +18,6 @@ const READY_EVAL_CODE = `(() => {
17
18
  bars: list?.getAttribute('data-kline-visible-bars') ?? null,
18
19
  });
19
20
  })()`;
20
- function sleep(ms) {
21
- return new Promise((resolve) => setTimeout(resolve, ms));
22
- }
23
- function unwrapEvaluateValue(data) {
24
- if (typeof data === 'string')
25
- return data;
26
- if (data && typeof data === 'object' && 'value' in data) {
27
- const value = data.value;
28
- if (typeof value === 'string')
29
- return value;
30
- }
31
- throw new WebbridgeError('Unexpected evaluate payload from WebBridge', 'bad_evaluate');
32
- }
33
21
  function parseReadyProbe(data) {
34
22
  const raw = unwrapEvaluateValue(data);
35
23
  const parsed = JSON.parse(raw);
@@ -42,17 +30,6 @@ function parseReadyProbe(data) {
42
30
  bars: parsed.bars ?? null,
43
31
  };
44
32
  }
45
- function unwrapScreenshot(data) {
46
- if (!data || typeof data !== 'object') {
47
- throw new WebbridgeError('Unexpected screenshot payload from WebBridge', 'bad_screenshot');
48
- }
49
- const path = String(data.path ?? '');
50
- const sizeBytes = Number(data.sizeBytes ?? 0);
51
- if (!path) {
52
- throw new WebbridgeError('WebBridge screenshot missing path', 'bad_screenshot');
53
- }
54
- return { path, sizeBytes };
55
- }
56
33
  async function waitForCardsReady(command, codes, timeoutMs, pollIntervalMs) {
57
34
  const expected = new Set(codes);
58
35
  const deadline = Date.now() + timeoutMs;
@@ -88,6 +65,7 @@ export async function captureKlineScreenshots(options) {
88
65
  `kline-shot-${Date.now().toString(36)}`;
89
66
  const timeoutMs = options.timeoutMs ?? 60_000;
90
67
  const pollIntervalMs = options.pollIntervalMs ?? 1_000;
68
+ const settleMs = options.settleMs ?? 900;
91
69
  const closeTab = options.closeTab !== false;
92
70
  const filePrefix = options.filePrefix?.trim() || 'kline';
93
71
  const outputDir = options.outputDir?.trim() ||
@@ -126,15 +104,15 @@ export async function captureKlineScreenshots(options) {
126
104
  group_title: 'K线列表截图',
127
105
  });
128
106
  tabOpened = true;
107
+ await prepareScreenshotViewport(command);
129
108
  const probe = await waitForCardsReady(command, codes, timeoutMs, pollIntervalMs);
130
109
  const cards = [];
131
110
  for (const code of codes) {
111
+ const selector = `[data-kline-card][data-code="${code}"]`;
132
112
  const path = join(outputDir, `${filePrefix}-${code}.png`);
133
- const shot = unwrapScreenshot(await command('screenshot', {
134
- format: 'png',
135
- selector: `[data-kline-card][data-code="${code}"]`,
136
- path,
137
- }));
113
+ const shot = await captureSelectorPngViaCdp(command, selector, path, {
114
+ settleMs,
115
+ });
138
116
  cards.push({ code, path: shot.path, sizeBytes: shot.sizeBytes });
139
117
  }
140
118
  await tryCloseTab();
@@ -3,6 +3,11 @@ import type { CaptureMarketKlineScreenshotsOptions } from '../types/market-kline
3
3
  /**
4
4
  * Open `/market-kline-list` via WebBridge and screenshot each
5
5
  * `[data-kline-card][data-symbol]` (indices / gold / US — not A-share stocks).
6
+ *
7
+ * Default `layout: 'per-symbol'` navigates one symbol at a time so each card is
8
+ * above the fold — avoids Kimi WebBridge selector clip bugs on scrollable lists
9
+ * (wrong neighbor / empty strip). Use `layout: 'batch'` only when you need speed
10
+ * and accept scrollIntoView + possible residual clip issues.
6
11
  */
7
12
  export declare function captureMarketKlineScreenshots(options?: CaptureMarketKlineScreenshotsOptions): Promise<CaptureKlineScreenshotsResult>;
8
13
  //# sourceMappingURL=capture-market-kline-screenshots.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"capture-market-kline-screenshots.d.ts","sourceRoot":"","sources":["../../src/kline/capture-market-kline-screenshots.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EACV,6BAA6B,EAG9B,MAAM,8BAA8B,CAAA;AACrC,OAAO,KAAK,EAAE,oCAAoC,EAAE,MAAM,qCAAqC,CAAA;AAuF/F;;;GAGG;AACH,wBAAsB,6BAA6B,CACjD,OAAO,GAAE,oCAAyC,GACjD,OAAO,CAAC,6BAA6B,CAAC,CA8FxC"}
1
+ {"version":3,"file":"capture-market-kline-screenshots.d.ts","sourceRoot":"","sources":["../../src/kline/capture-market-kline-screenshots.ts"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EACV,6BAA6B,EAG9B,MAAM,8BAA8B,CAAA;AACrC,OAAO,KAAK,EAAE,oCAAoC,EAAE,MAAM,qCAAqC,CAAA;AA8D/F;;;;;;;;GAQG;AACH,wBAAsB,6BAA6B,CACjD,OAAO,GAAE,oCAAyC,GACjD,OAAO,CAAC,6BAA6B,CAAC,CAmIxC"}
@@ -4,6 +4,7 @@ import { tmpdir } from 'node:os';
4
4
  import { DEFAULT_STOCK_APP_BASE_URL, DEFAULT_WEBBRIDGE_BASE_URL, } from '../config.js';
5
5
  import { DEFAULT_KLINE_SCREENSHOT_YEARS } from './kline-list-url.js';
6
6
  import { buildMarketKlineListUrl, parseMarketSymbols, } from './market-symbols.js';
7
+ import { captureSelectorPngViaCdp, prepareScreenshotViewport, sleep, unwrapEvaluateValue, } from './screenshot-helpers.js';
7
8
  import { createWebbridgeClient, WebbridgeError } from './webbridge-client.js';
8
9
  const READY_EVAL_CODE = `(() => {
9
10
  const cards = document.querySelectorAll('[data-kline-card]');
@@ -18,19 +19,6 @@ const READY_EVAL_CODE = `(() => {
18
19
  bars: list?.getAttribute('data-kline-visible-bars') ?? null,
19
20
  });
20
21
  })()`;
21
- function sleep(ms) {
22
- return new Promise((resolve) => setTimeout(resolve, ms));
23
- }
24
- function unwrapEvaluateValue(data) {
25
- if (typeof data === 'string')
26
- return data;
27
- if (data && typeof data === 'object' && 'value' in data) {
28
- const value = data.value;
29
- if (typeof value === 'string')
30
- return value;
31
- }
32
- throw new WebbridgeError('Unexpected evaluate payload from WebBridge', 'bad_evaluate');
33
- }
34
22
  function parseReadyProbe(data) {
35
23
  const raw = unwrapEvaluateValue(data);
36
24
  const parsed = JSON.parse(raw);
@@ -43,17 +31,6 @@ function parseReadyProbe(data) {
43
31
  bars: parsed.bars ?? null,
44
32
  };
45
33
  }
46
- function unwrapScreenshot(data) {
47
- if (!data || typeof data !== 'object') {
48
- throw new WebbridgeError('Unexpected screenshot payload from WebBridge', 'bad_screenshot');
49
- }
50
- const path = String(data.path ?? '');
51
- const sizeBytes = Number(data.sizeBytes ?? 0);
52
- if (!path) {
53
- throw new WebbridgeError('WebBridge screenshot missing path', 'bad_screenshot');
54
- }
55
- return { path, sizeBytes };
56
- }
57
34
  async function waitForCardsReady(command, symbolIds, timeoutMs, pollIntervalMs) {
58
35
  const deadline = Date.now() + timeoutMs;
59
36
  let last = null;
@@ -72,6 +49,11 @@ async function waitForCardsReady(command, symbolIds, timeoutMs, pollIntervalMs)
72
49
  /**
73
50
  * Open `/market-kline-list` via WebBridge and screenshot each
74
51
  * `[data-kline-card][data-symbol]` (indices / gold / US — not A-share stocks).
52
+ *
53
+ * Default `layout: 'per-symbol'` navigates one symbol at a time so each card is
54
+ * above the fold — avoids Kimi WebBridge selector clip bugs on scrollable lists
55
+ * (wrong neighbor / empty strip). Use `layout: 'batch'` only when you need speed
56
+ * and accept scrollIntoView + possible residual clip issues.
75
57
  */
76
58
  export async function captureMarketKlineScreenshots(options = {}) {
77
59
  const resolved = parseMarketSymbols(options.symbols);
@@ -83,16 +65,13 @@ export async function captureMarketKlineScreenshots(options = {}) {
83
65
  const session = options.session?.trim() || `market-kline-shot-${Date.now().toString(36)}`;
84
66
  const timeoutMs = options.timeoutMs ?? 60_000;
85
67
  const pollIntervalMs = options.pollIntervalMs ?? 1_000;
68
+ const settleMs = options.settleMs ?? 900;
86
69
  const closeTab = options.closeTab !== false;
87
70
  const filePrefix = options.filePrefix?.trim() || 'mk';
71
+ const layout = options.layout === 'batch' ? 'batch' : 'per-symbol';
72
+ const stockAppBaseUrl = options.stockAppBaseUrl ?? DEFAULT_STOCK_APP_BASE_URL;
88
73
  const outputDir = options.outputDir?.trim() || join(tmpdir(), 'agent-stock-sdk-market-kline');
89
74
  await mkdir(outputDir, { recursive: true });
90
- const url = buildMarketKlineListUrl({
91
- symbols: symbolIds,
92
- years,
93
- period,
94
- stockAppBaseUrl: options.stockAppBaseUrl ?? DEFAULT_STOCK_APP_BASE_URL,
95
- });
96
75
  const command = options.command ??
97
76
  createWebbridgeClient({
98
77
  baseUrl: options.webbridgeBaseUrl ?? DEFAULT_WEBBRIDGE_BASE_URL,
@@ -101,6 +80,8 @@ export async function captureMarketKlineScreenshots(options = {}) {
101
80
  }).command;
102
81
  let tabOpened = false;
103
82
  let tabClosed = false;
83
+ let lastUrl = '';
84
+ let lastBarsHint = Math.round(years * 250);
104
85
  const tryCloseTab = async () => {
105
86
  if (!closeTab || !tabOpened || tabClosed)
106
87
  return;
@@ -112,32 +93,69 @@ export async function captureMarketKlineScreenshots(options = {}) {
112
93
  console.warn('[captureMarketKlineScreenshots] close_tab failed:', err instanceof Error ? err.message : err);
113
94
  }
114
95
  };
115
- try {
116
- await command('navigate', {
117
- url,
118
- newTab: true,
119
- group_title: '市场K线列表截图',
96
+ const shotOne = async (symbolId) => {
97
+ const selector = `[data-kline-card][data-symbol="${symbolId}"]`;
98
+ const safeName = symbolId.replace(/[^a-zA-Z0-9._-]+/g, '_');
99
+ const path = join(outputDir, `${filePrefix}-${safeName}.png`);
100
+ const shot = await captureSelectorPngViaCdp(command, selector, path, {
101
+ settleMs,
120
102
  });
121
- tabOpened = true;
122
- const probe = await waitForCardsReady(command, symbolIds, timeoutMs, pollIntervalMs);
103
+ return { code: symbolId, path: shot.path, sizeBytes: shot.sizeBytes };
104
+ };
105
+ try {
123
106
  const cards = [];
124
- for (const symbolId of symbolIds) {
125
- const safeName = symbolId.replace(/[^a-zA-Z0-9._-]+/g, '_');
126
- const path = join(outputDir, `${filePrefix}-${safeName}.png`);
127
- const shot = unwrapScreenshot(await command('screenshot', {
128
- format: 'png',
129
- selector: `[data-kline-card][data-symbol="${symbolId}"]`,
130
- path,
131
- }));
132
- cards.push({ code: symbolId, path: shot.path, sizeBytes: shot.sizeBytes });
107
+ if (layout === 'per-symbol') {
108
+ for (let i = 0; i < symbolIds.length; i += 1) {
109
+ const symbolId = symbolIds[i];
110
+ const url = buildMarketKlineListUrl({
111
+ symbols: [symbolId],
112
+ years,
113
+ period,
114
+ stockAppBaseUrl,
115
+ });
116
+ lastUrl = url;
117
+ await command('navigate', {
118
+ url,
119
+ newTab: !tabOpened,
120
+ group_title: '市场K线列表截图',
121
+ });
122
+ tabOpened = true;
123
+ if (i === 0) {
124
+ await prepareScreenshotViewport(command);
125
+ }
126
+ const probe = await waitForCardsReady(command, [symbolId], timeoutMs, pollIntervalMs);
127
+ lastBarsHint = Number(probe.bars) || lastBarsHint;
128
+ cards.push(await shotOne(symbolId));
129
+ }
130
+ }
131
+ else {
132
+ const url = buildMarketKlineListUrl({
133
+ symbols: symbolIds,
134
+ years,
135
+ period,
136
+ stockAppBaseUrl,
137
+ });
138
+ lastUrl = url;
139
+ await command('navigate', {
140
+ url,
141
+ newTab: true,
142
+ group_title: '市场K线列表截图',
143
+ });
144
+ tabOpened = true;
145
+ await prepareScreenshotViewport(command);
146
+ const probe = await waitForCardsReady(command, symbolIds, timeoutMs, pollIntervalMs);
147
+ lastBarsHint = Number(probe.bars) || lastBarsHint;
148
+ for (const symbolId of symbolIds) {
149
+ cards.push(await shotOne(symbolId));
150
+ }
133
151
  }
134
152
  await tryCloseTab();
135
153
  return {
136
- url,
154
+ url: lastUrl,
137
155
  session,
138
156
  years,
139
157
  period,
140
- visibleBarsHint: Number(probe.bars) || Math.round(years * 250),
158
+ visibleBarsHint: lastBarsHint,
141
159
  cards,
142
160
  tabClosed,
143
161
  };
@@ -0,0 +1,59 @@
1
+ import type { WebbridgeCommandFn } from '../types/kline-screenshot.js';
2
+ /**
3
+ * CSS viewport for capture. deviceScaleFactor=1 keeps CSS coords == CDP surface
4
+ * pixels (avoids left-crop when iw ≠ surface width under DSF≠1).
5
+ */
6
+ export declare const SCREENSHOT_VIEWPORT: {
7
+ readonly width: 1100;
8
+ readonly height: 1600;
9
+ readonly deviceScaleFactor: 1;
10
+ };
11
+ /** Fixed card/column width for readable K-line screenshots. */
12
+ export declare const SCREENSHOT_CARD_MAX_WIDTH_PX = 960;
13
+ export declare function sleep(ms: number): Promise<void>;
14
+ export declare function unwrapEvaluateValue(data: unknown): string;
15
+ export declare function unwrapScreenshot(data: unknown): {
16
+ path: string;
17
+ sizeBytes: number;
18
+ };
19
+ /**
20
+ * Lock tab viewport via CDP. Prefer deviceScaleFactor=1 so clip CSS px match surface.
21
+ */
22
+ export declare function prepareScreenshotViewport(command: WebbridgeCommandFn, viewport?: {
23
+ width: number;
24
+ height: number;
25
+ deviceScaleFactor: number;
26
+ }): Promise<void>;
27
+ /**
28
+ * Hide app sidebar + force a centered fixed-width capture column.
29
+ */
30
+ export declare function prepareCapturePageLayout(command: WebbridgeCommandFn, columnWidthPx?: number): Promise<void>;
31
+ /**
32
+ * Scroll + remeasure card after capture layout is applied.
33
+ */
34
+ export declare function prepareCardForScreenshot(command: WebbridgeCommandFn, selector: string, maxWidthPx?: number, settleMs?: number): Promise<{
35
+ x: number;
36
+ y: number;
37
+ width: number;
38
+ height: number;
39
+ iw: number;
40
+ ih: number;
41
+ }>;
42
+ /**
43
+ * Capture element via CDP clip after pinning card to (0,0) at fixed width.
44
+ */
45
+ export declare function captureSelectorPngViaCdp(command: WebbridgeCommandFn, selector: string, outputPath: string, options?: {
46
+ maxWidthPx?: number;
47
+ settleMs?: number;
48
+ viewport?: {
49
+ width: number;
50
+ height: number;
51
+ deviceScaleFactor: number;
52
+ };
53
+ }): Promise<{
54
+ path: string;
55
+ sizeBytes: number;
56
+ }>;
57
+ /** @deprecated prefer captureSelectorPngViaCdp */
58
+ export declare function scrollSelectorIntoView(command: WebbridgeCommandFn, selector: string, settleMs?: number): Promise<void>;
59
+ //# sourceMappingURL=screenshot-helpers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"screenshot-helpers.d.ts","sourceRoot":"","sources":["../../src/kline/screenshot-helpers.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAA;AAGtE;;;GAGG;AACH,eAAO,MAAM,mBAAmB;;;;CAItB,CAAA;AAEV,+DAA+D;AAC/D,eAAO,MAAM,4BAA4B,MAAM,CAAA;AAE/C,wBAAgB,KAAK,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAE/C;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,OAAO,GAAG,MAAM,CAOzD;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,OAAO,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAUnF;AAeD;;GAEG;AACH,wBAAsB,yBAAyB,CAC7C,OAAO,EAAE,kBAAkB,EAC3B,QAAQ,GAAE;IACR,KAAK,EAAE,MAAM,CAAA;IACb,MAAM,EAAE,MAAM,CAAA;IACd,iBAAiB,EAAE,MAAM,CAAA;CACJ,GACtB,OAAO,CAAC,IAAI,CAAC,CAkBf;AAED;;GAEG;AACH,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,kBAAkB,EAC3B,aAAa,GAAE,MAAqC,GACnD,OAAO,CAAC,IAAI,CAAC,CA4Df;AAyGD;;GAEG;AACH,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,kBAAkB,EAC3B,QAAQ,EAAE,MAAM,EAChB,UAAU,GAAE,MAAqC,EACjD,QAAQ,SAAM,GACb,OAAO,CAAC;IAAE,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,CAAC,CAY1F;AAsCD;;GAEG;AACH,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,kBAAkB,EAC3B,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,EAClB,OAAO,CAAC,EAAE;IACR,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,QAAQ,CAAC,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,iBAAiB,EAAE,MAAM,CAAA;KAAE,CAAA;CACxE,GACA,OAAO,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAAC,CAgD9C;AAED,kDAAkD;AAClD,wBAAsB,sBAAsB,CAC1C,OAAO,EAAE,kBAAkB,EAC3B,QAAQ,EAAE,MAAM,EAChB,QAAQ,SAAM,GACb,OAAO,CAAC,IAAI,CAAC,CAEf"}
@@ -0,0 +1,320 @@
1
+ import { writeFile } from 'node:fs/promises';
2
+ import { PNG } from 'pngjs';
3
+ import { WebbridgeError } from './webbridge-client.js';
4
+ /**
5
+ * CSS viewport for capture. deviceScaleFactor=1 keeps CSS coords == CDP surface
6
+ * pixels (avoids left-crop when iw ≠ surface width under DSF≠1).
7
+ */
8
+ export const SCREENSHOT_VIEWPORT = {
9
+ width: 1100,
10
+ height: 1600,
11
+ deviceScaleFactor: 1,
12
+ };
13
+ /** Fixed card/column width for readable K-line screenshots. */
14
+ export const SCREENSHOT_CARD_MAX_WIDTH_PX = 960;
15
+ export function sleep(ms) {
16
+ return new Promise((resolve) => setTimeout(resolve, ms));
17
+ }
18
+ export function unwrapEvaluateValue(data) {
19
+ if (typeof data === 'string')
20
+ return data;
21
+ if (data && typeof data === 'object' && 'value' in data) {
22
+ const value = data.value;
23
+ if (typeof value === 'string')
24
+ return value;
25
+ }
26
+ throw new WebbridgeError('Unexpected evaluate payload from WebBridge', 'bad_evaluate');
27
+ }
28
+ export function unwrapScreenshot(data) {
29
+ if (!data || typeof data !== 'object') {
30
+ throw new WebbridgeError('Unexpected screenshot payload from WebBridge', 'bad_screenshot');
31
+ }
32
+ const path = String(data.path ?? '');
33
+ const sizeBytes = Number(data.sizeBytes ?? 0);
34
+ if (!path) {
35
+ throw new WebbridgeError('WebBridge screenshot missing path', 'bad_screenshot');
36
+ }
37
+ return { path, sizeBytes };
38
+ }
39
+ function unwrapCdpScreenshotBase64(data) {
40
+ if (!data || typeof data !== 'object') {
41
+ throw new WebbridgeError('Unexpected CDP screenshot payload', 'bad_screenshot');
42
+ }
43
+ const root = data;
44
+ if (typeof root.data === 'string' && root.data.length > 0)
45
+ return root.data;
46
+ if (root.result && typeof root.result === 'object') {
47
+ const nested = root.result.data;
48
+ if (typeof nested === 'string' && nested.length > 0)
49
+ return nested;
50
+ }
51
+ throw new WebbridgeError('CDP Page.captureScreenshot missing base64 data', 'bad_screenshot');
52
+ }
53
+ /**
54
+ * Lock tab viewport via CDP. Prefer deviceScaleFactor=1 so clip CSS px match surface.
55
+ */
56
+ export async function prepareScreenshotViewport(command, viewport = SCREENSHOT_VIEWPORT) {
57
+ try {
58
+ await command('cdp', {
59
+ method: 'Emulation.setPageScaleFactor',
60
+ params: { pageScaleFactor: 1 },
61
+ });
62
+ }
63
+ catch {
64
+ // optional on some bridges
65
+ }
66
+ await command('cdp', {
67
+ method: 'Emulation.setDeviceMetricsOverride',
68
+ params: {
69
+ width: viewport.width,
70
+ height: viewport.height,
71
+ deviceScaleFactor: viewport.deviceScaleFactor,
72
+ mobile: false,
73
+ },
74
+ });
75
+ }
76
+ /**
77
+ * Hide app sidebar + force a centered fixed-width capture column.
78
+ */
79
+ export async function prepareCapturePageLayout(command, columnWidthPx = SCREENSHOT_CARD_MAX_WIDTH_PX) {
80
+ const code = `(() => {
81
+ const width = ${JSON.stringify(`${columnWidthPx}px`)};
82
+
83
+ document.querySelectorAll('[data-sidebar="sidebar"]').forEach((node) => {
84
+ let p = node.parentElement;
85
+ while (p && p !== document.body) {
86
+ const cls = typeof p.className === 'string' ? p.className : '';
87
+ if (cls.includes('fixed') || p.getAttribute('data-slot') === 'sidebar') {
88
+ p.style.setProperty('display', 'none', 'important');
89
+ break;
90
+ }
91
+ p = p.parentElement;
92
+ }
93
+ if (node instanceof HTMLElement) {
94
+ node.style.setProperty('display', 'none', 'important');
95
+ }
96
+ });
97
+
98
+ document.querySelectorAll('[data-slot="sidebar-inset"]').forEach((node) => {
99
+ if (!(node instanceof HTMLElement)) return;
100
+ node.style.setProperty('margin-left', '0', 'important');
101
+ node.style.setProperty('margin-right', '0', 'important');
102
+ node.style.setProperty('width', '100%', 'important');
103
+ node.style.setProperty('max-width', '100%', 'important');
104
+ });
105
+
106
+ const roots = [
107
+ ...document.querySelectorAll('[data-kline-capture-root]'),
108
+ ...document.querySelectorAll('[data-kline-list]'),
109
+ ];
110
+ for (const root of roots) {
111
+ if (!(root instanceof HTMLElement)) continue;
112
+ root.style.setProperty('max-width', width, 'important');
113
+ root.style.setProperty('width', width, 'important');
114
+ root.style.setProperty('margin-left', 'auto', 'important');
115
+ root.style.setProperty('margin-right', 'auto', 'important');
116
+ }
117
+
118
+ document.querySelectorAll('[data-kline-card]').forEach((node) => {
119
+ if (!(node instanceof HTMLElement)) return;
120
+ node.style.setProperty('max-width', width, 'important');
121
+ node.style.setProperty('width', width, 'important');
122
+ node.style.setProperty('margin-left', 'auto', 'important');
123
+ node.style.setProperty('margin-right', 'auto', 'important');
124
+ });
125
+
126
+ document.body.setAttribute('data-kline-capture', '1');
127
+ window.dispatchEvent(new Event('resize'));
128
+ return JSON.stringify({
129
+ ok: true,
130
+ iw: innerWidth,
131
+ cards: document.querySelectorAll('[data-kline-card]').length,
132
+ });
133
+ })()`;
134
+ const raw = unwrapEvaluateValue(await command('evaluate', { code }));
135
+ const parsed = JSON.parse(raw);
136
+ if (!parsed.ok) {
137
+ throw new WebbridgeError('prepareCapturePageLayout failed', 'layout');
138
+ }
139
+ }
140
+ /**
141
+ * Move card onto document.body and pin at (0,0). Ancestors with transform/filter
142
+ * break position:fixed containing-block, which caused left-crop + sidebar bleed.
143
+ */
144
+ async function pinCardForCapture(command, selector, widthPx) {
145
+ const code = `(() => {
146
+ const el = document.querySelector(${JSON.stringify(selector)});
147
+ if (!(el instanceof HTMLElement)) return JSON.stringify({ ok: false });
148
+
149
+ document.querySelectorAll('[data-kline-capture-pinned]').forEach((n) => {
150
+ if (!(n instanceof HTMLElement)) return;
151
+ const homeId = n.getAttribute('data-kline-capture-home');
152
+ const home = homeId
153
+ ? document.querySelector('[data-kline-capture-slot="' + homeId + '"]')
154
+ : null;
155
+ if (home && home.parentNode) {
156
+ home.parentNode.insertBefore(n, home);
157
+ home.remove();
158
+ }
159
+ n.removeAttribute('data-kline-capture-pinned');
160
+ n.removeAttribute('data-kline-capture-home');
161
+ const prev = n.getAttribute('data-kline-capture-style');
162
+ if (prev != null) {
163
+ n.setAttribute('style', prev);
164
+ n.removeAttribute('data-kline-capture-style');
165
+ }
166
+ });
167
+
168
+ const homeId = 'h' + Date.now().toString(36);
169
+ const slot = document.createElement('div');
170
+ slot.setAttribute('data-kline-capture-slot', homeId);
171
+ slot.style.cssText = 'display:none';
172
+ if (el.parentNode) el.parentNode.insertBefore(slot, el);
173
+
174
+ el.setAttribute('data-kline-capture-style', el.getAttribute('style') || '');
175
+ el.setAttribute('data-kline-capture-pinned', '1');
176
+ el.setAttribute('data-kline-capture-home', homeId);
177
+
178
+ document.body.appendChild(el);
179
+
180
+ el.style.setProperty('position', 'fixed', 'important');
181
+ el.style.setProperty('left', '0px', 'important');
182
+ el.style.setProperty('top', '0px', 'important');
183
+ el.style.setProperty('right', 'auto', 'important');
184
+ el.style.setProperty('bottom', 'auto', 'important');
185
+ el.style.setProperty('width', ${JSON.stringify(`${widthPx}px`)}, 'important');
186
+ el.style.setProperty('max-width', ${JSON.stringify(`${widthPx}px`)}, 'important');
187
+ el.style.setProperty('margin', '0', 'important');
188
+ el.style.setProperty('z-index', '2147483646', 'important');
189
+ el.style.setProperty('background', '#ffffff', 'important');
190
+ el.style.setProperty('box-shadow', 'none', 'important');
191
+ el.style.setProperty('transform', 'none', 'important');
192
+
193
+ // Hide every other body child so clip cannot pick up sidebar chrome.
194
+ Array.prototype.forEach.call(document.body.children, (ch) => {
195
+ if (ch !== el && ch instanceof HTMLElement) {
196
+ ch.style.setProperty('visibility', 'hidden', 'important');
197
+ }
198
+ });
199
+
200
+ // Nudge chart containers so ResizeObserver / lightweight-charts reflow to 960.
201
+ el.querySelectorAll('canvas').forEach((c) => {
202
+ const p = c.parentElement;
203
+ if (!(p instanceof HTMLElement)) return;
204
+ const prev = p.style.width;
205
+ p.style.width = Math.max(1, p.clientWidth - 1) + 'px';
206
+ void p.offsetWidth;
207
+ p.style.width = prev;
208
+ });
209
+ window.dispatchEvent(new Event('resize'));
210
+
211
+ const r = el.getBoundingClientRect();
212
+ return JSON.stringify({
213
+ ok: true,
214
+ x: r.x,
215
+ y: r.y,
216
+ width: r.width,
217
+ height: r.height,
218
+ iw: innerWidth,
219
+ ih: innerHeight,
220
+ dpr: devicePixelRatio,
221
+ parent: el.parentElement && el.parentElement.tagName,
222
+ });
223
+ })()`;
224
+ const raw = unwrapEvaluateValue(await command('evaluate', { code }));
225
+ return JSON.parse(raw);
226
+ }
227
+ /**
228
+ * Scroll + remeasure card after capture layout is applied.
229
+ */
230
+ export async function prepareCardForScreenshot(command, selector, maxWidthPx = SCREENSHOT_CARD_MAX_WIDTH_PX, settleMs = 900) {
231
+ await prepareCapturePageLayout(command, maxWidthPx);
232
+ const pinned = await pinCardForCapture(command, selector, maxWidthPx);
233
+ if (!pinned.ok) {
234
+ throw new WebbridgeError(`pin failed: ${selector}`, 'missing_selector');
235
+ }
236
+ if (settleMs > 0)
237
+ await sleep(settleMs);
238
+ const pinned2 = await pinCardForCapture(command, selector, maxWidthPx);
239
+ if (!pinned2.ok) {
240
+ throw new WebbridgeError(`remeasure failed: ${selector}`, 'missing_selector');
241
+ }
242
+ return pinned2;
243
+ }
244
+ async function readCssVisualZoom(command) {
245
+ try {
246
+ const raw = await command('cdp', {
247
+ method: 'Page.getLayoutMetrics',
248
+ params: {},
249
+ });
250
+ const data = raw && typeof raw === 'object' && 'data' in raw
251
+ ? (raw.data ?? raw)
252
+ : raw;
253
+ const d = data;
254
+ const zoom = Number(d.cssVisualViewport?.zoom ?? d.visualViewport?.zoom ?? 1);
255
+ return Number.isFinite(zoom) && zoom > 0.05 && zoom <= 4 ? zoom : 1;
256
+ }
257
+ catch {
258
+ return 1;
259
+ }
260
+ }
261
+ /** Crop PNG to top-left WxH (fixes white-on-right when browser zoom < 1). */
262
+ function cropPngTopLeft(buf, width, height) {
263
+ const src = PNG.sync.read(buf);
264
+ const w = Math.max(1, Math.min(width, src.width));
265
+ const h = Math.max(1, Math.min(height, src.height));
266
+ if (w === src.width && h === src.height)
267
+ return buf;
268
+ const dst = new PNG({ width: w, height: h });
269
+ for (let y = 0; y < h; y += 1) {
270
+ const srcStart = y * src.width * 4;
271
+ const dstStart = y * w * 4;
272
+ src.data.copy(dst.data, dstStart, srcStart, srcStart + w * 4);
273
+ }
274
+ return Buffer.from(PNG.sync.write(dst));
275
+ }
276
+ /**
277
+ * Capture element via CDP clip after pinning card to (0,0) at fixed width.
278
+ */
279
+ export async function captureSelectorPngViaCdp(command, selector, outputPath, options) {
280
+ const viewport = options?.viewport ?? SCREENSHOT_VIEWPORT;
281
+ const maxWidthPx = options?.maxWidthPx ?? SCREENSHOT_CARD_MAX_WIDTH_PX;
282
+ await prepareScreenshotViewport(command, viewport);
283
+ const box = await prepareCardForScreenshot(command, selector, maxWidthPx, options?.settleMs ?? 1200);
284
+ // After body-pin + DSF=1, clip in CSS pixels (getBoundingClientRect).
285
+ const pad = 1;
286
+ const clip = {
287
+ x: Math.max(0, box.x - pad),
288
+ y: Math.max(0, box.y - pad),
289
+ width: Math.max(1, box.width + pad * 2),
290
+ height: Math.max(1, box.height + pad * 2),
291
+ scale: 1,
292
+ };
293
+ const zoom = await readCssVisualZoom(command);
294
+ const cdpResult = await command('cdp', {
295
+ method: 'Page.captureScreenshot',
296
+ params: {
297
+ format: 'png',
298
+ fromSurface: true,
299
+ captureBeyondViewport: true,
300
+ clip,
301
+ },
302
+ });
303
+ let buf = Buffer.from(unwrapCdpScreenshotBase64(cdpResult), 'base64');
304
+ if (buf.length < 8 || buf[0] !== 0x89 || buf[1] !== 0x50) {
305
+ throw new WebbridgeError('CDP screenshot did not return a PNG', 'bad_screenshot');
306
+ }
307
+ // Browser zoom < 1 leaves empty white on the right/bottom of fromSurface clips.
308
+ if (Math.abs(zoom - 1) > 0.02) {
309
+ const png = PNG.sync.read(buf);
310
+ const cw = Math.max(1, Math.round(png.width * zoom));
311
+ const ch = Math.max(1, Math.round(png.height * zoom));
312
+ buf = Buffer.from(cropPngTopLeft(buf, cw, ch));
313
+ }
314
+ await writeFile(outputPath, buf);
315
+ return { path: outputPath, sizeBytes: buf.length };
316
+ }
317
+ /** @deprecated prefer captureSelectorPngViaCdp */
318
+ export async function scrollSelectorIntoView(command, selector, settleMs = 400) {
319
+ await prepareCardForScreenshot(command, selector, SCREENSHOT_CARD_MAX_WIDTH_PX, settleMs);
320
+ }
@@ -29,6 +29,8 @@ export type CaptureKlineScreenshotsOptions = {
29
29
  timeoutMs?: number;
30
30
  /** Poll interval while waiting for charts. @default 1_000 */
31
31
  pollIntervalMs?: number;
32
+ /** Settle after card resize before CDP clip. @default 900 */
33
+ settleMs?: number;
32
34
  /**
33
35
  * Close the WebBridge tab opened for this capture after screenshots finish
34
36
  * (success or failure). Uses `close_tab` on the current session tab.
@@ -1 +1 @@
1
- {"version":3,"file":"kline-screenshot.d.ts","sourceRoot":"","sources":["../../src/types/kline-screenshot.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,qBAAqB,GAAG,KAAK,GAAG,MAAM,GAAG,OAAO,CAAA;AAE5D,MAAM,MAAM,8BAA8B,GAAG;IAC3C,kEAAkE;IAClE,KAAK,EAAE,MAAM,EAAE,CAAA;IACf;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,2DAA2D;IAC3D,MAAM,CAAC,EAAE,qBAAqB,CAAA;IAC9B;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,kFAAkF;IAClF,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,oFAAoF;IACpF,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,qEAAqE;IACrE,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,+DAA+D;IAC/D,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,6DAA6D;IAC7D,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,2DAA2D;IAC3D,KAAK,CAAC,EAAE,OAAO,KAAK,CAAA;IACpB;;;OAGG;IACH,OAAO,CAAC,EAAE,kBAAkB,CAAA;CAC7B,CAAA;AAED,MAAM,MAAM,kBAAkB,GAAG,CAC/B,MAAM,EAAE,MAAM,EACd,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAC3B,OAAO,CAAC,OAAO,CAAC,CAAA;AAErB,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;IACZ,SAAS,EAAE,MAAM,CAAA;CAClB,CAAA;AAED,MAAM,MAAM,6BAA6B,GAAG;IAC1C,GAAG,EAAE,MAAM,CAAA;IACX,OAAO,EAAE,MAAM,CAAA;IACf,KAAK,EAAE,MAAM,CAAA;IACb,MAAM,EAAE,qBAAqB,CAAA;IAC7B,eAAe,EAAE,MAAM,CAAA;IACvB,KAAK,EAAE,mBAAmB,EAAE,CAAA;IAC5B,oEAAoE;IACpE,SAAS,EAAE,OAAO,CAAA;CACnB,CAAA"}
1
+ {"version":3,"file":"kline-screenshot.d.ts","sourceRoot":"","sources":["../../src/types/kline-screenshot.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,qBAAqB,GAAG,KAAK,GAAG,MAAM,GAAG,OAAO,CAAA;AAE5D,MAAM,MAAM,8BAA8B,GAAG;IAC3C,kEAAkE;IAClE,KAAK,EAAE,MAAM,EAAE,CAAA;IACf;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,2DAA2D;IAC3D,MAAM,CAAC,EAAE,qBAAqB,CAAA;IAC9B;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,kFAAkF;IAClF,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,oFAAoF;IACpF,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,qEAAqE;IACrE,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,+DAA+D;IAC/D,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,6DAA6D;IAC7D,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,6DAA6D;IAC7D,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,2DAA2D;IAC3D,KAAK,CAAC,EAAE,OAAO,KAAK,CAAA;IACpB;;;OAGG;IACH,OAAO,CAAC,EAAE,kBAAkB,CAAA;CAC7B,CAAA;AAED,MAAM,MAAM,kBAAkB,GAAG,CAC/B,MAAM,EAAE,MAAM,EACd,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAC3B,OAAO,CAAC,OAAO,CAAC,CAAA;AAErB,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;IACZ,SAAS,EAAE,MAAM,CAAA;CAClB,CAAA;AAED,MAAM,MAAM,6BAA6B,GAAG;IAC1C,GAAG,EAAE,MAAM,CAAA;IACX,OAAO,EAAE,MAAM,CAAA;IACf,KAAK,EAAE,MAAM,CAAA;IACb,MAAM,EAAE,qBAAqB,CAAA;IAC7B,eAAe,EAAE,MAAM,CAAA;IACvB,KAAK,EAAE,mBAAmB,EAAE,CAAA;IAC5B,oEAAoE;IACpE,SAAS,EAAE,OAAO,CAAA;CACnB,CAAA"}
@@ -19,6 +19,14 @@ export type CaptureMarketKlineScreenshotsOptions = {
19
19
  filePrefix?: string;
20
20
  timeoutMs?: number;
21
21
  pollIntervalMs?: number;
22
+ /** Settle after card resize before CDP clip. @default 900 */
23
+ settleMs?: number;
24
+ /**
25
+ * `per-symbol` (default): navigate one symbol per page — avoids WebBridge
26
+ * selector clip bugs on scrollable multi-card lists.
27
+ * `batch`: one page with all symbols; scrolls each card into view before shot.
28
+ */
29
+ layout?: 'per-symbol' | 'batch';
22
30
  /** @default true */
23
31
  closeTab?: boolean;
24
32
  fetch?: typeof fetch;
@@ -1 +1 @@
1
- {"version":3,"file":"market-kline-screenshot.d.ts","sourceRoot":"","sources":["../../src/types/market-kline-screenshot.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,qBAAqB,EACrB,kBAAkB,EACnB,MAAM,uBAAuB,CAAA;AAE9B,MAAM,MAAM,oCAAoC,GAAG;IACjD;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;IAClB;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,0DAA0D;IAC1D,MAAM,CAAC,EAAE,OAAO,CAAC,qBAAqB,EAAE,OAAO,CAAC,CAAA;IAChD,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,oBAAoB;IACpB,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,KAAK,CAAC,EAAE,OAAO,KAAK,CAAA;IACpB,OAAO,CAAC,EAAE,kBAAkB,CAAA;CAC7B,CAAA"}
1
+ {"version":3,"file":"market-kline-screenshot.d.ts","sourceRoot":"","sources":["../../src/types/market-kline-screenshot.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,qBAAqB,EACrB,kBAAkB,EACnB,MAAM,uBAAuB,CAAA;AAE9B,MAAM,MAAM,oCAAoC,GAAG;IACjD;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;IAClB;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,0DAA0D;IAC1D,MAAM,CAAC,EAAE,OAAO,CAAC,qBAAqB,EAAE,OAAO,CAAC,CAAA;IAChD,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,6DAA6D;IAC7D,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB;;;;OAIG;IACH,MAAM,CAAC,EAAE,YAAY,GAAG,OAAO,CAAA;IAC/B,oBAAoB;IACpB,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,KAAK,CAAC,EAAE,OAAO,KAAK,CAAA;IACpB,OAAO,CAAC,EAAE,kBAAkB,CAAA;CAC7B,CAAA"}
@@ -0,0 +1,140 @@
1
+ # SnapshotPoolItem 字段说明
2
+
3
+ `SnapshotPoolItem` 不是 Nest `POST /stocks/snapshot/query` 的整包响应类型,而是 SDK 从 query **每一行**里裁剪出的子集(`pickSnapshotPoolItem`)。
4
+
5
+ - 整包响应壳:`SnapshotQueryResponse`(`items` / `total` / `page` …)
6
+ - 池方法返回:`SnapshotPoolResult`(`items: SnapshotPoolItem[]` + `sourceTotals` …)
7
+ - 单行子集:本文档的 `SnapshotPoolItem`
8
+
9
+ 对齐 K 线网格 `KlineGridCard`:头区 chips + 默认行情 meta + 各池筛选会驱动显示的技术 / 韭研列。完整 query 行字段远多于此,勿整行塞进 Agent 上下文。
10
+
11
+ 类型定义:`src/types/snapshot-pool.ts`。
12
+
13
+ ---
14
+
15
+ ## 1. 身份
16
+
17
+ | 字段 | 类型 | 含义 | 有什么用 | 举例 |
18
+ |------|------|------|----------|------|
19
+ | `code` | `string`(必有) | 股票代码 | 主键;合并去重、拉 K 线 / 截图、网格标题 | `"000001"`、`"600519"` |
20
+ | `name` | `string \| null` | 股票简称 | 展示用,旁挂在 code 旁 | `"平安银行"`、`"贵州茅台"` |
21
+
22
+ 无有效 `code` 的行会被丢弃。
23
+
24
+ ---
25
+
26
+ ## 2. 头区 chips(JJ / SZ)
27
+
28
+ 网格卡片头固定区:基金持股 / 流通市值 / 融资余额。
29
+
30
+ | 字段 | 类型 | 含义 | 有什么用 | 举例 |
31
+ |------|------|------|----------|------|
32
+ | `floatMarketCapYuan` | `number \| null` | 流通市值,单位 **元** | 分小/大市值池;UI 显示流通档 | `2e10` → 200 亿;池 A ≤ `3e10`(300 亿);池 C ≥ `5e10`(500 亿);池 D ≥ `3e10`(300 亿) |
33
+ | `fundHoldingsCount` | `number \| null` | 基金持股家数 | 机构参与度;A2 / 池 C 门槛 | `5`;A2 ≥ 3;池 C ≥ 40 |
34
+ | `financingBalanceYuan` | `number \| null` | 融资余额,单位 **元** | 杠杆资金热度芯片 | `1e8` → 1 亿元 |
35
+
36
+ > 读数时注意:市值 / 融资都是「元」,不是「亿元」。`2e10` = 200 亿。
37
+
38
+ ---
39
+
40
+ ## 3. 默认行情 meta
41
+
42
+ 网格默认可见列(非迷你 K 线模式)。
43
+
44
+ | 字段 | 类型 | 含义 | 有什么用 | 举例 |
45
+ |------|------|------|----------|------|
46
+ | `price` | `number \| null` | 最新价(通常为最近收盘价) | 看绝对价格档位 | `12.35` |
47
+ | `changePercent` | `number \| null` | 涨跌幅,单位 **%** | 当日强弱 | `5.2` → 涨 5.2%;`-2.1` → 跌 2.1% |
48
+ | `klineTurnover` | `number \| null` | 当日换手率,单位 **%** | 活跃度 / 筹码交换 | `3.2` → 换手 3.2% |
49
+ | `amount` | `number \| null` | 成交额(与 Nest snapshot 一致,通常为元) | 流动性粗判 | `1.5e9` 量级 |
50
+ | `bullBarDate` | `string \| null` | 走牛确认 bar 日期 | 「走牛点」列;趋势启动参照日 | `"2026-03-01"` |
51
+
52
+ ---
53
+
54
+ ## 4. 技术 / 收益(池筛选常用)
55
+
56
+ 多为百分比收益或振幅;具体筛选阈值见 [`趋势票与打板股票池.md`](./趋势票与打板股票池.md)。
57
+
58
+ | 字段 | 类型 | 含义 | 有什么用 | 举例 |
59
+ |------|------|------|----------|------|
60
+ | `dayReturn20d` | `number \| null` | 近 20 个交易日收益 % | 短线趋势强度;池 A 核心门槛 | `35`;A1 ≥ 30;A2 ≥ 25 |
61
+ | `dayReturn40d` | `number \| null` | 近 40 日收益 % | 中短周期;池 C 防过热上限 | `60`;池 C ≤ 100 |
62
+ | `dayReturn60d` | `number \| null` | 近 60 日收益 % | 中期趋势;池 A 区间、池 C 下限 | `50`;池 A ∈ `[25, 140]`;池 C ≥ 20 |
63
+ | `weekReturn26w` | `number \| null` | 近 26 周收益 % | 半年维度;过滤已翻倍过猛票 | `80`;池 A 常见上限 ≤ 180 |
64
+ | `boxAmplitudePct` | `number \| null` | 箱体振幅 % | 震荡幅度;过大说明波动过野 | `40`;池 A 常见上限 ≤ 150 |
65
+
66
+ ---
67
+
68
+ ## 5. 韭研异动 / 打板相关
69
+
70
+ 打板二波、中军、题材强度研判时重点看这组。
71
+
72
+ | 字段 | 类型 | 含义 | 有什么用 | 举例 |
73
+ |------|------|------|----------|------|
74
+ | `jiuyanActDate` | `string \| null` | 韭研异动日 | 时间窗筛选 + 默认排序键(desc) | `"2026-03-10"`;池 B 近 30 自然日;池 D 近 3 自然日 |
75
+ | `jiuyanFieldName` | `string \| null` | 韭研板块 / 题材名 | 归类主线题材 | `"银行"`、`"人工智能"` |
76
+ | `jiuyanLimitUpTotalDays` | `number \| null` | 涨停总天数(题材周期内累计) | 活跃度门槛 | `3`;池 A ≥ 2;池 B ≥ 5 |
77
+ | `jiuyanLimitUpDuringDays` | `number \| null` | 连板天数(本次行情持续天数口径) | 连板高度粗看 | `2` |
78
+ | `jiuyanConsecutiveLimitUpDays` | `number \| null` | 连续涨停天数 | 当前连板数 | `2` → 2 连板 |
79
+ | `jiuyanLimitUpTime` | `string \| null` | 涨停时间 | 早板 / 午后板强弱 | `"09:35:00"` |
80
+ | `jiuyanBriefReason` | `string[] \| null` | 涨停原因(简) | 一句话标签 | `["连板"]`、`["业绩预增"]` |
81
+ | `jiuyanDetailReason` | `string[] \| null` | 涨停原因(详) | 更细叙事 | `["主线", "资金回流"]` |
82
+ | `jiuyanThemeRank` | `number \| null` | 题材当日涨停强度排名 | 越小通常越强(视源定义) | `1` → 题材当日第一档 |
83
+
84
+ ---
85
+
86
+ ## 6. 完整示例(裁剪后)
87
+
88
+ ```ts
89
+ const item: SnapshotPoolItem = {
90
+ code: '000001',
91
+ name: '平安银行',
92
+ floatMarketCapYuan: 2e10, // 200 亿
93
+ fundHoldingsCount: 5,
94
+ financingBalanceYuan: 1e8, // 1 亿
95
+ price: 12.35,
96
+ changePercent: 5.2,
97
+ klineTurnover: 3.2,
98
+ amount: 1.5e9,
99
+ bullBarDate: '2026-03-01',
100
+ dayReturn20d: 35,
101
+ dayReturn40d: 60,
102
+ dayReturn60d: 50,
103
+ weekReturn26w: 80,
104
+ boxAmplitudePct: 40,
105
+ jiuyanActDate: '2026-03-10',
106
+ jiuyanFieldName: '银行',
107
+ jiuyanLimitUpTotalDays: 3,
108
+ jiuyanLimitUpDuringDays: 2,
109
+ jiuyanConsecutiveLimitUpDays: 2,
110
+ jiuyanLimitUpTime: '09:35:00',
111
+ jiuyanBriefReason: ['连板'],
112
+ jiuyanDetailReason: ['主线'],
113
+ jiuyanThemeRank: 1,
114
+ }
115
+ ```
116
+
117
+ Nest 原始 `items[]` 还会带大量其它列(如更长周期收益等);SDK 不会保留它们。例如测试里的 `dayReturn5d` / `dayReturn120d` 在 pick 后会被丢掉。
118
+
119
+ ---
120
+
121
+ ## 7. 和接口 / SDK 返回的关系
122
+
123
+ ```text
124
+ POST /stocks/snapshot/query
125
+ │
126
+ ▼
127
+ SnapshotQueryResponse
128
+ items: unknown[] ← 完整 snapshot 行(字段很多)
129
+ total / page / pageSize …
130
+ │
131
+ │ pickSnapshotPoolItem(s)
132
+ ▼
133
+ SnapshotPoolItem[] ← 本文档字段
134
+ │
135
+ │ 池方法封装
136
+ ▼
137
+ SnapshotPoolResult
138
+ items: SnapshotPoolItem[]
139
+ sourceTotals / dataVersion / stale / recentTradingDays10
140
+ ```
@@ -3,7 +3,8 @@
3
3
  *
4
4
  * pnpm --filter @t2b2c/agent-stock-sdk example:market-kline-shot
5
5
  * pnpm --filter @t2b2c/agent-stock-sdk example:market-kline-shot -- \
6
- * --symbols=cyb,sse,nasdaq,gold,us:AAPL --years=2.5
6
+ * --symbols=cyb,sse,nasdaq,gold,us:AAPL --years=2.5 \
7
+ * --stock-app=http://localhost:9311
7
8
  */
8
9
 
9
10
  import { mkdir } from 'node:fs/promises'
@@ -14,11 +15,37 @@ import {
14
15
  WebbridgeError,
15
16
  } from '../src/index.js'
16
17
 
18
+ function printUsage(): void {
19
+ console.log(`Usage:
20
+ pnpm --filter @t2b2c/agent-stock-sdk example:market-kline-shot -- [options]
21
+
22
+ Options:
23
+ --symbols=cyb,sse,nasdaq,gold Market symbols (default: cyb,sse,nasdaq,gold)
24
+ --years=2.5 Visible years (default: ${DEFAULT_KLINE_SCREENSHOT_YEARS})
25
+ --period=day|week Chart period (default: day)
26
+ --layout=per-symbol|batch Default per-symbol (avoids WebBridge clip bugs)
27
+ --out=DIR Output directory
28
+ --stock-app=URL stock-app origin (default: http://192.168.188.1:9311)
29
+ --webbridge=URL WebBridge daemon (default: http://127.0.0.1:10086)
30
+ --help Show this help
31
+ `)
32
+ }
33
+
17
34
  function parseArgs(argv: string[]) {
18
- const opts = {
19
- symbols: ['cyb', 'sse', 'nasdaq', 'gold'] as string[],
35
+ const opts: {
36
+ symbols: string[]
37
+ years: number
38
+ period: 'day' | 'week'
39
+ layout: 'per-symbol' | 'batch'
40
+ out: string
41
+ stockAppBaseUrl?: string
42
+ webbridgeBaseUrl?: string
43
+ help: boolean
44
+ } = {
45
+ symbols: ['cyb', 'sse', 'nasdaq', 'gold'],
20
46
  years: DEFAULT_KLINE_SCREENSHOT_YEARS,
21
- period: 'day' as 'day' | 'week',
47
+ period: 'day',
48
+ layout: 'per-symbol',
22
49
  out: resolve(process.cwd(), 'tmp/market-kline-exports'),
23
50
  help: false,
24
51
  }
@@ -30,45 +57,89 @@ function parseArgs(argv: string[]) {
30
57
  continue
31
58
  }
32
59
  const m = /^--([^=]+)=(.*)$/.exec(arg)
33
- if (!m) continue
60
+ if (!m) {
61
+ console.warn(`Ignoring unknown argument: ${arg}`)
62
+ continue
63
+ }
34
64
  const [, key, value] = m
35
- if (key === 'symbols') {
36
- opts.symbols = value.split(/[,,\s]+/).map((s) => s.trim()).filter(Boolean)
37
- } else if (key === 'years') {
38
- opts.years = Number(value)
39
- } else if (key === 'period' && (value === 'day' || value === 'week')) {
40
- opts.period = value
41
- } else if (key === 'out') {
42
- opts.out = resolve(process.cwd(), value)
65
+ switch (key) {
66
+ case 'symbols':
67
+ opts.symbols = value.split(/[,,\s]+/).map((s) => s.trim()).filter(Boolean)
68
+ break
69
+ case 'years': {
70
+ const n = Number(value)
71
+ if (!Number.isFinite(n) || n <= 0) throw new Error(`Invalid --years=${value}`)
72
+ opts.years = n
73
+ break
74
+ }
75
+ case 'period':
76
+ if (value !== 'day' && value !== 'week') {
77
+ throw new Error(`Invalid --period=${value}`)
78
+ }
79
+ opts.period = value
80
+ break
81
+ case 'layout':
82
+ if (value !== 'per-symbol' && value !== 'batch') {
83
+ throw new Error(`Invalid --layout=${value}`)
84
+ }
85
+ opts.layout = value
86
+ break
87
+ case 'out':
88
+ opts.out = resolve(process.cwd(), value)
89
+ break
90
+ case 'stock-app':
91
+ opts.stockAppBaseUrl = value
92
+ break
93
+ case 'webbridge':
94
+ opts.webbridgeBaseUrl = value
95
+ break
96
+ default:
97
+ console.warn(`Ignoring unknown option: --${key}`)
43
98
  }
44
99
  }
100
+
45
101
  return opts
46
102
  }
47
103
 
48
104
  async function main() {
49
105
  const opts = parseArgs(process.argv.slice(2))
50
106
  if (opts.help) {
51
- console.log(`Usage: example:market-kline-shot -- --symbols=cyb,us:AAPL --years=2.5`)
107
+ printUsage()
52
108
  return
53
109
  }
54
110
 
55
111
  await mkdir(opts.out, { recursive: true })
56
- const sdk = new AgentStockSdk()
57
- console.log('Capturing market K-line cards…', opts)
112
+ const sdk = new AgentStockSdk({
113
+ stockAppBaseUrl: opts.stockAppBaseUrl,
114
+ webbridgeBaseUrl: opts.webbridgeBaseUrl,
115
+ })
116
+
117
+ console.log('Capturing market K-line cards…')
118
+ console.log(` symbols: ${opts.symbols.join(', ')}`)
119
+ console.log(` years: ${opts.years}`)
120
+ console.log(` period: ${opts.period}`)
121
+ console.log(` layout: ${opts.layout}`)
122
+ console.log(` out: ${opts.out}`)
123
+ console.log(` app: ${sdk.stockAppBaseUrl}`)
124
+ console.log(` bridge: ${sdk.webbridgeBaseUrl}`)
58
125
 
59
126
  const result = await sdk.captureMarketKlineScreenshots({
60
127
  symbols: opts.symbols,
61
128
  years: opts.years,
62
129
  period: opts.period,
130
+ layout: opts.layout,
63
131
  outputDir: opts.out,
64
132
  filePrefix: 'mk',
133
+ stockAppBaseUrl: opts.stockAppBaseUrl,
134
+ webbridgeBaseUrl: opts.webbridgeBaseUrl,
65
135
  })
66
136
 
67
- console.log('Done.', {
68
- url: result.url,
69
- tabClosed: result.tabClosed,
70
- cards: result.cards,
71
- })
137
+ console.log('\nDone.')
138
+ console.log(` url: ${result.url}`)
139
+ console.log(` tabClosed: ${result.tabClosed}`)
140
+ for (const card of result.cards) {
141
+ console.log(` card: ${card.code} → ${card.path} (${card.sizeBytes} bytes)`)
142
+ }
72
143
  }
73
144
 
74
145
  main().catch((err) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@t2b2c/agent-stock-sdk",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Agent-facing stock SDK: dabang boards, snapshot trend/limit-up pools (Nest API), index/gold K-lines via stock-sdk, and K-line card screenshots via Kimi WebBridge",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -42,11 +42,13 @@
42
42
  ],
43
43
  "license": "UNLICENSED",
44
44
  "dependencies": {
45
+ "pngjs": "^7.0.0",
45
46
  "stock-sdk": "^2.4.6"
46
47
  },
47
48
  "devDependencies": {
48
49
  "@t2b2c/shared-config": "workspace:*",
49
50
  "@types/node": "^22.19.1",
51
+ "@types/pngjs": "^6.0.5",
50
52
  "tsx": "^4.19.4",
51
53
  "typescript": "^5.9.3",
52
54
  "vitest": "catalog:"