webcake-storefront-mcp 1.36.2 → 1.37.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.
@@ -18,8 +18,8 @@ catch {
18
18
  const NOISE_KEYS = new Set(["undefined", "locked", "loaded", "isChangeSection"]);
19
19
  // Cross-cutting specials available on virtually every element.
20
20
  export const SHARED_SPECIALS = {
21
- custom_class: "CSS class(es) on the element — target it with .your-class in site custom CSS.",
22
- custom_css: "Raw CSS scoped to this element.",
21
+ custom_class: "CSS class(es) on the element — a hook for a few lines of site CSS, or for CMS glue code to write into it. Try style/config first.",
22
+ custom_css: "Raw CSS scoped to this element. Last resort: try runtime.style/config first (see NATIVE FIRST).",
23
23
  element_async: "Mark the element async/lazy (advanced — usually leave unset).",
24
24
  event_name_custom: "Custom analytics event name fired on interaction.",
25
25
  tabIndex: "Bind this element to a tab item (TAB-ITEM-…) so a tabs element shows/hides it.",
@@ -1,7 +1,10 @@
1
1
  // Generation guide injected into builder tools so an AI agent understands the BuilderX
2
2
  // page model well enough to author pages that actually render.
3
+ import { NATIVE_FIRST_GUIDE } from "./native-first.js";
3
4
  export const BUILD_GUIDE = `# BuilderX page authoring guide
4
5
 
6
+ ${NATIVE_FIRST_GUIDE}
7
+
5
8
  ## DESIGN SYSTEM — lock this FIRST, every build (this is what makes free composition look DESIGNED)
6
9
  There are NO page templates here and NO seeded data — you COMPOSE every page from elements
7
10
  based on the user's actual goal. (One optional shortcut: a single section may start from the
@@ -0,0 +1,168 @@
1
+ // Native-first policy. Pages are meant to be edited by dragging elements on the BuilderX canvas;
2
+ // UI written in custom code doesn't exist on that canvas, so the shop owner can't touch it and
3
+ // every visit pays for it. This module holds what an AI must try before code (taught by the build
4
+ // guide, the custom-code guide and the block messages) and the checks every code writer goes through.
5
+ /** Everyday storefront needs → the catalog elements that already do them. test/native-first keeps
6
+ * every name here honest against the catalog. */
7
+ export const NATIVE_ALTERNATIVES = [
8
+ { need: "Banners, text, images, cards, sections", elements: ["section", "container", "text", "image", "button", "rectangle"] },
9
+ { need: "Header, footer, menus", elements: ["menu", "member-bar", "dropdown"], note: "save as a global section" },
10
+ { need: "Product lists, category tiles", elements: ["grid-product", "slider-product", "grid-category", "slider-category"] },
11
+ { need: "Category filters and sorting", elements: ["checkbox-group", "color-group", "two-point-range", "radio-group", "tags", "dropdown"], note: "specials.filter_elements drives the grid" },
12
+ { need: "Product detail", elements: ["product-gallery", "product-image-carousel", "attr", "quantity-input", "product-review", "masonry-review"] },
13
+ { need: "Cart, including a slide-out cart", elements: ["cart-icon", "cart-items", "cart-droppable", "cart-items-empty", "bonus-items"] },
14
+ { need: "Checkout", elements: ["form", "address", "payment", "delivery-method", "order-items", "coupon"], note: "form.specials.type = form_order" },
15
+ { need: "Login, signup, account", elements: ["form", "member-bar", "order-history", "customer-address", "reward-point"], note: "form_login / form_signup / order_tracking" },
16
+ { need: "Wishlist", elements: ["favorite-icon", "wishlist", "wishlist-container", "wishlist-item", "wishlist-empty"] },
17
+ { need: "Search", elements: ["search-form", "search-droppable", "input-search"] },
18
+ { need: "Promotions, flash sale, countdown", elements: ["flash-sale", "countdown", "promotions", "promotions-short", "coupon", "lucky-wheel"] },
19
+ { need: "Sliders, tabs, accordions, galleries", elements: ["swiper", "carousel", "tabs", "collapse", "gallery"] },
20
+ { need: "Popups, size charts", elements: ["popup", "table"], note: "open with an open_popup event" },
21
+ { need: "Video, maps", elements: ["video", "googlemap"] },
22
+ { need: "Blog", elements: ["post-list", "slider-post", "grid-blog"] },
23
+ ];
24
+ export const SITE_CODE_FIELDS = ["code_before_head", "code_before_body", "code_custom_javascript", "code_custom_css"];
25
+ const SCRIPT_FIELDS = ["code_before_head", "code_before_body", "code_custom_javascript"];
26
+ const CSS_FIELDS = ["code_custom_css"];
27
+ /** Site-wide, in chars. Above `soft` a write must name its native gap; crossing `hard` is refused. */
28
+ export const CODE_BUDGET = {
29
+ script: { soft: 30_000, hard: 100_000 },
30
+ css: { soft: 20_000, hard: 50_000 },
31
+ };
32
+ /** custom_css + embed code across one page or global source. */
33
+ export const NODE_CODE_BUDGET = { soft: 10_000, hard: 30_000 };
34
+ /** Growth still allowed on a site already past the ceiling, so it can ship fixes while it migrates. */
35
+ const SMALL_FIX = 2_000;
36
+ export const NATIVE_FIRST_GUIDE = `## NATIVE FIRST — elements on the canvas before any code
37
+ Pages are edited by dragging elements on the canvas. UI written in code is not on that canvas: the
38
+ shop owner can't edit it, it is missing from the page HTML until scripts run, and it loads on every
39
+ page. Go down this list and stop at the FIRST step that works:
40
+ 1. A NATIVE ELEMENT — list_elements / get_element (table below).
41
+ 2. THE ELEMENT'S OWN SETTINGS — runtime.style/config, responsive overrides, events (hover, click,
42
+ open_popup, filter…), bindings (live product/cart/order/post data), runtime.config.animation,
43
+ position:"sticky"/"pinned". Most "this needs CSS/JS" ideas stop here.
44
+ 3. AN EXISTING APP — list_apps / install_app (product_review, appointment, affiliates, course, automation…).
45
+ 4. ONLY for a feature none of the above can do (a size advisor, mix & match, a custom quiz…) —
46
+ custom code COMBINED WITH THE CMS APP, so it stays small:
47
+ a. install_app "cms".
48
+ b. DATA goes in a collection (create_collection), never hard-coded in a script.
49
+ c. LOGIC goes in an HTTP function (edit_http_function action "add" + webcake-data, test with run_function).
50
+ d. UI stays NATIVE elements, marked with specials.custom_class.
51
+ e. Custom code is only the glue: load webcake-fn once in code_before_head
52
+ (<script src="https://cdn.jsdelivr.net/npm/webcake-fn/dist/webcake-fn.umd.min.js"></script>),
53
+ then read through it and write into those native elements:
54
+ api.get_SizeAdvice({ height }).then((r) => {
55
+ document.querySelector(".size-result p").textContent = r.size;
56
+ });
57
+ 5. Third-party snippets (tracking, chat, a widget): the smallest code_before_head / embed that works.
58
+ A visual detail no style property can do: a few lines of CSS on a custom_class.
59
+
60
+ Never: render a page, section, product card, cart or checkout from JavaScript; put placeholder JSON in
61
+ text elements for a script to fill; copy product data into code (use products + bindings); or capture a
62
+ design as HTML. A reference design (Stitch, Figma, canvas, another site) is a visual brief: rebuild it
63
+ with elements (ingest_html → new_section) and accept small differences. If a design can't be matched
64
+ natively, tell the user what differs instead of switching to code.
65
+
66
+ Which element for which need:
67
+ ${NATIVE_ALTERNATIVES.map((a) => `- ${a.need}: ${a.elements.join(", ")}${a.note ? ` (${a.note})` : ""}`).join("\n")}
68
+
69
+ Limits: site scripts ${CODE_BUDGET.script.soft / 1000}k chars, site CSS ${CODE_BUDGET.css.soft / 1000}k chars. Above that, a write is refused unless
70
+ it names the gap in native_gap (scripts ${CODE_BUDGET.script.hard / 1000}k / CSS ${CODE_BUDGET.css.hard / 1000}k is refused outright; a site already past that may only
71
+ remove code or add small fixes). validate_page also refuses new placeholder JSON in text and more than
72
+ ${NODE_CODE_BUDGET.hard / 1000}k chars of custom_css + embed code on one page. Content already on a page never blocks an unrelated save.`;
73
+ const SMELLS = [
74
+ {
75
+ kind: "script",
76
+ limit: 20,
77
+ re: /<(?:div|section|article|ul|li|table|img|a|h[1-6]|p|button|form|input|span)[\s>]/gi,
78
+ label: "HTML tags in scripts",
79
+ fix: "build this UI with native elements",
80
+ },
81
+ {
82
+ kind: "script",
83
+ limit: 15,
84
+ re: /\.innerHTML\b|insertAdjacentHTML|createElement\(/g,
85
+ label: "DOM-building calls",
86
+ fix: "scripts should write into native elements, not create the UI",
87
+ },
88
+ {
89
+ kind: "script",
90
+ limit: 200,
91
+ re: /"[\w-]+"\s*:/g,
92
+ label: "JSON keys in scripts",
93
+ fix: "move this data to products + bindings or a CMS collection",
94
+ },
95
+ {
96
+ kind: "script",
97
+ limit: 0,
98
+ re: /<!doctype\s|<html[\s>]|<body[\s>]/gi,
99
+ label: "HTML document tags in scripts",
100
+ fix: "rebuild that page from native elements",
101
+ },
102
+ {
103
+ kind: "css",
104
+ limit: 30,
105
+ re: /!important/g,
106
+ label: "!important rules",
107
+ fix: "set runtime.style/config on the elements instead of overriding them",
108
+ },
109
+ ];
110
+ const PASTED_DOCUMENT = /^\s*(?:<!doctype\s|<html[\s>])/i;
111
+ const joined = (values, fields) => fields.map((f) => String(values[f] || "")).filter(Boolean).join("\n");
112
+ // HTML comments don't count: snippets ship with notes like "paste after the opening <body> tag".
113
+ const count = (text, re) => (text.replace(/<!--[\s\S]*?-->/g, "").match(re) || []).length;
114
+ /** How much of the budget a site's code uses (for reads, so an agent sees it before writing). */
115
+ export function codeUsage(values) {
116
+ const script = joined(values, SCRIPT_FIELDS).length;
117
+ const css = joined(values, CSS_FIELDS).length;
118
+ return {
119
+ script: { used: script, budget: CODE_BUDGET.script.soft },
120
+ css: { used: css, budget: CODE_BUDGET.css.soft },
121
+ over_budget: script > CODE_BUDGET.script.soft || css > CODE_BUDGET.css.soft,
122
+ };
123
+ }
124
+ /** Judge a write by what it ADDS: shrinking or swapping code on an already-large site always passes,
125
+ * so a site can move off custom code step by step and still ship small fixes. */
126
+ export function checkSiteCode(before, changes) {
127
+ const after = { ...before, ...changes };
128
+ const hard = [];
129
+ const soft = [];
130
+ const texts = (kind) => {
131
+ const fields = kind === "script" ? SCRIPT_FIELDS : CSS_FIELDS;
132
+ return { old: joined(before, fields), now: joined(after, fields) };
133
+ };
134
+ for (const kind of ["script", "css"]) {
135
+ const { old, now } = texts(kind);
136
+ if (now.length <= old.length)
137
+ continue;
138
+ const { soft: softLimit, hard: hardLimit } = CODE_BUDGET[kind];
139
+ if (now.length > hardLimit && (old.length <= hardLimit || now.length - old.length > SMALL_FIX))
140
+ hard.push(`Site ${kind} would reach ${now.length} chars (ceiling ${hardLimit}). That is an app, not a snippet: move UI to native elements, data to a collection, logic to an HTTP function.`);
141
+ else if (now.length > softLimit)
142
+ soft.push(`Site ${kind} would reach ${now.length} chars (budget ${softLimit}).`);
143
+ }
144
+ for (const [field, value] of Object.entries(changes)) {
145
+ if (PASTED_DOCUMENT.test(String(value || "")) && !PASTED_DOCUMENT.test(String(before[field] || "")))
146
+ hard.push(`${field} is a whole HTML page. Rebuild it from native elements (ingest_html → new_section).`);
147
+ }
148
+ for (const s of SMELLS) {
149
+ const { old, now } = texts(s.kind);
150
+ const found = count(now, s.re);
151
+ if (found > s.limit && found > count(old, s.re))
152
+ soft.push(`${found} ${s.label} (limit ${s.limit}): ${s.fix}.`);
153
+ }
154
+ return { hard, soft };
155
+ }
156
+ /** Turn a check into the tool's refusal, or null when the write may proceed. */
157
+ export function codeGuard(check, nativeGap) {
158
+ if (check.hard.length)
159
+ return { error: "BLOCKED: custom code refused. Not saved.", reasons: check.hard, native_first: NATIVE_FIRST_GUIDE };
160
+ if (check.soft.length && !nativeGap)
161
+ return {
162
+ error: "BLOCKED: this looks like UI or data that belongs in native elements or the CMS. Not saved.",
163
+ reasons: check.soft,
164
+ native_first: NATIVE_FIRST_GUIDE,
165
+ if_truly_no_native_way: "Tell the user why, then call again with native_gap: the need, the elements/apps you checked, and what each one lacks.",
166
+ };
167
+ return null;
168
+ }
@@ -8,6 +8,7 @@ import { buildElement, isKnownType, ELEMENT_TYPES } from "./catalog.js";
8
8
  import { randomString } from "./factory.js";
9
9
  import { validateEvents } from "./events.js";
10
10
  import { validateBindings } from "./bindings.js";
11
+ import { NODE_CODE_BUDGET } from "./native-first.js";
11
12
  import { BREAKPOINTS, BREAKPOINT_KEYS, genGridByBp, SECTION_CONTENT_COL_START, SECTION_CONTENT_COL_END, } from "./grid.js";
12
13
  const clone = (o) => structuredClone(o);
13
14
  /** Parse a CSS px length ("52px") or a bare number (52) → number, else null. */
@@ -308,9 +309,11 @@ export function checkEmbeds(source) {
308
309
  const errors = [];
309
310
  const warnings = [];
310
311
  walk(source, (node) => {
311
- if (node.type !== "embed")
312
+ // googlemap counts too: the renderer inlines its specials.iframe as raw HTML.
313
+ if (node.type !== "embed" && node.type !== "googlemap")
312
314
  return;
313
- const code = String((node.specials && node.specials.htmlCode) || "");
315
+ const s = node.specials || {};
316
+ const code = String(s.htmlCode || "") + String(s.iframe || "");
314
317
  if (/<!doctype\s|<html[\s>]|<body[\s>]/i.test(code)) {
315
318
  errors.push(`Embed "${node.id}" holds a whole HTML document (${code.length} chars). Embed is a last resort: build natively everything ` +
316
319
  `native elements can (text/image/button/form/container… via ingest_html → new_section), and embed ONLY the one piece no element ` +
@@ -325,7 +328,67 @@ export function checkEmbeds(source) {
325
328
  });
326
329
  return { errors, warnings };
327
330
  }
328
- export function validatePage(source) {
331
+ /** A text element holding only a JSON object is a slot for a script to fill, not content: that's how
332
+ * a page ends up empty on the canvas with its real UI in custom code. */
333
+ const isDataPlaceholder = (text) => {
334
+ const plain = text.replace(/<[^>]+>/g, "").replace(/&quot;|&#0*34;|&#x0*22;/gi, '"').trim();
335
+ if (!/^[{[]/.test(plain))
336
+ return false;
337
+ try {
338
+ const value = JSON.parse(plain);
339
+ const first = Array.isArray(value) ? value[0] : value;
340
+ return !!first && typeof first === "object" && Object.keys(first).length > 0;
341
+ }
342
+ catch {
343
+ return false;
344
+ }
345
+ };
346
+ function scanCode(source) {
347
+ const { errors, warnings } = checkEmbeds(source);
348
+ let code = 0;
349
+ walk(source, (node) => {
350
+ const s = node.specials || {};
351
+ code += String(s.custom_css || "").length + String(s.htmlCode || "").length + String(s.iframe || "").length;
352
+ if (typeof s.text === "string" && isDataPlaceholder(s.text))
353
+ errors.push(`"${node.id}" holds placeholder JSON for a script to fill (${s.text.slice(0, 60)}). Put the real content in native elements. See get_build_guide → NATIVE FIRST. If visitors should really read this JSON, add words around it.`);
354
+ });
355
+ return { errors, warnings, code };
356
+ }
357
+ const codeVolumeError = (code) => `${code} chars of custom_css + embed code (limit ${NODE_CODE_BUDGET.hard}). Build this with native elements. See get_build_guide → NATIVE FIRST.`;
358
+ /** Everything validatePage refuses about code inside a source: embeds, placeholders, code volume.
359
+ * Pass the `previous` source when saving over one: only what this save ADDS is refused, so an old
360
+ * page can still be edited and moved to native elements section by section. */
361
+ export function checkNativeContent(source, previous) {
362
+ const { errors, warnings, code } = scanCode(source);
363
+ const old = previous ? scanCode(previous) : null;
364
+ const added = old ? errors.filter((e) => !old.errors.includes(e)) : errors;
365
+ if (code > NODE_CODE_BUDGET.hard && (!old || code > old.code))
366
+ added.push(codeVolumeError(code));
367
+ else if (code > NODE_CODE_BUDGET.soft)
368
+ warnings.push(`${code} chars of custom_css + embed code (budget ${NODE_CODE_BUDGET.soft}): check whether native elements or their settings can replace it.`);
369
+ return { errors: added, warnings };
370
+ }
371
+ /** For element edits, after the patch is applied to `node` inside `source`: what the patch added to
372
+ * this element, plus the code total across the page, so batches can't add up past the limit. */
373
+ export function checkElementPatch(source, node, before, specials) {
374
+ if (!specials)
375
+ return [];
376
+ const alone = (n) => scanCode({ sections: [{ ...n, children: undefined }] });
377
+ const now = alone(node);
378
+ const old = alone(before);
379
+ const errors = now.errors.filter((e) => !old.errors.includes(e));
380
+ const total = scanCode(source).code;
381
+ if (now.code > old.code && total > NODE_CODE_BUDGET.hard)
382
+ errors.push(codeVolumeError(total));
383
+ return errors;
384
+ }
385
+ /** Translations are per-element text overrides, so they can hold placeholders too. Keyed by element id. */
386
+ export function checkContentPlaceholders(content, previous) {
387
+ return Object.entries(content || {})
388
+ .filter(([id, v]) => typeof v?.text === "string" && isDataPlaceholder(v.text) && previous?.[id]?.text !== v.text)
389
+ .map(([id]) => `"${id}" translation holds placeholder JSON for a script to fill. Translate real text. See get_build_guide → NATIVE FIRST.`);
390
+ }
391
+ export function validatePage(source, previous) {
329
392
  const errors = [];
330
393
  const warnings = [];
331
394
  if (!source || typeof source !== "object" || !Array.isArray(source.sections)) {
@@ -395,9 +458,9 @@ export function validatePage(source) {
395
458
  };
396
459
  for (const s of source.sections)
397
460
  checkTree(s, []);
398
- const embeds = checkEmbeds(source);
399
- errors.push(...embeds.errors);
400
- warnings.push(...embeds.warnings);
461
+ const code = checkNativeContent(source, previous);
462
+ errors.push(...code.errors);
463
+ warnings.push(...code.warnings);
401
464
  return {
402
465
  valid: errors.length === 0,
403
466
  ...(errors.length ? { errors } : {}),
@@ -1,4 +1,11 @@
1
1
  [
2
+ {
3
+ "v": "1.37.0",
4
+ "d": "04/11/2026",
5
+ "type": "Added",
6
+ "en": "A new native-first guide is now injected into get_build_guide's build guide, get_http_function's and get_site_custom_code's custom-code guide, and…",
7
+ "vi": "Hướng dẫn \"native first\" mới nay được chèn vào build guide của get_build_guide, custom-code guide của get_http_function và get_site_custom_code,…"
8
+ },
2
9
  {
3
10
  "v": "1.36.2",
4
11
  "d": "29/10/2026",
@@ -33,12 +40,5 @@
33
40
  "type": "Fixed",
34
41
  "en": "validate_page's \"not a container\" warning now only fires for true leaf elements (text, image, button, inputs, datasets, etc.); container-like…",
35
42
  "vi": "Cảnh báo \"not a container\" của validate_page nay chỉ xuất hiện với các element leaf thật sự (text, image, button, các input, dataset...); các…"
36
- },
37
- {
38
- "v": "1.34.0",
39
- "d": "14/10/2026",
40
- "type": "Added",
41
- "en": "New list_section_templates tool browses the designer-made section template library (categories, search by term, thumbnails) for starting a section…",
42
- "vi": "Tool mới list_section_templates để duyệt thư viện mẫu section do designer tạo (theo danh mục, tìm kiếm bằng term, có thumbnail) làm điểm khởi đầu…"
43
43
  }
44
44
  ]
package/dist/guides.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { NATIVE_FIRST_GUIDE } from "./builder/native-first.js";
1
2
  export const HTTP_FUNCTION_GUIDE = `
2
3
  # HTTP Function Guide
3
4
 
@@ -114,7 +115,7 @@ A "collection" is a custom DB table. To stand one up and use it from a function:
114
115
  await T.deleteMany({ email: "a@b.com" }); // delete
115
116
  const rows = await T.find({ … }).select([…]).limit(50); // query
116
117
  (There is NO direct dashboard record-INSERT API — record writes MUST go through a function.
117
- Deploy the function with the update_http_function MCP tool, then call it with run_function.)
118
+ Deploy the function with the edit_http_function MCP tool (action "add" or "replace_function"; update_http_function replaces the WHOLE file), then call it with run_function.)
118
119
 
119
120
  ## Built-in @webcake/* modules (first arg is always request; they auth via global.token — these run
120
121
  ## INSIDE the function sandbox, so they reach the /cms_function endpoints the dashboard JWT can't)
@@ -238,6 +239,8 @@ export const post_MyMembers = async (request) => {
238
239
  export const CUSTOM_CODE_GUIDE = `
239
240
  # Custom Code Guide
240
241
 
242
+ ${NATIVE_FIRST_GUIDE}
243
+
241
244
  Custom code is stored in site settings (applies to entire site, not per page).
242
245
 
243
246
  ## Injection points
package/dist/server.js CHANGED
@@ -24,6 +24,8 @@ Build the WHOLE site by FREE COMPOSITION FROM ELEMENTS — there are NO page tem
24
24
 
25
25
  To make a generated site look real, also CREATE DATA so dataset bindings resolve: create_product_category + create_product (storefront), create_blog_category + create_article (blog). Get image URLs from search_images / upload_images first, then reference them. A good flow for a fresh site: create_site → create a few categories → create products in them → build_page (home + store/blog pages) → publish_site.
26
26
 
27
+ NATIVE FIRST — this outranks matching a design exactly. Build with elements the shop owner can drag and edit on the canvas: first a native element, then that element's settings (style, events, bindings, animation), then an existing app. Custom code is the last resort, only for a feature none of those can do, and then it is COMBINED WITH THE CMS APP: data in a collection, logic in an HTTP function, UI in native elements, and only a small glue script in custom code. Never render pages, sections, product cards, cart or checkout from JavaScript, and never capture a design as HTML — rebuild it with elements and tell the user what differs. get_build_guide has the need → element table; oversized custom code is refused on save.
28
+
27
29
  INTAKE FIRST — when the user asks to BUILD/CREATE a site, store, or page (a fresh build, not a small edit or a data question), do NOT jump straight to create_site/build_page on the same turn. Act as a professional shop-website designer doing client work: first ask ONE short batch of questions (call get_intake_guide for the exact list), restate the plan you'll build, get a "yes", THEN build. The shop owner is an ORDINARY person, not a designer — ask in plain words and visual outcomes ("tông nâu ấm, ảnh sản phẩm to"), never jargon. Ask the essentials (with sensible defaults so they answer fast): what they sell + a few products & prices, brand/shop name, primary color/style, which pages they need, real contact info (hotline/Zalo, address, email, hours) + the main call-to-action, and any promotion. NEVER invent or silently placeholder real data (shop name, products, prices, phone, address) — ask for it; placeholder only what the user explicitly skips, and tell them what to fill in. Skip intake only when the user already gave the brief, says "just do it / tự quyết", or it's a tiny edit.
28
30
 
29
31
  Workflow:
@@ -366,7 +366,7 @@ Two-step safety: dry_run=true (default) previews; dry_run=false saves.`, {
366
366
  return { error: "Provided 'section' is not a section node (type must be 'section')." };
367
367
  }
368
368
  source.sections.push(sectionNode);
369
- const validation = validatePage(source);
369
+ const validation = validatePage(source, { sections: source.sections.slice(0, -1) });
370
370
  if (dry_run) {
371
371
  return {
372
372
  dry_run: true,
@@ -2,6 +2,7 @@ import { z } from "zod";
2
2
  import { getConfirmMode } from "./context.js";
3
3
  import { normalizeEvents } from "../builder/events.js";
4
4
  import { normalizeBindings } from "../builder/bindings.js";
5
+ import { checkContentPlaceholders, checkElementPatch, checkNativeContent } from "../builder/page.js";
5
6
  /**
6
7
  * Global Sources tools — manage site-wide components: cart, popup, overview, etc.
7
8
  *
@@ -23,6 +24,13 @@ export function parseSource(sourceJson) {
23
24
  return null;
24
25
  }
25
26
  }
27
+ /** Global sources come as a root node, { sections }, or an array: normalize so every shape is checked. */
28
+ const ALLOW_SHRINK = z.boolean().optional()
29
+ .describe("Allow the source to shrink by more than half: set it when native elements replaced an oversized embed or custom_css and you have read it first.");
30
+ const asPageShape = (source) => {
31
+ const parsed = parseSource(source);
32
+ return { sections: parsed?.sections ?? (Array.isArray(parsed) ? parsed : parsed ? [parsed] : []) };
33
+ };
26
34
  /** Get root nodes from source — handles both formats:
27
35
  * - Page format: { sections: [...] } → returns sections array
28
36
  * - Global source format: { id, type, children: [...] } → returns [rootNode]
@@ -447,7 +455,8 @@ events/bindings = REPLACE the whole array — pass the COMPLETE list (read it fi
447
455
  events: z.array(z.record(z.any())).optional().describe("Complete events array (replaces existing)"),
448
456
  bindings: z.array(z.record(z.any())).optional().describe("Complete bindings array (replaces existing)"),
449
457
  responsive: z.record(z.any()).optional().describe("Responsive overrides (e.g. {bp1: {style: {...}}})"),
450
- }, ({ global_source_id, element_id, component, dry_run: dryRunParam, ...updates }) => handle(async () => {
458
+ allow_shrink: ALLOW_SHRINK,
459
+ }, ({ global_source_id, element_id, component, dry_run: dryRunParam, allow_shrink, ...updates }) => handle(async () => {
451
460
  // Resolve dry_run: explicit param wins, otherwise follow confirm_mode setting
452
461
  const dry_run = dryRunParam !== undefined ? dryRunParam : getConfirmMode() === "always_confirm";
453
462
  // Force fresh read before write to avoid stale cache overwriting newer data
@@ -463,6 +472,9 @@ events/bindings = REPLACE the whole array — pass the COMPLETE list (read it fi
463
472
  // Clone node before mutation for diff
464
473
  const beforeNode = JSON.parse(JSON.stringify(node));
465
474
  applyNodeUpdates(node, updates);
475
+ const codeErrors = checkElementPatch(asPageShape(source), node, beforeNode, updates.specials);
476
+ if (codeErrors.length)
477
+ return { error: "BLOCKED: not saving.", element_id, errors: codeErrors };
466
478
  const diff = computeNodeDiff(beforeNode, node);
467
479
  if (!diff)
468
480
  return { info: "No changes detected", element_id };
@@ -479,7 +491,7 @@ events/bindings = REPLACE the whole array — pass the COMPLETE list (read it fi
479
491
  const existingLen = JSON.stringify(parseSource(gs.source)).length;
480
492
  const newLen = JSON.stringify(source).length;
481
493
  // Safeguard: block if source shrinks significantly
482
- if (existingLen > 200 && newLen < existingLen * 0.5) {
494
+ if (!allow_shrink && existingLen > 200 && newLen < existingLen * 0.5) {
483
495
  return {
484
496
  error: `BLOCKED: Source would shrink from ${existingLen} to ${newLen} chars. This indicates data loss.`,
485
497
  existing_length: existingLen,
@@ -510,7 +522,8 @@ Same merge rules: style/config/specials = shallow merge, events/bindings = repla
510
522
  component: z.string().optional().describe('Component hint for faster lookup'),
511
523
  dry_run: z.boolean().optional().describe("Preview only (true) or apply changes (false). Defaults to confirm_mode setting."),
512
524
  updates: z.array(elementUpdateShape).describe("Array of element updates"),
513
- }, ({ global_source_id, component, dry_run: dryRunParam, updates: elementUpdates }) => handle(async () => {
525
+ allow_shrink: ALLOW_SHRINK,
526
+ }, ({ global_source_id, component, dry_run: dryRunParam, updates: elementUpdates, allow_shrink }) => handle(async () => {
514
527
  const dry_run = dryRunParam !== undefined ? dryRunParam : getConfirmMode() === "always_confirm";
515
528
  invalidateGsCache();
516
529
  const { gs, source, error } = await getGsWithSource(api, global_source_id, component);
@@ -528,6 +541,9 @@ Same merge rules: style/config/specials = shallow merge, events/bindings = repla
528
541
  const beforeNode = JSON.parse(JSON.stringify(node));
529
542
  const { element_id, ...updates } = upd;
530
543
  applyNodeUpdates(node, updates);
544
+ const codeErrors = checkElementPatch(asPageShape(source), node, beforeNode, updates.specials);
545
+ if (codeErrors.length)
546
+ return { error: "BLOCKED: not saving any of this batch.", element_id, errors: codeErrors };
531
547
  const diff = computeNodeDiff(beforeNode, node);
532
548
  results.push({ element_id, diff: diff || "no changes" });
533
549
  }
@@ -541,7 +557,7 @@ Same merge rules: style/config/specials = shallow merge, events/bindings = repla
541
557
  // Actual save — send source as OBJECT (not string) because backend does Jason.encode!
542
558
  const existingLen = JSON.stringify(parseSource(gs.source)).length;
543
559
  const newLen = JSON.stringify(source).length;
544
- if (existingLen > 200 && newLen < existingLen * 0.5) {
560
+ if (!allow_shrink && existingLen > 200 && newLen < existingLen * 0.5) {
545
561
  return {
546
562
  error: `BLOCKED: Source would shrink from ${existingLen} to ${newLen} chars. This indicates data loss.`,
547
563
  existing_length: existingLen,
@@ -568,6 +584,9 @@ Same merge rules: style/config/specials = shallow merge, events/bindings = repla
568
584
  source: z.any().describe("Source configuration (sections/elements JSON)"),
569
585
  type: z.string().default("default").describe('Type variant (default: "default")'),
570
586
  }, ({ component, source, type }) => handle(async () => {
587
+ const code = checkNativeContent(asPageShape(source));
588
+ if (code.errors.length)
589
+ return { error: "BLOCKED: not saving.", errors: code.errors };
571
590
  const params = { component, source, type, site_id: api.siteId };
572
591
  const res = component === "cart-droppable"
573
592
  ? await api.createSourceCart(params)
@@ -583,7 +602,8 @@ IMPORTANT: Before calling this tool, you MUST:
583
602
  Safeguarded: blocks if new source is <50% of existing size. For element-level changes, prefer update_global_source_element instead.`, {
584
603
  global_source_id: z.string().describe("Global source ID"),
585
604
  source: z.any().describe("New source configuration (JSON object)"),
586
- }, ({ global_source_id, source: newSourceInput }) => handle(async () => {
605
+ allow_shrink: ALLOW_SHRINK,
606
+ }, ({ global_source_id, source: newSourceInput, allow_shrink }) => handle(async () => {
587
607
  // Force fresh read before write to avoid stale cache
588
608
  invalidateGsCache();
589
609
  const { gs, source: existingSource, error } = await getGsWithSource(api, global_source_id);
@@ -592,10 +612,13 @@ Safeguarded: blocks if new source is <50% of existing size. For element-level ch
592
612
  // Ensure source is an object (not string) — backend does Jason.encode! so we must send object
593
613
  const newSourceObj = typeof newSourceInput === "string" ? JSON.parse(newSourceInput) : newSourceInput;
594
614
  const newLen = JSON.stringify(newSourceObj).length;
615
+ const code = checkNativeContent(asPageShape(newSourceObj), existingSource ? asPageShape(existingSource) : undefined);
616
+ if (code.errors.length)
617
+ return { error: "BLOCKED: not saving.", errors: code.errors };
595
618
  // Safeguard: block if new source is suspiciously smaller
596
619
  if (existingSource) {
597
620
  const existingLen = JSON.stringify(existingSource).length;
598
- if (existingLen > 200 && newLen < existingLen * 0.5) {
621
+ if (!allow_shrink && existingLen > 200 && newLen < existingLen * 0.5) {
599
622
  return {
600
623
  error: `BLOCKED: New source (${newLen} chars) is much smaller than existing (${existingLen} chars) — ${Math.round((newLen / existingLen) * 100)}% of original. Use get_global_source_detail to read existing data first, or use update_global_source_element for targeted changes.`,
601
624
  existing_length: existingLen,
@@ -634,6 +657,18 @@ IMPORTANT: Before calling, you MUST read existing contents with get_global_sourc
634
657
  })).describe("Array of content entries to upsert"),
635
658
  }, ({ contents }) => handle(async () => {
636
659
  // Safeguard: for each entry, check existing content size
660
+ for (const c of contents) {
661
+ if (!checkContentPlaceholders(c.content).length)
662
+ continue;
663
+ const res = await api.getGlobalSourceContents({ site_id: api.siteId, component: c.type_component });
664
+ const list = (res && res.data) || res || [];
665
+ const old = Array.isArray(list)
666
+ ? list.find((e) => String(e.global_source_id) === String(c.global_source_id) && e.language_code === c.language_code)
667
+ : null;
668
+ const placeholders = checkContentPlaceholders(c.content, old?.content);
669
+ if (placeholders.length)
670
+ return { error: "BLOCKED: not saving.", errors: placeholders };
671
+ }
637
672
  for (const entry of contents) {
638
673
  if (!entry.content)
639
674
  continue;
@@ -552,6 +552,10 @@ If alt_path is omitted, it is auto-detected via the same probe used by list_imag
552
552
  }
553
553
  const probe = probeImagePaths(node);
554
554
  const path = it.alt_path || probe.alt_path;
555
+ if (!/(?:^|[._])alt$/i.test(path)) {
556
+ perItem.push({ element_id: it.element_id, error: `alt_path "${path}" is not an alt field` });
557
+ continue;
558
+ }
555
559
  const before = path.split(".").reduce((acc, k) => (acc == null ? acc : acc[k]), node);
556
560
  setByPath(node, path, it.alt);
557
561
  perItem.push({ element_id: it.element_id, alt_path: path, before: before == null ? "" : before, after: it.alt, _src: probe.src });
@@ -3,7 +3,8 @@ import { CUSTOM_CODE_GUIDE } from "../guides.js";
3
3
  import { getConfirmMode } from "./context.js";
4
4
  import { normalizeEvents } from "../builder/events.js";
5
5
  import { normalizeBindings } from "../builder/bindings.js";
6
- import { checkEmbeds } from "../builder/page.js";
6
+ import { checkContentPlaceholders, checkElementPatch, checkNativeContent } from "../builder/page.js";
7
+ import { SITE_CODE_FIELDS, checkSiteCode, codeGuard, codeUsage } from "../builder/native-first.js";
7
8
  import { PAGE_TYPE_NUM, PAGE_KINDS, applyPageMeta, normalizeSlug, checkPageCreateConflict } from "./builder.js";
8
9
  const pageSeoSchema = z.object({
9
10
  title: z.string().optional(),
@@ -263,6 +264,14 @@ async function getPageWithSource(api, pageId) {
263
264
  const source = parseSource(page.source && page.source.source);
264
265
  return { page, source };
265
266
  }
267
+ async function readSiteCode(api) {
268
+ const values = await Promise.all(SITE_CODE_FIELDS.map((f) => api.getSiteSettingField(f)));
269
+ return Object.fromEntries(SITE_CODE_FIELDS.map((f, i) => [f, values[i] || ""]));
270
+ }
271
+ const ALLOW_SHRINK = z.boolean().optional()
272
+ .describe("Allow the source to shrink by more than half: set it when native elements replaced an oversized embed or custom_css and you have read it first.");
273
+ const NATIVE_GAP = z.string().min(30).optional()
274
+ .describe("Only when the code was refused and no native way exists: the need, the elements/apps you checked, and what each one lacks. Tell the user first.");
266
275
  export function registerPageTools(server, api, handle) {
267
276
  server.tool("list_pages", "List all pages of the site (metadata only, without source)", {}, () => handle(async () => {
268
277
  const pages = await getCachedPages(api);
@@ -361,7 +370,8 @@ seo / settings are MERGED into the page's current settings — fields you don't
361
370
  server.tool("get_site_custom_code", `Get custom code of the site (CSS/JS). Two modes:
362
371
  - Default: returns ALL 4 code fields (full content)
363
372
  - With field filter: returns only the specified field(s) — saves tokens when you only need CSS or JS
364
- Add include_guide=true on first call to get the coding guide`, {
373
+ Add include_guide=true on first call to get the coding guide.
374
+ Custom code is the last resort: see get_build_guide → NATIVE FIRST before adding any. All-fields reads include _budget (usage vs limits).`, {
365
375
  fields: z.array(z.enum(["code_before_head", "code_before_body", "code_custom_css", "code_custom_javascript"]))
366
376
  .optional()
367
377
  .describe("Only return specific fields (e.g. ['code_custom_css']). Omit to get all 4 fields"),
@@ -379,12 +389,14 @@ Add include_guide=true on first call to get the coding guide`, {
379
389
  for (const f of allFields) {
380
390
  res._sizes[f] = (res[f] || "").length;
381
391
  }
392
+ res._budget = codeUsage(res);
382
393
  }
383
394
  if (include_guide)
384
395
  res.guide = CUSTOM_CODE_GUIDE;
385
396
  return res;
386
397
  }));
387
398
  server.tool("update_site_custom_code", `Update custom code (CSS/JS) for the entire site. Only sends fields you specify — others remain unchanged.
399
+ LAST RESORT: use native elements, their settings or an app first; a special feature uses the CMS app (collection + HTTP function) with only a small glue script here. See get_build_guide → NATIVE FIRST. Oversized code or UI/data in code is refused unless native_gap explains why.
388
400
  IMPORTANT: Before calling, you MUST read existing code with get_site_custom_code first, then show the user what will change and get explicit confirmation. NEVER update without user approval.
389
401
  - code_before_head: HTML/script inserted before </head>
390
402
  - code_before_body: HTML/script inserted before </body>
@@ -394,7 +406,9 @@ IMPORTANT: Before calling, you MUST read existing code with get_site_custom_code
394
406
  code_before_body: z.string().optional().describe("HTML/script to insert before </body>"),
395
407
  code_custom_css: z.string().optional().describe("Custom CSS for the site"),
396
408
  code_custom_javascript: z.string().optional().describe("Custom JavaScript for the site"),
397
- }, (codes) => {
409
+ native_gap: NATIVE_GAP,
410
+ allow_shrink: z.boolean().optional().describe("Allow removing more than half of a field: set it when native elements or the CMS replaced that code and you have read it first."),
411
+ }, ({ native_gap, allow_shrink, ...codes }) => {
398
412
  const settings = {};
399
413
  for (const [k, v] of Object.entries(codes)) {
400
414
  if (v != null)
@@ -405,17 +419,19 @@ IMPORTANT: Before calling, you MUST read existing code with get_site_custom_code
405
419
  if (fieldsToUpdate.length === 0)
406
420
  return { error: "No fields specified" };
407
421
  // Safeguard: read existing values and compare before overwriting
408
- const existingValues = await Promise.all(fieldsToUpdate.map((f) => api.getSiteSettingField(f)));
422
+ const current = await readSiteCode(api);
423
+ const blocked = codeGuard(checkSiteCode(current, settings), native_gap);
424
+ if (blocked)
425
+ return blocked;
409
426
  const comparison = {};
410
- for (let i = 0; i < fieldsToUpdate.length; i++) {
411
- const field = fieldsToUpdate[i];
412
- const existing = existingValues[i] || "";
427
+ for (const field of fieldsToUpdate) {
428
+ const existing = current[field] || "";
413
429
  const newVal = settings[field] || "";
414
430
  comparison[field] = { existing_length: existing.length, new_length: newVal.length };
415
431
  // Block if existing content is substantial and new content is much smaller (likely data loss)
416
- if (existing.length > 100 && newVal.length < existing.length * 0.5) {
432
+ if (!allow_shrink && existing.length > 100 && newVal.length < existing.length * 0.5) {
417
433
  return {
418
- error: `BLOCKED: Field "${field}" would shrink from ${existing.length} to ${newVal.length} chars (${Math.round((newVal.length / existing.length) * 100)}% of original). This may indicate data loss. Read existing content with get_site_custom_code first, then merge your changes.`,
434
+ error: `BLOCKED: Field "${field}" would shrink from ${existing.length} to ${newVal.length} chars (${Math.round((newVal.length / existing.length) * 100)}% of original). This may indicate data loss. Read existing content with get_site_custom_code first, then merge your changes. If native elements or the CMS replaced this code, pass allow_shrink:true.`,
419
435
  existing_preview: existing.substring(0, 500),
420
436
  comparison,
421
437
  };
@@ -425,22 +441,26 @@ IMPORTANT: Before calling, you MUST read existing code with get_site_custom_code
425
441
  return { success: true, comparison };
426
442
  });
427
443
  });
428
- server.tool("append_site_custom_code", `Append or prepend code to a custom code field WITHOUT reading the existing content first.
429
- Use this when you need to ADD new CSS rules, JS code, or script tags — no need to read first.
444
+ server.tool("append_site_custom_code", `Append or prepend code to a custom code field.
445
+ LAST RESORT: use native elements, their settings or an app first; a special feature uses the CMS app (collection + HTTP function) with only a small glue script here. See get_build_guide → NATIVE FIRST. Oversized code or UI/data in code is refused unless native_gap explains why.
430
446
  For full rewrites, use update_site_custom_code instead.`, {
431
447
  field: z.enum(["code_before_head", "code_before_body", "code_custom_css", "code_custom_javascript"])
432
448
  .describe("Which code field to modify"),
433
449
  code: z.string().describe("Code to add"),
434
450
  position: z.enum(["append", "prepend"]).default("append").describe("Add to end (append) or beginning (prepend)"),
435
- }, ({ field, code, position }) => handle(async () => {
436
- const existing = await api.getSiteSettingField(field);
437
- let content = existing || "";
451
+ native_gap: NATIVE_GAP,
452
+ }, ({ field, code, position, native_gap }) => handle(async () => {
453
+ const current = await readSiteCode(api);
454
+ let content = current[field] || "";
438
455
  if (position === "prepend") {
439
456
  content = code.trimEnd() + "\n\n" + content.trimStart();
440
457
  }
441
458
  else {
442
459
  content = content.trimEnd() + "\n\n" + code.trimEnd() + "\n";
443
460
  }
461
+ const blocked = codeGuard(checkSiteCode(current, { [field]: content }), native_gap);
462
+ if (blocked)
463
+ return blocked;
444
464
  await api.updateSiteSettings({ [field]: content });
445
465
  return { success: true, field, position, new_length: content.length };
446
466
  }));
@@ -478,6 +498,9 @@ IMPORTANT: Before calling, you MUST read existing content with list_page_content
478
498
  // Safeguard: read existing content and block if new content is suspiciously smaller
479
499
  const existingRes = await api.getPageContent(page_id, language_code);
480
500
  const existing = existingRes?.data ?? existingRes;
501
+ const placeholders = checkContentPlaceholders(content, existing?.content);
502
+ if (placeholders.length)
503
+ return { error: "BLOCKED: not saving.", errors: placeholders };
481
504
  if (existing && existing.content) {
482
505
  const existingStr = JSON.stringify(existing.content);
483
506
  const newStr = JSON.stringify(content);
@@ -528,7 +551,8 @@ events/bindings = REPLACE the whole array — pass the COMPLETE list (read it fi
528
551
  events: z.array(z.record(z.any())).optional().describe("Complete events array (replaces existing)"),
529
552
  bindings: z.array(z.record(z.any())).optional().describe("Complete bindings array (replaces existing)"),
530
553
  responsive: z.record(z.any()).optional().describe("Responsive breakpoint overrides (e.g. {bp1: {style: {...}, config: {...}}})"),
531
- }, ({ page_id, element_id, dry_run: dryRunParam, ...updates }) => handle(async () => {
554
+ allow_shrink: ALLOW_SHRINK,
555
+ }, ({ page_id, element_id, dry_run: dryRunParam, allow_shrink, ...updates }) => handle(async () => {
532
556
  const dry_run = dryRunParam !== undefined ? dryRunParam : getConfirmMode() === "always_confirm";
533
557
  invalidatePageCache();
534
558
  const { page, source, error } = await getPageWithSource(api, page_id);
@@ -541,6 +565,9 @@ events/bindings = REPLACE the whole array — pass the COMPLETE list (read it fi
541
565
  return { error: `Element "${element_id}" not found` };
542
566
  const beforeNode = JSON.parse(JSON.stringify(node));
543
567
  applyNodeUpdates(node, updates);
568
+ const codeErrors = checkElementPatch(source, node, beforeNode, updates.specials);
569
+ if (codeErrors.length)
570
+ return { error: "BLOCKED: not saving.", element_id, errors: codeErrors };
544
571
  const diff = computeNodeDiff(beforeNode, node);
545
572
  if (!diff)
546
573
  return { info: "No changes detected", element_id };
@@ -555,7 +582,7 @@ events/bindings = REPLACE the whole array — pass the COMPLETE list (read it fi
555
582
  // Actual save — send source as OBJECT (not string) because backend does Jason.encode!
556
583
  const newLen = JSON.stringify(source).length;
557
584
  const existingLen = JSON.stringify(parseSource(page.source && page.source.source)).length;
558
- if (existingLen > 200 && newLen < existingLen * 0.5) {
585
+ if (!allow_shrink && existingLen > 200 && newLen < existingLen * 0.5) {
559
586
  return {
560
587
  error: `BLOCKED: Page source would shrink from ${existingLen} to ${newLen} chars. This indicates data loss.`,
561
588
  existing_length: existingLen,
@@ -586,7 +613,8 @@ Same merge rules: style/config/specials = shallow merge, events/bindings = repla
586
613
  bindings: z.array(z.record(z.any())).optional(),
587
614
  responsive: z.record(z.any()).optional(),
588
615
  })).describe("Array of element updates"),
589
- }, ({ page_id, dry_run: dryRunParam, updates: elementUpdates }) => handle(async () => {
616
+ allow_shrink: ALLOW_SHRINK,
617
+ }, ({ page_id, dry_run: dryRunParam, updates: elementUpdates, allow_shrink }) => handle(async () => {
590
618
  const dry_run = dryRunParam !== undefined ? dryRunParam : getConfirmMode() === "always_confirm";
591
619
  invalidatePageCache();
592
620
  const { page, source, error } = await getPageWithSource(api, page_id);
@@ -604,6 +632,9 @@ Same merge rules: style/config/specials = shallow merge, events/bindings = repla
604
632
  const beforeNode = JSON.parse(JSON.stringify(node));
605
633
  const { element_id, ...updates } = upd;
606
634
  applyNodeUpdates(node, updates);
635
+ const codeErrors = checkElementPatch(source, node, beforeNode, updates.specials);
636
+ if (codeErrors.length)
637
+ return { error: "BLOCKED: not saving any of this batch.", element_id, errors: codeErrors };
607
638
  const diff = computeNodeDiff(beforeNode, node);
608
639
  results.push({ element_id, diff: diff || "no changes" });
609
640
  }
@@ -617,7 +648,7 @@ Same merge rules: style/config/specials = shallow merge, events/bindings = repla
617
648
  // Actual save — send source as OBJECT (not string) because backend does Jason.encode!
618
649
  const newLen = JSON.stringify(source).length;
619
650
  const existingLen = JSON.stringify(parseSource(page.source && page.source.source)).length;
620
- if (existingLen > 200 && newLen < existingLen * 0.5) {
651
+ if (!allow_shrink && existingLen > 200 && newLen < existingLen * 0.5) {
621
652
  return {
622
653
  error: `BLOCKED: Page source would shrink from ${existingLen} to ${newLen} chars. This indicates data loss.`,
623
654
  existing_length: existingLen,
@@ -639,27 +670,35 @@ IMPORTANT: Before calling this tool, you MUST:
639
670
  Safeguarded: blocks if new source is <50% of existing size.`, {
640
671
  page_id: z.string().describe("Page ID"),
641
672
  source: z.any().describe("Full page source object (sections tree) or JSON string"),
642
- custom_code: z.string().optional().describe("Custom code (CSS/JS) for this page"),
643
- }, ({ page_id, source, custom_code }) => handle(async () => {
673
+ custom_code: z.string().optional().describe("Custom code (CSS/JS) for this page. Last resort, same rules as update_site_custom_code."),
674
+ native_gap: NATIVE_GAP,
675
+ allow_shrink: ALLOW_SHRINK,
676
+ }, ({ page_id, source, custom_code, native_gap, allow_shrink }) => handle(async () => {
644
677
  const body = {};
645
678
  if (source != null) {
646
679
  // Ensure source is an object — backend does Jason.encode! so we must send object, not string
647
680
  body.source = typeof source === "string" ? JSON.parse(source) : source;
648
681
  }
649
682
  if (custom_code != null) {
683
+ invalidatePageCache();
684
+ const { page } = await getPageWithSource(api, page_id);
685
+ const old = page?.source?.custom_code;
686
+ const blocked = codeGuard(checkSiteCode({ code_custom_javascript: typeof old === "string" ? old : JSON.stringify(old ?? "") }, { code_custom_javascript: custom_code }), native_gap);
687
+ if (blocked)
688
+ return blocked;
650
689
  body.custom_code = custom_code;
651
690
  }
652
691
  // Safeguard: force fresh read and block if new source is suspiciously smaller
653
692
  if (body.source) {
654
- const embeds = checkEmbeds(body.source);
655
- if (embeds.errors.length)
656
- return { error: "BLOCKED: whole-page HTML embed — not saving.", errors: embeds.errors };
657
693
  invalidatePageCache();
658
694
  const { source: existingSource, error } = await getPageWithSource(api, page_id);
695
+ const code = checkNativeContent(body.source, existingSource || undefined);
696
+ if (code.errors.length)
697
+ return { error: "BLOCKED: not saving.", errors: code.errors };
659
698
  if (!error && existingSource) {
660
699
  const existingLen = JSON.stringify(existingSource).length;
661
700
  const newLen = JSON.stringify(body.source).length;
662
- if (existingLen > 200 && newLen < existingLen * 0.5) {
701
+ if (!allow_shrink && existingLen > 200 && newLen < existingLen * 0.5) {
663
702
  return {
664
703
  error: `BLOCKED: New source (${newLen} chars) is much smaller than existing (${existingLen} chars) — ${Math.round((newLen / existingLen) * 100)}% of original. This may indicate fabricated data or data loss. Read the page source with get_page_source/get_page_element first, then apply changes.`,
665
704
  existing_length: existingLen,
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { SITE_CODE_FIELDS } from "../builder/native-first.js";
2
3
  // Site-level configuration the dashboard manages: custom domains, SEO redirect URLs,
3
4
  // shipping rules, marketing UTM links, system logs, saved table filters, general site
4
5
  // settings, site rename/slug, fonts, API keys, and publish history.
@@ -79,7 +80,26 @@ export function registerSiteConfigTools(server, api, handle) {
79
80
  server.tool("delete_saved_filter", "Delete (or dismiss, if not owner) a saved filter by id.", { id: z.string().describe("Saved filter id") }, ({ id }) => handle(() => api.deleteSavedFilter(id)));
80
81
  // ── General settings / rename ──
81
82
  server.tool("update_site_settings", `Update general site settings. The \`settings\` object is shallow-merged onto existing settings;
82
- other top-level keys (currency, slugs, is_maintenance, robot_txt, …) replace directly.`, { settings: z.record(z.any()).describe("Top-level keys to update (nested settings:{...} merges; others replace)") }, ({ settings }) => handle(() => api.updateSiteRaw(settings)));
83
+ other top-level keys (currency, slugs, is_maintenance, robot_txt, …) replace directly.`, { settings: z.record(z.any()).describe("Top-level keys to update (nested settings:{...} merges; others replace)") }, ({ settings }) => handle(async () => {
84
+ // Custom code only changes through update_site_custom_code, where the native-first checks live.
85
+ // Sending it back unchanged is fine: that's a read-modify-write of the whole settings object.
86
+ const blocked = { error: "BLOCKED: custom code fields can't be changed here. Use update_site_custom_code." };
87
+ let nested = settings.settings;
88
+ if (typeof nested === "string") {
89
+ try {
90
+ nested = JSON.parse(nested);
91
+ }
92
+ catch {
93
+ nested = null;
94
+ }
95
+ }
96
+ const sent = { ...settings, ...(nested && typeof nested === "object" ? nested : {}) };
97
+ for (const field of SITE_CODE_FIELDS) {
98
+ if (field in sent && String(sent[field] ?? "") !== String((await api.getSiteSettingField(field)) ?? ""))
99
+ return blocked;
100
+ }
101
+ return api.updateSiteRaw(settings);
102
+ }));
83
103
  server.tool("rename_site", "Rename the site (display name).", { name: z.string().describe("New site name") }, ({ name }) => handle(() => api.updateSiteName(name)));
84
104
  server.tool("update_site_slug", "Change the site's slug (subdomain). Fails if the slug is already taken.", { slug: z.string().describe("New slug") }, ({ slug }) => handle(() => api.updateSiteSlug(slug)));
85
105
  // ── Fonts ──
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webcake-storefront-mcp",
3
- "version": "1.36.2",
3
+ "version": "1.37.0",
4
4
  "description": "MCP server for the WebCake/StoreCake storefront builder — page CRUD, page authoring, products, orders, and more",
5
5
  "mcpName": "io.github.vuluu2k/webcake-storefront-mcp",
6
6
  "license": "MIT",