-
Notifications
You must be signed in to change notification settings - Fork 522
/
index.js
262 lines (214 loc) · 7.89 KB
/
index.js
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
/**
* @license
* Copyright 2020 The Bazel Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const path = require('path');
const rollup = require('rollup');
const crypto = require('crypto')
const MNEMONIC = 'Rollup';
const PID = process.pid;
let worker;
try {
worker = require('./worker');
} catch {
// TODO: rely on the linker to link the first-party package
const helper = process.env['BAZEL_NODE_RUNFILES_HELPER'];
if (!helper) throw new Error('No runfiles helper and no @bazel/worker npm package');
const runfiles = require(helper);
const workerRequire = runfiles.resolve('build_bazel_rules_nodejs/packages/rollup/worker.js');
if (!workerRequire)
throw new Error(`build_bazel_rules_nodejs/packages/rollup/worker.js missing in runfiles ${
JSON.stringify(runfiles.manifest)}, ${runfiles.dir}`);
worker = require(workerRequire);
}
// Store the cache forever to re-use on each build
let cacheMap = Object.create(null);
// Generate a unique cache ID based on the given json data
function computeCacheKey(cacheKeyData) {
const hash = crypto.createHash('sha256');
const hashContent = JSON.stringify(cacheKeyData);
return hash.update(hashContent).digest('hex');
}
async function runRollup(cacheKeyData, inputOptions, outputOptions) {
const cacheKey = computeCacheKey(cacheKeyData);
let cache = cacheMap[cacheKey];
const rollupStartTime = Date.now();
const bundle = await rollup.rollup({...inputOptions, cache});
const rollupEndTime = Date.now();
worker.debug(
`${MNEMONIC}[${PID}][${cacheKey}].rollup()`, (rollupEndTime - rollupStartTime) / 1000);
cacheMap[cacheKey] = bundle.cache;
try {
await bundle.write(outputOptions);
} catch (e) {
worker.log(e);
return false;
}
const bundleEndTime = Date.now();
worker.debug(`${MNEMONIC}[${PID}][${cacheKey}].write()`, (bundleEndTime - rollupEndTime) / 1000);
return true;
}
// Run rollup, will use + re-populate the cache
async function runRollupBundler(args /*, inputs */) {
const {inputOptions, outputOptions} = await parseCLIArgs(args);
return runRollup(inputOptions.input, inputOptions, outputOptions);
}
// Load the config file.
// Must be rollup-ed first to allow use of es6 within the config.
// See the rollup CLI version:
// https://github.com/rollup/rollup/blob/v1.31.0/cli/run/loadConfigFile.ts#L14
async function loadConfigFile(configFile) {
const cjsConfigFile = configFile + '.cjs.js';
// inputOptions: https://github.com/rollup/rollup/blob/v1.31.0/cli/run/loadConfigFile.ts#L21-L28
const inputOptions = {
external: id => (id[0] !== '.' && !path.isAbsolute(id)) || id.slice(-5, id.length) === '.json',
input: configFile,
treeshake: false,
preserveSymlinks: true,
};
// outputOptions: https://github.com/rollup/rollup/blob/v1.31.0/cli/run/loadConfigFile.ts#L35-L38
const outputOptions = {
exports: 'named',
format: 'cjs',
file: cjsConfigFile,
};
await runRollup(configFile, inputOptions, outputOptions);
// Ensure node isn't caching a previous version of the config file
// https://github.com/rollup/rollup/blob/v1.31.0/cli/run/loadConfigFile.ts#L52
delete require.cache[require.resolve(cjsConfigFile)];
// Read the config file:
// https://github.com/rollup/rollup/blob/v1.31.0/cli/run/loadConfigFile.ts#L54-L61
//
// Supports:
// * async results
// * commonjs "default" export
let config = await Promise.resolve(require(cjsConfigFile));
if (config.default) {
config = config.default;
}
// Does NOT support (unlike rollup CLI):
// * factory function
// * multiple configs for multiple outputs
if (Array.isArray(config) || typeof config === 'function') {
throw new Error('Arrays + factory configs unsupported');
}
return config;
}
// Processing of --environment CLI options into environment vars
// https://github.com/rollup/rollup/blob/v1.31.0/cli/run/index.ts#L50-L57
function extractEnvironmentVariables(vars) {
vars.split(',').forEach(pair => {
const [key, ...value] = pair.split(':');
if (value.length) {
process.env[key] = value.join(':');
} else {
process.env[key] = String(true);
}
});
}
// Parse a subset of supported CLI arguments required for the rollup_bundle rule API.
// Returns input/outputOptions for the rollup.bundle/write() API
// input: https://rollupjs.org/guide/en/#inputoptions-object
// output: https://rollupjs.org/guide/en/#outputoptions-object
async function parseCLIArgs(args) {
let inputOptions = {
onwarn(...warnArgs) {
worker.log(...warnArgs);
},
};
let outputOptions = {};
let configFile = null;
// Input files to rollup
let inputs = [];
// Followed by suppported rollup CLI options
for (let i = 0; i < args.length; i++) {
const arg = args[i];
// Non-option is assumed to be an input file
if (!arg.startsWith('--')) {
inputs.push(arg);
continue;
}
const option = arg.slice(2);
switch (option) {
case 'config':
configFile = path.resolve(args[++i]);
break;
case 'silent':
inputOptions.onwarn = () => {};
break;
case 'format':
case 'output.dir':
case 'output.file':
case 'sourcemap':
outputOptions[option.replace('output.', '')] = args[++i];
break;
case 'preserveSymlinks':
inputOptions[option] = true;
break;
// Common rollup CLI args, but not required for use
case 'environment':
extractEnvironmentVariables(args[++i]);
break;
default:
throw new Error(`${MNEMONIC}: invalid or unsupported argument ${arg}`);
}
}
// If outputting a directory then rollup_bundle.bzl passed a series
// of name=path files as the input.
// TODO: do some not have the =?
if (outputOptions.dir) {
inputs = inputs.reduce((m, nameInput) => {
const [name, input] = nameInput.split('=', 2);
m[name] = input;
return m;
}, {});
}
// Additional options passed via config file
if (configFile) {
const config = await loadConfigFile(configFile);
if (config.output) {
outputOptions = {...config.output, ...outputOptions};
}
inputOptions = {...config, ...inputOptions};
// Delete from our copied inputOptions, not the config which
// may be external and persisted across runs
delete inputOptions.output;
}
// The inputs are the rule entry_point[s]
inputOptions.input = inputs;
return {inputOptions, outputOptions};
}
async function main(args) {
// Bazel will pass a special argument to the program when it's running us as a worker
if (worker.runAsWorker(args)) {
worker.log(`Running ${MNEMONIC} as a Bazel worker`);
worker.runWorkerLoop(runRollupBundler);
} else {
// Running standalone so stdout is available as usual
console.log(`Running ${MNEMONIC} as a standalone process`);
console.error(
`Started a new process to perform this action. Your build might be misconfigured, try
--strategy=${MNEMONIC}=worker`);
// Parse the options from the bazel-supplied options file.
// The first argument to the program is prefixed with '@'
// because Bazel does that for param files. Strip it first.
const paramFile = process.argv[2].replace(/^@/, '');
const args = require('fs').readFileSync(paramFile, 'utf-8').trim().split('\n');
return (await runRollupBundler(args)) ? 0 : 1;
}
}
if (require.main === module) {
main(process.argv.slice(2)).then(r => (process.exitCode = r));
}