vercel 28.6.0 → 28.7.1

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.
@@ -0,0 +1,186 @@
1
+ /**
2
+ * This file is spawned in the background and checks npm for the latest version
3
+ * of the CLI, then writes the version to the cache file.
4
+ *
5
+ * NOTE: Since this file runs asynchronously in the background, it's possible
6
+ * for multiple instances of this file to be running at the same time leading
7
+ * to a race condition where the most recent instance will overwrite the
8
+ * previous cache file resetting the `notified` flag and cause the update
9
+ * notification to appear for multiple consequetive commands. Not the end of
10
+ * the world, but something to be aware of.
11
+ */
12
+
13
+ const fetch = require('node-fetch');
14
+ const fs = require('fs-extra');
15
+ const path = require('path');
16
+ const { Agent: HttpsAgent } = require('https');
17
+ const { bold, gray, red } = require('chalk');
18
+ const { format, inspect } = require('util');
19
+
20
+ /**
21
+ * An simple output helper which accumulates error and debug log messages in
22
+ * memory for potential persistance to disk while immediately outputting errors
23
+ * and debug messages, when the `--debug` flag is set, to `stderr`.
24
+ */
25
+ class WorkerOutput {
26
+ debugLog = [];
27
+ logFile = null;
28
+
29
+ constructor({ debug = true }) {
30
+ this.debugOutputEnabled = debug;
31
+ }
32
+
33
+ debug(...args) {
34
+ this.print('debug', args);
35
+ }
36
+
37
+ error(...args) {
38
+ this.print('error', args);
39
+ }
40
+
41
+ print(type, args) {
42
+ const str = format(
43
+ ...args.map(s => (typeof s === 'string' ? s : inspect(s)))
44
+ );
45
+ this.debugLog.push(`[${new Date().toISOString()}] [${type}] ${str}`);
46
+ if (type === 'debug' && this.debugOutputEnabled) {
47
+ console.error(
48
+ `${gray('>')} ${bold('[debug]')} ${gray(
49
+ `[${new Date().toISOString()}]`
50
+ )} ${str}`
51
+ );
52
+ } else if (type === 'error') {
53
+ console.error(`${red(`Error:`)} ${str}`);
54
+ }
55
+ }
56
+
57
+ setLogFile(file) {
58
+ // wire up the exit handler the first time the log file is set
59
+ if (this.logFile === null) {
60
+ process.on('exit', () => {
61
+ if (this.debugLog.length) {
62
+ fs.outputFileSync(this.logFile, this.debugLog.join('\n'));
63
+ }
64
+ });
65
+ }
66
+ this.logFile = file;
67
+ }
68
+ }
69
+
70
+ const output = new WorkerOutput({
71
+ // enable the debug logging if the `--debug` is set or if this worker script
72
+ // was directly executed
73
+ debug: process.argv.includes('--debug') || !process.connected,
74
+ });
75
+
76
+ process.on('unhandledRejection', err => {
77
+ output.error('Exiting worker due to unhandled rejection:', err);
78
+ process.exit(1);
79
+ });
80
+
81
+ // this timer will prevent this worker process from running longer than 10s
82
+ const timer = setTimeout(() => {
83
+ output.error('Worker timed out after 10 seconds');
84
+ process.exit(1);
85
+ }, 10000);
86
+
87
+ // wait for the parent to give us the work payload
88
+ process.once('message', async msg => {
89
+ output.debug('Received message from parent:', msg);
90
+
91
+ output.debug('Disconnecting from parent');
92
+ process.disconnect();
93
+
94
+ const { cacheFile, distTag, name, updateCheckInterval } = msg;
95
+ const cacheFileParsed = path.parse(cacheFile);
96
+ await fs.mkdirp(cacheFileParsed.dir);
97
+
98
+ output.setLogFile(
99
+ path.join(cacheFileParsed.dir, `${cacheFileParsed.name}.log`)
100
+ );
101
+
102
+ const lockFile = path.join(
103
+ cacheFileParsed.dir,
104
+ `${cacheFileParsed.name}.lock`
105
+ );
106
+
107
+ try {
108
+ // check for a lock file and either bail if running or write our pid and continue
109
+ output.debug(`Checking lock file: ${lockFile}`);
110
+ if (await isRunning(lockFile)) {
111
+ output.debug('Worker already running, exiting');
112
+ process.exit(1);
113
+ }
114
+ output.debug(`Initializing lock file with pid ${process.pid}`);
115
+ await fs.writeFile(lockFile, String(process.pid), 'utf-8');
116
+
117
+ // fetch the latest version from npm
118
+ const agent = new HttpsAgent({
119
+ keepAlive: true,
120
+ maxSockets: 15, // See: `npm config get maxsockets`
121
+ });
122
+ const headers = {
123
+ accept:
124
+ 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*',
125
+ };
126
+ const url = `https://registry.npmjs.org/${name}`;
127
+ output.debug(`Fetching ${url}`);
128
+ const res = await fetch(url, { agent, headers });
129
+ const json = await res.json();
130
+ const tags = json['dist-tags'];
131
+ const version = tags[distTag];
132
+
133
+ if (version) {
134
+ output.debug(`Found dist tag "${distTag}" with version "${version}"`);
135
+ } else {
136
+ output.error(`Dist tag "${distTag}" not found`);
137
+ output.debug('Available dist tags:', Object.keys(tags));
138
+ }
139
+
140
+ output.debug(`Writing cache file: ${cacheFile}`);
141
+ await fs.outputJSON(cacheFile, {
142
+ expireAt: Date.now() + updateCheckInterval,
143
+ notified: false,
144
+ version,
145
+ });
146
+ } catch (err) {
147
+ output.error(`Failed to get package info:`, err);
148
+ } finally {
149
+ clearTimeout(timer);
150
+
151
+ output.debug(`Releasing lock file: ${lockFile}`);
152
+ await fs.remove(lockFile);
153
+
154
+ output.debug(`Worker finished successfully!`);
155
+
156
+ // force the worker to exit
157
+ process.exit(0);
158
+ }
159
+ });
160
+
161
+ // signal the parent process we're ready
162
+ if (process.connected) {
163
+ output.debug("Notifying parent we're ready");
164
+ process.send({ type: 'ready' });
165
+ } else {
166
+ console.error('No IPC bridge detected, exiting');
167
+ process.exit(1);
168
+ }
169
+
170
+ async function isRunning(lockFile) {
171
+ try {
172
+ const pid = parseInt(await fs.readFile(lockFile, 'utf-8'));
173
+ output.debug(`Found lock file with pid: ${pid}`);
174
+
175
+ // checks for existence of a process; throws if not found
176
+ process.kill(pid, 0);
177
+
178
+ // process is still running
179
+ return true;
180
+ } catch (err) {
181
+ // lock file does not exist or process is not running and pid is stale
182
+ output.debug(`Resetting lock file: ${err.toString()}`);
183
+ await fs.remove(lockFile);
184
+ return false;
185
+ }
186
+ }