-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmerge_css.js
More file actions
267 lines (225 loc) · 8.14 KB
/
Copy pathmerge_css.js
File metadata and controls
267 lines (225 loc) · 8.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
const fs = require("fs");
const path = require("path");
const css = require("css");
let selectorCounter = 1;
// Utility to generate stable selector IDs
function generateSelectorId() {
return `sel-${String(selectorCounter++).padStart(3, "0")}`;
}
// Add ID comments in --view mode
function addSelectorAnchors(ast) {
ast.stylesheet.rules.forEach((rule) => {
if (rule.type === "rule") {
const id = generateSelectorId();
rule.selectors = rule.selectors.map((sel) => `${sel} /* ID:${id} */`);
} else if (rule.rules) {
addSelectorAnchors({ stylesheet: { rules: rule.rules } });
}
});
}
// Strip ID comments before saving
function stripSelectorAnchors(ast) {
ast.stylesheet.rules.forEach((rule) => {
if (rule.type === "rule") {
rule.selectors = rule.selectors.map((sel) =>
sel.replace(/\s*\/\*\s*ID:[^)]+\*\//, "").trim()
);
} else if (rule.rules) {
stripSelectorAnchors({ stylesheet: { rules: rule.rules } });
}
});
}
function mergeCSS(originalContent, aiContent) {
const originalAST = css.parse(originalContent || "", { source: "original" });
const aiAST = css.parse(aiContent || "", { source: "ai" });
// Consolidate the original CSS to handle pre-existing duplicates.
originalAST.stylesheet.rules = consolidateRules(originalAST.stylesheet.rules);
// Merge the AI edits.
originalAST.stylesheet.rules = mergeRules(
originalAST.stylesheet.rules,
aiAST.stylesheet.rules
);
// Strip ID anchors before writing back
stripSelectorAnchors(originalAST);
return css.stringify(originalAST, { compress: false });
}
async function mergeAllFiles(files, aiEdits, projectRoot) {
files.forEach((file) => {
if (file.path.endsWith(".css") && aiEdits[file.path]) {
try {
const absolutePath = path.resolve(projectRoot, file.path);
const originalContent = fs.existsSync(absolutePath)
? fs.readFileSync(absolutePath, "utf-8")
: "";
const merged = mergeCSS(originalContent, aiEdits[file.path]);
fs.writeFileSync(absolutePath, merged, "utf-8");
console.log(`[LOG] Merged AI edits into ${file.path} -> ${absolutePath}`);
} catch (err) {
console.error(`[ERROR] Failed to merge ${file.path}:`, err.message);
process.exit(1);
}
}
});
}
function mergeDeclarations(origDecls, aiDecls) {
let merged = [...origDecls];
let deleteRule = false;
aiDecls.forEach((aiDecl) => {
if (aiDecl.type !== "declaration") return;
// Delete entire rule
if (aiDecl.property === "DELETE_THIS" && aiDecl.value === "DELETE_THIS") {
deleteRule = true;
return;
}
// Delete specific property
if (aiDecl.value === "DELETE_THIS") {
const exists = merged.some((d) => d.property === aiDecl.property);
if (!exists) {
throw new Error(
`Tried to delete property "${aiDecl.property}" but it does not exist in this selector.`
);
}
merged = merged.filter((d) => d.property !== aiDecl.property);
return;
}
// Add or override property
const idx = merged.findIndex((d) => d.property === aiDecl.property);
if (idx >= 0) {
merged[idx].value = aiDecl.value;
} else {
merged.push(aiDecl);
}
});
if (deleteRule) return null;
// Deduplicate properties while keeping last occurrence
const seen = new Map();
merged.forEach((decl) => {
if (decl.type !== "declaration") return;
seen.set(decl.property, decl);
});
return Array.from(seen.values());
}
// Merge rules recursively (handles @media/@supports)
function mergeRules(origRules, aiRules) {
const merged = [...origRules];
aiRules.forEach((aiRule) => {
if (aiRule.type === "rule") {
aiRule.selectors.forEach((rawSelector) => {
let selector = rawSelector.trim();
let isNewSelector = false;
// Explicit new selector prefix
if (selector.startsWith("NEW_SELECTOR:")) {
isNewSelector = true;
selector = selector.replace(/^NEW_SELECTOR:\s*/, "");
}
// Match including ID anchors
const existingMatches = merged.filter(
(r) =>
r.type === "rule" &&
r.selectors.some((sel) => sel.replace(/\s*\/\*\s*ID:[^)]+\*\//, "").trim() === selector)
);
if (existingMatches.length > 1) {
throw new Error(
`Ambiguity: Selector "${selector}" found multiple times. Use the ID comment from --view output to disambiguate.`
);
}
const existing = existingMatches[0];
if (existing) {
const newDecls = mergeDeclarations(existing.declarations, aiRule.declarations);
if (newDecls === null) {
// Drop this rule completely
const idx = merged.indexOf(existing);
if (idx >= 0) merged.splice(idx, 1);
} else {
existing.declarations = newDecls;
}
} else {
if (!isNewSelector) {
throw new Error(
`Selector "${selector}" not found in file. To add new selectors, use the "NEW_SELECTOR:" prefix.`
);
}
// Valid explicit new selector
const newDecls = mergeDeclarations([], aiRule.declarations);
if (newDecls !== null) {
merged.push({ ...aiRule, selectors: [selector], declarations: newDecls });
}
}
});
} else if (aiRule.type === "media" || aiRule.type === "supports") {
const key = aiRule.type === "media" ? aiRule.media : aiRule.condition;
const existingBlock = merged.find(
(r) =>
r.type === aiRule.type &&
(r.media === key || r.condition === key)
);
if (existingBlock) {
existingBlock.rules = mergeRules(existingBlock.rules, aiRule.rules);
} else {
const newBlock = { ...aiRule, rules: mergeRules([], aiRule.rules) };
merged.push(newBlock);
}
}
});
return merged;
}
function consolidateRules(rules) {
const selectorMap = new Map();
rules.forEach((rule, index) => {
if (rule.type === "rule") {
rule.selectors.forEach((selector) => {
if (selectorMap.has(selector)) {
throw new Error(
`Ambiguity: Selector "${selector}" found multiple times in original file. ` +
`Use --view mode IDs to disambiguate.`
);
}
selectorMap.set(selector, { rule, index });
});
} else if (rule.rules) {
rule.rules = consolidateRules(rule.rules);
}
});
return rules;
}
// --- CLI entrypoint ---
if (require.main === module) {
const PROJECT_ROOT = process.env.PROJECT_ROOT || process.cwd();
console.log("[LOG] Command line arguments:", process.argv);
console.log("[LOG] PROJECT_ROOT environment variable:", process.env.PROJECT_ROOT || "Not set");
// Handle --view mode
if (process.argv[2] === "--view") {
const filePath = process.argv[3];
if (!filePath) {
console.error("Usage: node merge_css.js --view <file>");
process.exit(1);
}
const abs = path.resolve(PROJECT_ROOT, filePath);
if (!fs.existsSync(abs)) {
console.error(`File not found: ${abs}`);
process.exit(1);
}
const original = fs.readFileSync(abs, "utf-8");
const ast = css.parse(original || "", { source: "view" });
addSelectorAnchors(ast);
const formatted = css.stringify(ast, { compress: false });
console.log(formatted);
process.exit(0);
}
// --- Normal merge mode ---
const [filesJsonPath, editsJsonPath] = process.argv.slice(2);
if (!filesJsonPath || !editsJsonPath) {
console.error("Usage: node merge_css.js <files.json> <ai_edits.json>");
process.exit(1);
}
const filesJsonAbs = path.resolve(PROJECT_ROOT, filesJsonPath);
const editsJsonAbs = path.resolve(PROJECT_ROOT, editsJsonPath);
const files = JSON.parse(fs.readFileSync(filesJsonAbs, "utf-8"));
const aiEdits = JSON.parse(fs.readFileSync(editsJsonAbs, "utf-8"));
files.forEach((file) => {
const absolutePath = path.resolve(PROJECT_ROOT, file.path);
console.log(`[LOG] File to merge: ${file.path} -> ${absolutePath}`);
});
mergeAllFiles(files, aiEdits, PROJECT_ROOT);
}
module.exports = { mergeCSS, mergeAllFiles, addSelectorAnchors, stripSelectorAnchors };