@mandujs/core 0.51.0 → 0.53.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.
@@ -0,0 +1,242 @@
1
+ /**
2
+ * Section-safe DESIGN.md patcher (Issue #245 M4 §3.5).
3
+ *
4
+ * The patcher rewrites only the *body* of a target H2 section, leaving:
5
+ * - the H1 title and other H2 sections untouched (verbatim)
6
+ * - the target heading line itself untouched
7
+ * - any free-form prose between the heading and the first structured
8
+ * row preserved
9
+ *
10
+ * Operations are scoped to one `(section, key)` pair at a time so an
11
+ * agent can stream multiple patches without re-loading the file. The
12
+ * `dryRun` flag returns the would-be next source without writing it,
13
+ * so MCP tools can show the user a diff before committing.
14
+ *
15
+ * Token row rules per section:
16
+ * - color-palette / shadows / layout / typography: bullet rows of
17
+ * the form `- <Name> — <value>` (extra columns preserved verbatim
18
+ * for `update`).
19
+ * - components: H3 sub-headings with optional bullet body.
20
+ *
21
+ * Unsupported sections return `{ applied: false, reason: ... }` —
22
+ * they're free-form by design. Callers decide whether to surface the
23
+ * limitation or fall back to a hand-edit.
24
+ */
25
+
26
+ import { parseDesignMd } from "./parser";
27
+
28
+ export type PatchableSection =
29
+ | "color-palette"
30
+ | "typography"
31
+ | "layout"
32
+ | "shadows"
33
+ | "components";
34
+
35
+ export interface PatchOperation {
36
+ section: PatchableSection;
37
+ /** "add" creates the row; "update" replaces an existing matching row;
38
+ * "remove" deletes a matching row. */
39
+ operation: "add" | "update" | "remove";
40
+ /** Token name. Match is case-insensitive on the slug. */
41
+ key: string;
42
+ /** Required for `add` / `update`. Free-form value (`#FF8C42`,
43
+ * `Inter, sans-serif`, `0 1px 3px rgba(...)`). */
44
+ value?: string;
45
+ /** Optional functional role / usage hint (color/shadow). */
46
+ role?: string;
47
+ }
48
+
49
+ export interface PatchResult {
50
+ applied: boolean;
51
+ /** Reason the operation was a no-op or rejected. */
52
+ reason?: string;
53
+ /** Source after applying — same as input when not applied. */
54
+ next: string;
55
+ /** Old row (for `update` / `remove`). Undefined for clean adds. */
56
+ before?: string;
57
+ /** New row (for `add` / `update`). Undefined for `remove`. */
58
+ after?: string;
59
+ }
60
+
61
+ const HEADING_BY_SECTION: Record<PatchableSection, RegExp> = {
62
+ "color-palette": /^##\s+.*?(color|palette).*$/im,
63
+ typography: /^##\s+.*?(typograph|typeface|font|type scale).*$/im,
64
+ layout: /^##\s+.*?(layout|spacing|grid).*$/im,
65
+ shadows: /^##\s+.*?(shadow|elevation|depth).*$/im,
66
+ components: /^##\s+.*?(component|button|card|input).*$/im,
67
+ };
68
+
69
+ /**
70
+ * Apply a single patch. Pure — does not touch the filesystem.
71
+ *
72
+ * The result's `applied` flag tells the caller whether the source
73
+ * actually changed (e.g. `remove` of a non-existent key returns
74
+ * `applied: false` with `reason`).
75
+ */
76
+ export function patchDesignMd(source: string, op: PatchOperation): PatchResult {
77
+ const headingRx = HEADING_BY_SECTION[op.section];
78
+ const headingMatch = headingRx.exec(source);
79
+ if (!headingMatch) {
80
+ return {
81
+ applied: false,
82
+ reason: `Section "${op.section}" not found in DESIGN.md`,
83
+ next: source,
84
+ };
85
+ }
86
+
87
+ const sectionStart = headingMatch.index + headingMatch[0].length;
88
+ const nextHeadingIdx = source.indexOf("\n## ", sectionStart);
89
+ const sectionEnd = nextHeadingIdx >= 0 ? nextHeadingIdx : source.length;
90
+ const sectionBody = source.slice(sectionStart, sectionEnd);
91
+
92
+ const updated = applyToBody(sectionBody, op);
93
+ if (!updated.applied) {
94
+ return { ...updated, next: source };
95
+ }
96
+
97
+ const next = source.slice(0, sectionStart) + updated.body + source.slice(sectionEnd);
98
+ return {
99
+ applied: true,
100
+ next,
101
+ before: updated.before,
102
+ after: updated.after,
103
+ };
104
+ }
105
+
106
+ interface BodyApplyResult {
107
+ applied: boolean;
108
+ reason?: string;
109
+ body: string;
110
+ before?: string;
111
+ after?: string;
112
+ }
113
+
114
+ function applyToBody(body: string, op: PatchOperation): BodyApplyResult {
115
+ const lines = body.split(/\r?\n/);
116
+ const targetSlug = slug(op.key);
117
+
118
+ const matchIdx = lines.findIndex((line) => {
119
+ const row = parseTokenRow(line, op.section);
120
+ return row !== null && slug(row.name) === targetSlug;
121
+ });
122
+
123
+ if (op.operation === "remove") {
124
+ if (matchIdx < 0) {
125
+ return { applied: false, reason: `No row with name "${op.key}"`, body };
126
+ }
127
+ const before = lines[matchIdx]!;
128
+ lines.splice(matchIdx, 1);
129
+ return { applied: true, body: lines.join("\n"), before };
130
+ }
131
+
132
+ if (op.operation === "update") {
133
+ if (matchIdx < 0) {
134
+ return { applied: false, reason: `No row with name "${op.key}"`, body };
135
+ }
136
+ if (op.value === undefined) {
137
+ return { applied: false, reason: "`value` is required for update", body };
138
+ }
139
+ const before = lines[matchIdx]!;
140
+ const after = renderRow(op);
141
+ lines[matchIdx] = after;
142
+ return { applied: true, body: lines.join("\n"), before, after };
143
+ }
144
+
145
+ // add — value is required for token rows, optional for component H3
146
+ if (op.section !== "components" && op.value === undefined) {
147
+ return { applied: false, reason: "`value` is required for add", body };
148
+ }
149
+ if (matchIdx >= 0) {
150
+ return {
151
+ applied: false,
152
+ reason: `Row "${op.key}" already exists — use update or remove first`,
153
+ body,
154
+ };
155
+ }
156
+
157
+ const after = renderRow(op);
158
+ // Find the last existing token row to anchor the insertion. When
159
+ // none exist, insert at the bottom of the section before any
160
+ // trailing whitespace.
161
+ let insertAt = lines.length;
162
+ for (let i = lines.length - 1; i >= 0; i--) {
163
+ if (parseTokenRow(lines[i]!, op.section) !== null) {
164
+ insertAt = i + 1;
165
+ break;
166
+ }
167
+ }
168
+ lines.splice(insertAt, 0, after);
169
+ // Ensure the section body keeps its trailing blank line before the
170
+ // next H2 (or EOF) so subsequent patches don't crowd headers.
171
+ let next = lines.join("\n");
172
+ if (!next.endsWith("\n")) next = `${next}\n`;
173
+ return { applied: true, body: next, after };
174
+ }
175
+
176
+ interface ParsedTokenRow {
177
+ name: string;
178
+ rest: string;
179
+ }
180
+
181
+ function parseTokenRow(line: string, section: PatchableSection): ParsedTokenRow | null {
182
+ if (section === "components") {
183
+ const h3 = /^###\s+(.+?)\s*$/.exec(line);
184
+ if (h3) return { name: h3[1]!, rest: "" };
185
+ return null;
186
+ }
187
+ const stripped = line.trim().replace(/^[-*+]\s*/, "");
188
+ if (!stripped || /^[#|]/.test(stripped)) return null;
189
+ const m = /^([^—:|]+?)\s*[—:–|]\s*(.+)$/.exec(stripped);
190
+ if (!m) return null;
191
+ return { name: m[1]!.replace(/[`*_]/g, "").trim(), rest: m[2]!.trim() };
192
+ }
193
+
194
+ function renderRow(op: PatchOperation): string {
195
+ if (op.section === "components") {
196
+ return `### ${op.key}`;
197
+ }
198
+ const value = op.value ?? "";
199
+ const role = op.role ? ` — ${op.role}` : "";
200
+ return `- ${op.key} — ${value}${role}`;
201
+ }
202
+
203
+ function slug(name: string): string {
204
+ return name
205
+ .normalize("NFKD")
206
+ .replace(/[^\w\s-]/g, "")
207
+ .trim()
208
+ .replace(/\s+/g, "-")
209
+ .toLowerCase();
210
+ }
211
+
212
+ // ─── Multi-op sugar ───────────────────────────────────────────────────
213
+
214
+ export interface PatchBatchResult {
215
+ next: string;
216
+ results: PatchResult[];
217
+ appliedCount: number;
218
+ }
219
+
220
+ /**
221
+ * Apply a list of operations in order. Each operation runs against
222
+ * the cumulative source — later ops see earlier ones. Failures are
223
+ * surfaced per-entry but never abort the batch (so a partial success
224
+ * is observable).
225
+ */
226
+ export function patchDesignMdBatch(
227
+ source: string,
228
+ ops: readonly PatchOperation[],
229
+ ): PatchBatchResult {
230
+ let current = source;
231
+ const results: PatchResult[] = [];
232
+ let appliedCount = 0;
233
+ for (const op of ops) {
234
+ const r = patchDesignMd(current, op);
235
+ results.push(r);
236
+ if (r.applied) {
237
+ appliedCount++;
238
+ current = r.next;
239
+ }
240
+ }
241
+ return { next: current, results, appliedCount };
242
+ }