dotcms-custom-mcp 0.0.0-stage → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +199 -2
- package/dotcms.js +258 -0
- package/hooks/confirm-write.mjs +41 -0
- package/index.js +601 -0
- package/package.json +39 -4
- package/plans.js +111 -0
- package/relations.js +171 -0
package/plans.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// Change plans: the "plan first" half of the plan -> human check -> write flow.
|
|
2
|
+
//
|
|
3
|
+
// plan_vtl_change stores a plan here; apply_vtl_change can only write what a stored
|
|
4
|
+
// plan contains, and the confirmation hook shows that same plan to the user.
|
|
5
|
+
|
|
6
|
+
import crypto from "node:crypto";
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
import os from "node:os";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
|
|
11
|
+
// Kept outside the package folder: under npx the package lives in the npm cache, and the
|
|
12
|
+
// server and the confirmation hook must agree on one location however each was started.
|
|
13
|
+
const DIR = process.env.DOTCMS_PLANS_DIR || path.join(os.homedir(), ".dotcms-mcp", "plans");
|
|
14
|
+
export const PLAN_TTL_MS = 30 * 60 * 1000;
|
|
15
|
+
const MAX_SHOWN_LINES = 40;
|
|
16
|
+
|
|
17
|
+
const splitLines = (s) => (s === "" ? [] : s.replace(/\r\n/g, "\n").split("\n"));
|
|
18
|
+
|
|
19
|
+
/** Line diff via longest common subsequence; returns only "+ n: text" / "- n: text" lines. */
|
|
20
|
+
export function diffLines(oldText, newText) {
|
|
21
|
+
const a = splitLines(oldText);
|
|
22
|
+
const b = splitLines(newText);
|
|
23
|
+
const lcs = Array.from({ length: a.length + 1 }, () => new Uint32Array(b.length + 1));
|
|
24
|
+
for (let i = a.length - 1; i >= 0; i--) {
|
|
25
|
+
for (let j = b.length - 1; j >= 0; j--) {
|
|
26
|
+
lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const out = [];
|
|
30
|
+
let i = 0;
|
|
31
|
+
let j = 0;
|
|
32
|
+
while (i < a.length || j < b.length) {
|
|
33
|
+
if (i < a.length && j < b.length && a[i] === b[j]) {
|
|
34
|
+
i++;
|
|
35
|
+
j++;
|
|
36
|
+
} else if (j < b.length && (i === a.length || lcs[i][j + 1] >= lcs[i + 1][j])) {
|
|
37
|
+
out.push(`+ ${j + 1}: ${b[j++]}`);
|
|
38
|
+
} else {
|
|
39
|
+
out.push(`- ${i + 1}: ${a[i++]}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const planFile = (id) => path.join(DIR, `${id}.json`);
|
|
46
|
+
|
|
47
|
+
function prune() {
|
|
48
|
+
if (!fs.existsSync(DIR)) return;
|
|
49
|
+
for (const name of fs.readdirSync(DIR)) {
|
|
50
|
+
const file = path.join(DIR, name);
|
|
51
|
+
try {
|
|
52
|
+
if (JSON.parse(fs.readFileSync(file, "utf8")).expiresAt < Date.now()) fs.rmSync(file);
|
|
53
|
+
} catch {
|
|
54
|
+
fs.rmSync(file, { force: true });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function savePlan(plan) {
|
|
60
|
+
fs.mkdirSync(DIR, { recursive: true, mode: 0o700 });
|
|
61
|
+
prune();
|
|
62
|
+
const id = crypto.randomBytes(6).toString("hex");
|
|
63
|
+
const stored = { ...plan, id, createdAt: Date.now(), expiresAt: Date.now() + PLAN_TTL_MS };
|
|
64
|
+
fs.writeFileSync(planFile(id), JSON.stringify(stored, null, 2), { mode: 0o600 });
|
|
65
|
+
return stored;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function loadPlan(id) {
|
|
69
|
+
if (!/^[a-f0-9]{12}$/.test(String(id ?? ""))) {
|
|
70
|
+
throw new Error("Missing or malformed planId. Create a plan with plan_vtl_change first.");
|
|
71
|
+
}
|
|
72
|
+
if (!fs.existsSync(planFile(id))) {
|
|
73
|
+
throw new Error(`Plan ${id} does not exist (already applied, expired, or never created). Create a new plan with plan_vtl_change.`);
|
|
74
|
+
}
|
|
75
|
+
const plan = JSON.parse(fs.readFileSync(planFile(id), "utf8"));
|
|
76
|
+
if (plan.expiresAt < Date.now()) {
|
|
77
|
+
fs.rmSync(planFile(id), { force: true });
|
|
78
|
+
throw new Error(`Plan ${id} has expired (plans are valid for ${PLAN_TTL_MS / 60000} minutes). Create a new plan with plan_vtl_change.`);
|
|
79
|
+
}
|
|
80
|
+
return plan;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export const deletePlan = (id) => fs.rmSync(planFile(id), { force: true });
|
|
84
|
+
|
|
85
|
+
const KIND_LABEL = { api: "API VTL file", "custom-field": "custom field VTL file", vtl: "VTL file" };
|
|
86
|
+
|
|
87
|
+
/** The human-readable plan: shown by plan_vtl_change and again by the confirmation hook. */
|
|
88
|
+
export function renderPlan(plan) {
|
|
89
|
+
const added = plan.changes.filter((l) => l.startsWith("+")).length;
|
|
90
|
+
const shown =
|
|
91
|
+
plan.changes.length > MAX_SHOWN_LINES
|
|
92
|
+
? [...plan.changes.slice(0, MAX_SHOWN_LINES), `… ${plan.changes.length - MAX_SHOWN_LINES} more changed lines`]
|
|
93
|
+
: plan.changes;
|
|
94
|
+
const minutesLeft = Math.max(0, Math.round((plan.expiresAt - Date.now()) / 60000));
|
|
95
|
+
|
|
96
|
+
return [
|
|
97
|
+
`PLAN ${plan.id}: ${plan.action} ${KIND_LABEL[plan.kind] || KIND_LABEL.vtl} in dotCMS`,
|
|
98
|
+
`Instance: ${plan.instance}`,
|
|
99
|
+
`Site: ${plan.site}`,
|
|
100
|
+
`Path: ${plan.path}`,
|
|
101
|
+
`Language: ${plan.languageId ?? "default"}`,
|
|
102
|
+
`Publish: ${plan.publish ? "YES — goes live immediately" : "no — working version only"}`,
|
|
103
|
+
`Size: ${splitLines(plan.content).length} lines, ${Buffer.byteLength(plan.content)} bytes`,
|
|
104
|
+
`Valid: ${minutesLeft} more minutes, one use`,
|
|
105
|
+
...(plan.warnings.length ? ["", ...plan.warnings.map((w) => `WARNING: ${w}`)] : []),
|
|
106
|
+
...(plan.hints.length ? ["", ...plan.hints] : []),
|
|
107
|
+
"",
|
|
108
|
+
plan.action === "CREATE" ? "New file:" : `Changes: +${added} / -${plan.changes.length - added} lines`,
|
|
109
|
+
...shown,
|
|
110
|
+
].join("\n");
|
|
111
|
+
}
|
package/relations.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
// Relationship tree of a content type: which content types it is connected to, through
|
|
2
|
+
// which fields, and how those types are connected in turn.
|
|
3
|
+
//
|
|
4
|
+
// dotCMS describes a relationship on the field itself:
|
|
5
|
+
// relationships: { cardinality: 0-3, isParentField: boolean, velocityVar: "Type" | "Type.field" }
|
|
6
|
+
// where velocityVar names the related content type and, when the other side has a field
|
|
7
|
+
// for the same relationship, that field.
|
|
8
|
+
|
|
9
|
+
const CARDINALITY = ["ONE_TO_MANY", "MANY_TO_MANY", "ONE_TO_ONE", "MANY_TO_ONE"];
|
|
10
|
+
// [parent side, child side] multiplicity for each cardinality.
|
|
11
|
+
const SIDES = { ONE_TO_MANY: ["one", "many"], MANY_TO_MANY: ["many", "many"], ONE_TO_ONE: ["one", "one"], MANY_TO_ONE: ["many", "one"] };
|
|
12
|
+
|
|
13
|
+
export const MAX_NODES = 150;
|
|
14
|
+
|
|
15
|
+
const isRelationship = (f) => /RelationshipField$/.test(f.clazz || "") && f.relationships?.velocityVar;
|
|
16
|
+
const isCategory = (f) => /CategoryField$/.test(f.clazz || "");
|
|
17
|
+
const key = (variable) => String(variable).toLowerCase();
|
|
18
|
+
|
|
19
|
+
/** The relationship fields of one content type, in a uniform shape. */
|
|
20
|
+
export function relationFields(ct) {
|
|
21
|
+
return (ct.fields || []).filter(isRelationship).map((f) => {
|
|
22
|
+
const [to, otherField] = String(f.relationships.velocityVar).split(".");
|
|
23
|
+
const cardinality = CARDINALITY[f.relationships.cardinality] || `UNKNOWN(${f.relationships.cardinality})`;
|
|
24
|
+
const parent = !!f.relationships.isParentField;
|
|
25
|
+
const sides = SIDES[cardinality];
|
|
26
|
+
const out = {
|
|
27
|
+
field: f.variable,
|
|
28
|
+
fieldName: f.name,
|
|
29
|
+
from: ct.variable,
|
|
30
|
+
to,
|
|
31
|
+
cardinality,
|
|
32
|
+
side: parent ? "parent" : "child",
|
|
33
|
+
required: !!f.required,
|
|
34
|
+
};
|
|
35
|
+
if (otherField) out.otherSideField = otherField;
|
|
36
|
+
if (sides) {
|
|
37
|
+
const [mine, theirs] = parent ? sides : [sides[1], sides[0]];
|
|
38
|
+
out.meaning = `${mine} ${ct.variable} — ${theirs} ${to}`;
|
|
39
|
+
}
|
|
40
|
+
return out;
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Build the tree.
|
|
46
|
+
* getType(variable) -> content type entity (with fields); may throw
|
|
47
|
+
* getAllTypes() -> every content type entity (with fields), for incoming relationships
|
|
48
|
+
*/
|
|
49
|
+
export async function buildRelationTree({ root, depth, includeIncoming, includeFields, getType, getAllTypes, describeField }) {
|
|
50
|
+
const warnings = [];
|
|
51
|
+
const cache = new Map();
|
|
52
|
+
const load = (variable) => {
|
|
53
|
+
if (!cache.has(key(variable))) cache.set(key(variable), getType(variable));
|
|
54
|
+
return cache.get(key(variable));
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
// Relationships declared only on the other type ("who points at me?").
|
|
58
|
+
let incomingByTarget = null;
|
|
59
|
+
if (includeIncoming) {
|
|
60
|
+
try {
|
|
61
|
+
incomingByTarget = new Map();
|
|
62
|
+
for (const ct of await getAllTypes()) {
|
|
63
|
+
cache.set(key(ct.variable), Promise.resolve(ct));
|
|
64
|
+
for (const rel of relationFields(ct)) {
|
|
65
|
+
if (!incomingByTarget.has(key(rel.to))) incomingByTarget.set(key(rel.to), []);
|
|
66
|
+
incomingByTarget.get(key(rel.to)).push(rel);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
} catch (err) {
|
|
70
|
+
incomingByTarget = null;
|
|
71
|
+
warnings.push(`Incoming relationships were skipped: could not list all content types (${err.message})`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
let nodes = 0;
|
|
76
|
+
let truncated = false;
|
|
77
|
+
const involved = new Set();
|
|
78
|
+
|
|
79
|
+
async function expand(variable, level, path) {
|
|
80
|
+
if (path.includes(key(variable))) return { variable, cycle: true };
|
|
81
|
+
let ct;
|
|
82
|
+
try {
|
|
83
|
+
ct = await load(variable);
|
|
84
|
+
} catch (err) {
|
|
85
|
+
return { variable, error: err.message };
|
|
86
|
+
}
|
|
87
|
+
if (++nodes > MAX_NODES) {
|
|
88
|
+
truncated = true;
|
|
89
|
+
return { variable: ct.variable, truncated: true };
|
|
90
|
+
}
|
|
91
|
+
involved.add(ct.variable);
|
|
92
|
+
|
|
93
|
+
const node = { variable: ct.variable, name: ct.name, baseType: ct.baseType };
|
|
94
|
+
if (ct.nEntries !== undefined) node.entries = ct.nEntries;
|
|
95
|
+
|
|
96
|
+
const categories = (ct.fields || []).filter(isCategory).map((f) => ({
|
|
97
|
+
field: f.variable,
|
|
98
|
+
fieldName: f.name,
|
|
99
|
+
category: f.categories?.categoryName || f.categories?.name || undefined,
|
|
100
|
+
categoryId: f.categories?.inode || f.values || undefined,
|
|
101
|
+
}));
|
|
102
|
+
if (categories.length) node.categories = categories;
|
|
103
|
+
if (includeFields) {
|
|
104
|
+
node.fields = (ct.fields || []).filter((f) => !isRelationship(f)).map(describeField).filter(Boolean);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const outgoing = relationFields(ct);
|
|
108
|
+
// An incoming relationship is one this type has no field for.
|
|
109
|
+
const mine = new Set(outgoing.map((r) => (r.otherSideField ? `${key(r.to)}.${key(r.otherSideField)}` : null)).filter(Boolean));
|
|
110
|
+
const incoming = (incomingByTarget?.get(key(ct.variable)) || [])
|
|
111
|
+
.filter((r) => !mine.has(`${key(r.from)}.${key(r.field)}`))
|
|
112
|
+
.filter((r) => !(r.otherSideField && outgoing.some((o) => key(o.field) === key(r.otherSideField))))
|
|
113
|
+
.map((r) => ({
|
|
114
|
+
direction: "incoming",
|
|
115
|
+
field: `${r.from}.${r.field}`,
|
|
116
|
+
fieldName: r.fieldName,
|
|
117
|
+
to: r.from,
|
|
118
|
+
cardinality: r.cardinality,
|
|
119
|
+
side: r.side === "parent" ? "child" : "parent",
|
|
120
|
+
required: r.required,
|
|
121
|
+
meaning: r.meaning,
|
|
122
|
+
}));
|
|
123
|
+
|
|
124
|
+
const relations = [...outgoing.map(({ from, ...r }) => ({ direction: "outgoing", ...r })), ...incoming];
|
|
125
|
+
if (!relations.length) return node;
|
|
126
|
+
|
|
127
|
+
if (level >= depth) {
|
|
128
|
+
node.relations = relations;
|
|
129
|
+
node.notExpanded = true;
|
|
130
|
+
return node;
|
|
131
|
+
}
|
|
132
|
+
node.relations = [];
|
|
133
|
+
for (const rel of relations) {
|
|
134
|
+
node.relations.push({ ...rel, type: await expand(rel.to, level + 1, [...path, key(variable)]) });
|
|
135
|
+
}
|
|
136
|
+
return node;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const tree = await expand(root, 0, []);
|
|
140
|
+
if (tree.error) throw new Error(tree.error);
|
|
141
|
+
if (truncated) warnings.push(`The tree was cut at ${MAX_NODES} content type nodes. Lower 'depth' or start from a more specific type.`);
|
|
142
|
+
return { tree, warnings, contentTypes: [...involved].sort() };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Plain-text drawing of the tree, for reading at a glance. */
|
|
146
|
+
export function renderRelationTree(tree) {
|
|
147
|
+
const lines = [];
|
|
148
|
+
const label = (rel) => {
|
|
149
|
+
const arrow = rel.direction === "incoming" ? "◄─" : "─►";
|
|
150
|
+
const bits = [rel.cardinality, `${rel.side} side`];
|
|
151
|
+
if (rel.otherSideField) bits.push(`other field: ${rel.otherSideField}`);
|
|
152
|
+
if (rel.required) bits.push("required");
|
|
153
|
+
if (rel.direction === "incoming") bits.push("declared on the other type");
|
|
154
|
+
return `${rel.field} ${arrow} ${rel.to} [${bits.join(", ")}]`;
|
|
155
|
+
};
|
|
156
|
+
const walk = (node, prefix) => {
|
|
157
|
+
const rels = node.relations || [];
|
|
158
|
+
rels.forEach((rel, i) => {
|
|
159
|
+
const last = i === rels.length - 1;
|
|
160
|
+
const child = rel.type;
|
|
161
|
+
const note = child?.cycle ? " (already shown above)" : child?.error ? " (not found)" : child?.truncated ? " (cut)" : "";
|
|
162
|
+
const more = !child && node.notExpanded ? "" : note;
|
|
163
|
+
lines.push(`${prefix}${last ? "└─ " : "├─ "}${label(rel)}${more}`);
|
|
164
|
+
if (child && !child.cycle && !child.error && !child.truncated) walk(child, prefix + (last ? " " : "│ "));
|
|
165
|
+
});
|
|
166
|
+
if (node.notExpanded && rels.length) lines.push(`${prefix} … not expanded further (depth limit)`);
|
|
167
|
+
};
|
|
168
|
+
lines.push(`${tree.name || tree.variable} (${tree.variable})`);
|
|
169
|
+
walk(tree, "");
|
|
170
|
+
return lines.join("\n");
|
|
171
|
+
}
|