webcake-storefront-mcp 1.38.0 → 1.40.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/api.js CHANGED
@@ -1,9 +1,25 @@
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));
13
+ /** True when `token` is a JWT whose `exp` is past (with `skewSec` margin). Non-JWTs never count as expired. */
14
+ export function jwtExpired(token, skewSec = 30) {
15
+ try {
16
+ const exp = JSON.parse(Buffer.from(String(token).split(".")[1], "base64url").toString()).exp;
17
+ return typeof exp === "number" && exp * 1000 < Date.now() + skewSec * 1000;
18
+ }
19
+ catch {
20
+ return false;
21
+ }
22
+ }
7
23
  export class WebcakeCmsApi {
8
24
  /** Parse (if string) and guarantee settings.breakpoints is a usable object — an empty/missing
9
25
  * breakpoints would make the backend compile CSS without media queries. */
@@ -30,7 +46,19 @@ export class WebcakeCmsApi {
30
46
  sessionId;
31
47
  _adminToken;
32
48
  _cmsApiKey;
33
- _siteBps = null;
49
+ _siteBps = null; // cached site.settings (breakpoints, defaultGrid)
50
+ /** Called when the session JWT is expired or the backend rejects it. Stdio: reopens the browser
51
+ * Connect page and returns the new credentials (request is retried once). Remote: marks it dead. */
52
+ onAuthExpired;
53
+ async renewAuth() {
54
+ const fresh = this.onAuthExpired ? await this.onAuthExpired() : null;
55
+ if (!fresh?.token)
56
+ return false;
57
+ this.switchToken(fresh.token);
58
+ if (fresh.sessionId)
59
+ this.switchSession(fresh.sessionId);
60
+ return true;
61
+ }
34
62
  constructor({ baseUrl, token, siteId, sessionId }) {
35
63
  this.baseUrl = (baseUrl || "").replace(/\/$/, "");
36
64
  this.token = token;
@@ -54,7 +82,12 @@ export class WebcakeCmsApi {
54
82
  getBundleParams() {
55
83
  return { token: this._adminToken, x_cms_api_key: this._cmsApiKey };
56
84
  }
57
- async request(method, path, { body, query, timeout, headers: extraHeaders } = {}) {
85
+ async request(method, path, opts = {}, retried = false) {
86
+ const { body, query, timeout, headers: extraHeaders } = opts;
87
+ // Calls that bring their own Bearer (CMS admin token) can't be fixed by a new login.
88
+ const ownAuth = !extraHeaders?.Authorization;
89
+ if (ownAuth && !retried && jwtExpired(this.token) && (await this.renewAuth()))
90
+ return this.request(method, path, opts, true);
58
91
  const url = new URL(`${this.baseUrl}${path}`);
59
92
  if (query) {
60
93
  for (const [k, v] of Object.entries(query)) {
@@ -71,7 +104,7 @@ export class WebcakeCmsApi {
71
104
  const controller = new AbortController();
72
105
  const timer = setTimeout(() => controller.abort(), timeout || DEFAULT_TIMEOUT);
73
106
  let res;
74
- let json;
107
+ let raw;
75
108
  try {
76
109
  res = await fetch(url, {
77
110
  method,
@@ -80,16 +113,25 @@ export class WebcakeCmsApi {
80
113
  signal: controller.signal,
81
114
  });
82
115
  // Read the body under the same timer — clearing it after the headers left a stalled body unbounded.
83
- json = await res.json().catch((e) => {
84
- if (controller.signal.aborted)
85
- throw e; // timed out mid-body: an error, not an empty success
86
- return null;
87
- });
116
+ raw = await res.text();
88
117
  }
89
118
  finally {
90
119
  clearTimeout(timer);
91
120
  }
121
+ let json = null;
122
+ try {
123
+ json = raw ? JSON.parse(raw) : null;
124
+ }
125
+ catch {
126
+ /* non-JSON body (e.g. plain "Unauthorized") */
127
+ }
92
128
  if (!res.ok) {
129
+ // AuthPlug answers a bad/expired session with a plain-text 401 "Unauthorized".
130
+ if (res.status === 401 && ownAuth && (jwtExpired(this.token) || raw.trim() === "Unauthorized")) {
131
+ if (!retried && (await this.renewAuth()))
132
+ return this.request(method, path, opts, true);
133
+ throw new Error("API 401: phiên đăng nhập WebCake đã hết hạn (token expired). Bấm Kết nối (Connect) lại để gia hạn — stdio: chạy `npx -y webcake-storefront-mcp login`.");
134
+ }
93
135
  const msg = (json && json.message) || (json && json.error) || res.statusText;
94
136
  throw new Error(`API ${res.status}: ${msg}`);
95
137
  }
@@ -155,11 +197,18 @@ export class WebcakeCmsApi {
155
197
  /** The site's breakpoints ({ bpN: [minW, maxW] } from settings, which may be a JSON string),
156
198
  * or null when unset/unreadable — callers then use the standard four. Cached per site. */
157
199
  getSiteBreakpoints() {
200
+ return this.siteLayout().then((s) => s?.breakpoints || null);
201
+ }
202
+ /** The site's section grid per breakpoint (settings.defaultGrid): the editor builds every new
203
+ * section from it (editor.js addBlankSection), so generated sections must too. */
204
+ getSiteDefaultGrid() {
205
+ return this.siteLayout().then((s) => s?.defaultGrid || null);
206
+ }
207
+ siteLayout() {
158
208
  this._siteBps ??= this.getSite()
159
209
  .then((res) => {
160
210
  const site = res?.data ?? res;
161
- const settings = typeof site?.settings === "string" ? JSON.parse(site.settings || "{}") : site?.settings;
162
- return settings?.breakpoints || null;
211
+ return (typeof site?.settings === "string" ? JSON.parse(site.settings || "{}") : site?.settings) || null;
163
212
  })
164
213
  .catch(() => {
165
214
  this._siteBps = null; // don't cache a failed lookup — retry on the next save
@@ -226,12 +275,14 @@ export class WebcakeCmsApi {
226
275
  * `slug`/`is_homepage` are NOT applied at create — set them afterwards via updatePage.
227
276
  * Every page born here is AI-authored, so we stamp `by_ai` (persisted to `pages.by_ai`)
228
277
  * and the builder shows an "AI" tag next to the page name. */
229
- createPage(params, opts) {
278
+ async createPage(params, opts) {
230
279
  const body = { ...params };
231
280
  if (body.source != null && typeof body.source !== "string")
232
281
  body.source = JSON.stringify(body.source);
282
+ // The editor never saves an empty page: it creates one blank grid section to drop into
283
+ // (editor.js createPage). An empty `sections` opened with nothing to drop elements on.
233
284
  if (body.source == null)
234
- body.source = JSON.stringify({ sections: [] });
285
+ body.source = JSON.stringify(finalizeForRender({ sections: [buildSection([])] }, await this.getSiteBreakpoints(), await this.getSiteDefaultGrid()));
235
286
  if (body.by_ai == null)
236
287
  body.by_ai = BY_AI_MARKER;
237
288
  return this.request("POST", `/api/v1/site/${this.siteId}/page`, { body, timeout: opts?.timeout });
@@ -239,8 +290,23 @@ export class WebcakeCmsApi {
239
290
  updatePage(pageId, params) {
240
291
  return this.request("POST", `/api/v1/site/${this.siteId}/${pageId}/update_page`, { body: params });
241
292
  }
242
- updatePageSource(pageId, params, opts) {
243
- return this.request("POST", `/api/v1/site/${this.siteId}/${pageId}/update_page_source`, { body: params, timeout: opts?.timeout });
293
+ /** Write a page source, then re-save it through /save like the editor (CSS + global sections,
294
+ * see syncPageAfterWrite). The source is already stored when the sync runs, so a sync failure
295
+ * says so instead of reading as a lost write. `sync:false` skips the /save, for intermediate
296
+ * writes of a batch whose last write syncs (each sync rebuilds the page CSS). */
297
+ async updatePageSource(pageId, params, opts) {
298
+ const sync = params && params.source != null && opts?.sync !== false;
299
+ const src = sync ? (typeof params.source === "string" ? JSON.parse(params.source) : params.source) : null;
300
+ // With a global section on the page, keep the sources as they were BEFORE this write: only a
301
+ // global node this write actually changed may be pushed to the other pages.
302
+ const before = src && globalsOf(src).length ? listOf(await this.listPages()) : null;
303
+ const res = await this.request("POST", `/api/v1/site/${this.siteId}/${pageId}/update_page_source`, { body: params, timeout: opts?.timeout });
304
+ if (sync) {
305
+ await this.syncPageAfterWrite(pageId, src, before).catch((e) => {
306
+ throw new Error(`Page source SAVED, but rebuilding its CSS / syncing global sections via /save failed: ${e?.message || e}. Retry the same write.`);
307
+ });
308
+ }
309
+ return res;
244
310
  }
245
311
  deletePage(params) {
246
312
  return this.request("POST", `/api/v1/site/${this.siteId}/delete_page`, { body: params });
@@ -264,136 +330,145 @@ export class WebcakeCmsApi {
264
330
  listGlobalSections() {
265
331
  return this.request("GET", `/api/v1/site/${this.siteId}/global_sections`);
266
332
  }
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`, {
333
+ /** The cart drawer + popups, as the editor sends them with every save and publish
334
+ * (PagePublish.vue: `global_sources: cart.source.concat(popup.popups)`). /save builds the
335
+ * cart CSS only from these, and /publish copies them into the LIVE global sources: sending []
336
+ * left popups and the cart unpublished and dropped the cart CSS. `source` goes as an object
337
+ * (the backend Jason.encode!s it). */
338
+ async globalSourcesForSave() {
339
+ const list = (r) => (Array.isArray(r?.data) ? r.data : Array.isArray(r) ? r : []);
340
+ const [cart, popups] = await Promise.all([this.getSourceCart(), this.getGlobalSources({ component: "popup" })]);
341
+ return [...list(cart), ...list(popups)].map((g) => ({
342
+ ...g,
343
+ source: typeof g.source === "string" ? JSON.parse(g.source) : g.source,
344
+ }));
345
+ }
346
+ /** POST /save or /publish with the body the editor sends (PagePublish.vue savePage):
347
+ * current site settings (or /save nulls them), the cart + popups, and the given pages /
348
+ * global sections. /publish is /save plus the live copy (site_controller.ex `publish` →
349
+ * `save(is_publish: true)`), so one call builds each page's CSS and publishes it. Every /save
350
+ * also stamps site.published_at, which opens the 10-minute draft preview. */
351
+ async siteSave(path, { pages = [], global_sections = [], changes = {}, domain }) {
352
+ const [settings, global_sources] = await Promise.all([this.readSettingsOrThrow(), this.globalSourcesForSave()]);
353
+ return this.request("POST", `/api/v1/site/${this.siteId}/${path}`, {
280
354
  body: {
281
- settings: settingsStr,
282
- global_sources: [],
283
- page_contents: [],
284
- changes: changes || {},
355
+ settings: JSON.stringify(this.ensureSafeSettings(settings)),
285
356
  pages,
357
+ changes,
358
+ global_sources,
286
359
  global_sections,
360
+ page_contents: [],
361
+ ...(domain ? { domain } : {}),
287
362
  },
288
363
  timeout: 120000,
289
364
  });
290
365
  }
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 });
366
+ /** A /save with no pages: stamps site.published_at, which (re)opens the draft preview window
367
+ * (PreviewExpire: 10 min after published_at on prod) without changing any content. */
368
+ refreshDraftPreview() {
369
+ return this.siteSave("save", {});
370
+ }
371
+ /** /save every page (as the editor's save does): popups and the cart drawer are compiled into
372
+ * each page's app_css (Qwik gets `popups` + `source_cart`), so after one changes, every page's
373
+ * CSS must be rebuilt or the new popup/cart renders unstyled until some page is saved. */
374
+ async resaveAllPages() {
375
+ const pages = listOf(await this.listPages())
376
+ .filter((p) => p && p.source && p.source.source != null && p.source.source !== "")
377
+ .map((p) => ({ id: p.id, source: typeof p.source.source === "string" ? p.source.source : JSON.stringify(p.source.source) }));
378
+ return this.siteSave("save", { pages });
379
+ }
380
+ /** A popup/cart write landed; rebuild every page's CSS. If that fails the write is still saved,
381
+ * so say so: retrying a create would duplicate the popup. */
382
+ async afterGlobalSourceWrite(res) {
383
+ await this.resaveAllPages().catch((e) => {
384
+ const id = res?.data?.id ?? res?.id;
385
+ 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.`);
386
+ });
296
387
  }
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,
388
+ /** Drop a deleted page from every global section's `pages` list, as the editor does on delete
389
+ * (globalSection.js removeGlobalSectionOfPage). */
390
+ async unlinkPageFromGlobalSections(pageId) {
391
+ const stale = listOf(await this.listGlobalSections()).filter((r) => (r.pages || []).includes(pageId));
392
+ if (!stale.length)
393
+ return 0;
394
+ await this.siteSave("save", {
395
+ global_sections: stale.map((r) => ({
396
+ section_id: r.section_id, name: r.name, type: r.type, status: "update",
397
+ pages: r.pages.filter((id) => id !== pageId), section: parseMaybe(r.section), contents: [],
398
+ })),
331
399
  });
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);
400
+ return stale.length;
401
+ }
402
+ /** Upsert/delete global sections (Header/Footer/reusable blocks) through /save, like the
403
+ * editor. Each entry carries `status` ("new"|"update"|"delete") and is matched by
404
+ * (site_id, section_id); `section` is an OBJECT. Pass `pages` (each { id, source } with source
405
+ * a JSON STRING) to embed the node in page sources in the same atomic save. */
406
+ saveGlobalSections({ global_sections = [], pages = [], changes } = {}) {
407
+ return this.siteSave("save", { global_sections, pages, changes: changes || {} });
408
+ }
409
+ /** After a page's source is written: re-save it through /save the way the editor does, so
410
+ * (1) its compiled CSS (app_css) is rebuilt — update_page_source never builds it, and the
411
+ * draft preview renders page.source.app_css; (2) a global header/footer/section edited on
412
+ * this page reaches its GlobalSection record and every other page that embeds it — the
413
+ * editor's updateGlobalSections(), without which the edit stays on one page and the editor
414
+ * later replaces it with the stale record.
415
+ * A global node is pushed only when THIS write changed it (vs `pagesBefore`) and it differs
416
+ * from the record: a write carrying an older copy of the header must not revert the newer
417
+ * one site-wide. `changes` stays {}: a version row per write (and per popup) is noise; publish
418
+ * versions every page. */
419
+ async syncPageAfterWrite(pageId, src, pagesBefore = null) {
420
+ const changed = [];
421
+ const globals = globalsOf(src);
422
+ if (globals.length && pagesBefore) {
423
+ const prev = pagesBefore.find((p) => p && p.id === pageId);
424
+ const prevSrc = parseMaybe(prev?.source?.source);
425
+ const prevNode = (id) => (prevSrc?.sections || []).find((s) => s && s.id === id);
426
+ const res = await this.listGlobalSections();
427
+ const records = listOf(res);
428
+ for (const node of globals) {
429
+ const rec = records.find((r) => r.section_id === node.id);
430
+ if (!rec || canon(prevNode(node.id)) === canon(node) || canon(parseMaybe(rec.section)) === canon(node))
431
+ continue;
432
+ changed.push({ section_id: rec.section_id, name: rec.name, type: rec.type, pages: rec.pages || [], status: "update", section: node, contents: [] });
433
+ }
377
434
  }
378
- if (changes === undefined) {
379
- changes = {};
380
- for (const p of pages)
381
- changes[p.id] = 1;
435
+ const pages = [{ id: pageId, source: JSON.stringify(src) }];
436
+ if (changed.length) {
437
+ const byId = new Map(changed.map((g) => [g.section_id, g.section]));
438
+ for (const p of pagesBefore || []) {
439
+ if (!p || p.id === pageId)
440
+ continue;
441
+ const other = parseMaybe(p.source?.source);
442
+ if (!other || !(other.sections || []).some((s) => s && byId.has(s.id)))
443
+ continue;
444
+ other.sections = other.sections.map((s) => (s && byId.has(s.id) ? byId.get(s.id) : s));
445
+ pages.push({ id: p.id, source: JSON.stringify(other) });
446
+ }
382
447
  }
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
- });
448
+ await this.siteSave("save", { pages, global_sections: changed });
449
+ return { rebuilt_pages: pages.length, global_sections_synced: changed.length };
450
+ }
451
+ getSite() {
452
+ return this.request("GET", `/api/v1/site/${this.siteId}/`);
453
+ }
454
+ /** Publish the site live, like the editor's "Xuất bản" (PagePublish.vue): every page with its
455
+ * saved source as `{ id, source, type, slug, is_homepage, settings }`. Sending no pages made
456
+ * the backend publish nothing. /publish runs the whole /save first, so CSS is built here; the
457
+ * old separate rebuild doubled the work and the page-version history. */
458
+ async publishSite(params = {}) {
459
+ const res = await this.listPages();
460
+ const pages = ((res && res.data) || res || [])
461
+ .filter((p) => p && p.source && p.source.source != null && p.source.source !== "")
462
+ .map((p) => ({
463
+ id: p.id,
464
+ source: typeof p.source.source === "string" ? p.source.source : JSON.stringify(p.source.source),
465
+ type: p.type,
466
+ slug: p.slug,
467
+ is_homepage: p.is_homepage === true,
468
+ settings: JSON.stringify(p.settings || {}),
469
+ }));
470
+ const changes = Object.fromEntries(pages.map((p) => [p.id, 1]));
471
+ return this.siteSave("publish", { pages, changes, domain: params.domain });
397
472
  }
398
473
  uploadImageBase64({ base64, content_type } = {}) {
399
474
  return this.request("POST", `/api/v1/site/${this.siteId}/media/content/b64`, {
@@ -739,23 +814,36 @@ export class WebcakeCmsApi {
739
814
  getSourceCart() {
740
815
  return this.request("GET", `/api/v1/site/${this.siteId}/cart/get_source_cart`);
741
816
  }
742
- createSourceCart(params) {
743
- return this.request("POST", `/api/v1/site/${this.siteId}/cart/create_source_cart`, { body: params });
817
+ async createSourceCart(params) {
818
+ const res = await this.request("POST", `/api/v1/site/${this.siteId}/cart/create_source_cart`, { body: params });
819
+ await this.afterGlobalSourceWrite(res);
820
+ return res;
744
821
  }
745
- updateSourceCart(params) {
746
- return this.request("POST", `/api/v1/site/${this.siteId}/cart/update_source_cart`, { body: params });
822
+ async updateSourceCart(params) {
823
+ const res = await this.request("POST", `/api/v1/site/${this.siteId}/cart/update_source_cart`, { body: params });
824
+ await this.afterGlobalSourceWrite(res);
825
+ return res;
747
826
  }
748
827
  getGlobalSources(query) {
749
828
  return this.request("GET", `/api/v1/site/${this.siteId}/global_source/`, { query });
750
829
  }
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 });
830
+ async createGlobalSource(params) {
831
+ const res = await this.request("POST", `/api/v1/site/${this.siteId}/global_source/create`, { body: params });
832
+ await this.afterGlobalSourceWrite(res);
833
+ return res;
834
+ }
835
+ async updateGlobalSource(params) {
836
+ const res = await this.request("POST", `/api/v1/site/${this.siteId}/global_source/update`, { body: params });
837
+ await this.afterGlobalSourceWrite(res);
838
+ return res;
839
+ }
840
+ async deleteGlobalSource(params) {
841
+ const res = await this.request("POST", `/api/v1/site/${this.siteId}/global_source/delete`, { body: params });
842
+ // A deleted popup's CSS stays compiled into every page until they are re-saved.
843
+ await this.resaveAllPages().catch((e) => {
844
+ 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.`);
845
+ });
846
+ return res;
759
847
  }
760
848
  getGlobalSourceContents(query) {
761
849
  return this.request("GET", `/api/v1/dashboard/site/${this.siteId}/multilingual/global_source_contents`, { query });
@@ -5,7 +5,7 @@ import { createServer } from "node:http";
5
5
  import { randomBytes } from "node:crypto";
6
6
  import { spawn, execFile } from "node:child_process";
7
7
  import { DEFAULT_ENV, resolveSettings } from "../config.js";
8
- import { setConfig } from "../db.js";
8
+ import { getConfig, setConfig } from "../db.js";
9
9
  function parseArgs(argv) {
10
10
  const opts = { open: true };
11
11
  for (let i = 0; i < argv.length; i++) {
@@ -196,3 +196,24 @@ export async function runLogin(argv) {
196
196
  }, 180_000).unref();
197
197
  });
198
198
  }
199
+ // One browser Connect at a time; after a failed/abandoned one, wait before reopening so a
200
+ // looping agent doesn't spam tabs. ponytail: process-wide, fine for one stdio user.
201
+ let renewing = null;
202
+ let lastFail = 0;
203
+ /** Token expired mid-session (stdio): reopen the Connect page and hand back the new credentials. */
204
+ export function renewInBrowser() {
205
+ if (!renewing && Date.now() - lastFail > 120_000) {
206
+ console.error("[webcake-storefront] Token hết hạn — mở trình duyệt để Kết nối lại…");
207
+ renewing = runLogin([])
208
+ .then(() => ({ token: getConfig("token") || "", sessionId: getConfig("session_id") || "" }))
209
+ .catch((e) => {
210
+ lastFail = Date.now();
211
+ console.error("[webcake-storefront] gia hạn token thất bại:", e?.message || e);
212
+ return null;
213
+ })
214
+ .finally(() => {
215
+ renewing = null;
216
+ });
217
+ }
218
+ return renewing ?? Promise.resolve(null);
219
+ }
@@ -22,6 +22,7 @@
22
22
  * All exported function names and signatures are IDENTICAL to the previous version
23
23
  * so http.ts requires no changes.
24
24
  */
25
+ import { jwtExpired } from "../api.js";
25
26
  import { randomBytes, createHash } from "node:crypto";
26
27
  import { getPg, ensureOAuthSchema } from "../persistence/postgres.js";
27
28
  import { getRedis } from "../persistence/redis.js";
@@ -332,6 +333,19 @@ export async function completeAuthorize(internalState, jwt, wsid) {
332
333
  });
333
334
  return { ok: true, redirectUri: p.redirect_uri, code, state: p.state };
334
335
  }
336
+ // ---- Dead WebCake sessions ---------------------------------------------------
337
+ // The OAuth tokens outlive the WebCake JWT they wrap. Once that JWT is expired (or the
338
+ // backend rejected it), refreshing would just re-issue the dead JWT; refusing it makes the
339
+ // client restart the full flow, i.e. open the Connect page again.
340
+ // ponytail: in-memory set, per process; share it via Redis if the server is ever scaled out.
341
+ const deadJwts = new Set();
342
+ export function markJwtDead(jwt) {
343
+ if (jwt)
344
+ deadJwts.add(jwt);
345
+ }
346
+ export function isDeadJwt(jwt) {
347
+ return !!jwt && (deadJwts.has(jwt) || jwtExpired(jwt));
348
+ }
335
349
  async function issueTokens(store, cred, client_id, scope) {
336
350
  const access = token(32);
337
351
  const refresh = token(32);
@@ -366,6 +380,9 @@ export async function exchangeToken(p) {
366
380
  if (!r) {
367
381
  return { ok: false, status: 400, error: "invalid_grant", error_description: "Unknown or expired refresh token." };
368
382
  }
383
+ if (isDeadJwt(r.cred.jwt)) {
384
+ return { ok: false, status: 400, error: "invalid_grant", error_description: "WebCake session expired — sign in again (Connect)." };
385
+ }
369
386
  return { ok: true, body: await issueTokens(store, r.cred, r.client_id, r.scope) };
370
387
  }
371
388
  return { ok: false, status: 400, error: "unsupported_grant_type", error_description: "grant_type must be authorization_code or refresh_token." };
@@ -386,11 +403,11 @@ export async function resolveAccessToken(accessToken) {
386
403
  if (redis) {
387
404
  const cached = await redisCacheGet(redis, accessToken);
388
405
  if (cached)
389
- return cached;
406
+ return isDeadJwt(cached.jwt) ? undefined : cached;
390
407
  }
391
408
  // 2. Fall through to the store (Postgres or memory).
392
409
  const a = await (await getStore()).getAccess(accessToken);
393
- if (!a)
410
+ if (!a || isDeadJwt(a.cred.jwt))
394
411
  return undefined;
395
412
  // Backfill the Redis cache for next time.
396
413
  if (redis)
@@ -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.