codesign-mcp-next 0.0.0-stage → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +137 -0
  2. package/LICENSE +21 -0
  3. package/README.md +457 -2
  4. package/dist/browser/manager.js +204 -0
  5. package/dist/browser/session.js +62 -0
  6. package/dist/codesign/cache.js +85 -0
  7. package/dist/codesign/errors.js +47 -0
  8. package/dist/codesign/integrity.js +197 -0
  9. package/dist/codesign/meta.js +57 -0
  10. package/dist/codesign/parser.js +56 -0
  11. package/dist/codesign/platform.js +232 -0
  12. package/dist/codesign/selection.js +205 -0
  13. package/dist/codesign/sharing.js +153 -0
  14. package/dist/codesign/slices.js +34 -0
  15. package/dist/codesign/types.js +1 -0
  16. package/dist/config.js +94 -0
  17. package/dist/index.js +16 -0
  18. package/dist/logger.js +68 -0
  19. package/dist/mcp/result.js +151 -0
  20. package/dist/mcp/schema.js +122 -0
  21. package/dist/mcp/server.js +313 -0
  22. package/dist/prompts/design-to-code.js +128 -0
  23. package/dist/resources/workflow.js +33 -0
  24. package/dist/server.js +61 -0
  25. package/dist/tools/artboards.js +96 -0
  26. package/dist/tools/diagnostics.js +192 -0
  27. package/dist/tools/image.js +134 -0
  28. package/dist/tools/login.js +136 -0
  29. package/dist/tools/slices.js +228 -0
  30. package/dist/tools/spec.js +236 -0
  31. package/dist/tools/status.js +62 -0
  32. package/dist/utils/download.js +290 -0
  33. package/dist/utils/filename.js +16 -0
  34. package/dist/utils/http.js +54 -0
  35. package/dist/utils/rate-limit.js +120 -0
  36. package/dist/utils/redact.js +110 -0
  37. package/dist/utils/retry.js +97 -0
  38. package/dist/utils/url.js +98 -0
  39. package/package.json +56 -4
  40. package/userscripts/codesign-ai-selection.user.js +445 -0
@@ -0,0 +1,120 @@
1
+ // 按 host 分组的令牌桶节流。CoDesign API 与 CDN 分别限速,避免批量抓取时
2
+ // 自己把远端打到 429。所有出站请求都应先经过 throttle()。
3
+ import { config } from '../config.js';
4
+ function defaultSleep(ms) {
5
+ return new Promise((resolve) => setTimeout(resolve, ms));
6
+ }
7
+ class TokenBucket {
8
+ key;
9
+ capacity;
10
+ refillPerSec;
11
+ sleep;
12
+ now;
13
+ tokens;
14
+ lastRefill;
15
+ queue = [];
16
+ draining = false;
17
+ acquired = 0;
18
+ throttled = 0;
19
+ totalWaitMs = 0;
20
+ constructor(key, capacity, refillPerSec, sleep, now) {
21
+ this.key = key;
22
+ this.capacity = capacity;
23
+ this.refillPerSec = refillPerSec;
24
+ this.sleep = sleep;
25
+ this.now = now;
26
+ this.tokens = capacity;
27
+ this.lastRefill = now();
28
+ }
29
+ acquire() {
30
+ if (this.refillPerSec <= 0)
31
+ return Promise.resolve();
32
+ return new Promise((resolve) => {
33
+ this.queue.push(resolve);
34
+ void this.drain();
35
+ });
36
+ }
37
+ async drain() {
38
+ if (this.draining)
39
+ return;
40
+ this.draining = true;
41
+ try {
42
+ while (this.queue.length > 0) {
43
+ const now = this.now();
44
+ const elapsedSeconds = Math.max(0, (now - this.lastRefill) / 1000);
45
+ this.tokens = Math.min(this.capacity, this.tokens + elapsedSeconds * this.refillPerSec);
46
+ this.lastRefill = now;
47
+ if (this.tokens >= 1) {
48
+ this.tokens -= 1;
49
+ this.acquired += 1;
50
+ this.queue.shift()?.();
51
+ continue;
52
+ }
53
+ const waitMs = Math.max(1, Math.ceil(((1 - this.tokens) / this.refillPerSec) * 1000));
54
+ this.throttled += 1;
55
+ this.totalWaitMs += waitMs;
56
+ await this.sleep(waitMs);
57
+ }
58
+ }
59
+ finally {
60
+ this.draining = false;
61
+ }
62
+ }
63
+ stats() {
64
+ return {
65
+ key: this.key,
66
+ capacity: this.capacity,
67
+ refillPerSec: this.refillPerSec,
68
+ acquired: this.acquired,
69
+ throttled: this.throttled,
70
+ totalWaitMs: this.totalWaitMs,
71
+ };
72
+ }
73
+ }
74
+ export class RateLimiter {
75
+ buckets = new Map();
76
+ apiRps;
77
+ cdnRps;
78
+ sleep;
79
+ now;
80
+ constructor(options = {}) {
81
+ this.apiRps = options.apiRps ?? config.apiRps;
82
+ this.cdnRps = options.cdnRps ?? config.cdnRps;
83
+ this.sleep = options.sleep ?? defaultSleep;
84
+ this.now = options.now ?? Date.now;
85
+ }
86
+ // 用 URL 的 host 决定用哪一组配额;非 CoDesign 域名走 CDN 桶。
87
+ bucketKeyFor(url) {
88
+ let host;
89
+ try {
90
+ host = new URL(url).hostname.toLowerCase();
91
+ }
92
+ catch {
93
+ return 'cdn';
94
+ }
95
+ const apiHost = new URL(config.origin).hostname.toLowerCase();
96
+ return host === apiHost || host.endsWith(`.${apiHost}`) ? 'api' : 'cdn';
97
+ }
98
+ acquire(url) {
99
+ const key = this.bucketKeyFor(url);
100
+ let bucket = this.buckets.get(key);
101
+ if (!bucket) {
102
+ const rps = key === 'api' ? this.apiRps : this.cdnRps;
103
+ bucket = new TokenBucket(key, Math.max(1, rps * 2), rps, this.sleep, this.now);
104
+ this.buckets.set(key, bucket);
105
+ }
106
+ return bucket.acquire();
107
+ }
108
+ stats() {
109
+ return ['api', 'cdn']
110
+ .filter((key) => this.buckets.has(key))
111
+ .map((key) => this.buckets.get(key).stats());
112
+ }
113
+ }
114
+ const defaultLimiter = new RateLimiter();
115
+ export function throttle(url) {
116
+ return defaultLimiter.acquire(url);
117
+ }
118
+ export function rateLimitStats() {
119
+ return defaultLimiter.stats();
120
+ }
@@ -0,0 +1,110 @@
1
+ // 脱敏工具,主要用于 debug_collect_network。
2
+ // 与 scripts/extract-fixtures.mjs 保持一致的规则。
3
+ const SENSITIVE_HEADER_NAMES = new Set([
4
+ 'cookie', 'set-cookie', 'authorization',
5
+ 'x-csrf-token', 'x-xsrf-token', 'x-codesign-token',
6
+ 'x-auth-token', 'x-tcb-token', 'x-real-ip', 'x-forwarded-for',
7
+ 'state-key', 'x-team-id', 'x-corp-id', 'x-user-id', 'x-project-id',
8
+ ]);
9
+ const ID_RULES = [
10
+ { re: /\/api\/sharings\/(\d{6,})/g, sub: '/api/sharings/SHARING_ID' },
11
+ { re: /\/api\/designs\/(\d{6,})/g, sub: '/api/designs/DESIGN_ID' },
12
+ { re: /\/api\/users\/(\d{6,})/g, sub: '/api/users/USER_ID' },
13
+ { re: /\/api\/teams\/(\d{6,})/g, sub: '/api/teams/TEAM_ID' },
14
+ { re: /\/api\/companies\/(\d{6,})/g, sub: '/api/companies/COMPANY_ID' },
15
+ { re: /\/api\/departments\/(\d{6,})/g, sub: '/api/departments/DEPARTMENT_ID' },
16
+ { re: /\/api\/projects\/(\d{6,})/g, sub: '/api/projects/PROJECT_ID' },
17
+ { re: /\/app\/s\/(\d{6,})/g, sub: '/app/s/SHARING_ID' },
18
+ { re: /\/s\/(\d{6,})/g, sub: '/s/SHARING_ID' },
19
+ {
20
+ re: /cdn(\d?)\.codesign\.qq\.com\/meta\/(\d{4})\/(\d{2})\/(\d{2})\/([\w-]+)\/([\w-]+)\/([\w-]+)\.json/g,
21
+ sub: 'cdn$1.codesign.qq.com/meta/$2/$3/$4/TOKEN_A/TOKEN_B/UUID.json',
22
+ },
23
+ { re: /\/oauth\/check\?key=[\w-]+/g, sub: '/oauth/check?key=OAUTH_KEY' },
24
+ ];
25
+ export function redactUrl(u) {
26
+ if (typeof u !== 'string')
27
+ return u;
28
+ let out = u;
29
+ for (const r of ID_RULES)
30
+ out = out.replace(r.re, r.sub);
31
+ return redactStructuredUrl(out);
32
+ }
33
+ export function isSensitiveHeader(name) {
34
+ return SENSITIVE_HEADER_NAMES.has(name.toLowerCase());
35
+ }
36
+ export function redactHeaderValue(name, value) {
37
+ return isSensitiveHeader(name) ? '<redacted>' : redactUrl(value);
38
+ }
39
+ export function topLevelKeys(body, maxDepth = 0) {
40
+ if (body == null)
41
+ return [];
42
+ if (Array.isArray(body))
43
+ return ['<array>'];
44
+ if (typeof body === 'object')
45
+ return collectObjectKeys(body, maxDepth);
46
+ return [`<${typeof body}>`];
47
+ }
48
+ function redactStructuredUrl(input) {
49
+ let url;
50
+ try {
51
+ url = new URL(input);
52
+ }
53
+ catch {
54
+ return input;
55
+ }
56
+ const pathname = redactPathname(url.hostname, url.pathname);
57
+ const search = redactSearch(url.search);
58
+ const hash = url.hash ? '#<redacted-fragment>' : '';
59
+ return `${url.origin}${pathname}${search}${hash}`;
60
+ }
61
+ function redactPathname(hostname, pathname) {
62
+ if (!/^cdn\d*\.codesign\.qq\.com$/i.test(hostname))
63
+ return pathname;
64
+ const parts = pathname.split('/');
65
+ const family = parts[1];
66
+ if (!family || !['meta', 'screen-slices', 'screens'].includes(family))
67
+ return pathname;
68
+ const datePrefixLength = family === 'screens' && ['previews', 'covers'].includes(parts[2])
69
+ ? 6
70
+ : 5;
71
+ if (parts.length <= datePrefixLength)
72
+ return pathname;
73
+ const prefix = parts.slice(0, datePrefixLength);
74
+ const filename = parts.at(-1) ?? '';
75
+ return [...prefix, redactFilename(filename)].join('/');
76
+ }
77
+ function redactFilename(filename) {
78
+ const ext = filename.match(/\.[a-z0-9]+$/i)?.[0] ?? '';
79
+ return `<redacted>${ext}`;
80
+ }
81
+ function redactSearch(search) {
82
+ if (!search)
83
+ return '';
84
+ const query = search.slice(1);
85
+ if (!query)
86
+ return '';
87
+ const parts = query.split('&');
88
+ return `?${parts.map(redactQueryPart).join('&')}`;
89
+ }
90
+ function redactQueryPart(part) {
91
+ if (!part || !part.includes('='))
92
+ return '<redacted-query>';
93
+ const key = part.slice(0, part.indexOf('='));
94
+ return `${key}=<redacted>`;
95
+ }
96
+ function collectObjectKeys(body, maxDepth) {
97
+ const out = [];
98
+ collectKeys(body, '', maxDepth, out);
99
+ return out;
100
+ }
101
+ function collectKeys(value, prefix, depthRemaining, out) {
102
+ if (!value || typeof value !== 'object' || Array.isArray(value))
103
+ return;
104
+ for (const [key, child] of Object.entries(value)) {
105
+ const path = prefix ? `${prefix}.${key}` : key;
106
+ out.push(path);
107
+ if (depthRemaining > 0)
108
+ collectKeys(child, path, depthRemaining - 1, out);
109
+ }
110
+ }
@@ -0,0 +1,97 @@
1
+ // 统一重试策略:只对明确的瞬时故障重试,指数退避 + 抖动,尊重 Retry-After。
2
+ // 不重试 4xx(除 408/429),避免把参数错误或权限错误放大成长时间等待。
3
+ import { config } from '../config.js';
4
+ import { CodesignError } from '../codesign/errors.js';
5
+ const RETRYABLE_STATUSES = new Set([408, 429, 500, 502, 503, 504]);
6
+ export function isRetryableStatus(status) {
7
+ return RETRYABLE_STATUSES.has(status);
8
+ }
9
+ // Retry-After 支持 delta-seconds 与 HTTP-date 两种形式。
10
+ export function parseRetryAfter(value, now = Date.now()) {
11
+ if (!value || typeof value !== 'string')
12
+ return undefined;
13
+ const trimmed = value.trim();
14
+ if (/^\d+(?:\.\d+)?$/.test(trimmed)) {
15
+ const seconds = Number(trimmed);
16
+ return Number.isFinite(seconds) && seconds >= 0 ? Math.round(seconds * 1000) : undefined;
17
+ }
18
+ const date = Date.parse(trimmed);
19
+ return Number.isFinite(date) ? Math.max(0, date - now) : undefined;
20
+ }
21
+ function isNetworkError(err) {
22
+ if (!(err instanceof Error))
23
+ return false;
24
+ const code = err.code;
25
+ return (code === 'ECONNRESET' ||
26
+ code === 'ETIMEDOUT' ||
27
+ code === 'ENOTFOUND' ||
28
+ code === 'EAI_AGAIN' ||
29
+ code === 'ECONNREFUSED' ||
30
+ code === 'EPIPE');
31
+ }
32
+ function isRetryableError(err) {
33
+ if (err instanceof CodesignError && err.code === 'RATE_LIMITED')
34
+ return true;
35
+ return isNetworkError(err);
36
+ }
37
+ function defaultSleep(ms) {
38
+ return new Promise((resolve) => setTimeout(resolve, ms));
39
+ }
40
+ export async function withRetry(operation, options = {}) {
41
+ const maxAttempts = options.maxAttempts ?? config.retryMaxAttempts;
42
+ const baseDelayMs = options.baseDelayMs ?? config.retryBaseDelayMs;
43
+ const maxDelayMs = options.maxDelayMs ?? config.retryMaxDelayMs;
44
+ const retryAfterMaxMs = options.retryAfterMaxMs ?? config.retryAfterMaxMs;
45
+ const sleep = options.sleep ?? defaultSleep;
46
+ const jitter = options.jitter ?? Math.random;
47
+ let lastError;
48
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
49
+ try {
50
+ return await operation();
51
+ }
52
+ catch (err) {
53
+ lastError = err;
54
+ if (attempt >= maxAttempts)
55
+ break;
56
+ let delay;
57
+ if (options.retryOn) {
58
+ const hint = options.retryOn(err, attempt);
59
+ if (hint === false)
60
+ break;
61
+ delay = hint;
62
+ }
63
+ else if (isRetryableError(err)) {
64
+ delay =
65
+ err instanceof CodesignError && err.code === 'RATE_LIMITED'
66
+ ? err.details?.retryAfterMs
67
+ : undefined;
68
+ }
69
+ else {
70
+ break;
71
+ }
72
+ const exponential = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1));
73
+ const resolved = delay != null
74
+ ? Math.min(retryAfterMaxMs, delay)
75
+ : Math.min(maxDelayMs, exponential + exponential * 0.25 * jitter());
76
+ options.onRetry?.({ attempt, maxAttempts, lastError: err }, resolved);
77
+ await sleep(resolved);
78
+ }
79
+ }
80
+ throw lastError;
81
+ }
82
+ // 把重试耗尽的瞬时故障统一转成对 LLM 友好的错误码。
83
+ export function rateLimitError(scope, status, retryAfterMs) {
84
+ return new CodesignError('RATE_LIMITED', `${scope} request failed with retryable status ${status ?? 'unknown'}`, {
85
+ scope,
86
+ status,
87
+ retryAfterMs,
88
+ suggestion: 'Wait and retry, or lower CODESIGN_API_RPS / CODESIGN_CDN_RPS.',
89
+ });
90
+ }
91
+ // 三处请求入口共用:遇到 408/429/5xx 抛 RATE_LIMITED,交给 withRetry 处理。
92
+ export function assertNotRateLimited(status, scope, retryAfterHeader) {
93
+ if (!isRetryableStatus(status))
94
+ return;
95
+ const retryAfterMs = parseRetryAfter(retryAfterHeader);
96
+ throw rateLimitError(scope, status, retryAfterMs);
97
+ }
@@ -0,0 +1,98 @@
1
+ import { CodesignError } from '../codesign/errors.js';
2
+ // 接受的输入:
3
+ // https://codesign.qq.com/app/s/<id>
4
+ // https://codesign.qq.com/s/<id>
5
+ // https://codesign.qq.com/app/s/<id>?password=xxx
6
+ // 纯数字 <id>
7
+ export function parseSharingId(input) {
8
+ if (!input || typeof input !== 'string') {
9
+ throw new CodesignError('INVALID_SHARING_URL', 'sharingUrl is empty');
10
+ }
11
+ const trimmed = input.trim();
12
+ // 纯数字
13
+ if (/^\d{6,}$/.test(trimmed))
14
+ return trimmed;
15
+ // URL
16
+ let u;
17
+ try {
18
+ u = new URL(trimmed);
19
+ }
20
+ catch {
21
+ throw new CodesignError('INVALID_SHARING_URL', `cannot parse as URL: ${trimmed}`);
22
+ }
23
+ const m = u.pathname.match(/\/(?:app\/)?s\/(\d{6,})(?:\/|$)/);
24
+ if (!m) {
25
+ throw new CodesignError('INVALID_SHARING_URL', `path does not contain /s/<id>: ${u.pathname}`);
26
+ }
27
+ return m[1];
28
+ }
29
+ export function getSharingPageUrl(sharingId, origin = 'https://codesign.qq.com') {
30
+ return `${origin}/app/s/${sharingId}`;
31
+ }
32
+ export function normalizeCodesignAssetUrl(input, cdnOrigin = 'https://cdn4.codesign.qq.com') {
33
+ let source;
34
+ try {
35
+ source = new URL(input);
36
+ }
37
+ catch {
38
+ return input;
39
+ }
40
+ if (/^codesign-\d+\.cos(?:\.[a-z0-9-]+)*\.myqcloud\.com$/i.test(source.hostname) &&
41
+ isCodesignCosAssetPath(source.pathname)) {
42
+ const cdn = new URL(cdnOrigin);
43
+ return `${cdn.origin}${source.pathname}${source.search}`;
44
+ }
45
+ return input;
46
+ }
47
+ export function assertCodesignOriginUrl(input, purpose, origin = 'https://codesign.qq.com') {
48
+ let url;
49
+ let allowedOrigin;
50
+ try {
51
+ url = new URL(input);
52
+ allowedOrigin = new URL(origin);
53
+ }
54
+ catch {
55
+ throw new CodesignError('REMOTE_URL_NOT_ALLOWED', `${purpose} url is not a valid URL`, {
56
+ url: input,
57
+ });
58
+ }
59
+ if (url.origin === allowedOrigin.origin)
60
+ return input;
61
+ throw new CodesignError('REMOTE_URL_NOT_ALLOWED', `${purpose} url must stay on CoDesign origin`, {
62
+ url: input,
63
+ origin: url.origin,
64
+ allowedOrigin: allowedOrigin.origin,
65
+ });
66
+ }
67
+ export function assertAllowedRemoteUrl(input, purpose) {
68
+ let url;
69
+ try {
70
+ url = new URL(input);
71
+ }
72
+ catch {
73
+ throw new CodesignError('REMOTE_URL_NOT_ALLOWED', `${purpose} url is not a valid URL`, {
74
+ url: input,
75
+ });
76
+ }
77
+ if (url.protocol !== 'https:') {
78
+ throw new CodesignError('REMOTE_URL_NOT_ALLOWED', `${purpose} url must use https`, {
79
+ url: input,
80
+ protocol: url.protocol,
81
+ });
82
+ }
83
+ if (isAllowedCodesignHost(url.hostname))
84
+ return input;
85
+ throw new CodesignError('REMOTE_URL_NOT_ALLOWED', `${purpose} url host is not allowed`, {
86
+ url: input,
87
+ host: url.hostname,
88
+ allowedHosts: ['codesign.qq.com', 'cdn*.codesign.qq.com'],
89
+ });
90
+ }
91
+ export function isAllowedCodesignHost(hostname) {
92
+ return hostname === 'codesign.qq.com' || /^cdn\d*\.codesign\.qq\.com$/i.test(hostname);
93
+ }
94
+ function isCodesignCosAssetPath(pathname) {
95
+ return (pathname.startsWith('/screen-slices/') ||
96
+ pathname.startsWith('/screens/') ||
97
+ pathname.startsWith('/meta/'));
98
+ }
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "codesign-mcp-next",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.3",
4
+ "description": "Local MCP server for Tencent CoDesign — read sharing artboards, specs, screenshots and slices.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/DOIT008/codesign-mcp.git"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/DOIT008/codesign-mcp/issues"
13
+ },
14
+ "homepage": "https://github.com/DOIT008/codesign-mcp#readme",
15
+ "keywords": [
16
+ "mcp",
17
+ "codesign",
18
+ "tencent",
19
+ "design-to-code"
20
+ ],
21
+ "engines": {
22
+ "node": ">=20"
23
+ },
24
+ "main": "dist/index.js",
25
+ "bin": {
26
+ "codesign-mcp-next": "dist/index.js"
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "!dist/**/*.map",
31
+ "userscripts",
32
+ "README.md",
33
+ "CHANGELOG.md",
34
+ "LICENSE",
35
+ "package.json"
36
+ ],
37
+ "publishConfig": {
38
+ "access": "public",
39
+ "registry": "https://registry.npmjs.org/"
40
+ },
41
+ "scripts": {
42
+ "build": "tsc -p tsconfig.json",
43
+ "start": "node dist/index.js",
44
+ "dev": "tsx watch src/index.ts",
45
+ "typecheck": "tsc -p tsconfig.json --noEmit",
46
+ "test": "npm run build && node --check userscripts/codesign-ai-selection.user.js && node --test tests/cache.test.mjs tests/config.test.mjs tests/download.test.mjs tests/hierarchy.test.mjs tests/http.test.mjs tests/integrity.test.mjs tests/login.test.mjs tests/manager.test.mjs tests/mcp.test.mjs tests/parser.test.mjs tests/platform.test.mjs tests/rate-limit.test.mjs tests/redact.test.mjs tests/result.test.mjs tests/retry.test.mjs tests/selection.test.mjs tests/sharing.test.mjs tests/slices.test.mjs tests/startup.test.mjs tests/url.test.mjs",
47
+ "prepack": "npm run build",
48
+ "install:browsers": "playwright install chromium"
49
+ },
50
+ "dependencies": {
51
+ "playwright": "1.60.0"
52
+ },
53
+ "devDependencies": {
54
+ "@types/node": "22.19.19",
55
+ "tsx": "4.22.2",
56
+ "typescript": "5.9.3"
57
+ }
58
+ }