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,56 @@
1
+ import { CodesignError } from './errors.js';
2
+ import { buildSpecHierarchy } from './selection.js';
3
+ // 浅校验 spec object 顶层 schema,符合 HAR 实测。
4
+ export function assertSpecObject(raw) {
5
+ if (raw == null || typeof raw !== 'object' || Array.isArray(raw)) {
6
+ throw new CodesignError('META_SCHEMA_MISMATCH', 'spec is not a plain object');
7
+ }
8
+ const r = raw;
9
+ for (const k of ['object_id', 'name', 'rect']) {
10
+ if (r[k] == null) {
11
+ throw new CodesignError('META_SCHEMA_MISMATCH', `spec missing required field: ${k}`, {
12
+ topKeys: Object.keys(r),
13
+ });
14
+ }
15
+ }
16
+ if (r.layers != null && !Array.isArray(r.layers)) {
17
+ throw new CodesignError('META_SCHEMA_MISMATCH', 'spec.layers is not an array');
18
+ }
19
+ if (r.groups != null && !Array.isArray(r.groups)) {
20
+ throw new CodesignError('META_SCHEMA_MISMATCH', 'spec.groups is not an array');
21
+ }
22
+ if (r.css != null && !Array.isArray(r.css) && typeof r.css !== 'string') {
23
+ throw new CodesignError('META_SCHEMA_MISMATCH', 'spec.css must be array or string');
24
+ }
25
+ }
26
+ export function normalizeSpec(spec, slices = [], platformSpec) {
27
+ const normalized = {
28
+ hierarchy: buildSpecHierarchy(spec.layers ?? [], spec.groups ?? [], spec.rect),
29
+ artboard: {
30
+ objectId: spec.object_id,
31
+ name: spec.name,
32
+ pageId: spec.page_id,
33
+ pageName: spec.page_name,
34
+ width: spec.width,
35
+ height: spec.height,
36
+ rect: spec.rect,
37
+ },
38
+ layers: (spec.layers ?? []).map(passthroughLayer),
39
+ groups: (spec.groups ?? []).map(passthroughLayer),
40
+ css: Array.isArray(spec.css) ? spec.css : spec.css ? [spec.css] : [],
41
+ slices,
42
+ };
43
+ if (platformSpec)
44
+ normalized.platformSpec = platformSpec;
45
+ return normalized;
46
+ }
47
+ // 按 objectId 在 layers + groups 中查找。
48
+ export function findLayerByObjectId(spec, objectId) {
49
+ const all = [...spec.layers, ...spec.groups];
50
+ return all.find((l) => l.object_id === objectId);
51
+ }
52
+ // HAR 实测字段保留 snake_case + 文本字段(content/fontSize/...)按存在性透出
53
+ function passthroughLayer(layer) {
54
+ // 这里不主动改名,直接透传。归一化由调用方按需做(避免吞掉新字段)。
55
+ return layer;
56
+ }
@@ -0,0 +1,232 @@
1
+ import { CodesignError } from './errors.js';
2
+ const PLATFORM_CONFIGS = [
3
+ {
4
+ id: 'raw',
5
+ label: 'Raw CoDesign',
6
+ unit: 'px',
7
+ aliases: ['raw', 'origin', 'original', 'source', '原始', '原始标注', '不转换'],
8
+ availableUnits: ['px'],
9
+ availableScales: [1],
10
+ },
11
+ {
12
+ id: 'web',
13
+ label: 'Web',
14
+ unit: 'px',
15
+ aliases: ['web', '网页', '前端', 'h5', 'pc', 'browser', '浏览器', 'css', 'html'],
16
+ availableUnits: ['px', 'rem'],
17
+ availableScales: [0.5, 1, 2, 3],
18
+ },
19
+ {
20
+ id: 'android',
21
+ label: 'Android',
22
+ unit: 'dp',
23
+ aliases: ['android', '安卓', '安卓端', 'android端', 'android app'],
24
+ availableUnits: ['dp', 'px'],
25
+ availableScales: [0.25, 0.5, 1, 2, 3, 4],
26
+ },
27
+ {
28
+ id: 'ios',
29
+ label: 'iOS',
30
+ unit: 'pt',
31
+ aliases: ['ios', 'iphone', 'ipad', '苹果', '苹果端', 'ios端', 'swift', 'uikit'],
32
+ availableUnits: ['pt', 'px'],
33
+ availableScales: [0.5, 1, 2, 3],
34
+ },
35
+ {
36
+ id: 'wechat-miniprogram',
37
+ label: '微信小程序',
38
+ unit: 'rpx',
39
+ aliases: [
40
+ 'wechat-miniprogram',
41
+ 'wechat mini program',
42
+ 'wechat',
43
+ 'mini program',
44
+ 'miniprogram',
45
+ '微信小程序',
46
+ '小程序',
47
+ '微信',
48
+ 'wx',
49
+ 'rpx',
50
+ ],
51
+ availableUnits: ['rpx'],
52
+ availableScales: [0.5, 1, 2],
53
+ },
54
+ {
55
+ id: 'other',
56
+ label: '其它平台',
57
+ unit: 'px',
58
+ aliases: ['other', 'others', '其它平台', '其他平台', '其它', '其他', 'custom', '自定义'],
59
+ availableUnits: ['px'],
60
+ availableScales: [0.5, 1, 2, 3],
61
+ },
62
+ ];
63
+ const PLATFORM_BY_ID = new Map(PLATFORM_CONFIGS.map((config) => [config.id, config]));
64
+ const DEFAULT_REM_BASE_PX = 16;
65
+ export function normalizeTargetPlatform(input) {
66
+ if (input == null || input.trim() === '')
67
+ return undefined;
68
+ const normalized = normalizePlatformText(input);
69
+ for (const config of PLATFORM_CONFIGS) {
70
+ if (config.id === normalized || config.aliases.some((alias) => normalizePlatformText(alias) === normalized)) {
71
+ return config.id;
72
+ }
73
+ }
74
+ throw new CodesignError('INVALID_PLATFORM', 'unsupported targetPlatform', {
75
+ targetPlatform: input,
76
+ supported: supportedTargetPlatforms(),
77
+ });
78
+ }
79
+ export function buildPlatformSpec(spec, requestedPlatform, options = {}) {
80
+ const id = normalizeTargetPlatform(requestedPlatform);
81
+ if (!id) {
82
+ throw new CodesignError('INVALID_PLATFORM', 'targetPlatform is empty', { targetPlatform: requestedPlatform });
83
+ }
84
+ const config = getPlatformConfig(id);
85
+ const unit = normalizeTargetUnit(options.targetUnit, config);
86
+ const conversion = resolveConversion(spec, unit, options);
87
+ const scale = conversion.scale;
88
+ return {
89
+ requested: requestedPlatform,
90
+ id,
91
+ label: config.label,
92
+ unit,
93
+ scale,
94
+ conversion: conversion.metadata,
95
+ availableUnits: config.availableUnits,
96
+ availableScales: config.availableScales,
97
+ source: {
98
+ kind: 'codesign-meta-url',
99
+ note: 'CoDesign platform selection is a client-side presentation over the same meta_url data; no platform-specific meta endpoint is fetched.',
100
+ },
101
+ artboard: {
102
+ objectId: spec.object_id,
103
+ name: spec.name,
104
+ width: convertNumber(spec.width, scale, conversion.remDivisor),
105
+ height: convertNumber(spec.height, scale, conversion.remDivisor),
106
+ unit,
107
+ rect: convertRect(spec.rect, unit, scale, conversion.remDivisor),
108
+ },
109
+ layers: (spec.layers ?? []).map((layer) => convertLayer(layer, unit, scale, conversion.remDivisor)),
110
+ groups: (spec.groups ?? []).map((layer) => convertLayer(layer, unit, scale, conversion.remDivisor)),
111
+ css: convertCssList(spec.css, unit, scale, conversion.remDivisor),
112
+ };
113
+ }
114
+ export function supportedTargetPlatforms() {
115
+ return PLATFORM_CONFIGS.map((config) => ({
116
+ id: config.id,
117
+ label: config.label,
118
+ unit: config.unit,
119
+ availableUnits: [...config.availableUnits],
120
+ availableScales: [...config.availableScales],
121
+ aliases: [...config.aliases],
122
+ }));
123
+ }
124
+ function getPlatformConfig(id) {
125
+ const config = PLATFORM_BY_ID.get(id);
126
+ if (!config) {
127
+ throw new CodesignError('INVALID_PLATFORM', 'unsupported targetPlatform', { targetPlatform: id });
128
+ }
129
+ return config;
130
+ }
131
+ function normalizeTargetUnit(input, config) {
132
+ if (input == null || input.trim() === '')
133
+ return config.unit;
134
+ const normalized = normalizeUnitText(input);
135
+ if (!config.availableUnits.includes(normalized)) {
136
+ throw new CodesignError('INVALID_PLATFORM', 'targetUnit is not supported for targetPlatform', {
137
+ targetUnit: input,
138
+ targetPlatform: config.id,
139
+ supportedUnits: config.availableUnits,
140
+ });
141
+ }
142
+ return normalized;
143
+ }
144
+ function resolveConversion(spec, unit, options) {
145
+ const hasCustomScale = options.customScale != null;
146
+ const hasCustomWidth = options.customWidth != null;
147
+ if (hasCustomScale && hasCustomWidth) {
148
+ throw new CodesignError('INVALID_PLATFORM', 'customScale and customWidth cannot both be set', {
149
+ customScale: options.customScale,
150
+ customWidth: options.customWidth,
151
+ });
152
+ }
153
+ let scale = 1;
154
+ const metadata = {
155
+ mode: 'default',
156
+ sourceWidth: spec.width,
157
+ };
158
+ if (hasCustomScale) {
159
+ scale = assertPositiveNumber(options.customScale, 'customScale');
160
+ metadata.mode = 'custom-scale';
161
+ metadata.customScale = scale;
162
+ }
163
+ else if (hasCustomWidth) {
164
+ const customWidth = assertPositiveNumber(options.customWidth, 'customWidth');
165
+ scale = customWidth / spec.width;
166
+ metadata.mode = 'custom-width';
167
+ metadata.customWidth = customWidth;
168
+ }
169
+ let remDivisor = 1;
170
+ if (unit === 'rem') {
171
+ remDivisor = options.remBasePx == null ? DEFAULT_REM_BASE_PX : assertPositiveNumber(options.remBasePx, 'remBasePx');
172
+ metadata.remBasePx = remDivisor;
173
+ metadata.remBasePxSource = options.remBasePx == null ? 'default' : 'explicit';
174
+ }
175
+ return { scale, remDivisor, metadata };
176
+ }
177
+ function convertLayer(layer, unit, scale, remDivisor) {
178
+ return {
179
+ objectId: layer.object_id,
180
+ name: layer.name,
181
+ type: layer.type,
182
+ rect: convertRect(layer.rect, unit, scale, remDivisor),
183
+ css: convertCssList(layer.css, unit, scale, remDivisor),
184
+ };
185
+ }
186
+ function convertRect(rect, unit, scale, remDivisor) {
187
+ return {
188
+ x: convertNumber(rect.x, scale, remDivisor),
189
+ y: convertNumber(rect.y, scale, remDivisor),
190
+ width: convertNumber(rect.width, scale, remDivisor),
191
+ height: convertNumber(rect.height, scale, remDivisor),
192
+ unit,
193
+ };
194
+ }
195
+ function convertCssList(css, unit, scale, remDivisor) {
196
+ const list = Array.isArray(css) ? css : css ? [css] : [];
197
+ return list.map((line) => convertCssUnits(line, unit, scale, remDivisor));
198
+ }
199
+ function convertCssUnits(css, unit, scale, remDivisor) {
200
+ if (unit === 'px' && scale === 1)
201
+ return css;
202
+ return css.replace(/(-?\d+(?:\.\d+)?)px\b/g, (_match, raw) => {
203
+ const n = Number(raw);
204
+ if (!Number.isFinite(n))
205
+ return `${raw}${unit}`;
206
+ return `${formatNumber((n * scale) / remDivisor)}${unit}`;
207
+ });
208
+ }
209
+ function convertNumber(value, scale, remDivisor) {
210
+ return Number(formatNumber((value * scale) / remDivisor));
211
+ }
212
+ function assertPositiveNumber(value, name) {
213
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
214
+ throw new CodesignError('INVALID_PLATFORM', `${name} must be a positive number`, { [name]: value });
215
+ }
216
+ return value;
217
+ }
218
+ function formatNumber(value) {
219
+ if (Number.isInteger(value))
220
+ return String(value);
221
+ return value.toFixed(2).replace(/\.?0+$/, '');
222
+ }
223
+ function normalizeUnitText(value) {
224
+ return value.trim().toLowerCase().replace(/\s+/g, '');
225
+ }
226
+ function normalizePlatformText(value) {
227
+ return value
228
+ .trim()
229
+ .toLowerCase()
230
+ .replace(/[\s_\-]+/g, '')
231
+ .replace(/[::,,。.!!]/g, '');
232
+ }
@@ -0,0 +1,205 @@
1
+ import { CodesignError } from './errors.js';
2
+ export const LAYER_SELECTION_SCOPES = ['layer', 'subtree', 'region'];
3
+ export function buildLayerSelection(spec, rootObjectId, scope) {
4
+ const entries = indexLayers(spec);
5
+ const byId = new Map(entries.map((entry) => [entry.value.object_id, entry]));
6
+ const rootEntry = byId.get(rootObjectId);
7
+ if (!rootEntry)
8
+ return undefined;
9
+ const childrenByParent = buildChildrenIndex(entries);
10
+ const selectedIds = selectObjectIds(rootEntry, scope, entries, byId, childrenByParent);
11
+ const selectedEntries = entries.filter((entry) => selectedIds.has(entry.value.object_id));
12
+ const orderedEntries = [...selectedEntries].sort(compareEntries);
13
+ const bounds = copyRect(rootEntry.value.rect);
14
+ const selectedLayers = orderedEntries
15
+ .filter((entry) => entry.kind === 'layer')
16
+ .map((entry) => withRelativeRect(entry.value, bounds));
17
+ const selectedGroups = orderedEntries
18
+ .filter((entry) => entry.kind === 'group')
19
+ .map((entry) => withRelativeRect(entry.value, bounds));
20
+ const hierarchy = buildHierarchy(orderedEntries, bounds);
21
+ return {
22
+ scope,
23
+ rootObjectId,
24
+ rootName: rootEntry.value.name,
25
+ bounds,
26
+ nodeCount: selectedEntries.length,
27
+ layerCount: selectedLayers.length,
28
+ groupCount: selectedGroups.length,
29
+ root: withRelativeRect(rootEntry.value, bounds),
30
+ layers: selectedLayers,
31
+ groups: selectedGroups,
32
+ hierarchy,
33
+ };
34
+ }
35
+ // 整页还原用的完整层级树:parent_id 指向画板本身(不在 layers/groups 中)的节点即为根。
36
+ // 与 buildLayerSelection 复用同一套索引与排序逻辑,relativeRect 相对画板,
37
+ // relativeToParent 相对直接父节点,便于直接映射成 CSS 定位。
38
+ export function buildSpecHierarchy(layers, groups, artboardRect) {
39
+ const entries = [];
40
+ const seen = new Set();
41
+ const append = (values, kind) => {
42
+ for (const value of values) {
43
+ if (seen.has(value.object_id)) {
44
+ throw new CodesignError('META_SCHEMA_MISMATCH', 'duplicate layer object_id', {
45
+ objectId: value.object_id,
46
+ });
47
+ }
48
+ seen.add(value.object_id);
49
+ entries.push({ kind, sourceOrder: entries.length, value });
50
+ }
51
+ };
52
+ append(layers, 'layer');
53
+ append(groups, 'group');
54
+ return buildHierarchy(entries, artboardRect);
55
+ }
56
+ function indexLayers(spec) {
57
+ const entries = [];
58
+ const seen = new Set();
59
+ const append = (values, kind) => {
60
+ for (const value of values) {
61
+ if (seen.has(value.object_id)) {
62
+ throw new CodesignError('META_SCHEMA_MISMATCH', 'duplicate layer object_id', {
63
+ objectId: value.object_id,
64
+ });
65
+ }
66
+ seen.add(value.object_id);
67
+ entries.push({ kind, sourceOrder: entries.length, value });
68
+ }
69
+ };
70
+ append(spec.layers, 'layer');
71
+ append(spec.groups, 'group');
72
+ return entries;
73
+ }
74
+ function buildChildrenIndex(entries) {
75
+ const childrenByParent = new Map();
76
+ for (const entry of entries) {
77
+ const children = childrenByParent.get(entry.value.parent_id) ?? [];
78
+ children.push(entry);
79
+ childrenByParent.set(entry.value.parent_id, children);
80
+ }
81
+ for (const children of childrenByParent.values())
82
+ children.sort(compareEntries);
83
+ return childrenByParent;
84
+ }
85
+ function selectObjectIds(root, scope, entries, byId, childrenByParent) {
86
+ if (scope === 'layer')
87
+ return new Set([root.value.object_id]);
88
+ if (scope === 'subtree')
89
+ return collectSubtreeIds(root, childrenByParent);
90
+ const ancestorIds = collectAncestorIds(root, byId);
91
+ const selected = new Set();
92
+ for (const entry of entries) {
93
+ if (ancestorIds.has(entry.value.object_id))
94
+ continue;
95
+ if (rectContains(root.value.rect, entry.value.rect))
96
+ selected.add(entry.value.object_id);
97
+ }
98
+ selected.add(root.value.object_id);
99
+ return selected;
100
+ }
101
+ function collectSubtreeIds(root, childrenByParent) {
102
+ const selected = new Set();
103
+ const stack = [root];
104
+ while (stack.length > 0) {
105
+ const current = stack.pop();
106
+ const objectId = current.value.object_id;
107
+ if (selected.has(objectId)) {
108
+ throw new CodesignError('META_SCHEMA_MISMATCH', 'layer hierarchy contains a cycle', {
109
+ objectId,
110
+ });
111
+ }
112
+ selected.add(objectId);
113
+ stack.push(...(childrenByParent.get(objectId) ?? []));
114
+ }
115
+ return selected;
116
+ }
117
+ function collectAncestorIds(root, byId) {
118
+ const ancestors = new Set();
119
+ let parentId = root.value.parent_id;
120
+ while (byId.has(parentId)) {
121
+ if (ancestors.has(parentId)) {
122
+ throw new CodesignError('META_SCHEMA_MISMATCH', 'layer hierarchy contains a cycle', {
123
+ objectId: root.value.object_id,
124
+ parentId,
125
+ });
126
+ }
127
+ ancestors.add(parentId);
128
+ parentId = byId.get(parentId).value.parent_id;
129
+ }
130
+ return ancestors;
131
+ }
132
+ function buildHierarchy(entries, bounds) {
133
+ const selectedIds = new Set(entries.map((entry) => entry.value.object_id));
134
+ const childrenByParent = buildChildrenIndex(entries);
135
+ const roots = entries
136
+ .filter((entry) => !selectedIds.has(entry.value.parent_id))
137
+ .sort(compareEntries);
138
+ const builtIds = new Set();
139
+ const buildNode = (entry, ancestors, parentRect) => {
140
+ const objectId = entry.value.object_id;
141
+ if (ancestors.has(objectId)) {
142
+ throw new CodesignError('META_SCHEMA_MISMATCH', 'selected layer hierarchy contains a cycle', {
143
+ objectId,
144
+ });
145
+ }
146
+ const nextAncestors = new Set(ancestors);
147
+ nextAncestors.add(objectId);
148
+ builtIds.add(objectId);
149
+ return {
150
+ objectId,
151
+ parentId: entry.value.parent_id,
152
+ name: entry.value.name,
153
+ type: entry.value.type,
154
+ kind: entry.kind,
155
+ rect: copyRect(entry.value.rect),
156
+ relativeRect: relativeRect(entry.value.rect, bounds),
157
+ relativeToParent: relativeRect(entry.value.rect, parentRect),
158
+ children: (childrenByParent.get(objectId) ?? []).map((child) => buildNode(child, nextAncestors, entry.value.rect)),
159
+ };
160
+ };
161
+ const hierarchy = roots.map((root) => buildNode(root, new Set(), bounds));
162
+ if (builtIds.size !== entries.length) {
163
+ throw new CodesignError('META_SCHEMA_MISMATCH', 'selected layer hierarchy has no valid root', {
164
+ selectedCount: entries.length,
165
+ reachableCount: builtIds.size,
166
+ });
167
+ }
168
+ return hierarchy;
169
+ }
170
+ function compareEntries(a, b) {
171
+ const aIndex = typeof a.value.layerIndex === 'number' ? a.value.layerIndex : undefined;
172
+ const bIndex = typeof b.value.layerIndex === 'number' ? b.value.layerIndex : undefined;
173
+ if (aIndex != null && bIndex != null && aIndex !== bIndex)
174
+ return aIndex - bIndex;
175
+ if (aIndex != null && bIndex == null)
176
+ return -1;
177
+ if (aIndex == null && bIndex != null)
178
+ return 1;
179
+ return a.sourceOrder - b.sourceOrder;
180
+ }
181
+ function withRelativeRect(layer, bounds) {
182
+ return {
183
+ ...layer,
184
+ rect: copyRect(layer.rect),
185
+ relativeRect: relativeRect(layer.rect, bounds),
186
+ };
187
+ }
188
+ function relativeRect(rect, bounds) {
189
+ return {
190
+ x: rect.x - bounds.x,
191
+ y: rect.y - bounds.y,
192
+ width: rect.width,
193
+ height: rect.height,
194
+ };
195
+ }
196
+ function rectContains(bounds, candidate) {
197
+ const epsilon = 0.01;
198
+ return (candidate.x >= bounds.x - epsilon &&
199
+ candidate.y >= bounds.y - epsilon &&
200
+ candidate.x + candidate.width <= bounds.x + bounds.width + epsilon &&
201
+ candidate.y + candidate.height <= bounds.y + bounds.height + epsilon);
202
+ }
203
+ function copyRect(rect) {
204
+ return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
205
+ }
@@ -0,0 +1,153 @@
1
+ import { config } from '../config.js';
2
+ import { getLogger } from '../logger.js';
3
+ import { requestJson } from '../utils/http.js';
4
+ import { CodesignError } from './errors.js';
5
+ import { probeLoggedIn } from '../browser/session.js';
6
+ const log = getLogger();
7
+ // POST /api/sharings/:id/state-keys
8
+ export async function exchangePassword(page, sharingId, password) {
9
+ await ensureOnOrigin(page, sharingId);
10
+ const resp = await requestJson(page.context().request, {
11
+ method: 'POST',
12
+ url: `${config.origin}/api/sharings/${sharingId}/state-keys`,
13
+ body: { password },
14
+ });
15
+ log.debug({ status: resp.status }, 'state-keys response');
16
+ if (resp.status === 200 && resp.body && typeof resp.body === 'object' && 'key' in resp.body) {
17
+ const body = resp.body;
18
+ return { key: body.key, expires: body.expires };
19
+ }
20
+ if (resp.status === 403) {
21
+ throw new CodesignError('INVALID_PASSWORD', 'Sharing password is incorrect', {
22
+ sharingId,
23
+ serverMessage: resp.body?.message,
24
+ });
25
+ }
26
+ if (resp.status === 401) {
27
+ throw new CodesignError('NEED_LOGIN', 'state-keys requires login', { sharingId });
28
+ }
29
+ if (resp.status === 404) {
30
+ throw new CodesignError('SHARING_NOT_FOUND', 'sharing not found', { sharingId });
31
+ }
32
+ throw new CodesignError('SHARING_NOT_FOUND', 'unexpected state-keys response', {
33
+ sharingId,
34
+ status: resp.status,
35
+ });
36
+ }
37
+ // GET /api/sharings/:id [state-key header]
38
+ export async function fetchSharingDetail(page, sharingId, stateKey) {
39
+ await ensureOnOrigin(page, sharingId);
40
+ const headers = {};
41
+ if (stateKey)
42
+ headers['state-key'] = stateKey;
43
+ const resp = await requestJson(page.context().request, {
44
+ url: `${config.origin}/api/sharings/${sharingId}`,
45
+ headers,
46
+ });
47
+ log.debug({ status: resp.status, hasStateKey: !!stateKey }, 'sharing-detail response');
48
+ if (resp.status === 200) {
49
+ return normalizeSharingDetail(resp.body, { sharingId, status: resp.status });
50
+ }
51
+ if (resp.status === 403) {
52
+ // 没有 state-key 通常意味着需要密码
53
+ throw new CodesignError('NEED_PASSWORD', 'this sharing requires a password', {
54
+ sharingId,
55
+ sharing_title: resp.body?.context?.sharing_title,
56
+ });
57
+ }
58
+ if (resp.status === 401) {
59
+ throw new CodesignError('NEED_LOGIN', 'sharing requires login', { sharingId });
60
+ }
61
+ if (resp.status === 404) {
62
+ throw new CodesignError('SHARING_NOT_FOUND', 'sharing not found', { sharingId });
63
+ }
64
+ throw new CodesignError('SHARING_NOT_FOUND', 'unexpected sharing-detail response', {
65
+ sharingId,
66
+ status: resp.status,
67
+ });
68
+ }
69
+ export function normalizeSharingDetail(body, errorDetails) {
70
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
71
+ throw unexpectedSharingDetail(errorDetails);
72
+ }
73
+ const record = body;
74
+ if (Array.isArray(record.designs)) {
75
+ return body;
76
+ }
77
+ if (!Array.isArray(record.screens)) {
78
+ throw unexpectedSharingDetail(errorDetails);
79
+ }
80
+ const id = record.id;
81
+ if (typeof id !== 'number' || !Number.isSafeInteger(id)) {
82
+ throw unexpectedSharingDetail(errorDetails);
83
+ }
84
+ const title = firstNonEmptyString(record.title, record.name) ?? `Sharing ${id}`;
85
+ const designId = typeof record.design_id === 'number' && Number.isSafeInteger(record.design_id)
86
+ ? record.design_id
87
+ : id;
88
+ const designName = firstNonEmptyString(record.design_name, record.name, record.title) ?? title;
89
+ return {
90
+ id,
91
+ title,
92
+ designs: [
93
+ {
94
+ id: designId,
95
+ name: designName,
96
+ screens: record.screens,
97
+ },
98
+ ],
99
+ };
100
+ }
101
+ function unexpectedSharingDetail(details) {
102
+ return new CodesignError('SHARING_NOT_FOUND', 'unexpected sharing-detail response', details);
103
+ }
104
+ function firstNonEmptyString(...values) {
105
+ return values.find((value) => typeof value === 'string' && value.length > 0);
106
+ }
107
+ // 综合入口:根据 password 选择是否换 state-key,再拉 detail。
108
+ export async function getSharingDetail(page, sharingId, password) {
109
+ let stateKey;
110
+ if (password) {
111
+ const sk = await exchangePassword(page, sharingId, password);
112
+ stateKey = sk.key;
113
+ }
114
+ try {
115
+ const detail = await fetchSharingDetail(page, sharingId, stateKey);
116
+ return stateKey ? { detail, stateKey } : { detail };
117
+ }
118
+ catch (err) {
119
+ if (err instanceof CodesignError && err.code === 'NEED_PASSWORD' && !password) {
120
+ // 透传,让 tool 层处理
121
+ throw err;
122
+ }
123
+ throw err;
124
+ }
125
+ }
126
+ // 确保 page 在 codesign.qq.com 同源上下文。
127
+ // headless 工具共享同一个 page,并发调用会合并成一次导航。
128
+ const pendingNavigations = new WeakMap();
129
+ export async function ensureOnOrigin(page, sharingId) {
130
+ const current = page.url();
131
+ if (current.startsWith(config.origin))
132
+ return;
133
+ const pending = pendingNavigations.get(page);
134
+ if (pending)
135
+ return pending;
136
+ const target = `${config.origin}/app/s/${sharingId}`;
137
+ log.debug({ target }, 'navigating to sharing page for origin context');
138
+ const navigation = page
139
+ .goto(target, { waitUntil: 'domcontentloaded', timeout: config.navTimeoutMs })
140
+ .then(() => undefined)
141
+ .finally(() => {
142
+ pendingNavigations.delete(page);
143
+ });
144
+ pendingNavigations.set(page, navigation);
145
+ return navigation;
146
+ }
147
+ // 检查是否需要登录(探测 /api/user 的便捷封装)
148
+ export async function ensureLoggedInOrThrow(page) {
149
+ const probe = await probeLoggedIn(page);
150
+ if (!probe.loggedIn) {
151
+ throw new CodesignError('NEED_LOGIN', 'user is not logged in', { status: probe.status });
152
+ }
153
+ }
@@ -0,0 +1,34 @@
1
+ import { fetchMetaJson } from './meta.js';
2
+ import { CodesignError } from './errors.js';
3
+ export async function fetchSliceManifest(slicesUrl) {
4
+ const raw = await fetchMetaJson(slicesUrl);
5
+ if (!Array.isArray(raw)) {
6
+ throw new CodesignError('META_SCHEMA_MISMATCH', 'slice manifest is not an array', {
7
+ url: slicesUrl,
8
+ typeOf: typeof raw,
9
+ });
10
+ }
11
+ // 浅校验每项必须有 object_id + exportables
12
+ for (let i = 0; i < raw.length; i++) {
13
+ const item = raw[i];
14
+ if (!item || typeof item !== 'object') {
15
+ throw new CodesignError('META_SCHEMA_MISMATCH', `slice item #${i} is not an object`, {
16
+ url: slicesUrl,
17
+ });
18
+ }
19
+ if (typeof item.object_id !== 'string') {
20
+ throw new CodesignError('META_SCHEMA_MISMATCH', `slice item #${i} missing object_id`, {
21
+ url: slicesUrl,
22
+ });
23
+ }
24
+ if (!Array.isArray(item.exportables)) {
25
+ throw new CodesignError('META_SCHEMA_MISMATCH', `slice item #${i} missing exportables`, {
26
+ url: slicesUrl,
27
+ });
28
+ }
29
+ }
30
+ return raw;
31
+ }
32
+ export function findSliceByObjectId(manifest, objectId) {
33
+ return manifest.find((s) => s.object_id === objectId);
34
+ }
@@ -0,0 +1 @@
1
+ export {};