webcake-storefront-mcp 1.41.0 → 1.42.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-catalog.generated.json +777 -0
- package/dist/builder/attributes.js +1 -1
- package/dist/builder/catalog.js +1 -1
- package/dist/builder/element-keys.generated.json +136 -4105
- package/dist/builder/element-schema.js +297 -0
- package/dist/builder/page.js +38 -26
- package/dist/changelog.json +7 -7
- package/dist/server.js +1 -1
- package/dist/tools/api-gateway.js +178 -0
- package/dist/tools/builder-extras.js +3 -1
- package/dist/tools/builder.js +12 -3
- package/dist/tools/registry.js +7 -3
- package/package.json +3 -1
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
// Per-element schema + the checks validate_page runs against it, and the one format every
|
|
2
|
+
// validation message uses.
|
|
3
|
+
//
|
|
4
|
+
// The key surface of each type is the union of what is known to be real, nothing invented:
|
|
5
|
+
// - keys mined from 329 published pages (element-keys.generated.json),
|
|
6
|
+
// - the curated tables in attributes.ts (meanings, enums like "h1|h2|…|p"),
|
|
7
|
+
// - the factory skeleton (also the source of each key's value TYPE),
|
|
8
|
+
// - the generic grid config + shared specials every node may carry.
|
|
9
|
+
// The renderer ignores a specials/config key it doesn't know (a dead key), so an unknown key is
|
|
10
|
+
// a WARNING with a did-you-mean. Style is different: the renderer emits every style key as CSS
|
|
11
|
+
// (camelCase → kebab), so style keys are checked as CSS properties, not per type.
|
|
12
|
+
import { OBSERVED, ELEMENT_ATTRS, SHARED_SPECIALS, SHARED_KEY_DICT, GENERIC_CONFIG } from "./attributes.js";
|
|
13
|
+
import { buildElement, describeType, isKnownType, ELEMENT_TYPES } from "./catalog.js";
|
|
14
|
+
/** `[CODE] #id (type) at: message → fix` — stable code first so an agent can act per code. */
|
|
15
|
+
export function formatFinding(f) {
|
|
16
|
+
const who = f.id ? ` #${f.id}${f.type ? ` (${f.type})` : ""}` : f.type ? ` (${f.type})` : "";
|
|
17
|
+
return `[${f.code}]${who}${f.at ? ` ${f.at}:` : ""} ${f.message}${f.fix ? ` → ${f.fix}` : ""}`;
|
|
18
|
+
}
|
|
19
|
+
/** Code of a formatted message (or the fallback for older free-text ones). */
|
|
20
|
+
export const codeOf = (msg, fallback = "OTHER") => /^\[([A-Z_]+)\]/.exec(msg)?.[1] ?? fallback;
|
|
21
|
+
/** Prefix a free-text message from an older checker with its code, once. */
|
|
22
|
+
export const withCode = (code, msg) => (/^\[[A-Z_]+\]/.test(msg) ? msg : `[${code}] ${msg}`);
|
|
23
|
+
/** Where a node must sit to work. Kept to rules the renderer actually depends on. */
|
|
24
|
+
const PARENTS = {
|
|
25
|
+
slide: ["swiper", "carousel"],
|
|
26
|
+
"collapse-item": ["collapse"],
|
|
27
|
+
};
|
|
28
|
+
export const FORM_FIELDS = new Set(["input", "email", "phone-number", "text-area", "select", "address", "password"]);
|
|
29
|
+
// "Semantic tag: h1|h2|h3." / "on|off." → an enum. Lists with an ellipsis are open-ended.
|
|
30
|
+
const ENUM_RE = /^(?:[^:|]*:\s*)?((?:[\w-]+)(?:\s*\|\s*[\w-]+)+)\.?$/;
|
|
31
|
+
const enumOf = (desc) => {
|
|
32
|
+
if (!desc || /…|\.\.\./.test(desc))
|
|
33
|
+
return undefined;
|
|
34
|
+
const m = ENUM_RE.exec(desc.trim());
|
|
35
|
+
return m ? m[1].split("|").map((s) => s.trim()) : undefined;
|
|
36
|
+
};
|
|
37
|
+
const typeOf = (v) => v === null || v === undefined ? undefined : Array.isArray(v) ? "array" : typeof v;
|
|
38
|
+
const cache = new Map();
|
|
39
|
+
/** Every specials / config key any element is known to carry. A key outside these is invented
|
|
40
|
+
* or misspelled; a key that exists on another element is left alone (the mined per-type lists
|
|
41
|
+
* are a sample, so "not seen on THIS type" is too weak to warn about). */
|
|
42
|
+
const ANY_SPECIALS = new Set([...Object.keys(SHARED_SPECIALS), ...Object.keys(SHARED_KEY_DICT)]);
|
|
43
|
+
const ANY_CONFIG = new Set(GENERIC_CONFIG);
|
|
44
|
+
for (const o of Object.values(OBSERVED)) {
|
|
45
|
+
o.specials.forEach((k) => ANY_SPECIALS.add(k));
|
|
46
|
+
o.config.forEach((k) => ANY_CONFIG.add(k));
|
|
47
|
+
}
|
|
48
|
+
for (const a of Object.values(ELEMENT_ATTRS)) {
|
|
49
|
+
Object.keys(a.specials || {}).forEach((k) => ANY_SPECIALS.add(k));
|
|
50
|
+
Object.keys(a.config || {}).forEach((k) => ANY_CONFIG.add(k));
|
|
51
|
+
}
|
|
52
|
+
const KEY_TYPES = new Set(["string", "number", "boolean", "array", "object"]);
|
|
53
|
+
export function elementSchema(type) {
|
|
54
|
+
if (!isKnownType(type))
|
|
55
|
+
return undefined;
|
|
56
|
+
const hit = cache.get(type);
|
|
57
|
+
if (hit)
|
|
58
|
+
return hit;
|
|
59
|
+
const skeleton = buildElement(type, {});
|
|
60
|
+
const obs = OBSERVED[type] || { specials: [], config: [], style: [], bindings: [], events: false };
|
|
61
|
+
const cur = ELEMENT_ATTRS[type] || {};
|
|
62
|
+
const bucket = (where, keys, defaults, curated, shared) => {
|
|
63
|
+
const out = {};
|
|
64
|
+
for (const k of [...keys].sort()) {
|
|
65
|
+
const desc = curated?.[k] ?? shared[k] ?? SHARED_KEY_DICT[k];
|
|
66
|
+
const spec = {};
|
|
67
|
+
const types = new Set((obs.types?.[`${where}.${k}`] || []).filter((t) => KEY_TYPES.has(t)));
|
|
68
|
+
const t = typeOf(defaults?.[k]);
|
|
69
|
+
if (t)
|
|
70
|
+
types.add(t);
|
|
71
|
+
if (types.size)
|
|
72
|
+
spec.types = [...types].sort();
|
|
73
|
+
const seen = obs.values?.[`${where}.${k}`];
|
|
74
|
+
const curatedEnum = enumOf(curated?.[k]);
|
|
75
|
+
// Enforced only when both the editor's list and real pages agree it is closed.
|
|
76
|
+
if (curatedEnum && seen)
|
|
77
|
+
spec.enum = [...new Set([...curatedEnum, ...seen])];
|
|
78
|
+
else if (seen)
|
|
79
|
+
spec.seen = seen;
|
|
80
|
+
if (desc)
|
|
81
|
+
spec.desc = desc;
|
|
82
|
+
out[k] = spec;
|
|
83
|
+
}
|
|
84
|
+
return out;
|
|
85
|
+
};
|
|
86
|
+
const sk = skeleton.specials || {};
|
|
87
|
+
const sc = skeleton.runtime?.config || {};
|
|
88
|
+
const schema = {
|
|
89
|
+
...describeType(type),
|
|
90
|
+
...(PARENTS[type] ? { parents: PARENTS[type] } : {}),
|
|
91
|
+
specials: bucket("specials", new Set([...obs.specials, ...Object.keys(cur.specials || {}), ...Object.keys(sk), ...Object.keys(SHARED_SPECIALS)]), sk, cur.specials, SHARED_SPECIALS),
|
|
92
|
+
config: bucket("config", new Set([...obs.config, ...Object.keys(cur.config || {}), ...Object.keys(sc), ...GENERIC_CONFIG]), sc, cur.config, {}),
|
|
93
|
+
style: "Any CSS property in camelCase (fontSize, backgroundColor…); emitted as CSS.",
|
|
94
|
+
events: !!obs.events || (!!cur.events && cur.events !== "none"),
|
|
95
|
+
...((cur.bindings?.length || obs.bindings?.length) ? { bindings: cur.bindings?.length ? cur.bindings : obs.bindings } : {}),
|
|
96
|
+
};
|
|
97
|
+
cache.set(type, schema);
|
|
98
|
+
return schema;
|
|
99
|
+
}
|
|
100
|
+
// ── CSS property names (style keys) ─────────────────────────────────────────────────────
|
|
101
|
+
// Mined style keys + standard CSS properties, camelCase. ponytail: a fixed list; add a
|
|
102
|
+
// property here if a real one gets flagged.
|
|
103
|
+
const CSS_PROPS = new Set(`alignContent alignItems alignSelf animation animationDelay animationDuration animationName aspectRatio
|
|
104
|
+
backdropFilter backfaceVisibility background backgroundAttachment backgroundBlendMode backgroundClip backgroundColor
|
|
105
|
+
backgroundImage backgroundOrigin backgroundPosition backgroundRepeat backgroundSize border borderBottom borderBottomColor
|
|
106
|
+
borderBottomLeftRadius borderBottomRightRadius borderBottomStyle borderBottomWidth borderColor borderLeft borderLeftColor
|
|
107
|
+
borderLeftStyle borderLeftWidth borderRadius borderRight borderRightColor borderRightStyle borderRightWidth borderSpacing
|
|
108
|
+
borderStyle borderTop borderTopColor borderTopLeftRadius borderTopRightRadius borderTopStyle borderTopWidth borderWidth
|
|
109
|
+
bottom boxShadow boxSizing clear clipPath color columnGap columns content cursor direction display fill filter flex
|
|
110
|
+
flexBasis flexDirection flexGrow flexShrink flexWrap float font fontFamily fontSize fontStyle fontVariant fontWeight gap
|
|
111
|
+
grid gridArea gridColumn gridColumnEnd gridColumnStart gridRow gridRowEnd gridRowStart gridTemplateAreas
|
|
112
|
+
gridTemplateColumns gridTemplateRows height inset isolation justifyContent justifyItems justifySelf left letterSpacing
|
|
113
|
+
lineHeight listStyle listStyleType margin marginBottom marginLeft marginRight marginTop mask maskImage maxHeight maxWidth
|
|
114
|
+
minHeight minWidth mixBlendMode objectFit objectPosition opacity order outline outlineColor outlineOffset outlineStyle
|
|
115
|
+
outlineWidth overflow overflowWrap overflowX overflowY padding paddingBottom paddingLeft paddingRight paddingTop
|
|
116
|
+
perspective placeItems placeSelf pointerEvents position right rotate rowGap scale stroke strokeWidth tableLayout textAlign
|
|
117
|
+
textDecoration textDecorationColor textIndent textOverflow textShadow textTransform top transform transformOrigin
|
|
118
|
+
transition transitionDelay transitionDuration transitionProperty translate userSelect verticalAlign visibility
|
|
119
|
+
webkitBackgroundClip webkitLineClamp webkitTextFillColor webkitTextStroke whiteSpace width wordBreak wordSpacing
|
|
120
|
+
writingMode zIndex WebkitBackgroundClip WebkitLineClamp WebkitTextFillColor WebkitBoxOrient`
|
|
121
|
+
.split(/\s+/)
|
|
122
|
+
.concat(Object.values(OBSERVED).flatMap((o) => o.style)));
|
|
123
|
+
// ── Checks ──────────────────────────────────────────────────────────────────────────────
|
|
124
|
+
const norm = (k) => k.toLowerCase().replace(/[-_]/g, "");
|
|
125
|
+
function lev(a, b) {
|
|
126
|
+
if (Math.abs(a.length - b.length) > 2)
|
|
127
|
+
return 3;
|
|
128
|
+
const d = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
129
|
+
for (let i = 1; i <= a.length; i++) {
|
|
130
|
+
let prev = d[0];
|
|
131
|
+
d[0] = i;
|
|
132
|
+
for (let j = 1; j <= b.length; j++) {
|
|
133
|
+
const t = d[j];
|
|
134
|
+
d[j] = Math.min(d[j] + 1, d[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
135
|
+
prev = t;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return d[b.length];
|
|
139
|
+
}
|
|
140
|
+
/** Closest known key: same letters ignoring case/-/_, else edit distance ≤ 2. */
|
|
141
|
+
export function didYouMean(key, known) {
|
|
142
|
+
let best;
|
|
143
|
+
let bestD = 3;
|
|
144
|
+
const nk = norm(key);
|
|
145
|
+
for (const k of known) {
|
|
146
|
+
if (norm(k) === nk)
|
|
147
|
+
return k;
|
|
148
|
+
const d = lev(key, k);
|
|
149
|
+
if (key.length < 4 && d > 1)
|
|
150
|
+
continue;
|
|
151
|
+
if (d < bestD)
|
|
152
|
+
[best, bestD] = [k, d];
|
|
153
|
+
}
|
|
154
|
+
return best;
|
|
155
|
+
}
|
|
156
|
+
const kebabToCamel = (k) => k.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
157
|
+
const NOISE = new Set(["undefined", "locked", "loaded", "isChangeSection"]);
|
|
158
|
+
/** Keys an agent invents from HTML habits → where the element really keeps that. */
|
|
159
|
+
const INVENTED = {
|
|
160
|
+
content: "put the text/HTML in specials.text",
|
|
161
|
+
html: "put the text/HTML in specials.text",
|
|
162
|
+
label: "put the label in specials.text",
|
|
163
|
+
innerText: "put the text in specials.text",
|
|
164
|
+
href: 'links are events: events:[{ trigger:"click", action:"open_link", link_target_url:"…" }] (see list_events)',
|
|
165
|
+
url: 'links are events: events:[{ trigger:"click", action:"open_link", link_target_url:"…" }] (see list_events)',
|
|
166
|
+
onClick: "interactions are events[] (see list_events)",
|
|
167
|
+
image: "put the hosted URL in specials.src / runtime.config.src",
|
|
168
|
+
};
|
|
169
|
+
function checkValue(spec, v, f, out) {
|
|
170
|
+
if (!spec || v === null || v === undefined || v === "")
|
|
171
|
+
return;
|
|
172
|
+
const got = typeOf(v);
|
|
173
|
+
if (spec.types && !spec.types.includes(got)) {
|
|
174
|
+
const asBool = spec.types.includes("boolean") && got === "string" && /^(true|false)$/i.test(v);
|
|
175
|
+
out.push({
|
|
176
|
+
...f, code: "TYPE_MISMATCH", severity: "warning",
|
|
177
|
+
message: `${got} value, the element reads ${spec.types.join("|")}`,
|
|
178
|
+
fix: asBool ? `use ${String(v).toLowerCase()} (boolean)` : undefined,
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
if (spec.enum && typeof v === "string" && !spec.enum.includes(v)) {
|
|
182
|
+
const guess = didYouMean(v, spec.enum);
|
|
183
|
+
out.push({ ...f, code: "BAD_VALUE", severity: "warning", message: `"${v}" is not one of ${spec.enum.join("|")}`, fix: guess ? `use "${guess}"` : undefined });
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
/** Unknown / mistyped specials, config and style keys of one node, per layer it carries. */
|
|
187
|
+
export function checkElementKeys(node) {
|
|
188
|
+
const out = [];
|
|
189
|
+
const schema = node && typeof node.type === "string" ? elementSchema(node.type) : undefined;
|
|
190
|
+
if (!schema)
|
|
191
|
+
return out;
|
|
192
|
+
const base = { id: node.id, type: node.type };
|
|
193
|
+
const specialsKeys = Object.keys(schema.specials);
|
|
194
|
+
const configKeys = Object.keys(schema.config);
|
|
195
|
+
const keysIn = (obj, where, specs, known, other) => {
|
|
196
|
+
if (!obj || typeof obj !== "object" || Array.isArray(obj))
|
|
197
|
+
return;
|
|
198
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
199
|
+
if (NOISE.has(k))
|
|
200
|
+
continue;
|
|
201
|
+
const at = `${where}.${k}`;
|
|
202
|
+
if (k in specs) {
|
|
203
|
+
checkValue(specs[k], v, { ...base, at }, out);
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
const anywhere = where === "specials" ? ANY_SPECIALS : ANY_CONFIG;
|
|
207
|
+
if (anywhere.has(k))
|
|
208
|
+
continue; // real key (seen on another element) — not a typo
|
|
209
|
+
const wrongPlace = other && k in other.specs ? other.name : CSS_PROPS.has(k) && where.endsWith("config") ? "style" : undefined;
|
|
210
|
+
const guess = wrongPlace || INVENTED[k] ? undefined : didYouMean(k, known) ?? didYouMean(k, anywhere);
|
|
211
|
+
out.push({
|
|
212
|
+
...base, at, code: "UNKNOWN_KEY", severity: "warning",
|
|
213
|
+
message: wrongPlace ? `belongs in ${wrongPlace}, not ${where.split(".").pop()}` : `no element has a ${where.split(".").pop()} key "${k}" — the renderer ignores it`,
|
|
214
|
+
fix: wrongPlace ? `move it to ${wrongPlace}` : INVENTED[k] ?? (guess ? `did you mean "${guess}"?` : `see get_element("${node.type}")`),
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
const styleIn = (obj, where) => {
|
|
219
|
+
if (!obj || typeof obj !== "object" || Array.isArray(obj))
|
|
220
|
+
return;
|
|
221
|
+
for (const k of Object.keys(obj)) {
|
|
222
|
+
if (CSS_PROPS.has(k) || NOISE.has(k))
|
|
223
|
+
continue;
|
|
224
|
+
const at = `${where}.${k}`;
|
|
225
|
+
if (k.includes("-") && CSS_PROPS.has(kebabToCamel(k)))
|
|
226
|
+
out.push({ ...base, at, code: "STYLE_KEY", severity: "warning", message: "kebab-case style key: element-specific CSS reads camelCase", fix: `rename to "${kebabToCamel(k)}"` });
|
|
227
|
+
else if (k in schema.config)
|
|
228
|
+
out.push({ ...base, at, code: "UNKNOWN_KEY", severity: "warning", message: "belongs in config, not style", fix: "move it to config" });
|
|
229
|
+
else {
|
|
230
|
+
const guess = didYouMean(k, CSS_PROPS);
|
|
231
|
+
out.push({ ...base, at, code: "STYLE_KEY", severity: "warning", message: `"${k}" is not a CSS property`, fix: guess ? `did you mean "${guess}"?` : undefined });
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
keysIn(node.specials, "specials", schema.specials, specialsKeys, { name: "config", specs: schema.config });
|
|
236
|
+
for (const layer of Object.keys(node).filter((k) => k === "runtime" || /^bp\d+$/.test(k))) {
|
|
237
|
+
const l = node[layer];
|
|
238
|
+
if (!l || typeof l !== "object")
|
|
239
|
+
continue;
|
|
240
|
+
keysIn(l.config, `${layer}.config`, schema.config, configKeys, { name: "specials", specs: schema.specials });
|
|
241
|
+
styleIn(l.style, `${layer}.style`);
|
|
242
|
+
}
|
|
243
|
+
return out;
|
|
244
|
+
}
|
|
245
|
+
/** An element that must sit inside a given parent type but doesn't. */
|
|
246
|
+
export function checkParent(node, ancestors) {
|
|
247
|
+
const need = PARENTS[node?.type];
|
|
248
|
+
if (!need || need.includes(ancestors[ancestors.length - 1]))
|
|
249
|
+
return undefined;
|
|
250
|
+
return { code: "BAD_PARENT", severity: "warning", id: node.id, type: node.type, message: `must be a direct child of ${need.join(" or ")} — it won't render here`, fix: `move it into a ${need[0]}` };
|
|
251
|
+
}
|
|
252
|
+
/** The value rules of one element, compact for get_element: enums, seen values and non-string
|
|
253
|
+
* types — the part of the schema the attribute descriptions don't already say. */
|
|
254
|
+
export function valueRules(type) {
|
|
255
|
+
const schema = elementSchema(type);
|
|
256
|
+
if (!schema)
|
|
257
|
+
return undefined;
|
|
258
|
+
const out = {};
|
|
259
|
+
for (const where of ["specials", "config"])
|
|
260
|
+
for (const [k, spec] of Object.entries(schema[where])) {
|
|
261
|
+
if (where === "config" && GENERIC_CONFIG.has(k))
|
|
262
|
+
continue; // grid/position: same on every element
|
|
263
|
+
const parts = [];
|
|
264
|
+
if (spec.enum)
|
|
265
|
+
parts.push(`one of ${spec.enum.join("|")}`);
|
|
266
|
+
else if (spec.seen)
|
|
267
|
+
parts.push(`seen ${spec.seen.join("|")}`);
|
|
268
|
+
if (spec.types && !(spec.types.length === 1 && spec.types[0] === "string"))
|
|
269
|
+
parts.push(spec.types.join("|"));
|
|
270
|
+
if (parts.length)
|
|
271
|
+
out[`${where}.${k}`] = parts.join("; ");
|
|
272
|
+
}
|
|
273
|
+
return Object.keys(out).length ? out : undefined;
|
|
274
|
+
}
|
|
275
|
+
/** Did-you-mean for an unknown element type. */
|
|
276
|
+
export const suggestType = (type) => didYouMean(type, ELEMENT_TYPES);
|
|
277
|
+
/** Collapse repeated warnings per code: keep the first `keep`, then one line with the rest. */
|
|
278
|
+
export function collapseByCode(msgs, keep = 5) {
|
|
279
|
+
const seen = {};
|
|
280
|
+
const out = [];
|
|
281
|
+
for (const m of msgs) {
|
|
282
|
+
const c = codeOf(m);
|
|
283
|
+
seen[c] = (seen[c] || 0) + 1;
|
|
284
|
+
if (seen[c] <= keep)
|
|
285
|
+
out.push(m);
|
|
286
|
+
}
|
|
287
|
+
for (const [c, n] of Object.entries(seen))
|
|
288
|
+
if (n > keep)
|
|
289
|
+
out.push(`[${c}] …and ${n - keep} more of this kind (fix the ones above the same way)`);
|
|
290
|
+
return out;
|
|
291
|
+
}
|
|
292
|
+
export function countByCode(msgs) {
|
|
293
|
+
const out = {};
|
|
294
|
+
for (const m of msgs)
|
|
295
|
+
out[codeOf(m)] = (out[codeOf(m)] || 0) + 1;
|
|
296
|
+
return out;
|
|
297
|
+
}
|
package/dist/builder/page.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// their children in a CSS grid driven by runtime.config (grid / columns / rows) and each
|
|
5
5
|
// child's runtime.config (columnStart/End, rowStart/End, constraintX/Y). The helpers here
|
|
6
6
|
// produce that structure the same way the builder does, so generated pages render.
|
|
7
|
+
import { checkElementKeys, checkParent, collapseByCode, countByCode, formatFinding, FORM_FIELDS, suggestType, withCode } from "./element-schema.js";
|
|
7
8
|
import { buildElement, isKnownType, ELEMENT_TYPES } from "./catalog.js";
|
|
8
9
|
import { randomString } from "./factory.js";
|
|
9
10
|
import { validateEvents, normalizeEvents } from "./events.js";
|
|
@@ -412,55 +413,57 @@ export function checkContentPlaceholders(content, previous) {
|
|
|
412
413
|
export function validatePage(source, previous) {
|
|
413
414
|
const errors = [];
|
|
414
415
|
const warnings = [];
|
|
416
|
+
const add = (f) => (f.severity === "error" ? errors : warnings).push(formatFinding(f));
|
|
415
417
|
// editor_v2 pages ({ nodes, root_node_id, schema_version }) are a different model this server
|
|
416
418
|
// doesn't author; judging them by v1 rules would block publishing every V2 site.
|
|
417
419
|
if (source && typeof source === "object" && source.nodes && source.root_node_id) {
|
|
418
420
|
return { valid: true, skipped: "editor_v2 source (nodes/root_node_id): not checked by the v1 validator" };
|
|
419
421
|
}
|
|
420
422
|
if (!source || typeof source !== "object" || !Array.isArray(source.sections)) {
|
|
421
|
-
return { valid: false, errors: ["Source must be an object shaped { sections: [...] }."] };
|
|
423
|
+
return { valid: false, errors: ["[BAD_SOURCE] Source must be an object shaped { sections: [...] }."] };
|
|
422
424
|
}
|
|
423
425
|
const ids = new Set();
|
|
424
426
|
const allIds = new Set();
|
|
425
427
|
let total = 0;
|
|
426
428
|
const typeCounts = {};
|
|
427
|
-
// First pass: collect ids + flag duplicates / unknown types / missing fields.
|
|
429
|
+
// First pass: collect ids + flag duplicates / unknown types / missing fields / unknown keys.
|
|
428
430
|
walk(source, (node) => {
|
|
429
431
|
total++;
|
|
430
432
|
const type = node.type || "(missing)";
|
|
431
433
|
typeCounts[type] = (typeCounts[type] || 0) + 1;
|
|
432
434
|
if (!node.id)
|
|
433
|
-
|
|
435
|
+
add({ code: "MISSING_ID", severity: "error", type, message: "node has no id", fix: "build it with new_element" });
|
|
434
436
|
else if (ids.has(node.id))
|
|
435
|
-
|
|
437
|
+
add({ code: "DUP_ID", severity: "error", id: node.id, type, message: `Duplicate element id "${node.id}"`, fix: "re-id the copy (new_element mints fresh ids)" });
|
|
436
438
|
else
|
|
437
439
|
ids.add(node.id);
|
|
438
440
|
if (node.id)
|
|
439
441
|
allIds.add(node.id);
|
|
440
442
|
if (!node.type)
|
|
441
|
-
|
|
442
|
-
else if (!isKnownType(node.type))
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
if (/^(input|email|phone-number|text-area|select|address|password)$/.test(node.type || "")) {
|
|
446
|
-
const fn = node.specials && node.specials.field_name;
|
|
447
|
-
if (!fn)
|
|
448
|
-
warnings.push(`Form field "${node.id}" (${node.type}) has no specials.field_name.`);
|
|
443
|
+
add({ code: "MISSING_TYPE", severity: "error", id: node.id || "?", message: "node has no type" });
|
|
444
|
+
else if (!isKnownType(node.type)) {
|
|
445
|
+
const guess = suggestType(node.type);
|
|
446
|
+
add({ code: "UNKNOWN_TYPE", severity: "warning", id: node.id, type: node.type, message: `Unknown element type "${node.type}"`, fix: guess ? `did you mean "${guess}"?` : "see list_elements" });
|
|
449
447
|
}
|
|
448
|
+
// Form fields should carry a field_name so submissions map to data.
|
|
449
|
+
if (FORM_FIELDS.has(node.type || "") && !(node.specials && node.specials.field_name))
|
|
450
|
+
add({ code: "FIELD_NAME", severity: "warning", id: node.id, type: node.type, at: "specials.field_name", message: `Form field has no specials.field_name — its value is not submitted`, fix: "set e.g. full_name / email / phone_number" });
|
|
451
|
+
for (const f of checkElementKeys(node))
|
|
452
|
+
add(f);
|
|
450
453
|
});
|
|
451
454
|
// Second pass: events + bindings against the authoritative catalogs (unknown
|
|
452
455
|
// trigger/action/dataset, missing required fields, dangling in-page event targets,
|
|
453
|
-
// unknown binding fields).
|
|
456
|
+
// unknown binding fields).
|
|
454
457
|
walk(source, (node) => {
|
|
455
458
|
if (node.events && node.events.length) {
|
|
456
459
|
const r = validateEvents(node, allIds);
|
|
457
|
-
errors.push(...r.errors);
|
|
458
|
-
warnings.push(...r.warnings);
|
|
460
|
+
errors.push(...r.errors.map((m) => withCode("EVENT", m)));
|
|
461
|
+
warnings.push(...r.warnings.map((m) => withCode("EVENT", m)));
|
|
459
462
|
}
|
|
460
463
|
if (node.bindings && node.bindings.length) {
|
|
461
464
|
const r = validateBindings(node);
|
|
462
|
-
errors.push(...r.errors);
|
|
463
|
-
warnings.push(...r.warnings);
|
|
465
|
+
errors.push(...r.errors.map((m) => withCode("BINDING", m)));
|
|
466
|
+
warnings.push(...r.warnings.map((m) => withCode("BINDING", m)));
|
|
464
467
|
}
|
|
465
468
|
});
|
|
466
469
|
// Third pass (needs ancestry): structures the renderer silently mishandles. Warnings only.
|
|
@@ -471,14 +474,20 @@ export function validatePage(source, previous) {
|
|
|
471
474
|
return;
|
|
472
475
|
const type = node.type;
|
|
473
476
|
const kids = Array.isArray(node.children) ? node.children : [];
|
|
477
|
+
const w = (code, message, fix) => add({ code, severity: "warning", id: node.id, type, message, fix });
|
|
474
478
|
if (!ancestors.length && type && type !== "section" && type !== "popup")
|
|
475
|
-
|
|
479
|
+
w("TOP_LEVEL", `Top-level node "${node.id}" is a ${type}: pages render only sections at the top level`, "wrap it in a section");
|
|
476
480
|
if (kids.length && LEAF_TYPES.has(type))
|
|
477
|
-
|
|
481
|
+
w("LEAF_CHILDREN", `"${node.id}" (${type}) has ${kids.length} child node(s), but ${type} is not a container — they won't render`, "move them into a container");
|
|
478
482
|
if (type === "submit-button" && !ancestors.some((t) => /form/.test(t)))
|
|
479
|
-
|
|
483
|
+
w("OUTSIDE_FORM", `Submit button "${node.id}" is not inside a form — it has nothing to submit`, "put it inside the form");
|
|
484
|
+
else if (FORM_FIELDS.has(type) && ancestors.length && !ancestors.some((t) => /form/.test(t)))
|
|
485
|
+
w("OUTSIDE_FORM", "form field is not inside a form — nothing submits it", "put it inside a form");
|
|
480
486
|
if ((node.bindings || []).some((b) => b?.name === "wishlist_item") && !ancestors.includes("wishlist-item"))
|
|
481
|
-
|
|
487
|
+
w("BINDING_SCOPE", `"${node.id}" binds wishlist_item::… outside a wishlist-item — those fields only resolve per saved product`);
|
|
488
|
+
const parent = ancestors.length ? checkParent(node, ancestors) : undefined;
|
|
489
|
+
if (parent)
|
|
490
|
+
add(parent);
|
|
482
491
|
for (const c of kids)
|
|
483
492
|
checkTree(c, [...ancestors, type]);
|
|
484
493
|
};
|
|
@@ -487,15 +496,18 @@ export function validatePage(source, previous) {
|
|
|
487
496
|
// Crash-level shapes for the renderer and the editor (null children, non-object specials/bp,
|
|
488
497
|
// bad widthUnit/constraints/grid…). See shape.ts.
|
|
489
498
|
const shape = checkShape(source);
|
|
490
|
-
errors.push(...shape.errors);
|
|
491
|
-
warnings.push(...shape.warnings);
|
|
499
|
+
errors.push(...shape.errors.map((m) => withCode("SHAPE", m)));
|
|
500
|
+
warnings.push(...shape.warnings.map((m) => withCode("SHAPE", m)));
|
|
492
501
|
const code = checkNativeContent(source, previous);
|
|
493
|
-
errors.push(...code.errors);
|
|
494
|
-
warnings.push(...code.warnings);
|
|
502
|
+
errors.push(...code.errors.map((m) => withCode("NATIVE", m)));
|
|
503
|
+
warnings.push(...code.warnings.map((m) => withCode("NATIVE", m)));
|
|
495
504
|
return {
|
|
496
505
|
valid: errors.length === 0,
|
|
497
506
|
...(errors.length ? { errors } : {}),
|
|
498
|
-
...(warnings.length ? { warnings } : {}),
|
|
507
|
+
...(warnings.length ? { warnings: collapseByCode(warnings) } : {}),
|
|
508
|
+
...(errors.length || warnings.length
|
|
509
|
+
? { summary: { errors: errors.length, warnings: warnings.length, by_code: countByCode([...errors, ...warnings]), read: "[CODE] #id (type) where: problem → fix. Errors block the save; warnings render wrong." } }
|
|
510
|
+
: {}),
|
|
499
511
|
stats: { sections: source.sections.length, total_elements: total, element_types: typeCounts },
|
|
500
512
|
};
|
|
501
513
|
}
|
package/dist/changelog.json
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
[
|
|
2
|
+
{
|
|
3
|
+
"v": "1.42.0",
|
|
4
|
+
"d": "19/11/2026",
|
|
5
|
+
"type": "Added",
|
|
6
|
+
"en": "New api_find, api_get, and api_call tools expose the full WebCake backend API that the storefront token can reach (775 operations), including 552…",
|
|
7
|
+
"vi": "Tool mới api_find, api_get, và api_call mở ra toàn bộ API backend WebCake mà token storefront có thể gọi (775 route), trong đó 552 route trước đây…"
|
|
8
|
+
},
|
|
2
9
|
{
|
|
3
10
|
"v": "1.41.0",
|
|
4
11
|
"d": "19/11/2026",
|
|
@@ -33,12 +40,5 @@
|
|
|
33
40
|
"type": "Added",
|
|
34
41
|
"en": "A new native-first guide is now injected into get_build_guide's build guide, get_http_function's and get_site_custom_code's custom-code guide, and…",
|
|
35
42
|
"vi": "Hướng dẫn \"native first\" mới nay được chèn vào build guide của get_build_guide, custom-code guide của get_http_function và get_site_custom_code,…"
|
|
36
|
-
},
|
|
37
|
-
{
|
|
38
|
-
"v": "1.36.2",
|
|
39
|
-
"d": "29/10/2026",
|
|
40
|
-
"type": "Fixed",
|
|
41
|
-
"en": "publish_site, create_global_section, delete_global_section, update_site_custom_code, and append_site_custom_code now fail with a clear error instead…",
|
|
42
|
-
"vi": "publish_site, create_global_section, delete_global_section, update_site_custom_code và append_site_custom_code nay báo lỗi rõ ràng thay vì âm thầm…"
|
|
43
43
|
}
|
|
44
44
|
]
|
package/dist/server.js
CHANGED
|
@@ -16,7 +16,7 @@ const INSTRUCTIONS = `You are an AI assistant connected to the WebCake/StoreCake
|
|
|
16
16
|
|
|
17
17
|
IMPORTANT: When the user asks ANY question about their website, store, products, orders, pages, or code — you MUST use the available tools to look up real data before answering. Never guess.
|
|
18
18
|
|
|
19
|
-
Tool discovery: the common tools (pages, builder, products, orders, blog, customers, apps, publishing) are loaded directly. MANY more capabilities are available on demand — marketing/CRM (email, contacts, subscribers, employees), translations, media library, appointments, affiliate, product reviews, custom domains / SEO redirects / shipping, brands / tags / ribbons / materials, courses, sale channels, automation, and more. If you don't see a directly-loaded tool for the task, call search_tools("keywords") to find it, then run it with invoke_read_tool(name, arguments) if it only reads (list_/get_/search_…), otherwise invoke_tool(name, arguments). Use list_tool_groups to see everything available.
|
|
19
|
+
Tool discovery: the common tools (pages, builder, products, orders, blog, customers, apps, publishing) are loaded directly. MANY more capabilities are available on demand — marketing/CRM (email, contacts, subscribers, employees), translations, media library, appointments, affiliate, product reviews, custom domains / SEO redirects / shipping, brands / tags / ribbons / materials, courses, sale channels, automation, and more. If you don't see a directly-loaded tool for the task, call search_tools("keywords") to find it, then run it with invoke_read_tool(name, arguments) if it only reads (list_/get_/search_…), otherwise invoke_tool(name, arguments). Use list_tool_groups to see everything available. If NO tool covers it, the whole backend API is reachable: api_find("keywords") → api_get (reads) / api_call (writes, dry_run first).
|
|
20
20
|
|
|
21
21
|
You can also BUILD pages: use get_build_guide, list_elements, get_element to learn the BuilderX component model, new_section/new_element to compose, validate_page to check, then build_page (dry_run first) to create. Publishing is site-level via publish_site.
|
|
22
22
|
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// api_find / api_get / api_call: the whole builderx_api surface the storefront JWT can reach,
|
|
2
|
+
// from src/api-catalog.generated.json (scripts/gen-api-catalog.mjs reads the Phoenix routers and
|
|
3
|
+
// controllers). The hand-written tools stay the way to do anything they cover: a write to a route
|
|
4
|
+
// one of them owns is refused here and names that tool, since those tools carry the guards
|
|
5
|
+
// (settings merge, page-source validation, native-first, CMS tokens, by_ai…).
|
|
6
|
+
import { readFileSync } from "node:fs";
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
let CATALOG = { meta: {}, ops: [] };
|
|
9
|
+
try {
|
|
10
|
+
CATALOG = JSON.parse(readFileSync(new URL("../api-catalog.generated.json", import.meta.url), "utf8"));
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
/* catalog missing: the tools answer with an empty list */
|
|
14
|
+
}
|
|
15
|
+
export const API_OPS = CATALOG.ops;
|
|
16
|
+
const BY_ID = new Map(API_OPS.map((o) => [o.id, o]));
|
|
17
|
+
/** Irreversible account-level operations: never through the generic gateway. */
|
|
18
|
+
const DENY = {
|
|
19
|
+
"post:/api/v1/dashboard/site/delete": "deleting a site is done by the owner in the WebCake dashboard",
|
|
20
|
+
"post:/api/v1/dashboard/site/:site_id/settings/employee/move_owner_permission": "transferring site ownership is done by the owner in the WebCake dashboard",
|
|
21
|
+
};
|
|
22
|
+
const pathParams = (path) => [...path.matchAll(/:(\w+)/g)].map((m) => m[1]);
|
|
23
|
+
const words = (s) => s.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
|
|
24
|
+
/** One line per operation — what api_find returns for a query. */
|
|
25
|
+
export function opLine(o) {
|
|
26
|
+
const keys = o.params ? Object.keys(o.params) : [];
|
|
27
|
+
const shown = keys.slice(0, 6).map((k) => (o.required?.includes(k) ? `${k}*` : k));
|
|
28
|
+
return `${o.id} — ${o.handler}${shown.length ? ` (${shown.join(", ")}${keys.length > 6 ? ", …" : ""})` : ""}${o.tools ? ` ⇒ tool: ${o.tools.slice(0, 3).join(", ")}` : ""}`;
|
|
29
|
+
}
|
|
30
|
+
export function searchOps(query, limit = 15, method) {
|
|
31
|
+
const terms = words(query);
|
|
32
|
+
const scored = API_OPS.filter((o) => !method || o.method === method.toUpperCase())
|
|
33
|
+
.map((o) => {
|
|
34
|
+
const segs = words(o.path.replace(/:\w+/g, ""));
|
|
35
|
+
const hw = words(o.handler);
|
|
36
|
+
const pw = Object.keys(o.params || {}).flatMap(words);
|
|
37
|
+
let s = 0;
|
|
38
|
+
for (const t of terms) {
|
|
39
|
+
if (segs.includes(t))
|
|
40
|
+
s += 3;
|
|
41
|
+
else if (segs.some((w) => w.startsWith(t) || t.startsWith(w) && w.length > 3))
|
|
42
|
+
s += 2;
|
|
43
|
+
if (hw.includes(t))
|
|
44
|
+
s += 2;
|
|
45
|
+
if (pw.includes(t))
|
|
46
|
+
s += 1;
|
|
47
|
+
}
|
|
48
|
+
if (s && o.path.includes("/dashboard/site/:site_id/"))
|
|
49
|
+
s += 0.5; // the site-scoped admin API
|
|
50
|
+
return { o, s };
|
|
51
|
+
})
|
|
52
|
+
.filter((x) => x.s > 0)
|
|
53
|
+
.sort((a, b) => b.s - a.s || a.o.path.length - b.o.path.length);
|
|
54
|
+
return scored.slice(0, limit).map((x) => x.o);
|
|
55
|
+
}
|
|
56
|
+
/** The call sheet: everything needed to call one operation correctly. */
|
|
57
|
+
export function describeOp(o) {
|
|
58
|
+
const where = o.method === "GET" ? "query" : "body";
|
|
59
|
+
return {
|
|
60
|
+
id: o.id,
|
|
61
|
+
method: o.method,
|
|
62
|
+
path: o.path,
|
|
63
|
+
handler: o.handler,
|
|
64
|
+
path_params: pathParams(o.path),
|
|
65
|
+
[where]: o.params || "not readable from the controller — send a modified copy of the matching GET",
|
|
66
|
+
...(o.required ? { required: o.required } : {}),
|
|
67
|
+
...(o.perms ? { needs_permission: o.perms } : {}),
|
|
68
|
+
...(o.tools
|
|
69
|
+
? { prefer_tool: o.tools, note: o.method === "GET" ? "A dedicated tool covers this route and returns a cleaner result." : "Writes to this route go through the dedicated tool (it carries the guards); api_call refuses them." }
|
|
70
|
+
: {}),
|
|
71
|
+
...(DENY[o.id] ? { refused: DENY[o.id] } : {}),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
const LIST_KEYS = ["data", "items", "products", "orders", "customers", "articles", "results", "list", "records", "entries"];
|
|
75
|
+
/** Trim a response for the model: keep `pick` fields per item, cap list length. */
|
|
76
|
+
export function trimResult(res, pick, maxItems = 50) {
|
|
77
|
+
const pickOne = (x) => pick && x && typeof x === "object" && !Array.isArray(x) ? Object.fromEntries(pick.filter((k) => k in x).map((k) => [k, x[k]])) : x;
|
|
78
|
+
const trimList = (arr) => {
|
|
79
|
+
const items = arr.slice(0, maxItems).map(pickOne);
|
|
80
|
+
return arr.length > maxItems ? { items, total_items: arr.length, truncated: true } : items;
|
|
81
|
+
};
|
|
82
|
+
if (Array.isArray(res))
|
|
83
|
+
return trimList(res);
|
|
84
|
+
if (res && typeof res === "object") {
|
|
85
|
+
for (const k of LIST_KEYS) {
|
|
86
|
+
if (Array.isArray(res[k]))
|
|
87
|
+
return { ...res, [k]: trimList(res[k]) };
|
|
88
|
+
if (res[k] && typeof res[k] === "object")
|
|
89
|
+
for (const k2 of LIST_KEYS)
|
|
90
|
+
if (Array.isArray(res[k][k2]))
|
|
91
|
+
return { ...res, [k]: { ...res[k], [k2]: trimList(res[k][k2]) } };
|
|
92
|
+
}
|
|
93
|
+
return pick ? pickOne(res) : res;
|
|
94
|
+
}
|
|
95
|
+
return res;
|
|
96
|
+
}
|
|
97
|
+
const MAX_CHARS = 30_000;
|
|
98
|
+
export function registerApiGatewayTools(server, api, handle) {
|
|
99
|
+
server.tool("api_find", `Search the FULL WebCake backend API (${API_OPS.length} operations the storefront account can call — far more than the dedicated tools cover). With \`query\`: one line per match \`id — Controller.action (body/query keys, * = required) ⇒ tool: dedicated tool if one exists\`. With \`id\`: the call sheet (path params, body/query keys with their nested fields, required keys, permission needed). Prefer a dedicated tool when one is listed; use api_get / api_call for the rest.`, {
|
|
100
|
+
query: z.string().optional().describe("English keywords from the path/controller, e.g. 'shipping fee', 'product tag', 'customer point'"),
|
|
101
|
+
id: z.string().optional().describe("Exact operation id from a previous search, e.g. 'post:/api/v1/dashboard/site/:site_id/products/create'"),
|
|
102
|
+
method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]).optional().describe("Only this HTTP method"),
|
|
103
|
+
limit: z.number().int().min(1).max(40).optional().describe("Max lines (default 15)"),
|
|
104
|
+
}, ({ query, id, method, limit }) => handle(async () => {
|
|
105
|
+
if (id) {
|
|
106
|
+
const o = BY_ID.get(id);
|
|
107
|
+
if (!o)
|
|
108
|
+
throw new Error(`Unknown operation "${id}". Search with api_find({ query }).`);
|
|
109
|
+
return describeOp(o);
|
|
110
|
+
}
|
|
111
|
+
if (!query)
|
|
112
|
+
throw new Error("Pass query (keywords) or id (an operation id).");
|
|
113
|
+
const hits = searchOps(query, limit ?? 15, method);
|
|
114
|
+
return hits.length ? hits.map(opLine) : `No operation matches "${query}". Try other English words from the path (e.g. 'promotion', 'shipping', 'tag').`;
|
|
115
|
+
}));
|
|
116
|
+
const call = async (args, readOnly) => {
|
|
117
|
+
const o = args.id ? BY_ID.get(args.id) : API_OPS.find((x) => x.method === String(args.method || "").toUpperCase() && x.path === args.path);
|
|
118
|
+
if (!o)
|
|
119
|
+
throw new Error(`Unknown operation${args.id ? ` "${args.id}"` : ""}. Find it with api_find({ query }) and pass its id.`);
|
|
120
|
+
if (readOnly && o.method !== "GET")
|
|
121
|
+
throw new Error(`${o.id} is a ${o.method} — run it with api_call.`);
|
|
122
|
+
if (DENY[o.id])
|
|
123
|
+
throw new Error(`Refused: ${DENY[o.id]}.`);
|
|
124
|
+
if (o.method !== "GET" && o.tools)
|
|
125
|
+
throw new Error(`Refused: ${o.id} is written through ${o.tools.join(" / ")} — that tool validates and guards this write. Use it instead.`);
|
|
126
|
+
const params = { ...(args.path_params || {}) };
|
|
127
|
+
if (params.site_id == null && pathParams(o.path).includes("site_id")) {
|
|
128
|
+
if (!api.siteId)
|
|
129
|
+
throw new Error("No site selected — call list_my_sites + switch_site, or pass path_params.site_id.");
|
|
130
|
+
params.site_id = api.siteId;
|
|
131
|
+
}
|
|
132
|
+
const missingPath = pathParams(o.path).filter((p) => params[p] == null || params[p] === "");
|
|
133
|
+
if (missingPath.length)
|
|
134
|
+
throw new Error(`Missing path_params: ${missingPath.join(", ")}. Call sheet: api_find({ id: "${o.id}" }).`);
|
|
135
|
+
const path = o.path.replace(/:(\w+)/g, (_, p) => encodeURIComponent(String(params[p])));
|
|
136
|
+
const input = o.method === "GET" ? args.query || {} : args.body || {};
|
|
137
|
+
const missing = (o.required || []).filter((k) => input[k] === undefined);
|
|
138
|
+
if (missing.length)
|
|
139
|
+
throw new Error(`Missing required ${o.method === "GET" ? "query" : "body"} keys: ${missing.join(", ")}. Call sheet: api_find({ id: "${o.id}" }).`);
|
|
140
|
+
const unknown = o.params ? Object.keys(input).filter((k) => !(k in o.params)) : [];
|
|
141
|
+
if (o.method !== "GET" && args.dry_run !== false)
|
|
142
|
+
return {
|
|
143
|
+
dry_run: true,
|
|
144
|
+
would_send: { method: o.method, path, ...(args.query ? { query: args.query } : {}), body: input },
|
|
145
|
+
...(unknown.length ? { unknown_keys: unknown, note: "the action never reads these keys" } : {}),
|
|
146
|
+
next: "Show the user what will change; on their OK call again with dry_run:false.",
|
|
147
|
+
};
|
|
148
|
+
let res;
|
|
149
|
+
try {
|
|
150
|
+
res = await api.request(o.method === "ANY" ? "POST" : o.method, path, o.method === "GET" ? { query: input } : { body: input, query: args.query });
|
|
151
|
+
}
|
|
152
|
+
catch (e) {
|
|
153
|
+
const msg = e?.message || String(e);
|
|
154
|
+
throw new Error(/API 403/.test(msg) && o.perms ? `${msg} — needs site permission ${o.perms.join(" / ")}.` : msg);
|
|
155
|
+
}
|
|
156
|
+
const out = trimResult(res, args.pick, args.max_items ?? 50);
|
|
157
|
+
const text = JSON.stringify(out);
|
|
158
|
+
return {
|
|
159
|
+
...(unknown.length ? { unknown_keys: unknown } : {}),
|
|
160
|
+
result: text.length > MAX_CHARS ? `${text.slice(0, MAX_CHARS)}… (cut at ${MAX_CHARS} chars — narrow with pick / max_items / query filters)` : out,
|
|
161
|
+
};
|
|
162
|
+
};
|
|
163
|
+
const shared = {
|
|
164
|
+
id: z.string().optional().describe("Operation id from api_find (preferred)"),
|
|
165
|
+
method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "ANY"]).optional().describe("With path, when id is not given"),
|
|
166
|
+
path: z.string().optional().describe("Catalog path with :params, e.g. /api/v1/dashboard/site/:site_id/product_tags/all"),
|
|
167
|
+
path_params: z.record(z.string()).optional().describe("Values for :params in the path; site_id defaults to the current site"),
|
|
168
|
+
query: z.record(z.any()).optional().describe("Query-string values"),
|
|
169
|
+
pick: z.array(z.string()).optional().describe("Keep only these fields on each item of a list result (or on a single object)"),
|
|
170
|
+
max_items: z.number().int().min(1).max(500).optional().describe("Cap list results (default 50)"),
|
|
171
|
+
};
|
|
172
|
+
server.tool("api_get", "Run a READ-ONLY (GET) operation from api_find by id. site_id is filled from the current site. Use pick / max_items to keep the result small. Refuses anything that is not a GET.", shared, (args) => handle(() => call(args, true)));
|
|
173
|
+
server.tool("api_call", "Run any operation from api_find by id (GET, POST, PUT, PATCH, DELETE). Writes default to dry_run:true and return exactly what would be sent — show the user, then repeat with dry_run:false. Refuses writes to routes a dedicated tool owns (it names the tool) and irreversible account operations. Required keys are checked against the call sheet before sending.", {
|
|
174
|
+
...shared,
|
|
175
|
+
body: z.any().optional().describe("JSON body for POST/PUT/PATCH/DELETE (keys from the call sheet)"),
|
|
176
|
+
dry_run: z.boolean().optional().describe("Default true for writes: describe, don't send"),
|
|
177
|
+
}, (args) => handle(() => call(args, false)));
|
|
178
|
+
}
|