webcake-storefront-mcp 1.36.2 → 1.38.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/dist/install.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // Installer: writes (or removes) this MCP server's entry in the config files of the
2
- // supported IDEs / agents. Flag-driven; falls back to a friendly numbered wizard on a
3
- // TTY. Mirrors webcake-landing-mcp's installer (numbered choices, colours, multi-IDE).
4
- import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ // supported IDEs / agents. A plain run connects to prod via the browser and
3
+ // configures the detected IDEs with no questions; --dev opens the numbered wizard. Mirrors webcake-landing-mcp's installer (numbered choices, colours, multi-IDE).
4
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
5
5
  import { homedir, platform } from "node:os";
6
6
  import { dirname, join } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
@@ -63,6 +63,8 @@ function parseArgs(argv) {
63
63
  o.launch = "npx";
64
64
  else if (a === "--local")
65
65
  o.launch = "local";
66
+ else if (a === "--dev")
67
+ o.dev = true;
66
68
  }
67
69
  return o;
68
70
  }
@@ -91,7 +93,20 @@ function buildEnv(opts) {
91
93
  return env;
92
94
  }
93
95
  // ── generic JSON config (Claude Desktop/Code, Cursor, Windsurf, VS Code, …) ───
94
- function mergeJson(file, launch, env) {
96
+ // These are the user's own files: an unchanged one isn't touched, a changed one keeps
97
+ // its previous version alongside so the install can be undone.
98
+ function writeConfig(file, next) {
99
+ if (existsSync(file)) {
100
+ if (readFileSync(file, "utf8") === next)
101
+ return;
102
+ const backup = `${file}.${NAME}-backup`;
103
+ copyFileSync(file, backup);
104
+ info(`Previous file saved as ${backup}`);
105
+ }
106
+ writeFileSync(file, next);
107
+ }
108
+ // VS Code is the one client that keeps servers under `servers` (and requires `type`).
109
+ function mergeJson(file, launch, env, key = "mcpServers") {
95
110
  mkdirSync(dirname(file), { recursive: true });
96
111
  let cfg = {};
97
112
  if (existsSync(file)) {
@@ -106,14 +121,15 @@ function mergeJson(file, launch, env) {
106
121
  }
107
122
  }
108
123
  }
109
- if (typeof cfg.mcpServers !== "object" || !cfg.mcpServers)
110
- cfg.mcpServers = {};
111
- cfg.mcpServers[NAME] = {
124
+ if (typeof cfg[key] !== "object" || !cfg[key])
125
+ cfg[key] = {};
126
+ cfg[key][NAME] = {
127
+ ...(key === "servers" ? { type: "stdio" } : {}),
112
128
  command: launch.command,
113
129
  args: launch.args,
114
130
  ...(Object.keys(env).length ? { env } : {}),
115
131
  };
116
- writeFileSync(file, JSON.stringify(cfg, null, 2) + "\n");
132
+ writeConfig(file, JSON.stringify(cfg, null, 2) + "\n");
117
133
  return true;
118
134
  }
119
135
  // ── OpenCode config (its own shape, not mcpServers) ──────────────────────────
@@ -141,7 +157,7 @@ function mergeOpencodeJson(file, launch, env) {
141
157
  enabled: true,
142
158
  ...(Object.keys(env).length ? { environment: env } : {}),
143
159
  };
144
- writeFileSync(file, JSON.stringify(cfg, null, 2) + "\n");
160
+ writeConfig(file, JSON.stringify(cfg, null, 2) + "\n");
145
161
  return true;
146
162
  }
147
163
  // ── TOML config (Codex) ──────────────────────────────────────────────────────
@@ -149,16 +165,15 @@ function configureCodex(launch, env) {
149
165
  const dir = join(HOME, ".codex");
150
166
  const cfg = join(dir, "config.toml");
151
167
  mkdirSync(dir, { recursive: true });
152
- const argsToml = launch.args.map((a) => `"${a}"`).join(", ");
168
+ const argsToml = launch.args.map((a) => JSON.stringify(a)).join(", ");
153
169
  const envParts = Object.entries(env)
154
- .map(([k, v]) => `"${k}" = "${v}"`)
170
+ .map(([k, v]) => `${JSON.stringify(k)} = ${JSON.stringify(v)}`)
155
171
  .join(", ");
156
172
  const envLine = envParts ? `env = { ${envParts} }\n` : "";
157
- const block = `\n[mcp_servers.${NAME}]\ncommand = "${launch.command}"\nargs = [${argsToml}]\n${envLine}`;
173
+ const block = `\n[mcp_servers.${NAME}]\ncommand = ${JSON.stringify(launch.command)}\nargs = [${argsToml}]\n${envLine}`;
158
174
  let content = existsSync(cfg) ? readFileSync(cfg, "utf8") : "# WebCake Storefront MCP\n";
159
175
  content = content.replace(new RegExp(`\\n?\\[mcp_servers\\.${NAME}\\][\\s\\S]*?(?=\\n\\[|$)`), "");
160
- content = content.trimEnd() + "\n" + block;
161
- writeFileSync(cfg, content);
176
+ writeConfig(cfg, content.trimEnd() + "\n" + block);
162
177
  }
163
178
  // ── IDE config-file locations ────────────────────────────────────────────────
164
179
  function claudeDesktopPath() {
@@ -188,10 +203,7 @@ function vscodeUserDir() {
188
203
  const mac = join(HOME, "Library", "Application Support", "Code", "User");
189
204
  if (existsSync(mac))
190
205
  return mac;
191
- const lin = join(HOME, ".config", "Code", "User");
192
- if (existsSync(lin))
193
- return lin;
194
- return join(HOME, ".vscode");
206
+ return join(HOME, ".config", "Code", "User");
195
207
  }
196
208
  const vscodeUserPath = () => join(vscodeUserDir(), "mcp.json");
197
209
  const cursorPath = () => join(HOME, ".cursor", "mcp.json");
@@ -206,13 +218,31 @@ function hasClaudeCli() {
206
218
  const probe = spawnSync(PLAT === "win32" ? "where" : "which", ["claude"], { stdio: "ignore" });
207
219
  return probe.status === 0;
208
220
  }
221
+ // Installed = its config dir exists (Claude Code: also the CLI on PATH), so a normal
222
+ // install needs no IDE question and never creates config for an app the user lacks.
223
+ function detectIdes() {
224
+ const marks = {
225
+ "claude-desktop": dirname(claudeDesktopPath()),
226
+ "claude-code": claudeJsonPath(),
227
+ cursor: join(HOME, ".cursor"),
228
+ windsurf: join(HOME, ".codeium", "windsurf"),
229
+ augment: vscodeUserDir(),
230
+ codex: join(HOME, ".codex"),
231
+ antigravity: dirname(antigravityPath()),
232
+ gemini: geminiPath(),
233
+ cline: dirname(dirname(clinePath())),
234
+ kiro: join(HOME, ".kiro"),
235
+ opencode: dirname(opencodePath()),
236
+ };
237
+ return Object.keys(marks).filter((id) => existsSync(marks[id]) || (id === "claude-code" && hasClaudeCli()));
238
+ }
209
239
  // ── per-IDE configure ────────────────────────────────────────────────────────
210
240
  function configureClaudeCode(launch, env) {
211
241
  info("Claude Code…");
212
242
  if (hasClaudeCli()) {
213
243
  spawnSync("claude", ["mcp", "remove", NAME], { stdio: "ignore" });
214
244
  const envFlags = Object.entries(env).flatMap(([k, v]) => ["-e", `${k}=${v}`]);
215
- const r = spawnSync("claude", ["mcp", "add", NAME, ...envFlags, "--", launch.command, ...launch.args], {
245
+ const r = spawnSync("claude", ["mcp", "add", "--scope", "user", NAME, ...envFlags, "--", launch.command, ...launch.args], {
216
246
  stdio: "inherit",
217
247
  });
218
248
  if (r.status === 0) {
@@ -243,7 +273,7 @@ function configureWindsurf(launch, env) {
243
273
  }
244
274
  function configureAugment(launch, env) {
245
275
  info("Augment / VS Code…");
246
- if (mergeJson(vscodeUserPath(), launch, env))
276
+ if (mergeJson(vscodeUserPath(), launch, env, "servers"))
247
277
  ok(`VS Code configured (${vscodeUserPath()})`);
248
278
  }
249
279
  function configureCodexIde(launch, env) {
@@ -329,10 +359,17 @@ function normalizeIdes(ides) {
329
359
  function runConfigure(ides, launch, env) {
330
360
  for (const id of ides) {
331
361
  const conf = CONFIGURATORS[id];
332
- if (conf)
333
- conf.run(launch, env);
334
- else
362
+ if (!conf) {
335
363
  warn(`Unknown IDE: ${id}`);
364
+ continue;
365
+ }
366
+ // One broken client must not leave the others unconfigured.
367
+ try {
368
+ conf.run(launch, env);
369
+ }
370
+ catch (e) {
371
+ warn(`${conf.label} skipped: ${e?.message ?? e}`);
372
+ }
336
373
  }
337
374
  }
338
375
  // ── uninstall ────────────────────────────────────────────────────────────────
@@ -341,8 +378,10 @@ function removeFromJson(file) {
341
378
  return;
342
379
  try {
343
380
  const cfg = JSON.parse(readFileSync(file, "utf8"));
344
- if (cfg.mcpServers && cfg.mcpServers[NAME]) {
345
- delete cfg.mcpServers[NAME];
381
+ const holders = [cfg.mcpServers, cfg.servers].filter((s) => s && s[NAME]);
382
+ if (holders.length) {
383
+ for (const s of holders)
384
+ delete s[NAME];
346
385
  writeFileSync(file, JSON.stringify(cfg, null, 2) + "\n");
347
386
  ok(`Cleaned ${file}`);
348
387
  }
@@ -362,6 +401,7 @@ function uninstall() {
362
401
  cursorPath(),
363
402
  windsurfPath(),
364
403
  vscodeUserPath(),
404
+ join(HOME, ".vscode", "mcp.json"), // older versions wrote here; nothing reads it
365
405
  antigravityPath(),
366
406
  geminiPath(),
367
407
  clinePath(),
@@ -392,18 +432,19 @@ function uninstall() {
392
432
  log(`\n${c.green}${c.bold} ✓ Removed. Restart your IDE.${c.reset}\n`);
393
433
  }
394
434
  /**
395
- * Interactive numbered wizard (TTY only): pick environment → authenticate (browser
396
- * login, recommended, or paste a token) → pick IDEs by number. Returns whether a
397
- * browser login completed (token then lives in the local config db, so it is NOT
435
+ * Default: prod, straight to the browser connect page, every detected IDE — never a
436
+ * question, TTY or not (only a scripted --ide run without a TTY skips the browser).
437
+ * --dev on a TTY: the numbered wizard (environment → login or pasted token → IDEs). Returns whether a browser
438
+ * login completed (token then lives in the local config db, so it is NOT
398
439
  * written into the IDE env block) and a short auth note for the summary.
399
440
  */
400
441
  async function promptInteractive(opts) {
401
442
  let loggedIn = false;
402
443
  let authNote = opts.token ? "token (from flag)" : "";
403
- if (!process.stdin.isTTY || !process.stdout.isTTY)
404
- return { loggedIn, authNote };
444
+ const tty = process.stdin.isTTY && process.stdout.isTTY;
445
+ const wizard = opts.dev && tty;
405
446
  // 1) Environment — one choice sets the API + app base URLs (default prod).
406
- if (!opts.env && !process.env.WEBCAKE_ENV) {
447
+ if (wizard && !opts.env && !process.env.WEBCAKE_ENV) {
407
448
  log(`\n${c.bold}1) Environment${c.reset} ${c.gray}(sets the WebCake API + app URLs)${c.reset}`);
408
449
  log(` ${c.bold}1${c.reset}) prod ${c.gray}api.storefront.webcake.io${c.reset} ${c.gray}(default)${c.reset}`);
409
450
  log(` ${c.bold}2${c.reset}) staging ${c.gray}api.staging.storecake.io${c.reset}`);
@@ -411,15 +452,18 @@ async function promptInteractive(opts) {
411
452
  const pick = (await ask(` ${c.cyan}Select [1=prod, Enter to accept]:${c.reset} `)).trim();
412
453
  opts.env = { "1": "prod", "2": "staging", "3": "local" }[pick] ?? "prod";
413
454
  }
414
- if (opts.env)
415
- process.env.WEBCAKE_ENV = opts.env; // so the login flow opens the right app
455
+ opts.env ||= process.env.WEBCAKE_ENV || "prod";
456
+ process.env.WEBCAKE_ENV = opts.env; // so the login flow opens the right app
416
457
  // 2) Authentication — browser login (recommended), paste a token, or skip.
417
- if (!opts.token && !process.env.WEBCAKE_TOKEN) {
418
- log(`\n${c.bold}2) Connect your WebCake account${c.reset}`);
419
- log(` ${c.bold}1${c.reset}) Log in via browser ${c.gray}(recommended — opens WebCake, saves a token)${c.reset}`);
420
- log(` ${c.bold}2${c.reset}) Paste a token manually`);
421
- log(` ${c.bold}3${c.reset}) Skip for now ${c.gray}(set credentials later with the login command)${c.reset}`);
422
- const choice = (await ask(` ${c.cyan}Select [1]:${c.reset} `)).trim() || "1";
458
+ if (!opts.token && !process.env.WEBCAKE_TOKEN && (tty || !opts.ides.length)) {
459
+ let choice = "1";
460
+ if (wizard) {
461
+ log(`\n${c.bold}2) Connect your WebCake account${c.reset}`);
462
+ log(` ${c.bold}1${c.reset}) Log in via browser ${c.gray}(recommended — opens WebCake, saves a token)${c.reset}`);
463
+ log(` ${c.bold}2${c.reset}) Paste a token manually`);
464
+ log(` ${c.bold}3${c.reset}) Skip for now ${c.gray}(set credentials later with the login command)${c.reset}`);
465
+ choice = (await ask(` ${c.cyan}Select [1]:${c.reset} `)).trim() || "1";
466
+ }
423
467
  if (choice === "1") {
424
468
  info("Opening your browser to log in…");
425
469
  try {
@@ -428,13 +472,15 @@ async function promptInteractive(opts) {
428
472
  authNote = "browser login (saved to local config)";
429
473
  }
430
474
  catch (e) {
431
- warn(`Login didn't complete (${e?.message ?? e}). Paste a token now, or run \`npx -y ${PKG} login\` later.`);
432
- const t = (await ask(` ${c.cyan}Token (paste JWT, or Enter to skip):${c.reset} `)).trim();
433
- if (t)
434
- opts.token = t;
435
- const s = t ? (await ask(` ${c.cyan}Session id (x-session-id):${c.reset} `)).trim() : "";
436
- if (s)
437
- opts.sessionId = s;
475
+ warn(`Login didn't complete (${e?.message ?? e}). Run \`npx -y ${PKG} login\` to connect later.`);
476
+ if (wizard) {
477
+ const t = (await ask(` ${c.cyan}Token (paste JWT, or Enter to skip):${c.reset} `)).trim();
478
+ if (t)
479
+ opts.token = t;
480
+ const s = t ? (await ask(` ${c.cyan}Session id (x-session-id):${c.reset} `)).trim() : "";
481
+ if (s)
482
+ opts.sessionId = s;
483
+ }
438
484
  }
439
485
  }
440
486
  else if (choice === "2") {
@@ -450,7 +496,9 @@ async function promptInteractive(opts) {
450
496
  if (!authNote)
451
497
  authNote = opts.token || process.env.WEBCAKE_TOKEN ? "token" : "none — log in later";
452
498
  // 3) IDEs to configure — numbered, comma-separated (e.g. 1,2 or the "All" number).
453
- if (!opts.ides.length) {
499
+ if (!opts.ides.length && !wizard)
500
+ opts.ides = detectIdes();
501
+ else if (!opts.ides.length) {
454
502
  log(`\n${c.bold}3) Which IDE(s) / agent(s) to configure?${c.reset}`);
455
503
  IDE_ORDER.forEach((id, i) => {
456
504
  const n = `${c.bold}${String(i + 1).padStart(2)}${c.reset}`;
@@ -483,13 +531,13 @@ export async function runInstaller(argv) {
483
531
  // promptInteractive returns early without touching opts.ides.
484
532
  const ides = normalizeIdes(opts.ides);
485
533
  if (!ides.length) {
486
- if (!process.stdin.isTTY) {
487
- warn("No --ide given (or not a TTY). Nothing to configure.");
488
- log(`${c.gray} Try: npx -y ${PKG} install --ide all${c.reset}\n`);
489
- }
490
- else {
534
+ if (opts.dev) {
491
535
  warn("No IDE selected — nothing to configure.");
536
+ return;
492
537
  }
538
+ warn("No AI app found on this computer (Claude, Cursor, VS Code…).");
539
+ log(`${c.gray} Install one and run this again, or name it: npx -y ${PKG} install --ide <name>${c.reset}\n`);
540
+ process.exitCode = 1;
493
541
  return;
494
542
  }
495
543
  const launch = resolveLaunch(opts);
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 });