@coraltravelcenter/b2c-landing-builder 3.0.0 → 3.1.1

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
@@ -113,7 +113,7 @@ export default {
113
113
  | Поле | Поддерживаемые значения |
114
114
  | --- | --- |
115
115
  | `stack.script` | `js`, `ts`, `vue`, `vue-ts`; `vanilla` — legacy-алиас |
116
- | `stack.markup` | `html`, `pug` |
116
+ | `stack.markup` | `html`, `pug`, `mix` |
117
117
  | `stack.styles` | `css`, `scss`, `less` |
118
118
 
119
119
  Зависимости стека устанавливаются локально в проект: `typescript` для TS,
@@ -126,6 +126,14 @@ export default {
126
126
  `check --strict` требует, чтобы каждый блок либо имел initializer, либо был явно
127
127
  объявлен статическим. Статический блок не может одновременно иметь script entry.
128
128
 
129
+ ### Смешанная разметка
130
+
131
+ `stack.markup: "mix"` позволяет использовать HTML и Pug в одном проекте. Для
132
+ каждого блока должен существовать ровно один файл: `src/markup/<key>.html` или
133
+ `src/markup/<key>.pug`. Наличие обоих вариантов считается ошибкой. Команда
134
+ `block:add` в режиме `mix` создаёт HTML-файл; при необходимости его можно
135
+ переименовать в `.pug` до следующей проверки или сборки.
136
+
129
137
  ## Блоки и порядок
130
138
 
131
139
  `src/order.json` — единственный источник порядка блоков и CDN-папки:
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@coraltravelcenter/b2c-landing-builder",
3
- "version": "3.0.0",
3
+ "version": "3.1.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@coraltravelcenter/b2c-landing-builder",
9
- "version": "3.0.0",
9
+ "version": "3.1.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@babel/parser": "7.28.6",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coraltravelcenter/b2c-landing-builder",
3
- "version": "3.0.0",
3
+ "version": "3.1.1",
4
4
  "description": "CLI and build toolkit for B2C landing projects",
5
5
  "type": "module",
6
6
  "bin": {
@@ -16,9 +16,9 @@ function styleTemplate(key) {
16
16
  return `.${key} {\n}\n`;
17
17
  }
18
18
 
19
- function scriptTemplate(key) {
19
+ function scriptTemplate(key, extension) {
20
20
  const functionName = key.replace(/-+/g, "_");
21
- return `export default function ${functionName}() {\n const block = document.querySelector(".${key}");\n if (!block) return;\n}\n`;
21
+ return `export default function ${functionName}()${extension === "ts" ? ": void" : ""} {\n}\n`;
22
22
  }
23
23
 
24
24
  export function addBlock(key, config, root = process.cwd(), {log = console.log} = {}) {
@@ -27,13 +27,21 @@ export function addBlock(key, config, root = process.cwd(), {log = console.log}
27
27
  if (order.blocks.includes(key)) throw new Error(`Block already exists in src/order.json: ${key}`);
28
28
 
29
29
  const scriptStack = resolveScriptStack(config.stack.script);
30
+ const markup = config.stack.markup === "mix" ? "html" : config.stack.markup;
31
+ const markupPath = path.resolve(root, "src/markup", `${key}.${markup}`);
30
32
  const files = [
31
- [path.resolve(root, "src/markup", `${key}.${config.stack.markup}`), markupTemplate(key, config.stack.markup)],
33
+ [markupPath, markupTemplate(key, markup)],
32
34
  [path.resolve(root, "src/styles", `${key}.${config.stack.styles}`), styleTemplate(key)],
33
- [path.resolve(root, "src/scripts", `${key}.${scriptStack.extension}`), scriptTemplate(key)],
35
+ [path.resolve(root, "src/scripts", `${key}.${scriptStack.extension}`), scriptTemplate(key, scriptStack.extension)],
34
36
  ];
35
- const collision = files.find(([filePath]) => fs.existsSync(filePath));
36
- if (collision) throw new Error(`Cannot add block; target already exists: ${displayPath(root, collision[0])}`);
37
+ const markupCollisions = config.stack.markup === "mix"
38
+ ? ["html", "pug"].map((extension) => path.resolve(root, "src/markup", `${key}.${extension}`))
39
+ : [markupPath];
40
+ const collisionPath = [
41
+ ...markupCollisions,
42
+ ...files.slice(1).map(([filePath]) => filePath),
43
+ ].find((filePath) => fs.existsSync(filePath));
44
+ if (collisionPath) throw new Error(`Cannot add block; target already exists: ${displayPath(root, collisionPath)}`);
37
45
 
38
46
  for (const [filePath, source] of files) {
39
47
  fs.mkdirSync(path.dirname(filePath), {recursive: true});
@@ -0,0 +1,18 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ export const MARKUP_FORMATS = ["html", "pug"];
5
+
6
+ export function resolveMarkupFile({directory, key, markup}) {
7
+ const formats = markup === "mix" ? MARKUP_FORMATS : [markup];
8
+ const matches = formats
9
+ .map((format) => ({format, filePath: path.resolve(directory, `${key}.${format}`)}))
10
+ .filter(({filePath}) => fs.existsSync(filePath));
11
+
12
+ if (matches.length > 1) {
13
+ throw new Error(
14
+ `Ambiguous markup for block ${key}: src/markup/${key}.html and src/markup/${key}.pug both exist`
15
+ );
16
+ }
17
+ return matches[0] || null;
18
+ }
@@ -6,7 +6,7 @@ const SUPPORTED_SCHEMA_VERSIONS = new Set([1, 2]);
6
6
  const VERSION_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
7
7
  const STACK_VALUES = {
8
8
  script: SCRIPT_STACK_VALUES,
9
- markup: new Set(["html", "pug"]),
9
+ markup: new Set(["html", "pug", "mix"]),
10
10
  styles: new Set(["css", "scss", "less"]),
11
11
  };
12
12
  const SITE_PRESETS = new Set(["coral", "sunmar"]);
@@ -3,21 +3,22 @@ import {createRequire} from "node:module";
3
3
  import path from "node:path";
4
4
 
5
5
  import {processMarkup} from "../lib/processMarkup.mjs";
6
+ import {resolveMarkupFile} from "./markup-stack.mjs";
6
7
  import {resolveScriptStack} from "./script-stack.mjs";
7
8
  import {hasDefaultInitializer} from "./validate-script-contract.mjs";
8
9
 
9
10
  const BLOCK_KEY_RE = /^[a-z0-9][a-z0-9-_]*$/i;
10
11
  const DEPLOY_FOLDER_RE = /^[a-z0-9][a-z0-9-]*$/;
11
12
  const STACK_DEPENDENCIES = {
12
- markup: {pug: ["pug"]},
13
13
  styles: {less: ["less"], scss: ["sass"]},
14
14
  };
15
15
  const SCRIPT_EXTENSIONS = ["js", "ts"];
16
16
 
17
- function validateLocalDependencies(config, root) {
17
+ function validateLocalDependencies(config, root, {usesPug = false} = {}) {
18
18
  const projectRequire = createRequire(path.resolve(root, "package.json"));
19
19
  const dependencies = [
20
20
  ...resolveScriptStack(config.stack.script).dependencies,
21
+ ...(usesPug ? ["pug"] : []),
21
22
  ...Object.entries(STACK_DEPENDENCIES)
22
23
  .flatMap(([section, values]) => values[config.stack[section]] || []),
23
24
  ];
@@ -62,6 +63,7 @@ export function validateProject(config, root = process.cwd(), {strict = false} =
62
63
  const seen = new Set();
63
64
  const staticBlocks = new Set(config.blocks?.static || []);
64
65
  const blockDetails = [];
66
+ let usesPug = false;
65
67
  for (const key of order.blocks) {
66
68
  if (typeof key !== "string" || !BLOCK_KEY_RE.test(key)) {
67
69
  throw new Error(`Invalid block key in src/order.json: ${JSON.stringify(key)}`);
@@ -69,12 +71,20 @@ export function validateProject(config, root = process.cwd(), {strict = false} =
69
71
  if (seen.has(key)) throw new Error(`Duplicate block key in src/order.json: ${key}`);
70
72
  seen.add(key);
71
73
 
72
- const markupPath = path.resolve(root, "src/markup", `${key}.${config.stack.markup}`);
73
- if (!fs.existsSync(markupPath)) {
74
- throw new Error(`Missing configured markup for block ${key}: src/markup/${key}.${config.stack.markup}`);
74
+ const markup = resolveMarkupFile({
75
+ directory: path.resolve(root, "src/markup"),
76
+ key,
77
+ markup: config.stack.markup,
78
+ });
79
+ if (!markup) {
80
+ const expected = config.stack.markup === "mix"
81
+ ? `src/markup/${key}.html or src/markup/${key}.pug`
82
+ : `src/markup/${key}.${config.stack.markup}`;
83
+ throw new Error(`Missing configured markup for block ${key}: ${expected}`);
75
84
  }
76
- if (config.stack.markup === "html") {
77
- processMarkup(fs.readFileSync(markupPath, "utf8"), {filePath: markupPath});
85
+ usesPug ||= markup.format === "pug";
86
+ if (markup.format === "html") {
87
+ processMarkup(fs.readFileSync(markup.filePath, "utf8"), {filePath: markup.filePath});
78
88
  }
79
89
 
80
90
  const stylePath = path.resolve(root, "src/styles", `${key}.${config.stack.styles}`);
@@ -120,6 +130,6 @@ export function validateProject(config, root = process.cwd(), {strict = false} =
120
130
  if (!seen.has(key)) throw new Error(`Unknown block in blocks.static: ${key}`);
121
131
  }
122
132
 
123
- validateLocalDependencies(config, root);
133
+ validateLocalDependencies(config, root, {usesPug});
124
134
  return {folder: order.folder, blocks: [...order.blocks], blockDetails};
125
135
  }
@@ -13,10 +13,10 @@ function callableDefaultExport(program) {
13
13
  const exported = program.body.find((node) => node.type === "ExportDefaultDeclaration")?.declaration;
14
14
  const target = exported?.type === "Identifier" ? bindings.get(exported.name) : exported;
15
15
  return target?.type === "FunctionDeclaration" || target?.type === "FunctionExpression" ||
16
- target?.type === "ArrowFunctionExpression";
16
+ target?.type === "ArrowFunctionExpression" ? target : null;
17
17
  }
18
18
 
19
- export function hasDefaultInitializer({source, filePath, extension}) {
19
+ function parseScript({source, filePath, extension}) {
20
20
  let program;
21
21
  try {
22
22
  program = parse(source, {
@@ -27,5 +27,25 @@ export function hasDefaultInitializer({source, filePath, extension}) {
27
27
  const language = extension === "ts" ? "TypeScript" : "JavaScript";
28
28
  throw new Error(`${filePath} contains invalid ${language}: ${error.message}`, {cause: error});
29
29
  }
30
- return callableDefaultExport(program);
30
+ return program;
31
+ }
32
+
33
+ export function hasDefaultInitializer(options) {
34
+ return Boolean(callableDefaultExport(parseScript(options)));
35
+ }
36
+
37
+ export function hasEmptyDefaultInitializer(options) {
38
+ const program = parseScript(options);
39
+ const initializer = callableDefaultExport(program);
40
+ if (!initializer || initializer.params.length || initializer.body.type !== "BlockStatement" ||
41
+ initializer.body.body.some((node) => node.type !== "EmptyStatement")) return false;
42
+
43
+ // Keep the call when module-level code could replace the exported binding.
44
+ return program.body.every((node) =>
45
+ node === initializer || node.type === "ExportDefaultDeclaration" ||
46
+ node.type === "ImportDeclaration" || node.type === "EmptyStatement" ||
47
+ node.type === "TSInterfaceDeclaration" || node.type === "TSTypeAliasDeclaration" ||
48
+ (node.type === "VariableDeclaration" && node.kind === "const" &&
49
+ node.declarations.length === 1 && node.declarations[0].init === initializer)
50
+ );
31
51
  }
@@ -4,7 +4,7 @@ import path from "node:path";
4
4
  export const RU_LANGUAGE_ID = "1049";
5
5
  export const HTML_WIDGET_ID = "d400b0e7-918d-4d4c-bea3-8522253b6544";
6
6
  export const STATUS = Object.freeze({published: 1, checkout: 2, unpublished: 4});
7
- const RETRYABLE_STATUSES = new Set([429, 502, 503, 504]);
7
+ const RETRYABLE_STATUSES = new Set([429, 500, 502, 503, 504]);
8
8
 
9
9
  export class BackofficeRequestError extends Error {
10
10
  constructor(message, {code, status, method, endpoint, retryable = false, cause} = {}) {
@@ -29,6 +29,31 @@ function widgetsForPlacement(pageContent, layoutAreaId, folder) {
29
29
  );
30
30
  }
31
31
 
32
+ const defaultWait = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
33
+
34
+ async function verifyMutation(client, placement, manifest, operation, widget, wait, verificationDelays) {
35
+ if (typeof client.getContent !== "function") return null;
36
+ for (let attempt = 0; ; attempt += 1) {
37
+ const pageContent = await client.getContent(placement.pageContentId);
38
+ const widgets = widgetsForPlacement(pageContent, placement.layoutAreaId, manifest.folder);
39
+ const current = widgets.find((candidate) =>
40
+ operation.type === "add"
41
+ ? candidate.cmsTitle === operation.title
42
+ : candidate.contentWidgetId === widget?.contentWidgetId
43
+ );
44
+ const applied = operation.type === "add"
45
+ ? current && (current.data?.content ?? current.content ?? "") === operation.content
46
+ : operation.type === "update"
47
+ ? current && (current.data?.content ?? current.content ?? "") === operation.content
48
+ : operation.type === "reorder"
49
+ ? current?.order === operation.desiredOrder
50
+ : !current;
51
+ if (applied) return {pageContent, widget: current || widget};
52
+ if (attempt >= verificationDelays.length) return null;
53
+ await wait(verificationDelays[attempt]);
54
+ }
55
+ }
56
+
32
57
  export function remoteSections(pageContent, placement, folder) {
33
58
  return Object.fromEntries(widgetsForPlacement(pageContent || {}, placement.layoutAreaId, folder).map((widget) => [
34
59
  widget.cmsTitle.slice(widget.cmsTitle.lastIndexOf(" | ") + 3), widget.data?.content ?? widget.content ?? "",
@@ -101,6 +126,8 @@ export async function syncWidgets({
101
126
  plan,
102
127
  beforeOperation,
103
128
  onOperation,
129
+ wait = defaultWait,
130
+ verificationDelays = [250, 500],
104
131
  }) {
105
132
  plan ||= planWidgetChanges({manifest, placement, pageContent, root, sectionIds});
106
133
  let added = 0;
@@ -110,34 +137,53 @@ export async function syncWidgets({
110
137
  const addedWidgets = new Map();
111
138
 
112
139
  for (const operation of plan.operations) {
113
- await beforeOperation?.(operation);
114
140
  let widget = operation.widget || addedWidgets.get(operation.id);
141
+ if (operation.type === "reorder" && widget?.order === operation.desiredOrder) continue;
142
+ await beforeOperation?.(operation);
115
143
  let refreshedPageContent = null;
116
- if (operation.type === "update") {
117
- await client.updateWidget(operation.title, widget.contentWidgetId, operation.content);
118
- updated += 1;
119
- } else if (operation.type === "add") {
120
- await client.addWidget({
121
- pageContentId: placement.pageContentId,
122
- layoutAreaId: placement.layoutAreaId,
123
- cmsTitle: operation.title,
124
- data: {content: operation.content},
125
- });
126
- refreshedPageContent = await client.getContent(placement.pageContentId);
127
- widget = widgetsForPlacement(refreshedPageContent, placement.layoutAreaId, manifest.folder)
128
- .find((candidate) => candidate.cmsTitle === operation.title);
129
- if (!widget) throw new Error(`Backoffice did not return the added widget: ${operation.title}`);
144
+ try {
145
+ if (operation.type === "update") {
146
+ await client.updateWidget(operation.title, widget.contentWidgetId, operation.content);
147
+ } else if (operation.type === "add") {
148
+ await client.addWidget({
149
+ pageContentId: placement.pageContentId,
150
+ layoutAreaId: placement.layoutAreaId,
151
+ cmsTitle: operation.title,
152
+ data: {content: operation.content},
153
+ });
154
+ } else if (operation.type === "reorder") {
155
+ await client.reorderWidget(widget.contentWidgetId, operation.desiredOrder);
156
+ } else if (operation.type === "remove") {
157
+ await client.removeWidget({
158
+ contentWidgetId: widget.contentWidgetId,
159
+ layoutAreaId: widget.layoutAreaId,
160
+ widgetId: widget.widgetId,
161
+ });
162
+ }
163
+ } catch (cause) {
164
+ const verified = await verifyMutation(
165
+ client, placement, manifest, operation, widget, wait, verificationDelays
166
+ );
167
+ if (!verified) throw cause;
168
+ refreshedPageContent = verified.pageContent;
169
+ widget = verified.widget;
170
+ }
171
+ if (operation.type === "add") {
172
+ if (!refreshedPageContent) {
173
+ const verified = await verifyMutation(
174
+ client, placement, manifest, operation, widget, wait, verificationDelays
175
+ );
176
+ if (!verified) throw new Error(`Backoffice did not return the added widget: ${operation.title}`);
177
+ refreshedPageContent = verified.pageContent;
178
+ widget = verified.widget;
179
+ }
130
180
  addedWidgets.set(operation.id, widget);
131
181
  added += 1;
182
+ } else if (operation.type === "update") {
183
+ updated += 1;
132
184
  } else if (operation.type === "reorder") {
133
- await client.reorderWidget(widget.contentWidgetId, operation.desiredOrder);
134
185
  reordered += 1;
135
186
  } else if (operation.type === "remove") {
136
- await client.removeWidget({
137
- contentWidgetId: widget.contentWidgetId,
138
- layoutAreaId: widget.layoutAreaId,
139
- widgetId: widget.widgetId,
140
- });
141
187
  removed += 1;
142
188
  }
143
189
  if (onOperation && !refreshedPageContent) {
@@ -6,7 +6,9 @@ import {cleanDir, ensureDir, existsFile, normalizeHtml, r, readBlocks} from "./_
6
6
  import {loadProjectVuePlugin} from "./loadProjectVuePlugin.mjs";
7
7
  import {processMarkup} from "./processMarkup.mjs";
8
8
  import {renderPugFile} from "./pugMarkup.mjs";
9
+ import {resolveMarkupFile} from "../config/markup-stack.mjs";
9
10
  import {resolveScriptStack} from "../config/script-stack.mjs";
11
+ import {hasEmptyDefaultInitializer} from "../config/validate-script-contract.mjs";
10
12
 
11
13
  const ORDER_FILE = r("src/order.json");
12
14
 
@@ -63,6 +65,11 @@ async function bundleCssInline(absCssPath) {
63
65
 
64
66
  async function bundleJsInline(absJsPath, stack) {
65
67
  const rel = "/" + path.relative(process.cwd(), absJsPath).replaceAll("\\", "/");
68
+ const emptyInitializer = hasEmptyDefaultInitializer({
69
+ source: fs.readFileSync(absJsPath, "utf8"),
70
+ filePath: absJsPath,
71
+ extension: resolveScriptStack(stack.script).extension,
72
+ });
66
73
 
67
74
  const V_ID = "virtual:cms-js";
68
75
  const R_ID = "\0" + V_ID;
@@ -75,6 +82,7 @@ async function bundleJsInline(absJsPath, stack) {
75
82
  },
76
83
  load(id) {
77
84
  if (id === R_ID) {
85
+ if (emptyInitializer) return `import ${JSON.stringify(rel)};`;
78
86
  // контракт: scripts/<key>.js экспортирует default init()
79
87
  return `
80
88
  import init from ${JSON.stringify(rel)};
@@ -122,16 +130,16 @@ try { if (typeof init === "function") init(); } catch (e) { console.warn(e); }
122
130
 
123
131
  async function buildBlock(key, stack) {
124
132
  const scriptStack = resolveScriptStack(stack.script);
125
- const markupPath = path.join(MARKUP_DIR, `${key}.${stack.markup}`);
126
- if (!markupPath) return null;
127
- if (!existsFile(markupPath)) return null;
133
+ const markup = resolveMarkupFile({directory: MARKUP_DIR, key, markup: stack.markup});
134
+ if (!markup) return null;
135
+ const markupPath = markup.filePath;
128
136
 
129
137
  const jsPath = path.join(SCRIPTS_DIR, `${key}.${scriptStack.extension}`);
130
138
 
131
- const markup = stack.markup === "pug"
139
+ const source = markup.format === "pug"
132
140
  ? renderPugFile(markupPath)
133
141
  : normalizeHtml(fs.readFileSync(markupPath, "utf8"));
134
- const html = processMarkup(markup, {filePath: markupPath});
142
+ const html = processMarkup(source, {filePath: markupPath});
135
143
 
136
144
  const configuredCssPath = path.join(STYLES_DIR, `${key}.${stack.styles}`);
137
145
  const cssPath = existsFile(configuredCssPath) ? configuredCssPath : null;
@@ -4,6 +4,7 @@ import path from "node:path";
4
4
  import {existsFile, normalizeHtml, readBlocks} from "./_utils.mjs";
5
5
  import {processMarkup} from "./processMarkup.mjs";
6
6
  import {getPugConfigFile, renderPugFile} from "./pugMarkup.mjs";
7
+ import {resolveMarkupFile} from "../config/markup-stack.mjs";
7
8
  import {resolveScriptStack} from "../config/script-stack.mjs";
8
9
 
9
10
  const VIRTUAL_ID = "virtual:landing-blocks";
@@ -75,9 +76,9 @@ export function landingBlocksPlugin({root = process.cwd(), stack} = {}) {
75
76
  throw new Error(`[landing-blocks] Invalid block key: "${key}"`);
76
77
  }
77
78
 
78
- const markupPath = path.join(markupDir, `${key}.${stack.markup}`);
79
- if (!markupPath) return;
80
- if (!existsFile(markupPath)) return;
79
+ const markup = resolveMarkupFile({directory: markupDir, key, markup: stack.markup});
80
+ if (!markup) return;
81
+ const markupPath = markup.filePath;
81
82
 
82
83
  this.addWatchFile(markupPath);
83
84
 
@@ -97,7 +98,7 @@ export function landingBlocksPlugin({root = process.cwd(), stack} = {}) {
97
98
  imports.push(`import ${init} from ${JSON.stringify(toVitePath(scriptPath))};`);
98
99
  }
99
100
 
100
- const source = stack.markup === "pug"
101
+ const source = markup.format === "pug"
101
102
  ? renderPugFile(markupPath)
102
103
  : normalizeHtml(fs.readFileSync(markupPath, "utf8"));
103
104
  const html = processMarkup(source, {