slicejs-cli 4.3.0 → 4.4.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/LICENSE +21 -21
- package/README.md +260 -257
- package/client.js +927 -823
- package/commands/Print.js +163 -163
- package/commands/Validations.js +92 -92
- package/commands/build/build.js +97 -107
- package/commands/buildProduction/buildProduction.js +613 -613
- package/commands/bundle/bundle.js +251 -239
- package/commands/createComponent/VisualComponentTemplate.js +55 -55
- package/commands/createComponent/createComponent.js +128 -128
- package/commands/deleteComponent/deleteComponent.js +81 -81
- package/commands/docs/docs.js +365 -365
- package/commands/doctor/doctor.js +677 -563
- package/commands/getComponent/getComponent.js +842 -842
- package/commands/init/init.js +526 -475
- package/commands/lint/lint.js +75 -0
- package/commands/lint/types.js +85 -0
- package/commands/listComponents/listComponents.js +172 -172
- package/commands/seo/check.js +91 -0
- package/commands/seo/images.js +586 -0
- package/commands/seo/sitemap.js +106 -0
- package/commands/seo/support.js +130 -0
- package/commands/setup/lint.js +151 -0
- package/commands/skill/skill.js +236 -236
- package/commands/startServer/startServer.js +240 -240
- package/commands/startServer/watchServer.js +66 -66
- package/commands/typecheck/typecheck.js +83 -0
- package/commands/types/types.js +1378 -1097
- package/commands/utils/JsMinifier.js +230 -230
- package/commands/utils/LocalCliDelegation.js +78 -53
- package/commands/utils/PackageManager.js +148 -148
- package/commands/utils/PathHelper.js +87 -75
- package/commands/utils/ProjectValidation.js +274 -0
- package/commands/utils/SourceDiagnostics.js +201 -201
- package/commands/utils/VersionChecker.js +169 -169
- package/commands/utils/analyzeSource.js +77 -77
- package/commands/utils/bundling/BundleGenerator.js +3748 -3776
- package/commands/utils/bundling/DependencyAnalyzer.js +976 -976
- package/commands/utils/bundling/ExternalModuleBundler.js +298 -298
- package/commands/utils/componentAudit.js +74 -0
- package/commands/utils/compressAssets.js +103 -103
- package/commands/utils/cssScope.js +83 -0
- package/commands/utils/loadConfig.js +31 -31
- package/commands/utils/semver.js +66 -0
- package/commands/utils/sliceConfigSchema.js +72 -0
- package/commands/utils/sliceScripts.js +48 -48
- package/commands/utils/updateManager.js +471 -471
- package/eslint-config.js +128 -0
- package/package.json +19 -13
|
@@ -1,842 +1,842 @@
|
|
|
1
|
-
// commands/getComponent/getComponent.js
|
|
2
|
-
|
|
3
|
-
import fs from "fs-extra";
|
|
4
|
-
import path from "path";
|
|
5
|
-
import inquirer from "inquirer";
|
|
6
|
-
import validations from "../Validations.js";
|
|
7
|
-
import Print from "../Print.js";
|
|
8
|
-
import { getComponentsJsPath, getPath } from "../utils/PathHelper.js";
|
|
9
|
-
import { loadConfig as sharedLoadConfig } from "../utils/loadConfig.js";
|
|
10
|
-
import { analyzeSource } from "../utils/analyzeSource.js";
|
|
11
|
-
import ora from "ora";
|
|
12
|
-
|
|
13
|
-
// Base URL of the Slice.js documentation repository
|
|
14
|
-
const DOCS_REPO_BASE_URL = 'https://raw.githubusercontent.com/VKneider/
|
|
15
|
-
const COMPONENTS_REGISTRY_URL = 'https://raw.githubusercontent.com/VKneider/
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* Loads configuration from sliceConfig.json
|
|
19
|
-
* @returns {object} - Configuration object
|
|
20
|
-
*/
|
|
21
|
-
const loadConfig = () => sharedLoadConfig(import.meta.url);
|
|
22
|
-
|
|
23
|
-
const fetchWithRetry = async (url, retries = 3, baseDelay = 500, binary = false) => {
|
|
24
|
-
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
25
|
-
try {
|
|
26
|
-
const response = await fetch(url);
|
|
27
|
-
if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
28
|
-
return binary ? await response.arrayBuffer() : await response.text();
|
|
29
|
-
} catch (e) {
|
|
30
|
-
if (attempt === retries) throw e;
|
|
31
|
-
const delay = baseDelay * Math.pow(2, attempt);
|
|
32
|
-
await new Promise(r => setTimeout(r, delay));
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
};
|
|
36
|
-
|
|
37
|
-
const runConcurrent = async (items, worker, concurrency = 3) => {
|
|
38
|
-
let index = 0;
|
|
39
|
-
const runners = Array(Math.min(concurrency, items.length)).fill(0).map(async () => {
|
|
40
|
-
while (true) {
|
|
41
|
-
const i = index++;
|
|
42
|
-
if (i >= items.length) break;
|
|
43
|
-
await worker(items[i]);
|
|
44
|
-
}
|
|
45
|
-
});
|
|
46
|
-
await Promise.all(runners);
|
|
47
|
-
};
|
|
48
|
-
|
|
49
|
-
class ComponentRegistry {
|
|
50
|
-
constructor() {
|
|
51
|
-
this.componentsRegistry = null;
|
|
52
|
-
this.config = null;
|
|
53
|
-
this._configPromise = null;
|
|
54
|
-
// Serializes read-modify-write cycles on components.js: installs run
|
|
55
|
-
// concurrently (runConcurrent), and parallel writers corrupt the file
|
|
56
|
-
// (partial reads) or silently drop registrations (lost updates).
|
|
57
|
-
this._registryLock = Promise.resolve();
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
async _ensureConfig() {
|
|
61
|
-
if (!this.config && !this._configPromise) {
|
|
62
|
-
this._configPromise = loadConfig();
|
|
63
|
-
}
|
|
64
|
-
if (this._configPromise) {
|
|
65
|
-
this.config = await this._configPromise;
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
async loadRegistry() {
|
|
70
|
-
await this._ensureConfig();
|
|
71
|
-
Print.info('Loading component registry from official repository...');
|
|
72
|
-
|
|
73
|
-
try {
|
|
74
|
-
const response = await fetch(COMPONENTS_REGISTRY_URL);
|
|
75
|
-
|
|
76
|
-
if (!response.ok) {
|
|
77
|
-
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
const content = await response.text();
|
|
81
|
-
|
|
82
|
-
// Parse the components.js file content
|
|
83
|
-
const match = content.match(/const components = ({[\s\S]*?});/);
|
|
84
|
-
if (!match) {
|
|
85
|
-
throw new Error('Invalid components.js format from repository');
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
const allComponents = JSON.parse(match[1]);
|
|
89
|
-
|
|
90
|
-
// Filter only Visual and Service components
|
|
91
|
-
this.componentsRegistry = this.filterOfficialComponents(allComponents);
|
|
92
|
-
|
|
93
|
-
Print.success('Component registry loaded successfully');
|
|
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
|
-
if (!await fs.pathExists(componentsPath)) {
|
|
131
|
-
return {};
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
const content = await fs.readFile(componentsPath, 'utf8');
|
|
135
|
-
const match = content.match(/const components = ({[\s\S]*?});/);
|
|
136
|
-
|
|
137
|
-
if (!match) {
|
|
138
|
-
return {};
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
return JSON.parse(match[1]);
|
|
142
|
-
} catch (error) {
|
|
143
|
-
Print.warning(`⚠️ Could not read the local component registry at: ${componentsPath}`);
|
|
144
|
-
return {};
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
async findUpdatableComponents() {
|
|
149
|
-
await this._ensureConfig();
|
|
150
|
-
const localComponents = await this.getLocalComponents();
|
|
151
|
-
const updatableComponents = [];
|
|
152
|
-
|
|
153
|
-
Object.entries(localComponents).forEach(([name, category]) => {
|
|
154
|
-
// Check if component exists in remote registry
|
|
155
|
-
if (this.componentsRegistry[name] && this.componentsRegistry[name] === category) {
|
|
156
|
-
// Check if local component directory exists using dynamic paths
|
|
157
|
-
const categoryPath = validations.getCategoryPath(category);
|
|
158
|
-
|
|
159
|
-
// Use 4 levels for node_modules compatibility
|
|
160
|
-
const isProduction = this.config?.production?.enabled === true;
|
|
161
|
-
const folderSuffix = isProduction ? 'dist' : 'src';
|
|
162
|
-
const componentPath = getPath(import.meta.url, folderSuffix, categoryPath, name);
|
|
163
|
-
|
|
164
|
-
if (fs.pathExistsSync(componentPath)) {
|
|
165
|
-
updatableComponents.push({
|
|
166
|
-
name,
|
|
167
|
-
category,
|
|
168
|
-
path: componentPath
|
|
169
|
-
});
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
});
|
|
173
|
-
|
|
174
|
-
return updatableComponents;
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
getAvailableComponents(category = null) {
|
|
178
|
-
if (!this.componentsRegistry) return {};
|
|
179
|
-
|
|
180
|
-
const components = {};
|
|
181
|
-
Object.entries(this.componentsRegistry).forEach(([name, componentCategory]) => {
|
|
182
|
-
if (!category || componentCategory === category) {
|
|
183
|
-
// Special components that don't need all files
|
|
184
|
-
let files;
|
|
185
|
-
if (componentCategory === 'Visual') {
|
|
186
|
-
// Logical routing components only need JS
|
|
187
|
-
if (['Route', 'MultiRoute', 'Link'].includes(name)) {
|
|
188
|
-
files = [`${name}.js`];
|
|
189
|
-
} else if (name === 'Icon') {
|
|
190
|
-
// Icon component needs font files to render glyphs
|
|
191
|
-
files = [`${name}.js`, `${name}.html`, `${name}.css`, 'slc.eot', 'slc.woff2', 'slc.woff', 'slc.ttf', 'slc.svg'];
|
|
192
|
-
} else {
|
|
193
|
-
// Normal visual components need JS, HTML, CSS
|
|
194
|
-
files = [`${name}.js`, `${name}.html`, `${name}.css`];
|
|
195
|
-
}
|
|
196
|
-
} else {
|
|
197
|
-
// Service components only need JS
|
|
198
|
-
files = [`${name}.js`];
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
components[name] = {
|
|
202
|
-
name,
|
|
203
|
-
category: componentCategory,
|
|
204
|
-
files: files
|
|
205
|
-
};
|
|
206
|
-
}
|
|
207
|
-
});
|
|
208
|
-
|
|
209
|
-
return components;
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
async downloadComponentFiles(componentName, category, targetPath) {
|
|
214
|
-
const component = this.getAvailableComponents(category)[componentName];
|
|
215
|
-
|
|
216
|
-
if (!component) {
|
|
217
|
-
throw new Error(`Component ${componentName} not found in ${category} category`);
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
const downloadedFiles = [];
|
|
221
|
-
const failedFiles = [];
|
|
222
|
-
const total = component.files.length;
|
|
223
|
-
let done = 0;
|
|
224
|
-
const spinner = ora(`Downloading ${componentName} 0/${total}`).start();
|
|
225
|
-
const BINARY_EXTENSIONS = ['.eot', '.woff2', '.woff', '.ttf'];
|
|
226
|
-
const worker = async (fileName) => {
|
|
227
|
-
const url = `${DOCS_REPO_BASE_URL}/${category}/${componentName}/${fileName}`;
|
|
228
|
-
const localPath = path.join(targetPath, fileName);
|
|
229
|
-
const isBinary = BINARY_EXTENSIONS.some(ext => fileName.endsWith(ext));
|
|
230
|
-
try {
|
|
231
|
-
const content = await fetchWithRetry(url, 3, 500, isBinary);
|
|
232
|
-
if (isBinary) {
|
|
233
|
-
await fs.writeFile(localPath, Buffer.from(content));
|
|
234
|
-
} else {
|
|
235
|
-
await fs.writeFile(localPath, content, 'utf8');
|
|
236
|
-
}
|
|
237
|
-
downloadedFiles.push(fileName);
|
|
238
|
-
} catch (error) {
|
|
239
|
-
Print.downloadError(fileName);
|
|
240
|
-
failedFiles.push(fileName);
|
|
241
|
-
} finally {
|
|
242
|
-
done += 1;
|
|
243
|
-
spinner.text = `Downloading ${componentName} ${done}/${total}`;
|
|
244
|
-
}
|
|
245
|
-
};
|
|
246
|
-
await runConcurrent(component.files, worker, 3);
|
|
247
|
-
spinner.stop();
|
|
248
|
-
|
|
249
|
-
// Only throw error if main file (.js) was not downloaded
|
|
250
|
-
const mainFileDownloaded = downloadedFiles.some(file => file.endsWith('.js'));
|
|
251
|
-
|
|
252
|
-
if (!mainFileDownloaded) {
|
|
253
|
-
throw new Error(`Failed to download main component file (${componentName}.js)`);
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
// Report files that failed (but don't stop the process)
|
|
257
|
-
if (failedFiles.length > 0) {
|
|
258
|
-
Print.warning(`Some files couldn't be downloaded: ${failedFiles.join(', ')}`);
|
|
259
|
-
Print.info('Component installed with available files');
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
return downloadedFiles;
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
async updateLocalRegistrySafe(componentName, category) {
|
|
266
|
-
const run = this._registryLock.then(() => this._updateLocalRegistry(componentName, category));
|
|
267
|
-
this._registryLock = run.catch(() => { /* non-critical: registry update failure is handled by caller */ });
|
|
268
|
-
return run;
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
async _updateLocalRegistry(componentName, category) {
|
|
272
|
-
const componentsPath = getComponentsJsPath(import.meta.url);
|
|
273
|
-
if (!await fs.pathExists(componentsPath)) {
|
|
274
|
-
const dir = path.dirname(componentsPath);
|
|
275
|
-
await fs.ensureDir(dir);
|
|
276
|
-
const initial = `const components = {};\n\nexport default components;\n`;
|
|
277
|
-
await fs.writeFile(componentsPath, initial, 'utf8');
|
|
278
|
-
}
|
|
279
|
-
const content = await fs.readFile(componentsPath, 'utf8');
|
|
280
|
-
const match = content.match(/const components = ({[\s\S]*?});/);
|
|
281
|
-
if (!match) throw new Error('Invalid components.js format in local project');
|
|
282
|
-
const componentsObj = JSON.parse(match[1]);
|
|
283
|
-
if (!componentsObj[componentName]) {
|
|
284
|
-
componentsObj[componentName] = category;
|
|
285
|
-
const sorted = Object.keys(componentsObj)
|
|
286
|
-
.sort()
|
|
287
|
-
.reduce((obj, key) => { obj[key] = componentsObj[key]; return obj; }, {});
|
|
288
|
-
const newContent = `const components = ${JSON.stringify(sorted, null, 2)};\n\nexport default components;\n`;
|
|
289
|
-
await fs.writeFile(componentsPath, newContent, 'utf8');
|
|
290
|
-
Print.registryUpdate(`Registered ${componentName} in local components.js`);
|
|
291
|
-
} else {
|
|
292
|
-
Print.info(`${componentName} already exists in local registry`);
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
async installComponent(componentName, category, force = false, opts = {}) {
|
|
297
|
-
const seen = opts.seen || new Set();
|
|
298
|
-
const withDeps = opts.withDeps !== false;
|
|
299
|
-
const isDep = opts.isDep === true;
|
|
300
|
-
|
|
301
|
-
// Dedupe within a single run: a component reached through several paths
|
|
302
|
-
// (explicitly requested + pulled in as a shared dependency) installs once.
|
|
303
|
-
// Check-and-add is synchronous (no await between), so concurrent installs
|
|
304
|
-
// from installMultipleComponents can't both pass this guard.
|
|
305
|
-
const seenKey = `comp:${componentName}`;
|
|
306
|
-
if (seen.has(seenKey)) return true;
|
|
307
|
-
seen.add(seenKey);
|
|
308
|
-
|
|
309
|
-
await this._ensureConfig();
|
|
310
|
-
const availableComponents = this.getAvailableComponents(category);
|
|
311
|
-
|
|
312
|
-
if (!availableComponents[componentName]) {
|
|
313
|
-
// A dependency that isn't in the official registry (e.g. a project-local or
|
|
314
|
-
// framework-structural component) can't be fetched — skip it, don't abort.
|
|
315
|
-
if (isDep) {
|
|
316
|
-
Print.warning(`Dependency '${componentName}' not found in registry category '${category}' — skipping`);
|
|
317
|
-
return false;
|
|
318
|
-
}
|
|
319
|
-
throw new Error(`Component '${componentName}' not found in category '${category}' in the official repository`);
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
// Detect if validations has access to configuration
|
|
323
|
-
let categoryPath;
|
|
324
|
-
const hasValidConfig = validations.config &&
|
|
325
|
-
validations.config.paths &&
|
|
326
|
-
validations.config.paths.components &&
|
|
327
|
-
validations.config.paths.components[category];
|
|
328
|
-
|
|
329
|
-
if (hasValidConfig) {
|
|
330
|
-
categoryPath = validations.getCategoryPath(category);
|
|
331
|
-
} else {
|
|
332
|
-
if (category === 'Visual') {
|
|
333
|
-
categoryPath = 'Components/Visual';
|
|
334
|
-
} else if (category === 'Service') {
|
|
335
|
-
categoryPath = 'Components/Service';
|
|
336
|
-
} else {
|
|
337
|
-
throw new Error(`Unknown category: ${category}`);
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
const isProduction = this.config?.production?.enabled === true;
|
|
342
|
-
const folderSuffix = isProduction ? 'dist' : 'src';
|
|
343
|
-
|
|
344
|
-
const cleanCategoryPath = categoryPath ? categoryPath.replace(/^[/\\]+/, '') : '';
|
|
345
|
-
const targetPath = getPath(import.meta.url, folderSuffix, cleanCategoryPath, componentName);
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
// Check if component already exists
|
|
350
|
-
if (await fs.pathExists(targetPath) && !force) {
|
|
351
|
-
// Dependencies pulled in transitively are never re-downloaded or prompted
|
|
352
|
-
// for: an existing local copy is assumed complete (with its own deps).
|
|
353
|
-
if (isDep) {
|
|
354
|
-
Print.info(`${componentName} already installed — skipping dependency`);
|
|
355
|
-
return true;
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
const { overwrite } = await inquirer.prompt([
|
|
359
|
-
{
|
|
360
|
-
type: 'confirm',
|
|
361
|
-
name: 'overwrite',
|
|
362
|
-
message: `The component '${componentName}' already exists locally. Overwrite with the repository version?`,
|
|
363
|
-
default: false
|
|
364
|
-
}
|
|
365
|
-
]);
|
|
366
|
-
|
|
367
|
-
if (!overwrite) {
|
|
368
|
-
Print.info('Installation cancelled by user');
|
|
369
|
-
return false;
|
|
370
|
-
}
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
try {
|
|
374
|
-
// Create component directory
|
|
375
|
-
await fs.ensureDir(targetPath);
|
|
376
|
-
|
|
377
|
-
// Download component files
|
|
378
|
-
const downloadedFiles = await this.downloadComponentFiles(componentName, category, targetPath);
|
|
379
|
-
|
|
380
|
-
await this.updateLocalRegistrySafe(componentName, category);
|
|
381
|
-
|
|
382
|
-
Print.success(`${componentName} installed successfully from official repository!`);
|
|
383
|
-
console.log(`📁 Location: ${[folderSuffix, categoryPath, componentName].join('/').replace(/\/+/g, '/')}/`);
|
|
384
|
-
console.log(`📄 Files: ${downloadedFiles.join(', ')}`);
|
|
385
|
-
|
|
386
|
-
// Resolve and install what this component pulls in: other components via
|
|
387
|
-
// slice.build('X') or relative imports, and helper .js modules it imports.
|
|
388
|
-
if (withDeps) {
|
|
389
|
-
const mainJsPath = path.join(targetPath, `${componentName}.js`);
|
|
390
|
-
if (await fs.pathExists(mainJsPath)) {
|
|
391
|
-
const jsText = await fs.readFile(mainJsPath, 'utf8');
|
|
392
|
-
// Path of this file relative to the repo's Components root — the anchor
|
|
393
|
-
// for resolving relative imports. category ('Visual'|'Service') matches
|
|
394
|
-
// the repo folder layout used by the download URLs.
|
|
395
|
-
const repoRelPath = `${category}/${componentName}/${componentName}.js`;
|
|
396
|
-
await this.resolveDependencies(jsText, repoRelPath, seen, force);
|
|
397
|
-
}
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
return true;
|
|
401
|
-
|
|
402
|
-
} catch (error) {
|
|
403
|
-
// Only clean up if main file (.js) does not exist
|
|
404
|
-
const mainFilePath = path.join(targetPath, `${componentName}.js`);
|
|
405
|
-
const mainFileExists = await fs.pathExists(mainFilePath);
|
|
406
|
-
|
|
407
|
-
if (!mainFileExists && await fs.pathExists(targetPath)) {
|
|
408
|
-
// Only clean up if main file was not installed
|
|
409
|
-
await fs.remove(targetPath);
|
|
410
|
-
} else if (mainFileExists) {
|
|
411
|
-
Print.warning('Component partially installed - main file exists');
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
throw error;
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
|
|
418
|
-
// Given the source of a just-installed module, install everything it needs.
|
|
419
|
-
// `repoRelPath` anchors relative-import resolution to the repo's Components root.
|
|
420
|
-
async resolveDependencies(jsText, repoRelPath, seen, force = false) {
|
|
421
|
-
const { builds, imports, bareImports } = analyzeSource(jsText);
|
|
422
|
-
|
|
423
|
-
// Bare (node_modules) imports can't be fetched from the registry — they are
|
|
424
|
-
// npm packages the user must install. Surface each one once.
|
|
425
|
-
for (const spec of bareImports || []) {
|
|
426
|
-
const root = spec.startsWith('@') ? spec.split('/').slice(0, 2).join('/') : spec.split('/')[0];
|
|
427
|
-
this._reportedExternal ??= new Set();
|
|
428
|
-
if (this._reportedExternal.has(root)) continue;
|
|
429
|
-
this._reportedExternal.add(root);
|
|
430
|
-
Print.warning(`↳ npm package required: "${root}" — install it in your project (e.g. "pnpm add ${root}")`);
|
|
431
|
-
}
|
|
432
|
-
|
|
433
|
-
// 1) Component dependencies via slice.build('X').
|
|
434
|
-
for (const name of builds) {
|
|
435
|
-
const info = this.findComponentInRegistry(name);
|
|
436
|
-
if (!info) continue; // structural/framework/unknown — nothing to fetch
|
|
437
|
-
if (!seen.has(`comp:${info.name}`)) {
|
|
438
|
-
Print.info(`↳ dependency: ${info.name} (${info.category})`);
|
|
439
|
-
}
|
|
440
|
-
await this.installComponent(info.name, info.category, force, { seen, withDeps: true, isDep: true });
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
// 2) Relative imports: either another component's entrypoint, or a plain
|
|
444
|
-
// helper .js module living inside a component folder.
|
|
445
|
-
for (const spec of imports) {
|
|
446
|
-
const resolved = this.resolveRepoImportPath(repoRelPath, spec);
|
|
447
|
-
if (!resolved) continue;
|
|
448
|
-
|
|
449
|
-
const parts = resolved.split('/');
|
|
450
|
-
const fileBase = parts[parts.length - 1].replace(/\.js$/, '');
|
|
451
|
-
const folder = parts.length >= 2 ? parts[parts.length - 2] : '';
|
|
452
|
-
const info = this.findComponentInRegistry(fileBase);
|
|
453
|
-
|
|
454
|
-
// <Category>/<Name>/<Name>.js → a registered component (e.g. Pagination
|
|
455
|
-
// importing ../../Service/DataGridEngine/DataGridEngine.js).
|
|
456
|
-
if (info && folder === info.name) {
|
|
457
|
-
if (!seen.has(`comp:${info.name}`)) {
|
|
458
|
-
Print.info(`↳ dependency: ${info.name} (${info.category})`);
|
|
459
|
-
}
|
|
460
|
-
await this.installComponent(info.name, info.category, force, { seen, withDeps: true, isDep: true });
|
|
461
|
-
} else {
|
|
462
|
-
await this.installHelperFile(resolved, seen, force);
|
|
463
|
-
}
|
|
464
|
-
}
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
// Resolves an import specifier to a path relative to the repo Components root,
|
|
468
|
-
// or null if it isn't a fetchable in-repo JS module.
|
|
469
|
-
resolveRepoImportPath(fromRepoRelPath, spec) {
|
|
470
|
-
const dir = path.posix.dirname(fromRepoRelPath);
|
|
471
|
-
let resolved = path.posix.normalize(path.posix.join(dir, spec));
|
|
472
|
-
|
|
473
|
-
// Escapes the Components root (e.g. test fixtures) → not fetchable here.
|
|
474
|
-
if (resolved.startsWith('..') || path.posix.isAbsolute(resolved)) return null;
|
|
475
|
-
|
|
476
|
-
const ext = path.posix.extname(resolved);
|
|
477
|
-
if (!ext) {
|
|
478
|
-
resolved += '.js';
|
|
479
|
-
} else if (ext !== '.js') {
|
|
480
|
-
return null; // only JS modules are followed
|
|
481
|
-
}
|
|
482
|
-
return resolved;
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
// Downloads a single helper module (a non-component .js imported by a
|
|
486
|
-
// component) into its mirrored location, then follows its own dependencies.
|
|
487
|
-
async installHelperFile(repoRelPath, seen, force = false) {
|
|
488
|
-
const seenKey = `file:${repoRelPath}`;
|
|
489
|
-
if (seen.has(seenKey)) return;
|
|
490
|
-
seen.add(seenKey);
|
|
491
|
-
|
|
492
|
-
await this._ensureConfig();
|
|
493
|
-
const folderSuffix = this.config?.production?.enabled === true ? 'dist' : 'src';
|
|
494
|
-
const segments = repoRelPath.split('/');
|
|
495
|
-
const localPath = getPath(import.meta.url, folderSuffix, 'Components', ...segments);
|
|
496
|
-
|
|
497
|
-
if (await fs.pathExists(localPath) && !force) {
|
|
498
|
-
Print.info(`↳ helper module ${repoRelPath} already present — skipping`);
|
|
499
|
-
return;
|
|
500
|
-
}
|
|
501
|
-
|
|
502
|
-
const url = `${DOCS_REPO_BASE_URL}/${repoRelPath}`;
|
|
503
|
-
let content;
|
|
504
|
-
try {
|
|
505
|
-
content = await fetchWithRetry(url, 3, 500, false);
|
|
506
|
-
} catch (error) {
|
|
507
|
-
Print.warning(`Could not download helper module '${repoRelPath}' — ${error.message}`);
|
|
508
|
-
return;
|
|
509
|
-
}
|
|
510
|
-
|
|
511
|
-
await fs.ensureDir(path.dirname(localPath));
|
|
512
|
-
await fs.writeFile(localPath, content, 'utf8');
|
|
513
|
-
Print.registryUpdate(`↳ helper module ${repoRelPath}`);
|
|
514
|
-
|
|
515
|
-
// A helper can import further helpers or build components.
|
|
516
|
-
await this.resolveDependencies(content, repoRelPath, seen, force);
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
async installMultipleComponents(componentNames, category = 'Visual', force = false, withDeps = true) {
|
|
520
|
-
const results = [];
|
|
521
|
-
// One shared visited-set so a dependency shared by several requested
|
|
522
|
-
// components (e.g. DataGridEngine under both Table and Pagination) installs once.
|
|
523
|
-
const seen = new Set();
|
|
524
|
-
Print.info(`Getting ${componentNames.length} ${category} components from official repository...`);
|
|
525
|
-
const total = componentNames.length;
|
|
526
|
-
let done = 0;
|
|
527
|
-
const spinner = ora(`Installing 0/${total}`).start();
|
|
528
|
-
const worker = async (componentName) => {
|
|
529
|
-
try {
|
|
530
|
-
const result = await this.installComponent(componentName, category, force, { seen, withDeps });
|
|
531
|
-
results.push({ name: componentName, success: result });
|
|
532
|
-
} catch (error) {
|
|
533
|
-
Print.componentError(componentName, 'getting', error.message);
|
|
534
|
-
results.push({ name: componentName, success: false, error: error.message });
|
|
535
|
-
} finally {
|
|
536
|
-
done += 1;
|
|
537
|
-
spinner.text = `Installing ${done}/${total}`;
|
|
538
|
-
}
|
|
539
|
-
};
|
|
540
|
-
await runConcurrent(componentNames, worker, 3);
|
|
541
|
-
spinner.stop();
|
|
542
|
-
|
|
543
|
-
// Summary
|
|
544
|
-
const successful = results.filter(r => r.success).length;
|
|
545
|
-
const failed = results.filter(r => !r.success).length;
|
|
546
|
-
|
|
547
|
-
Print.newLine();
|
|
548
|
-
Print.summary(successful, failed, componentNames.length);
|
|
549
|
-
|
|
550
|
-
return results;
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
async updateAllComponents(force = false) {
|
|
554
|
-
Print.info('Looking for updatable Visual components...');
|
|
555
|
-
|
|
556
|
-
const allUpdatableComponents = await this.findUpdatableComponents();
|
|
557
|
-
|
|
558
|
-
// Filter only Visual components
|
|
559
|
-
const updatableComponents = allUpdatableComponents.filter(comp => comp.category === 'Visual');
|
|
560
|
-
|
|
561
|
-
if (updatableComponents.length === 0) {
|
|
562
|
-
Print.info('No local Visual components found that match the official repository');
|
|
563
|
-
Print.info('Use "slice browse" to see available components');
|
|
564
|
-
return true;
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
// Show statistics if there are Service components that won't be synced
|
|
568
|
-
const serviceComponents = allUpdatableComponents.filter(comp => comp.category === 'Service');
|
|
569
|
-
if (serviceComponents.length > 0) {
|
|
570
|
-
Print.info(`Found ${serviceComponents.length} Service components (skipped - sync only affects Visual components)`);
|
|
571
|
-
}
|
|
572
|
-
|
|
573
|
-
Print.newLine();
|
|
574
|
-
Print.subtitle(`Found ${updatableComponents.length} updatable Visual components:`);
|
|
575
|
-
Print.newLine();
|
|
576
|
-
updatableComponents.forEach(comp => {
|
|
577
|
-
console.log(`🎨 ${comp.name} (${comp.category})`);
|
|
578
|
-
});
|
|
579
|
-
|
|
580
|
-
if (!force) {
|
|
581
|
-
const { confirmUpdate } = await inquirer.prompt([
|
|
582
|
-
{
|
|
583
|
-
type: 'confirm',
|
|
584
|
-
name: 'confirmUpdate',
|
|
585
|
-
message: `Do you want to update these Visual components to the repository versions?`,
|
|
586
|
-
default: true
|
|
587
|
-
}
|
|
588
|
-
]);
|
|
589
|
-
|
|
590
|
-
if (!confirmUpdate) {
|
|
591
|
-
Print.info('Update cancelled by user');
|
|
592
|
-
return false;
|
|
593
|
-
}
|
|
594
|
-
}
|
|
595
|
-
|
|
596
|
-
// Only update Visual components
|
|
597
|
-
const visualComponentNames = updatableComponents.map(c => c.name);
|
|
598
|
-
|
|
599
|
-
Print.info(`Updating ${visualComponentNames.length} Visual components...`);
|
|
600
|
-
const results = await this.installMultipleComponents(visualComponentNames, 'Visual', true);
|
|
601
|
-
|
|
602
|
-
// Final summary
|
|
603
|
-
const totalSuccessful = results.filter(r => r.success).length;
|
|
604
|
-
const totalFailed = results.filter(r => !r.success).length;
|
|
605
|
-
|
|
606
|
-
Print.newLine();
|
|
607
|
-
Print.title('Visual Components Sync Summary');
|
|
608
|
-
Print.success(`Visual components updated: ${totalSuccessful}`);
|
|
609
|
-
|
|
610
|
-
if (totalFailed > 0) {
|
|
611
|
-
Print.error(`Visual components failed: ${totalFailed}`);
|
|
612
|
-
} else {
|
|
613
|
-
Print.success('All your Visual components are now updated to the latest official versions!');
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
// Additional information about Service components
|
|
617
|
-
if (serviceComponents.length > 0) {
|
|
618
|
-
Print.newLine();
|
|
619
|
-
Print.info(`Note: ${serviceComponents.length} Service components were found but not updated`);
|
|
620
|
-
Print.info('Service components maintain manual versioning - update them individually if needed');
|
|
621
|
-
Print.commandExample('Update Service component manually', 'slice get FetchManager --service --force');
|
|
622
|
-
}
|
|
623
|
-
|
|
624
|
-
return totalFailed === 0;
|
|
625
|
-
}
|
|
626
|
-
|
|
627
|
-
displayAvailableComponents() {
|
|
628
|
-
if (!this.componentsRegistry) {
|
|
629
|
-
Print.error('❌ Could not load component registry');
|
|
630
|
-
return;
|
|
631
|
-
}
|
|
632
|
-
|
|
633
|
-
console.log('\n📚 Available components in the official Slice.js repository:\n');
|
|
634
|
-
|
|
635
|
-
const visualComponents = this.getAvailableComponents('Visual');
|
|
636
|
-
const serviceComponents = this.getAvailableComponents('Service');
|
|
637
|
-
|
|
638
|
-
// Only show names without descriptions
|
|
639
|
-
Print.info('🎨 Visual Components (UI):');
|
|
640
|
-
Object.keys(visualComponents).forEach(name => {
|
|
641
|
-
const files = visualComponents[name].files;
|
|
642
|
-
const fileIcons = files.map(file => {
|
|
643
|
-
if (file.endsWith('.js')) return '📜';
|
|
644
|
-
if (file.endsWith('.html')) return '🌐';
|
|
645
|
-
if (file.endsWith('.css')) return '🎨';
|
|
646
|
-
return '📄';
|
|
647
|
-
}).join(' ');
|
|
648
|
-
console.log(` • ${name} ${fileIcons}`);
|
|
649
|
-
});
|
|
650
|
-
|
|
651
|
-
Print.info('\n⚙️ Service Components (Logic):');
|
|
652
|
-
Object.keys(serviceComponents).forEach(name => {
|
|
653
|
-
console.log(` • ${name} 📜`);
|
|
654
|
-
});
|
|
655
|
-
|
|
656
|
-
Print.newLine();
|
|
657
|
-
Print.info(`Total: ${Object.keys(visualComponents).length} Visual + ${Object.keys(serviceComponents).length} Service components`);
|
|
658
|
-
|
|
659
|
-
console.log(`\n💡 Usage examples:`);
|
|
660
|
-
console.log(`slice get Button Card Input # Install Visual components`);
|
|
661
|
-
console.log(`slice get FetchManager --service # Install Service component`);
|
|
662
|
-
console.log(`slice sync # Sync Visual components`);
|
|
663
|
-
}
|
|
664
|
-
|
|
665
|
-
async interactiveInstall() {
|
|
666
|
-
const { componentType } = await inquirer.prompt([
|
|
667
|
-
{
|
|
668
|
-
type: 'list',
|
|
669
|
-
name: 'componentType',
|
|
670
|
-
message: 'Select the type of component to install from the repository:',
|
|
671
|
-
choices: [
|
|
672
|
-
{ name: '🎨 Visual Components (UI)', value: 'Visual' },
|
|
673
|
-
{ name: '⚙️ Service Components (Logic)', value: 'Service' }
|
|
674
|
-
]
|
|
675
|
-
}
|
|
676
|
-
]);
|
|
677
|
-
|
|
678
|
-
const availableComponents = this.getAvailableComponents(componentType);
|
|
679
|
-
const componentChoices = Object.keys(availableComponents).map(name => ({
|
|
680
|
-
name: name,
|
|
681
|
-
value: name
|
|
682
|
-
}));
|
|
683
|
-
|
|
684
|
-
if (componentType === 'Visual') {
|
|
685
|
-
const { installMode } = await inquirer.prompt([
|
|
686
|
-
{
|
|
687
|
-
type: 'list',
|
|
688
|
-
name: 'installMode',
|
|
689
|
-
message: 'How do you want to install Visual components?',
|
|
690
|
-
choices: [
|
|
691
|
-
{ name: 'Get one', value: 'single' },
|
|
692
|
-
{ name: 'Get multiple', value: 'multiple' }
|
|
693
|
-
]
|
|
694
|
-
}
|
|
695
|
-
]);
|
|
696
|
-
|
|
697
|
-
if (installMode === 'multiple') {
|
|
698
|
-
const { selectedComponents } = await inquirer.prompt([
|
|
699
|
-
{
|
|
700
|
-
type: 'checkbox',
|
|
701
|
-
name: 'selectedComponents',
|
|
702
|
-
message: 'Select Visual components to install from the repository:',
|
|
703
|
-
choices: componentChoices,
|
|
704
|
-
validate: (input) => {
|
|
705
|
-
if (input.length === 0) {
|
|
706
|
-
return 'You must select at least one component';
|
|
707
|
-
}
|
|
708
|
-
return true;
|
|
709
|
-
}
|
|
710
|
-
}
|
|
711
|
-
]);
|
|
712
|
-
|
|
713
|
-
await this.installMultipleComponents(selectedComponents, componentType);
|
|
714
|
-
} else {
|
|
715
|
-
const { selectedComponent } = await inquirer.prompt([
|
|
716
|
-
{
|
|
717
|
-
type: 'list',
|
|
718
|
-
name: 'selectedComponent',
|
|
719
|
-
message: 'Select a Visual component:',
|
|
720
|
-
choices: componentChoices
|
|
721
|
-
}
|
|
722
|
-
]);
|
|
723
|
-
|
|
724
|
-
await this.installComponent(selectedComponent, componentType);
|
|
725
|
-
}
|
|
726
|
-
} else {
|
|
727
|
-
const { selectedComponent } = await inquirer.prompt([
|
|
728
|
-
{
|
|
729
|
-
type: 'list',
|
|
730
|
-
name: 'selectedComponent',
|
|
731
|
-
message: 'Select a Service component:',
|
|
732
|
-
choices: componentChoices
|
|
733
|
-
}
|
|
734
|
-
]);
|
|
735
|
-
|
|
736
|
-
await this.installComponent(selectedComponent, componentType);
|
|
737
|
-
}
|
|
738
|
-
}
|
|
739
|
-
|
|
740
|
-
findComponentInRegistry(componentName) {
|
|
741
|
-
if (!this.componentsRegistry) return null;
|
|
742
|
-
|
|
743
|
-
const normalizedName = componentName.charAt(0).toUpperCase() + componentName.slice(1);
|
|
744
|
-
|
|
745
|
-
if (this.componentsRegistry[normalizedName]) {
|
|
746
|
-
return {
|
|
747
|
-
name: normalizedName,
|
|
748
|
-
category: this.componentsRegistry[normalizedName]
|
|
749
|
-
};
|
|
750
|
-
}
|
|
751
|
-
|
|
752
|
-
return null;
|
|
753
|
-
}
|
|
754
|
-
}
|
|
755
|
-
|
|
756
|
-
const sharedRegistry = new ComponentRegistry();
|
|
757
|
-
|
|
758
|
-
// Main get function
|
|
759
|
-
async function getComponents(componentNames = [], options = {}) {
|
|
760
|
-
try {
|
|
761
|
-
await sharedRegistry.loadRegistry();
|
|
762
|
-
} catch (error) {
|
|
763
|
-
Print.error('Could not load component registry from official repository');
|
|
764
|
-
Print.info('Check your internet connection and try again');
|
|
765
|
-
return false;
|
|
766
|
-
}
|
|
767
|
-
|
|
768
|
-
// Interactive mode if no components specified
|
|
769
|
-
if (!componentNames || componentNames.length === 0) {
|
|
770
|
-
await sharedRegistry.interactiveInstall();
|
|
771
|
-
return true;
|
|
772
|
-
}
|
|
773
|
-
|
|
774
|
-
// Determine category
|
|
775
|
-
const category = options.service ? 'Service' : 'Visual';
|
|
776
|
-
|
|
777
|
-
// Dependency resolution is on by default; `slice get X --no-deps` opts out.
|
|
778
|
-
const withDeps = options.deps !== false;
|
|
779
|
-
|
|
780
|
-
if (componentNames.length === 1) {
|
|
781
|
-
// Single component install
|
|
782
|
-
const componentInfo = sharedRegistry.findComponentInRegistry(componentNames[0]);
|
|
783
|
-
|
|
784
|
-
if (!componentInfo) {
|
|
785
|
-
Print.error(`Component '${componentNames[0]}' not found in official repository`);
|
|
786
|
-
Print.commandExample('View available components', 'slice browse');
|
|
787
|
-
return false;
|
|
788
|
-
}
|
|
789
|
-
|
|
790
|
-
// Use the category from registry unless Service is explicitly requested
|
|
791
|
-
const actualCategory = options.service ? 'Service' : componentInfo.category;
|
|
792
|
-
|
|
793
|
-
try {
|
|
794
|
-
await sharedRegistry.installComponent(componentInfo.name, actualCategory, options.force, { seen: new Set(), withDeps });
|
|
795
|
-
return true;
|
|
796
|
-
} catch (error) {
|
|
797
|
-
Print.error(`Error installing component: ${error.message}`);
|
|
798
|
-
return false;
|
|
799
|
-
}
|
|
800
|
-
} else {
|
|
801
|
-
// Multiple components install
|
|
802
|
-
const normalizedComponents = componentNames.map(name =>
|
|
803
|
-
name.charAt(0).toUpperCase() + name.slice(1)
|
|
804
|
-
);
|
|
805
|
-
|
|
806
|
-
try {
|
|
807
|
-
await sharedRegistry.installMultipleComponents(normalizedComponents, category, options.force, withDeps);
|
|
808
|
-
return true;
|
|
809
|
-
} catch (error) {
|
|
810
|
-
Print.error(`Error installing components: ${error.message}`);
|
|
811
|
-
return false;
|
|
812
|
-
}
|
|
813
|
-
}
|
|
814
|
-
}
|
|
815
|
-
|
|
816
|
-
// List components function
|
|
817
|
-
async function listComponents() {
|
|
818
|
-
try {
|
|
819
|
-
await sharedRegistry.loadRegistry();
|
|
820
|
-
sharedRegistry.displayAvailableComponents();
|
|
821
|
-
return true;
|
|
822
|
-
} catch (error) {
|
|
823
|
-
Print.error('Could not load component registry from official repository');
|
|
824
|
-
Print.info('Check your internet connection and try again');
|
|
825
|
-
return false;
|
|
826
|
-
}
|
|
827
|
-
}
|
|
828
|
-
|
|
829
|
-
// Sync components function
|
|
830
|
-
async function syncComponents(options = {}) {
|
|
831
|
-
try {
|
|
832
|
-
await sharedRegistry.loadRegistry();
|
|
833
|
-
return await sharedRegistry.updateAllComponents(options.force);
|
|
834
|
-
} catch (error) {
|
|
835
|
-
Print.error('Could not load component registry from official repository');
|
|
836
|
-
Print.info('Check your internet connection and try again');
|
|
837
|
-
return false;
|
|
838
|
-
}
|
|
839
|
-
}
|
|
840
|
-
|
|
841
|
-
export default getComponents;
|
|
842
|
-
export { listComponents, syncComponents, ComponentRegistry, loadConfig, runConcurrent, fetchWithRetry };
|
|
1
|
+
// commands/getComponent/getComponent.js
|
|
2
|
+
|
|
3
|
+
import fs from "fs-extra";
|
|
4
|
+
import path from "path";
|
|
5
|
+
import inquirer from "inquirer";
|
|
6
|
+
import validations from "../Validations.js";
|
|
7
|
+
import Print from "../Print.js";
|
|
8
|
+
import { getComponentsJsPath, getPath } from "../utils/PathHelper.js";
|
|
9
|
+
import { loadConfig as sharedLoadConfig } from "../utils/loadConfig.js";
|
|
10
|
+
import { analyzeSource } from "../utils/analyzeSource.js";
|
|
11
|
+
import ora from "ora";
|
|
12
|
+
|
|
13
|
+
// Base URL of the Slice.js documentation repository
|
|
14
|
+
const DOCS_REPO_BASE_URL = 'https://raw.githubusercontent.com/VKneider/slicejs-components/master/src/Components';
|
|
15
|
+
const COMPONENTS_REGISTRY_URL = 'https://raw.githubusercontent.com/VKneider/slicejs-components/master/src/Components/components.js';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Loads configuration from sliceConfig.json
|
|
19
|
+
* @returns {object} - Configuration object
|
|
20
|
+
*/
|
|
21
|
+
const loadConfig = () => sharedLoadConfig(import.meta.url);
|
|
22
|
+
|
|
23
|
+
const fetchWithRetry = async (url, retries = 3, baseDelay = 500, binary = false) => {
|
|
24
|
+
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
25
|
+
try {
|
|
26
|
+
const response = await fetch(url);
|
|
27
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
28
|
+
return binary ? await response.arrayBuffer() : await response.text();
|
|
29
|
+
} catch (e) {
|
|
30
|
+
if (attempt === retries) throw e;
|
|
31
|
+
const delay = baseDelay * Math.pow(2, attempt);
|
|
32
|
+
await new Promise(r => setTimeout(r, delay));
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const runConcurrent = async (items, worker, concurrency = 3) => {
|
|
38
|
+
let index = 0;
|
|
39
|
+
const runners = Array(Math.min(concurrency, items.length)).fill(0).map(async () => {
|
|
40
|
+
while (true) {
|
|
41
|
+
const i = index++;
|
|
42
|
+
if (i >= items.length) break;
|
|
43
|
+
await worker(items[i]);
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
await Promise.all(runners);
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
class ComponentRegistry {
|
|
50
|
+
constructor() {
|
|
51
|
+
this.componentsRegistry = null;
|
|
52
|
+
this.config = null;
|
|
53
|
+
this._configPromise = null;
|
|
54
|
+
// Serializes read-modify-write cycles on components.js: installs run
|
|
55
|
+
// concurrently (runConcurrent), and parallel writers corrupt the file
|
|
56
|
+
// (partial reads) or silently drop registrations (lost updates).
|
|
57
|
+
this._registryLock = Promise.resolve();
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async _ensureConfig() {
|
|
61
|
+
if (!this.config && !this._configPromise) {
|
|
62
|
+
this._configPromise = loadConfig();
|
|
63
|
+
}
|
|
64
|
+
if (this._configPromise) {
|
|
65
|
+
this.config = await this._configPromise;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async loadRegistry() {
|
|
70
|
+
await this._ensureConfig();
|
|
71
|
+
Print.info('Loading component registry from official repository...');
|
|
72
|
+
|
|
73
|
+
try {
|
|
74
|
+
const response = await fetch(COMPONENTS_REGISTRY_URL);
|
|
75
|
+
|
|
76
|
+
if (!response.ok) {
|
|
77
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const content = await response.text();
|
|
81
|
+
|
|
82
|
+
// Parse the components.js file content
|
|
83
|
+
const match = content.match(/const components = ({[\s\S]*?});/);
|
|
84
|
+
if (!match) {
|
|
85
|
+
throw new Error('Invalid components.js format from repository');
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const allComponents = JSON.parse(match[1]);
|
|
89
|
+
|
|
90
|
+
// Filter only Visual and Service components
|
|
91
|
+
this.componentsRegistry = this.filterOfficialComponents(allComponents);
|
|
92
|
+
|
|
93
|
+
Print.success('Component registry loaded successfully');} catch (error) {
|
|
94
|
+
throw new Error(`Could not load the component registry: ${error.message}`, { cause: error });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Filters the registry to include ONLY Visual and Service category components
|
|
100
|
+
* Excludes AppComponents and any other category
|
|
101
|
+
* @param {object} allComponents - Object with all registry components
|
|
102
|
+
* @returns {object} - Filtered object with only Visual and Service
|
|
103
|
+
*/
|
|
104
|
+
filterOfficialComponents(allComponents) {
|
|
105
|
+
const filtered = {};
|
|
106
|
+
let excludedCount = 0;
|
|
107
|
+
|
|
108
|
+
Object.entries(allComponents).forEach(([name, category]) => {
|
|
109
|
+
// Only include Visual or Service category components
|
|
110
|
+
if (category === 'Visual' || category === 'Service') {
|
|
111
|
+
filtered[name] = category;
|
|
112
|
+
} else {
|
|
113
|
+
excludedCount++;
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
if (excludedCount > 0) {
|
|
118
|
+
Print.info(`Filtered out ${excludedCount} non-Visual/Service components from registry`);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
return filtered;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async getLocalComponents() {
|
|
125
|
+
// Declared outside the try: the catch reports this path, and it used to
|
|
126
|
+
// throw a ReferenceError exactly when the registry was unreadable.
|
|
127
|
+
const componentsPath = getComponentsJsPath(import.meta.url);
|
|
128
|
+
|
|
129
|
+
try {
|
|
130
|
+
if (!await fs.pathExists(componentsPath)) {
|
|
131
|
+
return {};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const content = await fs.readFile(componentsPath, 'utf8');
|
|
135
|
+
const match = content.match(/const components = ({[\s\S]*?});/);
|
|
136
|
+
|
|
137
|
+
if (!match) {
|
|
138
|
+
return {};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return JSON.parse(match[1]);
|
|
142
|
+
} catch (error) {
|
|
143
|
+
Print.warning(`⚠️ Could not read the local component registry at: ${componentsPath}`);
|
|
144
|
+
return {};
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async findUpdatableComponents() {
|
|
149
|
+
await this._ensureConfig();
|
|
150
|
+
const localComponents = await this.getLocalComponents();
|
|
151
|
+
const updatableComponents = [];
|
|
152
|
+
|
|
153
|
+
Object.entries(localComponents).forEach(([name, category]) => {
|
|
154
|
+
// Check if component exists in remote registry
|
|
155
|
+
if (this.componentsRegistry[name] && this.componentsRegistry[name] === category) {
|
|
156
|
+
// Check if local component directory exists using dynamic paths
|
|
157
|
+
const categoryPath = validations.getCategoryPath(category);
|
|
158
|
+
|
|
159
|
+
// Use 4 levels for node_modules compatibility
|
|
160
|
+
const isProduction = this.config?.production?.enabled === true;
|
|
161
|
+
const folderSuffix = isProduction ? 'dist' : 'src';
|
|
162
|
+
const componentPath = getPath(import.meta.url, folderSuffix, categoryPath, name);
|
|
163
|
+
|
|
164
|
+
if (fs.pathExistsSync(componentPath)) {
|
|
165
|
+
updatableComponents.push({
|
|
166
|
+
name,
|
|
167
|
+
category,
|
|
168
|
+
path: componentPath
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
return updatableComponents;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
getAvailableComponents(category = null) {
|
|
178
|
+
if (!this.componentsRegistry) return {};
|
|
179
|
+
|
|
180
|
+
const components = {};
|
|
181
|
+
Object.entries(this.componentsRegistry).forEach(([name, componentCategory]) => {
|
|
182
|
+
if (!category || componentCategory === category) {
|
|
183
|
+
// Special components that don't need all files
|
|
184
|
+
let files;
|
|
185
|
+
if (componentCategory === 'Visual') {
|
|
186
|
+
// Logical routing components only need JS
|
|
187
|
+
if (['Route', 'MultiRoute', 'Link'].includes(name)) {
|
|
188
|
+
files = [`${name}.js`];
|
|
189
|
+
} else if (name === 'Icon') {
|
|
190
|
+
// Icon component needs font files to render glyphs
|
|
191
|
+
files = [`${name}.js`, `${name}.html`, `${name}.css`, 'slc.eot', 'slc.woff2', 'slc.woff', 'slc.ttf', 'slc.svg'];
|
|
192
|
+
} else {
|
|
193
|
+
// Normal visual components need JS, HTML, CSS
|
|
194
|
+
files = [`${name}.js`, `${name}.html`, `${name}.css`];
|
|
195
|
+
}
|
|
196
|
+
} else {
|
|
197
|
+
// Service components only need JS
|
|
198
|
+
files = [`${name}.js`];
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
components[name] = {
|
|
202
|
+
name,
|
|
203
|
+
category: componentCategory,
|
|
204
|
+
files: files
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
return components;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
async downloadComponentFiles(componentName, category, targetPath) {
|
|
214
|
+
const component = this.getAvailableComponents(category)[componentName];
|
|
215
|
+
|
|
216
|
+
if (!component) {
|
|
217
|
+
throw new Error(`Component ${componentName} not found in ${category} category`);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const downloadedFiles = [];
|
|
221
|
+
const failedFiles = [];
|
|
222
|
+
const total = component.files.length;
|
|
223
|
+
let done = 0;
|
|
224
|
+
const spinner = ora(`Downloading ${componentName} 0/${total}`).start();
|
|
225
|
+
const BINARY_EXTENSIONS = ['.eot', '.woff2', '.woff', '.ttf'];
|
|
226
|
+
const worker = async (fileName) => {
|
|
227
|
+
const url = `${DOCS_REPO_BASE_URL}/${category}/${componentName}/${fileName}`;
|
|
228
|
+
const localPath = path.join(targetPath, fileName);
|
|
229
|
+
const isBinary = BINARY_EXTENSIONS.some(ext => fileName.endsWith(ext));
|
|
230
|
+
try {
|
|
231
|
+
const content = await fetchWithRetry(url, 3, 500, isBinary);
|
|
232
|
+
if (isBinary) {
|
|
233
|
+
await fs.writeFile(localPath, Buffer.from(content));
|
|
234
|
+
} else {
|
|
235
|
+
await fs.writeFile(localPath, content, 'utf8');
|
|
236
|
+
}
|
|
237
|
+
downloadedFiles.push(fileName);
|
|
238
|
+
} catch (error) {
|
|
239
|
+
Print.downloadError(fileName);
|
|
240
|
+
failedFiles.push(fileName);
|
|
241
|
+
} finally {
|
|
242
|
+
done += 1;
|
|
243
|
+
spinner.text = `Downloading ${componentName} ${done}/${total}`;
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
await runConcurrent(component.files, worker, 3);
|
|
247
|
+
spinner.stop();
|
|
248
|
+
|
|
249
|
+
// Only throw error if main file (.js) was not downloaded
|
|
250
|
+
const mainFileDownloaded = downloadedFiles.some(file => file.endsWith('.js'));
|
|
251
|
+
|
|
252
|
+
if (!mainFileDownloaded) {
|
|
253
|
+
throw new Error(`Failed to download main component file (${componentName}.js)`);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// Report files that failed (but don't stop the process)
|
|
257
|
+
if (failedFiles.length > 0) {
|
|
258
|
+
Print.warning(`Some files couldn't be downloaded: ${failedFiles.join(', ')}`);
|
|
259
|
+
Print.info('Component installed with available files');
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
return downloadedFiles;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async updateLocalRegistrySafe(componentName, category) {
|
|
266
|
+
const run = this._registryLock.then(() => this._updateLocalRegistry(componentName, category));
|
|
267
|
+
this._registryLock = run.catch(() => { /* non-critical: registry update failure is handled by caller */ });
|
|
268
|
+
return run;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
async _updateLocalRegistry(componentName, category) {
|
|
272
|
+
const componentsPath = getComponentsJsPath(import.meta.url);
|
|
273
|
+
if (!await fs.pathExists(componentsPath)) {
|
|
274
|
+
const dir = path.dirname(componentsPath);
|
|
275
|
+
await fs.ensureDir(dir);
|
|
276
|
+
const initial = `const components = {};\n\nexport default components;\n`;
|
|
277
|
+
await fs.writeFile(componentsPath, initial, 'utf8');
|
|
278
|
+
}
|
|
279
|
+
const content = await fs.readFile(componentsPath, 'utf8');
|
|
280
|
+
const match = content.match(/const components = ({[\s\S]*?});/);
|
|
281
|
+
if (!match) throw new Error('Invalid components.js format in local project');
|
|
282
|
+
const componentsObj = JSON.parse(match[1]);
|
|
283
|
+
if (!componentsObj[componentName]) {
|
|
284
|
+
componentsObj[componentName] = category;
|
|
285
|
+
const sorted = Object.keys(componentsObj)
|
|
286
|
+
.sort()
|
|
287
|
+
.reduce((obj, key) => { obj[key] = componentsObj[key]; return obj; }, {});
|
|
288
|
+
const newContent = `const components = ${JSON.stringify(sorted, null, 2)};\n\nexport default components;\n`;
|
|
289
|
+
await fs.writeFile(componentsPath, newContent, 'utf8');
|
|
290
|
+
Print.registryUpdate(`Registered ${componentName} in local components.js`);
|
|
291
|
+
} else {
|
|
292
|
+
Print.info(`${componentName} already exists in local registry`);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
async installComponent(componentName, category, force = false, opts = {}) {
|
|
297
|
+
const seen = opts.seen || new Set();
|
|
298
|
+
const withDeps = opts.withDeps !== false;
|
|
299
|
+
const isDep = opts.isDep === true;
|
|
300
|
+
|
|
301
|
+
// Dedupe within a single run: a component reached through several paths
|
|
302
|
+
// (explicitly requested + pulled in as a shared dependency) installs once.
|
|
303
|
+
// Check-and-add is synchronous (no await between), so concurrent installs
|
|
304
|
+
// from installMultipleComponents can't both pass this guard.
|
|
305
|
+
const seenKey = `comp:${componentName}`;
|
|
306
|
+
if (seen.has(seenKey)) return true;
|
|
307
|
+
seen.add(seenKey);
|
|
308
|
+
|
|
309
|
+
await this._ensureConfig();
|
|
310
|
+
const availableComponents = this.getAvailableComponents(category);
|
|
311
|
+
|
|
312
|
+
if (!availableComponents[componentName]) {
|
|
313
|
+
// A dependency that isn't in the official registry (e.g. a project-local or
|
|
314
|
+
// framework-structural component) can't be fetched — skip it, don't abort.
|
|
315
|
+
if (isDep) {
|
|
316
|
+
Print.warning(`Dependency '${componentName}' not found in registry category '${category}' — skipping`);
|
|
317
|
+
return false;
|
|
318
|
+
}
|
|
319
|
+
throw new Error(`Component '${componentName}' not found in category '${category}' in the official repository`);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// Detect if validations has access to configuration
|
|
323
|
+
let categoryPath;
|
|
324
|
+
const hasValidConfig = validations.config &&
|
|
325
|
+
validations.config.paths &&
|
|
326
|
+
validations.config.paths.components &&
|
|
327
|
+
validations.config.paths.components[category];
|
|
328
|
+
|
|
329
|
+
if (hasValidConfig) {
|
|
330
|
+
categoryPath = validations.getCategoryPath(category);
|
|
331
|
+
} else {
|
|
332
|
+
if (category === 'Visual') {
|
|
333
|
+
categoryPath = 'Components/Visual';
|
|
334
|
+
} else if (category === 'Service') {
|
|
335
|
+
categoryPath = 'Components/Service';
|
|
336
|
+
} else {
|
|
337
|
+
throw new Error(`Unknown category: ${category}`);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const isProduction = this.config?.production?.enabled === true;
|
|
342
|
+
const folderSuffix = isProduction ? 'dist' : 'src';
|
|
343
|
+
|
|
344
|
+
const cleanCategoryPath = categoryPath ? categoryPath.replace(/^[/\\]+/, '') : '';
|
|
345
|
+
const targetPath = getPath(import.meta.url, folderSuffix, cleanCategoryPath, componentName);
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
// Check if component already exists
|
|
350
|
+
if (await fs.pathExists(targetPath) && !force) {
|
|
351
|
+
// Dependencies pulled in transitively are never re-downloaded or prompted
|
|
352
|
+
// for: an existing local copy is assumed complete (with its own deps).
|
|
353
|
+
if (isDep) {
|
|
354
|
+
Print.info(`${componentName} already installed — skipping dependency`);
|
|
355
|
+
return true;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
const { overwrite } = await inquirer.prompt([
|
|
359
|
+
{
|
|
360
|
+
type: 'confirm',
|
|
361
|
+
name: 'overwrite',
|
|
362
|
+
message: `The component '${componentName}' already exists locally. Overwrite with the repository version?`,
|
|
363
|
+
default: false
|
|
364
|
+
}
|
|
365
|
+
]);
|
|
366
|
+
|
|
367
|
+
if (!overwrite) {
|
|
368
|
+
Print.info('Installation cancelled by user');
|
|
369
|
+
return false;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
try {
|
|
374
|
+
// Create component directory
|
|
375
|
+
await fs.ensureDir(targetPath);
|
|
376
|
+
|
|
377
|
+
// Download component files
|
|
378
|
+
const downloadedFiles = await this.downloadComponentFiles(componentName, category, targetPath);
|
|
379
|
+
|
|
380
|
+
await this.updateLocalRegistrySafe(componentName, category);
|
|
381
|
+
|
|
382
|
+
Print.success(`${componentName} installed successfully from official repository!`);
|
|
383
|
+
console.log(`📁 Location: ${[folderSuffix, categoryPath, componentName].join('/').replace(/\/+/g, '/')}/`);
|
|
384
|
+
console.log(`📄 Files: ${downloadedFiles.join(', ')}`);
|
|
385
|
+
|
|
386
|
+
// Resolve and install what this component pulls in: other components via
|
|
387
|
+
// slice.build('X') or relative imports, and helper .js modules it imports.
|
|
388
|
+
if (withDeps) {
|
|
389
|
+
const mainJsPath = path.join(targetPath, `${componentName}.js`);
|
|
390
|
+
if (await fs.pathExists(mainJsPath)) {
|
|
391
|
+
const jsText = await fs.readFile(mainJsPath, 'utf8');
|
|
392
|
+
// Path of this file relative to the repo's Components root — the anchor
|
|
393
|
+
// for resolving relative imports. category ('Visual'|'Service') matches
|
|
394
|
+
// the repo folder layout used by the download URLs.
|
|
395
|
+
const repoRelPath = `${category}/${componentName}/${componentName}.js`;
|
|
396
|
+
await this.resolveDependencies(jsText, repoRelPath, seen, force);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
return true;
|
|
401
|
+
|
|
402
|
+
} catch (error) {
|
|
403
|
+
// Only clean up if main file (.js) does not exist
|
|
404
|
+
const mainFilePath = path.join(targetPath, `${componentName}.js`);
|
|
405
|
+
const mainFileExists = await fs.pathExists(mainFilePath);
|
|
406
|
+
|
|
407
|
+
if (!mainFileExists && await fs.pathExists(targetPath)) {
|
|
408
|
+
// Only clean up if main file was not installed
|
|
409
|
+
await fs.remove(targetPath);
|
|
410
|
+
} else if (mainFileExists) {
|
|
411
|
+
Print.warning('Component partially installed - main file exists');
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
throw error;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// Given the source of a just-installed module, install everything it needs.
|
|
419
|
+
// `repoRelPath` anchors relative-import resolution to the repo's Components root.
|
|
420
|
+
async resolveDependencies(jsText, repoRelPath, seen, force = false) {
|
|
421
|
+
const { builds, imports, bareImports } = analyzeSource(jsText);
|
|
422
|
+
|
|
423
|
+
// Bare (node_modules) imports can't be fetched from the registry — they are
|
|
424
|
+
// npm packages the user must install. Surface each one once.
|
|
425
|
+
for (const spec of bareImports || []) {
|
|
426
|
+
const root = spec.startsWith('@') ? spec.split('/').slice(0, 2).join('/') : spec.split('/')[0];
|
|
427
|
+
this._reportedExternal ??= new Set();
|
|
428
|
+
if (this._reportedExternal.has(root)) continue;
|
|
429
|
+
this._reportedExternal.add(root);
|
|
430
|
+
Print.warning(`↳ npm package required: "${root}" — install it in your project (e.g. "pnpm add ${root}")`);
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
// 1) Component dependencies via slice.build('X').
|
|
434
|
+
for (const name of builds) {
|
|
435
|
+
const info = this.findComponentInRegistry(name);
|
|
436
|
+
if (!info) continue; // structural/framework/unknown — nothing to fetch
|
|
437
|
+
if (!seen.has(`comp:${info.name}`)) {
|
|
438
|
+
Print.info(`↳ dependency: ${info.name} (${info.category})`);
|
|
439
|
+
}
|
|
440
|
+
await this.installComponent(info.name, info.category, force, { seen, withDeps: true, isDep: true });
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// 2) Relative imports: either another component's entrypoint, or a plain
|
|
444
|
+
// helper .js module living inside a component folder.
|
|
445
|
+
for (const spec of imports) {
|
|
446
|
+
const resolved = this.resolveRepoImportPath(repoRelPath, spec);
|
|
447
|
+
if (!resolved) continue;
|
|
448
|
+
|
|
449
|
+
const parts = resolved.split('/');
|
|
450
|
+
const fileBase = parts[parts.length - 1].replace(/\.js$/, '');
|
|
451
|
+
const folder = parts.length >= 2 ? parts[parts.length - 2] : '';
|
|
452
|
+
const info = this.findComponentInRegistry(fileBase);
|
|
453
|
+
|
|
454
|
+
// <Category>/<Name>/<Name>.js → a registered component (e.g. Pagination
|
|
455
|
+
// importing ../../Service/DataGridEngine/DataGridEngine.js).
|
|
456
|
+
if (info && folder === info.name) {
|
|
457
|
+
if (!seen.has(`comp:${info.name}`)) {
|
|
458
|
+
Print.info(`↳ dependency: ${info.name} (${info.category})`);
|
|
459
|
+
}
|
|
460
|
+
await this.installComponent(info.name, info.category, force, { seen, withDeps: true, isDep: true });
|
|
461
|
+
} else {
|
|
462
|
+
await this.installHelperFile(resolved, seen, force);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// Resolves an import specifier to a path relative to the repo Components root,
|
|
468
|
+
// or null if it isn't a fetchable in-repo JS module.
|
|
469
|
+
resolveRepoImportPath(fromRepoRelPath, spec) {
|
|
470
|
+
const dir = path.posix.dirname(fromRepoRelPath);
|
|
471
|
+
let resolved = path.posix.normalize(path.posix.join(dir, spec));
|
|
472
|
+
|
|
473
|
+
// Escapes the Components root (e.g. test fixtures) → not fetchable here.
|
|
474
|
+
if (resolved.startsWith('..') || path.posix.isAbsolute(resolved)) return null;
|
|
475
|
+
|
|
476
|
+
const ext = path.posix.extname(resolved);
|
|
477
|
+
if (!ext) {
|
|
478
|
+
resolved += '.js';
|
|
479
|
+
} else if (ext !== '.js') {
|
|
480
|
+
return null; // only JS modules are followed
|
|
481
|
+
}
|
|
482
|
+
return resolved;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// Downloads a single helper module (a non-component .js imported by a
|
|
486
|
+
// component) into its mirrored location, then follows its own dependencies.
|
|
487
|
+
async installHelperFile(repoRelPath, seen, force = false) {
|
|
488
|
+
const seenKey = `file:${repoRelPath}`;
|
|
489
|
+
if (seen.has(seenKey)) return;
|
|
490
|
+
seen.add(seenKey);
|
|
491
|
+
|
|
492
|
+
await this._ensureConfig();
|
|
493
|
+
const folderSuffix = this.config?.production?.enabled === true ? 'dist' : 'src';
|
|
494
|
+
const segments = repoRelPath.split('/');
|
|
495
|
+
const localPath = getPath(import.meta.url, folderSuffix, 'Components', ...segments);
|
|
496
|
+
|
|
497
|
+
if (await fs.pathExists(localPath) && !force) {
|
|
498
|
+
Print.info(`↳ helper module ${repoRelPath} already present — skipping`);
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
const url = `${DOCS_REPO_BASE_URL}/${repoRelPath}`;
|
|
503
|
+
let content;
|
|
504
|
+
try {
|
|
505
|
+
content = await fetchWithRetry(url, 3, 500, false);
|
|
506
|
+
} catch (error) {
|
|
507
|
+
Print.warning(`Could not download helper module '${repoRelPath}' — ${error.message}`);
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
await fs.ensureDir(path.dirname(localPath));
|
|
512
|
+
await fs.writeFile(localPath, content, 'utf8');
|
|
513
|
+
Print.registryUpdate(`↳ helper module ${repoRelPath}`);
|
|
514
|
+
|
|
515
|
+
// A helper can import further helpers or build components.
|
|
516
|
+
await this.resolveDependencies(content, repoRelPath, seen, force);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
async installMultipleComponents(componentNames, category = 'Visual', force = false, withDeps = true) {
|
|
520
|
+
const results = [];
|
|
521
|
+
// One shared visited-set so a dependency shared by several requested
|
|
522
|
+
// components (e.g. DataGridEngine under both Table and Pagination) installs once.
|
|
523
|
+
const seen = new Set();
|
|
524
|
+
Print.info(`Getting ${componentNames.length} ${category} components from official repository...`);
|
|
525
|
+
const total = componentNames.length;
|
|
526
|
+
let done = 0;
|
|
527
|
+
const spinner = ora(`Installing 0/${total}`).start();
|
|
528
|
+
const worker = async (componentName) => {
|
|
529
|
+
try {
|
|
530
|
+
const result = await this.installComponent(componentName, category, force, { seen, withDeps });
|
|
531
|
+
results.push({ name: componentName, success: result });
|
|
532
|
+
} catch (error) {
|
|
533
|
+
Print.componentError(componentName, 'getting', error.message);
|
|
534
|
+
results.push({ name: componentName, success: false, error: error.message });
|
|
535
|
+
} finally {
|
|
536
|
+
done += 1;
|
|
537
|
+
spinner.text = `Installing ${done}/${total}`;
|
|
538
|
+
}
|
|
539
|
+
};
|
|
540
|
+
await runConcurrent(componentNames, worker, 3);
|
|
541
|
+
spinner.stop();
|
|
542
|
+
|
|
543
|
+
// Summary
|
|
544
|
+
const successful = results.filter(r => r.success).length;
|
|
545
|
+
const failed = results.filter(r => !r.success).length;
|
|
546
|
+
|
|
547
|
+
Print.newLine();
|
|
548
|
+
Print.summary(successful, failed, componentNames.length);
|
|
549
|
+
|
|
550
|
+
return results;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
async updateAllComponents(force = false) {
|
|
554
|
+
Print.info('Looking for updatable Visual components...');
|
|
555
|
+
|
|
556
|
+
const allUpdatableComponents = await this.findUpdatableComponents();
|
|
557
|
+
|
|
558
|
+
// Filter only Visual components
|
|
559
|
+
const updatableComponents = allUpdatableComponents.filter(comp => comp.category === 'Visual');
|
|
560
|
+
|
|
561
|
+
if (updatableComponents.length === 0) {
|
|
562
|
+
Print.info('No local Visual components found that match the official repository');
|
|
563
|
+
Print.info('Use "slice browse" to see available components');
|
|
564
|
+
return true;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
// Show statistics if there are Service components that won't be synced
|
|
568
|
+
const serviceComponents = allUpdatableComponents.filter(comp => comp.category === 'Service');
|
|
569
|
+
if (serviceComponents.length > 0) {
|
|
570
|
+
Print.info(`Found ${serviceComponents.length} Service components (skipped - sync only affects Visual components)`);
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
Print.newLine();
|
|
574
|
+
Print.subtitle(`Found ${updatableComponents.length} updatable Visual components:`);
|
|
575
|
+
Print.newLine();
|
|
576
|
+
updatableComponents.forEach(comp => {
|
|
577
|
+
console.log(`🎨 ${comp.name} (${comp.category})`);
|
|
578
|
+
});
|
|
579
|
+
|
|
580
|
+
if (!force) {
|
|
581
|
+
const { confirmUpdate } = await inquirer.prompt([
|
|
582
|
+
{
|
|
583
|
+
type: 'confirm',
|
|
584
|
+
name: 'confirmUpdate',
|
|
585
|
+
message: `Do you want to update these Visual components to the repository versions?`,
|
|
586
|
+
default: true
|
|
587
|
+
}
|
|
588
|
+
]);
|
|
589
|
+
|
|
590
|
+
if (!confirmUpdate) {
|
|
591
|
+
Print.info('Update cancelled by user');
|
|
592
|
+
return false;
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
// Only update Visual components
|
|
597
|
+
const visualComponentNames = updatableComponents.map(c => c.name);
|
|
598
|
+
|
|
599
|
+
Print.info(`Updating ${visualComponentNames.length} Visual components...`);
|
|
600
|
+
const results = await this.installMultipleComponents(visualComponentNames, 'Visual', true);
|
|
601
|
+
|
|
602
|
+
// Final summary
|
|
603
|
+
const totalSuccessful = results.filter(r => r.success).length;
|
|
604
|
+
const totalFailed = results.filter(r => !r.success).length;
|
|
605
|
+
|
|
606
|
+
Print.newLine();
|
|
607
|
+
Print.title('Visual Components Sync Summary');
|
|
608
|
+
Print.success(`Visual components updated: ${totalSuccessful}`);
|
|
609
|
+
|
|
610
|
+
if (totalFailed > 0) {
|
|
611
|
+
Print.error(`Visual components failed: ${totalFailed}`);
|
|
612
|
+
} else {
|
|
613
|
+
Print.success('All your Visual components are now updated to the latest official versions!');
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
// Additional information about Service components
|
|
617
|
+
if (serviceComponents.length > 0) {
|
|
618
|
+
Print.newLine();
|
|
619
|
+
Print.info(`Note: ${serviceComponents.length} Service components were found but not updated`);
|
|
620
|
+
Print.info('Service components maintain manual versioning - update them individually if needed');
|
|
621
|
+
Print.commandExample('Update Service component manually', 'slice get FetchManager --service --force');
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
return totalFailed === 0;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
displayAvailableComponents() {
|
|
628
|
+
if (!this.componentsRegistry) {
|
|
629
|
+
Print.error('❌ Could not load component registry');
|
|
630
|
+
return;
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
console.log('\n📚 Available components in the official Slice.js repository:\n');
|
|
634
|
+
|
|
635
|
+
const visualComponents = this.getAvailableComponents('Visual');
|
|
636
|
+
const serviceComponents = this.getAvailableComponents('Service');
|
|
637
|
+
|
|
638
|
+
// Only show names without descriptions
|
|
639
|
+
Print.info('🎨 Visual Components (UI):');
|
|
640
|
+
Object.keys(visualComponents).forEach(name => {
|
|
641
|
+
const files = visualComponents[name].files;
|
|
642
|
+
const fileIcons = files.map(file => {
|
|
643
|
+
if (file.endsWith('.js')) return '📜';
|
|
644
|
+
if (file.endsWith('.html')) return '🌐';
|
|
645
|
+
if (file.endsWith('.css')) return '🎨';
|
|
646
|
+
return '📄';
|
|
647
|
+
}).join(' ');
|
|
648
|
+
console.log(` • ${name} ${fileIcons}`);
|
|
649
|
+
});
|
|
650
|
+
|
|
651
|
+
Print.info('\n⚙️ Service Components (Logic):');
|
|
652
|
+
Object.keys(serviceComponents).forEach(name => {
|
|
653
|
+
console.log(` • ${name} 📜`);
|
|
654
|
+
});
|
|
655
|
+
|
|
656
|
+
Print.newLine();
|
|
657
|
+
Print.info(`Total: ${Object.keys(visualComponents).length} Visual + ${Object.keys(serviceComponents).length} Service components`);
|
|
658
|
+
|
|
659
|
+
console.log(`\n💡 Usage examples:`);
|
|
660
|
+
console.log(`slice get Button Card Input # Install Visual components`);
|
|
661
|
+
console.log(`slice get FetchManager --service # Install Service component`);
|
|
662
|
+
console.log(`slice sync # Sync Visual components`);
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
async interactiveInstall() {
|
|
666
|
+
const { componentType } = await inquirer.prompt([
|
|
667
|
+
{
|
|
668
|
+
type: 'list',
|
|
669
|
+
name: 'componentType',
|
|
670
|
+
message: 'Select the type of component to install from the repository:',
|
|
671
|
+
choices: [
|
|
672
|
+
{ name: '🎨 Visual Components (UI)', value: 'Visual' },
|
|
673
|
+
{ name: '⚙️ Service Components (Logic)', value: 'Service' }
|
|
674
|
+
]
|
|
675
|
+
}
|
|
676
|
+
]);
|
|
677
|
+
|
|
678
|
+
const availableComponents = this.getAvailableComponents(componentType);
|
|
679
|
+
const componentChoices = Object.keys(availableComponents).map(name => ({
|
|
680
|
+
name: name,
|
|
681
|
+
value: name
|
|
682
|
+
}));
|
|
683
|
+
|
|
684
|
+
if (componentType === 'Visual') {
|
|
685
|
+
const { installMode } = await inquirer.prompt([
|
|
686
|
+
{
|
|
687
|
+
type: 'list',
|
|
688
|
+
name: 'installMode',
|
|
689
|
+
message: 'How do you want to install Visual components?',
|
|
690
|
+
choices: [
|
|
691
|
+
{ name: 'Get one', value: 'single' },
|
|
692
|
+
{ name: 'Get multiple', value: 'multiple' }
|
|
693
|
+
]
|
|
694
|
+
}
|
|
695
|
+
]);
|
|
696
|
+
|
|
697
|
+
if (installMode === 'multiple') {
|
|
698
|
+
const { selectedComponents } = await inquirer.prompt([
|
|
699
|
+
{
|
|
700
|
+
type: 'checkbox',
|
|
701
|
+
name: 'selectedComponents',
|
|
702
|
+
message: 'Select Visual components to install from the repository:',
|
|
703
|
+
choices: componentChoices,
|
|
704
|
+
validate: (input) => {
|
|
705
|
+
if (input.length === 0) {
|
|
706
|
+
return 'You must select at least one component';
|
|
707
|
+
}
|
|
708
|
+
return true;
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
]);
|
|
712
|
+
|
|
713
|
+
await this.installMultipleComponents(selectedComponents, componentType);
|
|
714
|
+
} else {
|
|
715
|
+
const { selectedComponent } = await inquirer.prompt([
|
|
716
|
+
{
|
|
717
|
+
type: 'list',
|
|
718
|
+
name: 'selectedComponent',
|
|
719
|
+
message: 'Select a Visual component:',
|
|
720
|
+
choices: componentChoices
|
|
721
|
+
}
|
|
722
|
+
]);
|
|
723
|
+
|
|
724
|
+
await this.installComponent(selectedComponent, componentType);
|
|
725
|
+
}
|
|
726
|
+
} else {
|
|
727
|
+
const { selectedComponent } = await inquirer.prompt([
|
|
728
|
+
{
|
|
729
|
+
type: 'list',
|
|
730
|
+
name: 'selectedComponent',
|
|
731
|
+
message: 'Select a Service component:',
|
|
732
|
+
choices: componentChoices
|
|
733
|
+
}
|
|
734
|
+
]);
|
|
735
|
+
|
|
736
|
+
await this.installComponent(selectedComponent, componentType);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
findComponentInRegistry(componentName) {
|
|
741
|
+
if (!this.componentsRegistry) return null;
|
|
742
|
+
|
|
743
|
+
const normalizedName = componentName.charAt(0).toUpperCase() + componentName.slice(1);
|
|
744
|
+
|
|
745
|
+
if (this.componentsRegistry[normalizedName]) {
|
|
746
|
+
return {
|
|
747
|
+
name: normalizedName,
|
|
748
|
+
category: this.componentsRegistry[normalizedName]
|
|
749
|
+
};
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
return null;
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
const sharedRegistry = new ComponentRegistry();
|
|
757
|
+
|
|
758
|
+
// Main get function
|
|
759
|
+
async function getComponents(componentNames = [], options = {}) {
|
|
760
|
+
try {
|
|
761
|
+
await sharedRegistry.loadRegistry();
|
|
762
|
+
} catch (error) {
|
|
763
|
+
Print.error('Could not load component registry from official repository');
|
|
764
|
+
Print.info('Check your internet connection and try again');
|
|
765
|
+
return false;
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
// Interactive mode if no components specified
|
|
769
|
+
if (!componentNames || componentNames.length === 0) {
|
|
770
|
+
await sharedRegistry.interactiveInstall();
|
|
771
|
+
return true;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
// Determine category
|
|
775
|
+
const category = options.service ? 'Service' : 'Visual';
|
|
776
|
+
|
|
777
|
+
// Dependency resolution is on by default; `slice get X --no-deps` opts out.
|
|
778
|
+
const withDeps = options.deps !== false;
|
|
779
|
+
|
|
780
|
+
if (componentNames.length === 1) {
|
|
781
|
+
// Single component install
|
|
782
|
+
const componentInfo = sharedRegistry.findComponentInRegistry(componentNames[0]);
|
|
783
|
+
|
|
784
|
+
if (!componentInfo) {
|
|
785
|
+
Print.error(`Component '${componentNames[0]}' not found in official repository`);
|
|
786
|
+
Print.commandExample('View available components', 'slice browse');
|
|
787
|
+
return false;
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
// Use the category from registry unless Service is explicitly requested
|
|
791
|
+
const actualCategory = options.service ? 'Service' : componentInfo.category;
|
|
792
|
+
|
|
793
|
+
try {
|
|
794
|
+
await sharedRegistry.installComponent(componentInfo.name, actualCategory, options.force, { seen: new Set(), withDeps });
|
|
795
|
+
return true;
|
|
796
|
+
} catch (error) {
|
|
797
|
+
Print.error(`Error installing component: ${error.message}`);
|
|
798
|
+
return false;
|
|
799
|
+
}
|
|
800
|
+
} else {
|
|
801
|
+
// Multiple components install
|
|
802
|
+
const normalizedComponents = componentNames.map(name =>
|
|
803
|
+
name.charAt(0).toUpperCase() + name.slice(1)
|
|
804
|
+
);
|
|
805
|
+
|
|
806
|
+
try {
|
|
807
|
+
await sharedRegistry.installMultipleComponents(normalizedComponents, category, options.force, withDeps);
|
|
808
|
+
return true;
|
|
809
|
+
} catch (error) {
|
|
810
|
+
Print.error(`Error installing components: ${error.message}`);
|
|
811
|
+
return false;
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
// List components function
|
|
817
|
+
async function listComponents() {
|
|
818
|
+
try {
|
|
819
|
+
await sharedRegistry.loadRegistry();
|
|
820
|
+
sharedRegistry.displayAvailableComponents();
|
|
821
|
+
return true;
|
|
822
|
+
} catch (error) {
|
|
823
|
+
Print.error('Could not load component registry from official repository');
|
|
824
|
+
Print.info('Check your internet connection and try again');
|
|
825
|
+
return false;
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
// Sync components function
|
|
830
|
+
async function syncComponents(options = {}) {
|
|
831
|
+
try {
|
|
832
|
+
await sharedRegistry.loadRegistry();
|
|
833
|
+
return await sharedRegistry.updateAllComponents(options.force);
|
|
834
|
+
} catch (error) {
|
|
835
|
+
Print.error('Could not load component registry from official repository');
|
|
836
|
+
Print.info('Check your internet connection and try again');
|
|
837
|
+
return false;
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
export default getComponents;
|
|
842
|
+
export { listComponents, syncComponents, ComponentRegistry, loadConfig, runConcurrent, fetchWithRetry };
|