codesign-mcp-next 0.0.0-stage → 0.3.2

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 +121 -0
  2. package/LICENSE +21 -0
  3. package/README.md +458 -3
  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 +58 -6
  40. package/userscripts/codesign-ai-selection.user.js +445 -0
@@ -0,0 +1,204 @@
1
+ // 浏览器单例 + lazy-launch + idle shutdown + 并发保护。
2
+ // headless 工具共享同一个 page,避免每次工具调用都重新打开分享页;
3
+ // headed(登录)使用独占 page,用完即关。
4
+ // 所有 acquire / shutdown 都经过同一把锁,launch 与模式切换不会互相踩踏。
5
+ import { mkdirSync } from 'node:fs';
6
+ import { chromium } from 'playwright';
7
+ import { config } from '../config.js';
8
+ import { getLogger } from '../logger.js';
9
+ const log = getLogger();
10
+ const defaultLauncher = {
11
+ async launch(mode, profileDir) {
12
+ mkdirSync(profileDir, { recursive: true });
13
+ log.info({ mode, profileDir }, 'launching persistent context');
14
+ return chromium.launchPersistentContext(profileDir, {
15
+ headless: mode === 'headless',
16
+ viewport: { width: 1440, height: 900 },
17
+ args: ['--disable-blink-features=AutomationControlled'],
18
+ });
19
+ },
20
+ };
21
+ function createMutex() {
22
+ let tail = Promise.resolve();
23
+ return async (fn) => {
24
+ const previous = tail;
25
+ let release;
26
+ tail = new Promise((resolve) => {
27
+ release = resolve;
28
+ });
29
+ await previous;
30
+ try {
31
+ return await fn();
32
+ }
33
+ finally {
34
+ release();
35
+ }
36
+ };
37
+ }
38
+ export function createBrowserManager(launcher = defaultLauncher) {
39
+ const state = {
40
+ context: null,
41
+ mode: null,
42
+ activeCalls: 0,
43
+ lastUsedAt: 0,
44
+ idleTimer: null,
45
+ launchedAt: null,
46
+ sharedPage: null,
47
+ launchPromise: null,
48
+ drainWaiters: [],
49
+ };
50
+ const runExclusive = createMutex();
51
+ function clearIdle() {
52
+ if (state.idleTimer) {
53
+ clearTimeout(state.idleTimer);
54
+ state.idleTimer = null;
55
+ }
56
+ }
57
+ function scheduleIdleShutdown() {
58
+ clearIdle();
59
+ if (config.keepBrowser)
60
+ return;
61
+ if (!state.context)
62
+ return;
63
+ state.idleTimer = setTimeout(() => {
64
+ if (state.activeCalls > 0)
65
+ return;
66
+ void shutdown('idle');
67
+ }, config.idleMs);
68
+ }
69
+ function waitForDrain() {
70
+ if (state.activeCalls === 0)
71
+ return Promise.resolve();
72
+ return new Promise((resolve) => {
73
+ state.drainWaiters.push(resolve);
74
+ });
75
+ }
76
+ function notifyDrain() {
77
+ if (state.activeCalls !== 0 || state.drainWaiters.length === 0)
78
+ return;
79
+ const waiters = state.drainWaiters.splice(0);
80
+ for (const resolve of waiters)
81
+ resolve();
82
+ }
83
+ async function ensure(mode) {
84
+ if (state.launchPromise)
85
+ await state.launchPromise;
86
+ if (state.context && state.mode === mode)
87
+ return state.context;
88
+ if (state.context && state.mode !== mode) {
89
+ await waitForDrain();
90
+ await shutdownInternal('mode-switch');
91
+ }
92
+ if (!state.context) {
93
+ state.launchPromise = launcher
94
+ .launch(mode, config.profileDir)
95
+ .then((ctx) => {
96
+ state.context = ctx;
97
+ state.mode = mode;
98
+ state.launchedAt = Date.now();
99
+ state.sharedPage = null;
100
+ ctx.on('close', () => {
101
+ if (state.context !== ctx)
102
+ return;
103
+ state.context = null;
104
+ state.mode = null;
105
+ state.launchedAt = null;
106
+ state.sharedPage = null;
107
+ clearIdle();
108
+ });
109
+ return ctx;
110
+ })
111
+ .finally(() => {
112
+ state.launchPromise = null;
113
+ });
114
+ await state.launchPromise;
115
+ }
116
+ return state.context;
117
+ }
118
+ async function shutdownInternal(reason) {
119
+ clearIdle();
120
+ if (!state.context)
121
+ return;
122
+ if (state.activeCalls > 0) {
123
+ log.warn({ reason, activeCalls: state.activeCalls }, 'shutdown waiting for active calls');
124
+ await waitForDrain();
125
+ }
126
+ if (!state.context)
127
+ return;
128
+ log.info({ reason }, 'shutting down context');
129
+ const ctx = state.context;
130
+ state.context = null;
131
+ state.mode = null;
132
+ state.launchedAt = null;
133
+ state.sharedPage = null;
134
+ notifyDrain();
135
+ try {
136
+ await ctx.close();
137
+ }
138
+ catch (err) {
139
+ log.warn({ err: err.message }, 'context.close failed');
140
+ }
141
+ }
142
+ function shutdown(reason) {
143
+ return runExclusive(() => shutdownInternal(reason));
144
+ }
145
+ async function acquireCall(mode, shared) {
146
+ return runExclusive(async () => {
147
+ const ctx = await ensure(mode);
148
+ let page;
149
+ if (shared && state.sharedPage && !state.sharedPage.isClosed()) {
150
+ page = state.sharedPage;
151
+ }
152
+ else {
153
+ page = await ctx.newPage();
154
+ if (shared)
155
+ state.sharedPage = page;
156
+ }
157
+ // 只在 newPage 成功之后计数,失败不会造成 activeCalls 泄漏。
158
+ state.activeCalls += 1;
159
+ clearIdle();
160
+ let released = false;
161
+ const done = async () => {
162
+ if (released)
163
+ return;
164
+ released = true;
165
+ if (!shared) {
166
+ try {
167
+ await page.close({ runBeforeUnload: false });
168
+ }
169
+ catch (err) {
170
+ log.warn({ err: err.message }, 'page.close failed');
171
+ }
172
+ if (state.sharedPage === page)
173
+ state.sharedPage = null;
174
+ }
175
+ state.activeCalls = Math.max(0, state.activeCalls - 1);
176
+ state.lastUsedAt = Date.now();
177
+ notifyDrain();
178
+ if (state.activeCalls === 0)
179
+ scheduleIdleShutdown();
180
+ };
181
+ return { context: ctx, page, done };
182
+ });
183
+ }
184
+ return {
185
+ acquireHeadless() {
186
+ return acquireCall('headless', true);
187
+ },
188
+ acquireHeaded() {
189
+ return acquireCall('headed', false);
190
+ },
191
+ shutdown,
192
+ snapshot() {
193
+ return {
194
+ running: state.context != null,
195
+ mode: state.mode,
196
+ activeCalls: state.activeCalls,
197
+ lastUsedAt: state.lastUsedAt,
198
+ launchedAt: state.launchedAt,
199
+ sharedPage: state.sharedPage != null,
200
+ };
201
+ },
202
+ };
203
+ }
204
+ export const browserManager = createBrowserManager();
@@ -0,0 +1,62 @@
1
+ // 通过 CoDesign 同源上下文调 /api/user,判断登录态。
2
+ // 不在这里启动浏览器,调用方负责传入 page。
3
+ import { config } from '../config.js';
4
+ import { getLogger } from '../logger.js';
5
+ const log = getLogger();
6
+ // 在已建立的浏览器上下文中调用 /api/user。
7
+ // BrowserContext.request 复用同一个上下文 cookie,不需要在页面里执行脚本。
8
+ export async function probeLoggedIn(page) {
9
+ const currentUrl = page.url();
10
+ if (!currentUrl.startsWith(config.origin)) {
11
+ log.debug({ currentUrl }, 'navigating to home before probe');
12
+ await page.goto(`${config.origin}${config.homePath}`, {
13
+ waitUntil: 'domcontentloaded',
14
+ timeout: config.navTimeoutMs,
15
+ });
16
+ }
17
+ const r = await page.context().request.get(`${config.origin}/api/user?include=profiles&appends=is_company_admin,is_company_member,is_company_guest,has_password,watermark_settings`, {
18
+ headers: { Accept: 'application/json' },
19
+ timeout: config.apiTimeoutMs,
20
+ });
21
+ let body = null;
22
+ try {
23
+ body = await r.json();
24
+ }
25
+ catch {
26
+ /* ignore */
27
+ }
28
+ const resp = { status: r.status(), body };
29
+ if (resp.status === 200 && resp.body && typeof resp.body === 'object') {
30
+ const body = resp.body;
31
+ return {
32
+ loggedIn: true,
33
+ status: 200,
34
+ user: {
35
+ id: body.id,
36
+ uuid: body.uuid,
37
+ has_password: body.has_password,
38
+ },
39
+ raw: undefined,
40
+ };
41
+ }
42
+ return { loggedIn: false, status: resp.status, raw: resp.body };
43
+ }
44
+ // 在 headed 浏览器中等待用户扫码登录完成。
45
+ // 周期性 probe /api/user,直到 200 或超时。
46
+ export async function waitForLogin(page, opts = { timeoutMs: 10 * 60 * 1000 }) {
47
+ const pollMs = opts.pollMs ?? 2000;
48
+ const deadline = Date.now() + opts.timeoutMs;
49
+ let last = { loggedIn: false, status: 0 };
50
+ while (Date.now() < deadline) {
51
+ try {
52
+ last = await probeLoggedIn(page);
53
+ if (last.loggedIn)
54
+ return last;
55
+ }
56
+ catch (err) {
57
+ log.debug({ err: err.message }, 'probe during waitForLogin failed');
58
+ }
59
+ await new Promise((r) => setTimeout(r, pollMs));
60
+ }
61
+ return last;
62
+ }
@@ -0,0 +1,85 @@
1
+ // 进程内短 TTL 缓存:避免一条 design-to-code 流程反复拉取同一份
2
+ // sharing detail / meta.json / slice manifest。缓存只存在于内存,不落盘。
3
+ // 并发相同 key 的请求共享同一个 Promise,避免 LLM 并行调用时重复发包。
4
+ import { createHash } from 'node:crypto';
5
+ import { config } from '../config.js';
6
+ import { getLogger } from '../logger.js';
7
+ import { getSharingDetail } from './sharing.js';
8
+ import { fetchMetaJson } from './meta.js';
9
+ import { fetchSliceManifest } from './slices.js';
10
+ import { assertSpecObject } from './parser.js';
11
+ import { enforceIntegrity, inspectManifest, inspectSharingDetail, inspectSpec } from './integrity.js';
12
+ const log = getLogger();
13
+ const entries = new Map();
14
+ const inflight = new Map();
15
+ // 密码等凭证只能以摘要形式参与 key,不能把原文留在缓存键里。
16
+ export function hashCredential(secret) {
17
+ return createHash('sha256').update(secret).digest('hex').slice(0, 16);
18
+ }
19
+ export async function cached(key, loader) {
20
+ const now = Date.now();
21
+ const hit = entries.get(key);
22
+ if (hit && hit.expiresAt > now) {
23
+ log.debug({ key }, 'cache hit');
24
+ return hit.value;
25
+ }
26
+ const running = inflight.get(key);
27
+ if (running) {
28
+ log.debug({ key }, 'cache request deduplicated');
29
+ return running;
30
+ }
31
+ const task = Promise.resolve()
32
+ .then(loader)
33
+ .then((value) => {
34
+ entries.set(key, { value, expiresAt: Date.now() + config.cacheTtlMs });
35
+ return value;
36
+ })
37
+ .finally(() => {
38
+ inflight.delete(key);
39
+ });
40
+ inflight.set(key, task);
41
+ return task;
42
+ }
43
+ export function clearCache(prefix) {
44
+ if (!prefix) {
45
+ entries.clear();
46
+ return;
47
+ }
48
+ for (const key of entries.keys()) {
49
+ if (key.startsWith(prefix))
50
+ entries.delete(key);
51
+ }
52
+ }
53
+ export function cacheStats() {
54
+ return { entries: entries.size, inflight: inflight.size, ttlMs: config.cacheTtlMs };
55
+ }
56
+ // stateKey 只保存在内存条目中,工具层仍把它转换成 '<acquired>',不会回显给 LLM。
57
+ export async function getCachedSharingDetail(page, sharingId, password) {
58
+ const credential = password ? hashCredential(password) : 'none';
59
+ const key = `sharing:${sharingId}:${credential}`;
60
+ return cached(key, async () => {
61
+ const result = await getSharingDetail(page, sharingId, password);
62
+ enforceIntegrity(inspectSharingDetail(result.detail), 'SHARING_INCOMPLETE');
63
+ return result;
64
+ });
65
+ }
66
+ export async function fetchCachedMetaJson(url) {
67
+ return cached(`meta:${url}`, () => fetchMetaJson(url));
68
+ }
69
+ // spec 专用入口:校验通过后才写入缓存,失败结果不会被缓存。
70
+ export async function fetchCachedSpec(url) {
71
+ return cached(`meta:${url}`, async () => {
72
+ const raw = await fetchMetaJson(url);
73
+ assertSpecObject(raw);
74
+ const spec = raw;
75
+ enforceIntegrity(inspectSpec(spec), 'META_INCOMPLETE');
76
+ return spec;
77
+ });
78
+ }
79
+ export async function fetchCachedSliceManifest(url) {
80
+ return cached(`slices:${url}`, async () => {
81
+ const manifest = await fetchSliceManifest(url);
82
+ enforceIntegrity(inspectManifest(manifest), 'SLICE_INCOMPLETE');
83
+ return manifest;
84
+ });
85
+ }
@@ -0,0 +1,47 @@
1
+ export const ERROR_CODES = [
2
+ 'INVALID_SHARING_URL',
3
+ 'NEED_PASSWORD',
4
+ 'INVALID_PASSWORD',
5
+ 'NEED_LOGIN',
6
+ 'SHARING_NOT_FOUND',
7
+ 'SHARING_FETCH_FAILED',
8
+ 'RATE_LIMITED',
9
+ 'SCREEN_SELECTOR_REQUIRED',
10
+ 'SCREEN_NOT_FOUND',
11
+ 'META_FETCH_FAILED',
12
+ 'META_SCHEMA_MISMATCH',
13
+ 'SHARING_INCOMPLETE',
14
+ 'META_INCOMPLETE',
15
+ 'SLICE_INCOMPLETE',
16
+ 'INVALID_SELECTION',
17
+ 'INVALID_PLATFORM',
18
+ 'REMOTE_URL_NOT_ALLOWED',
19
+ 'PROFILE_DIR_UNSAFE',
20
+ 'SLICE_FETCH_FAILED',
21
+ 'SLICE_NOT_FOUND',
22
+ 'ARTIFACT_SIZE_MISMATCH',
23
+ 'ARTIFACT_MAGIC_MISMATCH',
24
+ 'ARTIFACT_PATH_INVALID',
25
+ ];
26
+ export class CodesignError extends Error {
27
+ code;
28
+ details;
29
+ constructor(code, message, details) {
30
+ super(message);
31
+ this.name = 'CodesignError';
32
+ this.code = code;
33
+ this.details = details;
34
+ }
35
+ toJSON() {
36
+ const out = {
37
+ code: this.code,
38
+ message: this.message,
39
+ };
40
+ if (this.details)
41
+ out.details = this.details;
42
+ return out;
43
+ }
44
+ }
45
+ export function isCodesignError(err) {
46
+ return err instanceof CodesignError;
47
+ }
@@ -0,0 +1,197 @@
1
+ // 完整性校验:区分「损坏/缺失」(硬错误)与「语义待确认」(警告)。
2
+ // 注意:真实分享数据表明 screen.slices_count 与 manifest 长度不一致,
3
+ // 且 exportable.size 是倍率而不是字节数,因此这两项不能用于完整性判断。
4
+ import { config } from '../config.js';
5
+ import { CodesignError } from './errors.js';
6
+ function report(stats, warnings = []) {
7
+ return { ok: warnings.every((w) => w.code.startsWith('WARN_')), warnings, stats };
8
+ }
9
+ function issue(code, message, details) {
10
+ return { code, message, details };
11
+ }
12
+ function isFiniteNumber(value) {
13
+ return typeof value === 'number' && Number.isFinite(value);
14
+ }
15
+ function hasValidRect(value) {
16
+ if (!value || typeof value !== 'object')
17
+ return false;
18
+ const r = value;
19
+ return ['x', 'y', 'width', 'height'].every((k) => isFiniteNumber(r[k]));
20
+ }
21
+ function nonEmptyString(value) {
22
+ return typeof value === 'string' && value.length > 0;
23
+ }
24
+ function inspectLayers(nodes, rootId) {
25
+ const ids = new Set();
26
+ let duplicateIds = 0;
27
+ let badRects = 0;
28
+ let exportables = 0;
29
+ for (const node of nodes) {
30
+ if (!nonEmptyString(node.object_id))
31
+ continue;
32
+ if (ids.has(node.object_id))
33
+ duplicateIds += 1;
34
+ else
35
+ ids.add(node.object_id);
36
+ if (!hasValidRect(node.rect))
37
+ badRects += 1;
38
+ if (node.exportable === true)
39
+ exportables += 1;
40
+ }
41
+ const parentRoots = new Set(ids);
42
+ if (nonEmptyString(rootId))
43
+ parentRoots.add(rootId);
44
+ let orphanParents = 0;
45
+ for (const node of nodes) {
46
+ if (nonEmptyString(node.parent_id) && !parentRoots.has(node.parent_id))
47
+ orphanParents += 1;
48
+ }
49
+ return { duplicateIds, orphanParents, badRects, exportables, ids };
50
+ }
51
+ export function inspectSharingDetail(detail) {
52
+ const warnings = [];
53
+ const designs = Array.isArray(detail.designs) ? detail.designs : [];
54
+ const screens = designs.flatMap((d) => (Array.isArray(d?.screens) ? d.screens : []));
55
+ let missingMetaUrl = 0;
56
+ let missingSlicesUrl = 0;
57
+ const seen = new Set();
58
+ let duplicateScreenIds = 0;
59
+ for (const s of screens) {
60
+ if (!nonEmptyString(s?.meta_url))
61
+ missingMetaUrl += 1;
62
+ if (!nonEmptyString(s?.slices_url))
63
+ missingSlicesUrl += 1;
64
+ const key = `${s?.id ?? ''}:${s?.object_id ?? ''}`;
65
+ if (seen.has(key))
66
+ duplicateScreenIds += 1;
67
+ else
68
+ seen.add(key);
69
+ }
70
+ if (designs.length === 0 || screens.length === 0) {
71
+ warnings.push(issue('SHARING_EMPTY', 'sharing has no designs or screens'));
72
+ }
73
+ if (missingMetaUrl > 0) {
74
+ warnings.push(issue('SHARING_META_URL_MISSING', 'some screens have no meta_url', { missingMetaUrl }));
75
+ }
76
+ if (missingSlicesUrl > 0) {
77
+ warnings.push(issue('WARN_SLICES_URL_MISSING', 'some screens have no slices_url', { missingSlicesUrl }));
78
+ }
79
+ if (duplicateScreenIds > 0) {
80
+ warnings.push(issue('WARN_DUPLICATE_SCREEN', 'duplicate screen id/object_id pairs', { duplicateScreenIds }));
81
+ }
82
+ return report({ designs: designs.length, screens: screens.length, missingMetaUrl, missingSlicesUrl, duplicateScreenIds }, warnings);
83
+ }
84
+ export function inspectSpec(spec) {
85
+ const warnings = [];
86
+ const layers = Array.isArray(spec.layers) ? spec.layers : [];
87
+ const groups = Array.isArray(spec.groups) ? spec.groups : [];
88
+ const all = [...layers, ...groups];
89
+ const nodes = inspectLayers(all, spec.object_id);
90
+ const cssCount = Array.isArray(spec.css) ? spec.css.length : typeof spec.css === 'string' ? 1 : 0;
91
+ if (!nonEmptyString(spec.object_id)) {
92
+ warnings.push(issue('SPEC_OBJECT_ID_MISSING', 'spec.object_id is missing'));
93
+ }
94
+ if (!nonEmptyString(spec.name)) {
95
+ warnings.push(issue('SPEC_NAME_MISSING', 'spec.name is missing'));
96
+ }
97
+ if (!isFiniteNumber(spec.width) || spec.width <= 0 || !isFiniteNumber(spec.height) || spec.height <= 0) {
98
+ warnings.push(issue('SPEC_SIZE_INVALID', 'spec width/height must be positive finite numbers', {
99
+ width: spec.width,
100
+ height: spec.height,
101
+ }));
102
+ }
103
+ if (!hasValidRect(spec.rect)) {
104
+ warnings.push(issue('SPEC_RECT_INVALID', 'spec.rect is missing or malformed'));
105
+ }
106
+ if (all.length === 0) {
107
+ warnings.push(issue('SPEC_EMPTY', 'spec has neither layers nor groups'));
108
+ }
109
+ if (nodes.duplicateIds > 0) {
110
+ warnings.push(issue('SPEC_DUPLICATE_OBJECT_ID', 'spec contains duplicate layer object_ids', {
111
+ duplicateIds: nodes.duplicateIds,
112
+ }));
113
+ }
114
+ if (nodes.badRects > 0) {
115
+ warnings.push(issue('SPEC_BAD_RECT', 'spec contains layers with malformed rect', {
116
+ badRects: nodes.badRects,
117
+ }));
118
+ }
119
+ if (nodes.orphanParents > 0) {
120
+ warnings.push(issue('WARN_ORPHAN_PARENT', 'some layer parent_ids are not present in the spec', {
121
+ orphanParents: nodes.orphanParents,
122
+ }));
123
+ }
124
+ return report({
125
+ layers: layers.length,
126
+ groups: groups.length,
127
+ css: cssCount,
128
+ exportables: nodes.exportables,
129
+ duplicateIds: nodes.duplicateIds,
130
+ badRects: nodes.badRects,
131
+ orphanParents: nodes.orphanParents,
132
+ }, warnings);
133
+ }
134
+ export function inspectManifest(manifest) {
135
+ const warnings = [];
136
+ const items = Array.isArray(manifest) ? manifest : [];
137
+ let exportables = 0;
138
+ let missingUrl = 0;
139
+ let badRect = 0;
140
+ let withByteHint = 0;
141
+ const keys = new Map();
142
+ for (const item of items) {
143
+ if (!nonEmptyString(item?.object_id)) {
144
+ warnings.push(issue('SLICE_OBJECT_ID_MISSING', 'slice item has no object_id'));
145
+ }
146
+ if (!Array.isArray(item?.exportables)) {
147
+ warnings.push(issue('SLICE_EXPORTABLES_INVALID', 'slice item has no exportables array', {
148
+ objectId: item?.object_id,
149
+ }));
150
+ continue;
151
+ }
152
+ if (!hasValidRect(item.rect))
153
+ badRect += 1;
154
+ for (const e of item.exportables) {
155
+ exportables += 1;
156
+ if (!nonEmptyString(e?.screenshot?.url))
157
+ missingUrl += 1;
158
+ const length = e?.screenshot?.length;
159
+ const size = e?.screenshot?.size;
160
+ if ((isFiniteNumber(length) && length > 0) || (isFiniteNumber(size) && size > 0))
161
+ withByteHint += 1;
162
+ const key = `${item.object_id}|${e?.format ?? ''}|${e?.scale ?? ''}`;
163
+ keys.set(key, (keys.get(key) ?? 0) + 1);
164
+ }
165
+ }
166
+ let duplicateExports = 0;
167
+ for (const count of keys.values())
168
+ if (count > 1)
169
+ duplicateExports += count - 1;
170
+ if (items.length === 0) {
171
+ warnings.push(issue('SLICE_MANIFEST_EMPTY', 'slice manifest is empty'));
172
+ }
173
+ if (missingUrl > 0) {
174
+ warnings.push(issue('SLICE_URL_MISSING', 'some exportables have no screenshot.url', { missingUrl }));
175
+ }
176
+ if (badRect > 0) {
177
+ warnings.push(issue('WARN_SLICE_RECT_INVALID', 'some slice items have malformed rect', { badRect }));
178
+ }
179
+ if (duplicateExports > 0) {
180
+ warnings.push(issue('WARN_DUPLICATE_EXPORT', 'duplicate object_id/format/scale combinations', {
181
+ duplicateExports,
182
+ }));
183
+ }
184
+ return report({ items: items.length, exportables, missingUrl, withByteHint, duplicateExports, badRect }, warnings);
185
+ }
186
+ export function enforceIntegrity(report, code) {
187
+ if (!report.ok || (config.integrityStrict && report.warnings.length > 0)) {
188
+ throw new CodesignError(code, 'remote data failed integrity check', {
189
+ issues: report.warnings,
190
+ stats: report.stats,
191
+ strict: config.integrityStrict,
192
+ });
193
+ }
194
+ }
195
+ export function integrityView(report) {
196
+ return { ok: report.ok, warnings: report.warnings, stats: report.stats };
197
+ }
@@ -0,0 +1,57 @@
1
+ import { config } from '../config.js';
2
+ import { CodesignError } from './errors.js';
3
+ import { assertAllowedRemoteUrl, normalizeCodesignAssetUrl } from '../utils/url.js';
4
+ import { throttle } from '../utils/rate-limit.js';
5
+ import { assertNotRateLimited, withRetry } from '../utils/retry.js';
6
+ // CDN 资源在 HAR 中无 cookie 依赖,可直接 Node fetch。
7
+ // 加一个 User-Agent 避免被 CDN 防火墙误判。
8
+ const DEFAULT_HEADERS = {
9
+ 'User-Agent': 'Mozilla/5.0 (CodesignMcp/0.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
10
+ Accept: 'application/json,text/plain,*/*',
11
+ };
12
+ export async function fetchMetaJson(url) {
13
+ if (!url || typeof url !== 'string') {
14
+ throw new CodesignError('META_FETCH_FAILED', 'meta url is empty');
15
+ }
16
+ const remoteUrl = normalizeCodesignAssetUrl(url);
17
+ assertAllowedRemoteUrl(remoteUrl, 'meta');
18
+ try {
19
+ const resp = await withRetry(async () => {
20
+ await throttle(remoteUrl);
21
+ const controller = new AbortController();
22
+ const timer = setTimeout(() => controller.abort(), config.metaTimeoutMs);
23
+ try {
24
+ const response = await fetch(remoteUrl, { headers: DEFAULT_HEADERS, signal: controller.signal });
25
+ assertNotRateLimited(response.status, 'meta request', response.headers.get('retry-after'));
26
+ return response;
27
+ }
28
+ finally {
29
+ clearTimeout(timer);
30
+ }
31
+ });
32
+ if (!resp.ok) {
33
+ throw new CodesignError('META_FETCH_FAILED', `meta fetch failed: HTTP ${resp.status}`, {
34
+ url: remoteUrl,
35
+ status: resp.status,
36
+ });
37
+ }
38
+ const text = await resp.text();
39
+ try {
40
+ return JSON.parse(text);
41
+ }
42
+ catch (err) {
43
+ throw new CodesignError('META_SCHEMA_MISMATCH', 'meta body is not valid JSON', {
44
+ url: remoteUrl,
45
+ snippet: text.slice(0, 200),
46
+ parseError: err.message,
47
+ });
48
+ }
49
+ }
50
+ catch (err) {
51
+ if (err instanceof CodesignError)
52
+ throw err;
53
+ throw new CodesignError('META_FETCH_FAILED', `meta fetch threw: ${err.message}`, {
54
+ url: remoteUrl,
55
+ });
56
+ }
57
+ }