webcake-storefront-mcp 1.37.0 → 1.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -100,29 +100,42 @@ Pick **one**. Both hand your AI tool the full storefront toolkit. No coding.
100
100
 
101
101
  ### ① `npx` — runs on your machine (recommended)
102
102
 
103
- Zero install, always the latest version, needs Node.js 18+. **One line** configures your IDE:
103
+ Zero install, always the latest version, needs Node.js 18+. **One line** connects your account and configures your AI apps:
104
104
 
105
105
  ```bash
106
- # Interactive — pick your IDE(s) and paste your credentials
106
+ # Opens the browser — click Connect, your installed IDEs are configured (prod)
107
107
  npx -y webcake-storefront-mcp install
108
108
 
109
- # Non-interactive — configure every supported IDE at once
109
+ # Developers only — step by step: environment, login or token, IDE(s)
110
+ npx -y webcake-storefront-mcp install --dev
111
+
112
+ # Scripts and CI — every supported IDE, even ones not installed yet
110
113
  npx -y webcake-storefront-mcp install --ide all --token <token> --session <session-id>
111
114
 
112
115
  # Remove the server from every IDE config
113
116
  npx -y webcake-storefront-mcp uninstall
114
117
  ```
115
118
 
116
- Targets: `claude-desktop`, `claude-code`, `cursor`, `windsurf`, `vscode`, or `all`.
119
+ **`install` asks nothing.** It connects to production, opens your browser so you can click *Connect*, then adds the server
120
+ to every AI app it finds on this computer. Your other servers are kept, and any config file it changes is backed up next to
121
+ the original as `<file>.webcake-storefront-backup`. No AI app found? It says so and exits with an error: install one and run it again,
122
+ or name it with `--ide`.
123
+
124
+ Need staging or local? `--dev` opens the step-by-step wizard, or skip it with `--env staging` / `--env local`.
125
+
126
+ > **Installed with an older version?** Run `install` again. Older versions wrote VS Code's config under the wrong key, so the
127
+ > server never appeared there, and registered Claude Code for the current folder only.
128
+
129
+ Targets for `--ide`: `claude-desktop`, `claude-code`, `cursor`, `windsurf`, `vscode`, `codex`, `antigravity`, `gemini`, `cline`, `kiro`, `opencode`, or `all`.
117
130
  Just want to run the server (configure by hand)? `npx -y webcake-storefront-mcp`.
118
131
 
119
- ### ② Browser login — no token copy/paste
132
+ ### ② Reconnect your account — no token copy/paste
120
133
 
121
134
  ```bash
122
135
  npx -y webcake-storefront-mcp login
123
136
  ```
124
137
 
125
- Opens the builder's **connect page**; click *Connect* and your token + session are saved locally and picked up automatically.
138
+ `install` already does this the first time. Use `login` when your token expires: it opens the builder's **connect page**, you click *Connect*, and your token + session are saved locally and picked up automatically.
126
139
 
127
140
  ### Remote URL — self-hosted, nothing per-client to install
128
141
 
package/README.vi.md CHANGED
@@ -100,29 +100,41 @@ Chọn **một**. Cả hai đều trao cho AI toàn bộ bộ công cụ storefr
100
100
 
101
101
  ### ① `npx` — chạy trên máy bạn (khuyên dùng)
102
102
 
103
- Không cần cài, luôn mới nhất, cần Node.js 18+. **Một dòng** cấu hình IDE:
103
+ Không cần cài, luôn mới nhất, cần Node.js 18+. **Một dòng** kết nối tài khoản và cấu hình các ứng dụng AI:
104
104
 
105
105
  ```bash
106
- # Tương tác — chọn IDE và dán thông tin
106
+ # Mở trình duyệt — bấm Kết nối, các IDE trên máy được cấu hình tự động (prod)
107
107
  npx -y webcake-storefront-mcp install
108
108
 
109
- # Phi tương tác — cấu hình mọi IDE hỗ trợ cùng lúc
109
+ # Chỉ dành cho dev — từng bước: môi trường, đăng nhập hoặc token, IDE
110
+ npx -y webcake-storefront-mcp install --dev
111
+
112
+ # Script và CI — mọi IDE được hỗ trợ, kể cả IDE chưa cài
110
113
  npx -y webcake-storefront-mcp install --ide all --token <token> --session <session-id>
111
114
 
112
115
  # Gỡ khỏi mọi IDE
113
116
  npx -y webcake-storefront-mcp uninstall
114
117
  ```
115
118
 
116
- Hỗ trợ: `claude-desktop`, `claude-code`, `cursor`, `windsurf`, `vscode`, hoặc `all`.
119
+ **`install` không hỏi gì cả.** Lệnh kết nối tới production, mở trình duyệt để bạn bấm *Kết nối*, rồi thêm server vào mọi ứng dụng AI
120
+ tìm thấy trên máy. Các server khác của bạn được giữ nguyên, và file cấu hình nào bị đổi đều có bản sao lưu ngay cạnh, tên
121
+ `<file>.webcake-storefront-backup`. Không tìm thấy ứng dụng AI nào? Lệnh báo rõ và thoát với lỗi: hãy cài một ứng dụng rồi chạy lại, hoặc chỉ định bằng `--ide`.
122
+
123
+ Cần staging hoặc local? `--dev` mở các bước hỏi lần lượt, hoặc bỏ qua bằng `--env staging` / `--env local`.
124
+
125
+ > **Đã cài bằng bản cũ?** Hãy chạy lại `install`. Bản cũ ghi cấu hình VS Code sai khóa nên server không hiện trong VS Code, và chỉ đăng ký
126
+ > Claude Code cho đúng thư mục lúc chạy lệnh.
127
+
128
+ Giá trị cho `--ide`: `claude-desktop`, `claude-code`, `cursor`, `windsurf`, `vscode`, `codex`, `antigravity`, `gemini`, `cline`, `kiro`, `opencode`, hoặc `all`.
117
129
  Chỉ muốn chạy server (cấu hình tay)? `npx -y webcake-storefront-mcp`.
118
130
 
119
- ### ② Đăng nhập trình duyệt — khỏi copy token
131
+ ### ② Kết nối lại tài khoản — khỏi copy token
120
132
 
121
133
  ```bash
122
134
  npx -y webcake-storefront-mcp login
123
135
  ```
124
136
 
125
- Mở **trang kết nối** của builder; bấm *Kết nối* là token + session được lưu cục bộ và tự nạp.
137
+ `install` đã làm việc này ở lần đầu. Dùng `login` khi token hết hạn: lệnh mở **trang kết nối** của builder, bấm *Kết nối* là token + session được lưu cục bộ và tự nạp.
126
138
 
127
139
  ### Remote URL — tự host, mỗi client khỏi cài gì
128
140
 
package/dist/api.js CHANGED
@@ -1,9 +1,15 @@
1
+ import { buildSection, finalizeForRender } from "./builder/page.js";
1
2
  import { BREAKPOINTS } from "./builder/grid.js";
2
3
  const DEFAULT_TIMEOUT = 15000;
3
4
  /** Stamped on every site and page this MCP server creates (backend columns `sites.by_ai`
4
5
  * and `pages.by_ai`), so the builder can flag AI-authored work. Mirrors the landing-page convention. */
5
6
  export const BY_AI_MARKER = "mcp";
6
7
  const SETTINGS_READ_ERR = "Không đọc được site settings, huỷ lưu để tránh ghi đè rỗng";
8
+ const listOf = (r) => (Array.isArray(r?.data) ? r.data : Array.isArray(r) ? r : []);
9
+ const parseMaybe = (v) => (typeof v === "string" ? (v ? JSON.parse(v) : null) : v ?? null);
10
+ const globalsOf = (src) => (src?.sections || []).filter((s) => s && s.specials && s.specials.global);
11
+ /** Key-order-independent JSON, so a re-serialised but equal node doesn't count as an edit. */
12
+ const canon = (v) => JSON.stringify(v ?? null, (_k, x) => (x && typeof x === "object" && !Array.isArray(x) ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => (a < b ? -1 : 1))) : x));
7
13
  export class WebcakeCmsApi {
8
14
  /** Parse (if string) and guarantee settings.breakpoints is a usable object — an empty/missing
9
15
  * breakpoints would make the backend compile CSS without media queries. */
@@ -30,7 +36,7 @@ export class WebcakeCmsApi {
30
36
  sessionId;
31
37
  _adminToken;
32
38
  _cmsApiKey;
33
- _siteBps = null;
39
+ _siteBps = null; // cached site.settings (breakpoints, defaultGrid)
34
40
  constructor({ baseUrl, token, siteId, sessionId }) {
35
41
  this.baseUrl = (baseUrl || "").replace(/\/$/, "");
36
42
  this.token = token;
@@ -155,11 +161,18 @@ export class WebcakeCmsApi {
155
161
  /** The site's breakpoints ({ bpN: [minW, maxW] } from settings, which may be a JSON string),
156
162
  * or null when unset/unreadable — callers then use the standard four. Cached per site. */
157
163
  getSiteBreakpoints() {
164
+ return this.siteLayout().then((s) => s?.breakpoints || null);
165
+ }
166
+ /** The site's section grid per breakpoint (settings.defaultGrid): the editor builds every new
167
+ * section from it (editor.js addBlankSection), so generated sections must too. */
168
+ getSiteDefaultGrid() {
169
+ return this.siteLayout().then((s) => s?.defaultGrid || null);
170
+ }
171
+ siteLayout() {
158
172
  this._siteBps ??= this.getSite()
159
173
  .then((res) => {
160
174
  const site = res?.data ?? res;
161
- const settings = typeof site?.settings === "string" ? JSON.parse(site.settings || "{}") : site?.settings;
162
- return settings?.breakpoints || null;
175
+ return (typeof site?.settings === "string" ? JSON.parse(site.settings || "{}") : site?.settings) || null;
163
176
  })
164
177
  .catch(() => {
165
178
  this._siteBps = null; // don't cache a failed lookup — retry on the next save
@@ -226,12 +239,14 @@ export class WebcakeCmsApi {
226
239
  * `slug`/`is_homepage` are NOT applied at create — set them afterwards via updatePage.
227
240
  * Every page born here is AI-authored, so we stamp `by_ai` (persisted to `pages.by_ai`)
228
241
  * and the builder shows an "AI" tag next to the page name. */
229
- createPage(params, opts) {
242
+ async createPage(params, opts) {
230
243
  const body = { ...params };
231
244
  if (body.source != null && typeof body.source !== "string")
232
245
  body.source = JSON.stringify(body.source);
246
+ // The editor never saves an empty page: it creates one blank grid section to drop into
247
+ // (editor.js createPage). An empty `sections` opened with nothing to drop elements on.
233
248
  if (body.source == null)
234
- body.source = JSON.stringify({ sections: [] });
249
+ body.source = JSON.stringify(finalizeForRender({ sections: [buildSection([])] }, await this.getSiteBreakpoints(), await this.getSiteDefaultGrid()));
235
250
  if (body.by_ai == null)
236
251
  body.by_ai = BY_AI_MARKER;
237
252
  return this.request("POST", `/api/v1/site/${this.siteId}/page`, { body, timeout: opts?.timeout });
@@ -239,8 +254,23 @@ export class WebcakeCmsApi {
239
254
  updatePage(pageId, params) {
240
255
  return this.request("POST", `/api/v1/site/${this.siteId}/${pageId}/update_page`, { body: params });
241
256
  }
242
- updatePageSource(pageId, params, opts) {
243
- return this.request("POST", `/api/v1/site/${this.siteId}/${pageId}/update_page_source`, { body: params, timeout: opts?.timeout });
257
+ /** Write a page source, then re-save it through /save like the editor (CSS + global sections,
258
+ * see syncPageAfterWrite). The source is already stored when the sync runs, so a sync failure
259
+ * says so instead of reading as a lost write. `sync:false` skips the /save, for intermediate
260
+ * writes of a batch whose last write syncs (each sync rebuilds the page CSS). */
261
+ async updatePageSource(pageId, params, opts) {
262
+ const sync = params && params.source != null && opts?.sync !== false;
263
+ const src = sync ? (typeof params.source === "string" ? JSON.parse(params.source) : params.source) : null;
264
+ // With a global section on the page, keep the sources as they were BEFORE this write: only a
265
+ // global node this write actually changed may be pushed to the other pages.
266
+ const before = src && globalsOf(src).length ? listOf(await this.listPages()) : null;
267
+ const res = await this.request("POST", `/api/v1/site/${this.siteId}/${pageId}/update_page_source`, { body: params, timeout: opts?.timeout });
268
+ if (sync) {
269
+ await this.syncPageAfterWrite(pageId, src, before).catch((e) => {
270
+ throw new Error(`Page source SAVED, but rebuilding its CSS / syncing global sections via /save failed: ${e?.message || e}. Retry the same write.`);
271
+ });
272
+ }
273
+ return res;
244
274
  }
245
275
  deletePage(params) {
246
276
  return this.request("POST", `/api/v1/site/${this.siteId}/delete_page`, { body: params });
@@ -264,136 +294,145 @@ export class WebcakeCmsApi {
264
294
  listGlobalSections() {
265
295
  return this.request("GET", `/api/v1/site/${this.siteId}/global_sections`);
266
296
  }
267
- /** Upsert/delete global sections (Header/Footer/reusable blocks) via the site /save
268
- * pipeline — the SAME endpoint the builder uses. Each entry carries a `status`
269
- * ("new"|"update"|"delete") and is matched by (site_id, section_id). `section` is sent
270
- * as an OBJECT (backend Jason.encode!s it). Optionally pass `pages` (each { id, source }
271
- * with source a JSON STRING) to embed the section node into page sources in the same
272
- * atomic save — required for a header/footer to actually render. `settings` MUST be the
273
- * current site settings (string) or /save would null them; we fetch them when omitted. */
274
- async saveGlobalSections({ global_sections = [], pages = [], settings, changes } = {}) {
275
- let s = settings;
276
- if (s === undefined)
277
- s = await this.readSettingsOrThrow();
278
- const settingsStr = JSON.stringify(this.ensureSafeSettings(s));
279
- return this.request("POST", `/api/v1/site/${this.siteId}/save`, {
297
+ /** The cart drawer + popups, as the editor sends them with every save and publish
298
+ * (PagePublish.vue: `global_sources: cart.source.concat(popup.popups)`). /save builds the
299
+ * cart CSS only from these, and /publish copies them into the LIVE global sources: sending []
300
+ * left popups and the cart unpublished and dropped the cart CSS. `source` goes as an object
301
+ * (the backend Jason.encode!s it). */
302
+ async globalSourcesForSave() {
303
+ const list = (r) => (Array.isArray(r?.data) ? r.data : Array.isArray(r) ? r : []);
304
+ const [cart, popups] = await Promise.all([this.getSourceCart(), this.getGlobalSources({ component: "popup" })]);
305
+ return [...list(cart), ...list(popups)].map((g) => ({
306
+ ...g,
307
+ source: typeof g.source === "string" ? JSON.parse(g.source) : g.source,
308
+ }));
309
+ }
310
+ /** POST /save or /publish with the body the editor sends (PagePublish.vue savePage):
311
+ * current site settings (or /save nulls them), the cart + popups, and the given pages /
312
+ * global sections. /publish is /save plus the live copy (site_controller.ex `publish` →
313
+ * `save(is_publish: true)`), so one call builds each page's CSS and publishes it. Every /save
314
+ * also stamps site.published_at, which opens the 10-minute draft preview. */
315
+ async siteSave(path, { pages = [], global_sections = [], changes = {}, domain }) {
316
+ const [settings, global_sources] = await Promise.all([this.readSettingsOrThrow(), this.globalSourcesForSave()]);
317
+ return this.request("POST", `/api/v1/site/${this.siteId}/${path}`, {
280
318
  body: {
281
- settings: settingsStr,
282
- global_sources: [],
283
- page_contents: [],
284
- changes: changes || {},
319
+ settings: JSON.stringify(this.ensureSafeSettings(settings)),
285
320
  pages,
321
+ changes,
322
+ global_sources,
286
323
  global_sections,
324
+ page_contents: [],
325
+ ...(domain ? { domain } : {}),
287
326
  },
288
327
  timeout: 120000,
289
328
  });
290
329
  }
291
- getSite() {
292
- return this.request("GET", `/api/v1/site/${this.siteId}/`);
293
- }
294
- saveSite(params = {}) {
295
- return this.request("POST", `/api/v1/site/${this.siteId}/save`, { body: params, timeout: 60000 });
330
+ /** A /save with no pages: stamps site.published_at, which (re)opens the draft preview window
331
+ * (PreviewExpire: 10 min after published_at on prod) without changing any content. */
332
+ refreshDraftPreview() {
333
+ return this.siteSave("save", {});
334
+ }
335
+ /** /save every page (as the editor's save does): popups and the cart drawer are compiled into
336
+ * each page's app_css (Qwik gets `popups` + `source_cart`), so after one changes, every page's
337
+ * CSS must be rebuilt or the new popup/cart renders unstyled until some page is saved. */
338
+ async resaveAllPages() {
339
+ const pages = listOf(await this.listPages())
340
+ .filter((p) => p && p.source && p.source.source != null && p.source.source !== "")
341
+ .map((p) => ({ id: p.id, source: typeof p.source.source === "string" ? p.source.source : JSON.stringify(p.source.source) }));
342
+ return this.siteSave("save", { pages });
343
+ }
344
+ /** A popup/cart write landed; rebuild every page's CSS. If that fails the write is still saved,
345
+ * so say so: retrying a create would duplicate the popup. */
346
+ async afterGlobalSourceWrite(res) {
347
+ await this.resaveAllPages().catch((e) => {
348
+ const id = res?.data?.id ?? res?.id;
349
+ throw new Error(`Global source SAVED${id ? ` (id ${id})` : ""} — do not create it again — but rebuilding the pages' CSS via /save failed: ${e?.message || e}. Any page save or publish_site rebuilds it.`);
350
+ });
296
351
  }
297
- /** Rebuild every page's compiled CSS (page_source.app_css) by replaying the builder's
298
- * /save pipeline — the ONLY path that regenerates the storefront's dynamic CSS. The
299
- * backend builds CSS per page in `params["pages"]` from that page's `source`; /publish
300
- * does NOT do this, so a site changed only through the MCP renders with stale/empty CSS
301
- * until this runs. Sends each page's CURRENT saved source (stringified) + current
302
- * settings; empty global arrays leave globals/popups untouched. */
303
- async rebuildSiteCss(settings) {
304
- const res = await this.listPages();
305
- const list = (res && res.data) || res || [];
306
- const pages = (Array.isArray(list) ? list : [])
307
- .map((p) => {
308
- const src = p && p.source && p.source.source;
309
- if (src == null || src === "")
310
- return null;
311
- return {
312
- id: p.id,
313
- source: typeof src === "string" ? src : JSON.stringify(src),
314
- settings: JSON.stringify(p.settings || {}),
315
- custom_code: p.custom_code || {},
316
- };
317
- })
318
- .filter(Boolean);
319
- if (!pages.length)
320
- return { rebuilt: 0 };
321
- let s = settings;
322
- if (s === undefined)
323
- s = await this.readSettingsOrThrow();
324
- const settingsStr = JSON.stringify(this.ensureSafeSettings(s));
325
- const changes = {};
326
- for (const p of pages)
327
- changes[p.id] = 1;
328
- await this.request("POST", `/api/v1/site/${this.siteId}/save`, {
329
- body: { pages, settings: settingsStr, changes, global_sources: [], global_sections: [], page_contents: [] },
330
- timeout: 120000,
352
+ /** Drop a deleted page from every global section's `pages` list, as the editor does on delete
353
+ * (globalSection.js removeGlobalSectionOfPage). */
354
+ async unlinkPageFromGlobalSections(pageId) {
355
+ const stale = listOf(await this.listGlobalSections()).filter((r) => (r.pages || []).includes(pageId));
356
+ if (!stale.length)
357
+ return 0;
358
+ await this.siteSave("save", {
359
+ global_sections: stale.map((r) => ({
360
+ section_id: r.section_id, name: r.name, type: r.type, status: "update",
361
+ pages: r.pages.filter((id) => id !== pageId), section: parseMaybe(r.section), contents: [],
362
+ })),
331
363
  });
332
- return { rebuilt: pages.length };
333
- }
334
- /** Publish the site live. /publish snapshots the pages in the body into the LIVE version —
335
- * exactly like the builder's "Xuất bản" button (PagePublish.vue): it POSTs every page as
336
- * `{ source, id, type, slug, is_homepage, settings }` plus a `changes` map. Sending NO
337
- * pages (the old behaviour) made the backend publish nothing, so the storefront stayed on
338
- * "Trang chưa có giao diện hoặc chưa xuất bản" and every page kept is_build=false.
339
- * We also (a) keep the CURRENT site.settings so /publish doesn't null the theme + data-source
340
- * flags (use_store/use_blog/…), and (b) rebuild each page's compiled CSS first (rebuildSiteCss),
341
- * because /publish alone does not regenerate the storefront's dynamic CSS.
342
- * Global header/footer are already embedded inside each page's source, so they publish with
343
- * the page; the global_* arrays stay empty (empty = leave server-side globals untouched).
344
- * Pass `domain` (the site's live URL, e.g. https://<slug>.webcake.me) — builderx_spa sends
345
- * `domain: this.link` and without it the backend publishes to an EXPIRING preview. The
346
- * publish_site tool fills it from resolvePreviewUrl. Final body mirrors PagePublish.vue:
347
- * { pages, settings, changes, domain, global_sources:[], global_sections:[], page_contents:[] }. */
348
- async publishSite(params = {}) {
349
- let settings = params.settings;
350
- if (settings === undefined) {
351
- settings = await this.readSettingsOrThrow();
352
- }
353
- // The save pipeline stores site.settings as a JSON STRING — an object body is
354
- // rejected (422). Stringify unless the caller already passed a string.
355
- const settingsStr = JSON.stringify(this.ensureSafeSettings(settings));
356
- // Collect every page WITH its saved source so the backend has something to publish.
357
- let pages = params.pages;
358
- let changes = params.changes;
359
- if (!Array.isArray(pages)) {
360
- const res = await this.listPages();
361
- const list = (res && res.data) || res || [];
362
- pages = (Array.isArray(list) ? list : [])
363
- .map((p) => {
364
- const src = p && p.source && p.source.source;
365
- if (src == null || src === "")
366
- return null;
367
- return {
368
- id: p.id,
369
- source: typeof src === "string" ? src : JSON.stringify(src),
370
- type: p.type,
371
- slug: p.slug,
372
- is_homepage: p.is_homepage === true,
373
- settings: JSON.stringify(p.settings || {}),
374
- };
375
- })
376
- .filter(Boolean);
364
+ return stale.length;
365
+ }
366
+ /** Upsert/delete global sections (Header/Footer/reusable blocks) through /save, like the
367
+ * editor. Each entry carries `status` ("new"|"update"|"delete") and is matched by
368
+ * (site_id, section_id); `section` is an OBJECT. Pass `pages` (each { id, source } with source
369
+ * a JSON STRING) to embed the node in page sources in the same atomic save. */
370
+ saveGlobalSections({ global_sections = [], pages = [], changes } = {}) {
371
+ return this.siteSave("save", { global_sections, pages, changes: changes || {} });
372
+ }
373
+ /** After a page's source is written: re-save it through /save the way the editor does, so
374
+ * (1) its compiled CSS (app_css) is rebuilt — update_page_source never builds it, and the
375
+ * draft preview renders page.source.app_css; (2) a global header/footer/section edited on
376
+ * this page reaches its GlobalSection record and every other page that embeds it — the
377
+ * editor's updateGlobalSections(), without which the edit stays on one page and the editor
378
+ * later replaces it with the stale record.
379
+ * A global node is pushed only when THIS write changed it (vs `pagesBefore`) and it differs
380
+ * from the record: a write carrying an older copy of the header must not revert the newer
381
+ * one site-wide. `changes` stays {}: a version row per write (and per popup) is noise; publish
382
+ * versions every page. */
383
+ async syncPageAfterWrite(pageId, src, pagesBefore = null) {
384
+ const changed = [];
385
+ const globals = globalsOf(src);
386
+ if (globals.length && pagesBefore) {
387
+ const prev = pagesBefore.find((p) => p && p.id === pageId);
388
+ const prevSrc = parseMaybe(prev?.source?.source);
389
+ const prevNode = (id) => (prevSrc?.sections || []).find((s) => s && s.id === id);
390
+ const res = await this.listGlobalSections();
391
+ const records = listOf(res);
392
+ for (const node of globals) {
393
+ const rec = records.find((r) => r.section_id === node.id);
394
+ if (!rec || canon(prevNode(node.id)) === canon(node) || canon(parseMaybe(rec.section)) === canon(node))
395
+ continue;
396
+ changed.push({ section_id: rec.section_id, name: rec.name, type: rec.type, pages: rec.pages || [], status: "update", section: node, contents: [] });
397
+ }
377
398
  }
378
- if (changes === undefined) {
379
- changes = {};
380
- for (const p of pages)
381
- changes[p.id] = 1;
399
+ const pages = [{ id: pageId, source: JSON.stringify(src) }];
400
+ if (changed.length) {
401
+ const byId = new Map(changed.map((g) => [g.section_id, g.section]));
402
+ for (const p of pagesBefore || []) {
403
+ if (!p || p.id === pageId)
404
+ continue;
405
+ const other = parseMaybe(p.source?.source);
406
+ if (!other || !(other.sections || []).some((s) => s && byId.has(s.id)))
407
+ continue;
408
+ other.sections = other.sections.map((s) => (s && byId.has(s.id) ? byId.get(s.id) : s));
409
+ pages.push({ id: p.id, source: JSON.stringify(other) });
410
+ }
382
411
  }
383
- // Regenerate compiled CSS for every page before publishing (no-op-safe on failure).
384
- await this.rebuildSiteCss(settingsStr).catch(() => { });
385
- return this.request("POST", `/api/v1/site/${this.siteId}/publish`, {
386
- body: {
387
- pages,
388
- changes,
389
- global_sources: [],
390
- global_sections: [],
391
- page_contents: [],
392
- ...params,
393
- settings: settingsStr,
394
- },
395
- timeout: 120000,
396
- });
412
+ await this.siteSave("save", { pages, global_sections: changed });
413
+ return { rebuilt_pages: pages.length, global_sections_synced: changed.length };
414
+ }
415
+ getSite() {
416
+ return this.request("GET", `/api/v1/site/${this.siteId}/`);
417
+ }
418
+ /** Publish the site live, like the editor's "Xuất bản" (PagePublish.vue): every page with its
419
+ * saved source as `{ id, source, type, slug, is_homepage, settings }`. Sending no pages made
420
+ * the backend publish nothing. /publish runs the whole /save first, so CSS is built here; the
421
+ * old separate rebuild doubled the work and the page-version history. */
422
+ async publishSite(params = {}) {
423
+ const res = await this.listPages();
424
+ const pages = ((res && res.data) || res || [])
425
+ .filter((p) => p && p.source && p.source.source != null && p.source.source !== "")
426
+ .map((p) => ({
427
+ id: p.id,
428
+ source: typeof p.source.source === "string" ? p.source.source : JSON.stringify(p.source.source),
429
+ type: p.type,
430
+ slug: p.slug,
431
+ is_homepage: p.is_homepage === true,
432
+ settings: JSON.stringify(p.settings || {}),
433
+ }));
434
+ const changes = Object.fromEntries(pages.map((p) => [p.id, 1]));
435
+ return this.siteSave("publish", { pages, changes, domain: params.domain });
397
436
  }
398
437
  uploadImageBase64({ base64, content_type } = {}) {
399
438
  return this.request("POST", `/api/v1/site/${this.siteId}/media/content/b64`, {
@@ -739,23 +778,36 @@ export class WebcakeCmsApi {
739
778
  getSourceCart() {
740
779
  return this.request("GET", `/api/v1/site/${this.siteId}/cart/get_source_cart`);
741
780
  }
742
- createSourceCart(params) {
743
- return this.request("POST", `/api/v1/site/${this.siteId}/cart/create_source_cart`, { body: params });
781
+ async createSourceCart(params) {
782
+ const res = await this.request("POST", `/api/v1/site/${this.siteId}/cart/create_source_cart`, { body: params });
783
+ await this.afterGlobalSourceWrite(res);
784
+ return res;
744
785
  }
745
- updateSourceCart(params) {
746
- return this.request("POST", `/api/v1/site/${this.siteId}/cart/update_source_cart`, { body: params });
786
+ async updateSourceCart(params) {
787
+ const res = await this.request("POST", `/api/v1/site/${this.siteId}/cart/update_source_cart`, { body: params });
788
+ await this.afterGlobalSourceWrite(res);
789
+ return res;
747
790
  }
748
791
  getGlobalSources(query) {
749
792
  return this.request("GET", `/api/v1/site/${this.siteId}/global_source/`, { query });
750
793
  }
751
- createGlobalSource(params) {
752
- return this.request("POST", `/api/v1/site/${this.siteId}/global_source/create`, { body: params });
753
- }
754
- updateGlobalSource(params) {
755
- return this.request("POST", `/api/v1/site/${this.siteId}/global_source/update`, { body: params });
756
- }
757
- deleteGlobalSource(params) {
758
- return this.request("POST", `/api/v1/site/${this.siteId}/global_source/delete`, { body: params });
794
+ async createGlobalSource(params) {
795
+ const res = await this.request("POST", `/api/v1/site/${this.siteId}/global_source/create`, { body: params });
796
+ await this.afterGlobalSourceWrite(res);
797
+ return res;
798
+ }
799
+ async updateGlobalSource(params) {
800
+ const res = await this.request("POST", `/api/v1/site/${this.siteId}/global_source/update`, { body: params });
801
+ await this.afterGlobalSourceWrite(res);
802
+ return res;
803
+ }
804
+ async deleteGlobalSource(params) {
805
+ const res = await this.request("POST", `/api/v1/site/${this.siteId}/global_source/delete`, { body: params });
806
+ // A deleted popup's CSS stays compiled into every page until they are re-saved.
807
+ await this.resaveAllPages().catch((e) => {
808
+ throw new Error(`Global source DELETED, but rebuilding the pages' CSS via /save failed: ${e?.message || e}. Any page save or publish_site rebuilds it.`);
809
+ });
810
+ return res;
759
811
  }
760
812
  getGlobalSourceContents(query) {
761
813
  return this.request("GET", `/api/v1/dashboard/site/${this.siteId}/multilingual/global_source_contents`, { query });
@@ -4,7 +4,7 @@
4
4
  import { createServer } from "node:http";
5
5
  import { randomBytes } from "node:crypto";
6
6
  import { spawn, execFile } from "node:child_process";
7
- import { resolveSettings } from "../config.js";
7
+ import { DEFAULT_ENV, resolveSettings } from "../config.js";
8
8
  import { setConfig } from "../db.js";
9
9
  function parseArgs(argv) {
10
10
  const opts = { open: true };
@@ -132,7 +132,8 @@ function pathOf(url) {
132
132
  }
133
133
  export async function runLogin(argv) {
134
134
  const opts = parseArgs(argv);
135
- const settings = resolveSettings({ apiUrl: opts.apiUrl, appUrl: opts.appUrl });
135
+ // Pin the env: a stale saved api_url (an old staging login) must not pair with the prod connect page.
136
+ const settings = resolveSettings({ env: process.env.WEBCAKE_ENV || DEFAULT_ENV, apiUrl: opts.apiUrl, appUrl: opts.appUrl });
136
137
  const appUrl = settings.appUrl.replace(/\/$/, "");
137
138
  const apiUrl = settings.apiUrl.replace(/\/$/, "");
138
139
  const state = randomBytes(16).toString("hex");
@@ -20,7 +20,7 @@ const NOISE_KEYS = new Set(["undefined", "locked", "loaded", "isChangeSection"])
20
20
  export const SHARED_SPECIALS = {
21
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
22
  custom_css: "Raw CSS scoped to this element. Last resort: try runtime.style/config first (see NATIVE FIRST).",
23
- element_async: "Mark the element async/lazy (advanced — usually leave unset).",
23
+ element_async: "Editor responsive toggle: true = this element keeps different styles per breakpoint (the editor stops copying desktop edits onto tablet/mobile). Set automatically when breakpoints differ.",
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.",
26
26
  text_animation_type: "Animated words in text/button: set to the type used by the <span class=\"animationText\" data-type …> inside specials.text (typed|typed2|clip|rotate3|animate.css name). See get_build_guide → Motion.",
@@ -224,9 +224,10 @@ You can still hand-set a final \`node.bpN\` when editing an already-saved page.
224
224
  - Image: \`runtime.config.src\` (URL). The URL MUST be a WebCake CDN url — the storefront
225
225
  whitelists image domains, so external URLs (Pexels, random sites) won't render. Get CDN
226
226
  urls from search_images (uploads by default → use its cdn_url) or upload_images.
227
- - Form: wrap inputs in a \`form\`; set \`form.specials.type\`
228
- (form_order | form_login | form_signup | form_discount | order_tracking). Each input
229
- needs \`specials.field_name\`.
227
+ - Form: wrap inputs in a \`form\`; ALWAYS set \`form.specials.type\` — the renderer treats a form
228
+ with no type as form_order (a checkout). Contact / lead / quote request / newsletter →
229
+ \`subscribe\` (the editor's own contact form). Others: form_order (checkout) | form_login |
230
+ form_signup | form_discount | order_tracking | form_booking. Each input needs \`specials.field_name\`.
230
231
  - EMBED = LAST RESORT. Build everything native elements can build (text, image, button, form,
231
232
  container, gallery, swiper, video, googlemap, countdown…) natively. Use \`embed\` ONLY for the
232
233
  one piece no element can do (a third-party widget, a tracking/chat snippet, a custom
@@ -426,9 +427,14 @@ List existing popups with list_global_sources({component:"popup"}); edit via upd
426
427
  2. list_elements / get_element to pick the right component types; get_page_schema for the exact
427
428
  node contract ({ sections:[ { id,type,specials,runtime:{style,config},children,events,bindings } ] }).
428
429
  3. Build sections with new_section (or new_element for one node), fill content.
429
- 4. validate_page — fix every error and review warnings.
430
+ 4. validate_page — fix every error; treat warnings as a fix list.
430
431
  5. build_page with dry_run:true first → review → dry_run:false to persist.
431
- 6. For existing pages, prefer surgical edits (update_page_element) over full rewrites.
432
+ 6. LOOK at it: preview_page (desktop 1280 + mobile 420 screenshots of the saved draft, nothing
433
+ goes live). Judge it like the designer at the canvas: matches the brief? clear hierarchy,
434
+ consistent spacing and colours from the design system, nothing cut off or overflowing,
435
+ images loaded, mobile stacks cleanly. Fix each issue with update_page_element(s) (per
436
+ breakpoint via responsive.bpN), then preview_page again. Only then publish_site.
437
+ 7. For existing pages, prefer surgical edits (update_page_element) over full rewrites.
432
438
 
433
439
  ## LARGE PAGES — avoid timeout (use the DRAFT flow)
434
440
  A multi-section page sent in one build_page can be a huge request and hit the 15s timeout.
@@ -31,8 +31,6 @@ export const CODE_BUDGET = {
31
31
  };
32
32
  /** custom_css + embed code across one page or global source. */
33
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
34
  export const NATIVE_FIRST_GUIDE = `## NATIVE FIRST — elements on the canvas before any code
37
35
  Pages are edited by dragging elements on the canvas. UI written in code is not on that canvas: the
38
36
  shop owner can't edit it, it is missing from the page HTML until scripts run, and it loads on every
@@ -68,7 +66,7 @@ ${NATIVE_ALTERNATIVES.map((a) => `- ${a.need}: ${a.elements.join(", ")}${a.note
68
66
 
69
67
  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
68
  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
69
+ shrink or swap code: no write may grow it, publish_site refuses to publish it). validate_page also refuses new placeholder JSON in text and more than
72
70
  ${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
71
  const SMELLS = [
74
72
  {
@@ -122,7 +120,8 @@ export function codeUsage(values) {
122
120
  };
123
121
  }
124
122
  /** 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. */
123
+ * so a site can move off custom code step by step. Past the ceiling nothing may grow: small fixes
124
+ * used to be allowed and ratcheted a site to 90k chars of CSS, which then failed to publish. */
126
125
  export function checkSiteCode(before, changes) {
127
126
  const after = { ...before, ...changes };
128
127
  const hard = [];
@@ -136,7 +135,7 @@ export function checkSiteCode(before, changes) {
136
135
  if (now.length <= old.length)
137
136
  continue;
138
137
  const { soft: softLimit, hard: hardLimit } = CODE_BUDGET[kind];
139
- if (now.length > hardLimit && (old.length <= hardLimit || now.length - old.length > SMALL_FIX))
138
+ if (now.length > hardLimit)
140
139
  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
140
  else if (now.length > softLimit)
142
141
  soft.push(`Site ${kind} would reach ${now.length} chars (budget ${softLimit}).`);