-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinstall-plugin-files-v005.js
More file actions
412 lines (341 loc) Β· 12.8 KB
/
Copy pathinstall-plugin-files-v005.js
File metadata and controls
412 lines (341 loc) Β· 12.8 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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
#!/usr/bin/env node
/**
* Install Plugin Files - Self-Installing Script
*
* This script automatically installs its own dependencies on first run.
*
* Usage:
* node install-plugin-files.js @wix/vibe-stores-plugin@0.8.8 ./output
* node install-plugin-files.js https://github.com/.../plugin.tar.gz ./output
*
* Dependencies are installed to ./.deps/ directory automatically.
*/
const https = require('https');
const http = require('http');
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
// Self-install dependencies
// Use process.cwd() when running from stdin (node -), otherwise use script directory
const scriptDir = __dirname === '.' ? process.cwd() : __dirname;
const DEPS_DIR = path.join(scriptDir, '.deps');
const REQUIRED_PACKAGES = ['adm-zip'];
function ensureDependencies() {
const needsInstall = REQUIRED_PACKAGES.some(pkg => {
try {
require.resolve(pkg);
return false;
} catch {
return true;
}
});
if (needsInstall) {
console.log('π¦ Installing dependencies...');
console.log(' π Installing to:', DEPS_DIR);
if (!fs.existsSync(DEPS_DIR)) {
fs.mkdirSync(DEPS_DIR, { recursive: true });
}
// Create a minimal package.json to isolate from parent project
const packageJsonPath = path.join(DEPS_DIR, 'package.json');
if (!fs.existsSync(packageJsonPath)) {
fs.writeFileSync(packageJsonPath, JSON.stringify({
name: 'install-plugin-files-deps',
version: '1.0.0',
private: true
}, null, 2));
}
try {
execSync(
`cd "${DEPS_DIR}" && npm install ${REQUIRED_PACKAGES.join(' ')} --legacy-peer-deps --loglevel=error`,
{ stdio: 'inherit' }
);
console.log('β
Dependencies installed\n');
} catch (err) {
console.error('β Failed to install dependencies');
console.error(' Tip: You can pre-install adm-zip to avoid this:');
console.error(' npm install -g adm-zip');
console.error(' or: npm install adm-zip (in your project)');
process.exit(1);
}
}
// Add deps to require path
const nodeModulesPath = path.join(DEPS_DIR, 'node_modules');
if (fs.existsSync(nodeModulesPath)) {
require('module').globalPaths.unshift(nodeModulesPath);
}
}
// Ensure dependencies before loading them
ensureDependencies();
// Try to require adm-zip from multiple locations
let AdmZip;
try {
AdmZip = require('adm-zip');
} catch {
try {
// Try from deps directory
AdmZip = require(path.join(DEPS_DIR, 'node_modules', 'adm-zip'));
} catch (err) {
console.error('β Failed to load adm-zip module:', err.message);
console.error(' Tip: Try installing adm-zip globally: npm install -g adm-zip');
process.exit(1);
}
}
// Parse arguments
const [pluginSpecifier, destDir] = process.argv.slice(2);
if (!pluginSpecifier || !destDir) {
console.error('β Error: Plugin specifier and destination directory are required');
console.error('Usage: node install-plugin-files.js <package@version|tarball-url> <dest-dir>');
console.error('Example: node install-plugin-files.js @wix/vibe-stores-plugin@0.8.8 ./output');
process.exit(1);
}
console.log('π Starting plugin files installation...');
console.log('π¦ Plugin:', pluginSpecifier);
console.log('π Destination:', destDir);
console.log('');
function downloadFile(url, outputPath, callback) {
const client = url.startsWith('https') ? https : http;
const request = client.get(url, (res) => {
if (res.statusCode === 301 || res.statusCode === 302) {
console.log(' βͺοΈ Following redirect:', res.headers.location);
return downloadFile(res.headers.location, outputPath, callback);
}
if (res.statusCode !== 200) {
console.error(' β Download failed with status:', res.statusCode);
console.error(' URL:', url);
process.exit(1);
}
console.log(' β
Response status:', res.statusCode);
const fileStream = fs.createWriteStream(outputPath);
fileStream.on('error', (err) => {
console.error(' β File write error:', err.message);
console.error(' Path:', outputPath);
try { fs.unlinkSync(outputPath); } catch {}
process.exit(1);
});
res.on('error', (err) => {
console.error(' β Download stream error:', err.message);
try { fs.unlinkSync(outputPath); } catch {}
process.exit(1);
});
res.pipe(fileStream).on('finish', callback);
});
request.on('error', (err) => {
console.error(' β Network error:', err.message);
console.error(' URL:', url);
console.error(' Tip: Check your internet connection and firewall settings');
process.exit(1);
});
request.setTimeout(30000, () => {
request.destroy();
console.error(' β Download timeout (30s)');
console.error(' URL:', url);
process.exit(1);
});
}
function extractZip(zipPath, destDir) {
console.log(' π Extracting ZIP...');
let zip;
try {
zip = new AdmZip(zipPath);
} catch (err) {
console.error(' β Failed to read ZIP file:', err.message);
console.error(' Path:', zipPath);
console.error(' Tip: The downloaded file might be corrupted');
process.exit(1);
}
const entries = zip.getEntries();
if (entries.length === 0) {
console.error(' β ZIP file is empty');
process.exit(1);
}
let count = 0;
entries.forEach((entry) => {
if (!entry.isDirectory) {
try {
const relativePath = entry.entryName.replace(/^[^\/]+\//, '');
const targetPath = path.join(destDir, relativePath);
fs.mkdirSync(path.dirname(targetPath), { recursive: true });
fs.writeFileSync(targetPath, entry.getData());
count++;
console.log(' β', relativePath);
} catch (err) {
console.error(' β Failed to extract:', entry.entryName);
console.error(' Error:', err.message);
// Continue with other files
}
}
});
if (count === 0) {
console.error(' β No files were extracted');
process.exit(1);
}
return count;
}
function processPlugin(packageJson) {
try {
if (!packageJson || !packageJson.name) {
console.error('β Invalid package.json');
process.exit(1);
}
console.log('β
Plugin found:', packageJson.name + '@' + packageJson.version);
console.log('');
const pluginFilesPackageName = packageJson.name.replace('-plugin', '-plugin-files');
console.log('π Looking for dependency:', pluginFilesPackageName);
if (!packageJson.dependencies) {
console.error('β No dependencies found in package.json');
console.error(' Tip: Make sure this is a valid Vibe plugin package');
process.exit(1);
}
const depVersion = packageJson.dependencies[pluginFilesPackageName];
if (!depVersion) {
console.error('β Dependency not found:', pluginFilesPackageName);
console.error(' Available dependencies:', Object.keys(packageJson.dependencies).join(', '));
process.exit(1);
}
console.log(' π Raw version:', depVersion);
const version = depVersion
.replace(/^workspace:/, '')
.replace(/^https?:\/\/.+\/(.+)\.tar\.gz$/, '$1');
console.log(' π Resolved version:', version);
const match = packageJson.name.match(/@wix\/vibe-(.+)-plugin/);
if (!match) {
console.error('β Could not parse plugin name from:', packageJson.name);
console.error(' Expected format: @wix/vibe-XXX-plugin');
process.exit(1);
}
const shortName = match[1];
console.log(' π Plugin short name:', shortName);
const zipUrl = `https://static.parastorage.com/services/vibe-${shortName}-plugin-files/${version}/vibe-${shortName}-plugin-files-files.zip`;
console.log('');
console.log('π₯ Downloading plugin-files ZIP...');
console.log(' π URL:', zipUrl);
const zipPath = shortName + '.zip';
downloadFile(zipUrl, zipPath, () => {
try {
const stats = fs.statSync(zipPath);
console.log(' β
Downloaded:', (stats.size / 1024 / 1024).toFixed(2), 'MB');
console.log('');
console.log('π Extracting plugin files...');
const count = extractZip(zipPath, destDir);
try {
fs.unlinkSync(zipPath);
} catch (err) {
console.warn(' β οΈ Could not clean up ZIP file:', zipPath);
}
console.log(' β
Total files extracted:', count);
console.log('');
console.log('β¨ Done! All files extracted to:', destDir);
} catch (err) {
console.error('β Error processing downloaded file:', err.message);
process.exit(1);
}
});
} catch (err) {
console.error('β Error processing plugin:', err.message);
console.error('Stack:', err.stack);
process.exit(1);
}
}
// Main execution
if (pluginSpecifier.startsWith('http')) {
console.log('π₯ Mode: Tarball URL');
console.log('π Downloading plugin tarball...');
console.log(' π URL:', pluginSpecifier);
const tgzPath = 'plugin.tgz';
downloadFile(pluginSpecifier, tgzPath, () => {
try {
const stats = fs.statSync(tgzPath);
console.log(' β
Downloaded:', (stats.size / 1024 / 1024).toFixed(2), 'MB');
console.log('π¦ Extracting tarball...');
try {
execSync('tar -xzf ' + tgzPath, { stdio: 'pipe' });
console.log(' β
Tarball extracted');
} catch (err) {
console.error(' β Failed to extract tarball:', err.message);
console.error(' Tip: Make sure tar is installed on your system');
try { fs.unlinkSync(tgzPath); } catch {}
process.exit(1);
}
console.log('π Reading package.json...');
let packageJson;
try {
packageJson = JSON.parse(fs.readFileSync('package/package.json', 'utf8'));
} catch (err) {
console.error(' β Failed to read package.json:', err.message);
console.error(' Tip: The tarball might not contain a valid package.json');
try { fs.unlinkSync(tgzPath); } catch {}
try { fs.rmSync('package', { recursive: true }); } catch {}
process.exit(1);
}
try {
fs.unlinkSync(tgzPath);
fs.rmSync('package', { recursive: true });
} catch (err) {
console.warn(' β οΈ Could not clean up temporary files');
}
console.log(' β
Package.json loaded');
console.log('');
processPlugin(packageJson);
} catch (err) {
console.error('β Unexpected error:', err.message);
process.exit(1);
}
});
} else {
console.log('π₯ Mode: NPM Registry');
const match = pluginSpecifier.match(/^(@[^/]+\/[^@]+)(?:@(.+))?$/);
if (!match) {
console.error('β Invalid package specifier:', pluginSpecifier);
console.error(' Expected format: @scope/package@version');
console.error(' Example: @wix/vibe-stores-plugin@0.8.8');
process.exit(1);
}
const packageName = match[1];
const version = match[2] || 'latest';
console.log(' π¦ Package name:', packageName);
console.log(' π Version:', version);
const registryUrl = `https://registry.npmjs.org/${packageName.replace('/', '%2F')}/${version}`;
console.log('π Fetching metadata from npm...');
console.log(' π URL:', registryUrl);
const request = https.get(registryUrl, (res) => {
console.log(' β
Response status:', res.statusCode);
if (res.statusCode === 404) {
console.error(' β Package not found:', packageName + '@' + version);
console.error(' Tip: Check the package name and version');
process.exit(1);
}
if (res.statusCode !== 200) {
console.error(' β Failed to fetch package metadata (status:', res.statusCode + ')');
process.exit(1);
}
let data = '';
res.on('data', chunk => data += chunk);
res.on('error', (err) => {
console.error(' β Error reading response:', err.message);
process.exit(1);
});
res.on('end', () => {
try {
console.log(' β
Metadata received:', (data.length / 1024).toFixed(2), 'KB');
console.log('');
const packageJson = JSON.parse(data);
processPlugin(packageJson);
} catch (err) {
console.error(' β Failed to parse npm response:', err.message);
console.error(' Tip: The npm registry might be unavailable');
process.exit(1);
}
});
});
request.on('error', (err) => {
console.error(' β Network error:', err.message);
console.error(' Tip: Check your internet connection');
process.exit(1);
});
request.setTimeout(30000, () => {
request.destroy();
console.error(' β Request timeout (30s)');
console.error(' Tip: npm registry might be slow or unavailable');
process.exit(1);
});
}