@brimsites/brimjs 0.0.0-stage → 1.0.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 +110 -0
- package/README.md +22 -2
- package/bin/brim.js +5 -0
- package/dist/cli.js +3802 -0
- package/editor-dist/editor.css +1 -0
- package/editor-dist/editor.js +91 -0
- package/package.json +71 -3
- package/skills/brim-convert/SKILL.md +256 -0
- package/skills/brim-hosting/SKILL.md +221 -0
- package/src/astro-shim.d.ts +5 -0
- package/src/auth/accounts.ts +341 -0
- package/src/auth/password.ts +34 -0
- package/src/auth/permissions.ts +44 -0
- package/src/blocks/accordion/Accordion.astro +48 -0
- package/src/blocks/accordion/accordion.css +63 -0
- package/src/blocks/analytics/Analytics.astro +45 -0
- package/src/blocks/analytics/ConsentBanner.astro +41 -0
- package/src/blocks/analytics/analytics.client.ts +125 -0
- package/src/blocks/analytics/analytics.css +51 -0
- package/src/blocks/analytics/consent.ts +51 -0
- package/src/blocks/button/Button.astro +64 -0
- package/src/blocks/button/button.css +100 -0
- package/src/blocks/carousel/Carousel.astro +140 -0
- package/src/blocks/carousel/carousel.client.ts +153 -0
- package/src/blocks/carousel/carousel.css +181 -0
- package/src/blocks/data/icons.ts +285 -0
- package/src/blocks/data/image-shapes.ts +91 -0
- package/src/blocks/data/social-icons.ts +41 -0
- package/src/blocks/data/social-networks.ts +256 -0
- package/src/blocks/divider/Divider.astro +27 -0
- package/src/blocks/divider/divider.css +17 -0
- package/src/blocks/form/Captcha.astro +27 -0
- package/src/blocks/form/Form.astro +250 -0
- package/src/blocks/form/FormField.astro +138 -0
- package/src/blocks/form/Newsletter.astro +80 -0
- package/src/blocks/form/form.client.ts +339 -0
- package/src/blocks/form/form.css +271 -0
- package/src/blocks/gallery/ImageGallery.astro +126 -0
- package/src/blocks/gallery/gallery.css +43 -0
- package/src/blocks/gallery/lightbox.client.ts +178 -0
- package/src/blocks/gallery/lightbox.css +134 -0
- package/src/blocks/icon/Icon.astro +41 -0
- package/src/blocks/icon/icon.css +16 -0
- package/src/blocks/image/Image.astro +158 -0
- package/src/blocks/image/image.css +42 -0
- package/src/blocks/images.ts +64 -0
- package/src/blocks/in-editor.client.ts +8 -0
- package/src/blocks/listing/Listing.astro +288 -0
- package/src/blocks/listing/ListingCards.astro +48 -0
- package/src/blocks/listing/listing.css +136 -0
- package/src/blocks/listing/query.ts +363 -0
- package/src/blocks/map/Map.astro +75 -0
- package/src/blocks/map/map.css +32 -0
- package/src/blocks/schemas/accordion.ts +118 -0
- package/src/blocks/schemas/button.ts +78 -0
- package/src/blocks/schemas/carousel.ts +133 -0
- package/src/blocks/schemas/divider.ts +29 -0
- package/src/blocks/schemas/form-field-types.ts +29 -0
- package/src/blocks/schemas/form.ts +350 -0
- package/src/blocks/schemas/icon.ts +24 -0
- package/src/blocks/schemas/image-gallery.ts +54 -0
- package/src/blocks/schemas/image.ts +87 -0
- package/src/blocks/schemas/index.ts +33 -0
- package/src/blocks/schemas/listing.ts +14 -0
- package/src/blocks/schemas/map.ts +81 -0
- package/src/blocks/schemas/newsletter.ts +324 -0
- package/src/blocks/schemas/social-media.ts +348 -0
- package/src/blocks/schemas/text.ts +151 -0
- package/src/blocks/schemas/video.ts +57 -0
- package/src/blocks/search/Search.astro +147 -0
- package/src/blocks/search/search.css +69 -0
- package/src/blocks/search/state.ts +28 -0
- package/src/blocks/settings.ts +94 -0
- package/src/blocks/social/SocialMedia.astro +102 -0
- package/src/blocks/social/social-links.ts +16 -0
- package/src/blocks/social/social.css +31 -0
- package/src/blocks/theme.ts +35 -0
- package/src/blocks/types.ts +52 -0
- package/src/blocks/video/Video.astro +90 -0
- package/src/blocks/video/video-source.ts +77 -0
- package/src/blocks/video/video.client.ts +43 -0
- package/src/blocks/video/video.css +29 -0
- package/src/check.ts +1119 -0
- package/src/cli.ts +493 -0
- package/src/components/Blocks.astro +68 -0
- package/src/components/Field.astro +61 -0
- package/src/components/Footer.astro +36 -0
- package/src/components/Link.astro +18 -0
- package/src/components/MobileMenu.astro +77 -0
- package/src/components/Navbar.astro +42 -0
- package/src/components/RichText.astro +32 -0
- package/src/components/Seo.astro +202 -0
- package/src/components/Setting.astro +46 -0
- package/src/components/Shared.astro +17 -0
- package/src/components/Text.astro +91 -0
- package/src/components/blocks.css +86 -0
- package/src/components/index.ts +27 -0
- package/src/components/mobile-menu.client.ts +21 -0
- package/src/components/mobile-menu.css +52 -0
- package/src/components/text.css +48 -0
- package/src/config.ts +413 -0
- package/src/content/block-layout.ts +63 -0
- package/src/content/block-values.ts +48 -0
- package/src/content/content-check.ts +174 -0
- package/src/content/content-types.ts +408 -0
- package/src/content/drafts.ts +115 -0
- package/src/content/feed.ts +237 -0
- package/src/content/field-types.ts +107 -0
- package/src/content/history.ts +140 -0
- package/src/content/ids.ts +50 -0
- package/src/content/image-size.ts +212 -0
- package/src/content/image-sizes.ts +126 -0
- package/src/content/item-fields.ts +110 -0
- package/src/content/item-head.ts +126 -0
- package/src/content/item-image.ts +26 -0
- package/src/content/item-path.ts +122 -0
- package/src/content/items.ts +580 -0
- package/src/content/language-scopes.ts +40 -0
- package/src/content/media.ts +271 -0
- package/src/content/menus.ts +51 -0
- package/src/content/page-templates.ts +52 -0
- package/src/content/redirects.ts +112 -0
- package/src/content/references.ts +165 -0
- package/src/content/rich-text.ts +63 -0
- package/src/content/search.ts +167 -0
- package/src/content/seed.ts +229 -0
- package/src/content/site-settings.ts +111 -0
- package/src/content/sitemap.ts +143 -0
- package/src/content/store.ts +225 -0
- package/src/content/tags.ts +67 -0
- package/src/content/text-default.ts +139 -0
- package/src/content/types.ts +137 -0
- package/src/content/validate.ts +253 -0
- package/src/content/validation-error.ts +2 -0
- package/src/db/cached.ts +140 -0
- package/src/db/database.ts +15 -0
- package/src/db/libsql.ts +29 -0
- package/src/db/schema.ts +189 -0
- package/src/db/url.ts +44 -0
- package/src/editor/client/BlockSettings.tsx +1063 -0
- package/src/editor/client/Chrome.tsx +284 -0
- package/src/editor/client/ContentBrowser.tsx +1299 -0
- package/src/editor/client/Editor.tsx +1756 -0
- package/src/editor/client/HistoryPanel.tsx +114 -0
- package/src/editor/client/ImagesWidget.tsx +113 -0
- package/src/editor/client/Inspector.tsx +127 -0
- package/src/editor/client/ItemForm.tsx +535 -0
- package/src/editor/client/LinkWidget.tsx +440 -0
- package/src/editor/client/ListingPanel.tsx +99 -0
- package/src/editor/client/Login.tsx +338 -0
- package/src/editor/client/Menu.tsx +64 -0
- package/src/editor/client/PageSettings.tsx +270 -0
- package/src/editor/client/RedirectsSettings.tsx +130 -0
- package/src/editor/client/Resize.tsx +204 -0
- package/src/editor/client/Sidebar.tsx +51 -0
- package/src/editor/client/SiteMap.tsx +568 -0
- package/src/editor/client/SiteSettings.tsx +409 -0
- package/src/editor/client/TextTools.tsx +391 -0
- package/src/editor/client/Toolbar.tsx +449 -0
- package/src/editor/client/VideoUpload.tsx +251 -0
- package/src/editor/client/api.ts +417 -0
- package/src/editor/client/brand.ts +20 -0
- package/src/editor/client/connection.ts +98 -0
- package/src/editor/client/context.ts +19 -0
- package/src/editor/client/css.d.ts +2 -0
- package/src/editor/client/editor.css +4656 -0
- package/src/editor/client/fields.tsx +812 -0
- package/src/editor/client/icons.tsx +174 -0
- package/src/editor/client/keys.ts +15 -0
- package/src/editor/client/kinds.ts +289 -0
- package/src/editor/client/languages.ts +32 -0
- package/src/editor/client/main.tsx +100 -0
- package/src/editor/client/responses.ts +26 -0
- package/src/editor/client/rich-text.ts +326 -0
- package/src/editor/client/site-tree.ts +239 -0
- package/src/editor/client/theme.ts +55 -0
- package/src/editor/client/tsconfig.json +18 -0
- package/src/editor/client/tus.ts +137 -0
- package/src/editor/client/use-rect.ts +50 -0
- package/src/editor/client/widgets.tsx +1218 -0
- package/src/forms/captcha.ts +83 -0
- package/src/forms/define.ts +166 -0
- package/src/forms/fields.ts +197 -0
- package/src/forms/file-types.ts +108 -0
- package/src/forms/files.ts +216 -0
- package/src/forms/form-page.ts +9 -0
- package/src/forms/handler.ts +622 -0
- package/src/forms/spec.ts +89 -0
- package/src/forms/store.ts +96 -0
- package/src/forms/work.ts +50 -0
- package/src/icons/library.ts +144 -0
- package/src/icons/load.ts +63 -0
- package/src/index.ts +99 -0
- package/src/init.ts +257 -0
- package/src/integration.ts +469 -0
- package/src/mail/mailer.ts +197 -0
- package/src/mail/notify.ts +272 -0
- package/src/mail/settings.ts +173 -0
- package/src/mail/templates.ts +191 -0
- package/src/mcp/page-nodes.ts +209 -0
- package/src/mcp/server.ts +111 -0
- package/src/mcp/tools.ts +637 -0
- package/src/runtime/TemplatePage.astro +39 -0
- package/src/runtime/TemplatePageStatic.astro +13 -0
- package/src/runtime/admin-route.ts +80 -0
- package/src/runtime/connect.ts +53 -0
- package/src/runtime/content.ts +188 -0
- package/src/runtime/context.ts +131 -0
- package/src/runtime/form-files.ts +18 -0
- package/src/runtime/forms-route.ts +33 -0
- package/src/runtime/forms.ts +28 -0
- package/src/runtime/icons.ts +5 -0
- package/src/runtime/media.ts +175 -0
- package/src/runtime/middleware.ts +186 -0
- package/src/runtime/nav.ts +13 -0
- package/src/runtime/query-reads.ts +49 -0
- package/src/runtime/query-store.ts +16 -0
- package/src/runtime/request-state.ts +69 -0
- package/src/runtime/robots.ts +29 -0
- package/src/runtime/rss-static.ts +16 -0
- package/src/runtime/rss.ts +29 -0
- package/src/runtime/server.ts +29 -0
- package/src/runtime/sitemap.ts +34 -0
- package/src/runtime/template-paths.ts +34 -0
- package/src/runtime/uploads-route.ts +13 -0
- package/src/seed-cli.ts +253 -0
- package/src/server/auth.ts +31 -0
- package/src/server/fetch-image.ts +219 -0
- package/src/server/handler.ts +2106 -0
- package/src/server/http.ts +162 -0
- package/src/server/locales.ts +73 -0
- package/src/server/node.ts +57 -0
- package/src/server/query-params.ts +249 -0
- package/src/server/rate-limit.ts +72 -0
- package/src/server/video-host.ts +162 -0
- package/src/starter.ts +70 -0
- package/src/version.ts +4 -0
- package/src/virtual.d.ts +65 -0
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import type { InlineMark, InlineNode } from "../content/types.ts";
|
|
2
|
+
|
|
3
|
+
/** One editable element of a page, as its rendered HTML marks it while editing. */
|
|
4
|
+
export interface PageNode {
|
|
5
|
+
nodeId: string;
|
|
6
|
+
kind: string;
|
|
7
|
+
scope: string;
|
|
8
|
+
/** The text shown, for elements that hold text, with a line break as `\n`. */
|
|
9
|
+
text?: string;
|
|
10
|
+
/** For a text element with formatting (line breaks, bold, links…): the same text as Brim stores it. */
|
|
11
|
+
rich?: InlineNode[];
|
|
12
|
+
/** What the element carries: block settings, navigation, or the owner's text options. */
|
|
13
|
+
value?: unknown;
|
|
14
|
+
/** Set when the element shows a field of a content item: saving it changes that item. */
|
|
15
|
+
item?: string;
|
|
16
|
+
field?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const OPENING_TAG = /<([a-zA-Z][\w-]*)\b([^>]*\bdata-brim-node="[^"]*"[^>]*)>/g;
|
|
20
|
+
const VOID_TAGS = new Set(["img", "input", "br", "hr", "meta", "link", "source", "area", "col", "embed", "wbr"]);
|
|
21
|
+
const TEXT_KINDS = new Set(["text", "richtext", "link", "field"]);
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Lists the elements carrying `data-brim-*` markers in a page rendered by the dev server.
|
|
25
|
+
* Markers only exist while editing, never in the public build.
|
|
26
|
+
*/
|
|
27
|
+
export function pageNodes(html: string): PageNode[] {
|
|
28
|
+
const nodes = new Map<string, PageNode>();
|
|
29
|
+
for (const match of html.matchAll(OPENING_TAG)) {
|
|
30
|
+
const [whole, tag = "", attributes = ""] = match;
|
|
31
|
+
const nodeId = attribute(attributes, "data-brim-node");
|
|
32
|
+
const kind = attribute(attributes, "data-brim-kind");
|
|
33
|
+
const scope = attribute(attributes, "data-brim-scope") ?? "page";
|
|
34
|
+
if (!nodeId || !kind || nodes.has(`${scope}:${nodeId}`)) continue;
|
|
35
|
+
|
|
36
|
+
const node: PageNode = { nodeId, kind, scope };
|
|
37
|
+
const value = attribute(attributes, "data-brim-value");
|
|
38
|
+
if (value !== undefined) node.value = parseJson(value);
|
|
39
|
+
const item = attribute(attributes, "data-brim-item");
|
|
40
|
+
const field = attribute(attributes, "data-brim-field");
|
|
41
|
+
if (item && field) Object.assign(node, { item, field });
|
|
42
|
+
if (TEXT_KINDS.has(kind) && !VOID_TAGS.has(tag.toLowerCase())) {
|
|
43
|
+
const inner = innerHtml(html, tag, (match.index ?? 0) + whole.length);
|
|
44
|
+
node.text = plainText(inner);
|
|
45
|
+
const rich = kind === "text" ? inlineNodes(inner) : undefined;
|
|
46
|
+
if (rich) node.rich = rich;
|
|
47
|
+
}
|
|
48
|
+
nodes.set(`${scope}:${nodeId}`, node);
|
|
49
|
+
}
|
|
50
|
+
return [...nodes.values()];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function attribute(attributes: string, name: string): string | undefined {
|
|
54
|
+
const match = new RegExp(`\\b${name}="([^"]*)"`).exec(attributes);
|
|
55
|
+
return match?.[1] === undefined ? undefined : decodeEntities(match[1]);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The markup between an opening tag and its matching closing tag. */
|
|
59
|
+
function innerHtml(html: string, tag: string, start: number): string {
|
|
60
|
+
const tags = new RegExp(`<(/?)${tag}\\b[^>]*>`, "gi");
|
|
61
|
+
let depth = 1;
|
|
62
|
+
for (const match of html.slice(start).matchAll(tags)) {
|
|
63
|
+
depth += match[1] ? -1 : 1;
|
|
64
|
+
if (depth === 0) return html.slice(start, start + (match.index ?? 0));
|
|
65
|
+
}
|
|
66
|
+
return html.slice(start);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function plainText(markup: string): string {
|
|
70
|
+
return decodeEntities(
|
|
71
|
+
markup
|
|
72
|
+
.replace(/<(script|style)\b[\s\S]*?<\/\1>/gi, "")
|
|
73
|
+
.replace(/<br\s*\/?>/gi, "\n")
|
|
74
|
+
.replace(/<\/(p|div|h[1-6]|li|blockquote)>/gi, "\n")
|
|
75
|
+
.replace(/<[^>]*>/g, ""),
|
|
76
|
+
)
|
|
77
|
+
.replace(/[ \t]+/g, " ")
|
|
78
|
+
.replace(/ *\n */g, "\n")
|
|
79
|
+
.replace(/\n{2,}/g, "\n")
|
|
80
|
+
.trim();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function decodeEntities(text: string): string {
|
|
84
|
+
return text.replace(/&(#\d+|#x[\da-f]+|amp|lt|gt|quot|apos|nbsp);/gi, (entity, code: string) => {
|
|
85
|
+
const lower = code.toLowerCase();
|
|
86
|
+
if (lower.startsWith("#x")) return String.fromCodePoint(Number.parseInt(lower.slice(2), 16));
|
|
87
|
+
if (lower.startsWith("#")) return String.fromCodePoint(Number(lower.slice(1)));
|
|
88
|
+
return { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " }[lower] ?? entity;
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function parseJson(text: string): unknown {
|
|
93
|
+
try {
|
|
94
|
+
return JSON.parse(text);
|
|
95
|
+
} catch {
|
|
96
|
+
return text;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const MARKS: Record<string, InlineMark> = {
|
|
101
|
+
strong: "strong",
|
|
102
|
+
b: "strong",
|
|
103
|
+
em: "em",
|
|
104
|
+
i: "em",
|
|
105
|
+
u: "u",
|
|
106
|
+
s: "s",
|
|
107
|
+
strike: "s",
|
|
108
|
+
del: "s",
|
|
109
|
+
sub: "sub",
|
|
110
|
+
sup: "sup",
|
|
111
|
+
};
|
|
112
|
+
const HEX_OR_RGB = /^(#[\da-f]{3,8}|rgba?\([\d\s.,%]+\))$/i;
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The formatting of a text element's markup as Brim stores it (`rich`): line breaks, bold, italic, underline,
|
|
116
|
+
* strikethrough, sub- and superscript, links and colors. Any other element gives only its words. Nothing when the
|
|
117
|
+
* markup is plain text, so an agent sees `rich` only where there is formatting to keep.
|
|
118
|
+
*/
|
|
119
|
+
export function inlineNodes(markup: string): InlineNode[] | undefined {
|
|
120
|
+
const root: InlineNode[] = [];
|
|
121
|
+
const stack: { tag: string; children: InlineNode[] }[] = [];
|
|
122
|
+
const children = () => stack.at(-1)?.children ?? root;
|
|
123
|
+
let formatted = false;
|
|
124
|
+
const tokens = markup.replace(/<(script|style)\b[\s\S]*?<\/\1>/gi, "").split(/(<[^>]*>)/);
|
|
125
|
+
for (const token of tokens) {
|
|
126
|
+
if (token === "") continue;
|
|
127
|
+
const tag = /^<(\/?)([a-zA-Z][\w-]*)\b([^>]*)>$/.exec(token);
|
|
128
|
+
if (!tag) {
|
|
129
|
+
if (!token.startsWith("<")) pushText(children(), decodeEntities(token).replace(/\s+/g, " "));
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
const [, closing, rawName = "", attributes = ""] = tag;
|
|
133
|
+
const name = rawName.toLowerCase();
|
|
134
|
+
if (name === "br") {
|
|
135
|
+
children().push({ tag: "br", children: [] });
|
|
136
|
+
formatted = true;
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
if (closing) {
|
|
140
|
+
const index = stack.map((entry) => entry.tag).lastIndexOf(name);
|
|
141
|
+
if (index >= 0) stack.length = index;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (VOID_TAGS.has(name)) continue;
|
|
145
|
+
const node = inlineElement(name, attributes);
|
|
146
|
+
if (node) {
|
|
147
|
+
children().push(node);
|
|
148
|
+
formatted = true;
|
|
149
|
+
stack.push({ tag: name, children: node.children });
|
|
150
|
+
} else {
|
|
151
|
+
// Not formatting Brim keeps: its words join the element around it.
|
|
152
|
+
stack.push({ tag: name, children: children() });
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return formatted ? trimEnds(root) : undefined;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function inlineElement(name: string, attributes: string): Exclude<InlineNode, string> | undefined {
|
|
159
|
+
const mark = MARKS[name];
|
|
160
|
+
if (mark) return { tag: mark, children: [] };
|
|
161
|
+
if (name === "a") {
|
|
162
|
+
const href = attribute(attributes, "href");
|
|
163
|
+
return href ? { tag: "a", href, children: [] } : undefined;
|
|
164
|
+
}
|
|
165
|
+
if (name === "span") {
|
|
166
|
+
const style = attribute(attributes, "style") ?? "";
|
|
167
|
+
const color = /(?:^|;)\s*color\s*:\s*([^;]+)/i.exec(style)?.[1]?.trim();
|
|
168
|
+
const background = /background(?:-color)?\s*:\s*([^;]+)/i.exec(style)?.[1]?.trim();
|
|
169
|
+
const span = {
|
|
170
|
+
tag: "span" as const,
|
|
171
|
+
...(color && HEX_OR_RGB.test(color) && { color }),
|
|
172
|
+
...(background && HEX_OR_RGB.test(background) && { background }),
|
|
173
|
+
children: [],
|
|
174
|
+
};
|
|
175
|
+
return span.color || span.background ? span : undefined;
|
|
176
|
+
}
|
|
177
|
+
return undefined;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function pushText(list: InlineNode[], text: string): void {
|
|
181
|
+
if (text === "") return;
|
|
182
|
+
const last = list.at(-1);
|
|
183
|
+
if (typeof last === "string") list[list.length - 1] = last + text;
|
|
184
|
+
else list.push(text);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Whitespace at the very start and end of the element is the code's indentation, not the owner's words. */
|
|
188
|
+
function trimEnds(nodes: InlineNode[]): InlineNode[] {
|
|
189
|
+
const first = nodes[0];
|
|
190
|
+
if (typeof first === "string") nodes[0] = first.replace(/^\s+/, "");
|
|
191
|
+
const last = nodes.at(-1);
|
|
192
|
+
if (typeof last === "string") nodes[nodes.length - 1] = last.replace(/\s+$/, "");
|
|
193
|
+
return nodes.filter((node) => node !== "");
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Plain text with line breaks as Brim stores it: `Un spațiu.\nDe la primul pas` gives two lines. */
|
|
197
|
+
export function textWithBreaks(text: string): InlineNode[] {
|
|
198
|
+
const lines = text.replace(/\r\n?/g, "\n").split("\n");
|
|
199
|
+
return lines
|
|
200
|
+
.flatMap((line, index) => (index === 0 ? [line] : [{ tag: "br" as const, children: [] }, line]))
|
|
201
|
+
.filter((node) => node !== "");
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** What a formatted text reads as, with a line break for each `br`: the `text` saved beside `rich`. */
|
|
205
|
+
export function readingOf(nodes: InlineNode[]): string {
|
|
206
|
+
return nodes
|
|
207
|
+
.map((node) => (typeof node === "string" ? node : node.tag === "br" ? "\n" : readingOf(node.children)))
|
|
208
|
+
.join("");
|
|
209
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { HttpError, readBytes } from "../server/http.ts";
|
|
2
|
+
import { VERSION } from "../version.ts";
|
|
3
|
+
import { INSTRUCTIONS, TOOLS, type ToolContext } from "./tools.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The site's MCP endpoint (`/admin/mcp`): JSON-RPC over HTTP POST, the "streamable HTTP" transport
|
|
7
|
+
* without server-sent events. Each request answers with JSON. The caller has already checked the token.
|
|
8
|
+
*/
|
|
9
|
+
const PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];
|
|
10
|
+
/** A call carries at most an item or a page element; the API it reaches takes 64 KB each. */
|
|
11
|
+
const MAX_BODY_BYTES = 1024 * 1024;
|
|
12
|
+
const SERVER_INFO = { name: "brimjs", title: "Brim.js site", version: VERSION };
|
|
13
|
+
|
|
14
|
+
interface Message {
|
|
15
|
+
jsonrpc?: unknown;
|
|
16
|
+
id?: string | number | null;
|
|
17
|
+
method?: unknown;
|
|
18
|
+
params?: Record<string, unknown>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Requests one batch may hold; more is refused, so one body cannot start thousands of tool calls. */
|
|
22
|
+
const MAX_BATCH = 20;
|
|
23
|
+
|
|
24
|
+
export async function handleMcp(request: Request, context: ToolContext): Promise<Response> {
|
|
25
|
+
if (request.method !== "POST") {
|
|
26
|
+
return new Response(null, { status: 405, headers: { allow: "POST" } });
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
let body: unknown;
|
|
30
|
+
try {
|
|
31
|
+
body = JSON.parse(new TextDecoder().decode(await readBytes(request, MAX_BODY_BYTES)));
|
|
32
|
+
} catch (failure) {
|
|
33
|
+
if (failure instanceof HttpError) return reply(error(null, -32600, failure.message), failure.status);
|
|
34
|
+
return reply(error(null, -32700, "The request is not valid JSON."));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const messages = Array.isArray(body) ? body : [body];
|
|
38
|
+
if (messages.length > MAX_BATCH) {
|
|
39
|
+
return reply(error(null, -32600, `A batch has at most ${MAX_BATCH} requests.`), 413);
|
|
40
|
+
}
|
|
41
|
+
// One after another: a batch is a list of steps, and changes that run at once would race each other.
|
|
42
|
+
const answers: object[] = [];
|
|
43
|
+
for (const message of messages) {
|
|
44
|
+
const result = await answer(message as Message, context);
|
|
45
|
+
if (result !== undefined) answers.push(result);
|
|
46
|
+
}
|
|
47
|
+
// Notifications get no answer.
|
|
48
|
+
if (answers.length === 0) return new Response(null, { status: 202 });
|
|
49
|
+
return reply(Array.isArray(body) ? answers : answers[0]);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function answer(message: Message, context: ToolContext): Promise<object | undefined> {
|
|
53
|
+
if (typeof message !== "object" || message === null || typeof message.method !== "string") {
|
|
54
|
+
return error(message?.id ?? null, -32600, "Not a JSON-RPC request.");
|
|
55
|
+
}
|
|
56
|
+
const id = message.id;
|
|
57
|
+
if (id === undefined) return undefined;
|
|
58
|
+
|
|
59
|
+
switch (message.method) {
|
|
60
|
+
case "initialize": {
|
|
61
|
+
const asked = message.params?.protocolVersion;
|
|
62
|
+
const protocolVersion =
|
|
63
|
+
typeof asked === "string" && PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0];
|
|
64
|
+
return result(id, {
|
|
65
|
+
protocolVersion,
|
|
66
|
+
capabilities: { tools: {} },
|
|
67
|
+
serverInfo: SERVER_INFO,
|
|
68
|
+
instructions: INSTRUCTIONS,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
case "ping":
|
|
72
|
+
return result(id, {});
|
|
73
|
+
case "tools/list":
|
|
74
|
+
return result(id, {
|
|
75
|
+
tools: TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })),
|
|
76
|
+
});
|
|
77
|
+
case "tools/call": {
|
|
78
|
+
const tool = TOOLS.find((candidate) => candidate.name === message.params?.name);
|
|
79
|
+
if (!tool) return error(id, -32602, `There is no tool "${String(message.params?.name)}".`);
|
|
80
|
+
const args = message.params?.arguments;
|
|
81
|
+
try {
|
|
82
|
+
const output = await tool.run(
|
|
83
|
+
typeof args === "object" && args !== null ? (args as Record<string, unknown>) : {},
|
|
84
|
+
context,
|
|
85
|
+
);
|
|
86
|
+
return result(id, { content: [{ type: "text", text: JSON.stringify(output, null, 2) }] });
|
|
87
|
+
} catch (failure) {
|
|
88
|
+
// A refused change is the tool's answer, so the model can read it and try again.
|
|
89
|
+
const text = failure instanceof Error ? failure.message : String(failure);
|
|
90
|
+
return result(id, { content: [{ type: "text", text }], isError: true });
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
default:
|
|
94
|
+
return error(id, -32601, `The method "${message.method}" is not supported.`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function result(id: string | number | null, value: object): object {
|
|
99
|
+
return { jsonrpc: "2.0", id, result: value };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function error(id: string | number | null, code: number, message: string): object {
|
|
103
|
+
return { jsonrpc: "2.0", id, error: { code, message } };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function reply(body: unknown, status = 200): Response {
|
|
107
|
+
return new Response(JSON.stringify(body), {
|
|
108
|
+
status,
|
|
109
|
+
headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" },
|
|
110
|
+
});
|
|
111
|
+
}
|