@t2b2c/agent-stock-sdk 0.0.0-stage → 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.
Files changed (92) hide show
  1. package/README.md +188 -2
  2. package/dist/board/ge7-themes.d.ts +4 -0
  3. package/dist/board/ge7-themes.d.ts.map +1 -0
  4. package/dist/board/ge7-themes.js +10 -0
  5. package/dist/board/limit-up-ladder.d.ts +8 -0
  6. package/dist/board/limit-up-ladder.d.ts.map +1 -0
  7. package/dist/board/limit-up-ladder.js +13 -0
  8. package/dist/client.d.ts +76 -0
  9. package/dist/client.d.ts.map +1 -0
  10. package/dist/client.js +130 -0
  11. package/dist/config.d.ts +34 -0
  12. package/dist/config.d.ts.map +1 -0
  13. package/dist/config.js +12 -0
  14. package/dist/http.d.ts +12 -0
  15. package/dist/http.d.ts.map +1 -0
  16. package/dist/http.js +60 -0
  17. package/dist/index.d.ts +35 -0
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +22 -0
  20. package/dist/kline/capture-kline-screenshots.d.ts +10 -0
  21. package/dist/kline/capture-kline-screenshots.d.ts.map +1 -0
  22. package/dist/kline/capture-kline-screenshots.js +133 -0
  23. package/dist/kline/capture-market-kline-screenshots.d.ts +13 -0
  24. package/dist/kline/capture-market-kline-screenshots.d.ts.map +1 -0
  25. package/dist/kline/capture-market-kline-screenshots.js +167 -0
  26. package/dist/kline/fetch-kline.d.ts +30 -0
  27. package/dist/kline/fetch-kline.d.ts.map +1 -0
  28. package/dist/kline/fetch-kline.js +54 -0
  29. package/dist/kline/fetch-market-kline.d.ts +10 -0
  30. package/dist/kline/fetch-market-kline.d.ts.map +1 -0
  31. package/dist/kline/fetch-market-kline.js +67 -0
  32. package/dist/kline/kline-list-url.d.ts +14 -0
  33. package/dist/kline/kline-list-url.d.ts.map +1 -0
  34. package/dist/kline/kline-list-url.js +46 -0
  35. package/dist/kline/market-symbols.d.ts +22 -0
  36. package/dist/kline/market-symbols.d.ts.map +1 -0
  37. package/dist/kline/market-symbols.js +105 -0
  38. package/dist/kline/normalize.d.ts +17 -0
  39. package/dist/kline/normalize.d.ts.map +1 -0
  40. package/dist/kline/normalize.js +34 -0
  41. package/dist/kline/screenshot-helpers.d.ts +59 -0
  42. package/dist/kline/screenshot-helpers.d.ts.map +1 -0
  43. package/dist/kline/screenshot-helpers.js +320 -0
  44. package/dist/kline/screenshot-route.d.ts +25 -0
  45. package/dist/kline/screenshot-route.d.ts.map +1 -0
  46. package/dist/kline/screenshot-route.js +65 -0
  47. package/dist/kline/webbridge-client.d.ts +22 -0
  48. package/dist/kline/webbridge-client.d.ts.map +1 -0
  49. package/dist/kline/webbridge-client.js +41 -0
  50. package/dist/pool/large-cap-limit-up-3d.d.ts +7 -0
  51. package/dist/pool/large-cap-limit-up-3d.d.ts.map +1 -0
  52. package/dist/pool/large-cap-limit-up-3d.js +20 -0
  53. package/dist/pool/large-cap-trend.d.ts +7 -0
  54. package/dist/pool/large-cap-trend.d.ts.map +1 -0
  55. package/dist/pool/large-cap-trend.js +20 -0
  56. package/dist/pool/limit-up-30d.d.ts +8 -0
  57. package/dist/pool/limit-up-30d.d.ts.map +1 -0
  58. package/dist/pool/limit-up-30d.js +21 -0
  59. package/dist/pool/pick-and-merge.d.ts +12 -0
  60. package/dist/pool/pick-and-merge.d.ts.map +1 -0
  61. package/dist/pool/pick-and-merge.js +110 -0
  62. package/dist/pool/query-bodies.d.ts +68 -0
  63. package/dist/pool/query-bodies.d.ts.map +1 -0
  64. package/dist/pool/query-bodies.js +121 -0
  65. package/dist/pool/small-cap-trend.d.ts +8 -0
  66. package/dist/pool/small-cap-trend.d.ts.map +1 -0
  67. package/dist/pool/small-cap-trend.js +27 -0
  68. package/dist/pool/snapshot-query.d.ts +5 -0
  69. package/dist/pool/snapshot-query.d.ts.map +1 -0
  70. package/dist/pool/snapshot-query.js +15 -0
  71. package/dist/types/board.d.ts +67 -0
  72. package/dist/types/board.d.ts.map +1 -0
  73. package/dist/types/board.js +1 -0
  74. package/dist/types/kline-screenshot.d.ts +64 -0
  75. package/dist/types/kline-screenshot.d.ts.map +1 -0
  76. package/dist/types/kline-screenshot.js +1 -0
  77. package/dist/types/kline.d.ts +31 -0
  78. package/dist/types/kline.d.ts.map +1 -0
  79. package/dist/types/kline.js +6 -0
  80. package/dist/types/market-kline-screenshot.d.ts +35 -0
  81. package/dist/types/market-kline-screenshot.d.ts.map +1 -0
  82. package/dist/types/market-kline-screenshot.js +1 -0
  83. package/dist/types/snapshot-pool.d.ts +53 -0
  84. package/dist/types/snapshot-pool.d.ts.map +1 -0
  85. package/dist/types/snapshot-pool.js +1 -0
  86. package/docs/SnapshotPoolItem/345/255/227/346/256/265/350/257/264/346/230/216.md +140 -0
  87. package/docs//344/270/244/344/270/252/350/266/213/345/212/277/347/245/250curl.md +102 -0
  88. package/docs//350/266/213/345/212/277/347/245/250/344/270/216/346/211/223/346/235/277/350/202/241/347/245/250/346/261/240.md +260 -0
  89. package/examples/capture-kline-screenshots.ts +151 -0
  90. package/examples/capture-market-kline-screenshots.ts +152 -0
  91. package/examples/fetch-snapshot-pools.ts +237 -0
  92. package/package.json +54 -4
@@ -0,0 +1,105 @@
1
+ import { INDEX_KLINE_SYMBOLS, } from '../types/kline.js';
2
+ const PRESET_IDS = new Set(Object.keys(INDEX_KLINE_SYMBOLS));
3
+ const DEFAULT_MARKET_SYMBOLS = Object.keys(INDEX_KLINE_SYMBOLS).map((id) => {
4
+ const meta = INDEX_KLINE_SYMBOLS[id];
5
+ return {
6
+ symbolId: id,
7
+ label: meta.label,
8
+ code: meta.code,
9
+ market: meta.market,
10
+ };
11
+ });
12
+ /** Reject bare A-share 6-digit codes (those belong on `/kline-list`). */
13
+ const ASHARE_CODE_RE = /^\d{6}$/;
14
+ /**
15
+ * Parse `symbols` query tokens: presets (`cyb`) and US tickers (`us:AAPL`).
16
+ * Throws on bare A-share 6-digit codes.
17
+ */
18
+ export function parseMarketSymbols(raw) {
19
+ const parts = Array.isArray(raw) ? raw : raw == null ? [] : [raw];
20
+ const tokens = [];
21
+ for (const part of parts) {
22
+ for (const token of String(part).split(/[\s,,;;|]+/)) {
23
+ const t = token.trim();
24
+ if (t)
25
+ tokens.push(t);
26
+ }
27
+ }
28
+ if (!tokens.length) {
29
+ return [...DEFAULT_MARKET_SYMBOLS];
30
+ }
31
+ const seen = new Set();
32
+ const out = [];
33
+ for (const token of tokens) {
34
+ const resolved = resolveMarketSymbolToken(token);
35
+ if (seen.has(resolved.symbolId))
36
+ continue;
37
+ seen.add(resolved.symbolId);
38
+ out.push(resolved);
39
+ }
40
+ return out;
41
+ }
42
+ export function resolveMarketSymbolToken(token) {
43
+ const raw = token.trim();
44
+ if (!raw) {
45
+ throw new Error('Empty market symbol token');
46
+ }
47
+ const lower = raw.toLowerCase();
48
+ if (PRESET_IDS.has(lower)) {
49
+ const id = lower;
50
+ const meta = INDEX_KLINE_SYMBOLS[id];
51
+ return {
52
+ symbolId: id,
53
+ label: meta.label,
54
+ code: meta.code,
55
+ market: meta.market,
56
+ };
57
+ }
58
+ const usMatch = /^(?:us:|US:)(.+)$/.exec(raw);
59
+ if (usMatch) {
60
+ const ticker = usMatch[1].trim().toUpperCase();
61
+ if (!ticker)
62
+ throw new Error(`Invalid US symbol: ${raw}`);
63
+ if (ASHARE_CODE_RE.test(ticker)) {
64
+ throw new Error(`A-share code ${ticker} is not allowed on market-kline-list; use /kline-list`);
65
+ }
66
+ return {
67
+ symbolId: `us:${ticker}`,
68
+ label: ticker,
69
+ code: ticker,
70
+ market: 'us',
71
+ };
72
+ }
73
+ if (ASHARE_CODE_RE.test(raw)) {
74
+ throw new Error(`A-share code ${raw} is not allowed on market-kline-list; use /kline-list`);
75
+ }
76
+ // Bare US-style ticker (letters)
77
+ if (/^[A-Za-z][A-Za-z0-9.-]*$/.test(raw)) {
78
+ const ticker = raw.toUpperCase();
79
+ return {
80
+ symbolId: `us:${ticker}`,
81
+ label: ticker,
82
+ code: ticker,
83
+ market: 'us',
84
+ };
85
+ }
86
+ throw new Error(`Unknown market symbol: ${raw}`);
87
+ }
88
+ export function defaultMarketSymbols() {
89
+ return [...DEFAULT_MARKET_SYMBOLS];
90
+ }
91
+ export function buildMarketKlineListUrl(input) {
92
+ const base = (input.stockAppBaseUrl ?? 'http://192.168.188.1:9311').replace(/\/+$/, '');
93
+ const years = input.years != null && Number.isFinite(input.years) && input.years > 0
94
+ ? input.years
95
+ : 2.5;
96
+ const period = input.period ?? 'day';
97
+ const symbols = input.symbols?.length
98
+ ? parseMarketSymbols(input.symbols).map((s) => s.symbolId)
99
+ : defaultMarketSymbols().map((s) => s.symbolId);
100
+ const url = new URL(`${base}/market-kline-list`);
101
+ url.searchParams.set('symbols', symbols.join(','));
102
+ url.searchParams.set('years', String(years));
103
+ url.searchParams.set('period', period);
104
+ return url.toString();
105
+ }
@@ -0,0 +1,17 @@
1
+ import type { KlineBar } from '../types/kline.js';
2
+ type LooseBar = {
3
+ date?: string;
4
+ open?: number | null;
5
+ high?: number | null;
6
+ low?: number | null;
7
+ close?: number | null;
8
+ volume?: number | null;
9
+ amount?: number | null;
10
+ changePercent?: number | null;
11
+ change?: number | null;
12
+ code?: string;
13
+ name?: string;
14
+ };
15
+ export declare function normalizeKlineBars(rows: LooseBar[]): KlineBar[];
16
+ export {};
17
+ //# sourceMappingURL=normalize.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"normalize.d.ts","sourceRoot":"","sources":["../../src/kline/normalize.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AAEjD,KAAK,QAAQ,GAAG;IACd,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACnB,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACrB,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACtB,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACtB,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAC7B,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACtB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,MAAM,CAAA;CACd,CAAA;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,QAAQ,EAAE,GAAG,QAAQ,EAAE,CAoC/D"}
@@ -0,0 +1,34 @@
1
+ export function normalizeKlineBars(rows) {
2
+ const bars = rows
3
+ .map((row) => {
4
+ const date = String(row.date ?? '').trim();
5
+ if (!date)
6
+ return null;
7
+ return {
8
+ date,
9
+ open: row.open ?? null,
10
+ high: row.high ?? null,
11
+ low: row.low ?? null,
12
+ close: row.close ?? null,
13
+ volume: row.volume ?? null,
14
+ amount: row.amount ?? null,
15
+ ...(row.changePercent != null ? { changePercent: row.changePercent } : {}),
16
+ ...(row.change != null ? { change: row.change } : {}),
17
+ ...(row.code != null ? { code: row.code } : {}),
18
+ ...(row.name != null ? { name: row.name } : {}),
19
+ };
20
+ })
21
+ .filter((row) => row != null)
22
+ .sort((a, b) => a.date.localeCompare(b.date));
23
+ for (let i = 1; i < bars.length; i++) {
24
+ const prev = bars[i - 1];
25
+ const cur = bars[i];
26
+ if (cur.changePercent == null &&
27
+ cur.close != null &&
28
+ prev.close != null &&
29
+ prev.close !== 0) {
30
+ cur.changePercent = ((cur.close - prev.close) / prev.close) * 100;
31
+ }
32
+ }
33
+ return bars;
34
+ }
@@ -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
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Route K-line screenshot targets by symbol kind:
3
+ * - A-share 6-digit stock codes → `/kline-list`
4
+ * - presets / US / futures → `/market-kline-list`
5
+ */
6
+ export type KlineScreenshotPage = 'kline-list' | 'market-kline-list';
7
+ export type PartitionedKlineScreenshotTargets = {
8
+ /** A-share individual stocks → `captureKlineScreenshots` / `/kline-list` */
9
+ aShareCodes: string[];
10
+ /** Indices / gold / US → `captureMarketKlineScreenshots` / `/market-kline-list` */
11
+ marketSymbols: string[];
12
+ };
13
+ /** True for bare A-share 6-digit stock codes (not indices). */
14
+ export declare function isAShareStockCode(token: string): boolean;
15
+ /**
16
+ * Decide which page a single token should screenshot on.
17
+ * Presets (`cyb`), `us:TICKER`, letter tickers → market page;
18
+ * bare `000595` → kline-list.
19
+ */
20
+ export declare function resolveKlineScreenshotPage(token: string): KlineScreenshotPage;
21
+ /**
22
+ * Split mixed tokens into A-share codes vs market symbols for the two capture APIs.
23
+ */
24
+ export declare function partitionKlineScreenshotTargets(tokens: string[]): PartitionedKlineScreenshotTargets;
25
+ //# sourceMappingURL=screenshot-route.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"screenshot-route.d.ts","sourceRoot":"","sources":["../../src/kline/screenshot-route.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAUH,MAAM,MAAM,mBAAmB,GAAG,YAAY,GAAG,mBAAmB,CAAA;AAEpE,MAAM,MAAM,iCAAiC,GAAG;IAC9C,4EAA4E;IAC5E,WAAW,EAAE,MAAM,EAAE,CAAA;IACrB,mFAAmF;IACnF,aAAa,EAAE,MAAM,EAAE,CAAA;CACxB,CAAA;AAED,+DAA+D;AAC/D,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAExD;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,MAAM,GAAG,mBAAmB,CAa7E;AAED;;GAEG;AACH,wBAAgB,+BAA+B,CAC7C,MAAM,EAAE,MAAM,EAAE,GACf,iCAAiC,CA2BnC"}
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Route K-line screenshot targets by symbol kind:
3
+ * - A-share 6-digit stock codes → `/kline-list`
4
+ * - presets / US / futures → `/market-kline-list`
5
+ */
6
+ import { INDEX_KLINE_SYMBOLS, } from '../types/kline.js';
7
+ const ASHARE_CODE_RE = /^\d{6}$/;
8
+ const PRESET_IDS = new Set(Object.keys(INDEX_KLINE_SYMBOLS));
9
+ /** True for bare A-share 6-digit stock codes (not indices). */
10
+ export function isAShareStockCode(token) {
11
+ return ASHARE_CODE_RE.test(token.trim());
12
+ }
13
+ /**
14
+ * Decide which page a single token should screenshot on.
15
+ * Presets (`cyb`), `us:TICKER`, letter tickers → market page;
16
+ * bare `000595` → kline-list.
17
+ */
18
+ export function resolveKlineScreenshotPage(token) {
19
+ const raw = token.trim();
20
+ if (!raw) {
21
+ throw new Error('Empty screenshot symbol token');
22
+ }
23
+ if (isAShareStockCode(raw))
24
+ return 'kline-list';
25
+ const lower = raw.toLowerCase();
26
+ if (PRESET_IDS.has(lower))
27
+ return 'market-kline-list';
28
+ if (/^(?:us:|US:)/.test(raw))
29
+ return 'market-kline-list';
30
+ if (/^[A-Za-z][A-Za-z0-9.-]*$/.test(raw))
31
+ return 'market-kline-list';
32
+ throw new Error(`Unknown screenshot symbol: ${raw}`);
33
+ }
34
+ /**
35
+ * Split mixed tokens into A-share codes vs market symbols for the two capture APIs.
36
+ */
37
+ export function partitionKlineScreenshotTargets(tokens) {
38
+ const aShareCodes = [];
39
+ const marketSymbols = [];
40
+ const seenCodes = new Set();
41
+ const seenMarket = new Set();
42
+ for (const token of tokens) {
43
+ const raw = token.trim();
44
+ if (!raw)
45
+ continue;
46
+ const page = resolveKlineScreenshotPage(raw);
47
+ if (page === 'kline-list') {
48
+ if (seenCodes.has(raw))
49
+ continue;
50
+ seenCodes.add(raw);
51
+ aShareCodes.push(raw);
52
+ continue;
53
+ }
54
+ const symbolId = PRESET_IDS.has(raw.toLowerCase())
55
+ ? raw.toLowerCase()
56
+ : /^(?:us:|US:)/.test(raw)
57
+ ? `us:${raw.replace(/^(?:us:|US:)/, '').trim().toUpperCase()}`
58
+ : `us:${raw.toUpperCase()}`;
59
+ if (seenMarket.has(symbolId))
60
+ continue;
61
+ seenMarket.add(symbolId);
62
+ marketSymbols.push(symbolId);
63
+ }
64
+ return { aShareCodes, marketSymbols };
65
+ }
@@ -0,0 +1,22 @@
1
+ import { DEFAULT_WEBBRIDGE_BASE_URL } from '../config.js';
2
+ export { DEFAULT_WEBBRIDGE_BASE_URL };
3
+ export declare class WebbridgeError extends Error {
4
+ readonly code?: string;
5
+ constructor(message: string, code?: string);
6
+ }
7
+ export type WebbridgeClientOptions = {
8
+ baseUrl?: string;
9
+ session: string;
10
+ fetch?: typeof fetch;
11
+ };
12
+ /**
13
+ * Thin HTTP client for the Kimi WebBridge local daemon (`POST /command`).
14
+ * @see https://www.kimi.com/zh-cn/features/webbridge
15
+ */
16
+ export declare function createWebbridgeClient(options: WebbridgeClientOptions): {
17
+ command: (action: string, args?: Record<string, unknown>) => Promise<unknown>;
18
+ session: string;
19
+ baseUrl: string;
20
+ };
21
+ export type WebbridgeClient = ReturnType<typeof createWebbridgeClient>;
22
+ //# sourceMappingURL=webbridge-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webbridge-client.d.ts","sourceRoot":"","sources":["../../src/kline/webbridge-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAA;AAEzD,OAAO,EAAE,0BAA0B,EAAE,CAAA;AAErC,qBAAa,cAAe,SAAQ,KAAK;IACvC,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAA;gBAEV,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM;CAK3C;AAED,MAAM,MAAM,sBAAsB,GAAG;IACnC,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,OAAO,EAAE,MAAM,CAAA;IACf,KAAK,CAAC,EAAE,OAAO,KAAK,CAAA;CACrB,CAAA;AAQD;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,sBAAsB;sBASpC,MAAM,SAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAQ,OAAO,CAAC,OAAO,CAAC;;;EA2B7F;AAED,MAAM,MAAM,eAAe,GAAG,UAAU,CAAC,OAAO,qBAAqB,CAAC,CAAA"}