-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-release-install.js
More file actions
311 lines (278 loc) · 10.9 KB
/
Copy pathtest-release-install.js
File metadata and controls
311 lines (278 loc) · 10.9 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
const fs = require('fs');
const os = require('os');
const path = require('path');
const { execFileSync } = require('child_process');
const rootDir = __dirname;
const packageJson = require(path.join(rootDir, 'package.json'));
const npmCommand = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const npmCliPath = [
process.env.npm_execpath,
path.join(path.dirname(process.execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js'),
path.join(path.dirname(process.execPath), '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'),
path.join(path.dirname(process.execPath), '..', 'node_modules', 'npm', 'bin', 'npm-cli.js')
].find((candidate) => candidate && fs.existsSync(candidate));
const semverPattern = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
const verificationEnvironmentNames = new Set([
'PATH', 'SystemRoot', 'ComSpec', 'PATHEXT', 'TEMP', 'TMP', 'TMPDIR',
'HOME', 'USERPROFILE', 'WINDIR', 'LANG', 'LC_ALL', 'TZ'
].map((name) => name.toUpperCase()));
function usage() {
return [
'Usage: node test-release-install.js --version <semver> --github-tarball <path.tgz>',
' [--npm-tarball <path.tgz>] [--registry <URL>] [--retries <integer>]',
' [--retry-delay-ms <integer>]'
].join('\n');
}
function parseArguments(argv) {
const values = {};
const knownOptions = new Set([
'--version',
'--github-tarball',
'--npm-tarball',
'--registry',
'--retries',
'--retry-delay-ms'
]);
for (let index = 0; index < argv.length; index += 1) {
const option = argv[index];
if (!knownOptions.has(option)) throw new Error(`Unknown argument: ${option}\n${usage()}`);
if (Object.prototype.hasOwnProperty.call(values, option)) {
throw new Error(`Argument provided more than once: ${option}\n${usage()}`);
}
const value = argv[index + 1];
if (!value || value.startsWith('--')) throw new Error(`Missing value for ${option}\n${usage()}`);
values[option] = value;
index += 1;
}
if (!values['--version']) throw new Error(`Missing required argument: --version\n${usage()}`);
if (!semverPattern.test(values['--version'])) {
throw new Error(`Invalid --version semver: ${values['--version']}`);
}
if (!values['--github-tarball']) {
throw new Error(`Missing required argument: --github-tarball\n${usage()}`);
}
const parseInteger = (option, fallback) => {
const value = values[option] ?? String(fallback);
if (!/^\d+$/.test(value)) throw new Error(`${option} must be a non-negative integer`);
return Number(value);
};
const registry = values['--registry'] || 'https://registry.npmjs.org';
let parsed;
try {
parsed = new URL(registry);
} catch (_) {
throw new Error('Invalid --registry URL');
}
if (!['http:', 'https:'].includes(parsed.protocol)) {
throw new Error('Invalid --registry URL: only http and https are supported');
}
if (parsed.username || parsed.password) {
throw new Error('Invalid --registry URL: username and password are not allowed');
}
return {
version: values['--version'],
githubTarball: values['--github-tarball'],
npmTarball: values['--npm-tarball'],
registry,
retries: parseInteger('--retries', 5),
retryDelayMs: parseInteger('--retry-delay-ms', 10000)
};
}
function resolveTarball(tarballPath, channel) {
const resolvedPath = path.resolve(process.cwd(), tarballPath);
if (!resolvedPath.toLowerCase().endsWith('.tgz')) {
throw new Error(`${channel} tarball must end with .tgz: ${tarballPath}`);
}
if (!fs.existsSync(resolvedPath) || !fs.statSync(resolvedPath).isFile()) {
throw new Error(`${channel} tarball does not exist: ${resolvedPath}`);
}
return resolvedPath;
}
function redactSecrets(value, environment = process.env) {
let redacted = String(value);
const sensitiveValues = Object.entries(environment)
.filter(([name, environmentValue]) => (
!verificationEnvironmentNames.has(name.toUpperCase()) &&
typeof environmentValue === 'string' &&
environmentValue.length > 0
))
.map(([, environmentValue]) => String(environmentValue))
.sort((left, right) => right.length - left.length);
for (const sensitiveValue of sensitiveValues) {
redacted = redacted.split(sensitiveValue).join('[REDACTED]');
}
return redacted.replace(/(https?:\/\/)[^\s/@]*:[^\s/@]*@/gi, '$1[REDACTED]@');
}
function summarizeNpmError(error) {
return [error.message, error.stdout, error.stderr]
.filter(Boolean)
.map((value) => redactSecrets(value).trim())
.filter(Boolean)
.join('\n');
}
function createVerificationEnvironment(environment = process.env) {
return Object.fromEntries(
Object.entries(environment).filter(([name]) => verificationEnvironmentNames.has(name.toUpperCase()))
);
}
function runNpm(tempDir, registry, args, cwd) {
const command = npmCliPath ? process.execPath : npmCommand;
const commandArgs = npmCliPath ? [npmCliPath, ...args] : args;
try {
return execFileSync(command, commandArgs, {
cwd,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
env: {
...process.env,
npm_config_cache: path.join(tempDir, 'npm-cache'),
npm_config_registry: registry,
npm_config_fetch_timeout: '30000',
npm_config_fetch_retries: '1',
npm_config_update_notifier: 'false',
npm_config_fund: 'false'
}
});
} catch (error) {
throw new Error(`npm ${args.join(' ')} failed:\n${summarizeNpmError(error)}`);
}
}
function installSource(tempDir, registry, consumerDir, source) {
const args = [
'install',
'--no-save',
'--package-lock=false',
'--ignore-scripts',
'--omit=peer',
'--legacy-peer-deps',
'--no-audit',
'--no-fund'
];
args.push(source);
runNpm(tempDir, registry, args, consumerDir);
}
function installFromNpm(tempDir, options, consumerDir) {
const source = options.npmTarball
? resolveTarball(options.npmTarball, 'npm channel')
: `${packageJson.name}@${options.version}`;
let lastError;
for (let attempt = 0; attempt <= options.retries; attempt += 1) {
try {
// Local tarballs still need registry resolution for runtime dependencies.
installSource(tempDir, options.registry, consumerDir, source);
return;
} catch (error) {
lastError = error;
if (attempt === options.retries) break;
if (options.retryDelayMs > 0) {
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, options.retryDelayMs);
}
}
}
throw new Error(`npm channel installation failed after ${options.retries + 1} attempt(s):\n${lastError.message}`);
}
function installFromTarball(tempDir, options, consumerDir) {
const tarball = resolveTarball(options.githubTarball, 'GitHub channel');
try {
// The release asset is local, while package dependencies are resolved from
// the registry just like a real GitHub tarball installation.
installSource(tempDir, options.registry, consumerDir, tarball);
} catch (error) {
throw new Error(`GitHub channel installation failed:\n${error.message}`);
}
}
function verifyInstalledPackage(channel, consumerDir, version) {
const installedRoot = path.join(consumerDir, 'node_modules', packageJson.name);
const fail = (message) => {
throw new Error(`${channel} channel verification failed: ${message}`);
};
if (!fs.existsSync(installedRoot)) fail(`installed package is missing: ${installedRoot}`);
const verificationEnv = createVerificationEnvironment();
try {
const entrySmokeScript = [
'const installedRoot = process.argv[1];',
'const plugin = require(installedRoot);',
"if (plugin.name !== 'memory' || typeof plugin.apply !== 'function') {",
" throw new Error('package does not expose the DSH plugin API');",
'}'
].join('\n');
execFileSync(process.execPath, ['-e', entrySmokeScript, installedRoot], {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
env: verificationEnv,
cwd: consumerDir
});
} catch (error) {
fail(`package could not be loaded: ${error.message}`);
}
let installedPackage;
try {
installedPackage = JSON.parse(fs.readFileSync(path.join(installedRoot, 'package.json'), 'utf8'));
} catch (error) {
fail(`package.json could not be loaded: ${error.message}`);
}
if (installedPackage.version !== version) {
fail(`expected version ${version}, received ${installedPackage.version}`);
}
if (!installedPackage.dsh || !installedPackage.dsh.bundle || !installedPackage.dsh.bundle.patch) {
fail('package is missing dsh.bundle.patch metadata');
}
const patchPath = path.join(installedRoot, installedPackage.dsh.bundle.patch);
if (!fs.existsSync(patchPath)) fail(`bundle patch is missing: ${installedPackage.dsh.bundle.patch}`);
for (const file of ['dsh-memory-plugin.js', 'profile-doctor.js']) {
const filePath = file === 'dsh-memory-plugin.js'
? path.join(installedRoot, 'bin', file)
: path.join(installedRoot, file);
if (!fs.existsSync(filePath)) fail(`required CLI file is missing: ${file}`);
}
try {
const doctorHelp = execFileSync(
process.execPath,
[path.join(installedRoot, 'bin', 'dsh-memory-plugin.js'), 'doctor', '--help'],
{
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
env: verificationEnv,
cwd: consumerDir
}
);
if (!doctorHelp.includes('dsh-memory-plugin doctor')) {
fail('doctor --help does not expose its expected help text');
}
} catch (error) {
fail(`doctor --help failed: ${summarizeNpmError(error)}`);
}
for (const viewerFile of ['viewer.html', 'premium-viewer.html', 'open-viewer.cmd']) {
if (!fs.existsSync(path.join(installedRoot, viewerFile))) {
fail(`web viewer file is missing: ${viewerFile}`);
}
}
}
function main() {
const options = parseArguments(process.argv.slice(2));
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memory-release-install-'));
const npmConsumerDir = path.join(tempDir, 'npm-consumer');
const githubConsumerDir = path.join(tempDir, 'github-consumer');
try {
fs.mkdirSync(npmConsumerDir, { recursive: true });
fs.mkdirSync(githubConsumerDir, { recursive: true });
installFromNpm(tempDir, options, npmConsumerDir);
verifyInstalledPackage('npm', npmConsumerDir, options.version);
console.log(`npm channel passed: ${packageJson.name}@${options.version}`);
installFromTarball(tempDir, options, githubConsumerDir);
verifyInstalledPackage('GitHub', githubConsumerDir, options.version);
console.log(`GitHub channel passed: ${packageJson.name}@${options.version}`);
console.log(`Release installation verification passed: ${packageJson.name}@${options.version}`);
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}
if (require.main === module) {
try {
main();
} catch (error) {
console.error(`Release installation verification failed: ${error.message}`);
process.exitCode = 1;
}
}
module.exports = { createVerificationEnvironment, redactSecrets };