glyphsmith 0.1.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/LICENSE +21 -0
- package/README.ja.md +180 -0
- package/README.md +180 -0
- package/dist/index.js +4651 -0
- package/dist/index.js.map +7 -0
- package/package.json +33 -0
- package/skills/glyphsmith/SKILL.md +63 -0
- package/skills/glyphsmith-ast/SKILL.md +112 -0
- package/skills/glyphsmith-mcp/SKILL.md +294 -0
- package/skills/glyphsmith-patch/SKILL.md +239 -0
- package/web/_app/immutable/assets/0.6FezuCNY.css +2 -0
- package/web/_app/immutable/chunks/BAVS28_6.js +3 -0
- package/web/_app/immutable/chunks/BHNkEUd5.js +1 -0
- package/web/_app/immutable/chunks/kNaey6uv.js +1 -0
- package/web/_app/immutable/chunks/xihTtKlq.js +1 -0
- package/web/_app/immutable/entry/app.ueWjp9Q5.js +2 -0
- package/web/_app/immutable/entry/start.3V6PXC0_.js +1 -0
- package/web/_app/immutable/nodes/0.CgyV9l8M.js +1 -0
- package/web/_app/immutable/nodes/1.CVIOxv4y.js +1 -0
- package/web/_app/immutable/nodes/2.DAdKRbM5.js +72 -0
- package/web/_app/version.json +1 -0
- package/web/icons/App-Icon.svg +1 -0
- package/web/icons/Arc.svg +1 -0
- package/web/icons/Basis.svg +1 -0
- package/web/icons/Catmull.svg +1 -0
- package/web/icons/Cubic-Bezier.svg +1 -0
- package/web/icons/Edit.svg +1 -0
- package/web/icons/Ellipse.svg +1 -0
- package/web/icons/Line.svg +1 -0
- package/web/icons/Rect.svg +1 -0
- package/web/icons/Redo.svg +1 -0
- package/web/icons/Select.svg +1 -0
- package/web/icons/Text.svg +1 -0
- package/web/icons/Triangle.svg +1 -0
- package/web/icons/Undo.svg +1 -0
- package/web/index.html +37 -0
- package/web/robots.txt +3 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,4651 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/index.ts
|
|
4
|
+
import { spawn } from "node:child_process";
|
|
5
|
+
import { execFileSync } from "node:child_process";
|
|
6
|
+
import { existsSync as existsSync3 } from "node:fs";
|
|
7
|
+
import { cp, mkdir, readFile, readdir, rm, stat as stat2, writeFile } from "node:fs/promises";
|
|
8
|
+
import { homedir } from "node:os";
|
|
9
|
+
import { createServer as createNetServer } from "node:net";
|
|
10
|
+
import { basename as basename2, resolve as resolve2 } from "node:path";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
|
|
13
|
+
// ../../packages/ast/src/index.ts
|
|
14
|
+
function createDocument(options = {}) {
|
|
15
|
+
return {
|
|
16
|
+
id: options.id ?? "document-1",
|
|
17
|
+
name: options.name ?? "Untitled",
|
|
18
|
+
width: options.width ?? 1024,
|
|
19
|
+
height: options.height ?? 768,
|
|
20
|
+
background: options.background,
|
|
21
|
+
root: {
|
|
22
|
+
id: "root",
|
|
23
|
+
type: "group",
|
|
24
|
+
name: "Root",
|
|
25
|
+
children: []
|
|
26
|
+
},
|
|
27
|
+
comments: []
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
function createPage(options = {}) {
|
|
31
|
+
const pageId = options.pageId ?? "page-1";
|
|
32
|
+
const name = options.name ?? "Page 1";
|
|
33
|
+
return {
|
|
34
|
+
id: pageId,
|
|
35
|
+
name,
|
|
36
|
+
document: createDocument({
|
|
37
|
+
id: options.id ?? `${pageId}-document`,
|
|
38
|
+
name,
|
|
39
|
+
width: options.width,
|
|
40
|
+
height: options.height
|
|
41
|
+
})
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function createProject(options = {}) {
|
|
45
|
+
const firstPage = createPage({
|
|
46
|
+
pageId: options.pageId,
|
|
47
|
+
id: options.documentId,
|
|
48
|
+
name: "Page 1",
|
|
49
|
+
width: options.width,
|
|
50
|
+
height: options.height
|
|
51
|
+
});
|
|
52
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
53
|
+
return {
|
|
54
|
+
schemaVersion: 1,
|
|
55
|
+
id: options.id ?? "project-1",
|
|
56
|
+
name: options.name ?? "Untitled Project",
|
|
57
|
+
activePageId: firstPage.id,
|
|
58
|
+
projectPrompt: options.projectPrompt,
|
|
59
|
+
settings: {
|
|
60
|
+
defaultCanvas: {
|
|
61
|
+
width: options.width ?? 1024,
|
|
62
|
+
height: options.height ?? 768
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
pages: [firstPage],
|
|
66
|
+
createdAt: now,
|
|
67
|
+
updatedAt: now
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
function isGlyphSmithProject(value) {
|
|
71
|
+
if (!isRecord(value)) {
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
if (value.schemaVersion !== 1 || typeof value.id !== "string" || typeof value.name !== "string") {
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
if (typeof value.activePageId !== "string" || !Array.isArray(value.pages) || value.pages.length === 0) {
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
if ("projectPrompt" in value && value.projectPrompt !== void 0 && typeof value.projectPrompt !== "string") {
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
if ("settings" in value && value.settings !== void 0 && !isProjectSettings(value.settings)) {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
return value.pages.every(isGlyphSmithPage) && value.pages.some((page) => page.id === value.activePageId);
|
|
87
|
+
}
|
|
88
|
+
function isProjectSettings(value) {
|
|
89
|
+
if (!isRecord(value)) {
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
if ("defaultCanvas" in value && value.defaultCanvas !== void 0) {
|
|
93
|
+
const defaultCanvas = value.defaultCanvas;
|
|
94
|
+
return isRecord(defaultCanvas) && typeof defaultCanvas.width === "number" && Number.isFinite(defaultCanvas.width) && defaultCanvas.width >= 1 && typeof defaultCanvas.height === "number" && Number.isFinite(defaultCanvas.height) && defaultCanvas.height >= 1;
|
|
95
|
+
}
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
function isGlyphSmithPage(value) {
|
|
99
|
+
if (!isRecord(value)) {
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
return typeof value.id === "string" && typeof value.name === "string" && isGeometryDocument(value.document);
|
|
103
|
+
}
|
|
104
|
+
function isGeometryDocument(value) {
|
|
105
|
+
if (!isRecord(value) || !isRecord(value.root)) {
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
return typeof value.id === "string" && typeof value.name === "string" && typeof value.width === "number" && Number.isFinite(value.width) && value.width > 0 && typeof value.height === "number" && Number.isFinite(value.height) && value.height > 0 && value.root.type === "group" && typeof value.root.id === "string" && Array.isArray(value.root.children) && Array.isArray(value.comments);
|
|
109
|
+
}
|
|
110
|
+
function isRecord(value) {
|
|
111
|
+
return typeof value === "object" && value !== null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ../../packages/mcp/src/json-rpc.ts
|
|
115
|
+
function jsonRpcResult(id, result) {
|
|
116
|
+
return {
|
|
117
|
+
jsonrpc: "2.0",
|
|
118
|
+
id,
|
|
119
|
+
result
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
function jsonRpcError(id, code, message) {
|
|
123
|
+
return {
|
|
124
|
+
jsonrpc: "2.0",
|
|
125
|
+
id,
|
|
126
|
+
error: {
|
|
127
|
+
code,
|
|
128
|
+
message
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ../../packages/mcp/src/resources.ts
|
|
134
|
+
function mcpResources() {
|
|
135
|
+
return [
|
|
136
|
+
{
|
|
137
|
+
uri: "glyphsmith://project",
|
|
138
|
+
name: "Project",
|
|
139
|
+
title: "GlyphSmith Project",
|
|
140
|
+
mimeType: "application/json"
|
|
141
|
+
},
|
|
142
|
+
{
|
|
143
|
+
uri: "glyphsmith://pages",
|
|
144
|
+
name: "Pages",
|
|
145
|
+
title: "GlyphSmith Pages",
|
|
146
|
+
mimeType: "application/json"
|
|
147
|
+
},
|
|
148
|
+
{
|
|
149
|
+
uri: "glyphsmith://active-document",
|
|
150
|
+
name: "Active Document",
|
|
151
|
+
title: "Active Geometry Document",
|
|
152
|
+
mimeType: "application/json"
|
|
153
|
+
},
|
|
154
|
+
{
|
|
155
|
+
uri: "glyphsmith://comments",
|
|
156
|
+
name: "Comments",
|
|
157
|
+
title: "Active Document Comments",
|
|
158
|
+
mimeType: "application/json"
|
|
159
|
+
},
|
|
160
|
+
{
|
|
161
|
+
uri: "glyphsmith://selection",
|
|
162
|
+
name: "Selection",
|
|
163
|
+
title: "Editor Selection",
|
|
164
|
+
mimeType: "application/json"
|
|
165
|
+
},
|
|
166
|
+
{
|
|
167
|
+
uri: "glyphsmith://skill-guide",
|
|
168
|
+
name: "Skill Guide",
|
|
169
|
+
title: "GlyphSmith MCP Guide",
|
|
170
|
+
mimeType: "text/markdown"
|
|
171
|
+
}
|
|
172
|
+
];
|
|
173
|
+
}
|
|
174
|
+
function mcpResourceTemplates() {
|
|
175
|
+
return [
|
|
176
|
+
{
|
|
177
|
+
uriTemplate: "glyphsmith://document/{pageId}",
|
|
178
|
+
name: "Document By Page",
|
|
179
|
+
title: "Geometry Document By Page",
|
|
180
|
+
mimeType: "application/json"
|
|
181
|
+
}
|
|
182
|
+
];
|
|
183
|
+
}
|
|
184
|
+
function readMcpResource(project, selection, revision, uri) {
|
|
185
|
+
switch (uri) {
|
|
186
|
+
case "glyphsmith://project":
|
|
187
|
+
return mcpJsonResource(uri, { project, revision });
|
|
188
|
+
case "glyphsmith://pages":
|
|
189
|
+
return mcpJsonResource(uri, { pages: pagesSummary(project), activePageId: project.activePageId, revision });
|
|
190
|
+
case "glyphsmith://active-document":
|
|
191
|
+
return mcpJsonResource(uri, { document: activePage(project).document, pageId: activePage(project).id, revision });
|
|
192
|
+
case "glyphsmith://comments":
|
|
193
|
+
return mcpJsonResource(uri, { comments: activePage(project).document.comments, revision });
|
|
194
|
+
case "glyphsmith://selection":
|
|
195
|
+
return mcpJsonResource(uri, { selection, revision });
|
|
196
|
+
case "glyphsmith://skill-guide":
|
|
197
|
+
return {
|
|
198
|
+
contents: [
|
|
199
|
+
{
|
|
200
|
+
uri,
|
|
201
|
+
mimeType: "text/markdown",
|
|
202
|
+
text: [
|
|
203
|
+
"# GlyphSmith MCP",
|
|
204
|
+
"",
|
|
205
|
+
"Use GlyphSmith MCP for active `.gs.json` editor sessions.",
|
|
206
|
+
"Read Geometry AST resources and apply small patch operations.",
|
|
207
|
+
"Do not rewrite raw SVG strings for active editor changes.",
|
|
208
|
+
"",
|
|
209
|
+
"Before drawing or editing generated artwork, read `glyphsmith://project` or call `project_get` and follow `project.projectPrompt` when it is present."
|
|
210
|
+
].join("\n")
|
|
211
|
+
}
|
|
212
|
+
]
|
|
213
|
+
};
|
|
214
|
+
default:
|
|
215
|
+
if (uri.startsWith("glyphsmith://document/")) {
|
|
216
|
+
const pageId = decodeURIComponent(uri.slice("glyphsmith://document/".length));
|
|
217
|
+
const page = project.pages.find((item) => item.id === pageId);
|
|
218
|
+
if (!page) {
|
|
219
|
+
throw new Error(`Unknown pageId: ${pageId}`);
|
|
220
|
+
}
|
|
221
|
+
return mcpJsonResource(uri, { document: page.document, pageId, revision });
|
|
222
|
+
}
|
|
223
|
+
throw new Error(`Unknown MCP resource URI: ${uri}`);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
function activePage(project) {
|
|
227
|
+
return project.pages.find((page) => page.id === project.activePageId) ?? project.pages[0];
|
|
228
|
+
}
|
|
229
|
+
function pagesSummary(project) {
|
|
230
|
+
return project.pages.map((page) => ({
|
|
231
|
+
id: page.id,
|
|
232
|
+
name: page.name,
|
|
233
|
+
width: page.document.width,
|
|
234
|
+
height: page.document.height,
|
|
235
|
+
nodeCount: page.document.root.children.length,
|
|
236
|
+
commentCount: page.document.comments.length
|
|
237
|
+
}));
|
|
238
|
+
}
|
|
239
|
+
function mcpJsonResource(uri, value) {
|
|
240
|
+
return {
|
|
241
|
+
contents: [
|
|
242
|
+
{
|
|
243
|
+
uri,
|
|
244
|
+
mimeType: "application/json",
|
|
245
|
+
text: JSON.stringify(value, null, 2)
|
|
246
|
+
}
|
|
247
|
+
]
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// ../../packages/kernel/src/index.ts
|
|
252
|
+
function applyPatch(document, patch) {
|
|
253
|
+
switch (patch.op) {
|
|
254
|
+
case "updateDocument":
|
|
255
|
+
return {
|
|
256
|
+
...document,
|
|
257
|
+
...patch.changes,
|
|
258
|
+
width: patch.changes.width === void 0 ? document.width : clampDimension(patch.changes.width),
|
|
259
|
+
height: patch.changes.height === void 0 ? document.height : clampDimension(patch.changes.height)
|
|
260
|
+
};
|
|
261
|
+
case "insert":
|
|
262
|
+
return {
|
|
263
|
+
...document,
|
|
264
|
+
root: insertNode(document.root, patch.parentId, patch.node, patch.index)
|
|
265
|
+
};
|
|
266
|
+
case "update":
|
|
267
|
+
return {
|
|
268
|
+
...document,
|
|
269
|
+
root: updateNode(document.root, patch.target, (node) => ({
|
|
270
|
+
...node,
|
|
271
|
+
...patch.changes,
|
|
272
|
+
id: node.id,
|
|
273
|
+
type: node.type
|
|
274
|
+
}))
|
|
275
|
+
};
|
|
276
|
+
case "delete":
|
|
277
|
+
if (patch.target === document.root.id) {
|
|
278
|
+
return document;
|
|
279
|
+
}
|
|
280
|
+
return {
|
|
281
|
+
...document,
|
|
282
|
+
root: deleteNode(document.root, patch.target)
|
|
283
|
+
};
|
|
284
|
+
case "move":
|
|
285
|
+
return {
|
|
286
|
+
...document,
|
|
287
|
+
root: updateNode(document.root, patch.target, (node) => moveNode(node, patch))
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
function applyPatches(document, patches) {
|
|
292
|
+
return patches.reduce((current, patch) => applyPatch(current, patch), document);
|
|
293
|
+
}
|
|
294
|
+
function insertNode(current, parentId, node, index) {
|
|
295
|
+
if (current.id === parentId && current.type === "group") {
|
|
296
|
+
const children = [...current.children];
|
|
297
|
+
const insertAt = index === void 0 ? children.length : clamp(index, 0, children.length);
|
|
298
|
+
children.splice(insertAt, 0, node);
|
|
299
|
+
return {
|
|
300
|
+
...current,
|
|
301
|
+
children
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
if (current.type !== "group") {
|
|
305
|
+
return current;
|
|
306
|
+
}
|
|
307
|
+
return {
|
|
308
|
+
...current,
|
|
309
|
+
children: current.children.map((child) => insertNode(child, parentId, node, index))
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
function updateNode(current, targetId, updater) {
|
|
313
|
+
if (current.id === targetId) {
|
|
314
|
+
return updater(current);
|
|
315
|
+
}
|
|
316
|
+
if (current.type !== "group") {
|
|
317
|
+
return current;
|
|
318
|
+
}
|
|
319
|
+
return {
|
|
320
|
+
...current,
|
|
321
|
+
children: current.children.map((child) => updateNode(child, targetId, updater))
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
function deleteNode(current, targetId) {
|
|
325
|
+
if (current.type !== "group") {
|
|
326
|
+
return current;
|
|
327
|
+
}
|
|
328
|
+
return {
|
|
329
|
+
...current,
|
|
330
|
+
children: current.children.filter((child) => child.id !== targetId).map((child) => deleteNode(child, targetId))
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
function moveNode(node, patch) {
|
|
334
|
+
const delta = { x: patch.dx, y: patch.dy };
|
|
335
|
+
switch (node.type) {
|
|
336
|
+
case "group":
|
|
337
|
+
return {
|
|
338
|
+
...node,
|
|
339
|
+
children: node.children.map((child) => moveNode(child, patch))
|
|
340
|
+
};
|
|
341
|
+
case "rect":
|
|
342
|
+
return { ...node, x: node.x + delta.x, y: node.y + delta.y };
|
|
343
|
+
case "circle":
|
|
344
|
+
case "ellipse":
|
|
345
|
+
return { ...node, cx: node.cx + delta.x, cy: node.cy + delta.y };
|
|
346
|
+
case "line":
|
|
347
|
+
return {
|
|
348
|
+
...node,
|
|
349
|
+
x1: node.x1 + delta.x,
|
|
350
|
+
y1: node.y1 + delta.y,
|
|
351
|
+
x2: node.x2 + delta.x,
|
|
352
|
+
y2: node.y2 + delta.y
|
|
353
|
+
};
|
|
354
|
+
case "polygon":
|
|
355
|
+
case "polyline":
|
|
356
|
+
return {
|
|
357
|
+
...node,
|
|
358
|
+
points: node.points.map((point) => translatePoint(point, delta))
|
|
359
|
+
};
|
|
360
|
+
case "path":
|
|
361
|
+
return {
|
|
362
|
+
...node,
|
|
363
|
+
start: translatePoint(node.start, delta),
|
|
364
|
+
spline: node.spline ? {
|
|
365
|
+
...node.spline,
|
|
366
|
+
points: node.spline.points.map((point) => translatePoint(point, delta))
|
|
367
|
+
} : void 0,
|
|
368
|
+
segments: node.segments.map((segment) => {
|
|
369
|
+
switch (segment.type) {
|
|
370
|
+
case "line":
|
|
371
|
+
return { ...segment, to: translatePoint(segment.to, delta) };
|
|
372
|
+
case "quadratic":
|
|
373
|
+
return {
|
|
374
|
+
...segment,
|
|
375
|
+
control: translatePoint(segment.control, delta),
|
|
376
|
+
to: translatePoint(segment.to, delta)
|
|
377
|
+
};
|
|
378
|
+
case "cubic":
|
|
379
|
+
return {
|
|
380
|
+
...segment,
|
|
381
|
+
control1: translatePoint(segment.control1, delta),
|
|
382
|
+
control2: translatePoint(segment.control2, delta),
|
|
383
|
+
to: translatePoint(segment.to, delta)
|
|
384
|
+
};
|
|
385
|
+
case "arc":
|
|
386
|
+
return { ...segment, to: translatePoint(segment.to, delta) };
|
|
387
|
+
}
|
|
388
|
+
})
|
|
389
|
+
};
|
|
390
|
+
case "text":
|
|
391
|
+
return { ...node, x: node.x + delta.x, y: node.y + delta.y };
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
function translatePoint(point, delta) {
|
|
395
|
+
return {
|
|
396
|
+
x: point.x + delta.x,
|
|
397
|
+
y: point.y + delta.y
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
function clamp(value, min, max) {
|
|
401
|
+
return Math.min(Math.max(value, min), max);
|
|
402
|
+
}
|
|
403
|
+
function clampDimension(value) {
|
|
404
|
+
return Math.max(1, Math.round(value));
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// ../../packages/svg/src/index.ts
|
|
408
|
+
function exportToSvg(document) {
|
|
409
|
+
const children = document.root.children.map(renderNode).join("");
|
|
410
|
+
return [
|
|
411
|
+
`<svg xmlns="http://www.w3.org/2000/svg" width="${formatNumber(document.width)}" height="${formatNumber(document.height)}" viewBox="0 0 ${formatNumber(document.width)} ${formatNumber(document.height)}">`,
|
|
412
|
+
children,
|
|
413
|
+
"</svg>"
|
|
414
|
+
].join("");
|
|
415
|
+
}
|
|
416
|
+
function renderNode(node) {
|
|
417
|
+
if (node.visible === false) {
|
|
418
|
+
return "";
|
|
419
|
+
}
|
|
420
|
+
const common = `${renderId(node.id)}${renderName(node.name)}${renderStyle(node.style)}`;
|
|
421
|
+
switch (node.type) {
|
|
422
|
+
case "group":
|
|
423
|
+
return `<g${common}>${node.children.map(renderNode).join("")}</g>`;
|
|
424
|
+
case "rect":
|
|
425
|
+
return `<rect${common} x="${formatNumber(node.x)}" y="${formatNumber(node.y)}" width="${formatNumber(node.width)}" height="${formatNumber(node.height)}"${optionalNumber("rx", node.rx)}${optionalNumber("ry", node.ry)} />`;
|
|
426
|
+
case "circle":
|
|
427
|
+
return `<circle${common} cx="${formatNumber(node.cx)}" cy="${formatNumber(node.cy)}" r="${formatNumber(node.r)}" />`;
|
|
428
|
+
case "ellipse":
|
|
429
|
+
return `<ellipse${common} cx="${formatNumber(node.cx)}" cy="${formatNumber(node.cy)}" rx="${formatNumber(node.rx)}" ry="${formatNumber(node.ry)}" />`;
|
|
430
|
+
case "line":
|
|
431
|
+
return `<line${common} x1="${formatNumber(node.x1)}" y1="${formatNumber(node.y1)}" x2="${formatNumber(node.x2)}" y2="${formatNumber(node.y2)}" />`;
|
|
432
|
+
case "polygon":
|
|
433
|
+
return `<polygon${common} points="${renderPoints(node.points)}" />`;
|
|
434
|
+
case "polyline":
|
|
435
|
+
return `<polyline${common} points="${renderPoints(node.points)}" />`;
|
|
436
|
+
case "path":
|
|
437
|
+
return `<path${common} d="${renderPathData(node.start, node.segments, node.closed)}" />`;
|
|
438
|
+
case "text":
|
|
439
|
+
return renderTextNode(node);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
function renderTextNode(node) {
|
|
443
|
+
const lines = textLines(node.text);
|
|
444
|
+
const common = `${renderId(node.id)}${renderName(node.name)}${renderTextStyle(node)} x="${formatNumber(node.x)}" y="${formatNumber(node.y)}"`;
|
|
445
|
+
if (lines.length === 1) {
|
|
446
|
+
return `<text${common}>${escapeText(node.text)}</text>`;
|
|
447
|
+
}
|
|
448
|
+
const tspans = lines.map((line, index) => {
|
|
449
|
+
const dy = index === 0 ? "" : ` dy="1.2em"`;
|
|
450
|
+
return `<tspan x="${formatNumber(node.x)}"${dy}>${escapeText(line)}</tspan>`;
|
|
451
|
+
});
|
|
452
|
+
return `<text${common}>${tspans.join("")}</text>`;
|
|
453
|
+
}
|
|
454
|
+
function renderTextStyle(node) {
|
|
455
|
+
const fill = node.style?.fill ?? node.fill ?? "#111827";
|
|
456
|
+
const stroke = node.style?.stroke ?? node.stroke;
|
|
457
|
+
const strokeWidth = node.style?.strokeWidth ?? node.strokeWidth;
|
|
458
|
+
const opacity = node.style?.opacity ?? node.opacity;
|
|
459
|
+
return [
|
|
460
|
+
` fill="${escapeAttribute(fill)}"`,
|
|
461
|
+
stroke === void 0 ? "" : ` stroke="${escapeAttribute(stroke)}"`,
|
|
462
|
+
strokeWidth === void 0 ? "" : ` stroke-width="${formatNumber(strokeWidth)}"`,
|
|
463
|
+
node.fontFamily === void 0 ? "" : ` font-family="${escapeAttribute(node.fontFamily)}"`,
|
|
464
|
+
node.fontSize === void 0 ? "" : ` font-size="${formatNumber(node.fontSize)}"`,
|
|
465
|
+
node.fontWeight === void 0 ? "" : ` font-weight="${escapeAttribute(String(node.fontWeight))}"`,
|
|
466
|
+
node.fontStyle === void 0 ? "" : ` font-style="${escapeAttribute(node.fontStyle)}"`,
|
|
467
|
+
node.textAnchor === void 0 ? "" : ` text-anchor="${escapeAttribute(node.textAnchor)}"`,
|
|
468
|
+
node.dominantBaseline === void 0 ? "" : ` dominant-baseline="${escapeAttribute(node.dominantBaseline)}"`,
|
|
469
|
+
opacity === void 0 ? "" : ` opacity="${formatNumber(opacity)}"`
|
|
470
|
+
].join("");
|
|
471
|
+
}
|
|
472
|
+
function renderPathData(start, segments, closed) {
|
|
473
|
+
const commands = [`M ${formatNumber(start.x)} ${formatNumber(start.y)}`];
|
|
474
|
+
for (const segment of segments) {
|
|
475
|
+
switch (segment.type) {
|
|
476
|
+
case "line":
|
|
477
|
+
commands.push(`L ${formatNumber(segment.to.x)} ${formatNumber(segment.to.y)}`);
|
|
478
|
+
break;
|
|
479
|
+
case "quadratic":
|
|
480
|
+
commands.push(
|
|
481
|
+
`Q ${formatNumber(segment.control.x)} ${formatNumber(segment.control.y)} ${formatNumber(segment.to.x)} ${formatNumber(segment.to.y)}`
|
|
482
|
+
);
|
|
483
|
+
break;
|
|
484
|
+
case "cubic":
|
|
485
|
+
commands.push(
|
|
486
|
+
`C ${formatNumber(segment.control1.x)} ${formatNumber(segment.control1.y)} ${formatNumber(segment.control2.x)} ${formatNumber(segment.control2.y)} ${formatNumber(segment.to.x)} ${formatNumber(segment.to.y)}`
|
|
487
|
+
);
|
|
488
|
+
break;
|
|
489
|
+
case "arc":
|
|
490
|
+
commands.push(
|
|
491
|
+
`A ${formatNumber(segment.rx)} ${formatNumber(segment.ry)} ${formatNumber(segment.xAxisRotation)} ${segment.largeArc ? 1 : 0} ${segment.sweep ? 1 : 0} ${formatNumber(segment.to.x)} ${formatNumber(segment.to.y)}`
|
|
492
|
+
);
|
|
493
|
+
break;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
if (closed) {
|
|
497
|
+
commands.push("Z");
|
|
498
|
+
}
|
|
499
|
+
return commands.join(" ");
|
|
500
|
+
}
|
|
501
|
+
function renderStyle(style) {
|
|
502
|
+
const fill = style?.fill ?? "none";
|
|
503
|
+
const stroke = style?.stroke ?? "#111827";
|
|
504
|
+
const strokeWidth = style?.strokeWidth ?? 2;
|
|
505
|
+
const strokeLinecap = style?.strokeLinecap;
|
|
506
|
+
const strokeLinejoin = style?.strokeLinejoin;
|
|
507
|
+
const strokeMiterlimit = style?.strokeMiterlimit;
|
|
508
|
+
const strokeDasharray = style?.strokeDasharray;
|
|
509
|
+
const strokeDashoffset = style?.strokeDashoffset;
|
|
510
|
+
const opacity = style?.opacity;
|
|
511
|
+
return [
|
|
512
|
+
` fill="${escapeAttribute(fill)}"`,
|
|
513
|
+
` stroke="${escapeAttribute(stroke)}"`,
|
|
514
|
+
` stroke-width="${formatNumber(strokeWidth)}"`,
|
|
515
|
+
strokeLinecap === void 0 ? "" : ` stroke-linecap="${escapeAttribute(strokeLinecap)}"`,
|
|
516
|
+
strokeLinejoin === void 0 ? "" : ` stroke-linejoin="${escapeAttribute(strokeLinejoin)}"`,
|
|
517
|
+
strokeMiterlimit === void 0 ? "" : ` stroke-miterlimit="${formatNumber(strokeMiterlimit)}"`,
|
|
518
|
+
strokeDasharray === void 0 ? "" : ` stroke-dasharray="${escapeAttribute(strokeDasharray)}"`,
|
|
519
|
+
strokeDashoffset === void 0 ? "" : ` stroke-dashoffset="${formatNumber(strokeDashoffset)}"`,
|
|
520
|
+
opacity === void 0 ? "" : ` opacity="${formatNumber(opacity)}"`
|
|
521
|
+
].join("");
|
|
522
|
+
}
|
|
523
|
+
function renderPoints(points) {
|
|
524
|
+
return points.map((point) => `${formatNumber(point.x)},${formatNumber(point.y)}`).join(" ");
|
|
525
|
+
}
|
|
526
|
+
function renderId(id) {
|
|
527
|
+
return ` id="${escapeAttribute(id)}"`;
|
|
528
|
+
}
|
|
529
|
+
function renderName(name) {
|
|
530
|
+
return name ? ` data-name="${escapeAttribute(name)}"` : "";
|
|
531
|
+
}
|
|
532
|
+
function optionalNumber(name, value) {
|
|
533
|
+
return value === void 0 ? "" : ` ${name}="${formatNumber(value)}"`;
|
|
534
|
+
}
|
|
535
|
+
function formatNumber(value) {
|
|
536
|
+
return Number.isInteger(value) ? String(value) : value.toFixed(3).replace(/\.?0+$/, "");
|
|
537
|
+
}
|
|
538
|
+
function escapeAttribute(value) {
|
|
539
|
+
return value.replaceAll("&", "&").replaceAll('"', """).replaceAll("<", "<").replaceAll(">", ">");
|
|
540
|
+
}
|
|
541
|
+
function escapeText(value) {
|
|
542
|
+
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
543
|
+
}
|
|
544
|
+
function textLines(value) {
|
|
545
|
+
return value.replace(/\r\n?/g, "\n").split("\n");
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// ../../packages/mcp/src/tools.ts
|
|
549
|
+
function mcpTools() {
|
|
550
|
+
return [
|
|
551
|
+
{
|
|
552
|
+
name: "project_get",
|
|
553
|
+
description: "Read the active GlyphSmith project, including projectPrompt when present.",
|
|
554
|
+
inputSchema: { type: "object", properties: {} }
|
|
555
|
+
},
|
|
556
|
+
{
|
|
557
|
+
name: "pages_list",
|
|
558
|
+
description: "List pages in the active GlyphSmith project.",
|
|
559
|
+
inputSchema: { type: "object", properties: {} }
|
|
560
|
+
},
|
|
561
|
+
{
|
|
562
|
+
name: "document_get",
|
|
563
|
+
description: "Read a GeometryDocument by pageId, or the active document when pageId is omitted.",
|
|
564
|
+
inputSchema: {
|
|
565
|
+
type: "object",
|
|
566
|
+
properties: {
|
|
567
|
+
pageId: { type: "string" }
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
},
|
|
571
|
+
{
|
|
572
|
+
name: "selection_get",
|
|
573
|
+
description: "Read the current editor selection.",
|
|
574
|
+
inputSchema: { type: "object", properties: {} }
|
|
575
|
+
},
|
|
576
|
+
{
|
|
577
|
+
name: "comments_get",
|
|
578
|
+
description: "Read comments from a page, or the active page when pageId is omitted.",
|
|
579
|
+
inputSchema: {
|
|
580
|
+
type: "object",
|
|
581
|
+
properties: {
|
|
582
|
+
pageId: { type: "string" }
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
},
|
|
586
|
+
{
|
|
587
|
+
name: "patch_apply",
|
|
588
|
+
description: "Apply one Geometry AST patch to a page document.",
|
|
589
|
+
inputSchema: {
|
|
590
|
+
type: "object",
|
|
591
|
+
properties: {
|
|
592
|
+
pageId: { type: "string" },
|
|
593
|
+
patch: { type: "object" },
|
|
594
|
+
revision: { type: "string" },
|
|
595
|
+
dryRun: { type: "boolean" }
|
|
596
|
+
},
|
|
597
|
+
required: ["patch"]
|
|
598
|
+
}
|
|
599
|
+
},
|
|
600
|
+
{
|
|
601
|
+
name: "patches_apply",
|
|
602
|
+
description: "Apply multiple Geometry AST patches to a page document in one revision update.",
|
|
603
|
+
inputSchema: {
|
|
604
|
+
type: "object",
|
|
605
|
+
properties: {
|
|
606
|
+
pageId: { type: "string" },
|
|
607
|
+
patches: { type: "array", items: { type: "object" } },
|
|
608
|
+
revision: { type: "string" },
|
|
609
|
+
dryRun: { type: "boolean" }
|
|
610
|
+
},
|
|
611
|
+
required: ["patches"]
|
|
612
|
+
}
|
|
613
|
+
},
|
|
614
|
+
{
|
|
615
|
+
name: "node_insert",
|
|
616
|
+
description: "Insert a Geometry AST node into a document. Defaults parentId to root.",
|
|
617
|
+
inputSchema: {
|
|
618
|
+
type: "object",
|
|
619
|
+
properties: {
|
|
620
|
+
pageId: { type: "string" },
|
|
621
|
+
parentId: { type: "string" },
|
|
622
|
+
node: { type: "object" },
|
|
623
|
+
index: { type: "number" },
|
|
624
|
+
revision: { type: "string" },
|
|
625
|
+
dryRun: { type: "boolean" }
|
|
626
|
+
},
|
|
627
|
+
required: ["node"]
|
|
628
|
+
}
|
|
629
|
+
},
|
|
630
|
+
{
|
|
631
|
+
name: "node_update",
|
|
632
|
+
description: "Update one Geometry AST node by id.",
|
|
633
|
+
inputSchema: {
|
|
634
|
+
type: "object",
|
|
635
|
+
properties: {
|
|
636
|
+
pageId: { type: "string" },
|
|
637
|
+
target: { type: "string" },
|
|
638
|
+
changes: { type: "object" },
|
|
639
|
+
revision: { type: "string" },
|
|
640
|
+
dryRun: { type: "boolean" }
|
|
641
|
+
},
|
|
642
|
+
required: ["target", "changes"]
|
|
643
|
+
}
|
|
644
|
+
},
|
|
645
|
+
{
|
|
646
|
+
name: "node_delete",
|
|
647
|
+
description: "Delete one Geometry AST node by id.",
|
|
648
|
+
inputSchema: {
|
|
649
|
+
type: "object",
|
|
650
|
+
properties: {
|
|
651
|
+
pageId: { type: "string" },
|
|
652
|
+
target: { type: "string" },
|
|
653
|
+
revision: { type: "string" },
|
|
654
|
+
dryRun: { type: "boolean" }
|
|
655
|
+
},
|
|
656
|
+
required: ["target"]
|
|
657
|
+
}
|
|
658
|
+
},
|
|
659
|
+
{
|
|
660
|
+
name: "node_move",
|
|
661
|
+
description: "Move one Geometry AST node by delta.",
|
|
662
|
+
inputSchema: {
|
|
663
|
+
type: "object",
|
|
664
|
+
properties: {
|
|
665
|
+
pageId: { type: "string" },
|
|
666
|
+
target: { type: "string" },
|
|
667
|
+
dx: { type: "number" },
|
|
668
|
+
dy: { type: "number" },
|
|
669
|
+
revision: { type: "string" },
|
|
670
|
+
dryRun: { type: "boolean" }
|
|
671
|
+
},
|
|
672
|
+
required: ["target", "dx", "dy"]
|
|
673
|
+
}
|
|
674
|
+
},
|
|
675
|
+
{
|
|
676
|
+
name: "document_update",
|
|
677
|
+
description: "Update active document metadata such as name, width, or height.",
|
|
678
|
+
inputSchema: {
|
|
679
|
+
type: "object",
|
|
680
|
+
properties: {
|
|
681
|
+
pageId: { type: "string" },
|
|
682
|
+
changes: { type: "object" },
|
|
683
|
+
revision: { type: "string" },
|
|
684
|
+
dryRun: { type: "boolean" }
|
|
685
|
+
},
|
|
686
|
+
required: ["changes"]
|
|
687
|
+
}
|
|
688
|
+
},
|
|
689
|
+
{
|
|
690
|
+
name: "path_create",
|
|
691
|
+
description: "Create a PathNode with normalized Geometry AST segments.",
|
|
692
|
+
inputSchema: {
|
|
693
|
+
type: "object",
|
|
694
|
+
properties: {
|
|
695
|
+
pageId: { type: "string" },
|
|
696
|
+
parentId: { type: "string" },
|
|
697
|
+
id: { type: "string" },
|
|
698
|
+
start: { type: "object" },
|
|
699
|
+
segments: { type: "array", items: { type: "object" } },
|
|
700
|
+
closed: { type: "boolean" },
|
|
701
|
+
style: { type: "object" },
|
|
702
|
+
revision: { type: "string" },
|
|
703
|
+
dryRun: { type: "boolean" }
|
|
704
|
+
},
|
|
705
|
+
required: ["id", "start"]
|
|
706
|
+
}
|
|
707
|
+
},
|
|
708
|
+
{
|
|
709
|
+
name: "path_segment_append",
|
|
710
|
+
description: "Append one normalized segment to a PathNode.",
|
|
711
|
+
inputSchema: {
|
|
712
|
+
type: "object",
|
|
713
|
+
properties: {
|
|
714
|
+
pageId: { type: "string" },
|
|
715
|
+
target: { type: "string" },
|
|
716
|
+
segment: { type: "object" },
|
|
717
|
+
revision: { type: "string" },
|
|
718
|
+
dryRun: { type: "boolean" }
|
|
719
|
+
},
|
|
720
|
+
required: ["target", "segment"]
|
|
721
|
+
}
|
|
722
|
+
},
|
|
723
|
+
{
|
|
724
|
+
name: "path_segment_update",
|
|
725
|
+
description: "Replace one segment in a PathNode by zero-based index.",
|
|
726
|
+
inputSchema: {
|
|
727
|
+
type: "object",
|
|
728
|
+
properties: {
|
|
729
|
+
pageId: { type: "string" },
|
|
730
|
+
target: { type: "string" },
|
|
731
|
+
index: { type: "number" },
|
|
732
|
+
segment: { type: "object" },
|
|
733
|
+
revision: { type: "string" },
|
|
734
|
+
dryRun: { type: "boolean" }
|
|
735
|
+
},
|
|
736
|
+
required: ["target", "index", "segment"]
|
|
737
|
+
}
|
|
738
|
+
},
|
|
739
|
+
{
|
|
740
|
+
name: "path_segment_delete",
|
|
741
|
+
description: "Delete one segment from a PathNode by zero-based index.",
|
|
742
|
+
inputSchema: {
|
|
743
|
+
type: "object",
|
|
744
|
+
properties: {
|
|
745
|
+
pageId: { type: "string" },
|
|
746
|
+
target: { type: "string" },
|
|
747
|
+
index: { type: "number" },
|
|
748
|
+
revision: { type: "string" },
|
|
749
|
+
dryRun: { type: "boolean" }
|
|
750
|
+
},
|
|
751
|
+
required: ["target", "index"]
|
|
752
|
+
}
|
|
753
|
+
},
|
|
754
|
+
{
|
|
755
|
+
name: "path_set_closed",
|
|
756
|
+
description: "Set whether a PathNode is closed.",
|
|
757
|
+
inputSchema: {
|
|
758
|
+
type: "object",
|
|
759
|
+
properties: {
|
|
760
|
+
pageId: { type: "string" },
|
|
761
|
+
target: { type: "string" },
|
|
762
|
+
closed: { type: "boolean" },
|
|
763
|
+
revision: { type: "string" },
|
|
764
|
+
dryRun: { type: "boolean" }
|
|
765
|
+
},
|
|
766
|
+
required: ["target", "closed"]
|
|
767
|
+
}
|
|
768
|
+
},
|
|
769
|
+
{
|
|
770
|
+
name: "page_add",
|
|
771
|
+
description: "Add a new page to the project.",
|
|
772
|
+
inputSchema: {
|
|
773
|
+
type: "object",
|
|
774
|
+
properties: {
|
|
775
|
+
name: { type: "string" },
|
|
776
|
+
width: { type: "number" },
|
|
777
|
+
height: { type: "number" },
|
|
778
|
+
revision: { type: "string" },
|
|
779
|
+
dryRun: { type: "boolean" }
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
},
|
|
783
|
+
{
|
|
784
|
+
name: "page_duplicate",
|
|
785
|
+
description: "Duplicate a page.",
|
|
786
|
+
inputSchema: {
|
|
787
|
+
type: "object",
|
|
788
|
+
properties: {
|
|
789
|
+
pageId: { type: "string" },
|
|
790
|
+
revision: { type: "string" },
|
|
791
|
+
dryRun: { type: "boolean" }
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
},
|
|
795
|
+
{
|
|
796
|
+
name: "page_delete",
|
|
797
|
+
description: "Delete a page. At least one page must remain.",
|
|
798
|
+
inputSchema: {
|
|
799
|
+
type: "object",
|
|
800
|
+
properties: {
|
|
801
|
+
pageId: { type: "string" },
|
|
802
|
+
revision: { type: "string" },
|
|
803
|
+
dryRun: { type: "boolean" }
|
|
804
|
+
},
|
|
805
|
+
required: ["pageId"]
|
|
806
|
+
}
|
|
807
|
+
},
|
|
808
|
+
{
|
|
809
|
+
name: "page_set_active",
|
|
810
|
+
description: "Set the active page.",
|
|
811
|
+
inputSchema: {
|
|
812
|
+
type: "object",
|
|
813
|
+
properties: {
|
|
814
|
+
pageId: { type: "string" },
|
|
815
|
+
revision: { type: "string" },
|
|
816
|
+
dryRun: { type: "boolean" }
|
|
817
|
+
},
|
|
818
|
+
required: ["pageId"]
|
|
819
|
+
}
|
|
820
|
+
},
|
|
821
|
+
{
|
|
822
|
+
name: "svg_export",
|
|
823
|
+
description: "Export a page document to SVG.",
|
|
824
|
+
inputSchema: {
|
|
825
|
+
type: "object",
|
|
826
|
+
properties: {
|
|
827
|
+
pageId: { type: "string" }
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
},
|
|
831
|
+
{
|
|
832
|
+
name: "project_save",
|
|
833
|
+
description: "Persist the current project snapshot to disk.",
|
|
834
|
+
inputSchema: {
|
|
835
|
+
type: "object",
|
|
836
|
+
properties: {
|
|
837
|
+
revision: { type: "string" }
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
];
|
|
842
|
+
}
|
|
843
|
+
function callMcpTool(context, name, args) {
|
|
844
|
+
switch (name) {
|
|
845
|
+
case "project_get":
|
|
846
|
+
return mcpText({ ok: true, project: context.store.readProject(), revision: context.store.revision() });
|
|
847
|
+
case "pages_list":
|
|
848
|
+
return mcpText({
|
|
849
|
+
ok: true,
|
|
850
|
+
activePageId: context.store.readProject().activePageId,
|
|
851
|
+
pages: context.store.readProject().pages.map(pageSummary),
|
|
852
|
+
revision: context.store.revision()
|
|
853
|
+
});
|
|
854
|
+
case "document_get": {
|
|
855
|
+
const project = context.store.readProject();
|
|
856
|
+
const page = pageByOptionalId(project, optionalString(args.pageId));
|
|
857
|
+
return mcpText({ ok: true, pageId: page.id, document: page.document, revision: context.store.revision() });
|
|
858
|
+
}
|
|
859
|
+
case "selection_get":
|
|
860
|
+
return mcpText({ ok: true, selection: context.store.selection(), revision: context.store.revision() });
|
|
861
|
+
case "comments_get": {
|
|
862
|
+
const project = context.store.readProject();
|
|
863
|
+
const page = pageByOptionalId(project, optionalString(args.pageId));
|
|
864
|
+
return mcpText({ ok: true, pageId: page.id, comments: page.document.comments, revision: context.store.revision() });
|
|
865
|
+
}
|
|
866
|
+
case "patch_apply":
|
|
867
|
+
return mcpText(applyPatchTool(context, args));
|
|
868
|
+
case "patches_apply":
|
|
869
|
+
return mcpText(applyPatchesTool(context, args));
|
|
870
|
+
case "node_insert":
|
|
871
|
+
return mcpText(nodeInsertTool(context, args));
|
|
872
|
+
case "node_update":
|
|
873
|
+
return mcpText(nodeUpdateTool(context, args));
|
|
874
|
+
case "node_delete":
|
|
875
|
+
return mcpText(nodeDeleteTool(context, args));
|
|
876
|
+
case "node_move":
|
|
877
|
+
return mcpText(nodeMoveTool(context, args));
|
|
878
|
+
case "document_update":
|
|
879
|
+
return mcpText(documentUpdateTool(context, args));
|
|
880
|
+
case "path_create":
|
|
881
|
+
return mcpText(pathCreateTool(context, args));
|
|
882
|
+
case "path_segment_append":
|
|
883
|
+
return mcpText(pathSegmentAppendTool(context, args));
|
|
884
|
+
case "path_segment_update":
|
|
885
|
+
return mcpText(pathSegmentUpdateTool(context, args));
|
|
886
|
+
case "path_segment_delete":
|
|
887
|
+
return mcpText(pathSegmentDeleteTool(context, args));
|
|
888
|
+
case "path_set_closed":
|
|
889
|
+
return mcpText(pathSetClosedTool(context, args));
|
|
890
|
+
case "page_add":
|
|
891
|
+
return mcpText(pageAddTool(context, args));
|
|
892
|
+
case "page_duplicate":
|
|
893
|
+
return mcpText(pageDuplicateTool(context, args));
|
|
894
|
+
case "page_delete":
|
|
895
|
+
return mcpText(pageDeleteTool(context, args));
|
|
896
|
+
case "page_set_active":
|
|
897
|
+
return mcpText(pageSetActiveTool(context, args));
|
|
898
|
+
case "svg_export": {
|
|
899
|
+
const project = context.store.readProject();
|
|
900
|
+
const page = pageByOptionalId(project, optionalString(args.pageId));
|
|
901
|
+
return mcpText({ ok: true, pageId: page.id, svg: exportToSvg(page.document), revision: context.store.revision() });
|
|
902
|
+
}
|
|
903
|
+
case "project_save": {
|
|
904
|
+
assertRevision(context, optionalString(args.revision));
|
|
905
|
+
const change = context.store.writeProject(context.store.readProject());
|
|
906
|
+
return mcpText({ ok: true, revision: change.revision });
|
|
907
|
+
}
|
|
908
|
+
default:
|
|
909
|
+
throw new Error(`Unknown MCP tool: ${name}`);
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
function applyPatchTool(context, args) {
|
|
913
|
+
assertRevision(context, optionalString(args.revision));
|
|
914
|
+
const patch = args.patch;
|
|
915
|
+
if (!isPatchOperation(patch)) {
|
|
916
|
+
throw new Error("patch_apply requires a valid patch.");
|
|
917
|
+
}
|
|
918
|
+
return applyPatchOperations(context, args, [patch]);
|
|
919
|
+
}
|
|
920
|
+
function applyPatchesTool(context, args) {
|
|
921
|
+
const patches = args.patches;
|
|
922
|
+
if (!Array.isArray(patches) || !patches.every(isPatchOperation)) {
|
|
923
|
+
throw new Error("patches_apply requires an array of valid patches.");
|
|
924
|
+
}
|
|
925
|
+
return applyPatchOperations(context, args, patches);
|
|
926
|
+
}
|
|
927
|
+
function nodeInsertTool(context, args) {
|
|
928
|
+
const node = args.node;
|
|
929
|
+
if (!isGeometryNode(node)) {
|
|
930
|
+
throw new Error("node_insert requires a valid Geometry AST node.");
|
|
931
|
+
}
|
|
932
|
+
return applyPatchOperations(context, args, [
|
|
933
|
+
{
|
|
934
|
+
op: "insert",
|
|
935
|
+
parentId: optionalString(args.parentId) ?? "root",
|
|
936
|
+
node,
|
|
937
|
+
index: optionalNumber2(args.index)
|
|
938
|
+
}
|
|
939
|
+
]);
|
|
940
|
+
}
|
|
941
|
+
function nodeUpdateTool(context, args) {
|
|
942
|
+
return applyPatchOperations(context, args, [
|
|
943
|
+
{
|
|
944
|
+
op: "update",
|
|
945
|
+
target: requiredString(args.target, "target"),
|
|
946
|
+
changes: requiredRecord(args.changes, "changes")
|
|
947
|
+
}
|
|
948
|
+
]);
|
|
949
|
+
}
|
|
950
|
+
function nodeDeleteTool(context, args) {
|
|
951
|
+
return applyPatchOperations(context, args, [
|
|
952
|
+
{
|
|
953
|
+
op: "delete",
|
|
954
|
+
target: requiredString(args.target, "target")
|
|
955
|
+
}
|
|
956
|
+
]);
|
|
957
|
+
}
|
|
958
|
+
function nodeMoveTool(context, args) {
|
|
959
|
+
return applyPatchOperations(context, args, [
|
|
960
|
+
{
|
|
961
|
+
op: "move",
|
|
962
|
+
target: requiredString(args.target, "target"),
|
|
963
|
+
dx: requiredNumber(args.dx, "dx"),
|
|
964
|
+
dy: requiredNumber(args.dy, "dy")
|
|
965
|
+
}
|
|
966
|
+
]);
|
|
967
|
+
}
|
|
968
|
+
function documentUpdateTool(context, args) {
|
|
969
|
+
return applyPatchOperations(context, args, [
|
|
970
|
+
{
|
|
971
|
+
op: "updateDocument",
|
|
972
|
+
changes: requiredRecord(args.changes, "changes")
|
|
973
|
+
}
|
|
974
|
+
]);
|
|
975
|
+
}
|
|
976
|
+
function pathCreateTool(context, args) {
|
|
977
|
+
const segments = optionalSegments(args.segments);
|
|
978
|
+
const style = optionalRecord(args.style);
|
|
979
|
+
const node = {
|
|
980
|
+
id: requiredString(args.id, "id"),
|
|
981
|
+
type: "path",
|
|
982
|
+
start: requiredPoint(args.start, "start"),
|
|
983
|
+
closed: args.closed === true,
|
|
984
|
+
segments,
|
|
985
|
+
...style ? { style } : {}
|
|
986
|
+
};
|
|
987
|
+
return applyPatchOperations(context, args, [
|
|
988
|
+
{
|
|
989
|
+
op: "insert",
|
|
990
|
+
parentId: optionalString(args.parentId) ?? "root",
|
|
991
|
+
node
|
|
992
|
+
}
|
|
993
|
+
]);
|
|
994
|
+
}
|
|
995
|
+
function pathSegmentAppendTool(context, args) {
|
|
996
|
+
const path = readPathNode(context, args);
|
|
997
|
+
const segment = requiredSegment(args.segment, "segment");
|
|
998
|
+
return applyPatchOperations(context, args, [
|
|
999
|
+
{
|
|
1000
|
+
op: "update",
|
|
1001
|
+
target: path.id,
|
|
1002
|
+
changes: {
|
|
1003
|
+
segments: [...path.segments, segment],
|
|
1004
|
+
spline: void 0
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
]);
|
|
1008
|
+
}
|
|
1009
|
+
function pathSegmentUpdateTool(context, args) {
|
|
1010
|
+
const path = readPathNode(context, args);
|
|
1011
|
+
const index = requiredIndex(args.index, path.segments.length, "index");
|
|
1012
|
+
const segment = requiredSegment(args.segment, "segment");
|
|
1013
|
+
const segments = path.segments.map((current, currentIndex) => currentIndex === index ? segment : current);
|
|
1014
|
+
return applyPatchOperations(context, args, [
|
|
1015
|
+
{
|
|
1016
|
+
op: "update",
|
|
1017
|
+
target: path.id,
|
|
1018
|
+
changes: {
|
|
1019
|
+
segments,
|
|
1020
|
+
spline: void 0
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
]);
|
|
1024
|
+
}
|
|
1025
|
+
function pathSegmentDeleteTool(context, args) {
|
|
1026
|
+
const path = readPathNode(context, args);
|
|
1027
|
+
const index = requiredIndex(args.index, path.segments.length, "index");
|
|
1028
|
+
const segments = path.segments.filter((_, currentIndex) => currentIndex !== index);
|
|
1029
|
+
return applyPatchOperations(context, args, [
|
|
1030
|
+
{
|
|
1031
|
+
op: "update",
|
|
1032
|
+
target: path.id,
|
|
1033
|
+
changes: {
|
|
1034
|
+
segments,
|
|
1035
|
+
spline: void 0
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
]);
|
|
1039
|
+
}
|
|
1040
|
+
function pathSetClosedTool(context, args) {
|
|
1041
|
+
if (typeof args.closed !== "boolean") {
|
|
1042
|
+
throw new Error("closed must be a boolean.");
|
|
1043
|
+
}
|
|
1044
|
+
const path = readPathNode(context, args);
|
|
1045
|
+
return applyPatchOperations(context, args, [
|
|
1046
|
+
{
|
|
1047
|
+
op: "update",
|
|
1048
|
+
target: path.id,
|
|
1049
|
+
changes: {
|
|
1050
|
+
closed: args.closed
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
]);
|
|
1054
|
+
}
|
|
1055
|
+
function applyPatchOperations(context, args, patches) {
|
|
1056
|
+
assertRevision(context, optionalString(args.revision));
|
|
1057
|
+
const dryRun = args.dryRun === true;
|
|
1058
|
+
const project = context.store.readProject();
|
|
1059
|
+
const page = pageByOptionalId(project, optionalString(args.pageId));
|
|
1060
|
+
const nextDocument = patches.length === 1 ? applyPatch(page.document, patches[0]) : applyPatches(page.document, patches);
|
|
1061
|
+
const nextProject = updatePageDocument(project, page.id, nextDocument);
|
|
1062
|
+
if (dryRun) {
|
|
1063
|
+
return {
|
|
1064
|
+
ok: true,
|
|
1065
|
+
dryRun,
|
|
1066
|
+
pageId: page.id,
|
|
1067
|
+
patches,
|
|
1068
|
+
document: nextDocument,
|
|
1069
|
+
revision: context.store.revision()
|
|
1070
|
+
};
|
|
1071
|
+
}
|
|
1072
|
+
const change = context.store.writeProject(nextProject);
|
|
1073
|
+
return {
|
|
1074
|
+
ok: true,
|
|
1075
|
+
dryRun,
|
|
1076
|
+
pageId: page.id,
|
|
1077
|
+
patches,
|
|
1078
|
+
document: nextDocument,
|
|
1079
|
+
revision: change.revision
|
|
1080
|
+
};
|
|
1081
|
+
}
|
|
1082
|
+
function readPathNode(context, args) {
|
|
1083
|
+
const project = context.store.readProject();
|
|
1084
|
+
const page = pageByOptionalId(project, optionalString(args.pageId));
|
|
1085
|
+
const target = requiredString(args.target, "target");
|
|
1086
|
+
const node = findNode(page.document.root, target);
|
|
1087
|
+
if (!node) {
|
|
1088
|
+
throw new Error(`Unknown path node: ${target}`);
|
|
1089
|
+
}
|
|
1090
|
+
if (node.type !== "path") {
|
|
1091
|
+
throw new Error(`Node is not a path: ${target}`);
|
|
1092
|
+
}
|
|
1093
|
+
return node;
|
|
1094
|
+
}
|
|
1095
|
+
function pageAddTool(context, args) {
|
|
1096
|
+
assertRevision(context, optionalString(args.revision));
|
|
1097
|
+
const project = context.store.readProject();
|
|
1098
|
+
const pageId = nextPageId(project);
|
|
1099
|
+
const activePage2 = pageByOptionalId(project);
|
|
1100
|
+
const page = createPage({
|
|
1101
|
+
pageId,
|
|
1102
|
+
name: optionalString(args.name) ?? `Page ${project.pages.length + 1}`,
|
|
1103
|
+
width: optionalNumber2(args.width) ?? activePage2.document.width,
|
|
1104
|
+
height: optionalNumber2(args.height) ?? activePage2.document.height
|
|
1105
|
+
});
|
|
1106
|
+
const nextProject = touchProject({
|
|
1107
|
+
...project,
|
|
1108
|
+
activePageId: page.id,
|
|
1109
|
+
pages: [...project.pages, page]
|
|
1110
|
+
});
|
|
1111
|
+
if (args.dryRun === true) {
|
|
1112
|
+
return { ok: true, dryRun: true, page, project: nextProject, revision: context.store.revision() };
|
|
1113
|
+
}
|
|
1114
|
+
const change = context.store.writeProject(nextProject);
|
|
1115
|
+
return { ok: true, dryRun: false, page, revision: change.revision };
|
|
1116
|
+
}
|
|
1117
|
+
function pageDuplicateTool(context, args) {
|
|
1118
|
+
assertRevision(context, optionalString(args.revision));
|
|
1119
|
+
const project = context.store.readProject();
|
|
1120
|
+
const sourcePage = pageByOptionalId(project, optionalString(args.pageId));
|
|
1121
|
+
const pageId = nextPageId(project);
|
|
1122
|
+
const document = structuredClone(sourcePage.document);
|
|
1123
|
+
document.id = `${pageId}-document`;
|
|
1124
|
+
document.name = `${sourcePage.name} Copy`;
|
|
1125
|
+
const page = {
|
|
1126
|
+
id: pageId,
|
|
1127
|
+
name: document.name,
|
|
1128
|
+
document
|
|
1129
|
+
};
|
|
1130
|
+
const nextProject = touchProject({
|
|
1131
|
+
...project,
|
|
1132
|
+
activePageId: pageId,
|
|
1133
|
+
pages: [...project.pages, page]
|
|
1134
|
+
});
|
|
1135
|
+
if (args.dryRun === true) {
|
|
1136
|
+
return { ok: true, dryRun: true, page, project: nextProject, revision: context.store.revision() };
|
|
1137
|
+
}
|
|
1138
|
+
const change = context.store.writeProject(nextProject);
|
|
1139
|
+
return { ok: true, dryRun: false, page, revision: change.revision };
|
|
1140
|
+
}
|
|
1141
|
+
function pageDeleteTool(context, args) {
|
|
1142
|
+
assertRevision(context, optionalString(args.revision));
|
|
1143
|
+
const pageId = requiredString(args.pageId, "pageId");
|
|
1144
|
+
const project = context.store.readProject();
|
|
1145
|
+
if (project.pages.length <= 1) {
|
|
1146
|
+
throw new Error("Cannot delete the last page.");
|
|
1147
|
+
}
|
|
1148
|
+
if (!project.pages.some((page) => page.id === pageId)) {
|
|
1149
|
+
throw new Error(`Unknown pageId: ${pageId}`);
|
|
1150
|
+
}
|
|
1151
|
+
const pages = project.pages.filter((page) => page.id !== pageId);
|
|
1152
|
+
const activePageId = project.activePageId === pageId ? pages[0].id : project.activePageId;
|
|
1153
|
+
const nextProject = touchProject({ ...project, activePageId, pages });
|
|
1154
|
+
if (args.dryRun === true) {
|
|
1155
|
+
return { ok: true, dryRun: true, project: nextProject, revision: context.store.revision() };
|
|
1156
|
+
}
|
|
1157
|
+
const change = context.store.writeProject(nextProject);
|
|
1158
|
+
return { ok: true, dryRun: false, revision: change.revision };
|
|
1159
|
+
}
|
|
1160
|
+
function pageSetActiveTool(context, args) {
|
|
1161
|
+
assertRevision(context, optionalString(args.revision));
|
|
1162
|
+
const pageId = requiredString(args.pageId, "pageId");
|
|
1163
|
+
const project = context.store.readProject();
|
|
1164
|
+
if (!project.pages.some((page) => page.id === pageId)) {
|
|
1165
|
+
throw new Error(`Unknown pageId: ${pageId}`);
|
|
1166
|
+
}
|
|
1167
|
+
const nextProject = touchProject({ ...project, activePageId: pageId });
|
|
1168
|
+
if (args.dryRun === true) {
|
|
1169
|
+
return { ok: true, dryRun: true, project: nextProject, revision: context.store.revision() };
|
|
1170
|
+
}
|
|
1171
|
+
const change = context.store.writeProject(nextProject);
|
|
1172
|
+
return { ok: true, dryRun: false, activePageId: pageId, revision: change.revision };
|
|
1173
|
+
}
|
|
1174
|
+
function assertRevision(context, revision) {
|
|
1175
|
+
if (revision && revision !== context.store.revision()) {
|
|
1176
|
+
throw new Error(`Revision mismatch. Current revision is ${context.store.revision()}.`);
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
function updatePageDocument(project, pageId, document) {
|
|
1180
|
+
return touchProject({
|
|
1181
|
+
...project,
|
|
1182
|
+
pages: project.pages.map(
|
|
1183
|
+
(page) => page.id === pageId ? {
|
|
1184
|
+
...page,
|
|
1185
|
+
name: document.name,
|
|
1186
|
+
document
|
|
1187
|
+
} : page
|
|
1188
|
+
)
|
|
1189
|
+
});
|
|
1190
|
+
}
|
|
1191
|
+
function findNode(node, target) {
|
|
1192
|
+
if (node.id === target) {
|
|
1193
|
+
return node;
|
|
1194
|
+
}
|
|
1195
|
+
if (node.type !== "group") {
|
|
1196
|
+
return void 0;
|
|
1197
|
+
}
|
|
1198
|
+
for (const child of node.children) {
|
|
1199
|
+
const match2 = findNode(child, target);
|
|
1200
|
+
if (match2) {
|
|
1201
|
+
return match2;
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
return void 0;
|
|
1205
|
+
}
|
|
1206
|
+
function touchProject(project) {
|
|
1207
|
+
return {
|
|
1208
|
+
...project,
|
|
1209
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1210
|
+
};
|
|
1211
|
+
}
|
|
1212
|
+
function pageByOptionalId(project, pageId) {
|
|
1213
|
+
const page = pageId ? project.pages.find((item) => item.id === pageId) : project.pages.find((item) => item.id === project.activePageId) ?? project.pages[0];
|
|
1214
|
+
if (!page) {
|
|
1215
|
+
throw new Error(pageId ? `Unknown pageId: ${pageId}` : "Project has no pages.");
|
|
1216
|
+
}
|
|
1217
|
+
return page;
|
|
1218
|
+
}
|
|
1219
|
+
function pageSummary(page) {
|
|
1220
|
+
return {
|
|
1221
|
+
id: page.id,
|
|
1222
|
+
name: page.name,
|
|
1223
|
+
width: page.document.width,
|
|
1224
|
+
height: page.document.height,
|
|
1225
|
+
nodeCount: page.document.root.children.length,
|
|
1226
|
+
commentCount: page.document.comments.length
|
|
1227
|
+
};
|
|
1228
|
+
}
|
|
1229
|
+
function nextPageId(project) {
|
|
1230
|
+
let index = project.pages.length + 1;
|
|
1231
|
+
while (project.pages.some((page) => page.id === `page-${index}`)) {
|
|
1232
|
+
index += 1;
|
|
1233
|
+
}
|
|
1234
|
+
return `page-${index}`;
|
|
1235
|
+
}
|
|
1236
|
+
function isPatchOperation(value) {
|
|
1237
|
+
return Boolean(value && typeof value === "object" && "op" in value && typeof value.op === "string");
|
|
1238
|
+
}
|
|
1239
|
+
function isGeometryNode(value) {
|
|
1240
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
1241
|
+
return false;
|
|
1242
|
+
}
|
|
1243
|
+
const node = value;
|
|
1244
|
+
return typeof node.id === "string" && isNodeType(node.type);
|
|
1245
|
+
}
|
|
1246
|
+
function isNodeType(value) {
|
|
1247
|
+
return value === "group" || value === "rect" || value === "circle" || value === "ellipse" || value === "line" || value === "polygon" || value === "polyline" || value === "path";
|
|
1248
|
+
}
|
|
1249
|
+
function optionalSegments(value) {
|
|
1250
|
+
if (value === void 0) {
|
|
1251
|
+
return [];
|
|
1252
|
+
}
|
|
1253
|
+
if (!Array.isArray(value)) {
|
|
1254
|
+
throw new Error("segments must be an array.");
|
|
1255
|
+
}
|
|
1256
|
+
return value.map((segment, index) => requiredSegment(segment, `segments[${index}]`));
|
|
1257
|
+
}
|
|
1258
|
+
function requiredSegment(value, name) {
|
|
1259
|
+
const segment = requiredRecord(value, name);
|
|
1260
|
+
const type = segment.type;
|
|
1261
|
+
if (type === "line") {
|
|
1262
|
+
return {
|
|
1263
|
+
type,
|
|
1264
|
+
to: requiredPoint(segment.to, `${name}.to`)
|
|
1265
|
+
};
|
|
1266
|
+
}
|
|
1267
|
+
if (type === "quadratic") {
|
|
1268
|
+
return {
|
|
1269
|
+
type,
|
|
1270
|
+
control: requiredPoint(segment.control, `${name}.control`),
|
|
1271
|
+
to: requiredPoint(segment.to, `${name}.to`)
|
|
1272
|
+
};
|
|
1273
|
+
}
|
|
1274
|
+
if (type === "cubic") {
|
|
1275
|
+
return {
|
|
1276
|
+
type,
|
|
1277
|
+
control1: requiredPoint(segment.control1, `${name}.control1`),
|
|
1278
|
+
control2: requiredPoint(segment.control2, `${name}.control2`),
|
|
1279
|
+
to: requiredPoint(segment.to, `${name}.to`)
|
|
1280
|
+
};
|
|
1281
|
+
}
|
|
1282
|
+
if (type === "arc") {
|
|
1283
|
+
return {
|
|
1284
|
+
type,
|
|
1285
|
+
rx: requiredNumber(segment.rx, `${name}.rx`),
|
|
1286
|
+
ry: requiredNumber(segment.ry, `${name}.ry`),
|
|
1287
|
+
xAxisRotation: optionalNumber2(segment.xAxisRotation) ?? 0,
|
|
1288
|
+
largeArc: requiredBoolean(segment.largeArc, `${name}.largeArc`),
|
|
1289
|
+
sweep: requiredBoolean(segment.sweep, `${name}.sweep`),
|
|
1290
|
+
to: requiredPoint(segment.to, `${name}.to`)
|
|
1291
|
+
};
|
|
1292
|
+
}
|
|
1293
|
+
throw new Error(`${name}.type must be line, quadratic, cubic, or arc.`);
|
|
1294
|
+
}
|
|
1295
|
+
function requiredPoint(value, name) {
|
|
1296
|
+
const point = requiredRecord(value, name);
|
|
1297
|
+
return {
|
|
1298
|
+
x: requiredNumber(point.x, `${name}.x`),
|
|
1299
|
+
y: requiredNumber(point.y, `${name}.y`)
|
|
1300
|
+
};
|
|
1301
|
+
}
|
|
1302
|
+
function optionalString(value) {
|
|
1303
|
+
return typeof value === "string" ? value : void 0;
|
|
1304
|
+
}
|
|
1305
|
+
function requiredString(value, name) {
|
|
1306
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
1307
|
+
throw new Error(`${name} is required.`);
|
|
1308
|
+
}
|
|
1309
|
+
return value;
|
|
1310
|
+
}
|
|
1311
|
+
function requiredNumber(value, name) {
|
|
1312
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
1313
|
+
throw new Error(`${name} must be a finite number.`);
|
|
1314
|
+
}
|
|
1315
|
+
return value;
|
|
1316
|
+
}
|
|
1317
|
+
function requiredBoolean(value, name) {
|
|
1318
|
+
if (typeof value !== "boolean") {
|
|
1319
|
+
throw new Error(`${name} must be a boolean.`);
|
|
1320
|
+
}
|
|
1321
|
+
return value;
|
|
1322
|
+
}
|
|
1323
|
+
function requiredIndex(value, length, name) {
|
|
1324
|
+
const index = requiredNumber(value, name);
|
|
1325
|
+
if (!Number.isInteger(index) || index < 0 || index >= length) {
|
|
1326
|
+
throw new Error(`${name} must be an integer from 0 to ${Math.max(0, length - 1)}.`);
|
|
1327
|
+
}
|
|
1328
|
+
return index;
|
|
1329
|
+
}
|
|
1330
|
+
function requiredRecord(value, name) {
|
|
1331
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
1332
|
+
throw new Error(`${name} must be an object.`);
|
|
1333
|
+
}
|
|
1334
|
+
return value;
|
|
1335
|
+
}
|
|
1336
|
+
function optionalRecord(value) {
|
|
1337
|
+
if (value === void 0) {
|
|
1338
|
+
return void 0;
|
|
1339
|
+
}
|
|
1340
|
+
return requiredRecord(value, "style");
|
|
1341
|
+
}
|
|
1342
|
+
function optionalNumber2(value) {
|
|
1343
|
+
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
1344
|
+
}
|
|
1345
|
+
function mcpText(value, isError = false) {
|
|
1346
|
+
return {
|
|
1347
|
+
content: [
|
|
1348
|
+
{
|
|
1349
|
+
type: "text",
|
|
1350
|
+
text: typeof value === "string" ? value : JSON.stringify(value, null, 2)
|
|
1351
|
+
}
|
|
1352
|
+
],
|
|
1353
|
+
isError
|
|
1354
|
+
};
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
// ../../packages/mcp/src/index.ts
|
|
1358
|
+
async function handleMcpBody(context, body) {
|
|
1359
|
+
if (Array.isArray(body)) {
|
|
1360
|
+
const responses = await Promise.all(body.map((item) => handleMcpMessage(context, item)));
|
|
1361
|
+
const filteredResponses = responses.filter((response) => Boolean(response));
|
|
1362
|
+
return filteredResponses.length > 0 ? filteredResponses : null;
|
|
1363
|
+
}
|
|
1364
|
+
return handleMcpMessage(context, body);
|
|
1365
|
+
}
|
|
1366
|
+
async function handleMcpMessage(context, rawRequest) {
|
|
1367
|
+
const request = rawRequest;
|
|
1368
|
+
if (request.id === void 0 || request.id === null) {
|
|
1369
|
+
return null;
|
|
1370
|
+
}
|
|
1371
|
+
try {
|
|
1372
|
+
switch (request.method) {
|
|
1373
|
+
case "initialize":
|
|
1374
|
+
return jsonRpcResult(request.id, {
|
|
1375
|
+
protocolVersion: stringParam(request.params?.protocolVersion) ?? "2024-11-05",
|
|
1376
|
+
capabilities: {
|
|
1377
|
+
tools: { listChanged: false },
|
|
1378
|
+
resources: { subscribe: false, listChanged: false }
|
|
1379
|
+
},
|
|
1380
|
+
serverInfo: {
|
|
1381
|
+
name: "glyphsmith",
|
|
1382
|
+
version: "0.0.0"
|
|
1383
|
+
}
|
|
1384
|
+
});
|
|
1385
|
+
case "ping":
|
|
1386
|
+
return jsonRpcResult(request.id, {});
|
|
1387
|
+
case "tools/list":
|
|
1388
|
+
return jsonRpcResult(request.id, { tools: mcpTools() });
|
|
1389
|
+
case "resources/list":
|
|
1390
|
+
return jsonRpcResult(request.id, { resources: mcpResources() });
|
|
1391
|
+
case "resources/templates/list":
|
|
1392
|
+
return jsonRpcResult(request.id, { resourceTemplates: mcpResourceTemplates() });
|
|
1393
|
+
case "resources/read":
|
|
1394
|
+
return jsonRpcResult(
|
|
1395
|
+
request.id,
|
|
1396
|
+
readMcpResource(
|
|
1397
|
+
context.store.readProject(),
|
|
1398
|
+
context.store.selection(),
|
|
1399
|
+
context.store.revision(),
|
|
1400
|
+
String(request.params?.uri ?? "")
|
|
1401
|
+
)
|
|
1402
|
+
);
|
|
1403
|
+
case "tools/call":
|
|
1404
|
+
return jsonRpcResult(
|
|
1405
|
+
request.id,
|
|
1406
|
+
callMcpTool(
|
|
1407
|
+
context,
|
|
1408
|
+
String(request.params?.name ?? ""),
|
|
1409
|
+
recordParam(request.params?.arguments)
|
|
1410
|
+
)
|
|
1411
|
+
);
|
|
1412
|
+
default:
|
|
1413
|
+
return jsonRpcError(request.id, -32601, `Unsupported MCP method: ${request.method ?? ""}`);
|
|
1414
|
+
}
|
|
1415
|
+
} catch (error) {
|
|
1416
|
+
return jsonRpcError(request.id, -32e3, error instanceof Error ? error.message : String(error));
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
function recordParam(value) {
|
|
1420
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
1421
|
+
}
|
|
1422
|
+
function stringParam(value) {
|
|
1423
|
+
return typeof value === "string" ? value : void 0;
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
// src/project-store.ts
|
|
1427
|
+
import { createHash } from "node:crypto";
|
|
1428
|
+
import { existsSync, readFileSync, unwatchFile, watchFile, writeFileSync } from "node:fs";
|
|
1429
|
+
import { basename } from "node:path";
|
|
1430
|
+
var ProjectStore = class {
|
|
1431
|
+
projectFile;
|
|
1432
|
+
lastProjectText;
|
|
1433
|
+
listeners = /* @__PURE__ */ new Set();
|
|
1434
|
+
currentSelection = { nodeIds: [] };
|
|
1435
|
+
constructor(projectFile) {
|
|
1436
|
+
this.projectFile = projectFile;
|
|
1437
|
+
this.ensureProjectFile();
|
|
1438
|
+
this.lastProjectText = this.readProjectText();
|
|
1439
|
+
watchFile(this.projectFile, { interval: 500 }, () => {
|
|
1440
|
+
const nextProjectText = this.readProjectText();
|
|
1441
|
+
if (nextProjectText === this.lastProjectText) {
|
|
1442
|
+
return;
|
|
1443
|
+
}
|
|
1444
|
+
this.lastProjectText = nextProjectText;
|
|
1445
|
+
this.emitChange({ project: this.parseProjectText(nextProjectText), revision: this.revision() });
|
|
1446
|
+
});
|
|
1447
|
+
}
|
|
1448
|
+
close() {
|
|
1449
|
+
unwatchFile(this.projectFile);
|
|
1450
|
+
this.listeners.clear();
|
|
1451
|
+
}
|
|
1452
|
+
subscribe(listener) {
|
|
1453
|
+
this.listeners.add(listener);
|
|
1454
|
+
return () => {
|
|
1455
|
+
this.listeners.delete(listener);
|
|
1456
|
+
};
|
|
1457
|
+
}
|
|
1458
|
+
readProject() {
|
|
1459
|
+
return this.parseProjectText(this.lastProjectText);
|
|
1460
|
+
}
|
|
1461
|
+
writeProject(project, source) {
|
|
1462
|
+
const projectText = `${JSON.stringify(project, null, 2)}
|
|
1463
|
+
`;
|
|
1464
|
+
writeFileSync(this.projectFile, projectText, "utf8");
|
|
1465
|
+
this.lastProjectText = projectText;
|
|
1466
|
+
const change = {
|
|
1467
|
+
project,
|
|
1468
|
+
revision: this.revision(),
|
|
1469
|
+
source
|
|
1470
|
+
};
|
|
1471
|
+
this.emitChange(change);
|
|
1472
|
+
return change;
|
|
1473
|
+
}
|
|
1474
|
+
updateProject(mutator, source) {
|
|
1475
|
+
return this.writeProject(mutator(this.readProject()), source);
|
|
1476
|
+
}
|
|
1477
|
+
revision() {
|
|
1478
|
+
return createHash("sha1").update(this.lastProjectText).digest("hex");
|
|
1479
|
+
}
|
|
1480
|
+
selection() {
|
|
1481
|
+
return this.currentSelection;
|
|
1482
|
+
}
|
|
1483
|
+
setSelection(selection) {
|
|
1484
|
+
this.currentSelection = selection;
|
|
1485
|
+
}
|
|
1486
|
+
ensureProjectFile() {
|
|
1487
|
+
if (existsSync(this.projectFile)) {
|
|
1488
|
+
return;
|
|
1489
|
+
}
|
|
1490
|
+
writeFileSync(this.projectFile, `${JSON.stringify(createInitialProject(this.projectFile), null, 2)}
|
|
1491
|
+
`, "utf8");
|
|
1492
|
+
}
|
|
1493
|
+
readProjectText() {
|
|
1494
|
+
return readFileSync(this.projectFile, "utf8");
|
|
1495
|
+
}
|
|
1496
|
+
parseProjectText(projectText) {
|
|
1497
|
+
const project = JSON.parse(projectText);
|
|
1498
|
+
if (!isGlyphSmithProject(project)) {
|
|
1499
|
+
throw new Error(`Invalid GlyphSmith project: ${this.projectFile}`);
|
|
1500
|
+
}
|
|
1501
|
+
return project;
|
|
1502
|
+
}
|
|
1503
|
+
emitChange(change) {
|
|
1504
|
+
for (const listener of this.listeners) {
|
|
1505
|
+
listener(change);
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
};
|
|
1509
|
+
function createInitialProject(projectFile) {
|
|
1510
|
+
return createProject({
|
|
1511
|
+
name: basename(projectFile).replace(/\.gs\.json$/i, "") || "GlyphSmith Project",
|
|
1512
|
+
width: 256,
|
|
1513
|
+
height: 256
|
|
1514
|
+
});
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
// src/server.ts
|
|
1518
|
+
import { createServer } from "node:http";
|
|
1519
|
+
import { createReadStream, existsSync as existsSync2 } from "node:fs";
|
|
1520
|
+
import { stat } from "node:fs/promises";
|
|
1521
|
+
import { extname, join, normalize, resolve, sep } from "node:path";
|
|
1522
|
+
|
|
1523
|
+
// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/compose.js
|
|
1524
|
+
var compose = (middleware, onError, onNotFound) => {
|
|
1525
|
+
return (context, next) => {
|
|
1526
|
+
let index = -1;
|
|
1527
|
+
return dispatch(0);
|
|
1528
|
+
async function dispatch(i) {
|
|
1529
|
+
if (i <= index) {
|
|
1530
|
+
throw new Error("next() called multiple times");
|
|
1531
|
+
}
|
|
1532
|
+
index = i;
|
|
1533
|
+
let res;
|
|
1534
|
+
let isError = false;
|
|
1535
|
+
let handler;
|
|
1536
|
+
if (middleware[i]) {
|
|
1537
|
+
handler = middleware[i][0][0];
|
|
1538
|
+
context.req.routeIndex = i;
|
|
1539
|
+
} else {
|
|
1540
|
+
handler = i === middleware.length && next || void 0;
|
|
1541
|
+
}
|
|
1542
|
+
if (handler) {
|
|
1543
|
+
try {
|
|
1544
|
+
res = await handler(context, () => dispatch(i + 1));
|
|
1545
|
+
} catch (err) {
|
|
1546
|
+
if (err instanceof Error && onError) {
|
|
1547
|
+
context.error = err;
|
|
1548
|
+
res = await onError(err, context);
|
|
1549
|
+
isError = true;
|
|
1550
|
+
} else {
|
|
1551
|
+
throw err;
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
} else {
|
|
1555
|
+
if (context.finalized === false && onNotFound) {
|
|
1556
|
+
res = await onNotFound(context);
|
|
1557
|
+
}
|
|
1558
|
+
}
|
|
1559
|
+
if (res && (context.finalized === false || isError)) {
|
|
1560
|
+
context.res = res;
|
|
1561
|
+
}
|
|
1562
|
+
return context;
|
|
1563
|
+
}
|
|
1564
|
+
};
|
|
1565
|
+
};
|
|
1566
|
+
|
|
1567
|
+
// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/request/constants.js
|
|
1568
|
+
var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
|
|
1569
|
+
|
|
1570
|
+
// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/body.js
|
|
1571
|
+
var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
|
|
1572
|
+
const { all = false, dot = false } = options;
|
|
1573
|
+
const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
|
|
1574
|
+
const contentType = headers.get("Content-Type");
|
|
1575
|
+
if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
|
|
1576
|
+
return parseFormData(request, { all, dot });
|
|
1577
|
+
}
|
|
1578
|
+
return {};
|
|
1579
|
+
};
|
|
1580
|
+
async function parseFormData(request, options) {
|
|
1581
|
+
const formData = await request.formData();
|
|
1582
|
+
if (formData) {
|
|
1583
|
+
return convertFormDataToBodyData(formData, options);
|
|
1584
|
+
}
|
|
1585
|
+
return {};
|
|
1586
|
+
}
|
|
1587
|
+
function convertFormDataToBodyData(formData, options) {
|
|
1588
|
+
const form = /* @__PURE__ */ Object.create(null);
|
|
1589
|
+
formData.forEach((value, key) => {
|
|
1590
|
+
const shouldParseAllValues = options.all || key.endsWith("[]");
|
|
1591
|
+
if (!shouldParseAllValues) {
|
|
1592
|
+
form[key] = value;
|
|
1593
|
+
} else {
|
|
1594
|
+
handleParsingAllValues(form, key, value);
|
|
1595
|
+
}
|
|
1596
|
+
});
|
|
1597
|
+
if (options.dot) {
|
|
1598
|
+
Object.entries(form).forEach(([key, value]) => {
|
|
1599
|
+
const shouldParseDotValues = key.includes(".");
|
|
1600
|
+
if (shouldParseDotValues) {
|
|
1601
|
+
handleParsingNestedValues(form, key, value);
|
|
1602
|
+
delete form[key];
|
|
1603
|
+
}
|
|
1604
|
+
});
|
|
1605
|
+
}
|
|
1606
|
+
return form;
|
|
1607
|
+
}
|
|
1608
|
+
var handleParsingAllValues = (form, key, value) => {
|
|
1609
|
+
if (form[key] !== void 0) {
|
|
1610
|
+
if (Array.isArray(form[key])) {
|
|
1611
|
+
;
|
|
1612
|
+
form[key].push(value);
|
|
1613
|
+
} else {
|
|
1614
|
+
form[key] = [form[key], value];
|
|
1615
|
+
}
|
|
1616
|
+
} else {
|
|
1617
|
+
if (!key.endsWith("[]")) {
|
|
1618
|
+
form[key] = value;
|
|
1619
|
+
} else {
|
|
1620
|
+
form[key] = [value];
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
};
|
|
1624
|
+
var handleParsingNestedValues = (form, key, value) => {
|
|
1625
|
+
if (/(?:^|\.)__proto__\./.test(key)) {
|
|
1626
|
+
return;
|
|
1627
|
+
}
|
|
1628
|
+
let nestedForm = form;
|
|
1629
|
+
const keys = key.split(".");
|
|
1630
|
+
keys.forEach((key2, index) => {
|
|
1631
|
+
if (index === keys.length - 1) {
|
|
1632
|
+
nestedForm[key2] = value;
|
|
1633
|
+
} else {
|
|
1634
|
+
if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
|
|
1635
|
+
nestedForm[key2] = /* @__PURE__ */ Object.create(null);
|
|
1636
|
+
}
|
|
1637
|
+
nestedForm = nestedForm[key2];
|
|
1638
|
+
}
|
|
1639
|
+
});
|
|
1640
|
+
};
|
|
1641
|
+
|
|
1642
|
+
// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/url.js
|
|
1643
|
+
var splitPath = (path) => {
|
|
1644
|
+
const paths = path.split("/");
|
|
1645
|
+
if (paths[0] === "") {
|
|
1646
|
+
paths.shift();
|
|
1647
|
+
}
|
|
1648
|
+
return paths;
|
|
1649
|
+
};
|
|
1650
|
+
var splitRoutingPath = (routePath) => {
|
|
1651
|
+
const { groups, path } = extractGroupsFromPath(routePath);
|
|
1652
|
+
const paths = splitPath(path);
|
|
1653
|
+
return replaceGroupMarks(paths, groups);
|
|
1654
|
+
};
|
|
1655
|
+
var extractGroupsFromPath = (path) => {
|
|
1656
|
+
const groups = [];
|
|
1657
|
+
path = path.replace(/\{[^}]+\}/g, (match2, index) => {
|
|
1658
|
+
const mark = `@${index}`;
|
|
1659
|
+
groups.push([mark, match2]);
|
|
1660
|
+
return mark;
|
|
1661
|
+
});
|
|
1662
|
+
return { groups, path };
|
|
1663
|
+
};
|
|
1664
|
+
var replaceGroupMarks = (paths, groups) => {
|
|
1665
|
+
for (let i = groups.length - 1; i >= 0; i--) {
|
|
1666
|
+
const [mark] = groups[i];
|
|
1667
|
+
for (let j = paths.length - 1; j >= 0; j--) {
|
|
1668
|
+
if (paths[j].includes(mark)) {
|
|
1669
|
+
paths[j] = paths[j].replace(mark, groups[i][1]);
|
|
1670
|
+
break;
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
return paths;
|
|
1675
|
+
};
|
|
1676
|
+
var patternCache = {};
|
|
1677
|
+
var getPattern = (label, next) => {
|
|
1678
|
+
if (label === "*") {
|
|
1679
|
+
return "*";
|
|
1680
|
+
}
|
|
1681
|
+
const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
1682
|
+
if (match2) {
|
|
1683
|
+
const cacheKey = `${label}#${next}`;
|
|
1684
|
+
if (!patternCache[cacheKey]) {
|
|
1685
|
+
if (match2[2]) {
|
|
1686
|
+
patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
|
|
1687
|
+
} else {
|
|
1688
|
+
patternCache[cacheKey] = [label, match2[1], true];
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
return patternCache[cacheKey];
|
|
1692
|
+
}
|
|
1693
|
+
return null;
|
|
1694
|
+
};
|
|
1695
|
+
var tryDecode = (str, decoder) => {
|
|
1696
|
+
try {
|
|
1697
|
+
return decoder(str);
|
|
1698
|
+
} catch {
|
|
1699
|
+
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
|
|
1700
|
+
try {
|
|
1701
|
+
return decoder(match2);
|
|
1702
|
+
} catch {
|
|
1703
|
+
return match2;
|
|
1704
|
+
}
|
|
1705
|
+
});
|
|
1706
|
+
}
|
|
1707
|
+
};
|
|
1708
|
+
var tryDecodeURI = (str) => tryDecode(str, decodeURI);
|
|
1709
|
+
var getPath = (request) => {
|
|
1710
|
+
const url = request.url;
|
|
1711
|
+
const start = url.indexOf("/", url.indexOf(":") + 4);
|
|
1712
|
+
let i = start;
|
|
1713
|
+
for (; i < url.length; i++) {
|
|
1714
|
+
const charCode = url.charCodeAt(i);
|
|
1715
|
+
if (charCode === 37) {
|
|
1716
|
+
const queryIndex = url.indexOf("?", i);
|
|
1717
|
+
const hashIndex = url.indexOf("#", i);
|
|
1718
|
+
const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
|
|
1719
|
+
const path = url.slice(start, end);
|
|
1720
|
+
return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
|
|
1721
|
+
} else if (charCode === 63 || charCode === 35) {
|
|
1722
|
+
break;
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
return url.slice(start, i);
|
|
1726
|
+
};
|
|
1727
|
+
var getPathNoStrict = (request) => {
|
|
1728
|
+
const result = getPath(request);
|
|
1729
|
+
return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
|
|
1730
|
+
};
|
|
1731
|
+
var mergePath = (base, sub, ...rest) => {
|
|
1732
|
+
if (rest.length) {
|
|
1733
|
+
sub = mergePath(sub, ...rest);
|
|
1734
|
+
}
|
|
1735
|
+
return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
|
|
1736
|
+
};
|
|
1737
|
+
var checkOptionalParameter = (path) => {
|
|
1738
|
+
if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
|
|
1739
|
+
return null;
|
|
1740
|
+
}
|
|
1741
|
+
const segments = path.split("/");
|
|
1742
|
+
const results = [];
|
|
1743
|
+
let basePath = "";
|
|
1744
|
+
segments.forEach((segment) => {
|
|
1745
|
+
if (segment !== "" && !/\:/.test(segment)) {
|
|
1746
|
+
basePath += "/" + segment;
|
|
1747
|
+
} else if (/\:/.test(segment)) {
|
|
1748
|
+
if (/\?/.test(segment)) {
|
|
1749
|
+
if (results.length === 0 && basePath === "") {
|
|
1750
|
+
results.push("/");
|
|
1751
|
+
} else {
|
|
1752
|
+
results.push(basePath);
|
|
1753
|
+
}
|
|
1754
|
+
const optionalSegment = segment.replace("?", "");
|
|
1755
|
+
basePath += "/" + optionalSegment;
|
|
1756
|
+
results.push(basePath);
|
|
1757
|
+
} else {
|
|
1758
|
+
basePath += "/" + segment;
|
|
1759
|
+
}
|
|
1760
|
+
}
|
|
1761
|
+
});
|
|
1762
|
+
return results.filter((v, i, a) => a.indexOf(v) === i);
|
|
1763
|
+
};
|
|
1764
|
+
var _decodeURI = (value) => {
|
|
1765
|
+
if (!/[%+]/.test(value)) {
|
|
1766
|
+
return value;
|
|
1767
|
+
}
|
|
1768
|
+
if (value.indexOf("+") !== -1) {
|
|
1769
|
+
value = value.replace(/\+/g, " ");
|
|
1770
|
+
}
|
|
1771
|
+
return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
|
|
1772
|
+
};
|
|
1773
|
+
var _getQueryParam = (url, key, multiple) => {
|
|
1774
|
+
let encoded;
|
|
1775
|
+
if (!multiple && key && !/[%+]/.test(key)) {
|
|
1776
|
+
let keyIndex2 = url.indexOf("?", 8);
|
|
1777
|
+
if (keyIndex2 === -1) {
|
|
1778
|
+
return void 0;
|
|
1779
|
+
}
|
|
1780
|
+
if (!url.startsWith(key, keyIndex2 + 1)) {
|
|
1781
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
1782
|
+
}
|
|
1783
|
+
while (keyIndex2 !== -1) {
|
|
1784
|
+
const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
|
|
1785
|
+
if (trailingKeyCode === 61) {
|
|
1786
|
+
const valueIndex = keyIndex2 + key.length + 2;
|
|
1787
|
+
const endIndex = url.indexOf("&", valueIndex);
|
|
1788
|
+
return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
|
|
1789
|
+
} else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
|
|
1790
|
+
return "";
|
|
1791
|
+
}
|
|
1792
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
1793
|
+
}
|
|
1794
|
+
encoded = /[%+]/.test(url);
|
|
1795
|
+
if (!encoded) {
|
|
1796
|
+
return void 0;
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
const results = {};
|
|
1800
|
+
encoded ??= /[%+]/.test(url);
|
|
1801
|
+
let keyIndex = url.indexOf("?", 8);
|
|
1802
|
+
while (keyIndex !== -1) {
|
|
1803
|
+
const nextKeyIndex = url.indexOf("&", keyIndex + 1);
|
|
1804
|
+
let valueIndex = url.indexOf("=", keyIndex);
|
|
1805
|
+
if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
|
|
1806
|
+
valueIndex = -1;
|
|
1807
|
+
}
|
|
1808
|
+
let name = url.slice(
|
|
1809
|
+
keyIndex + 1,
|
|
1810
|
+
valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
|
|
1811
|
+
);
|
|
1812
|
+
if (encoded) {
|
|
1813
|
+
name = _decodeURI(name);
|
|
1814
|
+
}
|
|
1815
|
+
keyIndex = nextKeyIndex;
|
|
1816
|
+
if (name === "") {
|
|
1817
|
+
continue;
|
|
1818
|
+
}
|
|
1819
|
+
let value;
|
|
1820
|
+
if (valueIndex === -1) {
|
|
1821
|
+
value = "";
|
|
1822
|
+
} else {
|
|
1823
|
+
value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
|
|
1824
|
+
if (encoded) {
|
|
1825
|
+
value = _decodeURI(value);
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
if (multiple) {
|
|
1829
|
+
if (!(results[name] && Array.isArray(results[name]))) {
|
|
1830
|
+
results[name] = [];
|
|
1831
|
+
}
|
|
1832
|
+
;
|
|
1833
|
+
results[name].push(value);
|
|
1834
|
+
} else {
|
|
1835
|
+
results[name] ??= value;
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
return key ? results[key] : results;
|
|
1839
|
+
};
|
|
1840
|
+
var getQueryParam = _getQueryParam;
|
|
1841
|
+
var getQueryParams = (url, key) => {
|
|
1842
|
+
return _getQueryParam(url, key, true);
|
|
1843
|
+
};
|
|
1844
|
+
var decodeURIComponent_ = decodeURIComponent;
|
|
1845
|
+
|
|
1846
|
+
// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/request.js
|
|
1847
|
+
var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
|
|
1848
|
+
var HonoRequest = class {
|
|
1849
|
+
/**
|
|
1850
|
+
* `.raw` can get the raw Request object.
|
|
1851
|
+
*
|
|
1852
|
+
* @see {@link https://hono.dev/docs/api/request#raw}
|
|
1853
|
+
*
|
|
1854
|
+
* @example
|
|
1855
|
+
* ```ts
|
|
1856
|
+
* // For Cloudflare Workers
|
|
1857
|
+
* app.post('/', async (c) => {
|
|
1858
|
+
* const metadata = c.req.raw.cf?.hostMetadata?
|
|
1859
|
+
* ...
|
|
1860
|
+
* })
|
|
1861
|
+
* ```
|
|
1862
|
+
*/
|
|
1863
|
+
raw;
|
|
1864
|
+
#validatedData;
|
|
1865
|
+
// Short name of validatedData
|
|
1866
|
+
#matchResult;
|
|
1867
|
+
routeIndex = 0;
|
|
1868
|
+
/**
|
|
1869
|
+
* `.path` can get the pathname of the request.
|
|
1870
|
+
*
|
|
1871
|
+
* @see {@link https://hono.dev/docs/api/request#path}
|
|
1872
|
+
*
|
|
1873
|
+
* @example
|
|
1874
|
+
* ```ts
|
|
1875
|
+
* app.get('/about/me', (c) => {
|
|
1876
|
+
* const pathname = c.req.path // `/about/me`
|
|
1877
|
+
* })
|
|
1878
|
+
* ```
|
|
1879
|
+
*/
|
|
1880
|
+
path;
|
|
1881
|
+
bodyCache = {};
|
|
1882
|
+
constructor(request, path = "/", matchResult = [[]]) {
|
|
1883
|
+
this.raw = request;
|
|
1884
|
+
this.path = path;
|
|
1885
|
+
this.#matchResult = matchResult;
|
|
1886
|
+
this.#validatedData = {};
|
|
1887
|
+
}
|
|
1888
|
+
param(key) {
|
|
1889
|
+
return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
|
|
1890
|
+
}
|
|
1891
|
+
#getDecodedParam(key) {
|
|
1892
|
+
const paramKey = this.#matchResult[0][this.routeIndex][1][key];
|
|
1893
|
+
const param = this.#getParamValue(paramKey);
|
|
1894
|
+
return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
|
|
1895
|
+
}
|
|
1896
|
+
#getAllDecodedParams() {
|
|
1897
|
+
const decoded = {};
|
|
1898
|
+
const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
|
|
1899
|
+
for (const key of keys) {
|
|
1900
|
+
const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
|
|
1901
|
+
if (value !== void 0) {
|
|
1902
|
+
decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
return decoded;
|
|
1906
|
+
}
|
|
1907
|
+
#getParamValue(paramKey) {
|
|
1908
|
+
return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
|
|
1909
|
+
}
|
|
1910
|
+
query(key) {
|
|
1911
|
+
return getQueryParam(this.url, key);
|
|
1912
|
+
}
|
|
1913
|
+
queries(key) {
|
|
1914
|
+
return getQueryParams(this.url, key);
|
|
1915
|
+
}
|
|
1916
|
+
header(name) {
|
|
1917
|
+
if (name) {
|
|
1918
|
+
return this.raw.headers.get(name) ?? void 0;
|
|
1919
|
+
}
|
|
1920
|
+
const headerData = {};
|
|
1921
|
+
this.raw.headers.forEach((value, key) => {
|
|
1922
|
+
headerData[key] = value;
|
|
1923
|
+
});
|
|
1924
|
+
return headerData;
|
|
1925
|
+
}
|
|
1926
|
+
async parseBody(options) {
|
|
1927
|
+
return parseBody(this, options);
|
|
1928
|
+
}
|
|
1929
|
+
#cachedBody = (key) => {
|
|
1930
|
+
const { bodyCache, raw: raw2 } = this;
|
|
1931
|
+
const cachedBody = bodyCache[key];
|
|
1932
|
+
if (cachedBody) {
|
|
1933
|
+
return cachedBody;
|
|
1934
|
+
}
|
|
1935
|
+
const anyCachedKey = Object.keys(bodyCache)[0];
|
|
1936
|
+
if (anyCachedKey) {
|
|
1937
|
+
return bodyCache[anyCachedKey].then((body) => {
|
|
1938
|
+
if (anyCachedKey === "json") {
|
|
1939
|
+
body = JSON.stringify(body);
|
|
1940
|
+
}
|
|
1941
|
+
return new Response(body)[key]();
|
|
1942
|
+
});
|
|
1943
|
+
}
|
|
1944
|
+
return bodyCache[key] = raw2[key]();
|
|
1945
|
+
};
|
|
1946
|
+
/**
|
|
1947
|
+
* `.json()` can parse Request body of type `application/json`
|
|
1948
|
+
*
|
|
1949
|
+
* @see {@link https://hono.dev/docs/api/request#json}
|
|
1950
|
+
*
|
|
1951
|
+
* @example
|
|
1952
|
+
* ```ts
|
|
1953
|
+
* app.post('/entry', async (c) => {
|
|
1954
|
+
* const body = await c.req.json()
|
|
1955
|
+
* })
|
|
1956
|
+
* ```
|
|
1957
|
+
*/
|
|
1958
|
+
json() {
|
|
1959
|
+
return this.#cachedBody("text").then((text) => JSON.parse(text));
|
|
1960
|
+
}
|
|
1961
|
+
/**
|
|
1962
|
+
* `.text()` can parse Request body of type `text/plain`
|
|
1963
|
+
*
|
|
1964
|
+
* @see {@link https://hono.dev/docs/api/request#text}
|
|
1965
|
+
*
|
|
1966
|
+
* @example
|
|
1967
|
+
* ```ts
|
|
1968
|
+
* app.post('/entry', async (c) => {
|
|
1969
|
+
* const body = await c.req.text()
|
|
1970
|
+
* })
|
|
1971
|
+
* ```
|
|
1972
|
+
*/
|
|
1973
|
+
text() {
|
|
1974
|
+
return this.#cachedBody("text");
|
|
1975
|
+
}
|
|
1976
|
+
/**
|
|
1977
|
+
* `.arrayBuffer()` parse Request body as an `ArrayBuffer`
|
|
1978
|
+
*
|
|
1979
|
+
* @see {@link https://hono.dev/docs/api/request#arraybuffer}
|
|
1980
|
+
*
|
|
1981
|
+
* @example
|
|
1982
|
+
* ```ts
|
|
1983
|
+
* app.post('/entry', async (c) => {
|
|
1984
|
+
* const body = await c.req.arrayBuffer()
|
|
1985
|
+
* })
|
|
1986
|
+
* ```
|
|
1987
|
+
*/
|
|
1988
|
+
arrayBuffer() {
|
|
1989
|
+
return this.#cachedBody("arrayBuffer");
|
|
1990
|
+
}
|
|
1991
|
+
/**
|
|
1992
|
+
* `.bytes()` parses the request body as a `Uint8Array`.
|
|
1993
|
+
*
|
|
1994
|
+
* @see {@link https://hono.dev/docs/api/request#bytes}
|
|
1995
|
+
*
|
|
1996
|
+
* @example
|
|
1997
|
+
* ```ts
|
|
1998
|
+
* app.post('/entry', async (c) => {
|
|
1999
|
+
* const body = await c.req.bytes()
|
|
2000
|
+
* })
|
|
2001
|
+
* ```
|
|
2002
|
+
*/
|
|
2003
|
+
bytes() {
|
|
2004
|
+
return this.#cachedBody("arrayBuffer").then((buffer) => new Uint8Array(buffer));
|
|
2005
|
+
}
|
|
2006
|
+
/**
|
|
2007
|
+
* Parses the request body as a `Blob`.
|
|
2008
|
+
* @example
|
|
2009
|
+
* ```ts
|
|
2010
|
+
* app.post('/entry', async (c) => {
|
|
2011
|
+
* const body = await c.req.blob();
|
|
2012
|
+
* });
|
|
2013
|
+
* ```
|
|
2014
|
+
* @see https://hono.dev/docs/api/request#blob
|
|
2015
|
+
*/
|
|
2016
|
+
blob() {
|
|
2017
|
+
return this.#cachedBody("blob");
|
|
2018
|
+
}
|
|
2019
|
+
/**
|
|
2020
|
+
* Parses the request body as `FormData`.
|
|
2021
|
+
* @example
|
|
2022
|
+
* ```ts
|
|
2023
|
+
* app.post('/entry', async (c) => {
|
|
2024
|
+
* const body = await c.req.formData();
|
|
2025
|
+
* });
|
|
2026
|
+
* ```
|
|
2027
|
+
* @see https://hono.dev/docs/api/request#formdata
|
|
2028
|
+
*/
|
|
2029
|
+
formData() {
|
|
2030
|
+
return this.#cachedBody("formData");
|
|
2031
|
+
}
|
|
2032
|
+
/**
|
|
2033
|
+
* Adds validated data to the request.
|
|
2034
|
+
*
|
|
2035
|
+
* @param target - The target of the validation.
|
|
2036
|
+
* @param data - The validated data to add.
|
|
2037
|
+
*/
|
|
2038
|
+
addValidatedData(target, data) {
|
|
2039
|
+
this.#validatedData[target] = data;
|
|
2040
|
+
}
|
|
2041
|
+
valid(target) {
|
|
2042
|
+
return this.#validatedData[target];
|
|
2043
|
+
}
|
|
2044
|
+
/**
|
|
2045
|
+
* `.url()` can get the request url strings.
|
|
2046
|
+
*
|
|
2047
|
+
* @see {@link https://hono.dev/docs/api/request#url}
|
|
2048
|
+
*
|
|
2049
|
+
* @example
|
|
2050
|
+
* ```ts
|
|
2051
|
+
* app.get('/about/me', (c) => {
|
|
2052
|
+
* const url = c.req.url // `http://localhost:8787/about/me`
|
|
2053
|
+
* ...
|
|
2054
|
+
* })
|
|
2055
|
+
* ```
|
|
2056
|
+
*/
|
|
2057
|
+
get url() {
|
|
2058
|
+
return this.raw.url;
|
|
2059
|
+
}
|
|
2060
|
+
/**
|
|
2061
|
+
* `.method()` can get the method name of the request.
|
|
2062
|
+
*
|
|
2063
|
+
* @see {@link https://hono.dev/docs/api/request#method}
|
|
2064
|
+
*
|
|
2065
|
+
* @example
|
|
2066
|
+
* ```ts
|
|
2067
|
+
* app.get('/about/me', (c) => {
|
|
2068
|
+
* const method = c.req.method // `GET`
|
|
2069
|
+
* })
|
|
2070
|
+
* ```
|
|
2071
|
+
*/
|
|
2072
|
+
get method() {
|
|
2073
|
+
return this.raw.method;
|
|
2074
|
+
}
|
|
2075
|
+
get [GET_MATCH_RESULT]() {
|
|
2076
|
+
return this.#matchResult;
|
|
2077
|
+
}
|
|
2078
|
+
/**
|
|
2079
|
+
* `.matchedRoutes()` can return a matched route in the handler
|
|
2080
|
+
*
|
|
2081
|
+
* @deprecated
|
|
2082
|
+
*
|
|
2083
|
+
* Use matchedRoutes helper defined in "hono/route" instead.
|
|
2084
|
+
*
|
|
2085
|
+
* @see {@link https://hono.dev/docs/api/request#matchedroutes}
|
|
2086
|
+
*
|
|
2087
|
+
* @example
|
|
2088
|
+
* ```ts
|
|
2089
|
+
* app.use('*', async function logger(c, next) {
|
|
2090
|
+
* await next()
|
|
2091
|
+
* c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
|
|
2092
|
+
* const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
|
|
2093
|
+
* console.log(
|
|
2094
|
+
* method,
|
|
2095
|
+
* ' ',
|
|
2096
|
+
* path,
|
|
2097
|
+
* ' '.repeat(Math.max(10 - path.length, 0)),
|
|
2098
|
+
* name,
|
|
2099
|
+
* i === c.req.routeIndex ? '<- respond from here' : ''
|
|
2100
|
+
* )
|
|
2101
|
+
* })
|
|
2102
|
+
* })
|
|
2103
|
+
* ```
|
|
2104
|
+
*/
|
|
2105
|
+
get matchedRoutes() {
|
|
2106
|
+
return this.#matchResult[0].map(([[, route]]) => route);
|
|
2107
|
+
}
|
|
2108
|
+
/**
|
|
2109
|
+
* `routePath()` can retrieve the path registered within the handler
|
|
2110
|
+
*
|
|
2111
|
+
* @deprecated
|
|
2112
|
+
*
|
|
2113
|
+
* Use routePath helper defined in "hono/route" instead.
|
|
2114
|
+
*
|
|
2115
|
+
* @see {@link https://hono.dev/docs/api/request#routepath}
|
|
2116
|
+
*
|
|
2117
|
+
* @example
|
|
2118
|
+
* ```ts
|
|
2119
|
+
* app.get('/posts/:id', (c) => {
|
|
2120
|
+
* return c.json({ path: c.req.routePath })
|
|
2121
|
+
* })
|
|
2122
|
+
* ```
|
|
2123
|
+
*/
|
|
2124
|
+
get routePath() {
|
|
2125
|
+
return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
|
|
2126
|
+
}
|
|
2127
|
+
};
|
|
2128
|
+
|
|
2129
|
+
// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/html.js
|
|
2130
|
+
var HtmlEscapedCallbackPhase = {
|
|
2131
|
+
Stringify: 1,
|
|
2132
|
+
BeforeStream: 2,
|
|
2133
|
+
Stream: 3
|
|
2134
|
+
};
|
|
2135
|
+
var raw = (value, callbacks) => {
|
|
2136
|
+
const escapedString = new String(value);
|
|
2137
|
+
escapedString.isEscaped = true;
|
|
2138
|
+
escapedString.callbacks = callbacks;
|
|
2139
|
+
return escapedString;
|
|
2140
|
+
};
|
|
2141
|
+
var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
|
|
2142
|
+
if (typeof str === "object" && !(str instanceof String)) {
|
|
2143
|
+
if (!(str instanceof Promise)) {
|
|
2144
|
+
str = str.toString();
|
|
2145
|
+
}
|
|
2146
|
+
if (str instanceof Promise) {
|
|
2147
|
+
str = await str;
|
|
2148
|
+
}
|
|
2149
|
+
}
|
|
2150
|
+
const callbacks = str.callbacks;
|
|
2151
|
+
if (!callbacks?.length) {
|
|
2152
|
+
return Promise.resolve(str);
|
|
2153
|
+
}
|
|
2154
|
+
if (buffer) {
|
|
2155
|
+
buffer[0] += str;
|
|
2156
|
+
} else {
|
|
2157
|
+
buffer = [str];
|
|
2158
|
+
}
|
|
2159
|
+
const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
|
|
2160
|
+
(res) => Promise.all(
|
|
2161
|
+
res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
|
|
2162
|
+
).then(() => buffer[0])
|
|
2163
|
+
);
|
|
2164
|
+
if (preserveCallbacks) {
|
|
2165
|
+
return raw(await resStr, callbacks);
|
|
2166
|
+
} else {
|
|
2167
|
+
return resStr;
|
|
2168
|
+
}
|
|
2169
|
+
};
|
|
2170
|
+
|
|
2171
|
+
// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/context.js
|
|
2172
|
+
var TEXT_PLAIN = "text/plain; charset=UTF-8";
|
|
2173
|
+
var setDefaultContentType = (contentType, headers) => {
|
|
2174
|
+
return {
|
|
2175
|
+
"Content-Type": contentType,
|
|
2176
|
+
...headers
|
|
2177
|
+
};
|
|
2178
|
+
};
|
|
2179
|
+
var createResponseInstance = (body, init) => new Response(body, init);
|
|
2180
|
+
var Context = class {
|
|
2181
|
+
#rawRequest;
|
|
2182
|
+
#req;
|
|
2183
|
+
/**
|
|
2184
|
+
* `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
|
|
2185
|
+
*
|
|
2186
|
+
* @see {@link https://hono.dev/docs/api/context#env}
|
|
2187
|
+
*
|
|
2188
|
+
* @example
|
|
2189
|
+
* ```ts
|
|
2190
|
+
* // Environment object for Cloudflare Workers
|
|
2191
|
+
* app.get('*', async c => {
|
|
2192
|
+
* const counter = c.env.COUNTER
|
|
2193
|
+
* })
|
|
2194
|
+
* ```
|
|
2195
|
+
*/
|
|
2196
|
+
env = {};
|
|
2197
|
+
#var;
|
|
2198
|
+
finalized = false;
|
|
2199
|
+
/**
|
|
2200
|
+
* `.error` can get the error object from the middleware if the Handler throws an error.
|
|
2201
|
+
*
|
|
2202
|
+
* @see {@link https://hono.dev/docs/api/context#error}
|
|
2203
|
+
*
|
|
2204
|
+
* @example
|
|
2205
|
+
* ```ts
|
|
2206
|
+
* app.use('*', async (c, next) => {
|
|
2207
|
+
* await next()
|
|
2208
|
+
* if (c.error) {
|
|
2209
|
+
* // do something...
|
|
2210
|
+
* }
|
|
2211
|
+
* })
|
|
2212
|
+
* ```
|
|
2213
|
+
*/
|
|
2214
|
+
error;
|
|
2215
|
+
#status;
|
|
2216
|
+
#executionCtx;
|
|
2217
|
+
#res;
|
|
2218
|
+
#layout;
|
|
2219
|
+
#renderer;
|
|
2220
|
+
#notFoundHandler;
|
|
2221
|
+
#preparedHeaders;
|
|
2222
|
+
#matchResult;
|
|
2223
|
+
#path;
|
|
2224
|
+
/**
|
|
2225
|
+
* Creates an instance of the Context class.
|
|
2226
|
+
*
|
|
2227
|
+
* @param req - The Request object.
|
|
2228
|
+
* @param options - Optional configuration options for the context.
|
|
2229
|
+
*/
|
|
2230
|
+
constructor(req, options) {
|
|
2231
|
+
this.#rawRequest = req;
|
|
2232
|
+
if (options) {
|
|
2233
|
+
this.#executionCtx = options.executionCtx;
|
|
2234
|
+
this.env = options.env;
|
|
2235
|
+
this.#notFoundHandler = options.notFoundHandler;
|
|
2236
|
+
this.#path = options.path;
|
|
2237
|
+
this.#matchResult = options.matchResult;
|
|
2238
|
+
}
|
|
2239
|
+
}
|
|
2240
|
+
/**
|
|
2241
|
+
* `.req` is the instance of {@link HonoRequest}.
|
|
2242
|
+
*/
|
|
2243
|
+
get req() {
|
|
2244
|
+
this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
|
|
2245
|
+
return this.#req;
|
|
2246
|
+
}
|
|
2247
|
+
/**
|
|
2248
|
+
* @see {@link https://hono.dev/docs/api/context#event}
|
|
2249
|
+
* The FetchEvent associated with the current request.
|
|
2250
|
+
*
|
|
2251
|
+
* @throws Will throw an error if the context does not have a FetchEvent.
|
|
2252
|
+
*/
|
|
2253
|
+
get event() {
|
|
2254
|
+
if (this.#executionCtx && "respondWith" in this.#executionCtx) {
|
|
2255
|
+
return this.#executionCtx;
|
|
2256
|
+
} else {
|
|
2257
|
+
throw Error("This context has no FetchEvent");
|
|
2258
|
+
}
|
|
2259
|
+
}
|
|
2260
|
+
/**
|
|
2261
|
+
* @see {@link https://hono.dev/docs/api/context#executionctx}
|
|
2262
|
+
* The ExecutionContext associated with the current request.
|
|
2263
|
+
*
|
|
2264
|
+
* @throws Will throw an error if the context does not have an ExecutionContext.
|
|
2265
|
+
*/
|
|
2266
|
+
get executionCtx() {
|
|
2267
|
+
if (this.#executionCtx) {
|
|
2268
|
+
return this.#executionCtx;
|
|
2269
|
+
} else {
|
|
2270
|
+
throw Error("This context has no ExecutionContext");
|
|
2271
|
+
}
|
|
2272
|
+
}
|
|
2273
|
+
/**
|
|
2274
|
+
* @see {@link https://hono.dev/docs/api/context#res}
|
|
2275
|
+
* The Response object for the current request.
|
|
2276
|
+
*/
|
|
2277
|
+
get res() {
|
|
2278
|
+
return this.#res ||= createResponseInstance(null, {
|
|
2279
|
+
headers: this.#preparedHeaders ??= new Headers()
|
|
2280
|
+
});
|
|
2281
|
+
}
|
|
2282
|
+
/**
|
|
2283
|
+
* Sets the Response object for the current request.
|
|
2284
|
+
*
|
|
2285
|
+
* @param _res - The Response object to set.
|
|
2286
|
+
*/
|
|
2287
|
+
set res(_res) {
|
|
2288
|
+
if (this.#res && _res) {
|
|
2289
|
+
_res = createResponseInstance(_res.body, _res);
|
|
2290
|
+
for (const [k, v] of this.#res.headers.entries()) {
|
|
2291
|
+
if (k === "content-type") {
|
|
2292
|
+
continue;
|
|
2293
|
+
}
|
|
2294
|
+
if (k === "set-cookie") {
|
|
2295
|
+
const cookies = this.#res.headers.getSetCookie();
|
|
2296
|
+
_res.headers.delete("set-cookie");
|
|
2297
|
+
for (const cookie of cookies) {
|
|
2298
|
+
_res.headers.append("set-cookie", cookie);
|
|
2299
|
+
}
|
|
2300
|
+
} else {
|
|
2301
|
+
_res.headers.set(k, v);
|
|
2302
|
+
}
|
|
2303
|
+
}
|
|
2304
|
+
}
|
|
2305
|
+
this.#res = _res;
|
|
2306
|
+
this.finalized = true;
|
|
2307
|
+
}
|
|
2308
|
+
/**
|
|
2309
|
+
* `.render()` can create a response within a layout.
|
|
2310
|
+
*
|
|
2311
|
+
* @see {@link https://hono.dev/docs/api/context#render-setrenderer}
|
|
2312
|
+
*
|
|
2313
|
+
* @example
|
|
2314
|
+
* ```ts
|
|
2315
|
+
* app.get('/', (c) => {
|
|
2316
|
+
* return c.render('Hello!')
|
|
2317
|
+
* })
|
|
2318
|
+
* ```
|
|
2319
|
+
*/
|
|
2320
|
+
render = (...args) => {
|
|
2321
|
+
this.#renderer ??= (content) => this.html(content);
|
|
2322
|
+
return this.#renderer(...args);
|
|
2323
|
+
};
|
|
2324
|
+
/**
|
|
2325
|
+
* Sets the layout for the response.
|
|
2326
|
+
*
|
|
2327
|
+
* @param layout - The layout to set.
|
|
2328
|
+
* @returns The layout function.
|
|
2329
|
+
*/
|
|
2330
|
+
setLayout = (layout) => this.#layout = layout;
|
|
2331
|
+
/**
|
|
2332
|
+
* Gets the current layout for the response.
|
|
2333
|
+
*
|
|
2334
|
+
* @returns The current layout function.
|
|
2335
|
+
*/
|
|
2336
|
+
getLayout = () => this.#layout;
|
|
2337
|
+
/**
|
|
2338
|
+
* `.setRenderer()` can set the layout in the custom middleware.
|
|
2339
|
+
*
|
|
2340
|
+
* @see {@link https://hono.dev/docs/api/context#render-setrenderer}
|
|
2341
|
+
*
|
|
2342
|
+
* @example
|
|
2343
|
+
* ```tsx
|
|
2344
|
+
* app.use('*', async (c, next) => {
|
|
2345
|
+
* c.setRenderer((content) => {
|
|
2346
|
+
* return c.html(
|
|
2347
|
+
* <html>
|
|
2348
|
+
* <body>
|
|
2349
|
+
* <p>{content}</p>
|
|
2350
|
+
* </body>
|
|
2351
|
+
* </html>
|
|
2352
|
+
* )
|
|
2353
|
+
* })
|
|
2354
|
+
* await next()
|
|
2355
|
+
* })
|
|
2356
|
+
* ```
|
|
2357
|
+
*/
|
|
2358
|
+
setRenderer = (renderer) => {
|
|
2359
|
+
this.#renderer = renderer;
|
|
2360
|
+
};
|
|
2361
|
+
/**
|
|
2362
|
+
* `.header()` can set headers.
|
|
2363
|
+
*
|
|
2364
|
+
* @see {@link https://hono.dev/docs/api/context#header}
|
|
2365
|
+
*
|
|
2366
|
+
* @example
|
|
2367
|
+
* ```ts
|
|
2368
|
+
* app.get('/welcome', (c) => {
|
|
2369
|
+
* // Set headers
|
|
2370
|
+
* c.header('X-Message', 'Hello!')
|
|
2371
|
+
* c.header('Content-Type', 'text/plain')
|
|
2372
|
+
*
|
|
2373
|
+
* return c.body('Thank you for coming')
|
|
2374
|
+
* })
|
|
2375
|
+
* ```
|
|
2376
|
+
*/
|
|
2377
|
+
header = (name, value, options) => {
|
|
2378
|
+
if (this.finalized) {
|
|
2379
|
+
this.#res = createResponseInstance(this.#res.body, this.#res);
|
|
2380
|
+
}
|
|
2381
|
+
const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
|
|
2382
|
+
if (value === void 0) {
|
|
2383
|
+
headers.delete(name);
|
|
2384
|
+
} else if (options?.append) {
|
|
2385
|
+
headers.append(name, value);
|
|
2386
|
+
} else {
|
|
2387
|
+
headers.set(name, value);
|
|
2388
|
+
}
|
|
2389
|
+
};
|
|
2390
|
+
status = (status) => {
|
|
2391
|
+
this.#status = status;
|
|
2392
|
+
};
|
|
2393
|
+
/**
|
|
2394
|
+
* `.set()` can set the value specified by the key.
|
|
2395
|
+
*
|
|
2396
|
+
* @see {@link https://hono.dev/docs/api/context#set-get}
|
|
2397
|
+
*
|
|
2398
|
+
* @example
|
|
2399
|
+
* ```ts
|
|
2400
|
+
* app.use('*', async (c, next) => {
|
|
2401
|
+
* c.set('message', 'Hono is hot!!')
|
|
2402
|
+
* await next()
|
|
2403
|
+
* })
|
|
2404
|
+
* ```
|
|
2405
|
+
*/
|
|
2406
|
+
set = (key, value) => {
|
|
2407
|
+
this.#var ??= /* @__PURE__ */ new Map();
|
|
2408
|
+
this.#var.set(key, value);
|
|
2409
|
+
};
|
|
2410
|
+
/**
|
|
2411
|
+
* `.get()` can use the value specified by the key.
|
|
2412
|
+
*
|
|
2413
|
+
* @see {@link https://hono.dev/docs/api/context#set-get}
|
|
2414
|
+
*
|
|
2415
|
+
* @example
|
|
2416
|
+
* ```ts
|
|
2417
|
+
* app.get('/', (c) => {
|
|
2418
|
+
* const message = c.get('message')
|
|
2419
|
+
* return c.text(`The message is "${message}"`)
|
|
2420
|
+
* })
|
|
2421
|
+
* ```
|
|
2422
|
+
*/
|
|
2423
|
+
get = (key) => {
|
|
2424
|
+
return this.#var ? this.#var.get(key) : void 0;
|
|
2425
|
+
};
|
|
2426
|
+
/**
|
|
2427
|
+
* `.var` can access the value of a variable.
|
|
2428
|
+
*
|
|
2429
|
+
* @see {@link https://hono.dev/docs/api/context#var}
|
|
2430
|
+
*
|
|
2431
|
+
* @example
|
|
2432
|
+
* ```ts
|
|
2433
|
+
* const result = c.var.client.oneMethod()
|
|
2434
|
+
* ```
|
|
2435
|
+
*/
|
|
2436
|
+
// c.var.propName is a read-only
|
|
2437
|
+
get var() {
|
|
2438
|
+
if (!this.#var) {
|
|
2439
|
+
return {};
|
|
2440
|
+
}
|
|
2441
|
+
return Object.fromEntries(this.#var);
|
|
2442
|
+
}
|
|
2443
|
+
#newResponse(data, arg, headers) {
|
|
2444
|
+
const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
|
|
2445
|
+
if (typeof arg === "object" && "headers" in arg) {
|
|
2446
|
+
const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
|
|
2447
|
+
for (const [key, value] of argHeaders) {
|
|
2448
|
+
if (key.toLowerCase() === "set-cookie") {
|
|
2449
|
+
responseHeaders.append(key, value);
|
|
2450
|
+
} else {
|
|
2451
|
+
responseHeaders.set(key, value);
|
|
2452
|
+
}
|
|
2453
|
+
}
|
|
2454
|
+
}
|
|
2455
|
+
if (headers) {
|
|
2456
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
2457
|
+
if (typeof v === "string") {
|
|
2458
|
+
responseHeaders.set(k, v);
|
|
2459
|
+
} else {
|
|
2460
|
+
responseHeaders.delete(k);
|
|
2461
|
+
for (const v2 of v) {
|
|
2462
|
+
responseHeaders.append(k, v2);
|
|
2463
|
+
}
|
|
2464
|
+
}
|
|
2465
|
+
}
|
|
2466
|
+
}
|
|
2467
|
+
const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
|
|
2468
|
+
return createResponseInstance(data, { status, headers: responseHeaders });
|
|
2469
|
+
}
|
|
2470
|
+
newResponse = (...args) => this.#newResponse(...args);
|
|
2471
|
+
/**
|
|
2472
|
+
* `.body()` can return the HTTP response.
|
|
2473
|
+
* You can set headers with `.header()` and set HTTP status code with `.status`.
|
|
2474
|
+
* This can also be set in `.text()`, `.json()` and so on.
|
|
2475
|
+
*
|
|
2476
|
+
* @see {@link https://hono.dev/docs/api/context#body}
|
|
2477
|
+
*
|
|
2478
|
+
* @example
|
|
2479
|
+
* ```ts
|
|
2480
|
+
* app.get('/welcome', (c) => {
|
|
2481
|
+
* // Set headers
|
|
2482
|
+
* c.header('X-Message', 'Hello!')
|
|
2483
|
+
* c.header('Content-Type', 'text/plain')
|
|
2484
|
+
* // Set HTTP status code
|
|
2485
|
+
* c.status(201)
|
|
2486
|
+
*
|
|
2487
|
+
* // Return the response body
|
|
2488
|
+
* return c.body('Thank you for coming')
|
|
2489
|
+
* })
|
|
2490
|
+
* ```
|
|
2491
|
+
*/
|
|
2492
|
+
body = (data, arg, headers) => this.#newResponse(data, arg, headers);
|
|
2493
|
+
/**
|
|
2494
|
+
* `.text()` can render text as `Content-Type:text/plain`.
|
|
2495
|
+
*
|
|
2496
|
+
* @see {@link https://hono.dev/docs/api/context#text}
|
|
2497
|
+
*
|
|
2498
|
+
* @example
|
|
2499
|
+
* ```ts
|
|
2500
|
+
* app.get('/say', (c) => {
|
|
2501
|
+
* return c.text('Hello!')
|
|
2502
|
+
* })
|
|
2503
|
+
* ```
|
|
2504
|
+
*/
|
|
2505
|
+
text = (text, arg, headers) => {
|
|
2506
|
+
return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
|
|
2507
|
+
text,
|
|
2508
|
+
arg,
|
|
2509
|
+
setDefaultContentType(TEXT_PLAIN, headers)
|
|
2510
|
+
);
|
|
2511
|
+
};
|
|
2512
|
+
/**
|
|
2513
|
+
* `.json()` can render JSON as `Content-Type:application/json`.
|
|
2514
|
+
*
|
|
2515
|
+
* @see {@link https://hono.dev/docs/api/context#json}
|
|
2516
|
+
*
|
|
2517
|
+
* @example
|
|
2518
|
+
* ```ts
|
|
2519
|
+
* app.get('/api', (c) => {
|
|
2520
|
+
* return c.json({ message: 'Hello!' })
|
|
2521
|
+
* })
|
|
2522
|
+
* ```
|
|
2523
|
+
*/
|
|
2524
|
+
json = (object, arg, headers) => {
|
|
2525
|
+
return this.#newResponse(
|
|
2526
|
+
JSON.stringify(object),
|
|
2527
|
+
arg,
|
|
2528
|
+
setDefaultContentType("application/json", headers)
|
|
2529
|
+
);
|
|
2530
|
+
};
|
|
2531
|
+
html = (html, arg, headers) => {
|
|
2532
|
+
const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
|
|
2533
|
+
return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
|
|
2534
|
+
};
|
|
2535
|
+
/**
|
|
2536
|
+
* `.redirect()` can Redirect, default status code is 302.
|
|
2537
|
+
*
|
|
2538
|
+
* @see {@link https://hono.dev/docs/api/context#redirect}
|
|
2539
|
+
*
|
|
2540
|
+
* @example
|
|
2541
|
+
* ```ts
|
|
2542
|
+
* app.get('/redirect', (c) => {
|
|
2543
|
+
* return c.redirect('/')
|
|
2544
|
+
* })
|
|
2545
|
+
* app.get('/redirect-permanently', (c) => {
|
|
2546
|
+
* return c.redirect('/', 301)
|
|
2547
|
+
* })
|
|
2548
|
+
* ```
|
|
2549
|
+
*/
|
|
2550
|
+
redirect = (location, status) => {
|
|
2551
|
+
const locationString = String(location);
|
|
2552
|
+
this.header(
|
|
2553
|
+
"Location",
|
|
2554
|
+
// Multibyes should be encoded
|
|
2555
|
+
// eslint-disable-next-line no-control-regex
|
|
2556
|
+
!/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
|
|
2557
|
+
);
|
|
2558
|
+
return this.newResponse(null, status ?? 302);
|
|
2559
|
+
};
|
|
2560
|
+
/**
|
|
2561
|
+
* `.notFound()` can return the Not Found Response.
|
|
2562
|
+
*
|
|
2563
|
+
* @see {@link https://hono.dev/docs/api/context#notfound}
|
|
2564
|
+
*
|
|
2565
|
+
* @example
|
|
2566
|
+
* ```ts
|
|
2567
|
+
* app.get('/notfound', (c) => {
|
|
2568
|
+
* return c.notFound()
|
|
2569
|
+
* })
|
|
2570
|
+
* ```
|
|
2571
|
+
*/
|
|
2572
|
+
notFound = () => {
|
|
2573
|
+
this.#notFoundHandler ??= () => createResponseInstance();
|
|
2574
|
+
return this.#notFoundHandler(this);
|
|
2575
|
+
};
|
|
2576
|
+
};
|
|
2577
|
+
|
|
2578
|
+
// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router.js
|
|
2579
|
+
var METHOD_NAME_ALL = "ALL";
|
|
2580
|
+
var METHOD_NAME_ALL_LOWERCASE = "all";
|
|
2581
|
+
var METHODS = ["get", "post", "put", "delete", "options", "patch"];
|
|
2582
|
+
var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
|
|
2583
|
+
var UnsupportedPathError = class extends Error {
|
|
2584
|
+
};
|
|
2585
|
+
|
|
2586
|
+
// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/constants.js
|
|
2587
|
+
var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
|
|
2588
|
+
|
|
2589
|
+
// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/hono-base.js
|
|
2590
|
+
var notFoundHandler = (c) => {
|
|
2591
|
+
return c.text("404 Not Found", 404);
|
|
2592
|
+
};
|
|
2593
|
+
var errorHandler = (err, c) => {
|
|
2594
|
+
if ("getResponse" in err) {
|
|
2595
|
+
const res = err.getResponse();
|
|
2596
|
+
return c.newResponse(res.body, res);
|
|
2597
|
+
}
|
|
2598
|
+
console.error(err);
|
|
2599
|
+
return c.text("Internal Server Error", 500);
|
|
2600
|
+
};
|
|
2601
|
+
var Hono = class _Hono {
|
|
2602
|
+
get;
|
|
2603
|
+
post;
|
|
2604
|
+
put;
|
|
2605
|
+
delete;
|
|
2606
|
+
options;
|
|
2607
|
+
patch;
|
|
2608
|
+
all;
|
|
2609
|
+
on;
|
|
2610
|
+
use;
|
|
2611
|
+
/*
|
|
2612
|
+
This class is like an abstract class and does not have a router.
|
|
2613
|
+
To use it, inherit the class and implement router in the constructor.
|
|
2614
|
+
*/
|
|
2615
|
+
router;
|
|
2616
|
+
getPath;
|
|
2617
|
+
// Cannot use `#` because it requires visibility at JavaScript runtime.
|
|
2618
|
+
_basePath = "/";
|
|
2619
|
+
#path = "/";
|
|
2620
|
+
routes = [];
|
|
2621
|
+
constructor(options = {}) {
|
|
2622
|
+
const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
|
|
2623
|
+
allMethods.forEach((method) => {
|
|
2624
|
+
this[method] = (args1, ...args) => {
|
|
2625
|
+
if (typeof args1 === "string") {
|
|
2626
|
+
this.#path = args1;
|
|
2627
|
+
} else {
|
|
2628
|
+
this.#addRoute(method, this.#path, args1);
|
|
2629
|
+
}
|
|
2630
|
+
args.forEach((handler) => {
|
|
2631
|
+
this.#addRoute(method, this.#path, handler);
|
|
2632
|
+
});
|
|
2633
|
+
return this;
|
|
2634
|
+
};
|
|
2635
|
+
});
|
|
2636
|
+
this.on = (method, path, ...handlers) => {
|
|
2637
|
+
for (const p of [path].flat()) {
|
|
2638
|
+
this.#path = p;
|
|
2639
|
+
for (const m of [method].flat()) {
|
|
2640
|
+
handlers.map((handler) => {
|
|
2641
|
+
this.#addRoute(m.toUpperCase(), this.#path, handler);
|
|
2642
|
+
});
|
|
2643
|
+
}
|
|
2644
|
+
}
|
|
2645
|
+
return this;
|
|
2646
|
+
};
|
|
2647
|
+
this.use = (arg1, ...handlers) => {
|
|
2648
|
+
if (typeof arg1 === "string") {
|
|
2649
|
+
this.#path = arg1;
|
|
2650
|
+
} else {
|
|
2651
|
+
this.#path = "*";
|
|
2652
|
+
handlers.unshift(arg1);
|
|
2653
|
+
}
|
|
2654
|
+
handlers.forEach((handler) => {
|
|
2655
|
+
this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
|
|
2656
|
+
});
|
|
2657
|
+
return this;
|
|
2658
|
+
};
|
|
2659
|
+
const { strict, ...optionsWithoutStrict } = options;
|
|
2660
|
+
Object.assign(this, optionsWithoutStrict);
|
|
2661
|
+
this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
|
|
2662
|
+
}
|
|
2663
|
+
#clone() {
|
|
2664
|
+
const clone = new _Hono({
|
|
2665
|
+
router: this.router,
|
|
2666
|
+
getPath: this.getPath
|
|
2667
|
+
});
|
|
2668
|
+
clone.errorHandler = this.errorHandler;
|
|
2669
|
+
clone.#notFoundHandler = this.#notFoundHandler;
|
|
2670
|
+
clone.routes = this.routes;
|
|
2671
|
+
return clone;
|
|
2672
|
+
}
|
|
2673
|
+
#notFoundHandler = notFoundHandler;
|
|
2674
|
+
// Cannot use `#` because it requires visibility at JavaScript runtime.
|
|
2675
|
+
errorHandler = errorHandler;
|
|
2676
|
+
/**
|
|
2677
|
+
* `.route()` allows grouping other Hono instance in routes.
|
|
2678
|
+
*
|
|
2679
|
+
* @see {@link https://hono.dev/docs/api/routing#grouping}
|
|
2680
|
+
*
|
|
2681
|
+
* @param {string} path - base Path
|
|
2682
|
+
* @param {Hono} app - other Hono instance
|
|
2683
|
+
* @returns {Hono} routed Hono instance
|
|
2684
|
+
*
|
|
2685
|
+
* @example
|
|
2686
|
+
* ```ts
|
|
2687
|
+
* const app = new Hono()
|
|
2688
|
+
* const app2 = new Hono()
|
|
2689
|
+
*
|
|
2690
|
+
* app2.get("/user", (c) => c.text("user"))
|
|
2691
|
+
* app.route("/api", app2) // GET /api/user
|
|
2692
|
+
* ```
|
|
2693
|
+
*/
|
|
2694
|
+
route(path, app) {
|
|
2695
|
+
const subApp = this.basePath(path);
|
|
2696
|
+
app.routes.map((r) => {
|
|
2697
|
+
let handler;
|
|
2698
|
+
if (app.errorHandler === errorHandler) {
|
|
2699
|
+
handler = r.handler;
|
|
2700
|
+
} else {
|
|
2701
|
+
handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
|
|
2702
|
+
handler[COMPOSED_HANDLER] = r.handler;
|
|
2703
|
+
}
|
|
2704
|
+
subApp.#addRoute(r.method, r.path, handler, r.basePath);
|
|
2705
|
+
});
|
|
2706
|
+
return this;
|
|
2707
|
+
}
|
|
2708
|
+
/**
|
|
2709
|
+
* `.basePath()` allows base paths to be specified.
|
|
2710
|
+
*
|
|
2711
|
+
* @see {@link https://hono.dev/docs/api/routing#base-path}
|
|
2712
|
+
*
|
|
2713
|
+
* @param {string} path - base Path
|
|
2714
|
+
* @returns {Hono} changed Hono instance
|
|
2715
|
+
*
|
|
2716
|
+
* @example
|
|
2717
|
+
* ```ts
|
|
2718
|
+
* const api = new Hono().basePath('/api')
|
|
2719
|
+
* ```
|
|
2720
|
+
*/
|
|
2721
|
+
basePath(path) {
|
|
2722
|
+
const subApp = this.#clone();
|
|
2723
|
+
subApp._basePath = mergePath(this._basePath, path);
|
|
2724
|
+
return subApp;
|
|
2725
|
+
}
|
|
2726
|
+
/**
|
|
2727
|
+
* `.onError()` handles an error and returns a customized Response.
|
|
2728
|
+
*
|
|
2729
|
+
* @see {@link https://hono.dev/docs/api/hono#error-handling}
|
|
2730
|
+
*
|
|
2731
|
+
* @param {ErrorHandler} handler - request Handler for error
|
|
2732
|
+
* @returns {Hono} changed Hono instance
|
|
2733
|
+
*
|
|
2734
|
+
* @example
|
|
2735
|
+
* ```ts
|
|
2736
|
+
* app.onError((err, c) => {
|
|
2737
|
+
* console.error(`${err}`)
|
|
2738
|
+
* return c.text('Custom Error Message', 500)
|
|
2739
|
+
* })
|
|
2740
|
+
* ```
|
|
2741
|
+
*/
|
|
2742
|
+
onError = (handler) => {
|
|
2743
|
+
this.errorHandler = handler;
|
|
2744
|
+
return this;
|
|
2745
|
+
};
|
|
2746
|
+
/**
|
|
2747
|
+
* `.notFound()` allows you to customize a Not Found Response.
|
|
2748
|
+
*
|
|
2749
|
+
* @see {@link https://hono.dev/docs/api/hono#not-found}
|
|
2750
|
+
*
|
|
2751
|
+
* @param {NotFoundHandler} handler - request handler for not-found
|
|
2752
|
+
* @returns {Hono} changed Hono instance
|
|
2753
|
+
*
|
|
2754
|
+
* @example
|
|
2755
|
+
* ```ts
|
|
2756
|
+
* app.notFound((c) => {
|
|
2757
|
+
* return c.text('Custom 404 Message', 404)
|
|
2758
|
+
* })
|
|
2759
|
+
* ```
|
|
2760
|
+
*/
|
|
2761
|
+
notFound = (handler) => {
|
|
2762
|
+
this.#notFoundHandler = handler;
|
|
2763
|
+
return this;
|
|
2764
|
+
};
|
|
2765
|
+
/**
|
|
2766
|
+
* `.mount()` allows you to mount applications built with other frameworks into your Hono application.
|
|
2767
|
+
*
|
|
2768
|
+
* @see {@link https://hono.dev/docs/api/hono#mount}
|
|
2769
|
+
*
|
|
2770
|
+
* @param {string} path - base Path
|
|
2771
|
+
* @param {Function} applicationHandler - other Request Handler
|
|
2772
|
+
* @param {MountOptions} [options] - options of `.mount()`
|
|
2773
|
+
* @returns {Hono} mounted Hono instance
|
|
2774
|
+
*
|
|
2775
|
+
* @example
|
|
2776
|
+
* ```ts
|
|
2777
|
+
* import { Router as IttyRouter } from 'itty-router'
|
|
2778
|
+
* import { Hono } from 'hono'
|
|
2779
|
+
* // Create itty-router application
|
|
2780
|
+
* const ittyRouter = IttyRouter()
|
|
2781
|
+
* // GET /itty-router/hello
|
|
2782
|
+
* ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
|
|
2783
|
+
*
|
|
2784
|
+
* const app = new Hono()
|
|
2785
|
+
* app.mount('/itty-router', ittyRouter.handle)
|
|
2786
|
+
* ```
|
|
2787
|
+
*
|
|
2788
|
+
* @example
|
|
2789
|
+
* ```ts
|
|
2790
|
+
* const app = new Hono()
|
|
2791
|
+
* // Send the request to another application without modification.
|
|
2792
|
+
* app.mount('/app', anotherApp, {
|
|
2793
|
+
* replaceRequest: (req) => req,
|
|
2794
|
+
* })
|
|
2795
|
+
* ```
|
|
2796
|
+
*/
|
|
2797
|
+
mount(path, applicationHandler, options) {
|
|
2798
|
+
let replaceRequest;
|
|
2799
|
+
let optionHandler;
|
|
2800
|
+
if (options) {
|
|
2801
|
+
if (typeof options === "function") {
|
|
2802
|
+
optionHandler = options;
|
|
2803
|
+
} else {
|
|
2804
|
+
optionHandler = options.optionHandler;
|
|
2805
|
+
if (options.replaceRequest === false) {
|
|
2806
|
+
replaceRequest = (request) => request;
|
|
2807
|
+
} else {
|
|
2808
|
+
replaceRequest = options.replaceRequest;
|
|
2809
|
+
}
|
|
2810
|
+
}
|
|
2811
|
+
}
|
|
2812
|
+
const getOptions = optionHandler ? (c) => {
|
|
2813
|
+
const options2 = optionHandler(c);
|
|
2814
|
+
return Array.isArray(options2) ? options2 : [options2];
|
|
2815
|
+
} : (c) => {
|
|
2816
|
+
let executionContext = void 0;
|
|
2817
|
+
try {
|
|
2818
|
+
executionContext = c.executionCtx;
|
|
2819
|
+
} catch {
|
|
2820
|
+
}
|
|
2821
|
+
return [c.env, executionContext];
|
|
2822
|
+
};
|
|
2823
|
+
replaceRequest ||= (() => {
|
|
2824
|
+
const mergedPath = mergePath(this._basePath, path);
|
|
2825
|
+
const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
|
|
2826
|
+
return (request) => {
|
|
2827
|
+
const url = new URL(request.url);
|
|
2828
|
+
url.pathname = this.getPath(request).slice(pathPrefixLength) || "/";
|
|
2829
|
+
return new Request(url, request);
|
|
2830
|
+
};
|
|
2831
|
+
})();
|
|
2832
|
+
const handler = async (c, next) => {
|
|
2833
|
+
const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
|
|
2834
|
+
if (res) {
|
|
2835
|
+
return res;
|
|
2836
|
+
}
|
|
2837
|
+
await next();
|
|
2838
|
+
};
|
|
2839
|
+
this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
|
|
2840
|
+
return this;
|
|
2841
|
+
}
|
|
2842
|
+
#addRoute(method, path, handler, baseRoutePath) {
|
|
2843
|
+
method = method.toUpperCase();
|
|
2844
|
+
path = mergePath(this._basePath, path);
|
|
2845
|
+
const r = {
|
|
2846
|
+
basePath: baseRoutePath !== void 0 ? mergePath(this._basePath, baseRoutePath) : this._basePath,
|
|
2847
|
+
path,
|
|
2848
|
+
method,
|
|
2849
|
+
handler
|
|
2850
|
+
};
|
|
2851
|
+
this.router.add(method, path, [handler, r]);
|
|
2852
|
+
this.routes.push(r);
|
|
2853
|
+
}
|
|
2854
|
+
#handleError(err, c) {
|
|
2855
|
+
if (err instanceof Error) {
|
|
2856
|
+
return this.errorHandler(err, c);
|
|
2857
|
+
}
|
|
2858
|
+
throw err;
|
|
2859
|
+
}
|
|
2860
|
+
#dispatch(request, executionCtx, env, method) {
|
|
2861
|
+
if (method === "HEAD") {
|
|
2862
|
+
return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
|
|
2863
|
+
}
|
|
2864
|
+
const path = this.getPath(request, { env });
|
|
2865
|
+
const matchResult = this.router.match(method, path);
|
|
2866
|
+
const c = new Context(request, {
|
|
2867
|
+
path,
|
|
2868
|
+
matchResult,
|
|
2869
|
+
env,
|
|
2870
|
+
executionCtx,
|
|
2871
|
+
notFoundHandler: this.#notFoundHandler
|
|
2872
|
+
});
|
|
2873
|
+
if (matchResult[0].length === 1) {
|
|
2874
|
+
let res;
|
|
2875
|
+
try {
|
|
2876
|
+
res = matchResult[0][0][0][0](c, async () => {
|
|
2877
|
+
c.res = await this.#notFoundHandler(c);
|
|
2878
|
+
});
|
|
2879
|
+
} catch (err) {
|
|
2880
|
+
return this.#handleError(err, c);
|
|
2881
|
+
}
|
|
2882
|
+
return res instanceof Promise ? res.then(
|
|
2883
|
+
(resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
|
|
2884
|
+
).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
|
|
2885
|
+
}
|
|
2886
|
+
const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
|
|
2887
|
+
return (async () => {
|
|
2888
|
+
try {
|
|
2889
|
+
const context = await composed(c);
|
|
2890
|
+
if (!context.finalized) {
|
|
2891
|
+
throw new Error(
|
|
2892
|
+
"Context is not finalized. Did you forget to return a Response object or `await next()`?"
|
|
2893
|
+
);
|
|
2894
|
+
}
|
|
2895
|
+
return context.res;
|
|
2896
|
+
} catch (err) {
|
|
2897
|
+
return this.#handleError(err, c);
|
|
2898
|
+
}
|
|
2899
|
+
})();
|
|
2900
|
+
}
|
|
2901
|
+
/**
|
|
2902
|
+
* `.fetch()` will be entry point of your app.
|
|
2903
|
+
*
|
|
2904
|
+
* @see {@link https://hono.dev/docs/api/hono#fetch}
|
|
2905
|
+
*
|
|
2906
|
+
* @param {Request} request - request Object of request
|
|
2907
|
+
* @param {Env} Env - env Object
|
|
2908
|
+
* @param {ExecutionContext} - context of execution
|
|
2909
|
+
* @returns {Response | Promise<Response>} response of request
|
|
2910
|
+
*
|
|
2911
|
+
*/
|
|
2912
|
+
fetch = (request, ...rest) => {
|
|
2913
|
+
return this.#dispatch(request, rest[1], rest[0], request.method);
|
|
2914
|
+
};
|
|
2915
|
+
/**
|
|
2916
|
+
* `.request()` is a useful method for testing.
|
|
2917
|
+
* You can pass a URL or pathname to send a GET request.
|
|
2918
|
+
* app will return a Response object.
|
|
2919
|
+
* ```ts
|
|
2920
|
+
* test('GET /hello is ok', async () => {
|
|
2921
|
+
* const res = await app.request('/hello')
|
|
2922
|
+
* expect(res.status).toBe(200)
|
|
2923
|
+
* })
|
|
2924
|
+
* ```
|
|
2925
|
+
* @see https://hono.dev/docs/api/hono#request
|
|
2926
|
+
*/
|
|
2927
|
+
request = (input, requestInit, Env, executionCtx) => {
|
|
2928
|
+
if (input instanceof Request) {
|
|
2929
|
+
return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
|
|
2930
|
+
}
|
|
2931
|
+
input = input.toString();
|
|
2932
|
+
return this.fetch(
|
|
2933
|
+
new Request(
|
|
2934
|
+
/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
|
|
2935
|
+
requestInit
|
|
2936
|
+
),
|
|
2937
|
+
Env,
|
|
2938
|
+
executionCtx
|
|
2939
|
+
);
|
|
2940
|
+
};
|
|
2941
|
+
/**
|
|
2942
|
+
* `.fire()` automatically adds a global fetch event listener.
|
|
2943
|
+
* This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
|
|
2944
|
+
* @deprecated
|
|
2945
|
+
* Use `fire` from `hono/service-worker` instead.
|
|
2946
|
+
* ```ts
|
|
2947
|
+
* import { Hono } from 'hono'
|
|
2948
|
+
* import { fire } from 'hono/service-worker'
|
|
2949
|
+
*
|
|
2950
|
+
* const app = new Hono()
|
|
2951
|
+
* // ...
|
|
2952
|
+
* fire(app)
|
|
2953
|
+
* ```
|
|
2954
|
+
* @see https://hono.dev/docs/api/hono#fire
|
|
2955
|
+
* @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
|
|
2956
|
+
* @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
|
|
2957
|
+
*/
|
|
2958
|
+
fire = () => {
|
|
2959
|
+
addEventListener("fetch", (event) => {
|
|
2960
|
+
event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
|
|
2961
|
+
});
|
|
2962
|
+
};
|
|
2963
|
+
};
|
|
2964
|
+
|
|
2965
|
+
// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/reg-exp-router/matcher.js
|
|
2966
|
+
var emptyParam = [];
|
|
2967
|
+
function match(method, path) {
|
|
2968
|
+
const matchers = this.buildAllMatchers();
|
|
2969
|
+
const match2 = ((method2, path2) => {
|
|
2970
|
+
const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
|
|
2971
|
+
const staticMatch = matcher[2][path2];
|
|
2972
|
+
if (staticMatch) {
|
|
2973
|
+
return staticMatch;
|
|
2974
|
+
}
|
|
2975
|
+
const match3 = path2.match(matcher[0]);
|
|
2976
|
+
if (!match3) {
|
|
2977
|
+
return [[], emptyParam];
|
|
2978
|
+
}
|
|
2979
|
+
const index = match3.indexOf("", 1);
|
|
2980
|
+
return [matcher[1][index], match3];
|
|
2981
|
+
});
|
|
2982
|
+
this.match = match2;
|
|
2983
|
+
return match2(method, path);
|
|
2984
|
+
}
|
|
2985
|
+
|
|
2986
|
+
// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/reg-exp-router/node.js
|
|
2987
|
+
var LABEL_REG_EXP_STR = "[^/]+";
|
|
2988
|
+
var ONLY_WILDCARD_REG_EXP_STR = ".*";
|
|
2989
|
+
var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
|
|
2990
|
+
var PATH_ERROR = /* @__PURE__ */ Symbol();
|
|
2991
|
+
var regExpMetaChars = new Set(".\\+*[^]$()");
|
|
2992
|
+
function compareKey(a, b) {
|
|
2993
|
+
if (a.length === 1) {
|
|
2994
|
+
return b.length === 1 ? a < b ? -1 : 1 : -1;
|
|
2995
|
+
}
|
|
2996
|
+
if (b.length === 1) {
|
|
2997
|
+
return 1;
|
|
2998
|
+
}
|
|
2999
|
+
if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
|
|
3000
|
+
return 1;
|
|
3001
|
+
} else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
|
|
3002
|
+
return -1;
|
|
3003
|
+
}
|
|
3004
|
+
if (a === LABEL_REG_EXP_STR) {
|
|
3005
|
+
return 1;
|
|
3006
|
+
} else if (b === LABEL_REG_EXP_STR) {
|
|
3007
|
+
return -1;
|
|
3008
|
+
}
|
|
3009
|
+
return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
|
|
3010
|
+
}
|
|
3011
|
+
var Node = class _Node {
|
|
3012
|
+
#index;
|
|
3013
|
+
#varIndex;
|
|
3014
|
+
#children = /* @__PURE__ */ Object.create(null);
|
|
3015
|
+
insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
|
|
3016
|
+
if (tokens.length === 0) {
|
|
3017
|
+
if (this.#index !== void 0) {
|
|
3018
|
+
throw PATH_ERROR;
|
|
3019
|
+
}
|
|
3020
|
+
if (pathErrorCheckOnly) {
|
|
3021
|
+
return;
|
|
3022
|
+
}
|
|
3023
|
+
this.#index = index;
|
|
3024
|
+
return;
|
|
3025
|
+
}
|
|
3026
|
+
const [token, ...restTokens] = tokens;
|
|
3027
|
+
const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
3028
|
+
let node;
|
|
3029
|
+
if (pattern) {
|
|
3030
|
+
const name = pattern[1];
|
|
3031
|
+
let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
|
|
3032
|
+
if (name && pattern[2]) {
|
|
3033
|
+
if (regexpStr === ".*") {
|
|
3034
|
+
throw PATH_ERROR;
|
|
3035
|
+
}
|
|
3036
|
+
regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
|
|
3037
|
+
if (/\((?!\?:)/.test(regexpStr)) {
|
|
3038
|
+
throw PATH_ERROR;
|
|
3039
|
+
}
|
|
3040
|
+
}
|
|
3041
|
+
node = this.#children[regexpStr];
|
|
3042
|
+
if (!node) {
|
|
3043
|
+
if (Object.keys(this.#children).some(
|
|
3044
|
+
(k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
|
|
3045
|
+
)) {
|
|
3046
|
+
throw PATH_ERROR;
|
|
3047
|
+
}
|
|
3048
|
+
if (pathErrorCheckOnly) {
|
|
3049
|
+
return;
|
|
3050
|
+
}
|
|
3051
|
+
node = this.#children[regexpStr] = new _Node();
|
|
3052
|
+
if (name !== "") {
|
|
3053
|
+
node.#varIndex = context.varIndex++;
|
|
3054
|
+
}
|
|
3055
|
+
}
|
|
3056
|
+
if (!pathErrorCheckOnly && name !== "") {
|
|
3057
|
+
paramMap.push([name, node.#varIndex]);
|
|
3058
|
+
}
|
|
3059
|
+
} else {
|
|
3060
|
+
node = this.#children[token];
|
|
3061
|
+
if (!node) {
|
|
3062
|
+
if (Object.keys(this.#children).some(
|
|
3063
|
+
(k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
|
|
3064
|
+
)) {
|
|
3065
|
+
throw PATH_ERROR;
|
|
3066
|
+
}
|
|
3067
|
+
if (pathErrorCheckOnly) {
|
|
3068
|
+
return;
|
|
3069
|
+
}
|
|
3070
|
+
node = this.#children[token] = new _Node();
|
|
3071
|
+
}
|
|
3072
|
+
}
|
|
3073
|
+
node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
|
|
3074
|
+
}
|
|
3075
|
+
buildRegExpStr() {
|
|
3076
|
+
const childKeys = Object.keys(this.#children).sort(compareKey);
|
|
3077
|
+
const strList = childKeys.map((k) => {
|
|
3078
|
+
const c = this.#children[k];
|
|
3079
|
+
return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
|
|
3080
|
+
});
|
|
3081
|
+
if (typeof this.#index === "number") {
|
|
3082
|
+
strList.unshift(`#${this.#index}`);
|
|
3083
|
+
}
|
|
3084
|
+
if (strList.length === 0) {
|
|
3085
|
+
return "";
|
|
3086
|
+
}
|
|
3087
|
+
if (strList.length === 1) {
|
|
3088
|
+
return strList[0];
|
|
3089
|
+
}
|
|
3090
|
+
return "(?:" + strList.join("|") + ")";
|
|
3091
|
+
}
|
|
3092
|
+
};
|
|
3093
|
+
|
|
3094
|
+
// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/reg-exp-router/trie.js
|
|
3095
|
+
var Trie = class {
|
|
3096
|
+
#context = { varIndex: 0 };
|
|
3097
|
+
#root = new Node();
|
|
3098
|
+
insert(path, index, pathErrorCheckOnly) {
|
|
3099
|
+
const paramAssoc = [];
|
|
3100
|
+
const groups = [];
|
|
3101
|
+
for (let i = 0; ; ) {
|
|
3102
|
+
let replaced = false;
|
|
3103
|
+
path = path.replace(/\{[^}]+\}/g, (m) => {
|
|
3104
|
+
const mark = `@\\${i}`;
|
|
3105
|
+
groups[i] = [mark, m];
|
|
3106
|
+
i++;
|
|
3107
|
+
replaced = true;
|
|
3108
|
+
return mark;
|
|
3109
|
+
});
|
|
3110
|
+
if (!replaced) {
|
|
3111
|
+
break;
|
|
3112
|
+
}
|
|
3113
|
+
}
|
|
3114
|
+
const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
|
|
3115
|
+
for (let i = groups.length - 1; i >= 0; i--) {
|
|
3116
|
+
const [mark] = groups[i];
|
|
3117
|
+
for (let j = tokens.length - 1; j >= 0; j--) {
|
|
3118
|
+
if (tokens[j].indexOf(mark) !== -1) {
|
|
3119
|
+
tokens[j] = tokens[j].replace(mark, groups[i][1]);
|
|
3120
|
+
break;
|
|
3121
|
+
}
|
|
3122
|
+
}
|
|
3123
|
+
}
|
|
3124
|
+
this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
|
|
3125
|
+
return paramAssoc;
|
|
3126
|
+
}
|
|
3127
|
+
buildRegExp() {
|
|
3128
|
+
let regexp = this.#root.buildRegExpStr();
|
|
3129
|
+
if (regexp === "") {
|
|
3130
|
+
return [/^$/, [], []];
|
|
3131
|
+
}
|
|
3132
|
+
let captureIndex = 0;
|
|
3133
|
+
const indexReplacementMap = [];
|
|
3134
|
+
const paramReplacementMap = [];
|
|
3135
|
+
regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
|
|
3136
|
+
if (handlerIndex !== void 0) {
|
|
3137
|
+
indexReplacementMap[++captureIndex] = Number(handlerIndex);
|
|
3138
|
+
return "$()";
|
|
3139
|
+
}
|
|
3140
|
+
if (paramIndex !== void 0) {
|
|
3141
|
+
paramReplacementMap[Number(paramIndex)] = ++captureIndex;
|
|
3142
|
+
return "";
|
|
3143
|
+
}
|
|
3144
|
+
return "";
|
|
3145
|
+
});
|
|
3146
|
+
return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
|
|
3147
|
+
}
|
|
3148
|
+
};
|
|
3149
|
+
|
|
3150
|
+
// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/reg-exp-router/router.js
|
|
3151
|
+
var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
|
|
3152
|
+
var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
3153
|
+
function buildWildcardRegExp(path) {
|
|
3154
|
+
return wildcardRegExpCache[path] ??= new RegExp(
|
|
3155
|
+
path === "*" ? "" : `^${path.replace(
|
|
3156
|
+
/\/\*$|([.\\+*[^\]$()])/g,
|
|
3157
|
+
(_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
|
|
3158
|
+
)}$`
|
|
3159
|
+
);
|
|
3160
|
+
}
|
|
3161
|
+
function clearWildcardRegExpCache() {
|
|
3162
|
+
wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
3163
|
+
}
|
|
3164
|
+
function buildMatcherFromPreprocessedRoutes(routes) {
|
|
3165
|
+
const trie = new Trie();
|
|
3166
|
+
const handlerData = [];
|
|
3167
|
+
if (routes.length === 0) {
|
|
3168
|
+
return nullMatcher;
|
|
3169
|
+
}
|
|
3170
|
+
const routesWithStaticPathFlag = routes.map(
|
|
3171
|
+
(route) => [!/\*|\/:/.test(route[0]), ...route]
|
|
3172
|
+
).sort(
|
|
3173
|
+
([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
|
|
3174
|
+
);
|
|
3175
|
+
const staticMap = /* @__PURE__ */ Object.create(null);
|
|
3176
|
+
for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
|
|
3177
|
+
const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
|
|
3178
|
+
if (pathErrorCheckOnly) {
|
|
3179
|
+
staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
|
|
3180
|
+
} else {
|
|
3181
|
+
j++;
|
|
3182
|
+
}
|
|
3183
|
+
let paramAssoc;
|
|
3184
|
+
try {
|
|
3185
|
+
paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
|
|
3186
|
+
} catch (e) {
|
|
3187
|
+
throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
|
|
3188
|
+
}
|
|
3189
|
+
if (pathErrorCheckOnly) {
|
|
3190
|
+
continue;
|
|
3191
|
+
}
|
|
3192
|
+
handlerData[j] = handlers.map(([h, paramCount]) => {
|
|
3193
|
+
const paramIndexMap = /* @__PURE__ */ Object.create(null);
|
|
3194
|
+
paramCount -= 1;
|
|
3195
|
+
for (; paramCount >= 0; paramCount--) {
|
|
3196
|
+
const [key, value] = paramAssoc[paramCount];
|
|
3197
|
+
paramIndexMap[key] = value;
|
|
3198
|
+
}
|
|
3199
|
+
return [h, paramIndexMap];
|
|
3200
|
+
});
|
|
3201
|
+
}
|
|
3202
|
+
const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
|
|
3203
|
+
for (let i = 0, len = handlerData.length; i < len; i++) {
|
|
3204
|
+
for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
|
|
3205
|
+
const map = handlerData[i][j]?.[1];
|
|
3206
|
+
if (!map) {
|
|
3207
|
+
continue;
|
|
3208
|
+
}
|
|
3209
|
+
const keys = Object.keys(map);
|
|
3210
|
+
for (let k = 0, len3 = keys.length; k < len3; k++) {
|
|
3211
|
+
map[keys[k]] = paramReplacementMap[map[keys[k]]];
|
|
3212
|
+
}
|
|
3213
|
+
}
|
|
3214
|
+
}
|
|
3215
|
+
const handlerMap = [];
|
|
3216
|
+
for (const i in indexReplacementMap) {
|
|
3217
|
+
handlerMap[i] = handlerData[indexReplacementMap[i]];
|
|
3218
|
+
}
|
|
3219
|
+
return [regexp, handlerMap, staticMap];
|
|
3220
|
+
}
|
|
3221
|
+
function findMiddleware(middleware, path) {
|
|
3222
|
+
if (!middleware) {
|
|
3223
|
+
return void 0;
|
|
3224
|
+
}
|
|
3225
|
+
for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
|
|
3226
|
+
if (buildWildcardRegExp(k).test(path)) {
|
|
3227
|
+
return [...middleware[k]];
|
|
3228
|
+
}
|
|
3229
|
+
}
|
|
3230
|
+
return void 0;
|
|
3231
|
+
}
|
|
3232
|
+
var RegExpRouter = class {
|
|
3233
|
+
name = "RegExpRouter";
|
|
3234
|
+
#middleware;
|
|
3235
|
+
#routes;
|
|
3236
|
+
constructor() {
|
|
3237
|
+
this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
|
|
3238
|
+
this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
|
|
3239
|
+
}
|
|
3240
|
+
add(method, path, handler) {
|
|
3241
|
+
const middleware = this.#middleware;
|
|
3242
|
+
const routes = this.#routes;
|
|
3243
|
+
if (!middleware || !routes) {
|
|
3244
|
+
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
3245
|
+
}
|
|
3246
|
+
if (!middleware[method]) {
|
|
3247
|
+
;
|
|
3248
|
+
[middleware, routes].forEach((handlerMap) => {
|
|
3249
|
+
handlerMap[method] = /* @__PURE__ */ Object.create(null);
|
|
3250
|
+
Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
|
|
3251
|
+
handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
|
|
3252
|
+
});
|
|
3253
|
+
});
|
|
3254
|
+
}
|
|
3255
|
+
if (path === "/*") {
|
|
3256
|
+
path = "*";
|
|
3257
|
+
}
|
|
3258
|
+
const paramCount = (path.match(/\/:/g) || []).length;
|
|
3259
|
+
if (/\*$/.test(path)) {
|
|
3260
|
+
const re = buildWildcardRegExp(path);
|
|
3261
|
+
if (method === METHOD_NAME_ALL) {
|
|
3262
|
+
Object.keys(middleware).forEach((m) => {
|
|
3263
|
+
middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
|
|
3264
|
+
});
|
|
3265
|
+
} else {
|
|
3266
|
+
middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
|
|
3267
|
+
}
|
|
3268
|
+
Object.keys(middleware).forEach((m) => {
|
|
3269
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
3270
|
+
Object.keys(middleware[m]).forEach((p) => {
|
|
3271
|
+
re.test(p) && middleware[m][p].push([handler, paramCount]);
|
|
3272
|
+
});
|
|
3273
|
+
}
|
|
3274
|
+
});
|
|
3275
|
+
Object.keys(routes).forEach((m) => {
|
|
3276
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
3277
|
+
Object.keys(routes[m]).forEach(
|
|
3278
|
+
(p) => re.test(p) && routes[m][p].push([handler, paramCount])
|
|
3279
|
+
);
|
|
3280
|
+
}
|
|
3281
|
+
});
|
|
3282
|
+
return;
|
|
3283
|
+
}
|
|
3284
|
+
const paths = checkOptionalParameter(path) || [path];
|
|
3285
|
+
for (let i = 0, len = paths.length; i < len; i++) {
|
|
3286
|
+
const path2 = paths[i];
|
|
3287
|
+
Object.keys(routes).forEach((m) => {
|
|
3288
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
3289
|
+
routes[m][path2] ||= [
|
|
3290
|
+
...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
|
|
3291
|
+
];
|
|
3292
|
+
routes[m][path2].push([handler, paramCount - len + i + 1]);
|
|
3293
|
+
}
|
|
3294
|
+
});
|
|
3295
|
+
}
|
|
3296
|
+
}
|
|
3297
|
+
match = match;
|
|
3298
|
+
buildAllMatchers() {
|
|
3299
|
+
const matchers = /* @__PURE__ */ Object.create(null);
|
|
3300
|
+
Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
|
|
3301
|
+
matchers[method] ||= this.#buildMatcher(method);
|
|
3302
|
+
});
|
|
3303
|
+
this.#middleware = this.#routes = void 0;
|
|
3304
|
+
clearWildcardRegExpCache();
|
|
3305
|
+
return matchers;
|
|
3306
|
+
}
|
|
3307
|
+
#buildMatcher(method) {
|
|
3308
|
+
const routes = [];
|
|
3309
|
+
let hasOwnRoute = method === METHOD_NAME_ALL;
|
|
3310
|
+
[this.#middleware, this.#routes].forEach((r) => {
|
|
3311
|
+
const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
|
|
3312
|
+
if (ownRoute.length !== 0) {
|
|
3313
|
+
hasOwnRoute ||= true;
|
|
3314
|
+
routes.push(...ownRoute);
|
|
3315
|
+
} else if (method !== METHOD_NAME_ALL) {
|
|
3316
|
+
routes.push(
|
|
3317
|
+
...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])
|
|
3318
|
+
);
|
|
3319
|
+
}
|
|
3320
|
+
});
|
|
3321
|
+
if (!hasOwnRoute) {
|
|
3322
|
+
return null;
|
|
3323
|
+
} else {
|
|
3324
|
+
return buildMatcherFromPreprocessedRoutes(routes);
|
|
3325
|
+
}
|
|
3326
|
+
}
|
|
3327
|
+
};
|
|
3328
|
+
|
|
3329
|
+
// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/smart-router/router.js
|
|
3330
|
+
var SmartRouter = class {
|
|
3331
|
+
name = "SmartRouter";
|
|
3332
|
+
#routers = [];
|
|
3333
|
+
#routes = [];
|
|
3334
|
+
constructor(init) {
|
|
3335
|
+
this.#routers = init.routers;
|
|
3336
|
+
}
|
|
3337
|
+
add(method, path, handler) {
|
|
3338
|
+
if (!this.#routes) {
|
|
3339
|
+
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
3340
|
+
}
|
|
3341
|
+
this.#routes.push([method, path, handler]);
|
|
3342
|
+
}
|
|
3343
|
+
match(method, path) {
|
|
3344
|
+
if (!this.#routes) {
|
|
3345
|
+
throw new Error("Fatal error");
|
|
3346
|
+
}
|
|
3347
|
+
const routers = this.#routers;
|
|
3348
|
+
const routes = this.#routes;
|
|
3349
|
+
const len = routers.length;
|
|
3350
|
+
let i = 0;
|
|
3351
|
+
let res;
|
|
3352
|
+
for (; i < len; i++) {
|
|
3353
|
+
const router = routers[i];
|
|
3354
|
+
try {
|
|
3355
|
+
for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
|
|
3356
|
+
router.add(...routes[i2]);
|
|
3357
|
+
}
|
|
3358
|
+
res = router.match(method, path);
|
|
3359
|
+
} catch (e) {
|
|
3360
|
+
if (e instanceof UnsupportedPathError) {
|
|
3361
|
+
continue;
|
|
3362
|
+
}
|
|
3363
|
+
throw e;
|
|
3364
|
+
}
|
|
3365
|
+
this.match = router.match.bind(router);
|
|
3366
|
+
this.#routers = [router];
|
|
3367
|
+
this.#routes = void 0;
|
|
3368
|
+
break;
|
|
3369
|
+
}
|
|
3370
|
+
if (i === len) {
|
|
3371
|
+
throw new Error("Fatal error");
|
|
3372
|
+
}
|
|
3373
|
+
this.name = `SmartRouter + ${this.activeRouter.name}`;
|
|
3374
|
+
return res;
|
|
3375
|
+
}
|
|
3376
|
+
get activeRouter() {
|
|
3377
|
+
if (this.#routes || this.#routers.length !== 1) {
|
|
3378
|
+
throw new Error("No active router has been determined yet.");
|
|
3379
|
+
}
|
|
3380
|
+
return this.#routers[0];
|
|
3381
|
+
}
|
|
3382
|
+
};
|
|
3383
|
+
|
|
3384
|
+
// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/trie-router/node.js
|
|
3385
|
+
var emptyParams = /* @__PURE__ */ Object.create(null);
|
|
3386
|
+
var hasChildren = (children) => {
|
|
3387
|
+
for (const _ in children) {
|
|
3388
|
+
return true;
|
|
3389
|
+
}
|
|
3390
|
+
return false;
|
|
3391
|
+
};
|
|
3392
|
+
var Node2 = class _Node2 {
|
|
3393
|
+
#methods;
|
|
3394
|
+
#children;
|
|
3395
|
+
#patterns;
|
|
3396
|
+
#order = 0;
|
|
3397
|
+
#params = emptyParams;
|
|
3398
|
+
constructor(method, handler, children) {
|
|
3399
|
+
this.#children = children || /* @__PURE__ */ Object.create(null);
|
|
3400
|
+
this.#methods = [];
|
|
3401
|
+
if (method && handler) {
|
|
3402
|
+
const m = /* @__PURE__ */ Object.create(null);
|
|
3403
|
+
m[method] = { handler, possibleKeys: [], score: 0 };
|
|
3404
|
+
this.#methods = [m];
|
|
3405
|
+
}
|
|
3406
|
+
this.#patterns = [];
|
|
3407
|
+
}
|
|
3408
|
+
insert(method, path, handler) {
|
|
3409
|
+
this.#order = ++this.#order;
|
|
3410
|
+
let curNode = this;
|
|
3411
|
+
const parts = splitRoutingPath(path);
|
|
3412
|
+
const possibleKeys = [];
|
|
3413
|
+
for (let i = 0, len = parts.length; i < len; i++) {
|
|
3414
|
+
const p = parts[i];
|
|
3415
|
+
const nextP = parts[i + 1];
|
|
3416
|
+
const pattern = getPattern(p, nextP);
|
|
3417
|
+
const key = Array.isArray(pattern) ? pattern[0] : p;
|
|
3418
|
+
if (key in curNode.#children) {
|
|
3419
|
+
curNode = curNode.#children[key];
|
|
3420
|
+
if (pattern) {
|
|
3421
|
+
possibleKeys.push(pattern[1]);
|
|
3422
|
+
}
|
|
3423
|
+
continue;
|
|
3424
|
+
}
|
|
3425
|
+
curNode.#children[key] = new _Node2();
|
|
3426
|
+
if (pattern) {
|
|
3427
|
+
curNode.#patterns.push(pattern);
|
|
3428
|
+
possibleKeys.push(pattern[1]);
|
|
3429
|
+
}
|
|
3430
|
+
curNode = curNode.#children[key];
|
|
3431
|
+
}
|
|
3432
|
+
curNode.#methods.push({
|
|
3433
|
+
[method]: {
|
|
3434
|
+
handler,
|
|
3435
|
+
possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
|
|
3436
|
+
score: this.#order
|
|
3437
|
+
}
|
|
3438
|
+
});
|
|
3439
|
+
return curNode;
|
|
3440
|
+
}
|
|
3441
|
+
#pushHandlerSets(handlerSets, node, method, nodeParams, params) {
|
|
3442
|
+
for (let i = 0, len = node.#methods.length; i < len; i++) {
|
|
3443
|
+
const m = node.#methods[i];
|
|
3444
|
+
const handlerSet = m[method] || m[METHOD_NAME_ALL];
|
|
3445
|
+
const processedSet = {};
|
|
3446
|
+
if (handlerSet !== void 0) {
|
|
3447
|
+
handlerSet.params = /* @__PURE__ */ Object.create(null);
|
|
3448
|
+
handlerSets.push(handlerSet);
|
|
3449
|
+
if (nodeParams !== emptyParams || params && params !== emptyParams) {
|
|
3450
|
+
for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
|
|
3451
|
+
const key = handlerSet.possibleKeys[i2];
|
|
3452
|
+
const processed = processedSet[handlerSet.score];
|
|
3453
|
+
handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
|
|
3454
|
+
processedSet[handlerSet.score] = true;
|
|
3455
|
+
}
|
|
3456
|
+
}
|
|
3457
|
+
}
|
|
3458
|
+
}
|
|
3459
|
+
}
|
|
3460
|
+
search(method, path) {
|
|
3461
|
+
const handlerSets = [];
|
|
3462
|
+
this.#params = emptyParams;
|
|
3463
|
+
const curNode = this;
|
|
3464
|
+
let curNodes = [curNode];
|
|
3465
|
+
const parts = splitPath(path);
|
|
3466
|
+
const curNodesQueue = [];
|
|
3467
|
+
const len = parts.length;
|
|
3468
|
+
let partOffsets = null;
|
|
3469
|
+
for (let i = 0; i < len; i++) {
|
|
3470
|
+
const part = parts[i];
|
|
3471
|
+
const isLast = i === len - 1;
|
|
3472
|
+
const tempNodes = [];
|
|
3473
|
+
for (let j = 0, len2 = curNodes.length; j < len2; j++) {
|
|
3474
|
+
const node = curNodes[j];
|
|
3475
|
+
const nextNode = node.#children[part];
|
|
3476
|
+
if (nextNode) {
|
|
3477
|
+
nextNode.#params = node.#params;
|
|
3478
|
+
if (isLast) {
|
|
3479
|
+
if (nextNode.#children["*"]) {
|
|
3480
|
+
this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
|
|
3481
|
+
}
|
|
3482
|
+
this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
|
|
3483
|
+
} else {
|
|
3484
|
+
tempNodes.push(nextNode);
|
|
3485
|
+
}
|
|
3486
|
+
}
|
|
3487
|
+
for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
|
|
3488
|
+
const pattern = node.#patterns[k];
|
|
3489
|
+
const params = node.#params === emptyParams ? {} : { ...node.#params };
|
|
3490
|
+
if (pattern === "*") {
|
|
3491
|
+
const astNode = node.#children["*"];
|
|
3492
|
+
if (astNode) {
|
|
3493
|
+
this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
|
|
3494
|
+
astNode.#params = params;
|
|
3495
|
+
tempNodes.push(astNode);
|
|
3496
|
+
}
|
|
3497
|
+
continue;
|
|
3498
|
+
}
|
|
3499
|
+
const [key, name, matcher] = pattern;
|
|
3500
|
+
if (!part && !(matcher instanceof RegExp)) {
|
|
3501
|
+
continue;
|
|
3502
|
+
}
|
|
3503
|
+
const child = node.#children[key];
|
|
3504
|
+
if (matcher instanceof RegExp) {
|
|
3505
|
+
if (partOffsets === null) {
|
|
3506
|
+
partOffsets = new Array(len);
|
|
3507
|
+
let offset = path[0] === "/" ? 1 : 0;
|
|
3508
|
+
for (let p = 0; p < len; p++) {
|
|
3509
|
+
partOffsets[p] = offset;
|
|
3510
|
+
offset += parts[p].length + 1;
|
|
3511
|
+
}
|
|
3512
|
+
}
|
|
3513
|
+
const restPathString = path.substring(partOffsets[i]);
|
|
3514
|
+
const m = matcher.exec(restPathString);
|
|
3515
|
+
if (m) {
|
|
3516
|
+
params[name] = m[0];
|
|
3517
|
+
this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
|
|
3518
|
+
if (hasChildren(child.#children)) {
|
|
3519
|
+
child.#params = params;
|
|
3520
|
+
const componentCount = m[0].match(/\//)?.length ?? 0;
|
|
3521
|
+
const targetCurNodes = curNodesQueue[componentCount] ||= [];
|
|
3522
|
+
targetCurNodes.push(child);
|
|
3523
|
+
}
|
|
3524
|
+
continue;
|
|
3525
|
+
}
|
|
3526
|
+
}
|
|
3527
|
+
if (matcher === true || matcher.test(part)) {
|
|
3528
|
+
params[name] = part;
|
|
3529
|
+
if (isLast) {
|
|
3530
|
+
this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
|
|
3531
|
+
if (child.#children["*"]) {
|
|
3532
|
+
this.#pushHandlerSets(
|
|
3533
|
+
handlerSets,
|
|
3534
|
+
child.#children["*"],
|
|
3535
|
+
method,
|
|
3536
|
+
params,
|
|
3537
|
+
node.#params
|
|
3538
|
+
);
|
|
3539
|
+
}
|
|
3540
|
+
} else {
|
|
3541
|
+
child.#params = params;
|
|
3542
|
+
tempNodes.push(child);
|
|
3543
|
+
}
|
|
3544
|
+
}
|
|
3545
|
+
}
|
|
3546
|
+
}
|
|
3547
|
+
const shifted = curNodesQueue.shift();
|
|
3548
|
+
curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
|
|
3549
|
+
}
|
|
3550
|
+
if (handlerSets.length > 1) {
|
|
3551
|
+
handlerSets.sort((a, b) => {
|
|
3552
|
+
return a.score - b.score;
|
|
3553
|
+
});
|
|
3554
|
+
}
|
|
3555
|
+
return [handlerSets.map(({ handler, params }) => [handler, params])];
|
|
3556
|
+
}
|
|
3557
|
+
};
|
|
3558
|
+
|
|
3559
|
+
// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/trie-router/router.js
|
|
3560
|
+
var TrieRouter = class {
|
|
3561
|
+
name = "TrieRouter";
|
|
3562
|
+
#node;
|
|
3563
|
+
constructor() {
|
|
3564
|
+
this.#node = new Node2();
|
|
3565
|
+
}
|
|
3566
|
+
add(method, path, handler) {
|
|
3567
|
+
const results = checkOptionalParameter(path);
|
|
3568
|
+
if (results) {
|
|
3569
|
+
for (let i = 0, len = results.length; i < len; i++) {
|
|
3570
|
+
this.#node.insert(method, results[i], handler);
|
|
3571
|
+
}
|
|
3572
|
+
return;
|
|
3573
|
+
}
|
|
3574
|
+
this.#node.insert(method, path, handler);
|
|
3575
|
+
}
|
|
3576
|
+
match(method, path) {
|
|
3577
|
+
return this.#node.search(method, path);
|
|
3578
|
+
}
|
|
3579
|
+
};
|
|
3580
|
+
|
|
3581
|
+
// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/hono.js
|
|
3582
|
+
var Hono2 = class extends Hono {
|
|
3583
|
+
/**
|
|
3584
|
+
* Creates an instance of the Hono class.
|
|
3585
|
+
*
|
|
3586
|
+
* @param options - Optional configuration options for the Hono instance.
|
|
3587
|
+
*/
|
|
3588
|
+
constructor(options = {}) {
|
|
3589
|
+
super(options);
|
|
3590
|
+
this.router = options.router ?? new SmartRouter({
|
|
3591
|
+
routers: [new RegExpRouter(), new TrieRouter()]
|
|
3592
|
+
});
|
|
3593
|
+
}
|
|
3594
|
+
};
|
|
3595
|
+
|
|
3596
|
+
// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/middleware/cors/index.js
|
|
3597
|
+
var cors = (options) => {
|
|
3598
|
+
const opts = {
|
|
3599
|
+
origin: "*",
|
|
3600
|
+
allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
|
|
3601
|
+
allowHeaders: [],
|
|
3602
|
+
exposeHeaders: [],
|
|
3603
|
+
...options
|
|
3604
|
+
};
|
|
3605
|
+
const findAllowOrigin = ((optsOrigin) => {
|
|
3606
|
+
if (typeof optsOrigin === "string") {
|
|
3607
|
+
if (optsOrigin === "*") {
|
|
3608
|
+
if (opts.credentials) {
|
|
3609
|
+
return (origin) => origin || null;
|
|
3610
|
+
}
|
|
3611
|
+
return () => optsOrigin;
|
|
3612
|
+
} else {
|
|
3613
|
+
return (origin) => optsOrigin === origin ? origin : null;
|
|
3614
|
+
}
|
|
3615
|
+
} else if (typeof optsOrigin === "function") {
|
|
3616
|
+
return optsOrigin;
|
|
3617
|
+
} else {
|
|
3618
|
+
return (origin) => optsOrigin.includes(origin) ? origin : null;
|
|
3619
|
+
}
|
|
3620
|
+
})(opts.origin);
|
|
3621
|
+
const findAllowMethods = ((optsAllowMethods) => {
|
|
3622
|
+
if (typeof optsAllowMethods === "function") {
|
|
3623
|
+
return optsAllowMethods;
|
|
3624
|
+
} else if (Array.isArray(optsAllowMethods)) {
|
|
3625
|
+
return () => optsAllowMethods;
|
|
3626
|
+
} else {
|
|
3627
|
+
return () => [];
|
|
3628
|
+
}
|
|
3629
|
+
})(opts.allowMethods);
|
|
3630
|
+
return async function cors2(c, next) {
|
|
3631
|
+
function set(key, value) {
|
|
3632
|
+
c.res.headers.set(key, value);
|
|
3633
|
+
}
|
|
3634
|
+
const allowOrigin = await findAllowOrigin(c.req.header("origin") || "", c);
|
|
3635
|
+
if (allowOrigin) {
|
|
3636
|
+
set("Access-Control-Allow-Origin", allowOrigin);
|
|
3637
|
+
}
|
|
3638
|
+
if (opts.credentials) {
|
|
3639
|
+
set("Access-Control-Allow-Credentials", "true");
|
|
3640
|
+
}
|
|
3641
|
+
if (opts.exposeHeaders?.length) {
|
|
3642
|
+
set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
|
|
3643
|
+
}
|
|
3644
|
+
if (c.req.method === "OPTIONS") {
|
|
3645
|
+
if (opts.origin !== "*" || opts.credentials) {
|
|
3646
|
+
set("Vary", "Origin");
|
|
3647
|
+
}
|
|
3648
|
+
if (opts.maxAge != null) {
|
|
3649
|
+
set("Access-Control-Max-Age", opts.maxAge.toString());
|
|
3650
|
+
}
|
|
3651
|
+
const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
|
|
3652
|
+
if (allowMethods.length) {
|
|
3653
|
+
set("Access-Control-Allow-Methods", allowMethods.join(","));
|
|
3654
|
+
}
|
|
3655
|
+
let headers = opts.allowHeaders;
|
|
3656
|
+
if (!headers?.length) {
|
|
3657
|
+
const requestHeaders = c.req.header("Access-Control-Request-Headers");
|
|
3658
|
+
if (requestHeaders) {
|
|
3659
|
+
headers = requestHeaders.split(/\s*,\s*/);
|
|
3660
|
+
}
|
|
3661
|
+
}
|
|
3662
|
+
if (headers?.length) {
|
|
3663
|
+
set("Access-Control-Allow-Headers", headers.join(","));
|
|
3664
|
+
c.res.headers.append("Vary", "Access-Control-Request-Headers");
|
|
3665
|
+
}
|
|
3666
|
+
c.res.headers.delete("Content-Length");
|
|
3667
|
+
c.res.headers.delete("Content-Type");
|
|
3668
|
+
return new Response(null, {
|
|
3669
|
+
headers: c.res.headers,
|
|
3670
|
+
status: 204,
|
|
3671
|
+
statusText: "No Content"
|
|
3672
|
+
});
|
|
3673
|
+
}
|
|
3674
|
+
await next();
|
|
3675
|
+
if (opts.origin !== "*" || opts.credentials) {
|
|
3676
|
+
c.header("Vary", "Origin", { append: true });
|
|
3677
|
+
}
|
|
3678
|
+
};
|
|
3679
|
+
};
|
|
3680
|
+
|
|
3681
|
+
// src/websocket.ts
|
|
3682
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
3683
|
+
var webSocketGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
|
3684
|
+
var WebSocketHub = class {
|
|
3685
|
+
constructor(store) {
|
|
3686
|
+
this.store = store;
|
|
3687
|
+
this.unsubscribeStore = store.subscribe((change) => {
|
|
3688
|
+
this.broadcast({
|
|
3689
|
+
type: "project:snapshot",
|
|
3690
|
+
project: change.project,
|
|
3691
|
+
revision: change.revision
|
|
3692
|
+
}, change.source);
|
|
3693
|
+
});
|
|
3694
|
+
}
|
|
3695
|
+
store;
|
|
3696
|
+
clients = /* @__PURE__ */ new Set();
|
|
3697
|
+
unsubscribeStore;
|
|
3698
|
+
close() {
|
|
3699
|
+
this.unsubscribeStore();
|
|
3700
|
+
for (const client of this.clients) {
|
|
3701
|
+
client.socket.destroy();
|
|
3702
|
+
}
|
|
3703
|
+
this.clients.clear();
|
|
3704
|
+
}
|
|
3705
|
+
handleUpgrade(request, socket) {
|
|
3706
|
+
if (request.url !== "/ws") {
|
|
3707
|
+
socket.destroy();
|
|
3708
|
+
return;
|
|
3709
|
+
}
|
|
3710
|
+
const key = request.headers["sec-websocket-key"];
|
|
3711
|
+
if (typeof key !== "string") {
|
|
3712
|
+
socket.destroy();
|
|
3713
|
+
return;
|
|
3714
|
+
}
|
|
3715
|
+
const accept = createHash2("sha1").update(`${key}${webSocketGuid}`).digest("base64");
|
|
3716
|
+
socket.write(
|
|
3717
|
+
[
|
|
3718
|
+
"HTTP/1.1 101 Switching Protocols",
|
|
3719
|
+
"Upgrade: websocket",
|
|
3720
|
+
"Connection: Upgrade",
|
|
3721
|
+
`Sec-WebSocket-Accept: ${accept}`,
|
|
3722
|
+
""
|
|
3723
|
+
].join("\r\n") + "\r\n"
|
|
3724
|
+
);
|
|
3725
|
+
const client = {
|
|
3726
|
+
buffer: Buffer.alloc(0),
|
|
3727
|
+
socket
|
|
3728
|
+
};
|
|
3729
|
+
this.clients.add(client);
|
|
3730
|
+
this.sendJson(socket, {
|
|
3731
|
+
type: "project:snapshot",
|
|
3732
|
+
project: this.store.readProject(),
|
|
3733
|
+
revision: this.store.revision()
|
|
3734
|
+
});
|
|
3735
|
+
socket.on("data", (chunk) => {
|
|
3736
|
+
client.buffer = Buffer.concat([client.buffer, chunk]);
|
|
3737
|
+
client.buffer = readWebSocketFrames(client.buffer, (message) => {
|
|
3738
|
+
this.handleMessage(client, message);
|
|
3739
|
+
}, socket);
|
|
3740
|
+
});
|
|
3741
|
+
socket.on("close", () => {
|
|
3742
|
+
this.clients.delete(client);
|
|
3743
|
+
});
|
|
3744
|
+
socket.on("error", () => {
|
|
3745
|
+
this.clients.delete(client);
|
|
3746
|
+
});
|
|
3747
|
+
}
|
|
3748
|
+
handleMessage(client, message) {
|
|
3749
|
+
let payload;
|
|
3750
|
+
try {
|
|
3751
|
+
payload = JSON.parse(message);
|
|
3752
|
+
} catch {
|
|
3753
|
+
this.sendJson(client.socket, { type: "error", error: "Invalid JSON message." });
|
|
3754
|
+
return;
|
|
3755
|
+
}
|
|
3756
|
+
if (isProjectUpdateMessage(payload) && isGlyphSmithProject(payload.project)) {
|
|
3757
|
+
this.store.writeProject(payload.project, client);
|
|
3758
|
+
this.sendJson(client.socket, { type: "project:ack", revision: this.store.revision() });
|
|
3759
|
+
return;
|
|
3760
|
+
}
|
|
3761
|
+
if (isSelectionUpdateMessage(payload)) {
|
|
3762
|
+
this.store.setSelection({ nodeIds: payload.nodeIds.filter((nodeId) => typeof nodeId === "string") });
|
|
3763
|
+
this.sendJson(client.socket, { type: "selection:ack" });
|
|
3764
|
+
return;
|
|
3765
|
+
}
|
|
3766
|
+
this.sendJson(client.socket, { type: "error", error: "Unsupported host message." });
|
|
3767
|
+
}
|
|
3768
|
+
broadcast(payload, exceptSource) {
|
|
3769
|
+
for (const client of this.clients) {
|
|
3770
|
+
if (client === exceptSource) {
|
|
3771
|
+
continue;
|
|
3772
|
+
}
|
|
3773
|
+
this.sendJson(client.socket, payload);
|
|
3774
|
+
}
|
|
3775
|
+
}
|
|
3776
|
+
sendJson(socket, payload) {
|
|
3777
|
+
sendWebSocketFrame(socket, Buffer.from(JSON.stringify(payload), "utf8"), 1);
|
|
3778
|
+
}
|
|
3779
|
+
};
|
|
3780
|
+
function isProjectUpdateMessage(value) {
|
|
3781
|
+
return Boolean(
|
|
3782
|
+
value && typeof value === "object" && "type" in value && value.type === "project:update" && "project" in value
|
|
3783
|
+
);
|
|
3784
|
+
}
|
|
3785
|
+
function isSelectionUpdateMessage(value) {
|
|
3786
|
+
return Boolean(
|
|
3787
|
+
value && typeof value === "object" && "type" in value && value.type === "selection:update" && "nodeIds" in value && Array.isArray(value.nodeIds)
|
|
3788
|
+
);
|
|
3789
|
+
}
|
|
3790
|
+
function readWebSocketFrames(buffer, onTextMessage, socket) {
|
|
3791
|
+
let offset = 0;
|
|
3792
|
+
while (buffer.length - offset >= 2) {
|
|
3793
|
+
const firstByte = buffer[offset];
|
|
3794
|
+
const secondByte = buffer[offset + 1];
|
|
3795
|
+
const opcode = firstByte & 15;
|
|
3796
|
+
const masked = (secondByte & 128) === 128;
|
|
3797
|
+
let payloadLength = secondByte & 127;
|
|
3798
|
+
let headerLength = 2;
|
|
3799
|
+
if (payloadLength === 126) {
|
|
3800
|
+
if (buffer.length - offset < 4) {
|
|
3801
|
+
break;
|
|
3802
|
+
}
|
|
3803
|
+
payloadLength = buffer.readUInt16BE(offset + 2);
|
|
3804
|
+
headerLength = 4;
|
|
3805
|
+
} else if (payloadLength === 127) {
|
|
3806
|
+
if (buffer.length - offset < 10) {
|
|
3807
|
+
break;
|
|
3808
|
+
}
|
|
3809
|
+
const largePayloadLength = buffer.readBigUInt64BE(offset + 2);
|
|
3810
|
+
if (largePayloadLength > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
3811
|
+
socket.destroy();
|
|
3812
|
+
return Buffer.alloc(0);
|
|
3813
|
+
}
|
|
3814
|
+
payloadLength = Number(largePayloadLength);
|
|
3815
|
+
headerLength = 10;
|
|
3816
|
+
}
|
|
3817
|
+
const maskLength = masked ? 4 : 0;
|
|
3818
|
+
const frameLength = headerLength + maskLength + payloadLength;
|
|
3819
|
+
if (buffer.length - offset < frameLength) {
|
|
3820
|
+
break;
|
|
3821
|
+
}
|
|
3822
|
+
const maskOffset = offset + headerLength;
|
|
3823
|
+
const payloadOffset = maskOffset + maskLength;
|
|
3824
|
+
const payload = Buffer.from(buffer.subarray(payloadOffset, payloadOffset + payloadLength));
|
|
3825
|
+
if (masked) {
|
|
3826
|
+
const mask = buffer.subarray(maskOffset, maskOffset + 4);
|
|
3827
|
+
for (let index = 0; index < payload.length; index += 1) {
|
|
3828
|
+
payload[index] = payload[index] ^ mask[index % 4];
|
|
3829
|
+
}
|
|
3830
|
+
}
|
|
3831
|
+
if (opcode === 1) {
|
|
3832
|
+
onTextMessage(payload.toString("utf8"));
|
|
3833
|
+
} else if (opcode === 8) {
|
|
3834
|
+
socket.end();
|
|
3835
|
+
return Buffer.alloc(0);
|
|
3836
|
+
} else if (opcode === 9) {
|
|
3837
|
+
sendWebSocketFrame(socket, payload, 10);
|
|
3838
|
+
}
|
|
3839
|
+
offset += frameLength;
|
|
3840
|
+
}
|
|
3841
|
+
return buffer.subarray(offset);
|
|
3842
|
+
}
|
|
3843
|
+
function sendWebSocketFrame(socket, payload, opcode) {
|
|
3844
|
+
const payloadLength = payload.length;
|
|
3845
|
+
let header;
|
|
3846
|
+
if (payloadLength < 126) {
|
|
3847
|
+
header = Buffer.from([128 | opcode, payloadLength]);
|
|
3848
|
+
} else if (payloadLength <= 65535) {
|
|
3849
|
+
header = Buffer.alloc(4);
|
|
3850
|
+
header[0] = 128 | opcode;
|
|
3851
|
+
header[1] = 126;
|
|
3852
|
+
header.writeUInt16BE(payloadLength, 2);
|
|
3853
|
+
} else {
|
|
3854
|
+
header = Buffer.alloc(10);
|
|
3855
|
+
header[0] = 128 | opcode;
|
|
3856
|
+
header[1] = 127;
|
|
3857
|
+
header.writeBigUInt64BE(BigInt(payloadLength), 2);
|
|
3858
|
+
}
|
|
3859
|
+
socket.write(Buffer.concat([header, payload]));
|
|
3860
|
+
}
|
|
3861
|
+
|
|
3862
|
+
// src/server.ts
|
|
3863
|
+
function startHostServer(options) {
|
|
3864
|
+
const websocketHub = new WebSocketHub(options.store);
|
|
3865
|
+
const app = createHostApp(options);
|
|
3866
|
+
const server = createServer(async (request, response) => {
|
|
3867
|
+
try {
|
|
3868
|
+
if (options.webDirectory && shouldServeWebAsset(request)) {
|
|
3869
|
+
const served = await serveWebAsset(options.webDirectory, request, response);
|
|
3870
|
+
if (served) {
|
|
3871
|
+
return;
|
|
3872
|
+
}
|
|
3873
|
+
}
|
|
3874
|
+
const fetchRequest = await nodeRequestToFetchRequest(request);
|
|
3875
|
+
const fetchResponse = await app.fetch(fetchRequest);
|
|
3876
|
+
await writeFetchResponse(response, fetchResponse);
|
|
3877
|
+
} catch (error) {
|
|
3878
|
+
response.writeHead(500, { "content-type": "application/json" });
|
|
3879
|
+
response.end(`${JSON.stringify({ ok: false, error: error instanceof Error ? error.message : String(error) })}
|
|
3880
|
+
`);
|
|
3881
|
+
}
|
|
3882
|
+
});
|
|
3883
|
+
server.on("upgrade", (request, socket) => {
|
|
3884
|
+
websocketHub.handleUpgrade(request, socket);
|
|
3885
|
+
});
|
|
3886
|
+
server.listen(Number(options.port), options.host);
|
|
3887
|
+
return {
|
|
3888
|
+
close() {
|
|
3889
|
+
websocketHub.close();
|
|
3890
|
+
server.close();
|
|
3891
|
+
},
|
|
3892
|
+
server
|
|
3893
|
+
};
|
|
3894
|
+
}
|
|
3895
|
+
function createHostApp(options) {
|
|
3896
|
+
const app = new Hono2();
|
|
3897
|
+
app.use("/mcp", cors());
|
|
3898
|
+
app.get("/health", (context) => {
|
|
3899
|
+
return context.json({
|
|
3900
|
+
ok: true,
|
|
3901
|
+
server: "glyphsmith-cli",
|
|
3902
|
+
mcpUrl: options.mcpUrl,
|
|
3903
|
+
projectFile: options.store.projectFile
|
|
3904
|
+
});
|
|
3905
|
+
});
|
|
3906
|
+
app.get("/project", (context) => {
|
|
3907
|
+
return context.json({
|
|
3908
|
+
hostWebSocketUrl: websocketUrl(context.req.raw.url, options.host, options.port),
|
|
3909
|
+
project: options.store.readProject(),
|
|
3910
|
+
revision: options.store.revision()
|
|
3911
|
+
});
|
|
3912
|
+
});
|
|
3913
|
+
app.options("/mcp", (context) => {
|
|
3914
|
+
return context.body(null, 204);
|
|
3915
|
+
});
|
|
3916
|
+
app.post("/mcp", async (context) => {
|
|
3917
|
+
const body = await context.req.json();
|
|
3918
|
+
const result = await handleMcpBody({ store: options.store }, body);
|
|
3919
|
+
if (!result) {
|
|
3920
|
+
return context.json({}, 202);
|
|
3921
|
+
}
|
|
3922
|
+
return context.json(result);
|
|
3923
|
+
});
|
|
3924
|
+
app.notFound((context) => {
|
|
3925
|
+
return context.json({ ok: false, error: "Not found." }, 404);
|
|
3926
|
+
});
|
|
3927
|
+
return app;
|
|
3928
|
+
}
|
|
3929
|
+
function shouldServeWebAsset(request) {
|
|
3930
|
+
const method = request.method ?? "GET";
|
|
3931
|
+
if (method !== "GET" && method !== "HEAD") {
|
|
3932
|
+
return false;
|
|
3933
|
+
}
|
|
3934
|
+
const pathname = new URL(request.url ?? "/", `http://${request.headers.host ?? "localhost"}`).pathname;
|
|
3935
|
+
return !pathname.startsWith("/mcp") && pathname !== "/health" && pathname !== "/project" && pathname !== "/ws";
|
|
3936
|
+
}
|
|
3937
|
+
async function serveWebAsset(webDirectory, request, response) {
|
|
3938
|
+
const url = new URL(request.url ?? "/", `http://${request.headers.host ?? "localhost"}`);
|
|
3939
|
+
const pathname = decodeURIComponent(url.pathname);
|
|
3940
|
+
const requestedPath = pathname === "/" ? "index.html" : pathname.replace(/^\/+/, "");
|
|
3941
|
+
const resolvedWebDirectory = resolve(webDirectory);
|
|
3942
|
+
const candidatePath = resolve(resolvedWebDirectory, normalize(requestedPath));
|
|
3943
|
+
if (!candidatePath.startsWith(`${resolvedWebDirectory}${sep}`) && candidatePath !== resolvedWebDirectory) {
|
|
3944
|
+
response.writeHead(403, { "content-type": "text/plain; charset=utf-8" });
|
|
3945
|
+
response.end("Forbidden");
|
|
3946
|
+
return true;
|
|
3947
|
+
}
|
|
3948
|
+
const filePath = await webFilePath(candidatePath, resolvedWebDirectory);
|
|
3949
|
+
if (!filePath) {
|
|
3950
|
+
return false;
|
|
3951
|
+
}
|
|
3952
|
+
const headers = {
|
|
3953
|
+
"content-type": contentTypeForPath(filePath)
|
|
3954
|
+
};
|
|
3955
|
+
const fileStat = await stat(filePath);
|
|
3956
|
+
headers["content-length"] = String(fileStat.size);
|
|
3957
|
+
if (request.method === "HEAD") {
|
|
3958
|
+
response.writeHead(200, headers);
|
|
3959
|
+
response.end();
|
|
3960
|
+
return true;
|
|
3961
|
+
}
|
|
3962
|
+
response.writeHead(200, headers);
|
|
3963
|
+
createReadStream(filePath).pipe(response);
|
|
3964
|
+
return true;
|
|
3965
|
+
}
|
|
3966
|
+
async function webFilePath(candidatePath, webDirectory) {
|
|
3967
|
+
if (existsSync2(candidatePath) && (await stat(candidatePath)).isFile()) {
|
|
3968
|
+
return candidatePath;
|
|
3969
|
+
}
|
|
3970
|
+
const indexPath = join(webDirectory, "index.html");
|
|
3971
|
+
return existsSync2(indexPath) ? indexPath : void 0;
|
|
3972
|
+
}
|
|
3973
|
+
function contentTypeForPath(path) {
|
|
3974
|
+
switch (extname(path).toLowerCase()) {
|
|
3975
|
+
case ".css":
|
|
3976
|
+
return "text/css; charset=utf-8";
|
|
3977
|
+
case ".html":
|
|
3978
|
+
return "text/html; charset=utf-8";
|
|
3979
|
+
case ".js":
|
|
3980
|
+
return "text/javascript; charset=utf-8";
|
|
3981
|
+
case ".json":
|
|
3982
|
+
return "application/json; charset=utf-8";
|
|
3983
|
+
case ".png":
|
|
3984
|
+
return "image/png";
|
|
3985
|
+
case ".svg":
|
|
3986
|
+
return "image/svg+xml";
|
|
3987
|
+
case ".webp":
|
|
3988
|
+
return "image/webp";
|
|
3989
|
+
default:
|
|
3990
|
+
return "application/octet-stream";
|
|
3991
|
+
}
|
|
3992
|
+
}
|
|
3993
|
+
function websocketUrl(rawUrl, host, port) {
|
|
3994
|
+
const url = new URL(rawUrl);
|
|
3995
|
+
const hostname = host === "0.0.0.0" ? "localhost" : url.hostname;
|
|
3996
|
+
return `ws://${hostname}:${port}/ws`;
|
|
3997
|
+
}
|
|
3998
|
+
async function nodeRequestToFetchRequest(request) {
|
|
3999
|
+
const url = new URL(request.url ?? "/", `http://${request.headers.host ?? "localhost"}`);
|
|
4000
|
+
const headers = new Headers();
|
|
4001
|
+
for (const [key, value] of Object.entries(request.headers)) {
|
|
4002
|
+
if (Array.isArray(value)) {
|
|
4003
|
+
for (const item of value) {
|
|
4004
|
+
headers.append(key, item);
|
|
4005
|
+
}
|
|
4006
|
+
} else if (value !== void 0) {
|
|
4007
|
+
headers.set(key, value);
|
|
4008
|
+
}
|
|
4009
|
+
}
|
|
4010
|
+
const method = request.method ?? "GET";
|
|
4011
|
+
const hasBody = method !== "GET" && method !== "HEAD";
|
|
4012
|
+
return new Request(url, {
|
|
4013
|
+
method,
|
|
4014
|
+
headers,
|
|
4015
|
+
body: hasBody ? (await readRequestBody(request)).toString("utf8") : void 0
|
|
4016
|
+
});
|
|
4017
|
+
}
|
|
4018
|
+
function readRequestBody(request) {
|
|
4019
|
+
return new Promise((resolveBody, rejectBody) => {
|
|
4020
|
+
const chunks = [];
|
|
4021
|
+
request.on("data", (chunk) => {
|
|
4022
|
+
chunks.push(chunk);
|
|
4023
|
+
});
|
|
4024
|
+
request.on("end", () => {
|
|
4025
|
+
resolveBody(Buffer.concat(chunks));
|
|
4026
|
+
});
|
|
4027
|
+
request.on("error", rejectBody);
|
|
4028
|
+
});
|
|
4029
|
+
}
|
|
4030
|
+
async function writeFetchResponse(response, fetchResponse) {
|
|
4031
|
+
response.writeHead(fetchResponse.status, Object.fromEntries(fetchResponse.headers.entries()));
|
|
4032
|
+
response.end(Buffer.from(await fetchResponse.arrayBuffer()));
|
|
4033
|
+
}
|
|
4034
|
+
|
|
4035
|
+
// src/index.ts
|
|
4036
|
+
var DEFAULT_PORT = "6201";
|
|
4037
|
+
var DEFAULT_HOST_PORT = "6202";
|
|
4038
|
+
var DEFAULT_HOST = "127.0.0.1";
|
|
4039
|
+
var DEV_BIND_HOST = "0.0.0.0";
|
|
4040
|
+
var DEV_PUBLIC_HOST = "localhost";
|
|
4041
|
+
var cliDirectory = fileURLToPath(new URL(".", import.meta.url));
|
|
4042
|
+
var packagedWebDirectory = resolve2(cliDirectory, "../web");
|
|
4043
|
+
async function main() {
|
|
4044
|
+
const rawArgs = process.argv.slice(2);
|
|
4045
|
+
if (rawArgs[0] === "mcp") {
|
|
4046
|
+
await handleMcpCommand(rawArgs.slice(1));
|
|
4047
|
+
return;
|
|
4048
|
+
}
|
|
4049
|
+
if (rawArgs[0] === "skills") {
|
|
4050
|
+
await handleSkillsCommand(rawArgs.slice(1));
|
|
4051
|
+
return;
|
|
4052
|
+
}
|
|
4053
|
+
if (rawArgs[0] === "export") {
|
|
4054
|
+
await handleExportCommand(rawArgs.slice(1));
|
|
4055
|
+
return;
|
|
4056
|
+
}
|
|
4057
|
+
const options = parseArgs(rawArgs);
|
|
4058
|
+
if (options.help) {
|
|
4059
|
+
printHelp();
|
|
4060
|
+
return;
|
|
4061
|
+
}
|
|
4062
|
+
const projectFile = resolveProjectFile(options);
|
|
4063
|
+
if (options.command === "init") {
|
|
4064
|
+
const store2 = new ProjectStore(projectFile);
|
|
4065
|
+
store2.close();
|
|
4066
|
+
console.log(`\u2713 Project created at ${projectFile}`);
|
|
4067
|
+
return;
|
|
4068
|
+
}
|
|
4069
|
+
if (options.command === "host") {
|
|
4070
|
+
const requestedHostPort2 = options.port ?? DEFAULT_HOST_PORT;
|
|
4071
|
+
const hostPort2 = await requireAvailablePort(requestedHostPort2, /* @__PURE__ */ new Set(), DEV_BIND_HOST);
|
|
4072
|
+
const store2 = new ProjectStore(projectFile);
|
|
4073
|
+
const mcpUrl2 = `http://${DEV_PUBLIC_HOST}:${hostPort2}/mcp`;
|
|
4074
|
+
const hostServer2 = startHostServer({
|
|
4075
|
+
host: DEV_BIND_HOST,
|
|
4076
|
+
mcpUrl: mcpUrl2,
|
|
4077
|
+
port: hostPort2,
|
|
4078
|
+
store: store2
|
|
4079
|
+
});
|
|
4080
|
+
console.log(`\u2713 Project: ${projectFile}`);
|
|
4081
|
+
if (hostPort2 !== requestedHostPort2) {
|
|
4082
|
+
console.log(`\u2713 Host port ${requestedHostPort2} is unavailable, using ${hostPort2}`);
|
|
4083
|
+
}
|
|
4084
|
+
console.log(`\u2713 Host running on ws://${DEV_PUBLIC_HOST}:${hostPort2}/ws`);
|
|
4085
|
+
console.log(`\u2713 MCP running on ${mcpUrl2}`);
|
|
4086
|
+
const shutdownHost = () => {
|
|
4087
|
+
hostServer2.close();
|
|
4088
|
+
store2.close();
|
|
4089
|
+
};
|
|
4090
|
+
process.once("SIGINT", shutdownHost);
|
|
4091
|
+
process.once("SIGTERM", shutdownHost);
|
|
4092
|
+
return;
|
|
4093
|
+
}
|
|
4094
|
+
const requestedPort = options.port ?? DEFAULT_PORT;
|
|
4095
|
+
const packagedWeb = packagedWebDirectoryExists();
|
|
4096
|
+
const port = options.portFixed ? await requireAvailablePort(requestedPort) : await findAvailablePort(requestedPort);
|
|
4097
|
+
const requestedHostPort = packagedWeb ? port : nextPort(port);
|
|
4098
|
+
const hostPort = packagedWeb ? port : options.portFixed ? await requireAvailablePort(requestedHostPort, /* @__PURE__ */ new Set([port])) : await findAvailablePort(requestedHostPort, /* @__PURE__ */ new Set([port]));
|
|
4099
|
+
const store = new ProjectStore(projectFile);
|
|
4100
|
+
const mcpUrl = `http://${DEFAULT_HOST}:${hostPort}/mcp`;
|
|
4101
|
+
const hostServer = startHostServer({
|
|
4102
|
+
host: DEFAULT_HOST,
|
|
4103
|
+
mcpUrl,
|
|
4104
|
+
port: hostPort,
|
|
4105
|
+
store,
|
|
4106
|
+
webDirectory: packagedWeb ? packagedWebDirectory : void 0
|
|
4107
|
+
});
|
|
4108
|
+
console.log(`\u2713 Project: ${projectFile}`);
|
|
4109
|
+
if (port !== requestedPort) {
|
|
4110
|
+
console.log(`\u2713 UI port ${requestedPort} is unavailable, using ${port}`);
|
|
4111
|
+
}
|
|
4112
|
+
if (hostPort !== requestedHostPort) {
|
|
4113
|
+
console.log(`\u2713 Host port ${requestedHostPort} is unavailable, using ${hostPort}`);
|
|
4114
|
+
}
|
|
4115
|
+
console.log(`\u2713 UI running on http://${DEFAULT_HOST}:${port}`);
|
|
4116
|
+
console.log(`\u2713 Host running on ws://${DEFAULT_HOST}:${hostPort}/ws`);
|
|
4117
|
+
console.log(`\u2713 MCP running on ${mcpUrl}`);
|
|
4118
|
+
if (packagedWeb) {
|
|
4119
|
+
return;
|
|
4120
|
+
}
|
|
4121
|
+
const child = spawn("pnpm", ["--filter", "web", "dev", "--host", DEFAULT_HOST], {
|
|
4122
|
+
cwd: resolve2(cliDirectory, "../../.."),
|
|
4123
|
+
env: {
|
|
4124
|
+
...process.env,
|
|
4125
|
+
GLYPHSMITH_HOST_WS_URL: `ws://${DEFAULT_HOST}:${hostPort}/ws`,
|
|
4126
|
+
VITE_GLYPHSMITH_HOST_WS_URL: `ws://${DEFAULT_HOST}:${hostPort}/ws`,
|
|
4127
|
+
GLYPHSMITH_PROJECT_FILE: projectFile,
|
|
4128
|
+
PORT: port
|
|
4129
|
+
},
|
|
4130
|
+
stdio: "inherit"
|
|
4131
|
+
});
|
|
4132
|
+
child.on("exit", (code) => {
|
|
4133
|
+
process.exitCode = code ?? 0;
|
|
4134
|
+
hostServer.close();
|
|
4135
|
+
store.close();
|
|
4136
|
+
});
|
|
4137
|
+
const shutdown = () => {
|
|
4138
|
+
child.kill("SIGTERM");
|
|
4139
|
+
hostServer.close();
|
|
4140
|
+
store.close();
|
|
4141
|
+
};
|
|
4142
|
+
process.once("SIGINT", shutdown);
|
|
4143
|
+
process.once("SIGTERM", shutdown);
|
|
4144
|
+
}
|
|
4145
|
+
function packagedWebDirectoryExists() {
|
|
4146
|
+
return existsSync3(resolve2(packagedWebDirectory, "index.html"));
|
|
4147
|
+
}
|
|
4148
|
+
async function findAvailablePort(startPort, reservedPorts = /* @__PURE__ */ new Set(), host = DEFAULT_HOST) {
|
|
4149
|
+
let port = Number(startPort);
|
|
4150
|
+
while (port <= 65535) {
|
|
4151
|
+
const portText = String(port);
|
|
4152
|
+
if (!reservedPorts.has(portText) && await isPortAvailable(port, host)) {
|
|
4153
|
+
return portText;
|
|
4154
|
+
}
|
|
4155
|
+
port += 1;
|
|
4156
|
+
}
|
|
4157
|
+
throw new Error(`No available port found from ${startPort}.`);
|
|
4158
|
+
}
|
|
4159
|
+
async function requireAvailablePort(port, reservedPorts = /* @__PURE__ */ new Set(), host = DEFAULT_HOST) {
|
|
4160
|
+
if (reservedPorts.has(port) || !await isPortAvailable(Number(port), host)) {
|
|
4161
|
+
throw new Error(`Port ${port} is unavailable.`);
|
|
4162
|
+
}
|
|
4163
|
+
return port;
|
|
4164
|
+
}
|
|
4165
|
+
function isPortAvailable(port, host = DEFAULT_HOST) {
|
|
4166
|
+
return new Promise((resolveAvailable) => {
|
|
4167
|
+
const probe = createNetServer();
|
|
4168
|
+
probe.once("error", () => {
|
|
4169
|
+
resolveAvailable(false);
|
|
4170
|
+
});
|
|
4171
|
+
probe.once("listening", () => {
|
|
4172
|
+
probe.close(() => {
|
|
4173
|
+
resolveAvailable(true);
|
|
4174
|
+
});
|
|
4175
|
+
});
|
|
4176
|
+
probe.listen(port, host);
|
|
4177
|
+
});
|
|
4178
|
+
}
|
|
4179
|
+
function resolveProjectFile(options) {
|
|
4180
|
+
if (options.example && options.projectFile) {
|
|
4181
|
+
throw new Error("--example cannot be used with a project path.");
|
|
4182
|
+
}
|
|
4183
|
+
if (options.example) {
|
|
4184
|
+
return resolveExampleProjectFile(options.example);
|
|
4185
|
+
}
|
|
4186
|
+
const rawPath = options.projectFile ?? "glyphsmith.gs.json";
|
|
4187
|
+
const trimmedPath = rawPath.replace(/[\\/]+$/, "");
|
|
4188
|
+
const filePath = /\.gs\.json$/i.test(trimmedPath) ? trimmedPath : `${trimmedPath}.gs.json`;
|
|
4189
|
+
return resolve2(process.cwd(), filePath);
|
|
4190
|
+
}
|
|
4191
|
+
function resolveExampleProjectFile(exampleName) {
|
|
4192
|
+
const normalizedName = exampleName.trim().replace(/\.gs\.json$/i, "");
|
|
4193
|
+
if (!/^[\w-]+$/.test(normalizedName)) {
|
|
4194
|
+
throw new Error(`Invalid example name: ${exampleName}`);
|
|
4195
|
+
}
|
|
4196
|
+
return resolve2(cliDirectory, "../../..", "examples", `${normalizedName}.gs.json`);
|
|
4197
|
+
}
|
|
4198
|
+
function parseArgs(args) {
|
|
4199
|
+
const options = {
|
|
4200
|
+
command: "open",
|
|
4201
|
+
example: void 0,
|
|
4202
|
+
help: false,
|
|
4203
|
+
port: void 0,
|
|
4204
|
+
portFixed: false,
|
|
4205
|
+
projectFile: void 0
|
|
4206
|
+
};
|
|
4207
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
4208
|
+
const arg = args[index];
|
|
4209
|
+
if (arg === "--") {
|
|
4210
|
+
continue;
|
|
4211
|
+
}
|
|
4212
|
+
if (arg === "--help" || arg === "-h") {
|
|
4213
|
+
options.help = true;
|
|
4214
|
+
continue;
|
|
4215
|
+
}
|
|
4216
|
+
if ((arg === "host" || arg === "init") && options.command === "open" && options.projectFile === void 0) {
|
|
4217
|
+
options.command = arg;
|
|
4218
|
+
continue;
|
|
4219
|
+
}
|
|
4220
|
+
if (arg === "--port") {
|
|
4221
|
+
const value = args[index + 1];
|
|
4222
|
+
if (!value || value.startsWith("-")) {
|
|
4223
|
+
throw new Error("--port requires a value.");
|
|
4224
|
+
}
|
|
4225
|
+
options.port = parsePort(value);
|
|
4226
|
+
options.portFixed = true;
|
|
4227
|
+
index += 1;
|
|
4228
|
+
continue;
|
|
4229
|
+
}
|
|
4230
|
+
if (arg.startsWith("--port=")) {
|
|
4231
|
+
options.port = parsePort(arg.slice("--port=".length));
|
|
4232
|
+
options.portFixed = true;
|
|
4233
|
+
continue;
|
|
4234
|
+
}
|
|
4235
|
+
if (arg === "--example") {
|
|
4236
|
+
const value = args[index + 1];
|
|
4237
|
+
if (!value || value.startsWith("-")) {
|
|
4238
|
+
throw new Error("--example requires a value.");
|
|
4239
|
+
}
|
|
4240
|
+
options.example = value;
|
|
4241
|
+
index += 1;
|
|
4242
|
+
continue;
|
|
4243
|
+
}
|
|
4244
|
+
if (arg.startsWith("--example=")) {
|
|
4245
|
+
options.example = arg.slice("--example=".length);
|
|
4246
|
+
continue;
|
|
4247
|
+
}
|
|
4248
|
+
if (arg.startsWith("-")) {
|
|
4249
|
+
throw new Error(`Unknown option: ${arg}`);
|
|
4250
|
+
}
|
|
4251
|
+
if (options.projectFile !== void 0) {
|
|
4252
|
+
throw new Error(`Unexpected argument: ${arg}`);
|
|
4253
|
+
}
|
|
4254
|
+
options.projectFile = arg;
|
|
4255
|
+
}
|
|
4256
|
+
return options;
|
|
4257
|
+
}
|
|
4258
|
+
async function handleExportCommand(args) {
|
|
4259
|
+
const options = parseExportArgs(args);
|
|
4260
|
+
if (options.help) {
|
|
4261
|
+
printExportHelp();
|
|
4262
|
+
return;
|
|
4263
|
+
}
|
|
4264
|
+
const projectFile = resolveProjectFile(options);
|
|
4265
|
+
const project = await readProject(projectFile);
|
|
4266
|
+
const outDir = resolve2(process.cwd(), options.out ?? `${projectFileStem(projectFile)}-svg`);
|
|
4267
|
+
const usedNames = /* @__PURE__ */ new Map();
|
|
4268
|
+
if (options.clean) {
|
|
4269
|
+
await rm(outDir, { recursive: true, force: true });
|
|
4270
|
+
}
|
|
4271
|
+
await mkdir(outDir, { recursive: true });
|
|
4272
|
+
for (const page of project.pages) {
|
|
4273
|
+
const basename3 = uniqueExportFilename(fileSafeName(page.name || page.id), usedNames);
|
|
4274
|
+
await writeFile(resolve2(outDir, `${basename3}.svg`), exportToSvg(page.document), "utf8");
|
|
4275
|
+
}
|
|
4276
|
+
console.log(`\u2713 Exported ${project.pages.length} SVG file${project.pages.length === 1 ? "" : "s"} to ${outDir}`);
|
|
4277
|
+
}
|
|
4278
|
+
function parseExportArgs(args) {
|
|
4279
|
+
const options = {
|
|
4280
|
+
clean: false,
|
|
4281
|
+
example: void 0,
|
|
4282
|
+
help: false,
|
|
4283
|
+
out: void 0,
|
|
4284
|
+
projectFile: void 0
|
|
4285
|
+
};
|
|
4286
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
4287
|
+
const arg = args[index];
|
|
4288
|
+
if (arg === "--") {
|
|
4289
|
+
continue;
|
|
4290
|
+
}
|
|
4291
|
+
if (arg === "--help" || arg === "-h") {
|
|
4292
|
+
options.help = true;
|
|
4293
|
+
continue;
|
|
4294
|
+
}
|
|
4295
|
+
if (arg === "--clean") {
|
|
4296
|
+
options.clean = true;
|
|
4297
|
+
continue;
|
|
4298
|
+
}
|
|
4299
|
+
if (arg === "--out") {
|
|
4300
|
+
const value = args[index + 1];
|
|
4301
|
+
if (!value || value.startsWith("-")) {
|
|
4302
|
+
throw new Error("--out requires a value.");
|
|
4303
|
+
}
|
|
4304
|
+
options.out = value;
|
|
4305
|
+
index += 1;
|
|
4306
|
+
continue;
|
|
4307
|
+
}
|
|
4308
|
+
if (arg.startsWith("--out=")) {
|
|
4309
|
+
options.out = arg.slice("--out=".length);
|
|
4310
|
+
continue;
|
|
4311
|
+
}
|
|
4312
|
+
if (arg === "--example") {
|
|
4313
|
+
const value = args[index + 1];
|
|
4314
|
+
if (!value || value.startsWith("-")) {
|
|
4315
|
+
throw new Error("--example requires a value.");
|
|
4316
|
+
}
|
|
4317
|
+
options.example = value;
|
|
4318
|
+
index += 1;
|
|
4319
|
+
continue;
|
|
4320
|
+
}
|
|
4321
|
+
if (arg.startsWith("--example=")) {
|
|
4322
|
+
options.example = arg.slice("--example=".length);
|
|
4323
|
+
continue;
|
|
4324
|
+
}
|
|
4325
|
+
if (arg.startsWith("-")) {
|
|
4326
|
+
throw new Error(`Unknown export option: ${arg}`);
|
|
4327
|
+
}
|
|
4328
|
+
if (options.projectFile !== void 0) {
|
|
4329
|
+
throw new Error(`Unexpected export argument: ${arg}`);
|
|
4330
|
+
}
|
|
4331
|
+
options.projectFile = arg;
|
|
4332
|
+
}
|
|
4333
|
+
return options;
|
|
4334
|
+
}
|
|
4335
|
+
async function readProject(projectFile) {
|
|
4336
|
+
const project = JSON.parse(await readFile(projectFile, "utf8"));
|
|
4337
|
+
if (!isGlyphSmithProject(project)) {
|
|
4338
|
+
throw new Error(`Invalid GlyphSmith project: ${projectFile}`);
|
|
4339
|
+
}
|
|
4340
|
+
return project;
|
|
4341
|
+
}
|
|
4342
|
+
function projectFileStem(projectFile) {
|
|
4343
|
+
return basename2(projectFile).replace(/\.gs\.json$/i, "") || "glyphsmith-project";
|
|
4344
|
+
}
|
|
4345
|
+
function fileSafeName(value) {
|
|
4346
|
+
return value.trim().replace(/[^a-z0-9-_]+/gi, "-").replace(/^-+|-+$/g, "") || "glyphsmith";
|
|
4347
|
+
}
|
|
4348
|
+
function uniqueExportFilename(basename3, usedNames) {
|
|
4349
|
+
const count = usedNames.get(basename3) ?? 0;
|
|
4350
|
+
usedNames.set(basename3, count + 1);
|
|
4351
|
+
return count === 0 ? basename3 : `${basename3}-${count + 1}`;
|
|
4352
|
+
}
|
|
4353
|
+
async function handleMcpCommand(args) {
|
|
4354
|
+
const [action, target] = args;
|
|
4355
|
+
if (!action || action === "-h" || action === "--help") {
|
|
4356
|
+
console.log(`Usage:
|
|
4357
|
+
glyphsmith mcp install <codex|claude> --url <mcp-url> [--project <project-dir>]`);
|
|
4358
|
+
return;
|
|
4359
|
+
}
|
|
4360
|
+
if (action !== "install") {
|
|
4361
|
+
throw new Error(`Unknown mcp command: ${action}`);
|
|
4362
|
+
}
|
|
4363
|
+
const url = optionValue(args, "--url");
|
|
4364
|
+
if (!url) {
|
|
4365
|
+
throw new Error("Missing MCP URL. Usage: glyphsmith mcp install <codex|claude> --url <mcp-url>");
|
|
4366
|
+
}
|
|
4367
|
+
if (target === "codex") {
|
|
4368
|
+
const path = await installCodexMcpConfig(url);
|
|
4369
|
+
console.log(`Codex MCP configured for GlyphSmith (${path})`);
|
|
4370
|
+
return;
|
|
4371
|
+
}
|
|
4372
|
+
if (target === "claude") {
|
|
4373
|
+
const projectPath = optionValue(args, "--project");
|
|
4374
|
+
const path = await installClaudeMcpConfig(url, projectPath ? resolve2(process.cwd(), projectPath) : void 0);
|
|
4375
|
+
console.log(`Claude Code MCP configured for GlyphSmith (${path})`);
|
|
4376
|
+
return;
|
|
4377
|
+
}
|
|
4378
|
+
throw new Error("Missing MCP target. Usage: glyphsmith mcp install <codex|claude> --url <mcp-url>");
|
|
4379
|
+
}
|
|
4380
|
+
async function handleSkillsCommand(args) {
|
|
4381
|
+
const [action, target] = args;
|
|
4382
|
+
if (!action || action === "-h" || action === "--help") {
|
|
4383
|
+
console.log(`Usage:
|
|
4384
|
+
glyphsmith skills install <codex|claude> [--project <project-dir>] [--dest <skills-dir>] [--force]`);
|
|
4385
|
+
return;
|
|
4386
|
+
}
|
|
4387
|
+
if (action !== "install") {
|
|
4388
|
+
throw new Error(`Unknown skills command: ${action}`);
|
|
4389
|
+
}
|
|
4390
|
+
const destination = resolveSkillsDestination(target, {
|
|
4391
|
+
dest: optionValue(args, "--dest"),
|
|
4392
|
+
project: optionValue(args, "--project")
|
|
4393
|
+
});
|
|
4394
|
+
const source = await resolveSkillsSource();
|
|
4395
|
+
const force = args.includes("--force");
|
|
4396
|
+
const result = await installSkills(source, destination, force);
|
|
4397
|
+
const installedSummary = result.installed.length ? result.installed.join(", ") : "none";
|
|
4398
|
+
const skippedSummary = result.skipped.length ? `; skipped existing: ${result.skipped.join(", ")}` : "";
|
|
4399
|
+
console.log(`GlyphSmith skills installed for ${target} (${destination})`);
|
|
4400
|
+
console.log(`Installed: ${installedSummary}${skippedSummary}`);
|
|
4401
|
+
if (result.skipped.length) {
|
|
4402
|
+
console.log("Use --force to replace existing GlyphSmith skills.");
|
|
4403
|
+
}
|
|
4404
|
+
}
|
|
4405
|
+
function resolveSkillsDestination(target, options) {
|
|
4406
|
+
if (target !== "codex" && target !== "claude") {
|
|
4407
|
+
throw new Error("Missing skills target. Usage: glyphsmith skills install <codex|claude>");
|
|
4408
|
+
}
|
|
4409
|
+
if (options.dest) {
|
|
4410
|
+
return resolve2(process.cwd(), options.dest);
|
|
4411
|
+
}
|
|
4412
|
+
if (target === "codex") {
|
|
4413
|
+
return resolve2(process.env.CODEX_HOME || resolve2(homedir(), ".codex"), "skills");
|
|
4414
|
+
}
|
|
4415
|
+
if (target === "claude") {
|
|
4416
|
+
if (options.project) {
|
|
4417
|
+
return resolve2(process.cwd(), options.project, ".claude", "skills");
|
|
4418
|
+
}
|
|
4419
|
+
return resolve2(process.env.CLAUDE_HOME || resolve2(homedir(), ".claude"), "skills");
|
|
4420
|
+
}
|
|
4421
|
+
throw new Error("Missing skills target. Usage: glyphsmith skills install <codex|claude>");
|
|
4422
|
+
}
|
|
4423
|
+
async function resolveSkillsSource() {
|
|
4424
|
+
const candidates = [
|
|
4425
|
+
resolve2(cliDirectory, "../../..", "skills"),
|
|
4426
|
+
resolve2(cliDirectory, "..", "skills"),
|
|
4427
|
+
resolve2(cliDirectory, "skills")
|
|
4428
|
+
];
|
|
4429
|
+
for (const candidate of candidates) {
|
|
4430
|
+
if ((await listSkillDirectories(candidate)).length) {
|
|
4431
|
+
return candidate;
|
|
4432
|
+
}
|
|
4433
|
+
}
|
|
4434
|
+
throw new Error("GlyphSmith skills directory was not found.");
|
|
4435
|
+
}
|
|
4436
|
+
async function installSkills(source, destination, force) {
|
|
4437
|
+
const skills = await listSkillDirectories(source);
|
|
4438
|
+
const installed = [];
|
|
4439
|
+
const skipped = [];
|
|
4440
|
+
await mkdir(destination, { recursive: true });
|
|
4441
|
+
for (const skillPath of skills) {
|
|
4442
|
+
const name = basename2(skillPath);
|
|
4443
|
+
const destinationPath = resolve2(destination, name);
|
|
4444
|
+
if (await pathExists(destinationPath)) {
|
|
4445
|
+
if (!force) {
|
|
4446
|
+
skipped.push(name);
|
|
4447
|
+
continue;
|
|
4448
|
+
}
|
|
4449
|
+
await rm(destinationPath, { recursive: true, force: true });
|
|
4450
|
+
}
|
|
4451
|
+
await cp(skillPath, destinationPath, { recursive: true });
|
|
4452
|
+
installed.push(name);
|
|
4453
|
+
}
|
|
4454
|
+
return { installed, skipped };
|
|
4455
|
+
}
|
|
4456
|
+
async function listSkillDirectories(path) {
|
|
4457
|
+
try {
|
|
4458
|
+
const entries = await readdir(path, { withFileTypes: true });
|
|
4459
|
+
const directories = [];
|
|
4460
|
+
for (const entry of entries) {
|
|
4461
|
+
if (!entry.isDirectory()) {
|
|
4462
|
+
continue;
|
|
4463
|
+
}
|
|
4464
|
+
const skillPath = resolve2(path, entry.name);
|
|
4465
|
+
if (await pathExists(resolve2(skillPath, "SKILL.md"))) {
|
|
4466
|
+
directories.push(skillPath);
|
|
4467
|
+
}
|
|
4468
|
+
}
|
|
4469
|
+
return directories.sort((a, b) => basename2(a).localeCompare(basename2(b)));
|
|
4470
|
+
} catch (error) {
|
|
4471
|
+
if (isNodeError(error) && error.code === "ENOENT") {
|
|
4472
|
+
return [];
|
|
4473
|
+
}
|
|
4474
|
+
throw error;
|
|
4475
|
+
}
|
|
4476
|
+
}
|
|
4477
|
+
function optionValue(args, name) {
|
|
4478
|
+
const index = args.indexOf(name);
|
|
4479
|
+
if (index === -1) {
|
|
4480
|
+
return void 0;
|
|
4481
|
+
}
|
|
4482
|
+
return args[index + 1];
|
|
4483
|
+
}
|
|
4484
|
+
async function installCodexMcpConfig(url) {
|
|
4485
|
+
if (commandHelpIncludes("codex", ["mcp", "add", "--help"], "--url")) {
|
|
4486
|
+
commandOutputIgnored("codex", ["mcp", "remove", "glyphsmith"]);
|
|
4487
|
+
commandOutput("codex", ["mcp", "add", "glyphsmith", "--url", url]);
|
|
4488
|
+
}
|
|
4489
|
+
const path = resolve2(process.env.CODEX_HOME || resolve2(homedir(), ".codex"), "config.toml");
|
|
4490
|
+
const content = await readOptionalTextFile(path);
|
|
4491
|
+
let nextContent = upsertTomlTable(
|
|
4492
|
+
content,
|
|
4493
|
+
"mcp_servers.glyphsmith",
|
|
4494
|
+
`enabled = true
|
|
4495
|
+
url = ${JSON.stringify(url)}`
|
|
4496
|
+
);
|
|
4497
|
+
for (const tool of mcpTools()) {
|
|
4498
|
+
nextContent = upsertTomlTable(
|
|
4499
|
+
nextContent,
|
|
4500
|
+
`mcp_servers.glyphsmith.tools.${tool.name}`,
|
|
4501
|
+
`approval_mode = "approve"`
|
|
4502
|
+
);
|
|
4503
|
+
}
|
|
4504
|
+
await writeTextFile(path, nextContent);
|
|
4505
|
+
return path;
|
|
4506
|
+
}
|
|
4507
|
+
async function installClaudeMcpConfig(url, projectPath) {
|
|
4508
|
+
if (commandHelpIncludes("claude", ["mcp", "add", "--help"], "--transport") && commandHelpIncludes("claude", ["mcp", "add", "--help"], "--scope")) {
|
|
4509
|
+
commandOutputIgnored("claude", ["mcp", "remove", "--scope", "user", "glyphsmith"]);
|
|
4510
|
+
commandOutput("claude", ["mcp", "add", "--scope", "user", "--transport", "http", "glyphsmith", url]);
|
|
4511
|
+
return "Claude Code user scope";
|
|
4512
|
+
}
|
|
4513
|
+
if (!projectPath) {
|
|
4514
|
+
throw new Error("Claude Code CLI MCP command is unavailable. Pass --project <project-dir> to write .mcp.json.");
|
|
4515
|
+
}
|
|
4516
|
+
const path = resolve2(projectPath, ".mcp.json");
|
|
4517
|
+
const content = await readOptionalTextFile(path);
|
|
4518
|
+
const root = content.trim() ? JSON.parse(content) : {};
|
|
4519
|
+
const nextRoot = root && typeof root === "object" && !Array.isArray(root) ? root : {};
|
|
4520
|
+
const existingServers = nextRoot.mcpServers;
|
|
4521
|
+
const servers = existingServers && typeof existingServers === "object" && !Array.isArray(existingServers) ? existingServers : {};
|
|
4522
|
+
servers.glyphsmith = { url };
|
|
4523
|
+
nextRoot.mcpServers = servers;
|
|
4524
|
+
await writeTextFile(path, `${JSON.stringify(nextRoot, null, 2)}
|
|
4525
|
+
`);
|
|
4526
|
+
return path;
|
|
4527
|
+
}
|
|
4528
|
+
function commandHelpIncludes(command, args, needle) {
|
|
4529
|
+
try {
|
|
4530
|
+
return commandOutput(command, args).includes(needle);
|
|
4531
|
+
} catch {
|
|
4532
|
+
return false;
|
|
4533
|
+
}
|
|
4534
|
+
}
|
|
4535
|
+
function commandOutput(command, args) {
|
|
4536
|
+
return execFileSync(command, args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
|
|
4537
|
+
}
|
|
4538
|
+
function commandOutputIgnored(command, args) {
|
|
4539
|
+
try {
|
|
4540
|
+
execFileSync(command, args, { stdio: "ignore" });
|
|
4541
|
+
} catch {
|
|
4542
|
+
}
|
|
4543
|
+
}
|
|
4544
|
+
async function readOptionalTextFile(path) {
|
|
4545
|
+
try {
|
|
4546
|
+
return await readFile(path, "utf8");
|
|
4547
|
+
} catch (error) {
|
|
4548
|
+
if (isNodeError(error) && error.code === "ENOENT") {
|
|
4549
|
+
return "";
|
|
4550
|
+
}
|
|
4551
|
+
throw error;
|
|
4552
|
+
}
|
|
4553
|
+
}
|
|
4554
|
+
async function pathExists(path) {
|
|
4555
|
+
try {
|
|
4556
|
+
await stat2(path);
|
|
4557
|
+
return true;
|
|
4558
|
+
} catch (error) {
|
|
4559
|
+
if (isNodeError(error) && error.code === "ENOENT") {
|
|
4560
|
+
return false;
|
|
4561
|
+
}
|
|
4562
|
+
throw error;
|
|
4563
|
+
}
|
|
4564
|
+
}
|
|
4565
|
+
async function writeTextFile(path, content) {
|
|
4566
|
+
await mkdir(resolve2(path, ".."), { recursive: true });
|
|
4567
|
+
await writeFile(path, content, "utf8");
|
|
4568
|
+
}
|
|
4569
|
+
function upsertTomlTable(content, table, body) {
|
|
4570
|
+
const header = `[${table}]`;
|
|
4571
|
+
const lines = content.split(/\r?\n/);
|
|
4572
|
+
const start = lines.findIndex((line) => line.trim() === header);
|
|
4573
|
+
if (start === -1) {
|
|
4574
|
+
const prefix = content.trimEnd();
|
|
4575
|
+
return `${prefix}${prefix ? "\n\n" : ""}${header}
|
|
4576
|
+
${body}
|
|
4577
|
+
`;
|
|
4578
|
+
}
|
|
4579
|
+
let end = start + 1;
|
|
4580
|
+
while (end < lines.length && !/^\s*\[.+]\s*$/.test(lines[end] ?? "")) {
|
|
4581
|
+
end += 1;
|
|
4582
|
+
}
|
|
4583
|
+
const nextLines = [...lines.slice(0, start), header, body, ...lines.slice(end)];
|
|
4584
|
+
return `${nextLines.join("\n").trimEnd()}
|
|
4585
|
+
`;
|
|
4586
|
+
}
|
|
4587
|
+
function isNodeError(error) {
|
|
4588
|
+
return error instanceof Error && "code" in error;
|
|
4589
|
+
}
|
|
4590
|
+
function nextPort(port) {
|
|
4591
|
+
const next = Number(port) + 1;
|
|
4592
|
+
if (next > 65535) {
|
|
4593
|
+
throw new Error(`Cannot derive host port from UI port: ${port}`);
|
|
4594
|
+
}
|
|
4595
|
+
return String(next);
|
|
4596
|
+
}
|
|
4597
|
+
function parsePort(value) {
|
|
4598
|
+
if (!/^\d+$/.test(value)) {
|
|
4599
|
+
throw new Error(`Invalid port: ${value}`);
|
|
4600
|
+
}
|
|
4601
|
+
const port = Number(value);
|
|
4602
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
4603
|
+
throw new Error(`Invalid port: ${value}`);
|
|
4604
|
+
}
|
|
4605
|
+
return String(port);
|
|
4606
|
+
}
|
|
4607
|
+
function printHelp() {
|
|
4608
|
+
console.log(`GlyphSmith
|
|
4609
|
+
|
|
4610
|
+
Usage:
|
|
4611
|
+
glyphsmith [project]
|
|
4612
|
+
glyphsmith host [project]
|
|
4613
|
+
glyphsmith host --example <name>
|
|
4614
|
+
glyphsmith init [project]
|
|
4615
|
+
glyphsmith export [project] [--out <dir>] [--clean]
|
|
4616
|
+
glyphsmith export --example <name> [--out <dir>] [--clean]
|
|
4617
|
+
glyphsmith mcp install <codex|claude> --url <mcp-url> [--project <project-dir>]
|
|
4618
|
+
glyphsmith skills install <codex|claude> [--project <project-dir>] [--force]
|
|
4619
|
+
|
|
4620
|
+
Project paths may omit .gs.json:
|
|
4621
|
+
glyphsmith logo -> logo.gs.json
|
|
4622
|
+
glyphsmith logo.gs.json
|
|
4623
|
+
|
|
4624
|
+
Options:
|
|
4625
|
+
--port <port> Web UI port for open mode. Host/MCP port for host mode.
|
|
4626
|
+
Defaults to ${DEFAULT_PORT} for open mode and ${DEFAULT_HOST_PORT} for host mode.
|
|
4627
|
+
--example <name> Use examples/<name>.gs.json.
|
|
4628
|
+
|
|
4629
|
+
Explicit --port values are always treated as fixed ports.
|
|
4630
|
+
`);
|
|
4631
|
+
}
|
|
4632
|
+
function printExportHelp() {
|
|
4633
|
+
console.log(`GlyphSmith SVG Export
|
|
4634
|
+
|
|
4635
|
+
Usage:
|
|
4636
|
+
glyphsmith export [project] [--out <dir>] [--clean]
|
|
4637
|
+
glyphsmith export --example <name> [--out <dir>] [--clean]
|
|
4638
|
+
|
|
4639
|
+
Options:
|
|
4640
|
+
--out <dir> Output directory. Defaults to <project-stem>-svg.
|
|
4641
|
+
--clean Remove the output directory before writing SVG files.
|
|
4642
|
+
--example <name> Export examples/<name>.gs.json.
|
|
4643
|
+
`);
|
|
4644
|
+
}
|
|
4645
|
+
try {
|
|
4646
|
+
await main();
|
|
4647
|
+
} catch (error) {
|
|
4648
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
4649
|
+
process.exitCode = 1;
|
|
4650
|
+
}
|
|
4651
|
+
//# sourceMappingURL=index.js.map
|