-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcx.js
More file actions
321 lines (284 loc) · 7.41 KB
/
cx.js
File metadata and controls
321 lines (284 loc) · 7.41 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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
#!/usr/bin/env node
import fs from 'fs';
import axios from 'axios';
import * as cheerio from 'cheerio';
import AdmZip from 'adm-zip';
import {fileURLToPath} from 'url';
import path from 'path';
import minimist from 'minimist';
import {checkbox, input} from '@inquirer/prompts';
import yaml from 'yaml';
import chalk from 'chalk';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// --- CLI args (robustos) ---
const args = minimist(process.argv.slice(2), {
boolean: ['all', 'no-zip', 'noZip', 'debug'],
alias: {
m: 'mode',
n: 'name',
all: 'a',
// permitir ambas variantes:
noZip: 'no-zip',
},
default: {
'all': false,
'no-zip': false,
'noZip': false,
'debug': false,
},
});
const url = args._[0];
const mode = args.mode;
const sharedName = args.name;
const includeAll = !!args.all;
const noZip = !!(args['no-zip'] || args.noZip); // <- acepta ambas
if (args.debug) {
console.log(chalk.cyan('[DEBUG] raw argv:'), process.argv.slice(2));
console.log(chalk.cyan('[DEBUG] parsed args:'), args);
}
if (!url) {
console.error(
`${chalk.red(
'❌'
)} Usage: node cx.js https://example.com [--mode=css|js] [--all] [--name "Name"] [--no-zip] [--debug]`
);
process.exit(1);
}
// --- Paths ---
const OUTPUT_DIR = path.join(__dirname, 'output');
const TEMP_DIR = path.join(OUTPUT_DIR, 'temp');
const ASSETS_DIR = path.join(TEMP_DIR, 'assets');
// --- Config por modo ---
const MODES = {
css: {
fileName: 'global.css',
yamlType: 'globalCSS',
},
js: {
fileName: 'global.js',
yamlType: 'globalJS',
scriptElementAttributes: {
'async': true,
'data-attribute': 'value',
'data-senna-track': 'permanent',
'fetchpriority': 'low',
},
},
};
// --- Helpers ---
function slugify(name, suffix) {
return (
name
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^a-z0-9\-]/g, '') + `-${suffix}`
);
}
async function fetchPage(targetUrl) {
try {
const res = await axios.get(targetUrl);
return res.data;
} catch (e) {
throw new Error(`Failed to fetch page: ${e.message}`);
}
}
function parseResources(html, baseUrl, currentMode) {
const $ = cheerio.load(html);
const found = [];
let inlineCounter = 1;
if (currentMode === 'css') {
$('link[rel="stylesheet"], style').each((_, el) => {
if (el.tagName === 'link') {
const href = $(el).attr('href');
if (href) {
const full = new URL(href, baseUrl).href;
found.push({type: 'external', label: full, url: full});
}
} else {
found.push({
type: 'inline',
label: `<style> inline #${inlineCounter++}`,
content: $(el).html(),
});
}
});
} else {
$('script').each((_, el) => {
const src = $(el).attr('src');
if (src) {
const full = new URL(src, baseUrl).href;
found.push({type: 'external', label: full, url: full});
} else {
const content = $(el).html();
if (content?.trim()) {
found.push({
type: 'inline',
label: `<script> inline #${inlineCounter++}`,
content,
});
}
}
});
}
return found;
}
async function promptSelection(resources, currentMode, includeAllFlag) {
if (includeAllFlag) {
console.log(
`${chalk.green(
'✅'
)} --all flag: all ${currentMode.toUpperCase()} resources included.\n`
);
return resources;
}
const choices = await checkbox({
message: `Select which ${currentMode.toUpperCase()} resources to include:`,
choices: resources.map((item, i) => ({
name: item.label,
value: i.toString(),
checked: true,
})),
});
if (choices.length === 0) {
console.log(
`${chalk.yellow(
'⚠️'
)} No ${currentMode.toUpperCase()} selected. Skipping.`
);
return [];
}
return choices.map((i) => resources[parseInt(i, 10)]);
}
async function downloadResources(resources) {
const results = await Promise.all(
resources.map(async (res) => {
if (res.type === 'external') {
try {
const r = await axios.get(res.url);
console.log(
`${chalk.green('✅')} Loaded external: ${res.url}`
);
return `/* ${res.url} */\n${r.data}`;
} catch (e) {
console.warn(
`${chalk.yellow('⚠️')} Failed to load ${res.url}: ${
e.message
}`
);
return '';
}
} else {
console.log(`${chalk.green('✅')} Loaded ${res.label}`);
return `/* ${res.label} */\n${res.content}`;
}
})
);
return results.join('\n\n');
}
function generateYaml(technicalName, visibleName, currentMode, fileName) {
const base = {
assemble: [{from: 'assets', into: 'static'}],
[technicalName]: {
name: visibleName,
type: MODES[currentMode].yamlType,
url: fileName,
},
};
if (currentMode === 'js') {
base[technicalName].scriptElementAttributes =
MODES.js.scriptElementAttributes;
}
return yaml.stringify(base);
}
function saveFiles(fileName, content, yamlContent, technicalName, noZipFlag) {
fs.mkdirSync(ASSETS_DIR, {recursive: true});
const filePath = path.join(ASSETS_DIR, fileName);
const yamlPath = path.join(TEMP_DIR, 'client-extension.yaml');
fs.writeFileSync(filePath, content, 'utf8');
fs.writeFileSync(yamlPath, yamlContent, 'utf8');
const zipPath = path.join(OUTPUT_DIR, `${technicalName}.zip`);
if (!noZipFlag) {
const zip = new AdmZip();
zip.addLocalFile(filePath, 'assets');
zip.addLocalFile(yamlPath);
zip.writeZip(zipPath);
console.log(`${chalk.green('🎉')} Final ZIP created at: ${zipPath}`);
// Limpiar temp SOLO si hemos zipeado
fs.rmSync(TEMP_DIR, {recursive: true, force: true});
} else {
console.log(
`${chalk.green('📂')} Files saved without ZIP in: ${TEMP_DIR}`
);
console.log(
`${chalk.yellow(
'ℹ️'
)} Note: running both modes without --mode will overwrite temp/ on the second run.`
);
}
}
// --- Main extraction ---
async function runOnce(targetUrl, currentMode, sharedVisibleName) {
console.log(
`${chalk.blue(
'🌐'
)} Fetching ${targetUrl} for ${currentMode.toUpperCase()}...`
);
const html = await fetchPage(targetUrl);
const found = parseResources(html, targetUrl, currentMode);
if (found.length === 0) {
console.log(
`${chalk.red(
'❌'
)} No ${currentMode.toUpperCase()} resources found.`
);
return;
}
const selected = await promptSelection(found, currentMode, includeAll);
if (selected.length === 0) return;
let visibleName = sharedVisibleName;
if (!visibleName) {
visibleName = await input({
message: `Visible name of the Client Extension (${currentMode.toUpperCase()}):`,
default:
currentMode === 'css'
? 'Liferay CSS Client Extension'
: 'Liferay JS Client Extension',
validate: (val) => {
if (!/^[a-zA-Z0-9\s\-]+$/.test(val)) {
return 'Only letters, numbers, spaces and dashes are allowed.';
}
return true;
},
});
}
const technicalName = slugify(visibleName, currentMode);
const fileName = MODES[currentMode].fileName;
console.log(
`${chalk.blue('📄')} Selected ${currentMode.toUpperCase()} blocks: ${
selected.length
}`
);
const combined = await downloadResources(selected);
const yamlContent = generateYaml(
technicalName,
visibleName,
currentMode,
fileName
);
saveFiles(fileName, combined, yamlContent, technicalName, noZip);
}
// --- CLI entry point ---
(async () => {
if (!mode) {
await runOnce(url, 'css', sharedName);
await runOnce(url, 'js', sharedName);
} else if (mode === 'css' || mode === 'js') {
await runOnce(url, mode, sharedName);
} else {
console.error(
`${chalk.red('❌')} Invalid mode. Use --mode=css or --mode=js`
);
process.exit(1);
}
})();