@tempad-dev/mcp 0.8.0-alpha.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +46 -8
- package/README.zh-Hans.md +40 -7
- package/dist/cli.mjs +13 -2
- package/dist/cli.mjs.map +1 -1
- package/dist/hub.mjs +3047 -885
- package/dist/hub.mjs.map +1 -1
- package/dist/shared-8rz2qWXn.mjs +2513 -0
- package/dist/shared-8rz2qWXn.mjs.map +1 -0
- package/package.json +15 -14
- package/dist/shared-BM-k8yN9.mjs +0 -120
- package/dist/shared-BM-k8yN9.mjs.map +0 -1
|
@@ -0,0 +1,2513 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { closeSync, mkdirSync, openSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import pino from "pino";
|
|
6
|
+
//#region ../shared/dist/index.js
|
|
7
|
+
const MCP_PORT_CANDIDATES = [
|
|
8
|
+
6220,
|
|
9
|
+
7431,
|
|
10
|
+
8127
|
|
11
|
+
];
|
|
12
|
+
const TEMPAD_MCP_BRIDGE_SUBPROTOCOL = "tempad-mcp";
|
|
13
|
+
const TEMPAD_MCP_BRIDGE_SUPPORTED_PROTOCOL_VERSIONS = [13];
|
|
14
|
+
const MCP_MAX_PAYLOAD_BYTES = 4194304;
|
|
15
|
+
const MCP_TOOL_INLINE_BUDGET_BYTES = 65536;
|
|
16
|
+
const MCP_APPLY_CANVAS_RUNTIME_BUDGET_BYTES = 2048;
|
|
17
|
+
const MCP_TOOL_TIMEOUT_MS = 15e3;
|
|
18
|
+
const MCP_GET_CODE_TIMEOUT_MS = 3e4;
|
|
19
|
+
const MCP_GET_DESIGN_SYSTEM_TIMEOUT_MS = 45e3;
|
|
20
|
+
const MCP_APPLY_CANVAS_TIMEOUT_MS = 12e4;
|
|
21
|
+
const MCP_AUTO_ACTIVATE_GRACE_MS = 1500;
|
|
22
|
+
const MCP_MAX_ASSET_BYTES = 8388608;
|
|
23
|
+
const MCP_MAX_ASSET_STORE_BYTES = 268435456;
|
|
24
|
+
const MCP_ASSET_TTL_MS = 2592e6;
|
|
25
|
+
const MCP_HASH_PATTERN = new RegExp(`^(?:[a-f0-9]{64}|[a-f0-9]{8})$`);
|
|
26
|
+
const MCP_DESIGN_TASK_LEASE_MS = 3e5;
|
|
27
|
+
const DesignTaskIdSchema = z.string().min(1).max(128);
|
|
28
|
+
const DesignTaskParameterSchema = DesignTaskIdSchema.describe("Task id returned by begin_design. Pass it on every call belonging to that design task; omit for independent reads.").optional();
|
|
29
|
+
const FigmaSessionSchema = z.object({
|
|
30
|
+
sessionId: z.string().min(1),
|
|
31
|
+
fileKey: z.string().min(1).max(256),
|
|
32
|
+
fileName: z.string().max(256),
|
|
33
|
+
pageId: z.string().min(1),
|
|
34
|
+
busy: z.boolean(),
|
|
35
|
+
tabId: z.number().int().nonnegative().optional(),
|
|
36
|
+
documentId: z.string().min(1).optional()
|
|
37
|
+
}).strict();
|
|
38
|
+
const DesignTaskTargetSchema = FigmaSessionSchema.omit({
|
|
39
|
+
busy: true,
|
|
40
|
+
tabId: true,
|
|
41
|
+
documentId: true
|
|
42
|
+
});
|
|
43
|
+
const AgentClientKindSchema = z.enum([
|
|
44
|
+
"codex-app",
|
|
45
|
+
"codex-cli",
|
|
46
|
+
"codex",
|
|
47
|
+
"claude",
|
|
48
|
+
"other",
|
|
49
|
+
"unknown"
|
|
50
|
+
]);
|
|
51
|
+
const AGENT_CLIENTS = {
|
|
52
|
+
"codex-app": {
|
|
53
|
+
name: "Codex App",
|
|
54
|
+
feedback: true
|
|
55
|
+
},
|
|
56
|
+
"codex-cli": {
|
|
57
|
+
name: "Codex CLI",
|
|
58
|
+
feedback: false
|
|
59
|
+
},
|
|
60
|
+
codex: {
|
|
61
|
+
name: "Codex",
|
|
62
|
+
feedback: true
|
|
63
|
+
},
|
|
64
|
+
claude: {
|
|
65
|
+
name: "Claude",
|
|
66
|
+
feedback: false
|
|
67
|
+
},
|
|
68
|
+
other: {
|
|
69
|
+
name: "Agent",
|
|
70
|
+
feedback: false
|
|
71
|
+
},
|
|
72
|
+
unknown: {
|
|
73
|
+
name: "Agent",
|
|
74
|
+
feedback: false
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
const AgentClientSchema = z.object({
|
|
78
|
+
kind: AgentClientKindSchema,
|
|
79
|
+
name: z.string().min(1).max(80),
|
|
80
|
+
sessionId: z.string().min(1).max(256).optional()
|
|
81
|
+
}).strict();
|
|
82
|
+
const AgentCapabilitiesSchema = z.object({
|
|
83
|
+
interrupt: z.boolean(),
|
|
84
|
+
queue: z.boolean(),
|
|
85
|
+
steer: z.boolean(),
|
|
86
|
+
continue: z.boolean(),
|
|
87
|
+
queueDelivery: z.enum(["native", "turn-end"]).optional(),
|
|
88
|
+
steerDelivery: z.enum(["native", "next-tool"]).optional(),
|
|
89
|
+
reason: z.string().max(240).optional()
|
|
90
|
+
}).strict();
|
|
91
|
+
const DesignTaskEpochSchema = z.number().int().nonnegative().optional().describe("Lease epoch returned by begin_design or resume_design. Required after resuming; stale epochs cannot write.");
|
|
92
|
+
const MCP_DESIGN_FEEDBACK_MAX_TEXT = 32e3;
|
|
93
|
+
const FeedbackCommentSchema = z.string().trim().max(8e3);
|
|
94
|
+
const DesignFeedbackItemSchema = z.object({
|
|
95
|
+
nodeId: z.string().min(1).max(128),
|
|
96
|
+
nodeName: z.string().max(256),
|
|
97
|
+
pageId: z.string().min(1).max(256),
|
|
98
|
+
pageName: z.string().max(256).optional(),
|
|
99
|
+
frame: z.object({
|
|
100
|
+
nodeId: z.string().min(1).max(128),
|
|
101
|
+
nodeName: z.string().max(256)
|
|
102
|
+
}).strict().optional(),
|
|
103
|
+
text: z.string().trim().min(1).max(8e3),
|
|
104
|
+
createdAt: z.number().finite().nonnegative()
|
|
105
|
+
}).strict();
|
|
106
|
+
const DesignFeedbackSchema = z.object({
|
|
107
|
+
id: z.string().uuid(),
|
|
108
|
+
mode: z.enum([
|
|
109
|
+
"queue",
|
|
110
|
+
"steer",
|
|
111
|
+
"continue"
|
|
112
|
+
]),
|
|
113
|
+
fileKey: z.string().min(1).max(256),
|
|
114
|
+
comment: FeedbackCommentSchema.min(1).optional(),
|
|
115
|
+
items: z.array(DesignFeedbackItemSchema).max(20),
|
|
116
|
+
createdAt: z.number().finite().nonnegative()
|
|
117
|
+
}).strict().refine((value) => value.items.length > 0 || !!value.comment, { message: "Add a general comment or at least one element comment." }).refine((value) => new Set(value.items.map((item) => item.nodeId)).size === value.items.length, { message: "Each element can appear only once in a feedback batch." }).refine((value) => value.items.reduce((length, item) => length + item.text.length, value.comment?.length ?? 0) <= MCP_DESIGN_FEEDBACK_MAX_TEXT, { message: "The feedback batch is too long." });
|
|
118
|
+
const FeedbackDraftScopeSchema = z.object({
|
|
119
|
+
taskId: DesignTaskIdSchema,
|
|
120
|
+
fileKey: z.string().min(1).max(256),
|
|
121
|
+
clientKind: AgentClientSchema.shape.kind,
|
|
122
|
+
conversationId: z.string().min(1).max(256)
|
|
123
|
+
}).strict();
|
|
124
|
+
const FeedbackDraftSnapshotSchema = z.object({
|
|
125
|
+
items: z.array(DesignFeedbackItemSchema).max(20),
|
|
126
|
+
comment: FeedbackCommentSchema.min(1).optional(),
|
|
127
|
+
submission: DesignFeedbackSchema.optional()
|
|
128
|
+
}).strict();
|
|
129
|
+
const FeedbackDraftRequestSchema = z.discriminatedUnion("operation", [
|
|
130
|
+
z.object({
|
|
131
|
+
operation: z.literal("load"),
|
|
132
|
+
scope: FeedbackDraftScopeSchema
|
|
133
|
+
}).strict(),
|
|
134
|
+
z.object({
|
|
135
|
+
operation: z.literal("clear"),
|
|
136
|
+
scope: FeedbackDraftScopeSchema
|
|
137
|
+
}).strict(),
|
|
138
|
+
z.object({
|
|
139
|
+
operation: z.literal("comment"),
|
|
140
|
+
scope: FeedbackDraftScopeSchema,
|
|
141
|
+
comment: FeedbackCommentSchema
|
|
142
|
+
}).strict(),
|
|
143
|
+
z.object({
|
|
144
|
+
operation: z.literal("save"),
|
|
145
|
+
scope: FeedbackDraftScopeSchema,
|
|
146
|
+
item: DesignFeedbackItemSchema
|
|
147
|
+
}).strict(),
|
|
148
|
+
z.object({
|
|
149
|
+
operation: z.literal("remove"),
|
|
150
|
+
scope: FeedbackDraftScopeSchema,
|
|
151
|
+
nodeId: z.string().min(1).max(128)
|
|
152
|
+
}).strict()
|
|
153
|
+
]);
|
|
154
|
+
const DesignActionSchema = z.object({
|
|
155
|
+
requestId: z.string().uuid(),
|
|
156
|
+
taskId: DesignTaskIdSchema,
|
|
157
|
+
epoch: z.number().int().nonnegative(),
|
|
158
|
+
action: z.enum([
|
|
159
|
+
"stop",
|
|
160
|
+
"done",
|
|
161
|
+
"feedback",
|
|
162
|
+
"steer"
|
|
163
|
+
]),
|
|
164
|
+
feedback: DesignFeedbackSchema.optional(),
|
|
165
|
+
feedbackId: z.string().uuid().optional()
|
|
166
|
+
}).strict().refine((value) => value.action === "feedback" === !!value.feedback, { message: "Feedback is required only for a feedback action." }).refine((value) => !value.feedback || value.feedback.id === value.requestId, { message: "Feedback and delivery must use the same request identity." }).refine((value) => value.action === "steer" === !!value.feedbackId, { message: "A queued feedback identity is required only when switching to Steer." }).refine((value) => value.feedbackId !== value.requestId, { message: "A delivery timing change must have its own request identity." });
|
|
167
|
+
const DesignActionResultSchema = z.object({
|
|
168
|
+
requestId: z.string().uuid(),
|
|
169
|
+
taskId: DesignTaskIdSchema,
|
|
170
|
+
status: z.enum([
|
|
171
|
+
"accepted",
|
|
172
|
+
"delivered",
|
|
173
|
+
"failed"
|
|
174
|
+
]),
|
|
175
|
+
message: z.string().max(500)
|
|
176
|
+
}).strict();
|
|
177
|
+
const DesignTaskSchema = z.object({
|
|
178
|
+
taskId: DesignTaskIdSchema,
|
|
179
|
+
title: z.string().trim().min(1).max(120),
|
|
180
|
+
target: DesignTaskTargetSchema,
|
|
181
|
+
status: z.enum([
|
|
182
|
+
"active",
|
|
183
|
+
"stopping",
|
|
184
|
+
"paused",
|
|
185
|
+
"completed",
|
|
186
|
+
"cancelled",
|
|
187
|
+
"expired",
|
|
188
|
+
"interrupted"
|
|
189
|
+
]),
|
|
190
|
+
epoch: z.number().int().nonnegative().optional(),
|
|
191
|
+
reviewClosed: z.boolean().optional().describe("User closed this review with Done. A completed task remains resumable until then, while it is still the current task."),
|
|
192
|
+
client: AgentClientSchema.optional(),
|
|
193
|
+
capabilities: AgentCapabilitiesSchema.optional(),
|
|
194
|
+
needsRead: z.boolean().optional(),
|
|
195
|
+
result: z.object({
|
|
196
|
+
nodeIds: z.array(z.string().min(1)).max(20),
|
|
197
|
+
summary: z.string().trim().max(400).optional(),
|
|
198
|
+
capturedAt: z.number().finite().nonnegative()
|
|
199
|
+
}).strict().optional(),
|
|
200
|
+
operation: z.enum(["reading", "writing"]).nullable(),
|
|
201
|
+
expiresAt: z.number().finite().nonnegative(),
|
|
202
|
+
revision: z.number().int().nonnegative()
|
|
203
|
+
}).strict();
|
|
204
|
+
const BeginDesignParametersSchema = z.object({
|
|
205
|
+
title: z.string().trim().min(1).max(120).describe("Short task title for the Figma UI."),
|
|
206
|
+
sessionId: z.string().min(1).optional().describe("Exact target from list_design_sessions; omit to use the activated Figma session."),
|
|
207
|
+
requestId: z.string().uuid().describe("Generate a fresh UUID for this task. Reuse it only to retry the same begin request.")
|
|
208
|
+
}).strict();
|
|
209
|
+
const ResumeDesignParametersSchema = z.object({
|
|
210
|
+
taskId: DesignTaskIdSchema.describe("Current task to continue after pause, expiry, interruption, or completion awaiting review. Closed, cancelled, and replaced tasks cannot resume."),
|
|
211
|
+
epoch: z.number().int().nonnegative()
|
|
212
|
+
}).strict();
|
|
213
|
+
const SetDesignAnchorParametersSchema = z.object({
|
|
214
|
+
taskId: DesignTaskIdSchema,
|
|
215
|
+
taskEpoch: DesignTaskEpochSchema,
|
|
216
|
+
nodeId: z.string().min(1).describe("Exact existing Frame to use as this task’s stable design region. Does not select, move, or modify it.")
|
|
217
|
+
}).strict();
|
|
218
|
+
const DesignAnchorSchema = z.object({
|
|
219
|
+
nodeId: z.string().min(1),
|
|
220
|
+
pageId: z.string().min(1)
|
|
221
|
+
}).strict();
|
|
222
|
+
const EndDesignParametersSchema = z.object({
|
|
223
|
+
taskId: DesignTaskIdSchema,
|
|
224
|
+
taskEpoch: DesignTaskEpochSchema,
|
|
225
|
+
outcome: z.enum(["completed", "cancelled"]).default("completed"),
|
|
226
|
+
summary: z.string().trim().min(1).max(400).optional().describe("Optional brief explanation of the result for the user. Describe applied changes, not a proposal or live progress.")
|
|
227
|
+
}).strict();
|
|
228
|
+
const DesignToolRouteSchema = z.object({
|
|
229
|
+
sessionId: z.string().min(1),
|
|
230
|
+
fileKey: z.string().min(1),
|
|
231
|
+
gatewayId: z.string().min(1),
|
|
232
|
+
taskId: DesignTaskIdSchema.optional(),
|
|
233
|
+
epoch: z.number().int().nonnegative().optional()
|
|
234
|
+
}).strict();
|
|
235
|
+
/** A task in one of these statuses can be resumed; the Hub and the canvas UI gate on the same set. */
|
|
236
|
+
const RESUMABLE_DESIGN_TASK_STATUSES = [
|
|
237
|
+
"paused",
|
|
238
|
+
"expired",
|
|
239
|
+
"interrupted",
|
|
240
|
+
"completed"
|
|
241
|
+
];
|
|
242
|
+
function formatDesignFeedback(feedback) {
|
|
243
|
+
const label = (text) => text.replace(/\r\n|\r|\n/g, " ").replace(/[\\[\]`*_<>&]/g, "\\$&");
|
|
244
|
+
const encode = (text) => encodeURIComponent(text).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
245
|
+
const sections = feedback.comment ? [feedback.comment] : [];
|
|
246
|
+
feedback.items.forEach((item, index) => {
|
|
247
|
+
const prefix = `${index + 1}. `;
|
|
248
|
+
const url = `https://www.figma.com/design/${encode(feedback.fileKey)}?node-id=${encode(item.nodeId)}&page-id=${encode(item.pageId)}`;
|
|
249
|
+
const comment = item.text.split(/\r\n|\r|\n/).map((line) => `${" ".repeat(prefix.length)}${line}`).join("\n");
|
|
250
|
+
sections.push(`${prefix}[${label(item.nodeName) || "Unnamed element"}](${url})\n\n${comment}`);
|
|
251
|
+
});
|
|
252
|
+
return sections.join("\n\n");
|
|
253
|
+
}
|
|
254
|
+
const TEMPAD_MCP_ERROR_CODES = {
|
|
255
|
+
NO_ACTIVE_EXTENSION: "NO_ACTIVE_EXTENSION",
|
|
256
|
+
EXTENSION_TIMEOUT: "EXTENSION_TIMEOUT",
|
|
257
|
+
EXTENSION_DISCONNECTED: "EXTENSION_DISCONNECTED",
|
|
258
|
+
EXTENSION_UPGRADE_REQUIRED: "EXTENSION_UPGRADE_REQUIRED",
|
|
259
|
+
RUNTIME_IDENTITY_MISMATCH: "RUNTIME_IDENTITY_MISMATCH",
|
|
260
|
+
INVALID_SELECTION: "INVALID_SELECTION",
|
|
261
|
+
NODE_NOT_VISIBLE: "NODE_NOT_VISIBLE",
|
|
262
|
+
CANVAS_READ_ONLY: "CANVAS_READ_ONLY",
|
|
263
|
+
CANVAS_UNSUPPORTED_EDITOR: "CANVAS_UNSUPPORTED_EDITOR",
|
|
264
|
+
CANVAS_BUSY: "CANVAS_BUSY",
|
|
265
|
+
DESIGN_TASK_BUSY: "DESIGN_TASK_BUSY",
|
|
266
|
+
DESIGN_TASK_INACTIVE: "DESIGN_TASK_INACTIVE",
|
|
267
|
+
DESIGN_TASK_OWNER_MISMATCH: "DESIGN_TASK_OWNER_MISMATCH",
|
|
268
|
+
DESIGN_TARGET_CHANGED: "DESIGN_TARGET_CHANGED",
|
|
269
|
+
INVALID_CANVAS_SCOPE: "INVALID_CANVAS_SCOPE",
|
|
270
|
+
INVALID_CANVAS_SPEC: "INVALID_CANVAS_SPEC",
|
|
271
|
+
CANVAS_APPLY_FAILED: "CANVAS_APPLY_FAILED",
|
|
272
|
+
ASSET_SERVER_NOT_CONFIGURED: "ASSET_SERVER_NOT_CONFIGURED",
|
|
273
|
+
ASSET_NOT_FOUND: "ASSET_NOT_FOUND",
|
|
274
|
+
ASSET_HASH_MISMATCH: "ASSET_HASH_MISMATCH",
|
|
275
|
+
ASSET_TOO_LARGE: "ASSET_TOO_LARGE",
|
|
276
|
+
ASSET_MIME_UNSUPPORTED: "ASSET_MIME_UNSUPPORTED",
|
|
277
|
+
ASSET_BRIDGE_UNAVAILABLE: "ASSET_BRIDGE_UNAVAILABLE",
|
|
278
|
+
SVG_INVALID: "SVG_INVALID",
|
|
279
|
+
SVG_EXTERNAL_REFERENCE: "SVG_EXTERNAL_REFERENCE",
|
|
280
|
+
SVG_TOO_COMPLEX: "SVG_TOO_COMPLEX",
|
|
281
|
+
SVG_IMPORT_FAILED: "SVG_IMPORT_FAILED",
|
|
282
|
+
SVG_WRAPPER_DIRTY: "SVG_WRAPPER_DIRTY",
|
|
283
|
+
IMAGE_IMPORT_FAILED: "IMAGE_IMPORT_FAILED",
|
|
284
|
+
TRANSPORT_NOT_CONNECTED: "TRANSPORT_NOT_CONNECTED"
|
|
285
|
+
};
|
|
286
|
+
const TempadMcpErrorPayloadSchema = z.object({
|
|
287
|
+
code: z.enum(TEMPAD_MCP_ERROR_CODES).optional(),
|
|
288
|
+
message: z.string().min(1)
|
|
289
|
+
}).strict();
|
|
290
|
+
const TOOL_RESULT_OUTCOME_ERROR = "Tool results must contain exactly one defined payload or error.";
|
|
291
|
+
function hasToolResultOutcome(result) {
|
|
292
|
+
return result.payload !== void 0 !== (result.error !== void 0);
|
|
293
|
+
}
|
|
294
|
+
const TEMPAD_MCP_BROWSER_SOURCE = "tempad-dev:mcp";
|
|
295
|
+
const MCP_MAX_ASSET_BASE64_LENGTH = 4 * Math.ceil(MCP_MAX_ASSET_BYTES / 3);
|
|
296
|
+
const MessageBaseSchema = z.object({
|
|
297
|
+
source: z.literal(TEMPAD_MCP_BROWSER_SOURCE),
|
|
298
|
+
version: z.literal(12)
|
|
299
|
+
}).strict();
|
|
300
|
+
const PageMessageBaseSchema = MessageBaseSchema.extend({ sessionId: z.string().min(1) }).strict();
|
|
301
|
+
function messageSchema(base, type, shape) {
|
|
302
|
+
return base.extend({
|
|
303
|
+
type: z.literal(type),
|
|
304
|
+
...shape
|
|
305
|
+
}).strict();
|
|
306
|
+
}
|
|
307
|
+
const AssetMetadataSchema = z.object({
|
|
308
|
+
height: z.number().int().positive().optional(),
|
|
309
|
+
themeable: z.boolean().optional(),
|
|
310
|
+
width: z.number().int().positive().optional()
|
|
311
|
+
}).strict();
|
|
312
|
+
const AssetUploadPayloadSchema = z.object({
|
|
313
|
+
base64: z.string().min(1).max(MCP_MAX_ASSET_BASE64_LENGTH),
|
|
314
|
+
hash: z.string().regex(MCP_HASH_PATTERN),
|
|
315
|
+
metadata: AssetMetadataSchema.optional(),
|
|
316
|
+
mimeType: z.string().min(1)
|
|
317
|
+
}).strict();
|
|
318
|
+
const AssetDownloadPayloadSchema = z.object({ hash: z.string().regex(MCP_HASH_PATTERN) }).strict();
|
|
319
|
+
const AssetDownloadResultPayloadSchema = z.object({
|
|
320
|
+
base64: z.string().min(1).max(MCP_MAX_ASSET_BASE64_LENGTH),
|
|
321
|
+
mimeType: z.string().min(1),
|
|
322
|
+
size: z.number().int().nonnegative().max(MCP_MAX_ASSET_BYTES)
|
|
323
|
+
}).strict();
|
|
324
|
+
const PageEnableMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.enable", {
|
|
325
|
+
reviewTask: DesignTaskSchema.optional(),
|
|
326
|
+
document: FigmaSessionSchema.omit({
|
|
327
|
+
sessionId: true,
|
|
328
|
+
tabId: true,
|
|
329
|
+
documentId: true
|
|
330
|
+
}).optional()
|
|
331
|
+
});
|
|
332
|
+
const PageSessionInfoMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.sessionInfo", { document: FigmaSessionSchema.omit({
|
|
333
|
+
sessionId: true,
|
|
334
|
+
tabId: true,
|
|
335
|
+
documentId: true
|
|
336
|
+
}) });
|
|
337
|
+
const PageDesignActionMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.designAction", {
|
|
338
|
+
action: DesignActionSchema,
|
|
339
|
+
draftScope: FeedbackDraftScopeSchema.optional()
|
|
340
|
+
});
|
|
341
|
+
const PageFeedbackDraftsMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.feedbackDrafts", {
|
|
342
|
+
requestId: z.string().uuid(),
|
|
343
|
+
request: FeedbackDraftRequestSchema
|
|
344
|
+
});
|
|
345
|
+
const PageDisableMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.disable", {});
|
|
346
|
+
const PageActivateSessionMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.activateSession", {});
|
|
347
|
+
const PageToolResultMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.toolResult", {
|
|
348
|
+
callId: z.string().min(1),
|
|
349
|
+
error: TempadMcpErrorPayloadSchema.optional(),
|
|
350
|
+
payload: z.unknown().optional()
|
|
351
|
+
});
|
|
352
|
+
const PageAssetUploadMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.uploadAsset", {
|
|
353
|
+
payload: AssetUploadPayloadSchema,
|
|
354
|
+
requestId: z.string().min(1)
|
|
355
|
+
});
|
|
356
|
+
const PageAssetDownloadMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.downloadAsset", {
|
|
357
|
+
payload: AssetDownloadPayloadSchema,
|
|
358
|
+
requestId: z.string().min(1)
|
|
359
|
+
});
|
|
360
|
+
z.discriminatedUnion("type", [
|
|
361
|
+
PageDesignActionMessageSchema,
|
|
362
|
+
PageFeedbackDraftsMessageSchema,
|
|
363
|
+
PageEnableMessageSchema,
|
|
364
|
+
PageDisableMessageSchema,
|
|
365
|
+
PageActivateSessionMessageSchema,
|
|
366
|
+
PageSessionInfoMessageSchema,
|
|
367
|
+
PageToolResultMessageSchema,
|
|
368
|
+
PageAssetUploadMessageSchema,
|
|
369
|
+
PageAssetDownloadMessageSchema
|
|
370
|
+
]).refine((message) => message.type !== "mcp.toolResult" || hasToolResultOutcome(message), { message: TOOL_RESULT_OUTCOME_ERROR });
|
|
371
|
+
const McpBrowserStateStatusSchema = z.enum([
|
|
372
|
+
"disabled",
|
|
373
|
+
"connecting",
|
|
374
|
+
"connected",
|
|
375
|
+
"error"
|
|
376
|
+
]);
|
|
377
|
+
const BridgeStateMessageSchema = messageSchema(MessageBaseSchema, "mcp.state", { payload: z.object({
|
|
378
|
+
activeSessionId: z.string().nullable(),
|
|
379
|
+
gatewayId: z.string().nullable().optional(),
|
|
380
|
+
assetServerUrl: z.string().nullable().optional(),
|
|
381
|
+
errorMessage: z.string().nullable(),
|
|
382
|
+
sessionCount: z.number().nonnegative(),
|
|
383
|
+
sessionId: z.string(),
|
|
384
|
+
status: McpBrowserStateStatusSchema
|
|
385
|
+
}).strict() });
|
|
386
|
+
const BridgeToolCallMessageSchema = messageSchema(MessageBaseSchema, "mcp.toolCall", {
|
|
387
|
+
callId: z.string().min(1),
|
|
388
|
+
route: DesignToolRouteSchema.optional(),
|
|
389
|
+
payload: z.object({
|
|
390
|
+
args: z.unknown().optional(),
|
|
391
|
+
name: z.string()
|
|
392
|
+
}).strict()
|
|
393
|
+
});
|
|
394
|
+
const BridgeDesignActionResultMessageSchema = messageSchema(MessageBaseSchema, "mcp.designActionResult", { result: DesignActionResultSchema });
|
|
395
|
+
const BridgeReviewClosedMessageSchema = messageSchema(MessageBaseSchema, "mcp.designReviewClosed", {
|
|
396
|
+
taskId: z.string().min(1),
|
|
397
|
+
fileKey: z.string().min(1)
|
|
398
|
+
});
|
|
399
|
+
const BridgeDesignTaskMessageSchema = messageSchema(MessageBaseSchema, "mcp.designTaskState", {
|
|
400
|
+
gatewayId: z.string().min(1),
|
|
401
|
+
task: DesignTaskSchema
|
|
402
|
+
});
|
|
403
|
+
const BridgeFeedbackDraftsResultMessageSchema = messageSchema(MessageBaseSchema, "mcp.feedbackDraftsResult", {
|
|
404
|
+
requestId: z.string().uuid(),
|
|
405
|
+
sessionId: z.string().min(1),
|
|
406
|
+
payload: FeedbackDraftSnapshotSchema.optional(),
|
|
407
|
+
error: TempadMcpErrorPayloadSchema.optional()
|
|
408
|
+
});
|
|
409
|
+
const BridgeAssetUploadResultMessageSchema = messageSchema(MessageBaseSchema, "mcp.assetUploadResult", {
|
|
410
|
+
error: TempadMcpErrorPayloadSchema.optional(),
|
|
411
|
+
requestId: z.string().min(1),
|
|
412
|
+
sessionId: z.string().min(1)
|
|
413
|
+
});
|
|
414
|
+
const BridgeAssetDownloadResultMessageSchema = messageSchema(MessageBaseSchema, "mcp.assetDownloadResult", {
|
|
415
|
+
error: TempadMcpErrorPayloadSchema.optional(),
|
|
416
|
+
payload: AssetDownloadResultPayloadSchema.optional(),
|
|
417
|
+
requestId: z.string().min(1),
|
|
418
|
+
sessionId: z.string().min(1)
|
|
419
|
+
});
|
|
420
|
+
z.discriminatedUnion("type", [
|
|
421
|
+
BridgeDesignActionResultMessageSchema,
|
|
422
|
+
BridgeReviewClosedMessageSchema,
|
|
423
|
+
BridgeFeedbackDraftsResultMessageSchema,
|
|
424
|
+
BridgeStateMessageSchema,
|
|
425
|
+
BridgeToolCallMessageSchema,
|
|
426
|
+
BridgeDesignTaskMessageSchema,
|
|
427
|
+
BridgeAssetUploadResultMessageSchema,
|
|
428
|
+
BridgeAssetDownloadResultMessageSchema
|
|
429
|
+
]).refine((message) => message.type !== "mcp.assetDownloadResult" && message.type !== "mcp.feedbackDraftsResult" || hasToolResultOutcome(message), { message: "Asset download or feedback draft result requires exactly one of payload or error." });
|
|
430
|
+
const SERVER_NAME = "tempad-dev";
|
|
431
|
+
const SERVER_COMMAND = "npx";
|
|
432
|
+
const SERVER_ARGS = ["-y", "@tempad-dev/mcp@latest"];
|
|
433
|
+
const REPOSITORY = "ecomfe/tempad-dev";
|
|
434
|
+
const PLUGIN_INSTALL_COMMAND = `npx plugins add ${REPOSITORY}`;
|
|
435
|
+
const SKILLS_SOURCE_URL = "https://github.com/ecomfe/tempad-dev/tree/main/agent-plugin/targets/standard/skills";
|
|
436
|
+
const DESIGN_TO_CODE_SKILL_NAME = "figma-design-to-code";
|
|
437
|
+
const CANVAS_AUTHORING_SKILL_NAME = "figma-canvas-authoring";
|
|
438
|
+
const SKILLS_INSTALL_COMMAND = `npx skills add ${SKILLS_SOURCE_URL} --skill ${[DESIGN_TO_CODE_SKILL_NAME, CANVAS_AUTHORING_SKILL_NAME].join(" ")}`;
|
|
439
|
+
const stdioConfig = {
|
|
440
|
+
type: "stdio",
|
|
441
|
+
command: SERVER_COMMAND,
|
|
442
|
+
args: [...SERVER_ARGS]
|
|
443
|
+
};
|
|
444
|
+
const commandConfig = {
|
|
445
|
+
command: SERVER_COMMAND,
|
|
446
|
+
args: [...SERVER_ARGS]
|
|
447
|
+
};
|
|
448
|
+
function toBase64(input) {
|
|
449
|
+
if (typeof globalThis.btoa === "function") return globalThis.btoa(input);
|
|
450
|
+
const bufferLike = globalThis.Buffer;
|
|
451
|
+
if (bufferLike) return bufferLike.from(input, "utf8").toString("base64");
|
|
452
|
+
throw new Error("Base64 encoding not supported in this environment.");
|
|
453
|
+
}
|
|
454
|
+
function buildVscodeDeepLink() {
|
|
455
|
+
return `vscode:mcp/install?${encodeURIComponent(JSON.stringify({
|
|
456
|
+
name: SERVER_NAME,
|
|
457
|
+
...stdioConfig
|
|
458
|
+
}))}`;
|
|
459
|
+
}
|
|
460
|
+
function buildCursorConfigBase64() {
|
|
461
|
+
return encodeURIComponent(toBase64(JSON.stringify(commandConfig)));
|
|
462
|
+
}
|
|
463
|
+
function buildCursorDeepLink() {
|
|
464
|
+
return `cursor://anysphere.cursor-deeplink/mcp/install?name=${encodeURIComponent(SERVER_NAME)}&config=${buildCursorConfigBase64()}`;
|
|
465
|
+
}
|
|
466
|
+
function buildTraeDeepLink(protocol) {
|
|
467
|
+
return `${protocol}://trae.ai-ide/mcp-import?type=stdio&name=${encodeURIComponent(SERVER_NAME)}&config=${buildCursorConfigBase64()}`;
|
|
468
|
+
}
|
|
469
|
+
function buildCodexConfigSnippet() {
|
|
470
|
+
return [
|
|
471
|
+
`[mcp_servers.${SERVER_NAME}]`,
|
|
472
|
+
`command = ${JSON.stringify(SERVER_COMMAND)}`,
|
|
473
|
+
`args = [${SERVER_ARGS.map((arg) => JSON.stringify(arg)).join(", ")}]`
|
|
474
|
+
].join("\n");
|
|
475
|
+
}
|
|
476
|
+
function buildMcpConfigSnippet() {
|
|
477
|
+
return JSON.stringify({ mcpServers: { [SERVER_NAME]: commandConfig } }, null, 2);
|
|
478
|
+
}
|
|
479
|
+
const OPENCODE_CONFIG_SNIPPET = JSON.stringify({
|
|
480
|
+
$schema: "https://opencode.ai/config.json",
|
|
481
|
+
mcp: { [SERVER_NAME]: {
|
|
482
|
+
type: "local",
|
|
483
|
+
command: [SERVER_COMMAND, ...SERVER_ARGS]
|
|
484
|
+
} }
|
|
485
|
+
}, null, 2);
|
|
486
|
+
function buildCliCommand(prefix) {
|
|
487
|
+
const args = `${SERVER_COMMAND} ${SERVER_ARGS.join(" ")}`;
|
|
488
|
+
if (prefix === "claude") return `claude mcp add --transport stdio "${SERVER_NAME}" -- ${args}`;
|
|
489
|
+
if (prefix === "gemini") return `gemini mcp add --scope user "${SERVER_NAME}" ${args}`;
|
|
490
|
+
return `codex mcp add "${SERVER_NAME}" -- ${args}`;
|
|
491
|
+
}
|
|
492
|
+
const CODEX_SPARSE = "--sparse .agents --sparse agent-plugin/targets/codex";
|
|
493
|
+
const CLAUDE_SPARSE = "--sparse .claude-plugin agent-plugin/targets/claude";
|
|
494
|
+
function buildPluginSetupCommand(agent) {
|
|
495
|
+
if (agent === "codex") return `codex plugin marketplace add ${REPOSITORY} --ref main ${CODEX_SPARSE} && codex plugin add tempad-dev@tempad-dev`;
|
|
496
|
+
if (agent === "claude-code") return `claude plugin marketplace add ${REPOSITORY} ${CLAUDE_SPARSE} && claude plugin install tempad-dev@tempad-dev`;
|
|
497
|
+
return `${PLUGIN_INSTALL_COMMAND} --target ${agent}`;
|
|
498
|
+
}
|
|
499
|
+
function pluginCliAction(agent) {
|
|
500
|
+
return {
|
|
501
|
+
id: "plugin-cli",
|
|
502
|
+
label: "Plugin CLI",
|
|
503
|
+
kind: "command",
|
|
504
|
+
value: buildPluginSetupCommand(agent)
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
function buildSkillsInstallCommand(agent) {
|
|
508
|
+
return `${SKILLS_INSTALL_COMMAND} --global --agent ${agent}`;
|
|
509
|
+
}
|
|
510
|
+
function buildGeminiSkillInstallCommand(skillName) {
|
|
511
|
+
return `gemini skills install ${SKILLS_SOURCE_URL}/${skillName}`;
|
|
512
|
+
}
|
|
513
|
+
[...SERVER_ARGS];
|
|
514
|
+
JSON.stringify({ [SERVER_NAME]: commandConfig }, null, 2);
|
|
515
|
+
buildMcpConfigSnippet();
|
|
516
|
+
const MCP_CLIENTS_BY_ID = {
|
|
517
|
+
vscode: {
|
|
518
|
+
id: "vscode",
|
|
519
|
+
name: "VS Code",
|
|
520
|
+
brandColor: "#0098ff",
|
|
521
|
+
supportsDeepLink: true,
|
|
522
|
+
deepLink: buildVscodeDeepLink()
|
|
523
|
+
},
|
|
524
|
+
cursor: {
|
|
525
|
+
id: "cursor",
|
|
526
|
+
name: "Cursor",
|
|
527
|
+
brandColor: ["#000", "#fff"],
|
|
528
|
+
supportsDeepLink: true,
|
|
529
|
+
deepLink: buildCursorDeepLink()
|
|
530
|
+
},
|
|
531
|
+
claude: {
|
|
532
|
+
id: "claude",
|
|
533
|
+
name: "Claude Code",
|
|
534
|
+
brandColor: "#D97757",
|
|
535
|
+
supportsDeepLink: false,
|
|
536
|
+
copyText: buildCliCommand("claude"),
|
|
537
|
+
copyKind: "command"
|
|
538
|
+
},
|
|
539
|
+
codex: {
|
|
540
|
+
id: "codex",
|
|
541
|
+
name: "Codex",
|
|
542
|
+
brandColor: ["#0d0d0d", "#fff"],
|
|
543
|
+
supportsDeepLink: false,
|
|
544
|
+
copyText: buildCliCommand("codex"),
|
|
545
|
+
copyKind: "command",
|
|
546
|
+
alternateCopyText: buildCodexConfigSnippet(),
|
|
547
|
+
alternateCopyKind: "config"
|
|
548
|
+
},
|
|
549
|
+
gemini: {
|
|
550
|
+
id: "gemini",
|
|
551
|
+
name: "Gemini",
|
|
552
|
+
brandColor: "#4e6ef2",
|
|
553
|
+
supportsDeepLink: false,
|
|
554
|
+
copyText: buildCliCommand("gemini"),
|
|
555
|
+
copyKind: "command",
|
|
556
|
+
alternateCopyText: buildMcpConfigSnippet(),
|
|
557
|
+
alternateCopyKind: "config"
|
|
558
|
+
},
|
|
559
|
+
opencode: {
|
|
560
|
+
id: "opencode",
|
|
561
|
+
name: "OpenCode",
|
|
562
|
+
brandColor: ["#211e1e", "#f1ecec"],
|
|
563
|
+
supportsDeepLink: false,
|
|
564
|
+
copyText: OPENCODE_CONFIG_SNIPPET,
|
|
565
|
+
copyKind: "config"
|
|
566
|
+
},
|
|
567
|
+
trae: {
|
|
568
|
+
id: "trae",
|
|
569
|
+
name: "TRAE",
|
|
570
|
+
brandColor: ["#0fdc78", "#32f08c"],
|
|
571
|
+
supportsDeepLink: true,
|
|
572
|
+
deepLink: buildTraeDeepLink("trae"),
|
|
573
|
+
fallbackDeepLink: buildTraeDeepLink("trae-cn")
|
|
574
|
+
}
|
|
575
|
+
};
|
|
576
|
+
Object.values(MCP_CLIENTS_BY_ID);
|
|
577
|
+
const AGENT_INTEGRATIONS_BY_ID = {
|
|
578
|
+
codex: {
|
|
579
|
+
id: "codex",
|
|
580
|
+
name: "Codex",
|
|
581
|
+
actions: [pluginCliAction("codex")]
|
|
582
|
+
},
|
|
583
|
+
claude: {
|
|
584
|
+
id: "claude",
|
|
585
|
+
name: "Claude Code",
|
|
586
|
+
actions: [pluginCliAction("claude-code")]
|
|
587
|
+
},
|
|
588
|
+
cursor: {
|
|
589
|
+
id: "cursor",
|
|
590
|
+
name: "Cursor",
|
|
591
|
+
actions: [pluginCliAction("cursor")]
|
|
592
|
+
},
|
|
593
|
+
gemini: {
|
|
594
|
+
id: "gemini",
|
|
595
|
+
name: "Gemini",
|
|
596
|
+
actions: [
|
|
597
|
+
{
|
|
598
|
+
id: "mcp-cli",
|
|
599
|
+
label: "MCP CLI",
|
|
600
|
+
kind: "command",
|
|
601
|
+
value: buildCliCommand("gemini")
|
|
602
|
+
},
|
|
603
|
+
{
|
|
604
|
+
id: "skill-design-to-code-cli",
|
|
605
|
+
label: "Design-to-code skill",
|
|
606
|
+
kind: "command",
|
|
607
|
+
value: buildGeminiSkillInstallCommand(DESIGN_TO_CODE_SKILL_NAME)
|
|
608
|
+
},
|
|
609
|
+
{
|
|
610
|
+
id: "skill-canvas-authoring-cli",
|
|
611
|
+
label: "Canvas authoring skill",
|
|
612
|
+
kind: "command",
|
|
613
|
+
value: buildGeminiSkillInstallCommand(CANVAS_AUTHORING_SKILL_NAME)
|
|
614
|
+
}
|
|
615
|
+
]
|
|
616
|
+
},
|
|
617
|
+
vscode: {
|
|
618
|
+
id: "vscode",
|
|
619
|
+
name: "VS Code",
|
|
620
|
+
actions: [pluginCliAction("vscode")]
|
|
621
|
+
},
|
|
622
|
+
opencode: {
|
|
623
|
+
id: "opencode",
|
|
624
|
+
name: "OpenCode",
|
|
625
|
+
actions: [{
|
|
626
|
+
id: "mcp-config",
|
|
627
|
+
label: "MCP config",
|
|
628
|
+
kind: "config",
|
|
629
|
+
value: OPENCODE_CONFIG_SNIPPET
|
|
630
|
+
}, {
|
|
631
|
+
id: "skill-cli",
|
|
632
|
+
label: "Agent skills",
|
|
633
|
+
kind: "command",
|
|
634
|
+
value: buildSkillsInstallCommand("opencode")
|
|
635
|
+
}]
|
|
636
|
+
},
|
|
637
|
+
trae: {
|
|
638
|
+
id: "trae",
|
|
639
|
+
name: "TRAE",
|
|
640
|
+
actions: [{
|
|
641
|
+
id: "mcp-deep-link",
|
|
642
|
+
label: "MCP install",
|
|
643
|
+
kind: "deep-link",
|
|
644
|
+
value: MCP_CLIENTS_BY_ID.trae.deepLink ?? "",
|
|
645
|
+
fallbackValue: MCP_CLIENTS_BY_ID.trae.fallbackDeepLink
|
|
646
|
+
}, {
|
|
647
|
+
id: "skill-cli",
|
|
648
|
+
label: "Agent skills",
|
|
649
|
+
kind: "command",
|
|
650
|
+
value: buildSkillsInstallCommand("trae")
|
|
651
|
+
}]
|
|
652
|
+
}
|
|
653
|
+
};
|
|
654
|
+
Object.values(AGENT_INTEGRATIONS_BY_ID);
|
|
655
|
+
const LegacyToolCallPayloadSchema = z.discriminatedUnion("name", [
|
|
656
|
+
z.object({
|
|
657
|
+
name: z.literal("get_code"),
|
|
658
|
+
args: z.object({
|
|
659
|
+
nodeId: z.string().optional(),
|
|
660
|
+
preferredLang: z.enum(["jsx", "vue"]).optional(),
|
|
661
|
+
resolveTokens: z.boolean().optional(),
|
|
662
|
+
vectorMode: z.enum(["smart", "snapshot"]).optional()
|
|
663
|
+
}).strict()
|
|
664
|
+
}).strict(),
|
|
665
|
+
z.object({
|
|
666
|
+
name: z.literal("get_structure"),
|
|
667
|
+
args: z.object({
|
|
668
|
+
nodeId: z.string().optional(),
|
|
669
|
+
options: z.object({ depth: z.number().int().positive().optional() }).strict().optional()
|
|
670
|
+
}).strict()
|
|
671
|
+
}).strict(),
|
|
672
|
+
z.object({
|
|
673
|
+
name: z.literal("get_screenshot"),
|
|
674
|
+
args: z.object({ nodeId: z.string().optional() }).strict()
|
|
675
|
+
}).strict(),
|
|
676
|
+
z.object({
|
|
677
|
+
name: z.literal("get_token_defs"),
|
|
678
|
+
args: z.object({
|
|
679
|
+
names: z.array(z.string().regex(/^--[a-zA-Z0-9-_]+$/)).min(1),
|
|
680
|
+
includeAllModes: z.boolean().optional()
|
|
681
|
+
}).strict()
|
|
682
|
+
}).strict()
|
|
683
|
+
]);
|
|
684
|
+
const RegisteredMessageSchema = z.object({
|
|
685
|
+
type: z.literal("registered"),
|
|
686
|
+
id: z.string().min(1),
|
|
687
|
+
protocolVersion: z.number().int().positive(),
|
|
688
|
+
supportedProtocolVersions: z.array(z.number().int().positive()).min(1).optional()
|
|
689
|
+
});
|
|
690
|
+
const StateMessageSchema = z.object({
|
|
691
|
+
type: z.literal("state"),
|
|
692
|
+
activeId: z.string().nullable(),
|
|
693
|
+
assetServerUrl: z.string().url()
|
|
694
|
+
});
|
|
695
|
+
const ToolCallPayloadSchema = z.object({
|
|
696
|
+
name: z.string(),
|
|
697
|
+
args: z.unknown()
|
|
698
|
+
});
|
|
699
|
+
const ToolCallMessageSchema = z.object({
|
|
700
|
+
type: z.literal("toolCall"),
|
|
701
|
+
id: z.string().min(1),
|
|
702
|
+
route: DesignToolRouteSchema.optional(),
|
|
703
|
+
payload: ToolCallPayloadSchema
|
|
704
|
+
});
|
|
705
|
+
const DesignTaskStateMessageSchema = z.object({
|
|
706
|
+
type: z.literal("designTaskState"),
|
|
707
|
+
task: DesignTaskSchema
|
|
708
|
+
});
|
|
709
|
+
const DesignActionResultMessageSchema = z.object({
|
|
710
|
+
type: z.literal("designActionResult"),
|
|
711
|
+
sessionId: z.string().min(1),
|
|
712
|
+
result: DesignActionResultSchema
|
|
713
|
+
});
|
|
714
|
+
const DesignActionMessageSchema = z.object({
|
|
715
|
+
type: z.literal("designAction"),
|
|
716
|
+
sessionId: z.string().min(1),
|
|
717
|
+
action: DesignActionSchema
|
|
718
|
+
}).strict();
|
|
719
|
+
z.discriminatedUnion("type", [
|
|
720
|
+
DesignActionResultMessageSchema,
|
|
721
|
+
RegisteredMessageSchema,
|
|
722
|
+
StateMessageSchema,
|
|
723
|
+
DesignTaskStateMessageSchema,
|
|
724
|
+
ToolCallMessageSchema
|
|
725
|
+
]);
|
|
726
|
+
const ActivateMessageSchema = z.object({ type: z.literal("activate") }).strict();
|
|
727
|
+
const ToolResultMessageSchema = z.object({
|
|
728
|
+
type: z.literal("toolResult"),
|
|
729
|
+
id: z.string().min(1),
|
|
730
|
+
payload: z.unknown().optional(),
|
|
731
|
+
error: TempadMcpErrorPayloadSchema.optional()
|
|
732
|
+
}).strict().refine(hasToolResultOutcome, { message: TOOL_RESULT_OUTCOME_ERROR });
|
|
733
|
+
const PingMessageSchema = z.object({ type: z.literal("ping") }).strict();
|
|
734
|
+
const RuntimeHelloMessageSchema = z.object({
|
|
735
|
+
type: z.literal("runtimeHello"),
|
|
736
|
+
extensionVersion: z.string().min(1),
|
|
737
|
+
extensionRuntimeFingerprint: z.string().regex(/^[a-f0-9]{64}$/)
|
|
738
|
+
}).strict();
|
|
739
|
+
const FigmaSessionsMessageSchema = z.object({
|
|
740
|
+
type: z.literal("sessions"),
|
|
741
|
+
browserId: z.string().min(1),
|
|
742
|
+
activeSessionId: z.string().nullable(),
|
|
743
|
+
sessions: z.array(FigmaSessionSchema).max(128),
|
|
744
|
+
reviews: z.array(z.object({
|
|
745
|
+
sessionId: z.string().min(1),
|
|
746
|
+
task: DesignTaskSchema
|
|
747
|
+
}).strict()).max(128).optional(),
|
|
748
|
+
openTabIds: z.array(z.number().int().nonnegative()).max(1e4).optional()
|
|
749
|
+
}).strict();
|
|
750
|
+
const MessageFromExtensionSchema = z.union([
|
|
751
|
+
DesignActionMessageSchema,
|
|
752
|
+
ActivateMessageSchema,
|
|
753
|
+
ToolResultMessageSchema,
|
|
754
|
+
RuntimeHelloMessageSchema,
|
|
755
|
+
FigmaSessionsMessageSchema,
|
|
756
|
+
PingMessageSchema
|
|
757
|
+
]);
|
|
758
|
+
const LegacyMessageFromExtensionSchema = z.union([
|
|
759
|
+
ActivateMessageSchema,
|
|
760
|
+
ToolResultMessageSchema,
|
|
761
|
+
PingMessageSchema
|
|
762
|
+
]);
|
|
763
|
+
const ENCODER = new TextEncoder();
|
|
764
|
+
function utf8Bytes(value) {
|
|
765
|
+
const serialized = typeof value === "string" ? value : JSON.stringify(value, null, 0) ?? "undefined";
|
|
766
|
+
return ENCODER.encode(serialized).length;
|
|
767
|
+
}
|
|
768
|
+
function measureCallToolResultBytes(result) {
|
|
769
|
+
return utf8Bytes(result);
|
|
770
|
+
}
|
|
771
|
+
function buildGetCodeToolResult(payload) {
|
|
772
|
+
const summary = [];
|
|
773
|
+
const codeSize = utf8Bytes(payload.code);
|
|
774
|
+
summary.push(`Generated \`${payload.lang}\` snippet (${formatBytes(codeSize)}).`);
|
|
775
|
+
if (payload.warnings?.length) summary.push(...payload.warnings.map((warning) => warning.message));
|
|
776
|
+
summary.push(payload.assets?.length ? `Assets attached: ${payload.assets.length}. Use asset.localPath directly when present; otherwise download asset.url.` : "No binary assets were attached to this response.");
|
|
777
|
+
const tokenCount = payload.tokens ? Object.keys(payload.tokens).length : 0;
|
|
778
|
+
if (tokenCount) summary.push(`Token references included: ${tokenCount}.`);
|
|
779
|
+
summary.push("Read structuredContent for the full code string and metadata.");
|
|
780
|
+
return buildTextToolResult(summary.join("\n"), payload);
|
|
781
|
+
}
|
|
782
|
+
function buildGetDesignSystemToolResult(payload) {
|
|
783
|
+
if ("scope" in payload && payload.scope === "pages") return buildTextToolResult(`Returned ${formatCount(payload.pages.length, "Figma page")}.${payload.nextCursor === void 0 ? "" : ` Continue the page list with cursor ${payload.nextCursor}.`} Use an exact pageId to limit component discovery when only that page is relevant.`, payload);
|
|
784
|
+
if ("scope" in payload) return buildTextToolResult(`Returned ${payload.fonts?.length ?? payload.families?.length ?? 0} available font ${payload.fonts ? "faces" : "families"}.${payload.nextCursor === void 0 ? "" : ` Continue with the same font filters and cursor ${payload.nextCursor}.`} Availability does not establish glyph coverage; verify rendered text.`, payload);
|
|
785
|
+
if (payload.details) return buildTextToolResult(`Returned bounded ${payload.details.kind} definition ${payload.details.ref} from catalog ${payload.catalogId}.`, payload);
|
|
786
|
+
return buildTextToolResult(`${`Returned ${formatCount(payload.components.length, "component")}, ${formatCount(payload.variables.length, "variable")}, ${formatCount(payload.styles.length, "style")}, ${formatCount(payload.collections.length, "collection")}, and ${formatCount(payload.shaders?.length ?? 0, "shader")} from catalog ${payload.catalogId}.`}${payload.warnings?.length ? `\n${payload.warnings.join("\n")}` : ""}\nRead structuredContent for deterministic short refs and component tags.${payload.nextCursor === void 0 ? "" : ` Continue this catalog with cursor ${payload.nextCursor} to inspect omitted resources.`} Read one bounded definition with this catalogId and a returned ref.`, payload);
|
|
787
|
+
}
|
|
788
|
+
function buildApplyCanvasToolResult(payload) {
|
|
789
|
+
const nodeChanges = {
|
|
790
|
+
created: payload.createdNodeIds.length,
|
|
791
|
+
updated: payload.updatedNodeIds.length,
|
|
792
|
+
removed: payload.removedNodeIds.length
|
|
793
|
+
};
|
|
794
|
+
const summary = `Applied ${formatCount(payload.mutationCount, "canvas mutation")}: ${formatCount(nodeChanges.created, "node")} created, ${formatCount(nodeChanges.updated, "node")} updated, and ${formatCount(nodeChanges.removed, "node")} removed.`;
|
|
795
|
+
const verifiedCounts = [
|
|
796
|
+
formatCount(payload.verification.nodesChecked, "node"),
|
|
797
|
+
formatCount(payload.verification.referencesChecked, "native reference"),
|
|
798
|
+
...payload.verification.nativeFieldsChecked === void 0 ? [] : [formatCount(payload.verification.nativeFieldsChecked, "native state assertion")]
|
|
799
|
+
];
|
|
800
|
+
const verification = `Structural verification ${payload.verification.status}: ${verifiedCounts.length === 2 ? `${verifiedCounts[0]} and ${verifiedCounts[1]}` : `${verifiedCounts.slice(0, -1).join(", ")}, and ${verifiedCounts.at(-1)}`} checked.`;
|
|
801
|
+
const warnings = payload.verification.warnings.length ? `\n${payload.verification.warnings.map(({ code, key, message }) => `${code}${key ? ` (${key})` : ""}: ${message}`).join("\n")}` : "";
|
|
802
|
+
const root = payload.rootNodeId ? payload.rootRemoved ? `Root node is absent: ${payload.rootNodeId}. Repeating the same assertion is safe.` : `Root node: ${payload.rootNodeId}.` : void 0;
|
|
803
|
+
const page = payload.page ? `Page: "${payload.page.name}" (${payload.page.id}) at index ${payload.page.index}; ${payload.page.active ? "active" : "not active"}, ${payload.page.removed ? "removed" : `${formatCount(payload.page.childCount, "child", "children")} and ${formatCount(payload.page.selectionCount, "selected node")}`}.` : void 0;
|
|
804
|
+
const identities = payload.rootNodeId && !payload.rootRemoved ? "\nRead structuredContent.nodeIdsByKey before a follow-up update or component instance call." : "";
|
|
805
|
+
return buildTextToolResult(`${summary}\n${verification}${warnings}\n${[root, page].filter(Boolean).join("\n")}${identities}`, {
|
|
806
|
+
...payload.rootNodeId ? { rootNodeId: payload.rootNodeId } : {},
|
|
807
|
+
...payload.rootRemoved ? { rootRemoved: true } : {},
|
|
808
|
+
nodeIdsByKey: payload.nodeIdsByKey,
|
|
809
|
+
mutationCount: payload.mutationCount,
|
|
810
|
+
nodeChanges,
|
|
811
|
+
...payload.page ? { page: payload.page } : {},
|
|
812
|
+
verification: payload.verification,
|
|
813
|
+
...payload.runtime ? { runtime: payload.runtime } : {}
|
|
814
|
+
});
|
|
815
|
+
}
|
|
816
|
+
function buildGetStructureToolResult(payload) {
|
|
817
|
+
const roots = payload.roots.length;
|
|
818
|
+
const nodeCount = countOutlineNodes(payload.roots);
|
|
819
|
+
const summary = roots === 0 ? "No structure nodes were returned." : `Returned ${payload.truncated ? "a truncated structure outline" : "structure outline"} with ${formatCount(roots, "root")} and ${formatCount(nodeCount, "node")}.`;
|
|
820
|
+
const guidance = payload.truncated ? "The outline is partial because the response safety cap was reached; narrow the selection or depth before treating it as complete." : "Read structuredContent for the full outline payload.";
|
|
821
|
+
return buildTextToolResult(`${summary}${payload.page ? ` Page "${payload.page.name}" (${payload.page.id}) is ${payload.page.active ? "active" : "not active"} with ${formatCount(payload.page.childCount, "child", "children")}.` : ""}\n${guidance}`, payload);
|
|
822
|
+
}
|
|
823
|
+
function buildGetTokenDefsToolResult(payload) {
|
|
824
|
+
const count = Object.keys(payload).length;
|
|
825
|
+
return buildTextToolResult(`${count === 0 ? "No token definitions were resolved." : `Resolved ${formatCount(count, "token definition")}.`}\nRead structuredContent for token values and aliases.`, payload);
|
|
826
|
+
}
|
|
827
|
+
function buildGetScreenshotToolResult(payload) {
|
|
828
|
+
const access = payload.asset.localPath ? `Open the local PNG directly with an image viewer: ${payload.asset.localPath}.` : "Download and open the linked PNG with an image viewer.";
|
|
829
|
+
return {
|
|
830
|
+
content: [{
|
|
831
|
+
type: "text",
|
|
832
|
+
text: `${describeScreenshot(payload)}. ${access} Receiving the asset reference alone is not visual verification. If this is a representative-screen check, inspect it before applying dependent screens.`
|
|
833
|
+
}, {
|
|
834
|
+
type: "resource_link",
|
|
835
|
+
uri: payload.asset.url,
|
|
836
|
+
name: `Figma screenshot ${payload.asset.hash}.png`,
|
|
837
|
+
description: `${payload.width}x${payload.height} rendered Figma node`,
|
|
838
|
+
mimeType: payload.asset.mimeType,
|
|
839
|
+
size: payload.asset.size
|
|
840
|
+
}],
|
|
841
|
+
structuredContent: payload
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
function buildGetAssetsToolResult(payload) {
|
|
845
|
+
const summary = [];
|
|
846
|
+
summary.push(payload.assets.length ? `Resolved ${formatCount(payload.assets.length, "asset")}.` : "No assets were resolved for the requested hashes.");
|
|
847
|
+
if (payload.missing.length) summary.push(`Missing: ${payload.missing.join(", ")}`);
|
|
848
|
+
summary.push("Use asset.localPath directly when present; otherwise download asset.url.");
|
|
849
|
+
return buildTextToolResult(summary.join("\n"), payload);
|
|
850
|
+
}
|
|
851
|
+
function buildUploadAssetToolResult(payload) {
|
|
852
|
+
return buildTextToolResult(`Stored generated image asset ${payload.assetHash} (${formatBytes(payload.size)}, ${payload.mimeType}). Use structuredContent.assetHash in an apply_canvas IMAGE asset declaration.`, payload);
|
|
853
|
+
}
|
|
854
|
+
function buildTextToolResult(text, structuredContent) {
|
|
855
|
+
return {
|
|
856
|
+
content: [{
|
|
857
|
+
type: "text",
|
|
858
|
+
text
|
|
859
|
+
}],
|
|
860
|
+
structuredContent
|
|
861
|
+
};
|
|
862
|
+
}
|
|
863
|
+
function countOutlineNodes(nodes) {
|
|
864
|
+
let count = 0;
|
|
865
|
+
const stack = [...nodes];
|
|
866
|
+
while (stack.length) {
|
|
867
|
+
const current = stack.pop();
|
|
868
|
+
if (!current) continue;
|
|
869
|
+
count += 1;
|
|
870
|
+
if (current.children?.length) stack.push(...current.children);
|
|
871
|
+
}
|
|
872
|
+
return count;
|
|
873
|
+
}
|
|
874
|
+
function formatBytes(bytes) {
|
|
875
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
876
|
+
if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`;
|
|
877
|
+
return `${(bytes / 1048576).toFixed(1)} MB`;
|
|
878
|
+
}
|
|
879
|
+
function formatCount(count, singular, plural = `${singular}s`) {
|
|
880
|
+
return `${count} ${count === 1 ? singular : plural}`;
|
|
881
|
+
}
|
|
882
|
+
function describeScreenshot(result) {
|
|
883
|
+
return `Screenshot ${result.width}x${result.height} @${result.scale}x (${formatBytes(result.bytes)})`;
|
|
884
|
+
}
|
|
885
|
+
const CanvasStableKeySchema = z.string().min(1).max(128).regex(/^[\w./:-]+$/, "Use a stable key containing letters, numbers, ., /, :, _, or -.");
|
|
886
|
+
const CanvasDesignReferenceSchema = z.object({
|
|
887
|
+
id: z.string().min(1).describe("Live Figma node, variable, or style id.").optional(),
|
|
888
|
+
key: z.string().min(1).describe("Importable Figma library key.").optional()
|
|
889
|
+
}).strict().refine((reference) => reference.id !== void 0 || reference.key !== void 0, { message: "A design-system reference requires id or key." });
|
|
890
|
+
const CanvasVariableReferenceSchema = z.union([CanvasDesignReferenceSchema, z.object({ variableKey: CanvasStableKeySchema.describe("Stable key of a local variable authored through apply_canvas.") }).strict()]);
|
|
891
|
+
const CanvasVariableCollectionReferenceSchema = z.union([CanvasDesignReferenceSchema, z.object({ collectionKey: CanvasStableKeySchema.describe("Stable key of a local variable collection authored through apply_canvas.") }).strict()]);
|
|
892
|
+
const CanvasStyleReferenceSchema = z.union([CanvasDesignReferenceSchema, z.object({ styleKey: CanvasStableKeySchema.describe("Stable key of a local style authored through apply_canvas.") }).strict()]);
|
|
893
|
+
function hasFields(value) {
|
|
894
|
+
return Object.keys(value).length > 0;
|
|
895
|
+
}
|
|
896
|
+
const CanvasNonnegativeNumberSchema = z.number().finite().min(0);
|
|
897
|
+
const CanvasUnitNumberSchema = z.number().finite().min(0).max(1);
|
|
898
|
+
const CanvasFiniteNumberSchema = z.number().finite();
|
|
899
|
+
const CanvasRgbSchema = z.object({
|
|
900
|
+
r: CanvasUnitNumberSchema,
|
|
901
|
+
g: CanvasUnitNumberSchema,
|
|
902
|
+
b: CanvasUnitNumberSchema
|
|
903
|
+
}).strict();
|
|
904
|
+
const CanvasRgbaSchema = CanvasRgbSchema.extend({ a: CanvasUnitNumberSchema }).strict();
|
|
905
|
+
const CanvasVectorSchema = z.object({
|
|
906
|
+
x: CanvasFiniteNumberSchema,
|
|
907
|
+
y: CanvasFiniteNumberSchema
|
|
908
|
+
}).strict();
|
|
909
|
+
const CanvasVariableAliasSchema = z.object({ variable: CanvasVariableReferenceSchema }).strict();
|
|
910
|
+
const CanvasFigmaShaderColorSchema = z.union([
|
|
911
|
+
CanvasRgbSchema,
|
|
912
|
+
CanvasRgbaSchema,
|
|
913
|
+
CanvasVariableAliasSchema
|
|
914
|
+
]);
|
|
915
|
+
const CanvasFigmaShaderPropertyValueSchema = z.union([
|
|
916
|
+
z.boolean(),
|
|
917
|
+
z.string(),
|
|
918
|
+
CanvasFiniteNumberSchema,
|
|
919
|
+
CanvasRgbSchema,
|
|
920
|
+
CanvasRgbaSchema,
|
|
921
|
+
CanvasVectorSchema,
|
|
922
|
+
CanvasVectorSchema.extend({
|
|
923
|
+
x2: CanvasFiniteNumberSchema,
|
|
924
|
+
y2: CanvasFiniteNumberSchema
|
|
925
|
+
}).strict(),
|
|
926
|
+
CanvasVectorSchema.extend({ radius: CanvasFiniteNumberSchema }).strict(),
|
|
927
|
+
CanvasVectorSchema.extend({
|
|
928
|
+
radius: CanvasFiniteNumberSchema,
|
|
929
|
+
angle: CanvasFiniteNumberSchema
|
|
930
|
+
}).strict(),
|
|
931
|
+
CanvasVectorSchema.extend({ color: CanvasFigmaShaderColorSchema }).strict(),
|
|
932
|
+
z.object({ stops: z.array(z.object({
|
|
933
|
+
position: CanvasFiniteNumberSchema,
|
|
934
|
+
color: CanvasFigmaShaderColorSchema
|
|
935
|
+
}).strict()) }).strict(),
|
|
936
|
+
CanvasVariableAliasSchema
|
|
937
|
+
]);
|
|
938
|
+
const CanvasBlendModeSchema = z.enum([
|
|
939
|
+
"PASS_THROUGH",
|
|
940
|
+
"NORMAL",
|
|
941
|
+
"DARKEN",
|
|
942
|
+
"MULTIPLY",
|
|
943
|
+
"LINEAR_BURN",
|
|
944
|
+
"COLOR_BURN",
|
|
945
|
+
"LIGHTEN",
|
|
946
|
+
"SCREEN",
|
|
947
|
+
"LINEAR_DODGE",
|
|
948
|
+
"COLOR_DODGE",
|
|
949
|
+
"OVERLAY",
|
|
950
|
+
"SOFT_LIGHT",
|
|
951
|
+
"HARD_LIGHT",
|
|
952
|
+
"DIFFERENCE",
|
|
953
|
+
"EXCLUSION",
|
|
954
|
+
"HUE",
|
|
955
|
+
"SATURATION",
|
|
956
|
+
"COLOR",
|
|
957
|
+
"LUMINOSITY"
|
|
958
|
+
]);
|
|
959
|
+
const CanvasTransformSchema = z.tuple([z.tuple([
|
|
960
|
+
CanvasFiniteNumberSchema,
|
|
961
|
+
CanvasFiniteNumberSchema,
|
|
962
|
+
CanvasFiniteNumberSchema
|
|
963
|
+
]), z.tuple([
|
|
964
|
+
CanvasFiniteNumberSchema,
|
|
965
|
+
CanvasFiniteNumberSchema,
|
|
966
|
+
CanvasFiniteNumberSchema
|
|
967
|
+
])]);
|
|
968
|
+
const CanvasRelativeTransformSchema = CanvasTransformSchema.refine(([[m00, m01], [m10, m11]]) => Math.abs(Math.hypot(m00, m10) - 1) <= 1e-6 && Math.abs(Math.hypot(m01, m11) - 1) <= 1e-6, { message: "Relative transform axes must each have unit length." });
|
|
969
|
+
const CanvasFigmaPaintVariablesSchema = z.object({ color: CanvasVariableReferenceSchema }).strict();
|
|
970
|
+
const CanvasFigmaPaintFields = {
|
|
971
|
+
visible: z.boolean().optional(),
|
|
972
|
+
opacity: CanvasUnitNumberSchema.optional(),
|
|
973
|
+
blendMode: CanvasBlendModeSchema.optional()
|
|
974
|
+
};
|
|
975
|
+
const CanvasFigmaImageFiltersSchema = z.object({
|
|
976
|
+
exposure: CanvasFiniteNumberSchema.min(-1).max(1).optional(),
|
|
977
|
+
contrast: CanvasFiniteNumberSchema.min(-1).max(1).optional(),
|
|
978
|
+
saturation: CanvasFiniteNumberSchema.min(-1).max(1).optional(),
|
|
979
|
+
temperature: CanvasFiniteNumberSchema.min(-1).max(1).optional(),
|
|
980
|
+
tint: CanvasFiniteNumberSchema.min(-1).max(1).optional(),
|
|
981
|
+
highlights: CanvasFiniteNumberSchema.min(-1).max(1).optional(),
|
|
982
|
+
shadows: CanvasFiniteNumberSchema.min(-1).max(1).optional()
|
|
983
|
+
}).strict().refine(hasFields, "Image filters cannot be empty.");
|
|
984
|
+
const CanvasFigmaMediaFields = {
|
|
985
|
+
filters: CanvasFigmaImageFiltersSchema.optional(),
|
|
986
|
+
rotation: CanvasFiniteNumberSchema.refine((rotation) => Number.isInteger(rotation / 90), { message: "Media rotation must be a multiple of 90 degrees." }).optional(),
|
|
987
|
+
...CanvasFigmaPaintFields
|
|
988
|
+
};
|
|
989
|
+
function isHttpUrl(value) {
|
|
990
|
+
try {
|
|
991
|
+
return ["http:", "https:"].includes(new URL(value).protocol);
|
|
992
|
+
} catch {
|
|
993
|
+
return false;
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
const CanvasFigmaImageSourceFields = {
|
|
997
|
+
imageHash: z.string().min(1).nullable().optional(),
|
|
998
|
+
imageUrl: z.string().refine(isHttpUrl, { message: "Image URL must use HTTP or HTTPS." }).optional(),
|
|
999
|
+
assetKey: CanvasStableKeySchema.optional()
|
|
1000
|
+
};
|
|
1001
|
+
function hasOneImageSource(paint) {
|
|
1002
|
+
return [
|
|
1003
|
+
paint.imageHash,
|
|
1004
|
+
paint.imageUrl,
|
|
1005
|
+
paint.assetKey
|
|
1006
|
+
].filter((source) => source !== void 0).length === 1;
|
|
1007
|
+
}
|
|
1008
|
+
const CanvasFigmaVideoSourceFields = {
|
|
1009
|
+
videoHash: z.string().min(1).nullable().optional(),
|
|
1010
|
+
videoUrl: z.string().refine(isHttpUrl, { message: "Video URL must use HTTP or HTTPS." }).optional()
|
|
1011
|
+
};
|
|
1012
|
+
function hasOneVideoSource(paint) {
|
|
1013
|
+
return paint.videoHash === void 0 !== (paint.videoUrl === void 0);
|
|
1014
|
+
}
|
|
1015
|
+
const CanvasFigmaImagePaintSchemas = [
|
|
1016
|
+
z.object({
|
|
1017
|
+
type: z.literal("IMAGE"),
|
|
1018
|
+
...CanvasFigmaImageSourceFields,
|
|
1019
|
+
scaleMode: z.enum(["FILL", "FIT"]),
|
|
1020
|
+
...CanvasFigmaMediaFields
|
|
1021
|
+
}).strict().refine(hasOneImageSource, { message: "Image paint requires exactly one of imageHash, imageUrl, or assetKey." }),
|
|
1022
|
+
z.object({
|
|
1023
|
+
type: z.literal("IMAGE"),
|
|
1024
|
+
...CanvasFigmaImageSourceFields,
|
|
1025
|
+
scaleMode: z.literal("CROP"),
|
|
1026
|
+
imageTransform: CanvasTransformSchema.optional(),
|
|
1027
|
+
filters: CanvasFigmaImageFiltersSchema.optional(),
|
|
1028
|
+
...CanvasFigmaPaintFields
|
|
1029
|
+
}).strict().refine(hasOneImageSource, { message: "Image paint requires exactly one of imageHash, imageUrl, or assetKey." }),
|
|
1030
|
+
z.object({
|
|
1031
|
+
type: z.literal("IMAGE"),
|
|
1032
|
+
...CanvasFigmaImageSourceFields,
|
|
1033
|
+
scaleMode: z.literal("TILE"),
|
|
1034
|
+
scalingFactor: CanvasFiniteNumberSchema.optional(),
|
|
1035
|
+
...CanvasFigmaMediaFields
|
|
1036
|
+
}).strict().refine(hasOneImageSource, { message: "Image paint requires exactly one of imageHash, imageUrl, or assetKey." })
|
|
1037
|
+
];
|
|
1038
|
+
const CanvasFigmaVideoPaintSchemas = [
|
|
1039
|
+
z.object({
|
|
1040
|
+
type: z.literal("VIDEO"),
|
|
1041
|
+
...CanvasFigmaVideoSourceFields,
|
|
1042
|
+
scaleMode: z.enum(["FILL", "FIT"]),
|
|
1043
|
+
...CanvasFigmaMediaFields
|
|
1044
|
+
}).strict().refine(hasOneVideoSource, { message: "Video paint requires exactly one of videoHash or videoUrl." }),
|
|
1045
|
+
z.object({
|
|
1046
|
+
type: z.literal("VIDEO"),
|
|
1047
|
+
...CanvasFigmaVideoSourceFields,
|
|
1048
|
+
scaleMode: z.literal("CROP"),
|
|
1049
|
+
videoTransform: CanvasTransformSchema.optional(),
|
|
1050
|
+
filters: CanvasFigmaImageFiltersSchema.optional(),
|
|
1051
|
+
...CanvasFigmaPaintFields
|
|
1052
|
+
}).strict().refine(hasOneVideoSource, { message: "Video paint requires exactly one of videoHash or videoUrl." }),
|
|
1053
|
+
z.object({
|
|
1054
|
+
type: z.literal("VIDEO"),
|
|
1055
|
+
...CanvasFigmaVideoSourceFields,
|
|
1056
|
+
scaleMode: z.literal("TILE"),
|
|
1057
|
+
scalingFactor: CanvasFiniteNumberSchema.optional(),
|
|
1058
|
+
...CanvasFigmaMediaFields
|
|
1059
|
+
}).strict().refine(hasOneVideoSource, { message: "Video paint requires exactly one of videoHash or videoUrl." })
|
|
1060
|
+
];
|
|
1061
|
+
const CanvasFigmaGradientStopSchema = z.object({
|
|
1062
|
+
position: CanvasUnitNumberSchema,
|
|
1063
|
+
color: CanvasRgbaSchema,
|
|
1064
|
+
variables: CanvasFigmaPaintVariablesSchema.optional()
|
|
1065
|
+
}).strict();
|
|
1066
|
+
const CanvasFigmaSolidPaintSchema = z.object({
|
|
1067
|
+
type: z.literal("SOLID"),
|
|
1068
|
+
color: CanvasRgbSchema,
|
|
1069
|
+
variables: CanvasFigmaPaintVariablesSchema.optional(),
|
|
1070
|
+
...CanvasFigmaPaintFields
|
|
1071
|
+
}).strict();
|
|
1072
|
+
const CanvasFigmaPaintSchema = z.union([
|
|
1073
|
+
CanvasFigmaSolidPaintSchema,
|
|
1074
|
+
z.object({
|
|
1075
|
+
type: z.enum([
|
|
1076
|
+
"GRADIENT_LINEAR",
|
|
1077
|
+
"GRADIENT_RADIAL",
|
|
1078
|
+
"GRADIENT_ANGULAR",
|
|
1079
|
+
"GRADIENT_DIAMOND"
|
|
1080
|
+
]),
|
|
1081
|
+
gradientTransform: CanvasTransformSchema,
|
|
1082
|
+
gradientStops: z.array(CanvasFigmaGradientStopSchema),
|
|
1083
|
+
...CanvasFigmaPaintFields
|
|
1084
|
+
}).strict(),
|
|
1085
|
+
...CanvasFigmaImagePaintSchemas,
|
|
1086
|
+
...CanvasFigmaVideoPaintSchemas,
|
|
1087
|
+
z.object({
|
|
1088
|
+
type: z.literal("PATTERN"),
|
|
1089
|
+
sourceNodeId: z.string().min(1).optional(),
|
|
1090
|
+
sourceCanvasKey: CanvasStableKeySchema.optional(),
|
|
1091
|
+
tileType: z.enum([
|
|
1092
|
+
"RECTANGULAR",
|
|
1093
|
+
"HORIZONTAL_HEXAGONAL",
|
|
1094
|
+
"VERTICAL_HEXAGONAL"
|
|
1095
|
+
]),
|
|
1096
|
+
scalingFactor: CanvasFiniteNumberSchema,
|
|
1097
|
+
spacing: CanvasVectorSchema,
|
|
1098
|
+
horizontalAlignment: z.enum([
|
|
1099
|
+
"START",
|
|
1100
|
+
"CENTER",
|
|
1101
|
+
"END"
|
|
1102
|
+
]),
|
|
1103
|
+
...CanvasFigmaPaintFields
|
|
1104
|
+
}).strict().refine((paint) => paint.sourceNodeId === void 0 !== (paint.sourceCanvasKey === void 0), { message: "Pattern paint requires exactly one of sourceNodeId or sourceCanvasKey." }),
|
|
1105
|
+
z.object({
|
|
1106
|
+
type: z.literal("SHADER"),
|
|
1107
|
+
id: z.string().min(1),
|
|
1108
|
+
properties: z.record(z.string().min(1), CanvasFigmaShaderPropertyValueSchema).optional(),
|
|
1109
|
+
...CanvasFigmaPaintFields
|
|
1110
|
+
}).strict()
|
|
1111
|
+
]);
|
|
1112
|
+
const CanvasFigmaShadowVariablesSchema = z.object({
|
|
1113
|
+
color: CanvasVariableReferenceSchema.optional(),
|
|
1114
|
+
radius: CanvasVariableReferenceSchema.optional(),
|
|
1115
|
+
spread: CanvasVariableReferenceSchema.optional(),
|
|
1116
|
+
offsetX: CanvasVariableReferenceSchema.optional(),
|
|
1117
|
+
offsetY: CanvasVariableReferenceSchema.optional()
|
|
1118
|
+
}).strict().refine(hasFields, "Shadow variable bindings cannot be empty.");
|
|
1119
|
+
const CanvasFigmaBlurVariablesSchema = z.object({ radius: CanvasVariableReferenceSchema }).strict();
|
|
1120
|
+
const CanvasFigmaShadowFields = {
|
|
1121
|
+
color: CanvasRgbaSchema,
|
|
1122
|
+
offset: CanvasVectorSchema,
|
|
1123
|
+
radius: CanvasNonnegativeNumberSchema,
|
|
1124
|
+
spread: CanvasFiniteNumberSchema.optional(),
|
|
1125
|
+
visible: z.boolean().optional(),
|
|
1126
|
+
blendMode: CanvasBlendModeSchema.optional(),
|
|
1127
|
+
variables: CanvasFigmaShadowVariablesSchema.optional()
|
|
1128
|
+
};
|
|
1129
|
+
const CanvasFigmaBlurFields = {
|
|
1130
|
+
radius: CanvasNonnegativeNumberSchema,
|
|
1131
|
+
visible: z.boolean().optional(),
|
|
1132
|
+
variables: CanvasFigmaBlurVariablesSchema.optional()
|
|
1133
|
+
};
|
|
1134
|
+
const CanvasFigmaNoiseFields = {
|
|
1135
|
+
type: z.literal("NOISE"),
|
|
1136
|
+
color: CanvasRgbaSchema,
|
|
1137
|
+
visible: z.boolean().optional(),
|
|
1138
|
+
blendMode: CanvasBlendModeSchema.optional(),
|
|
1139
|
+
noiseSize: CanvasFiniteNumberSchema,
|
|
1140
|
+
noiseSizeVector: CanvasVectorSchema.optional(),
|
|
1141
|
+
density: CanvasFiniteNumberSchema
|
|
1142
|
+
};
|
|
1143
|
+
function noiseSizeMatches(effect) {
|
|
1144
|
+
return effect.noiseSizeVector === void 0 || effect.noiseSizeVector.x === effect.noiseSize && effect.noiseSizeVector.y === effect.noiseSize;
|
|
1145
|
+
}
|
|
1146
|
+
const CanvasFigmaNoiseEffectSchema = z.discriminatedUnion("noiseType", [
|
|
1147
|
+
z.object({
|
|
1148
|
+
...CanvasFigmaNoiseFields,
|
|
1149
|
+
noiseType: z.literal("MONOTONE")
|
|
1150
|
+
}).strict(),
|
|
1151
|
+
z.object({
|
|
1152
|
+
...CanvasFigmaNoiseFields,
|
|
1153
|
+
noiseType: z.literal("DUOTONE"),
|
|
1154
|
+
secondaryColor: CanvasRgbaSchema
|
|
1155
|
+
}).strict(),
|
|
1156
|
+
z.object({
|
|
1157
|
+
...CanvasFigmaNoiseFields,
|
|
1158
|
+
noiseType: z.literal("MULTITONE"),
|
|
1159
|
+
opacity: CanvasFiniteNumberSchema
|
|
1160
|
+
}).strict()
|
|
1161
|
+
]).refine(noiseSizeMatches, {
|
|
1162
|
+
message: "noiseSizeVector.x and noiseSizeVector.y must equal noiseSize.",
|
|
1163
|
+
path: ["noiseSizeVector"]
|
|
1164
|
+
});
|
|
1165
|
+
const CanvasFigmaEffectSchema = z.union([
|
|
1166
|
+
z.object({
|
|
1167
|
+
type: z.literal("DROP_SHADOW"),
|
|
1168
|
+
...CanvasFigmaShadowFields,
|
|
1169
|
+
showShadowBehindNode: z.boolean().optional()
|
|
1170
|
+
}).strict(),
|
|
1171
|
+
z.object({
|
|
1172
|
+
type: z.literal("INNER_SHADOW"),
|
|
1173
|
+
...CanvasFigmaShadowFields
|
|
1174
|
+
}).strict(),
|
|
1175
|
+
z.object({
|
|
1176
|
+
type: z.enum(["LAYER_BLUR", "BACKGROUND_BLUR"]),
|
|
1177
|
+
...CanvasFigmaBlurFields,
|
|
1178
|
+
blurType: z.literal("NORMAL")
|
|
1179
|
+
}).strict(),
|
|
1180
|
+
z.object({
|
|
1181
|
+
type: z.enum(["LAYER_BLUR", "BACKGROUND_BLUR"]),
|
|
1182
|
+
...CanvasFigmaBlurFields,
|
|
1183
|
+
blurType: z.literal("PROGRESSIVE"),
|
|
1184
|
+
startRadius: CanvasFiniteNumberSchema,
|
|
1185
|
+
startOffset: CanvasVectorSchema,
|
|
1186
|
+
endOffset: CanvasVectorSchema
|
|
1187
|
+
}).strict(),
|
|
1188
|
+
CanvasFigmaNoiseEffectSchema,
|
|
1189
|
+
z.object({
|
|
1190
|
+
type: z.literal("TEXTURE"),
|
|
1191
|
+
visible: z.boolean().optional(),
|
|
1192
|
+
noiseSize: CanvasFiniteNumberSchema,
|
|
1193
|
+
noiseSizeVector: CanvasVectorSchema.optional(),
|
|
1194
|
+
radius: CanvasFiniteNumberSchema,
|
|
1195
|
+
clipToShape: z.boolean()
|
|
1196
|
+
}).strict().refine(noiseSizeMatches, {
|
|
1197
|
+
message: "noiseSizeVector.x and noiseSizeVector.y must equal noiseSize.",
|
|
1198
|
+
path: ["noiseSizeVector"]
|
|
1199
|
+
}),
|
|
1200
|
+
z.object({
|
|
1201
|
+
type: z.literal("GLASS"),
|
|
1202
|
+
visible: z.boolean().optional(),
|
|
1203
|
+
lightIntensity: CanvasUnitNumberSchema,
|
|
1204
|
+
lightAngle: CanvasFiniteNumberSchema,
|
|
1205
|
+
refraction: CanvasUnitNumberSchema,
|
|
1206
|
+
depth: CanvasFiniteNumberSchema.min(1),
|
|
1207
|
+
dispersion: CanvasUnitNumberSchema,
|
|
1208
|
+
radius: CanvasFiniteNumberSchema
|
|
1209
|
+
}).strict(),
|
|
1210
|
+
z.object({
|
|
1211
|
+
type: z.literal("SHADER"),
|
|
1212
|
+
id: z.string().min(1),
|
|
1213
|
+
visible: z.boolean().optional(),
|
|
1214
|
+
properties: z.record(z.string().min(1), CanvasFigmaShaderPropertyValueSchema).optional()
|
|
1215
|
+
}).strict()
|
|
1216
|
+
]);
|
|
1217
|
+
const CanvasNullableVariableReferenceSchema = CanvasVariableReferenceSchema.nullable();
|
|
1218
|
+
const CanvasVariableBindingsSchema = z.object({
|
|
1219
|
+
fill: CanvasNullableVariableReferenceSchema.optional(),
|
|
1220
|
+
stroke: CanvasNullableVariableReferenceSchema.optional(),
|
|
1221
|
+
characters: CanvasNullableVariableReferenceSchema.optional(),
|
|
1222
|
+
visible: CanvasNullableVariableReferenceSchema.optional(),
|
|
1223
|
+
width: CanvasNullableVariableReferenceSchema.optional(),
|
|
1224
|
+
height: CanvasNullableVariableReferenceSchema.optional(),
|
|
1225
|
+
minWidth: CanvasNullableVariableReferenceSchema.optional(),
|
|
1226
|
+
maxWidth: CanvasNullableVariableReferenceSchema.optional(),
|
|
1227
|
+
minHeight: CanvasNullableVariableReferenceSchema.optional(),
|
|
1228
|
+
maxHeight: CanvasNullableVariableReferenceSchema.optional(),
|
|
1229
|
+
gap: CanvasNullableVariableReferenceSchema.optional(),
|
|
1230
|
+
counterAxisSpacing: CanvasNullableVariableReferenceSchema.optional(),
|
|
1231
|
+
gridRowGap: CanvasNullableVariableReferenceSchema.optional(),
|
|
1232
|
+
gridColumnGap: CanvasNullableVariableReferenceSchema.optional(),
|
|
1233
|
+
paddingTop: CanvasNullableVariableReferenceSchema.optional(),
|
|
1234
|
+
paddingRight: CanvasNullableVariableReferenceSchema.optional(),
|
|
1235
|
+
paddingBottom: CanvasNullableVariableReferenceSchema.optional(),
|
|
1236
|
+
paddingLeft: CanvasNullableVariableReferenceSchema.optional(),
|
|
1237
|
+
cornerRadius: CanvasNullableVariableReferenceSchema.optional(),
|
|
1238
|
+
topLeftRadius: CanvasNullableVariableReferenceSchema.optional(),
|
|
1239
|
+
topRightRadius: CanvasNullableVariableReferenceSchema.optional(),
|
|
1240
|
+
bottomRightRadius: CanvasNullableVariableReferenceSchema.optional(),
|
|
1241
|
+
bottomLeftRadius: CanvasNullableVariableReferenceSchema.optional(),
|
|
1242
|
+
strokeWeight: CanvasNullableVariableReferenceSchema.optional(),
|
|
1243
|
+
strokeTopWeight: CanvasNullableVariableReferenceSchema.optional(),
|
|
1244
|
+
strokeRightWeight: CanvasNullableVariableReferenceSchema.optional(),
|
|
1245
|
+
strokeBottomWeight: CanvasNullableVariableReferenceSchema.optional(),
|
|
1246
|
+
strokeLeftWeight: CanvasNullableVariableReferenceSchema.optional(),
|
|
1247
|
+
opacity: CanvasNullableVariableReferenceSchema.optional(),
|
|
1248
|
+
fontFamily: CanvasNullableVariableReferenceSchema.optional(),
|
|
1249
|
+
fontStyle: CanvasNullableVariableReferenceSchema.optional(),
|
|
1250
|
+
fontWeight: CanvasNullableVariableReferenceSchema.optional(),
|
|
1251
|
+
fontSize: CanvasNullableVariableReferenceSchema.optional(),
|
|
1252
|
+
lineHeight: CanvasNullableVariableReferenceSchema.optional(),
|
|
1253
|
+
letterSpacing: CanvasNullableVariableReferenceSchema.optional(),
|
|
1254
|
+
paragraphIndent: CanvasNullableVariableReferenceSchema.optional(),
|
|
1255
|
+
paragraphSpacing: CanvasNullableVariableReferenceSchema.optional()
|
|
1256
|
+
}).strict().refine(hasFields, "Variable bindings cannot be empty.");
|
|
1257
|
+
const CanvasVariableModesSchema = z.record(z.string().min(1), z.string().min(1).nullable()).refine(hasFields, "Variable mode overrides cannot be empty.");
|
|
1258
|
+
const CANVAS_VARIABLE_SCOPES = [
|
|
1259
|
+
"ALL_SCOPES",
|
|
1260
|
+
"TEXT_CONTENT",
|
|
1261
|
+
"CORNER_RADIUS",
|
|
1262
|
+
"WIDTH_HEIGHT",
|
|
1263
|
+
"GAP",
|
|
1264
|
+
"ALL_FILLS",
|
|
1265
|
+
"FRAME_FILL",
|
|
1266
|
+
"SHAPE_FILL",
|
|
1267
|
+
"TEXT_FILL",
|
|
1268
|
+
"STROKE_COLOR",
|
|
1269
|
+
"STROKE_FLOAT",
|
|
1270
|
+
"EFFECT_FLOAT",
|
|
1271
|
+
"EFFECT_COLOR",
|
|
1272
|
+
"OPACITY",
|
|
1273
|
+
"FONT_FAMILY",
|
|
1274
|
+
"FONT_STYLE",
|
|
1275
|
+
"FONT_WEIGHT",
|
|
1276
|
+
"FONT_SIZE",
|
|
1277
|
+
"LINE_HEIGHT",
|
|
1278
|
+
"LETTER_SPACING",
|
|
1279
|
+
"PARAGRAPH_SPACING",
|
|
1280
|
+
"PARAGRAPH_INDENT"
|
|
1281
|
+
];
|
|
1282
|
+
const CanvasVariableScopeSchema = z.enum(CANVAS_VARIABLE_SCOPES, { error: `Invalid variable scope. Use one of: ${CANVAS_VARIABLE_SCOPES.join(", ")}.` });
|
|
1283
|
+
const CANVAS_VARIABLE_FILL_SCOPES = [
|
|
1284
|
+
"FRAME_FILL",
|
|
1285
|
+
"SHAPE_FILL",
|
|
1286
|
+
"TEXT_FILL"
|
|
1287
|
+
];
|
|
1288
|
+
const CanvasVariableValueSchema = z.union([
|
|
1289
|
+
z.boolean(),
|
|
1290
|
+
z.string(),
|
|
1291
|
+
CanvasFiniteNumberSchema,
|
|
1292
|
+
CanvasRgbSchema,
|
|
1293
|
+
CanvasRgbaSchema,
|
|
1294
|
+
CanvasVariableAliasSchema
|
|
1295
|
+
]);
|
|
1296
|
+
const CanvasVariableModeResourceSchema = z.object({
|
|
1297
|
+
id: z.string().min(1).optional(),
|
|
1298
|
+
name: z.string().min(1).optional()
|
|
1299
|
+
}).strict().refine(hasFields, "A variable mode requires an id or desired name.");
|
|
1300
|
+
const CanvasVariableCodeSyntaxSchema = z.object({
|
|
1301
|
+
WEB: z.string().min(1).nullable().optional(),
|
|
1302
|
+
ANDROID: z.string().min(1).nullable().optional(),
|
|
1303
|
+
iOS: z.string().min(1).nullable().optional()
|
|
1304
|
+
}).strict().refine(hasFields, "Variable code syntax cannot be empty.");
|
|
1305
|
+
const CanvasVariableResourceSchema = z.object({
|
|
1306
|
+
id: z.string().min(1).optional(),
|
|
1307
|
+
name: z.string().min(1).optional(),
|
|
1308
|
+
type: z.enum([
|
|
1309
|
+
"BOOLEAN",
|
|
1310
|
+
"COLOR",
|
|
1311
|
+
"FLOAT",
|
|
1312
|
+
"STRING"
|
|
1313
|
+
]).optional(),
|
|
1314
|
+
description: z.string().optional(),
|
|
1315
|
+
hiddenFromPublishing: z.boolean().optional(),
|
|
1316
|
+
scopes: z.array(CanvasVariableScopeSchema).refine((scopes) => new Set(scopes).size === scopes.length, { message: "Variable scopes cannot contain duplicates." }).superRefine((scopes, context) => {
|
|
1317
|
+
if (scopes.includes("ALL_SCOPES") && scopes.length > 1) context.addIssue({
|
|
1318
|
+
code: "custom",
|
|
1319
|
+
message: "ALL_SCOPES cannot be combined with another variable scope."
|
|
1320
|
+
});
|
|
1321
|
+
if (scopes.includes("ALL_FILLS") && CANVAS_VARIABLE_FILL_SCOPES.some((scope) => scopes.includes(scope))) context.addIssue({
|
|
1322
|
+
code: "custom",
|
|
1323
|
+
message: "ALL_FILLS cannot be combined with FRAME_FILL, SHAPE_FILL, or TEXT_FILL."
|
|
1324
|
+
});
|
|
1325
|
+
}).optional(),
|
|
1326
|
+
codeSyntax: CanvasVariableCodeSyntaxSchema.optional(),
|
|
1327
|
+
values: z.record(z.string().min(1), CanvasVariableValueSchema).refine(hasFields, "Variable values cannot be empty.").optional()
|
|
1328
|
+
}).strict().refine(hasFields, "A variable resource cannot be empty.");
|
|
1329
|
+
const CanvasExtendedVariableOverrideSchema = z.object({
|
|
1330
|
+
variable: CanvasVariableReferenceSchema.describe("Inherited variable to override in this extended collection."),
|
|
1331
|
+
values: z.record(z.string().min(1), CanvasVariableValueSchema.nullable()).refine(hasFields, "Extended variable override values cannot be empty.").describe("Extended-mode IDs, inherited parent-mode IDs, or parent authoring keys to override values; null removes an existing override.")
|
|
1332
|
+
}).strict();
|
|
1333
|
+
const CanvasVariableCollectionResourceSchema = z.object({
|
|
1334
|
+
id: z.string().min(1).optional(),
|
|
1335
|
+
name: z.string().min(1).optional(),
|
|
1336
|
+
hiddenFromPublishing: z.boolean().optional(),
|
|
1337
|
+
extends: CanvasVariableCollectionReferenceSchema.describe("Existing local or published parent collection for a new extended collection.").optional(),
|
|
1338
|
+
modes: z.record(CanvasStableKeySchema, CanvasVariableModeResourceSchema.nullable()).refine(hasFields, "Variable collection modes cannot be empty.").optional(),
|
|
1339
|
+
overrides: z.array(CanvasExtendedVariableOverrideSchema).min(1).describe("Explicit inherited-variable overrides for an extended collection.").optional(),
|
|
1340
|
+
variables: z.record(CanvasStableKeySchema, CanvasVariableResourceSchema.nullable()).refine(hasFields, "Variable collection variables cannot be empty.").optional()
|
|
1341
|
+
}).strict().refine(hasFields, "A variable collection resource cannot be empty.");
|
|
1342
|
+
const CanvasVariableCollectionsSchema = z.record(CanvasStableKeySchema, CanvasVariableCollectionResourceSchema.nullable()).refine(hasFields, "Variable collections cannot be empty.").superRefine((collections, context) => {
|
|
1343
|
+
const variableKeys = /* @__PURE__ */ new Set();
|
|
1344
|
+
let count = 0;
|
|
1345
|
+
for (const [collectionKey, collection] of Object.entries(collections)) {
|
|
1346
|
+
if (collection === null) {
|
|
1347
|
+
count += 1;
|
|
1348
|
+
continue;
|
|
1349
|
+
}
|
|
1350
|
+
count += 1 + Object.keys(collection.modes ?? {}).length + (collection.overrides?.length ?? 0);
|
|
1351
|
+
for (const variableKey of Object.keys(collection.variables ?? {})) {
|
|
1352
|
+
if (variableKeys.has(variableKey)) context.addIssue({
|
|
1353
|
+
code: "custom",
|
|
1354
|
+
message: `Variable key "${variableKey}" is duplicated.`,
|
|
1355
|
+
path: [
|
|
1356
|
+
collectionKey,
|
|
1357
|
+
"variables",
|
|
1358
|
+
variableKey
|
|
1359
|
+
]
|
|
1360
|
+
});
|
|
1361
|
+
variableKeys.add(variableKey);
|
|
1362
|
+
count += 1;
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
if (count > 100) context.addIssue({
|
|
1366
|
+
code: "custom",
|
|
1367
|
+
message: `Variable collections may describe at most 100 resources.`
|
|
1368
|
+
});
|
|
1369
|
+
});
|
|
1370
|
+
const CanvasStyleBindingsSchema = z.object({
|
|
1371
|
+
fill: CanvasStyleReferenceSchema.nullable().optional(),
|
|
1372
|
+
stroke: CanvasStyleReferenceSchema.nullable().optional(),
|
|
1373
|
+
text: CanvasStyleReferenceSchema.nullable().optional(),
|
|
1374
|
+
effect: CanvasStyleReferenceSchema.nullable().optional(),
|
|
1375
|
+
grid: CanvasStyleReferenceSchema.nullable().optional()
|
|
1376
|
+
}).strict().refine(hasFields, "Style bindings cannot be empty.");
|
|
1377
|
+
const CanvasTextCaseSchema = z.enum([
|
|
1378
|
+
"ORIGINAL",
|
|
1379
|
+
"UPPER",
|
|
1380
|
+
"LOWER",
|
|
1381
|
+
"TITLE",
|
|
1382
|
+
"SMALL_CAPS",
|
|
1383
|
+
"SMALL_CAPS_FORCED"
|
|
1384
|
+
]);
|
|
1385
|
+
const CanvasHyperlinkSchema = z.discriminatedUnion("type", [z.object({
|
|
1386
|
+
type: z.literal("URL"),
|
|
1387
|
+
value: z.string().min(1)
|
|
1388
|
+
}).strict(), z.object({
|
|
1389
|
+
type: z.literal("NODE"),
|
|
1390
|
+
value: z.union([z.string().min(1), z.object({ canvasKey: CanvasStableKeySchema }).strict()])
|
|
1391
|
+
}).strict()]).nullable();
|
|
1392
|
+
const CanvasAutoOrTextMeasureSchema = z.union([z.object({ unit: z.literal("AUTO") }).strict(), z.object({
|
|
1393
|
+
unit: z.enum(["PIXELS", "PERCENT"]),
|
|
1394
|
+
value: z.number().finite()
|
|
1395
|
+
}).strict()]);
|
|
1396
|
+
const CanvasLetterSpacingSchema = z.object({
|
|
1397
|
+
unit: z.enum(["PIXELS", "PERCENT"]),
|
|
1398
|
+
value: z.number().finite()
|
|
1399
|
+
}).strict();
|
|
1400
|
+
const CanvasFontNameSchema = z.object({
|
|
1401
|
+
family: z.string().min(1),
|
|
1402
|
+
style: z.string().min(1)
|
|
1403
|
+
}).strict();
|
|
1404
|
+
function textVariableBindings(kind) {
|
|
1405
|
+
return z.object({
|
|
1406
|
+
fontFamily: CanvasNullableVariableReferenceSchema.optional(),
|
|
1407
|
+
fontSize: CanvasNullableVariableReferenceSchema.optional(),
|
|
1408
|
+
fontStyle: CanvasNullableVariableReferenceSchema.optional(),
|
|
1409
|
+
fontWeight: CanvasNullableVariableReferenceSchema.optional(),
|
|
1410
|
+
letterSpacing: CanvasNullableVariableReferenceSchema.optional(),
|
|
1411
|
+
lineHeight: CanvasNullableVariableReferenceSchema.optional(),
|
|
1412
|
+
paragraphSpacing: CanvasNullableVariableReferenceSchema.optional(),
|
|
1413
|
+
paragraphIndent: CanvasNullableVariableReferenceSchema.optional()
|
|
1414
|
+
}).strict().refine(hasFields, `Text-${kind} variable bindings cannot be empty.`);
|
|
1415
|
+
}
|
|
1416
|
+
const CanvasFigmaTextRangeVariablesSchema = textVariableBindings("range");
|
|
1417
|
+
const CanvasFigmaTextRangeSchema = z.object({
|
|
1418
|
+
start: z.number().int().min(0),
|
|
1419
|
+
end: z.number().int().min(1),
|
|
1420
|
+
fontName: CanvasFontNameSchema.optional(),
|
|
1421
|
+
fontSize: z.number().finite().min(1).optional(),
|
|
1422
|
+
textCase: CanvasTextCaseSchema.optional(),
|
|
1423
|
+
letterSpacing: CanvasLetterSpacingSchema.optional(),
|
|
1424
|
+
lineHeight: CanvasAutoOrTextMeasureSchema.optional(),
|
|
1425
|
+
textDecoration: z.enum([
|
|
1426
|
+
"NONE",
|
|
1427
|
+
"UNDERLINE",
|
|
1428
|
+
"STRIKETHROUGH"
|
|
1429
|
+
]).optional(),
|
|
1430
|
+
textDecorationStyle: z.enum([
|
|
1431
|
+
"SOLID",
|
|
1432
|
+
"WAVY",
|
|
1433
|
+
"DOTTED"
|
|
1434
|
+
]).optional(),
|
|
1435
|
+
textDecorationOffset: CanvasAutoOrTextMeasureSchema.optional(),
|
|
1436
|
+
textDecorationThickness: CanvasAutoOrTextMeasureSchema.optional(),
|
|
1437
|
+
textDecorationColor: z.union([z.object({ value: z.literal("AUTO") }).strict(), z.object({ value: CanvasFigmaSolidPaintSchema }).strict()]).optional(),
|
|
1438
|
+
textDecorationSkipInk: z.boolean().optional(),
|
|
1439
|
+
fills: z.array(CanvasFigmaPaintSchema).optional(),
|
|
1440
|
+
textStyle: CanvasStyleReferenceSchema.nullable().optional(),
|
|
1441
|
+
fillStyle: CanvasStyleReferenceSchema.nullable().optional(),
|
|
1442
|
+
listOptions: z.object({ type: z.enum([
|
|
1443
|
+
"ORDERED",
|
|
1444
|
+
"UNORDERED",
|
|
1445
|
+
"NONE"
|
|
1446
|
+
]) }).strict().optional(),
|
|
1447
|
+
listSpacing: z.number().finite().optional(),
|
|
1448
|
+
indentation: z.number().finite().optional(),
|
|
1449
|
+
paragraphIndent: z.number().finite().optional(),
|
|
1450
|
+
paragraphSpacing: z.number().finite().optional(),
|
|
1451
|
+
hyperlink: CanvasHyperlinkSchema.optional(),
|
|
1452
|
+
variables: CanvasFigmaTextRangeVariablesSchema.optional()
|
|
1453
|
+
}).strict().superRefine((range, context) => {
|
|
1454
|
+
if (range.end <= range.start) context.addIssue({
|
|
1455
|
+
code: "custom",
|
|
1456
|
+
message: "Text-range end must be greater than start.",
|
|
1457
|
+
path: ["end"]
|
|
1458
|
+
});
|
|
1459
|
+
if (Object.keys(range).every((field) => field === "start" || field === "end")) context.addIssue({
|
|
1460
|
+
code: "custom",
|
|
1461
|
+
message: "A text range requires at least one desired field."
|
|
1462
|
+
});
|
|
1463
|
+
if (range.fills !== void 0 && range.fillStyle !== void 0) context.addIssue({
|
|
1464
|
+
code: "custom",
|
|
1465
|
+
message: "A text range cannot combine direct fills and a fill style.",
|
|
1466
|
+
path: ["fills"]
|
|
1467
|
+
});
|
|
1468
|
+
});
|
|
1469
|
+
const CanvasFigmaTextPropertiesSchema = z.object({
|
|
1470
|
+
autoRename: z.boolean().optional(),
|
|
1471
|
+
fontName: CanvasFontNameSchema.optional(),
|
|
1472
|
+
verticalAlign: z.enum([
|
|
1473
|
+
"TOP",
|
|
1474
|
+
"CENTER",
|
|
1475
|
+
"BOTTOM"
|
|
1476
|
+
]).optional(),
|
|
1477
|
+
case: CanvasTextCaseSchema.optional(),
|
|
1478
|
+
paragraphIndent: z.number().finite().optional(),
|
|
1479
|
+
paragraphSpacing: z.number().finite().optional(),
|
|
1480
|
+
listSpacing: z.number().finite().optional(),
|
|
1481
|
+
hangingPunctuation: z.boolean().optional(),
|
|
1482
|
+
hangingList: z.boolean().optional(),
|
|
1483
|
+
leadingTrim: z.enum(["CAP_HEIGHT", "NONE"]).optional(),
|
|
1484
|
+
hyperlink: CanvasHyperlinkSchema.optional(),
|
|
1485
|
+
ranges: z.array(CanvasFigmaTextRangeSchema).min(1).superRefine((ranges, context) => {
|
|
1486
|
+
for (let index = 1; index < ranges.length; index += 1) if (ranges[index].start < ranges[index - 1].end) context.addIssue({
|
|
1487
|
+
code: "custom",
|
|
1488
|
+
message: "Text ranges must be ordered and non-overlapping.",
|
|
1489
|
+
path: [index, "start"]
|
|
1490
|
+
});
|
|
1491
|
+
}).optional()
|
|
1492
|
+
}).strict().refine(hasFields, "Figma text properties cannot be empty.");
|
|
1493
|
+
const CanvasFigmaArcSchema = z.object({
|
|
1494
|
+
startAngle: z.number().finite().describe("Clockwise degrees from the positive x-axis."),
|
|
1495
|
+
endAngle: z.number().finite().describe("Clockwise degrees from the positive x-axis."),
|
|
1496
|
+
innerRadius: CanvasUnitNumberSchema
|
|
1497
|
+
}).strict();
|
|
1498
|
+
const CanvasStrokeCapSchema = z.enum([
|
|
1499
|
+
"NONE",
|
|
1500
|
+
"ROUND",
|
|
1501
|
+
"SQUARE",
|
|
1502
|
+
"ARROW_LINES",
|
|
1503
|
+
"ARROW_EQUILATERAL",
|
|
1504
|
+
"DIAMOND_FILLED",
|
|
1505
|
+
"TRIANGLE_FILLED",
|
|
1506
|
+
"CIRCLE_FILLED"
|
|
1507
|
+
]);
|
|
1508
|
+
const CanvasStrokeJoinSchema = z.enum([
|
|
1509
|
+
"MITER",
|
|
1510
|
+
"BEVEL",
|
|
1511
|
+
"ROUND"
|
|
1512
|
+
]);
|
|
1513
|
+
const CanvasHandleMirroringSchema = z.enum([
|
|
1514
|
+
"NONE",
|
|
1515
|
+
"ANGLE",
|
|
1516
|
+
"ANGLE_AND_LENGTH"
|
|
1517
|
+
]);
|
|
1518
|
+
const CanvasFigmaVectorVertexSchema = CanvasVectorSchema.extend({
|
|
1519
|
+
strokeCap: CanvasStrokeCapSchema.optional(),
|
|
1520
|
+
strokeJoin: CanvasStrokeJoinSchema.optional(),
|
|
1521
|
+
cornerRadius: CanvasNonnegativeNumberSchema.optional(),
|
|
1522
|
+
handleMirroring: CanvasHandleMirroringSchema.optional()
|
|
1523
|
+
}).strict();
|
|
1524
|
+
const CanvasFigmaVectorSegmentSchema = z.object({
|
|
1525
|
+
start: z.number().int().nonnegative(),
|
|
1526
|
+
end: z.number().int().nonnegative(),
|
|
1527
|
+
tangentStart: CanvasVectorSchema.optional(),
|
|
1528
|
+
tangentEnd: CanvasVectorSchema.optional()
|
|
1529
|
+
}).strict();
|
|
1530
|
+
const CanvasFigmaVectorRegionSchema = z.object({
|
|
1531
|
+
windingRule: z.enum(["NONZERO", "EVENODD"]),
|
|
1532
|
+
loops: z.array(z.array(z.number().int().nonnegative()).min(1)).min(1),
|
|
1533
|
+
fills: z.array(CanvasFigmaPaintSchema).optional(),
|
|
1534
|
+
fillStyle: CanvasStyleReferenceSchema.optional()
|
|
1535
|
+
}).strict().refine((region) => !(region.fills && region.fillStyle), { message: "A vector region cannot combine direct fills with a fill style." });
|
|
1536
|
+
function vectorLoopCloses(loop, segments) {
|
|
1537
|
+
const first = segments[loop[0]];
|
|
1538
|
+
if (!first) return true;
|
|
1539
|
+
const walk = (start, next) => {
|
|
1540
|
+
let vertex = next;
|
|
1541
|
+
for (const segmentIndex of loop.slice(1)) {
|
|
1542
|
+
const segment = segments[segmentIndex];
|
|
1543
|
+
if (!segment) return true;
|
|
1544
|
+
if (segment.start === vertex) vertex = segment.end;
|
|
1545
|
+
else if (segment.end === vertex) vertex = segment.start;
|
|
1546
|
+
else return false;
|
|
1547
|
+
}
|
|
1548
|
+
return vertex === start;
|
|
1549
|
+
};
|
|
1550
|
+
return walk(first.start, first.end) || walk(first.end, first.start);
|
|
1551
|
+
}
|
|
1552
|
+
const CanvasFigmaVectorNetworkSchema = z.object({
|
|
1553
|
+
vertices: z.array(CanvasFigmaVectorVertexSchema),
|
|
1554
|
+
segments: z.array(CanvasFigmaVectorSegmentSchema),
|
|
1555
|
+
regions: z.array(CanvasFigmaVectorRegionSchema).optional()
|
|
1556
|
+
}).strict().superRefine((network, context) => {
|
|
1557
|
+
network.segments.forEach((segment, index) => {
|
|
1558
|
+
for (const field of ["start", "end"]) if (segment[field] >= network.vertices.length) context.addIssue({
|
|
1559
|
+
code: "custom",
|
|
1560
|
+
message: `Vector segment ${field} must reference an existing vertex.`,
|
|
1561
|
+
path: [
|
|
1562
|
+
"segments",
|
|
1563
|
+
index,
|
|
1564
|
+
field
|
|
1565
|
+
]
|
|
1566
|
+
});
|
|
1567
|
+
});
|
|
1568
|
+
network.regions?.forEach((region, regionIndex) => {
|
|
1569
|
+
region.loops.forEach((loop, loopIndex) => {
|
|
1570
|
+
for (const [index, segment] of loop.entries()) if (segment >= network.segments.length) context.addIssue({
|
|
1571
|
+
code: "custom",
|
|
1572
|
+
message: "Vector region loops must reference existing segments.",
|
|
1573
|
+
path: [
|
|
1574
|
+
"regions",
|
|
1575
|
+
regionIndex,
|
|
1576
|
+
"loops",
|
|
1577
|
+
loopIndex,
|
|
1578
|
+
index
|
|
1579
|
+
]
|
|
1580
|
+
});
|
|
1581
|
+
if (loop.every((segment) => segment < network.segments.length) && !vectorLoopCloses(loop, network.segments)) context.addIssue({
|
|
1582
|
+
code: "custom",
|
|
1583
|
+
message: "Vector region loops must form a closed continuous chain.",
|
|
1584
|
+
path: [
|
|
1585
|
+
"regions",
|
|
1586
|
+
regionIndex,
|
|
1587
|
+
"loops",
|
|
1588
|
+
loopIndex
|
|
1589
|
+
]
|
|
1590
|
+
});
|
|
1591
|
+
});
|
|
1592
|
+
});
|
|
1593
|
+
});
|
|
1594
|
+
const CanvasFigmaVectorPathSchema = z.object({
|
|
1595
|
+
windingRule: z.enum([
|
|
1596
|
+
"NONE",
|
|
1597
|
+
"NONZERO",
|
|
1598
|
+
"EVENODD"
|
|
1599
|
+
]),
|
|
1600
|
+
data: z.string().trim().min(1)
|
|
1601
|
+
}).strict();
|
|
1602
|
+
const CanvasFigmaShapeSchema = z.discriminatedUnion("type", [
|
|
1603
|
+
z.object({ type: z.literal("RECTANGLE") }).strict(),
|
|
1604
|
+
z.object({ type: z.literal("LINE") }).strict(),
|
|
1605
|
+
z.object({
|
|
1606
|
+
type: z.literal("ELLIPSE"),
|
|
1607
|
+
arc: CanvasFigmaArcSchema.optional()
|
|
1608
|
+
}).strict(),
|
|
1609
|
+
z.object({
|
|
1610
|
+
type: z.literal("POLYGON"),
|
|
1611
|
+
pointCount: z.number().int().min(3).optional()
|
|
1612
|
+
}).strict(),
|
|
1613
|
+
z.object({
|
|
1614
|
+
type: z.literal("STAR"),
|
|
1615
|
+
pointCount: z.number().int().min(3).optional(),
|
|
1616
|
+
innerRadius: CanvasUnitNumberSchema.optional()
|
|
1617
|
+
}).strict(),
|
|
1618
|
+
z.object({
|
|
1619
|
+
type: z.literal("VECTOR"),
|
|
1620
|
+
paths: z.array(CanvasFigmaVectorPathSchema).optional(),
|
|
1621
|
+
network: CanvasFigmaVectorNetworkSchema.optional(),
|
|
1622
|
+
handleMirroring: CanvasHandleMirroringSchema.optional()
|
|
1623
|
+
}).strict()
|
|
1624
|
+
]).superRefine((shape, context) => {
|
|
1625
|
+
if (shape.type === "VECTOR" && shape.paths !== void 0 && shape.network !== void 0) context.addIssue({
|
|
1626
|
+
code: "custom",
|
|
1627
|
+
message: "A vector shape cannot combine paths with a vector network."
|
|
1628
|
+
});
|
|
1629
|
+
});
|
|
1630
|
+
const CanvasSideValuesSchema = z.object({
|
|
1631
|
+
top: CanvasNonnegativeNumberSchema,
|
|
1632
|
+
right: CanvasNonnegativeNumberSchema,
|
|
1633
|
+
bottom: CanvasNonnegativeNumberSchema,
|
|
1634
|
+
left: CanvasNonnegativeNumberSchema
|
|
1635
|
+
}).strict();
|
|
1636
|
+
const CanvasFigmaStrokePropertiesSchema = z.object({
|
|
1637
|
+
weight: CanvasNonnegativeNumberSchema.optional(),
|
|
1638
|
+
weights: CanvasSideValuesSchema.optional(),
|
|
1639
|
+
align: z.enum([
|
|
1640
|
+
"CENTER",
|
|
1641
|
+
"INSIDE",
|
|
1642
|
+
"OUTSIDE"
|
|
1643
|
+
]).optional(),
|
|
1644
|
+
cap: CanvasStrokeCapSchema.optional(),
|
|
1645
|
+
join: CanvasStrokeJoinSchema.optional(),
|
|
1646
|
+
miterLimit: z.number().finite().min(1).optional(),
|
|
1647
|
+
dashPattern: z.array(CanvasNonnegativeNumberSchema).optional()
|
|
1648
|
+
}).strict().refine(hasFields, "Figma stroke properties cannot be empty.").refine((stroke) => !(stroke.weight !== void 0 && stroke.weights), { message: "Uniform and individual stroke weights cannot be combined." });
|
|
1649
|
+
const CanvasCornerRadiiSchema = z.object({
|
|
1650
|
+
topLeft: CanvasNonnegativeNumberSchema,
|
|
1651
|
+
topRight: CanvasNonnegativeNumberSchema,
|
|
1652
|
+
bottomRight: CanvasNonnegativeNumberSchema,
|
|
1653
|
+
bottomLeft: CanvasNonnegativeNumberSchema
|
|
1654
|
+
}).strict();
|
|
1655
|
+
const CanvasFigmaCornerPropertiesSchema = z.object({
|
|
1656
|
+
radius: CanvasNonnegativeNumberSchema.optional(),
|
|
1657
|
+
radii: CanvasCornerRadiiSchema.optional(),
|
|
1658
|
+
smoothing: CanvasUnitNumberSchema.optional()
|
|
1659
|
+
}).strict().refine(hasFields, "Figma corner properties cannot be empty.").refine((corners) => !(corners.radius !== void 0 && corners.radii), { message: "Uniform and individual corner radii cannot be combined." });
|
|
1660
|
+
const CanvasFigmaAutoLayoutPropertiesSchema = z.object({
|
|
1661
|
+
itemSpacing: CanvasFiniteNumberSchema.optional(),
|
|
1662
|
+
counterAxisSpacing: CanvasFiniteNumberSchema.positive().nullable().optional(),
|
|
1663
|
+
itemReverseZIndex: z.boolean().optional()
|
|
1664
|
+
}).strict().refine(hasFields, "Figma Auto Layout properties cannot be empty.");
|
|
1665
|
+
const CanvasFigmaLayoutGridVariablesSchema = z.object({
|
|
1666
|
+
sectionSize: CanvasVariableReferenceSchema.optional(),
|
|
1667
|
+
count: CanvasVariableReferenceSchema.optional(),
|
|
1668
|
+
offset: CanvasVariableReferenceSchema.optional(),
|
|
1669
|
+
gutterSize: CanvasVariableReferenceSchema.optional()
|
|
1670
|
+
}).strict().refine(hasFields, "Layout-grid variable bindings cannot be empty.");
|
|
1671
|
+
const CanvasFigmaLayoutGridSchema = z.discriminatedUnion("pattern", [z.object({
|
|
1672
|
+
pattern: z.enum(["ROWS", "COLUMNS"]),
|
|
1673
|
+
alignment: z.enum([
|
|
1674
|
+
"MIN",
|
|
1675
|
+
"MAX",
|
|
1676
|
+
"STRETCH",
|
|
1677
|
+
"CENTER"
|
|
1678
|
+
]),
|
|
1679
|
+
gutterSize: CanvasFiniteNumberSchema,
|
|
1680
|
+
count: z.union([z.number().int().positive(), z.literal("AUTO")]),
|
|
1681
|
+
sectionSize: CanvasFiniteNumberSchema.optional(),
|
|
1682
|
+
offset: CanvasFiniteNumberSchema.optional(),
|
|
1683
|
+
visible: z.boolean().optional(),
|
|
1684
|
+
color: CanvasRgbaSchema.optional(),
|
|
1685
|
+
variables: CanvasFigmaLayoutGridVariablesSchema.optional()
|
|
1686
|
+
}).strict(), z.object({
|
|
1687
|
+
pattern: z.literal("GRID"),
|
|
1688
|
+
sectionSize: CanvasFiniteNumberSchema,
|
|
1689
|
+
visible: z.boolean().optional(),
|
|
1690
|
+
color: CanvasRgbaSchema.optional(),
|
|
1691
|
+
variables: z.object({ sectionSize: CanvasVariableReferenceSchema }).strict().optional()
|
|
1692
|
+
}).strict()]).superRefine((grid, context) => {
|
|
1693
|
+
if (grid.pattern === "GRID") return;
|
|
1694
|
+
if (grid.alignment === "STRETCH" && (grid.sectionSize !== void 0 || grid.variables?.sectionSize)) context.addIssue({
|
|
1695
|
+
code: "custom",
|
|
1696
|
+
message: "STRETCH layout grids cannot set or bind ignored sectionSize.",
|
|
1697
|
+
path: ["sectionSize"]
|
|
1698
|
+
});
|
|
1699
|
+
if (grid.alignment === "CENTER" && (grid.offset !== void 0 || grid.variables?.offset)) context.addIssue({
|
|
1700
|
+
code: "custom",
|
|
1701
|
+
message: "CENTER layout grids cannot set or bind ignored offset.",
|
|
1702
|
+
path: ["offset"]
|
|
1703
|
+
});
|
|
1704
|
+
});
|
|
1705
|
+
const CanvasTextStyleVariablesSchema = textVariableBindings("style");
|
|
1706
|
+
const CanvasStyleResourceFields = {
|
|
1707
|
+
id: z.string().min(1).optional(),
|
|
1708
|
+
name: z.string().min(1).optional(),
|
|
1709
|
+
descriptionMarkdown: z.string().optional(),
|
|
1710
|
+
documentationLink: z.string().url().nullable().optional()
|
|
1711
|
+
};
|
|
1712
|
+
const CanvasStyleResourceSchema = z.discriminatedUnion("type", [
|
|
1713
|
+
z.object({
|
|
1714
|
+
...CanvasStyleResourceFields,
|
|
1715
|
+
type: z.literal("PAINT"),
|
|
1716
|
+
paints: z.array(CanvasFigmaPaintSchema).optional()
|
|
1717
|
+
}).strict(),
|
|
1718
|
+
z.object({
|
|
1719
|
+
...CanvasStyleResourceFields,
|
|
1720
|
+
type: z.literal("TEXT"),
|
|
1721
|
+
fontName: CanvasFontNameSchema.optional(),
|
|
1722
|
+
fontSize: z.number().finite().min(1).optional(),
|
|
1723
|
+
textDecoration: z.enum([
|
|
1724
|
+
"NONE",
|
|
1725
|
+
"UNDERLINE",
|
|
1726
|
+
"STRIKETHROUGH"
|
|
1727
|
+
]).optional(),
|
|
1728
|
+
letterSpacing: CanvasLetterSpacingSchema.optional(),
|
|
1729
|
+
lineHeight: CanvasAutoOrTextMeasureSchema.optional(),
|
|
1730
|
+
leadingTrim: z.enum(["CAP_HEIGHT", "NONE"]).optional(),
|
|
1731
|
+
paragraphIndent: z.number().finite().optional(),
|
|
1732
|
+
paragraphSpacing: z.number().finite().optional(),
|
|
1733
|
+
listSpacing: z.number().finite().optional(),
|
|
1734
|
+
hangingPunctuation: z.boolean().optional(),
|
|
1735
|
+
hangingList: z.boolean().optional(),
|
|
1736
|
+
textCase: CanvasTextCaseSchema.optional(),
|
|
1737
|
+
variables: CanvasTextStyleVariablesSchema.optional()
|
|
1738
|
+
}).strict(),
|
|
1739
|
+
z.object({
|
|
1740
|
+
...CanvasStyleResourceFields,
|
|
1741
|
+
type: z.literal("EFFECT"),
|
|
1742
|
+
effects: z.array(CanvasFigmaEffectSchema).optional()
|
|
1743
|
+
}).strict(),
|
|
1744
|
+
z.object({
|
|
1745
|
+
...CanvasStyleResourceFields,
|
|
1746
|
+
type: z.literal("GRID"),
|
|
1747
|
+
layoutGrids: z.array(CanvasFigmaLayoutGridSchema).optional()
|
|
1748
|
+
}).strict()
|
|
1749
|
+
]);
|
|
1750
|
+
const CanvasStylesSchema = z.record(CanvasStableKeySchema, CanvasStyleResourceSchema.nullable()).refine(hasFields, "Styles cannot be empty.").refine((styles) => Object.keys(styles).length <= 100, { message: `Styles may describe at most 100 resources.` });
|
|
1751
|
+
const CanvasFigmaGuideSchema = z.object({
|
|
1752
|
+
axis: z.enum(["X", "Y"]),
|
|
1753
|
+
offset: CanvasFiniteNumberSchema
|
|
1754
|
+
}).strict();
|
|
1755
|
+
const CanvasPagePropertiesSchema = z.object({
|
|
1756
|
+
id: z.string().min(1).describe("Existing local page id to target or adopt.").optional(),
|
|
1757
|
+
pageKey: CanvasStableKeySchema.describe("Stable key of a local page authored through apply_canvas.").optional(),
|
|
1758
|
+
name: z.string().trim().min(1).max(256).optional(),
|
|
1759
|
+
index: z.number().int().nonnegative().describe("Zero-based position of the page in the Figma document.").optional(),
|
|
1760
|
+
background: CanvasRgbaSchema.describe("The page canvas background as its single supported solid RGBA color.").optional(),
|
|
1761
|
+
guides: z.array(CanvasFigmaGuideSchema).describe("Ordered guides on the page containing the applied result.").optional(),
|
|
1762
|
+
variableModes: CanvasVariableModesSchema.describe("Explicit collection modes inherited by nodes on the result page.").optional()
|
|
1763
|
+
}).strict().refine(hasFields, "Page properties cannot be empty.");
|
|
1764
|
+
const CanvasPageSnapshotSchema = z.object({
|
|
1765
|
+
id: z.string().min(1),
|
|
1766
|
+
pageKey: CanvasStableKeySchema.optional(),
|
|
1767
|
+
name: z.string().min(1),
|
|
1768
|
+
index: z.number().int().nonnegative(),
|
|
1769
|
+
active: z.boolean(),
|
|
1770
|
+
removed: z.literal(true).optional(),
|
|
1771
|
+
childCount: z.number().int().nonnegative(),
|
|
1772
|
+
selectionCount: z.number().int().nonnegative()
|
|
1773
|
+
}).strict();
|
|
1774
|
+
const CanvasFigmaInstancePropertiesSchema = z.object({
|
|
1775
|
+
scaleFactor: CanvasFiniteNumberSchema.min(.01).optional(),
|
|
1776
|
+
exposed: z.boolean().optional(),
|
|
1777
|
+
preserveOverrides: z.boolean().describe("Whether a changed component binding preserves existing instance overrides. Omission preserves them.").optional()
|
|
1778
|
+
}).strict().refine(hasFields, "Figma instance properties cannot be empty.");
|
|
1779
|
+
const CanvasFigmaSectionPropertiesSchema = z.object({ contentsHidden: z.boolean().optional() }).strict();
|
|
1780
|
+
const CanvasFigmaBooleanOperationSchema = z.enum([
|
|
1781
|
+
"UNION",
|
|
1782
|
+
"SUBTRACT",
|
|
1783
|
+
"INTERSECT",
|
|
1784
|
+
"EXCLUDE"
|
|
1785
|
+
]);
|
|
1786
|
+
const CanvasFigmaComponentPreferredValueSchema = z.object({
|
|
1787
|
+
type: z.enum(["COMPONENT", "COMPONENT_SET"]),
|
|
1788
|
+
key: z.string().min(1)
|
|
1789
|
+
}).strict();
|
|
1790
|
+
const CanvasFigmaComponentPropertyDefinitionSchema = z.discriminatedUnion("type", [
|
|
1791
|
+
z.object({
|
|
1792
|
+
type: z.literal("BOOLEAN"),
|
|
1793
|
+
name: z.string().min(1),
|
|
1794
|
+
defaultValue: z.union([z.boolean(), CanvasVariableAliasSchema])
|
|
1795
|
+
}).strict(),
|
|
1796
|
+
z.object({
|
|
1797
|
+
type: z.literal("TEXT"),
|
|
1798
|
+
name: z.string().min(1),
|
|
1799
|
+
defaultValue: z.union([z.string(), CanvasVariableAliasSchema])
|
|
1800
|
+
}).strict(),
|
|
1801
|
+
z.object({
|
|
1802
|
+
type: z.literal("INSTANCE_SWAP"),
|
|
1803
|
+
name: z.string().min(1),
|
|
1804
|
+
defaultValue: z.union([CanvasDesignReferenceSchema, CanvasVariableAliasSchema]),
|
|
1805
|
+
preferredValues: z.array(CanvasFigmaComponentPreferredValueSchema).optional()
|
|
1806
|
+
}).strict()
|
|
1807
|
+
]);
|
|
1808
|
+
const CanvasFigmaComponentPropertiesSchema = z.record(z.string().min(1).max(256), CanvasFigmaComponentPropertyDefinitionSchema.nullable()).refine(hasFields, "Component property patches cannot be empty.");
|
|
1809
|
+
const CanvasFigmaAuthoredComponentSchema = z.object({
|
|
1810
|
+
type: z.enum(["COMPONENT", "COMPONENT_SET"]),
|
|
1811
|
+
descriptionMarkdown: z.string().optional(),
|
|
1812
|
+
documentationLink: z.string().url().nullable().optional(),
|
|
1813
|
+
properties: CanvasFigmaComponentPropertiesSchema.describe("Component-property definitions keyed by a stable logical name or an existing exact Figma property name. A definition creates or updates it; null explicitly deletes it.").optional()
|
|
1814
|
+
}).strict();
|
|
1815
|
+
const CanvasFigmaSlotSettingsSchema = z.object({
|
|
1816
|
+
stretchChildOnInsert: z.boolean().optional(),
|
|
1817
|
+
displayEmptyByDefault: z.boolean().optional(),
|
|
1818
|
+
minChildren: z.number().int().nonnegative().nullable().optional(),
|
|
1819
|
+
maxChildren: z.number().int().nonnegative().nullable().optional(),
|
|
1820
|
+
allowPreferredValuesOnly: z.boolean().optional()
|
|
1821
|
+
}).strict().refine(hasFields, "Slot settings cannot be empty.").superRefine((settings, context) => {
|
|
1822
|
+
if (settings.minChildren != null && settings.maxChildren != null && settings.minChildren > settings.maxChildren) context.addIssue({
|
|
1823
|
+
code: "custom",
|
|
1824
|
+
message: "Slot minChildren cannot exceed maxChildren."
|
|
1825
|
+
});
|
|
1826
|
+
});
|
|
1827
|
+
const CanvasFigmaSlotSchema = z.object({ property: z.object({
|
|
1828
|
+
name: z.string().min(1),
|
|
1829
|
+
description: z.string().optional(),
|
|
1830
|
+
preferredValues: z.array(CanvasFigmaComponentPreferredValueSchema).optional(),
|
|
1831
|
+
settings: CanvasFigmaSlotSettingsSchema.optional()
|
|
1832
|
+
}).strict().optional() }).strict();
|
|
1833
|
+
const CanvasFigmaComponentPropertyReferencesSchema = z.object({
|
|
1834
|
+
visible: z.string().min(1).max(256).nullable().optional(),
|
|
1835
|
+
characters: z.string().min(1).max(256).nullable().optional(),
|
|
1836
|
+
mainComponent: z.string().min(1).max(256).nullable().optional()
|
|
1837
|
+
}).strict().refine(hasFields, "Component property references cannot be empty.");
|
|
1838
|
+
const CanvasSvgPlacementSchema = z.object({
|
|
1839
|
+
assetKey: CanvasStableKeySchema,
|
|
1840
|
+
color: z.string().regex(/^#[0-9A-Fa-f]{6}(?:[0-9A-Fa-f]{2})?$/).optional()
|
|
1841
|
+
}).strict();
|
|
1842
|
+
const CanvasFigmaPropertiesSchema = z.object({
|
|
1843
|
+
name: z.string().optional(),
|
|
1844
|
+
locked: z.boolean().optional(),
|
|
1845
|
+
aspectRatioLocked: z.boolean().optional(),
|
|
1846
|
+
relativeTransform: CanvasRelativeTransformSchema.describe("Native translation, rotation, and skew matrix. Auto Layout computes child translation. Create roots preserve the axes but use automatic placement. Width and height remain separate.").optional(),
|
|
1847
|
+
mask: z.enum([
|
|
1848
|
+
"ALPHA",
|
|
1849
|
+
"VECTOR",
|
|
1850
|
+
"LUMINANCE"
|
|
1851
|
+
]).nullable().describe("Native sibling mask. A type enables it, null disables it, and omission preserves it.").optional(),
|
|
1852
|
+
autoLayout: CanvasFigmaAutoLayoutPropertiesSchema.describe("Native linear Auto Layout spacing and stacking with no honest CSS equivalent.").optional(),
|
|
1853
|
+
layoutGrids: z.array(CanvasFigmaLayoutGridSchema).describe("Ordered frame layout grids. Omit to preserve live grids; use [] to clear them.").optional(),
|
|
1854
|
+
guides: z.array(CanvasFigmaGuideSchema).describe("Ordered frame guides. Omit to preserve live guides; use [] to clear them.").optional(),
|
|
1855
|
+
instance: CanvasFigmaInstancePropertiesSchema.describe("Native instance-only scale-tool factor, component-swap override policy, and existing primary nested-instance exposure state.").optional(),
|
|
1856
|
+
section: CanvasFigmaSectionPropertiesSchema.describe("Native section container for organizing screens. An empty object selects the node type; contentsHidden controls whether its contents are collapsed on the canvas.").optional(),
|
|
1857
|
+
group: z.literal(true).describe("Native intrinsic group fitted to its children. Repeat true on updates to preserve the node kind.").optional(),
|
|
1858
|
+
booleanOperation: CanvasFigmaBooleanOperationSchema.describe("Native non-destructive boolean operation fitted to its shape or text children.").optional(),
|
|
1859
|
+
component: CanvasFigmaAuthoredComponentSchema.describe("Native authored component or component set. Keep descriptionMarkdown and documentationLink inside this component object, beside type and properties.").optional(),
|
|
1860
|
+
slot: CanvasFigmaSlotSchema.describe("Native slot frame. An empty object preserves an existing slot; new slots require property metadata.").optional(),
|
|
1861
|
+
svg: CanvasSvgPlacementSchema.describe("Figma-native import of a declared SVG asset into a childless managed frame.").optional(),
|
|
1862
|
+
componentPropertyReferences: CanvasFigmaComponentPropertyReferencesSchema.describe("Links a component sublayer field to a stable or exact component-property definition name. Null clears one link. A visible reference controls layer visibility; an Auto Layout flow child may trigger a layout-affecting warning.").optional(),
|
|
1863
|
+
text: CanvasFigmaTextPropertiesSchema.optional(),
|
|
1864
|
+
shape: CanvasFigmaShapeSchema.describe("Native editable shape for a childless div. Repeat it on updates to preserve the node kind; omitted geometry preserves live update values.").optional(),
|
|
1865
|
+
stroke: CanvasFigmaStrokePropertiesSchema.describe("Figma stroke geometry. It does not create a stroke paint.").optional(),
|
|
1866
|
+
corners: CanvasFigmaCornerPropertiesSchema.describe("Figma corner geometry for nodes that expose corner properties.").optional(),
|
|
1867
|
+
effects: z.array(CanvasFigmaEffectSchema).describe("Ordered native Figma effect stack. Omit to preserve live effects; use [] to clear them.").optional(),
|
|
1868
|
+
fills: z.array(CanvasFigmaPaintSchema).describe("Ordered native Figma fill stack. Omit to preserve live fills; use [] to clear them.").optional(),
|
|
1869
|
+
strokes: z.array(CanvasFigmaPaintSchema).describe("Ordered native Figma stroke-paint stack. Omit to preserve live strokes; use [] to clear them.").optional()
|
|
1870
|
+
}).strict().refine(hasFields, "Figma properties cannot be empty.").refine((properties) => [
|
|
1871
|
+
properties.text,
|
|
1872
|
+
properties.shape,
|
|
1873
|
+
properties.section,
|
|
1874
|
+
properties.group,
|
|
1875
|
+
properties.booleanOperation,
|
|
1876
|
+
properties.component,
|
|
1877
|
+
properties.slot,
|
|
1878
|
+
properties.svg
|
|
1879
|
+
].filter(Boolean).length < 2, { message: "Figma text, shape, section, group, boolean-operation, authored-component, slot, and SVG properties are mutually exclusive." }).refine((properties) => !(properties.name !== void 0 && properties.text?.autoRename), {
|
|
1880
|
+
message: "An auto-renamed text node cannot also declare a fixed layer name.",
|
|
1881
|
+
path: ["name"]
|
|
1882
|
+
});
|
|
1883
|
+
const CanvasComponentPropertyValueSchema = z.union([
|
|
1884
|
+
z.string(),
|
|
1885
|
+
z.boolean(),
|
|
1886
|
+
CanvasVariableAliasSchema
|
|
1887
|
+
]);
|
|
1888
|
+
const CanvasBindingSchema = z.object({
|
|
1889
|
+
component: CanvasDesignReferenceSchema.describe("Design-system component used by the childless div with this data-key.").optional(),
|
|
1890
|
+
componentProperties: z.record(z.string().min(1), CanvasComponentPropertyValueSchema).describe("Exposed component values. Direct values remove a variable alias, variable references bind one, and omission preserves the property.").optional(),
|
|
1891
|
+
variables: CanvasVariableBindingsSchema.describe("Figma variable bindings for the markup node. References bind and null clears; bindings win over literal classes.").optional(),
|
|
1892
|
+
variableModes: CanvasVariableModesSchema.describe("Explicit mode by variable collection id. A mode id sets the override and null clears it.").optional(),
|
|
1893
|
+
styles: CanvasStyleBindingsSchema.describe("Figma style bindings for the markup node. References apply, null unlinks, and non-null styles win over literal classes.").optional(),
|
|
1894
|
+
figma: CanvasFigmaPropertiesSchema.describe("Typed Figma-only node state that has no honest HTML or Tailwind equivalent.").optional()
|
|
1895
|
+
}).strict().superRefine((binding, context) => {
|
|
1896
|
+
if (!binding.component && !binding.componentProperties && !binding.variables && !binding.variableModes && !binding.styles && !binding.figma) context.addIssue({
|
|
1897
|
+
code: "custom",
|
|
1898
|
+
message: "A canvas binding requires a component, variables, variable modes, styles, or Figma properties."
|
|
1899
|
+
});
|
|
1900
|
+
if (binding.component && (binding.figma?.shape || binding.figma?.section || binding.figma?.group || binding.figma?.booleanOperation || binding.figma?.component || binding.figma?.slot || binding.figma?.svg)) context.addIssue({
|
|
1901
|
+
code: "custom",
|
|
1902
|
+
message: "A component binding cannot also create a native shape, section, group, boolean operation, authored component, slot, or SVG.",
|
|
1903
|
+
path: ["figma"]
|
|
1904
|
+
});
|
|
1905
|
+
});
|
|
1906
|
+
const MAX_CANVAS_MARKUP_LENGTH = 2e5;
|
|
1907
|
+
const CanvasBindingsSchema = z.record(CanvasStableKeySchema, CanvasBindingSchema).refine((bindings) => Object.keys(bindings).length <= 160, { message: `Canvas bindings may contain at most 160 entries.` });
|
|
1908
|
+
const CanvasRemoveKeysSchema = z.array(CanvasStableKeySchema).max(160).refine((keys) => new Set(keys).size === keys.length, { message: "removeKeys cannot contain duplicate stable keys." });
|
|
1909
|
+
const CanvasAssetHashSchema = z.string().regex(MCP_HASH_PATTERN);
|
|
1910
|
+
const CanvasAssetSchema = z.union([
|
|
1911
|
+
z.object({
|
|
1912
|
+
type: z.literal("SVG"),
|
|
1913
|
+
svg: z.string().min(1).max(32768)
|
|
1914
|
+
}).strict(),
|
|
1915
|
+
z.object({
|
|
1916
|
+
type: z.literal("SVG"),
|
|
1917
|
+
assetHash: CanvasAssetHashSchema
|
|
1918
|
+
}).strict(),
|
|
1919
|
+
z.object({
|
|
1920
|
+
type: z.literal("IMAGE"),
|
|
1921
|
+
assetHash: CanvasAssetHashSchema
|
|
1922
|
+
}).strict()
|
|
1923
|
+
]);
|
|
1924
|
+
const CanvasAssetsSchema = z.record(CanvasStableKeySchema, CanvasAssetSchema).refine((assets) => Object.keys(assets).length <= 32, { message: "Canvas assets may contain at most 32 entries." }).refine((assets) => Object.values(assets).reduce((bytes, asset) => bytes + ("svg" in asset ? new TextEncoder().encode(asset.svg).byteLength : 0), 0) <= 65536, { message: "Inline SVG assets may contain at most 64 KiB in total." });
|
|
1925
|
+
const CanvasNativeBindingSchema = z.object({
|
|
1926
|
+
component: z.object({ id: z.string().min(1) }).strict().describe("Exact live component or component-set id from prior canvas work.").optional(),
|
|
1927
|
+
componentProperties: z.record(z.string().min(1), CanvasComponentPropertyValueSchema).describe("Values keyed by an exact Figma property name or a TemPad-authored stable key.").optional(),
|
|
1928
|
+
variables: z.record(z.string(), z.object({ variableKey: CanvasStableKeySchema }).strict().nullable()).describe("Local authored-variable bindings and explicit null removals.").optional(),
|
|
1929
|
+
variableModes: z.record(z.string(), z.string().nullable()).describe("Explicit collection modes; catalog kN/mN_M refs require catalogId.").optional(),
|
|
1930
|
+
styles: z.object({
|
|
1931
|
+
fill: z.object({ styleKey: CanvasStableKeySchema }).strict().nullable().optional(),
|
|
1932
|
+
stroke: z.object({ styleKey: CanvasStableKeySchema }).strict().nullable().optional(),
|
|
1933
|
+
text: z.object({ styleKey: CanvasStableKeySchema }).strict().nullable().optional(),
|
|
1934
|
+
effect: z.object({ styleKey: CanvasStableKeySchema }).strict().nullable().optional(),
|
|
1935
|
+
grid: z.object({ styleKey: CanvasStableKeySchema }).strict().nullable().optional()
|
|
1936
|
+
}).strict().describe("Local authored-style bindings and explicit null removals.").optional(),
|
|
1937
|
+
figma: z.record(z.string(), z.unknown()).describe("Strict desired state for the selected Figma-native capability. Use the matching progressive reference from the canvas-authoring skill for its exact shape.").optional()
|
|
1938
|
+
}).strict();
|
|
1939
|
+
const CanvasThemeSchema = z.object({
|
|
1940
|
+
variables: z.record(z.string().regex(/^--[a-zA-Z0-9_-]+$/), z.union([z.object({ ref: z.string().min(1) }).strict(), z.object({ variableKey: CanvasStableKeySchema }).strict()])).optional(),
|
|
1941
|
+
textStyles: z.record(z.string().regex(/^type-[a-zA-Z0-9_-]+$/), z.union([z.object({ ref: z.string().min(1) }).strict(), z.object({ styleKey: CanvasStableKeySchema }).strict()])).optional()
|
|
1942
|
+
}).strict();
|
|
1943
|
+
function validateCanvasApplyScope(value, context) {
|
|
1944
|
+
const issue = (message, path) => context.addIssue({
|
|
1945
|
+
code: "custom",
|
|
1946
|
+
message,
|
|
1947
|
+
path: [path]
|
|
1948
|
+
});
|
|
1949
|
+
const hasResources = [
|
|
1950
|
+
"bindings",
|
|
1951
|
+
"native",
|
|
1952
|
+
"catalogId",
|
|
1953
|
+
"theme",
|
|
1954
|
+
"variableCollections",
|
|
1955
|
+
"styles",
|
|
1956
|
+
"assets",
|
|
1957
|
+
"removeKeys"
|
|
1958
|
+
].some((field) => value[field] !== void 0);
|
|
1959
|
+
const pageIdentity = value.page?.id !== void 0 || value.page?.pageKey !== void 0;
|
|
1960
|
+
if (value.theme !== void 0 && value.markup === void 0) issue("theme requires markup.", "theme");
|
|
1961
|
+
if (value.mode === "create") {
|
|
1962
|
+
if (value.targetNodeId !== void 0) issue("targetNodeId is not valid in create mode.", "targetNodeId");
|
|
1963
|
+
if (value.removeKeys !== void 0) issue("removeKeys is only valid in update mode.", "removeKeys");
|
|
1964
|
+
if (value.selection !== void 0) issue("selection is only valid in activate mode.", "selection");
|
|
1965
|
+
if (value.markup === void 0 && value.page === void 0) issue("Create mode requires markup or page.", "markup");
|
|
1966
|
+
if (value.markup === void 0) {
|
|
1967
|
+
if (hasResources) issue("Page-only create cannot include node or resource fields.", "markup");
|
|
1968
|
+
if (!value.page?.pageKey) issue("Page-only create requires page.pageKey.", "page");
|
|
1969
|
+
if (!value.page?.name) issue("Page-only create requires page.name.", "page");
|
|
1970
|
+
if (value.page?.id) issue("Page-only create cannot include page.id.", "page");
|
|
1971
|
+
}
|
|
1972
|
+
return;
|
|
1973
|
+
}
|
|
1974
|
+
if (value.mode === "update") {
|
|
1975
|
+
if (value.selection !== void 0) issue("selection is only valid in activate mode.", "selection");
|
|
1976
|
+
if (value.markup !== void 0 && value.targetNodeId === void 0) issue("A markup update requires targetNodeId.", "targetNodeId");
|
|
1977
|
+
if (value.markup === void 0) {
|
|
1978
|
+
if (value.targetNodeId !== void 0) {
|
|
1979
|
+
if (value.page !== void 0) issue("Native-only update cannot include page.", "page");
|
|
1980
|
+
if (value.removeKeys !== void 0) issue("Native-only update cannot remove nodes.", "removeKeys");
|
|
1981
|
+
const bindings = value.native ?? value.bindings;
|
|
1982
|
+
if (!bindings || typeof bindings !== "object" || Array.isArray(bindings) || Object.keys(bindings).length === 0) issue("Native-only update requires native node state.", "native");
|
|
1983
|
+
return;
|
|
1984
|
+
}
|
|
1985
|
+
if (hasResources) issue("Page-only update cannot include node or resource fields.", "markup");
|
|
1986
|
+
if (!value.page) issue("Update mode requires markup or page.", "markup");
|
|
1987
|
+
if (value.page && !pageIdentity) issue("Page-only update requires page.id or page.pageKey.", "page");
|
|
1988
|
+
}
|
|
1989
|
+
return;
|
|
1990
|
+
}
|
|
1991
|
+
if (value.mode === "remove") {
|
|
1992
|
+
if (value.markup !== void 0) issue("Remove mode cannot include markup.", "markup");
|
|
1993
|
+
if (hasResources) issue("Remove mode cannot include node or resource fields.", "markup");
|
|
1994
|
+
if (value.selection !== void 0) issue("selection is only valid in activate mode.", "selection");
|
|
1995
|
+
if (value.targetNodeId === void 0 === (value.page === void 0)) issue("Remove mode requires exactly one of targetNodeId or page.", "targetNodeId");
|
|
1996
|
+
if (value.page) {
|
|
1997
|
+
if (!value.page.pageKey) issue("Page removal requires page.pageKey.", "page");
|
|
1998
|
+
if (Object.keys(value.page).some((field) => field !== "id" && field !== "pageKey")) issue("Page removal accepts only page.id and page.pageKey.", "page");
|
|
1999
|
+
}
|
|
2000
|
+
return;
|
|
2001
|
+
}
|
|
2002
|
+
if (value.targetNodeId !== void 0) issue("targetNodeId is not valid in activate mode.", "targetNodeId");
|
|
2003
|
+
if (value.markup !== void 0) issue("Activate mode cannot include markup.", "markup");
|
|
2004
|
+
if (hasResources) issue("Activate mode cannot include node or resource fields.", "markup");
|
|
2005
|
+
if (!value.page || !pageIdentity) issue("Activate mode requires page.id or page.pageKey.", "page");
|
|
2006
|
+
if (value.page) {
|
|
2007
|
+
if (Object.keys(value.page).some((field) => field !== "id" && field !== "pageKey")) issue("Activate mode accepts only page.id and page.pageKey.", "page");
|
|
2008
|
+
}
|
|
2009
|
+
}
|
|
2010
|
+
const ApplyCanvasParametersSchema = z.object({
|
|
2011
|
+
taskId: DesignTaskParameterSchema,
|
|
2012
|
+
taskEpoch: DesignTaskEpochSchema,
|
|
2013
|
+
mode: z.enum([
|
|
2014
|
+
"create",
|
|
2015
|
+
"update",
|
|
2016
|
+
"remove",
|
|
2017
|
+
"activate"
|
|
2018
|
+
]),
|
|
2019
|
+
targetNodeId: z.string().min(1).optional(),
|
|
2020
|
+
catalogId: z.string().min(1).optional(),
|
|
2021
|
+
theme: CanvasThemeSchema.describe("Call-scoped aliases: CSS custom property names to catalog variable refs or local variableKey; type-* classes to catalog text-style refs or local styleKey. Catalog cssName/className aliases work automatically.").optional(),
|
|
2022
|
+
markup: z.string().trim().min(1).max(MAX_CANVAS_MARKUP_LENGTH).describe(`Canvas HTML serialization of the desired managed Figma layer tree, with at most 160 elements and 12 levels. Conflicting classes are rejected, not resolved by order: replace default font sizes, colors, or line heights instead of appending overrides. When catalogId is supplied, use its component tags and bind its variable or style refs with data-var-<field>="vN" or data-style-<field>="sN"; use "none" to unlink.`).optional(),
|
|
2023
|
+
native: z.record(CanvasStableKeySchema, CanvasNativeBindingSchema).describe("Desired native Figma state and bindings for selected capabilities. With markup, every native key must match a data-key in that supplied tree, even for existing nodes. Without markup, update may bind existing stable keys inside targetNodeId. For a mixed structural/native edit, include the bound nodes in the supplied structure or use a separate native-only update.").optional(),
|
|
2024
|
+
variableCollections: z.record(CanvasStableKeySchema, z.unknown()).describe("Optional local variable collections, modes, and variables keyed by file-wide authoring identities. This does not require catalogId; use the canvas-authoring variables reference for the exact shape.").optional(),
|
|
2025
|
+
styles: z.record(CanvasStableKeySchema, z.unknown()).describe("Optional local Paint, Text, Effect, and Grid styles keyed by file-wide authoring identities. This does not require catalogId; use the canvas-authoring local-styles reference for the exact shape.").optional(),
|
|
2026
|
+
assets: z.record(CanvasStableKeySchema, z.unknown()).describe("Optional call-scoped inline SVG or content-addressed Hub assets referenced by native desired state.").optional(),
|
|
2027
|
+
removeKeys: CanvasRemoveKeysSchema.optional(),
|
|
2028
|
+
page: z.record(z.string(), z.unknown()).describe("Optional local page identity and desired state. Use the canvas-authoring document-geometry reference for the exact shape.").optional(),
|
|
2029
|
+
selection: z.array(z.string().min(1)).max(100).describe("Exact scene-node ids to select after activate; an empty array clears selection and omission preserves it.").optional()
|
|
2030
|
+
}).strict().superRefine(validateCanvasApplyScope);
|
|
2031
|
+
z.object({
|
|
2032
|
+
theme: CanvasThemeSchema.optional(),
|
|
2033
|
+
mode: z.enum([
|
|
2034
|
+
"create",
|
|
2035
|
+
"update",
|
|
2036
|
+
"remove",
|
|
2037
|
+
"activate"
|
|
2038
|
+
]).describe("Create a page or managed root, update exact page or root state, remove an exact managed page or root, or activate an exact page."),
|
|
2039
|
+
targetNodeId: z.string().min(1).describe("Exact managed root identity for markup/native update or root removal.").optional(),
|
|
2040
|
+
markup: z.string().trim().min(1).max(MAX_CANVAS_MARKUP_LENGTH).describe(`One well-formed div/span tree using the documented Tailwind utility subset, with at most 160 elements and 12 levels.`).optional(),
|
|
2041
|
+
bindings: CanvasBindingsSchema.describe("Optional Figma component, variable, style, and typed native data keyed by a markup data-key or an existing stable key inside a markup-less update target.").optional(),
|
|
2042
|
+
variableCollections: CanvasVariableCollectionsSchema.describe("Optional local base or extended variable collections, modes, variables, and inherited-value overrides keyed by file-wide stable authoring identities. Omission preserves resources; null explicitly removes an unconsumed managed resource. Verification warns when a new variable is unreferenced or a same-call binding silently overrides a literal fallback that matches none of its direct mode values.").optional(),
|
|
2043
|
+
styles: CanvasStylesSchema.describe("Optional local Paint, Text, Effect, and Grid styles keyed by file-wide stable authoring identities. Omission preserves resources; null explicitly removes an unconsumed managed style. A newly created style without a reference in the same desired result produces a verification warning.").optional(),
|
|
2044
|
+
assets: CanvasAssetsSchema.describe("Call-scoped inline SVG or content-addressed SVG/image assets referenced by native desired state.").optional(),
|
|
2045
|
+
removeKeys: CanvasRemoveKeysSchema.describe("Optional stable keys that must be absent after a scoped update. Omitted live nodes remain untouched.").optional(),
|
|
2046
|
+
page: CanvasPagePropertiesSchema.describe("Optional exact local page identity and desired state. In create mode, an unknown pageKey with a name creates a page; omission targets the page containing the result.").optional(),
|
|
2047
|
+
selection: z.array(z.string().min(1)).max(100).optional()
|
|
2048
|
+
}).strict().superRefine(validateCanvasApplyScope);
|
|
2049
|
+
const AuthoringRuntimeEvidenceSchema = z.object({
|
|
2050
|
+
protocolVersion: z.number().int().positive(),
|
|
2051
|
+
locked: z.boolean(),
|
|
2052
|
+
valid: z.boolean(),
|
|
2053
|
+
issues: z.array(z.string()),
|
|
2054
|
+
hub: z.object({
|
|
2055
|
+
packageVersion: z.string().min(1),
|
|
2056
|
+
runtimeFingerprint: z.string().regex(/^[a-f0-9]{64}$/),
|
|
2057
|
+
startedAt: z.string().min(1)
|
|
2058
|
+
}).strict(),
|
|
2059
|
+
extension: z.object({
|
|
2060
|
+
version: z.string().min(1),
|
|
2061
|
+
runtimeFingerprint: z.string().regex(/^[a-f0-9]{64}$/),
|
|
2062
|
+
connectedAt: z.string().min(1)
|
|
2063
|
+
}).strict()
|
|
2064
|
+
}).strict();
|
|
2065
|
+
const ApplyCanvasResultSchema = z.object({
|
|
2066
|
+
rootNodeId: z.string().min(1).optional(),
|
|
2067
|
+
rootRemoved: z.literal(true).optional(),
|
|
2068
|
+
nodeIdsByKey: z.record(z.string(), z.string().min(1)),
|
|
2069
|
+
createdNodeIds: z.array(z.string().min(1)),
|
|
2070
|
+
updatedNodeIds: z.array(z.string().min(1)),
|
|
2071
|
+
removedNodeIds: z.array(z.string().min(1)),
|
|
2072
|
+
page: CanvasPageSnapshotSchema.optional(),
|
|
2073
|
+
mutationCount: z.number().int().nonnegative(),
|
|
2074
|
+
runtime: AuthoringRuntimeEvidenceSchema.optional(),
|
|
2075
|
+
verification: z.object({
|
|
2076
|
+
status: z.enum(["passed", "warning"]),
|
|
2077
|
+
nodesChecked: z.number().int().nonnegative(),
|
|
2078
|
+
referencesChecked: z.number().int().nonnegative(),
|
|
2079
|
+
nativeFieldsChecked: z.number().int().nonnegative().optional(),
|
|
2080
|
+
warnings: z.array(z.object({
|
|
2081
|
+
code: z.string().min(1),
|
|
2082
|
+
message: z.string(),
|
|
2083
|
+
key: z.string().optional()
|
|
2084
|
+
}).strict())
|
|
2085
|
+
}).strict()
|
|
2086
|
+
}).strict().superRefine((value, context) => {
|
|
2087
|
+
if (value.rootNodeId === void 0 && value.page === void 0) context.addIssue({
|
|
2088
|
+
code: "custom",
|
|
2089
|
+
message: "An apply_canvas result requires rootNodeId or page."
|
|
2090
|
+
});
|
|
2091
|
+
if (value.rootRemoved && value.rootNodeId === void 0) context.addIssue({
|
|
2092
|
+
code: "custom",
|
|
2093
|
+
message: "rootRemoved requires rootNodeId.",
|
|
2094
|
+
path: ["rootRemoved"]
|
|
2095
|
+
});
|
|
2096
|
+
});
|
|
2097
|
+
const ExactReadSessionParameterSchema = z.string().min(1).describe("Exact sessionId from list_design_sessions; omit for the active badge target.").optional();
|
|
2098
|
+
const AssetDescriptorSchema = z.object({
|
|
2099
|
+
hash: z.string().regex(MCP_HASH_PATTERN),
|
|
2100
|
+
url: z.string().url(),
|
|
2101
|
+
localPath: z.string().min(1).optional(),
|
|
2102
|
+
mimeType: z.string().min(1),
|
|
2103
|
+
size: z.number().int().nonnegative(),
|
|
2104
|
+
width: z.number().int().positive().optional(),
|
|
2105
|
+
height: z.number().int().positive().optional(),
|
|
2106
|
+
themeable: z.boolean().optional(),
|
|
2107
|
+
figmaImageHash: z.string().min(1).optional(),
|
|
2108
|
+
figmaImageHashes: z.array(z.string().min(1)).min(1).optional(),
|
|
2109
|
+
figmaVideoHashes: z.array(z.string().min(1)).min(1).optional()
|
|
2110
|
+
});
|
|
2111
|
+
const GetCodeParametersSchema = z.object({
|
|
2112
|
+
taskId: DesignTaskParameterSchema,
|
|
2113
|
+
taskEpoch: DesignTaskEpochSchema,
|
|
2114
|
+
sessionId: ExactReadSessionParameterSchema,
|
|
2115
|
+
nodeId: z.string().describe("Optional exact target node id; omit to use the current single selection.").optional(),
|
|
2116
|
+
preferredLang: z.enum(["jsx", "vue"]).describe("Preferred output language to bias the snapshot; otherwise uses the design’s hint/detected language, then falls back to JSX.").optional(),
|
|
2117
|
+
resolveTokens: z.boolean().describe("Inline token values instead of references for quick renders; default false returns token metadata plus bounded repeated-unbound-color diagnostics so you can reconcile the theming system. When true, values are resolved per-node (mode-aware) and literal diagnostics are omitted.").optional(),
|
|
2118
|
+
vectorMode: z.enum(["smart", "snapshot"]).describe("Vector output mode. `smart` (default) emits `<svg data-src=\"...\">` placeholders in code and preserves themeable instance color on the emitted SVG root markup for downstream adaptation; if asset upload fails after export, the tool may inline the SVG as a fallback to preserve source of truth. `snapshot` preserves vector assets for fidelity. Final vector delivery may still be adapted to the Host app’s SVG policy.").optional()
|
|
2119
|
+
});
|
|
2120
|
+
const GetTokenDefsParametersSchema = z.object({
|
|
2121
|
+
taskId: DesignTaskParameterSchema,
|
|
2122
|
+
taskEpoch: DesignTaskEpochSchema,
|
|
2123
|
+
sessionId: ExactReadSessionParameterSchema,
|
|
2124
|
+
names: z.array(z.string().regex(/^--[a-zA-Z0-9-_]+$/)).min(1).describe("Canonical token names (CSS variable form) from Object.keys(get_code.tokens) or your own list to resolve, e.g., --color-primary."),
|
|
2125
|
+
includeAllModes: z.boolean().describe("Include all token modes (light/dark/etc.) instead of just the active one to mirror responsive tokens; default false.").optional()
|
|
2126
|
+
});
|
|
2127
|
+
const GetScreenshotParametersSchema = z.object({
|
|
2128
|
+
taskId: DesignTaskParameterSchema,
|
|
2129
|
+
taskEpoch: DesignTaskEpochSchema,
|
|
2130
|
+
sessionId: ExactReadSessionParameterSchema,
|
|
2131
|
+
nodeId: z.string().describe("Optional exact node id to render; omit to use the current single selection.").optional()
|
|
2132
|
+
});
|
|
2133
|
+
const GetStructureParametersSchema = z.object({
|
|
2134
|
+
taskId: DesignTaskParameterSchema,
|
|
2135
|
+
taskEpoch: DesignTaskEpochSchema,
|
|
2136
|
+
sessionId: ExactReadSessionParameterSchema,
|
|
2137
|
+
nodeId: z.string().describe("Optional node id to outline; defaults to the current single selection when no page identity is supplied.").optional(),
|
|
2138
|
+
pageId: z.string().min(1).describe("Exact local page id to outline.").optional(),
|
|
2139
|
+
pageKey: CanvasStableKeySchema.describe("Exact stable key of a local page authored through apply_canvas.").optional(),
|
|
2140
|
+
options: z.object({
|
|
2141
|
+
depth: z.number().int().positive().describe("Positive integer; 1 is the shallowest traversal (root plus direct children). Omit for the full tree, subject to safety caps.").optional(),
|
|
2142
|
+
native: z.boolean().describe("Include compact native read-back for masks, IMAGE paint hashes, layout grids, and frame guides.").optional()
|
|
2143
|
+
}).strict().optional()
|
|
2144
|
+
}).strict().superRefine((value, context) => {
|
|
2145
|
+
if ([
|
|
2146
|
+
value.nodeId,
|
|
2147
|
+
value.pageId,
|
|
2148
|
+
value.pageKey
|
|
2149
|
+
].filter((identity) => identity !== void 0).length <= 1) return;
|
|
2150
|
+
context.addIssue({
|
|
2151
|
+
code: "custom",
|
|
2152
|
+
message: "Use only one of nodeId, pageId, or pageKey."
|
|
2153
|
+
});
|
|
2154
|
+
});
|
|
2155
|
+
const GetDesignSystemParametersSchema = z.object({
|
|
2156
|
+
taskId: DesignTaskParameterSchema,
|
|
2157
|
+
taskEpoch: DesignTaskEpochSchema,
|
|
2158
|
+
sessionId: ExactReadSessionParameterSchema,
|
|
2159
|
+
scope: z.enum([
|
|
2160
|
+
"resources",
|
|
2161
|
+
"fonts",
|
|
2162
|
+
"pages"
|
|
2163
|
+
]).optional(),
|
|
2164
|
+
pageId: z.string().min(1).describe("Load this exact page and limit component discovery to it; local file-wide resources remain included.").optional(),
|
|
2165
|
+
query: z.string().trim().min(1).max(100).describe("Case-insensitive font-family search.").optional(),
|
|
2166
|
+
families: z.array(z.string().min(1)).min(1).max(8).describe("Exact font families to inspect for available native style names.").optional(),
|
|
2167
|
+
catalogId: z.string().min(1).describe("Catalog returned by an earlier discovery call.").optional(),
|
|
2168
|
+
cursor: z.number().int().nonnegative().describe("Continuation cursor for a catalog, font query, or page list.").optional(),
|
|
2169
|
+
ref: z.string().min(1).describe("Exact resource ref from the same catalog.").optional()
|
|
2170
|
+
}).strict().superRefine((value, context) => {
|
|
2171
|
+
const issue = (message, path) => context.addIssue({
|
|
2172
|
+
code: "custom",
|
|
2173
|
+
message,
|
|
2174
|
+
path: [path]
|
|
2175
|
+
});
|
|
2176
|
+
if (value.scope === "pages") {
|
|
2177
|
+
if (value.catalogId || value.ref || value.pageId || value.query || value.families) issue("Page listing accepts only scope and cursor.", "pageId");
|
|
2178
|
+
return;
|
|
2179
|
+
}
|
|
2180
|
+
if (value.scope === "fonts") {
|
|
2181
|
+
if (value.catalogId || value.ref) issue("Font queries cannot use resource catalog refs.", "catalogId");
|
|
2182
|
+
if (value.pageId) issue("Font queries cannot use a component page.", "pageId");
|
|
2183
|
+
if (value.query && value.families) issue("Use query or families, not both.", "query");
|
|
2184
|
+
return;
|
|
2185
|
+
}
|
|
2186
|
+
if (value.query || value.families) issue("Font filters require scope: fonts.", "query");
|
|
2187
|
+
if (!value.catalogId) {
|
|
2188
|
+
if (value.cursor !== void 0) issue("cursor requires catalogId.", "cursor");
|
|
2189
|
+
if (value.ref !== void 0) issue("ref requires catalogId.", "ref");
|
|
2190
|
+
return;
|
|
2191
|
+
}
|
|
2192
|
+
if (value.cursor === void 0 === (value.ref === void 0)) issue("Catalog reuse requires exactly one of cursor or ref.", "catalogId");
|
|
2193
|
+
if (value.pageId) issue("A component page cannot be changed within a catalog.", "pageId");
|
|
2194
|
+
});
|
|
2195
|
+
const DesignSystemCatalogPropertySchema = z.object({
|
|
2196
|
+
type: z.enum([
|
|
2197
|
+
"boolean",
|
|
2198
|
+
"instance",
|
|
2199
|
+
"text",
|
|
2200
|
+
"variant"
|
|
2201
|
+
]),
|
|
2202
|
+
label: z.string().optional(),
|
|
2203
|
+
default: z.union([z.string(), z.boolean()]).optional(),
|
|
2204
|
+
options: z.array(z.string()).optional(),
|
|
2205
|
+
omittedOptions: z.number().int().nonnegative().optional()
|
|
2206
|
+
}).strict();
|
|
2207
|
+
const DesignSystemCatalogComponentSchema = z.object({
|
|
2208
|
+
ref: z.string().min(1),
|
|
2209
|
+
tag: z.string().min(1),
|
|
2210
|
+
name: z.string(),
|
|
2211
|
+
summary: z.string().optional(),
|
|
2212
|
+
page: z.string().optional(),
|
|
2213
|
+
variantCount: z.number().int().nonnegative().optional(),
|
|
2214
|
+
nativeSize: z.object({
|
|
2215
|
+
width: z.number().finite().nonnegative(),
|
|
2216
|
+
height: z.number().finite().nonnegative()
|
|
2217
|
+
}).strict().optional(),
|
|
2218
|
+
props: z.record(z.string(), DesignSystemCatalogPropertySchema),
|
|
2219
|
+
omittedProps: z.number().int().nonnegative().optional()
|
|
2220
|
+
}).strict();
|
|
2221
|
+
const DesignSystemCatalogVariableSchema = z.object({
|
|
2222
|
+
ref: z.string().min(1),
|
|
2223
|
+
cssName: z.string().optional(),
|
|
2224
|
+
name: z.string(),
|
|
2225
|
+
collection: z.string(),
|
|
2226
|
+
type: z.enum([
|
|
2227
|
+
"boolean",
|
|
2228
|
+
"color",
|
|
2229
|
+
"number",
|
|
2230
|
+
"string"
|
|
2231
|
+
]),
|
|
2232
|
+
scopes: z.array(z.string()).optional(),
|
|
2233
|
+
defaultValue: z.union([
|
|
2234
|
+
z.string(),
|
|
2235
|
+
z.number().finite(),
|
|
2236
|
+
z.boolean()
|
|
2237
|
+
]).optional()
|
|
2238
|
+
}).strict();
|
|
2239
|
+
const DesignSystemCatalogCollectionSchema = z.object({
|
|
2240
|
+
ref: z.string().min(1),
|
|
2241
|
+
name: z.string(),
|
|
2242
|
+
modes: z.array(z.object({
|
|
2243
|
+
ref: z.string().min(1),
|
|
2244
|
+
name: z.string()
|
|
2245
|
+
}).strict()),
|
|
2246
|
+
defaultModeRef: z.string().min(1)
|
|
2247
|
+
}).strict();
|
|
2248
|
+
const DesignSystemCatalogStyleSchema = z.object({
|
|
2249
|
+
ref: z.string().min(1),
|
|
2250
|
+
className: z.string().optional(),
|
|
2251
|
+
name: z.string(),
|
|
2252
|
+
type: z.enum([
|
|
2253
|
+
"effect",
|
|
2254
|
+
"grid",
|
|
2255
|
+
"paint",
|
|
2256
|
+
"text"
|
|
2257
|
+
]),
|
|
2258
|
+
signature: z.string(),
|
|
2259
|
+
summary: z.string().optional()
|
|
2260
|
+
}).strict();
|
|
2261
|
+
const DesignSystemCatalogShaderSchema = z.object({
|
|
2262
|
+
ref: z.string().min(1),
|
|
2263
|
+
name: z.string(),
|
|
2264
|
+
type: z.enum(["effect", "fill"]),
|
|
2265
|
+
summary: z.string().optional()
|
|
2266
|
+
}).strict();
|
|
2267
|
+
const DesignSystemResourcesResultSchema = z.object({
|
|
2268
|
+
catalogId: z.string().min(1),
|
|
2269
|
+
components: z.array(DesignSystemCatalogComponentSchema),
|
|
2270
|
+
variables: z.array(DesignSystemCatalogVariableSchema),
|
|
2271
|
+
collections: z.array(DesignSystemCatalogCollectionSchema),
|
|
2272
|
+
styles: z.array(DesignSystemCatalogStyleSchema),
|
|
2273
|
+
shaders: z.array(DesignSystemCatalogShaderSchema).optional(),
|
|
2274
|
+
details: z.object({
|
|
2275
|
+
ref: z.string().min(1),
|
|
2276
|
+
kind: z.enum([
|
|
2277
|
+
"collection",
|
|
2278
|
+
"component",
|
|
2279
|
+
"mode",
|
|
2280
|
+
"shader",
|
|
2281
|
+
"style",
|
|
2282
|
+
"variable"
|
|
2283
|
+
]),
|
|
2284
|
+
definition: z.unknown()
|
|
2285
|
+
}).strict().optional(),
|
|
2286
|
+
nextCursor: z.number().int().nonnegative().optional(),
|
|
2287
|
+
omitted: z.record(z.string(), z.number().int().nonnegative()).optional(),
|
|
2288
|
+
warnings: z.array(z.string()).optional()
|
|
2289
|
+
}).strict();
|
|
2290
|
+
const DesignSystemFontsResultSchema = z.object({
|
|
2291
|
+
scope: z.literal("fonts"),
|
|
2292
|
+
families: z.array(z.string()).optional(),
|
|
2293
|
+
fonts: z.array(z.object({
|
|
2294
|
+
family: z.string(),
|
|
2295
|
+
style: z.string()
|
|
2296
|
+
}).strict()).optional(),
|
|
2297
|
+
missingFamilies: z.array(z.string()).optional(),
|
|
2298
|
+
nextCursor: z.number().int().nonnegative().optional()
|
|
2299
|
+
}).strict().refine((value) => value.families === void 0 !== (value.fonts === void 0), "A font result requires either families or fonts.");
|
|
2300
|
+
const DesignSystemPagesResultSchema = z.object({
|
|
2301
|
+
scope: z.literal("pages"),
|
|
2302
|
+
pages: z.array(z.object({
|
|
2303
|
+
id: z.string().min(1),
|
|
2304
|
+
name: z.string(),
|
|
2305
|
+
index: z.number().int().nonnegative(),
|
|
2306
|
+
active: z.boolean(),
|
|
2307
|
+
isPageDivider: z.boolean().optional()
|
|
2308
|
+
}).strict()),
|
|
2309
|
+
nextCursor: z.number().int().nonnegative().optional()
|
|
2310
|
+
}).strict();
|
|
2311
|
+
const GetDesignSystemResultSchema = z.union([
|
|
2312
|
+
DesignSystemResourcesResultSchema,
|
|
2313
|
+
DesignSystemFontsResultSchema,
|
|
2314
|
+
DesignSystemPagesResultSchema
|
|
2315
|
+
]);
|
|
2316
|
+
const GetAssetsParametersSchema = z.object({
|
|
2317
|
+
taskId: DesignTaskParameterSchema,
|
|
2318
|
+
taskEpoch: DesignTaskEpochSchema,
|
|
2319
|
+
hashes: z.array(z.string().regex(MCP_HASH_PATTERN)).min(1).describe("Asset hashes returned from get_code (or other tools) to download/resolve exact bytes for rasterized images or SVGs before routing through your asset pipeline.")
|
|
2320
|
+
});
|
|
2321
|
+
const GetAssetsResultSchema = z.object({
|
|
2322
|
+
assets: z.array(AssetDescriptorSchema),
|
|
2323
|
+
missing: z.array(z.string().regex(MCP_HASH_PATTERN))
|
|
2324
|
+
});
|
|
2325
|
+
const MAX_IMAGE_DATA_URL_LENGTH = Math.ceil(MCP_MAX_ASSET_BYTES * 4 / 3) + 256;
|
|
2326
|
+
const UploadAssetParametersSchema = z.object({
|
|
2327
|
+
taskId: DesignTaskParameterSchema,
|
|
2328
|
+
taskEpoch: DesignTaskEpochSchema,
|
|
2329
|
+
dataUrl: z.string().min(1).max(MAX_IMAGE_DATA_URL_LENGTH).regex(/^data:image\/(?:png|jpeg|gif);base64,[A-Za-z0-9+/]+={0,2}$/).describe("A PNG, JPEG, or GIF data URL from an image-generation tool. Compose the tool calls programmatically; never print or copy the encoded bytes into prose.")
|
|
2330
|
+
}).strict();
|
|
2331
|
+
const UploadAssetResultSchema = z.object({
|
|
2332
|
+
assetHash: z.string().regex(MCP_HASH_PATTERN),
|
|
2333
|
+
mimeType: z.enum([
|
|
2334
|
+
"image/png",
|
|
2335
|
+
"image/jpeg",
|
|
2336
|
+
"image/gif"
|
|
2337
|
+
]),
|
|
2338
|
+
size: z.number().int().positive()
|
|
2339
|
+
}).strict();
|
|
2340
|
+
//#endregion
|
|
2341
|
+
//#region src/agent-clients/identity.ts
|
|
2342
|
+
const ClientEventSchema = z.object({
|
|
2343
|
+
method: z.literal("notifications/tempad/client-event"),
|
|
2344
|
+
params: z.object({
|
|
2345
|
+
event: z.enum([
|
|
2346
|
+
"connect",
|
|
2347
|
+
"taskBound",
|
|
2348
|
+
"Interrupt",
|
|
2349
|
+
"Stop",
|
|
2350
|
+
"SessionEnd",
|
|
2351
|
+
"UserPromptSubmit"
|
|
2352
|
+
]),
|
|
2353
|
+
kind: AgentClientKindSchema,
|
|
2354
|
+
sessionId: AgentClientSchema.shape.sessionId,
|
|
2355
|
+
taskId: DesignTaskIdSchema.optional(),
|
|
2356
|
+
turnId: z.string().min(1).max(256).optional()
|
|
2357
|
+
}).strict()
|
|
2358
|
+
});
|
|
2359
|
+
function runtimeIdentity(env) {
|
|
2360
|
+
return { client: clientDescriptor(env.CODEX_APP_TOOLS_PIPE_PATH ? "codex-app" : env.CODEX_THREAD_ID || env.CODEX_SESSION_ID ? "codex-cli" : env.CLAUDE_CODE ? "claude" : "other", env.CODEX_THREAD_ID || env.CODEX_SESSION_ID) };
|
|
2361
|
+
}
|
|
2362
|
+
function clientDescriptor(kind, sessionId) {
|
|
2363
|
+
return {
|
|
2364
|
+
kind,
|
|
2365
|
+
name: AGENT_CLIENTS[kind].name,
|
|
2366
|
+
...sessionId ? { sessionId } : {}
|
|
2367
|
+
};
|
|
2368
|
+
}
|
|
2369
|
+
function object(value) {
|
|
2370
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
2371
|
+
}
|
|
2372
|
+
/** Read host-supplied MCP metadata, never agent-authored tool arguments. */
|
|
2373
|
+
function bindRequestMetadata(binding, meta) {
|
|
2374
|
+
let codex = object(meta)["x-codex-turn-metadata"];
|
|
2375
|
+
if (typeof codex === "string") try {
|
|
2376
|
+
codex = JSON.parse(codex);
|
|
2377
|
+
} catch {
|
|
2378
|
+
codex = void 0;
|
|
2379
|
+
}
|
|
2380
|
+
const metadata = object(codex);
|
|
2381
|
+
const sessionId = metadata.thread_id;
|
|
2382
|
+
const turnId = metadata.turn_id;
|
|
2383
|
+
if (typeof sessionId !== "string" || !sessionId || sessionId.length > 256) return binding;
|
|
2384
|
+
const next = {
|
|
2385
|
+
...binding,
|
|
2386
|
+
client: clientDescriptor(["other", "unknown"].includes(binding.client.kind) ? "codex" : binding.client.kind, sessionId)
|
|
2387
|
+
};
|
|
2388
|
+
if (typeof turnId === "string" && turnId && turnId.length <= 256) next.turnId = turnId;
|
|
2389
|
+
else if (sessionId !== binding.client.sessionId) delete next.turnId;
|
|
2390
|
+
return next;
|
|
2391
|
+
}
|
|
2392
|
+
//#endregion
|
|
2393
|
+
//#region package.json
|
|
2394
|
+
var package_default = {
|
|
2395
|
+
name: "@tempad-dev/mcp",
|
|
2396
|
+
version: "0.9.0",
|
|
2397
|
+
description: "Connect coding agents to Figma for design inspection, native canvas editing, and UI implementation.",
|
|
2398
|
+
license: "MIT",
|
|
2399
|
+
repository: {
|
|
2400
|
+
"type": "git",
|
|
2401
|
+
"url": "git+https://github.com/ecomfe/tempad-dev.git",
|
|
2402
|
+
"directory": "packages/mcp-server"
|
|
2403
|
+
},
|
|
2404
|
+
bin: "dist/cli.mjs",
|
|
2405
|
+
files: ["README.md", "dist/**/*"],
|
|
2406
|
+
type: "module",
|
|
2407
|
+
main: "dist/cli.mjs",
|
|
2408
|
+
publishConfig: { "access": "public" },
|
|
2409
|
+
scripts: {
|
|
2410
|
+
"build": "tsdown",
|
|
2411
|
+
"dev": "tsdown --watch --no-clean",
|
|
2412
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
2413
|
+
"test": "vitest --config vitest.config.ts",
|
|
2414
|
+
"test:run": "vitest run --config vitest.config.ts",
|
|
2415
|
+
"test:coverage": "vitest run --config vitest.config.ts --coverage",
|
|
2416
|
+
"check:bridge-compatibility": "pnpm build && node scripts/check-bridge-compatibility.mjs",
|
|
2417
|
+
"lint": "eslint . --ext .ts,.mts,.cts,.js,.mjs,.cjs",
|
|
2418
|
+
"lint:fix": "eslint . --fix --ext .ts,.mts,.cts,.js,.mjs,.cjs",
|
|
2419
|
+
"format": "oxfmt -c ../../.oxfmtrc.json --ignore-path ../../.gitignore",
|
|
2420
|
+
"format:check": "oxfmt -c ../../.oxfmtrc.json --ignore-path ../../.gitignore --check",
|
|
2421
|
+
"prepublishOnly": "pnpm run build"
|
|
2422
|
+
},
|
|
2423
|
+
dependencies: {
|
|
2424
|
+
"@modelcontextprotocol/sdk": "^1.30.0",
|
|
2425
|
+
"nanoid": "^6.0.1",
|
|
2426
|
+
"pino": "^10.3.1",
|
|
2427
|
+
"pino-pretty": "^13.1.3",
|
|
2428
|
+
"proper-lockfile": "^4.1.2",
|
|
2429
|
+
"ws": "^8.21.3",
|
|
2430
|
+
"zod": "^4.6.5"
|
|
2431
|
+
},
|
|
2432
|
+
devDependencies: {
|
|
2433
|
+
"@tempad-dev/shared": "workspace:^0.1.0",
|
|
2434
|
+
"@types/node": "^24.13.4",
|
|
2435
|
+
"@types/proper-lockfile": "^4.1.4",
|
|
2436
|
+
"@types/ws": "^8.18.1",
|
|
2437
|
+
"tsdown": "^0.23.0",
|
|
2438
|
+
"typescript": "^6.0.3",
|
|
2439
|
+
"unplugin-raw": "^0.8.0",
|
|
2440
|
+
"vitest": "5.0.0"
|
|
2441
|
+
},
|
|
2442
|
+
engines: { "node": "^22 || ^24 || >=26" }
|
|
2443
|
+
};
|
|
2444
|
+
//#endregion
|
|
2445
|
+
//#region src/shared.ts
|
|
2446
|
+
function normalizePackageVersion(version) {
|
|
2447
|
+
return typeof version === "string" ? version : "0.0.0";
|
|
2448
|
+
}
|
|
2449
|
+
function ensureDir(dirPath) {
|
|
2450
|
+
mkdirSync(dirPath, {
|
|
2451
|
+
recursive: true,
|
|
2452
|
+
mode: 448
|
|
2453
|
+
});
|
|
2454
|
+
}
|
|
2455
|
+
function getRecordProperty(record, key) {
|
|
2456
|
+
if (!record || typeof record !== "object") return;
|
|
2457
|
+
return Reflect.get(record, key);
|
|
2458
|
+
}
|
|
2459
|
+
const PACKAGE_VERSION = normalizePackageVersion(getRecordProperty(package_default, "version"));
|
|
2460
|
+
function resolveRuntimeDir(env = process.env, systemTmpDir = tmpdir()) {
|
|
2461
|
+
if (env.TEMPAD_MCP_RUNTIME_DIR) return env.TEMPAD_MCP_RUNTIME_DIR;
|
|
2462
|
+
return join(systemTmpDir, "tempad-dev", "run");
|
|
2463
|
+
}
|
|
2464
|
+
function resolveLogDir(env = process.env, systemTmpDir = tmpdir()) {
|
|
2465
|
+
if (env.TEMPAD_MCP_LOG_DIR) return env.TEMPAD_MCP_LOG_DIR;
|
|
2466
|
+
return join(systemTmpDir, "tempad-dev", "log");
|
|
2467
|
+
}
|
|
2468
|
+
function resolveAssetDir(env = process.env, systemTmpDir = tmpdir()) {
|
|
2469
|
+
if (env.TEMPAD_MCP_ASSET_DIR) return env.TEMPAD_MCP_ASSET_DIR;
|
|
2470
|
+
return join(systemTmpDir, "tempad-dev", "assets");
|
|
2471
|
+
}
|
|
2472
|
+
function resolveLogLevel(debugValue = process.env.DEBUG) {
|
|
2473
|
+
return debugValue ? "debug" : "info";
|
|
2474
|
+
}
|
|
2475
|
+
function resolveSockPath(platform = process.platform, runtimeDir = RUNTIME_DIR) {
|
|
2476
|
+
return platform === "win32" ? "\\\\.\\pipe\\tempad-mcp" : join(runtimeDir, "mcp.sock");
|
|
2477
|
+
}
|
|
2478
|
+
const RUNTIME_DIR = resolveRuntimeDir();
|
|
2479
|
+
const LOG_DIR = resolveLogDir();
|
|
2480
|
+
const ASSET_DIR = resolveAssetDir();
|
|
2481
|
+
ensureDir(RUNTIME_DIR);
|
|
2482
|
+
ensureDir(LOG_DIR);
|
|
2483
|
+
ensureDir(ASSET_DIR);
|
|
2484
|
+
function ensureFile(filePath) {
|
|
2485
|
+
const fd = openSync(filePath, "a");
|
|
2486
|
+
closeSync(fd);
|
|
2487
|
+
}
|
|
2488
|
+
const LOCK_PATH = join(RUNTIME_DIR, "mcp.lock");
|
|
2489
|
+
const HUB_LOCK_PATH = join(RUNTIME_DIR, "hub.lock");
|
|
2490
|
+
const HUB_RUNTIME_IDENTITY_PATH = join(RUNTIME_DIR, "hub-runtime.json");
|
|
2491
|
+
ensureFile(LOCK_PATH);
|
|
2492
|
+
ensureFile(HUB_LOCK_PATH);
|
|
2493
|
+
const HUB_LOCK_STALE_MS = 6e4;
|
|
2494
|
+
const HUB_LOCK_UPDATE_MS = 1e4;
|
|
2495
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replaceAll(":", "-").replaceAll(".", "-");
|
|
2496
|
+
const pid = process.pid;
|
|
2497
|
+
const LOG_FILE = join(LOG_DIR, `mcp-${timestamp}-${pid}.log`);
|
|
2498
|
+
const prettyTransport = pino.transport({
|
|
2499
|
+
target: "pino-pretty",
|
|
2500
|
+
options: {
|
|
2501
|
+
translateTime: "SYS:HH:MM:ss",
|
|
2502
|
+
destination: LOG_FILE
|
|
2503
|
+
}
|
|
2504
|
+
});
|
|
2505
|
+
const log = pino({
|
|
2506
|
+
level: resolveLogLevel(),
|
|
2507
|
+
msgPrefix: "[tempad-dev/mcp] "
|
|
2508
|
+
}, prettyTransport);
|
|
2509
|
+
const SOCK_PATH = resolveSockPath();
|
|
2510
|
+
//#endregion
|
|
2511
|
+
export { SetDesignAnchorParametersSchema as $, GetDesignSystemParametersSchema as A, MCP_AUTO_ACTIVATE_GRACE_MS as B, DesignTaskIdSchema as C, GetAssetsParametersSchema as D, FigmaSessionSchema as E, LegacyMessageFromExtensionSchema as F, MCP_MAX_ASSET_STORE_BYTES as G, MCP_GET_CODE_TIMEOUT_MS as H, LegacyToolCallPayloadSchema as I, MCP_TOOL_INLINE_BUDGET_BYTES as J, MCP_MAX_PAYLOAD_BYTES as K, MCP_APPLY_CANVAS_RUNTIME_BUDGET_BYTES as L, GetScreenshotParametersSchema as M, GetStructureParametersSchema as N, GetAssetsResultSchema as O, GetTokenDefsParametersSchema as P, ResumeDesignParametersSchema as Q, MCP_APPLY_CANVAS_TIMEOUT_MS as R, DesignAnchorSchema as S, EndDesignParametersSchema as T, MCP_GET_DESIGN_SYSTEM_TIMEOUT_MS as U, MCP_DESIGN_TASK_LEASE_MS as V, MCP_MAX_ASSET_BYTES as W, MessageFromExtensionSchema as X, MCP_TOOL_TIMEOUT_MS as Y, RESUMABLE_DESIGN_TASK_STATUSES as Z, runtimeIdentity as _, HUB_RUNTIME_IDENTITY_PATH as a, buildApplyCanvasToolResult as at, ApplyCanvasResultSchema as b, RUNTIME_DIR as c, buildGetDesignSystemToolResult as ct, ensureFile as d, buildGetTokenDefsToolResult as dt, TEMPAD_MCP_BRIDGE_SUBPROTOCOL as et, getRecordProperty as f, buildUploadAssetToolResult as ft, clientDescriptor as g, bindRequestMetadata as h, utf8Bytes as ht, HUB_LOCK_UPDATE_MS as i, UploadAssetResultSchema as it, GetDesignSystemResultSchema as j, GetCodeParametersSchema as k, SOCK_PATH as l, buildGetScreenshotToolResult as lt, ClientEventSchema as m, measureCallToolResultBytes as mt, HUB_LOCK_PATH as n, TEMPAD_MCP_ERROR_CODES as nt, LOCK_PATH as o, buildGetAssetsToolResult as ot, log as p, formatDesignFeedback as pt, MCP_PORT_CANDIDATES as q, HUB_LOCK_STALE_MS as r, UploadAssetParametersSchema as rt, PACKAGE_VERSION as s, buildGetCodeToolResult as st, ASSET_DIR as t, TEMPAD_MCP_BRIDGE_SUPPORTED_PROTOCOL_VERSIONS as tt, ensureDir as u, buildGetStructureToolResult as ut, AGENT_CLIENTS as v, DesignTaskSchema as w, BeginDesignParametersSchema as x, ApplyCanvasParametersSchema as y, MCP_ASSET_TTL_MS as z };
|
|
2512
|
+
|
|
2513
|
+
//# sourceMappingURL=shared-8rz2qWXn.mjs.map
|