forked from w3c/respec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuilder.cjs
executable file
·161 lines (149 loc) · 4.73 KB
/
builder.cjs
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
#!/usr/bin/env node
"use strict";
const sade = require("sade");
const colors = require("colors");
const { readFileSync } = require("fs");
const path = require("path");
const rollup = require("rollup");
const alias = require("@rollup/plugin-alias");
const rel = p => path.relative(process.cwd(), p);
/**
* @param {object} opts
* @param {RegExp[]} opts.include
*/
function string(opts) {
return {
transform(code, id) {
if (!opts.include.some(re => re.test(id))) return;
if (id.endsWith(".runtime.js")) {
code = `(() => {\n${code}})()`;
}
return {
code: `export default ${JSON.stringify(code)};`,
map: { mappings: "" },
};
},
};
}
const Builder = {
/**
* Async function that gets the current version of ReSpec from package.json
*
* @returns {string} The version string.
*/
getRespecVersion: () => {
const packagePath = path.join(__dirname, "../package.json");
const content = readFileSync(packagePath, "utf-8");
return JSON.parse(content).version;
},
_getOptions(name, { debug }) {
if (!name) {
throw new TypeError("name is required");
}
const buildPath = path.join(__dirname, "../builds");
const outFile = `respec-${name}.js`;
const outPath = path.join(buildPath, outFile);
const version = this.getRespecVersion();
/** @type {import("rollup").InputOptions} */
const inputOptions = {
input: require.resolve(`../profiles/${name}.js`),
plugins: [
!debug && require("@rollup/plugin-terser").default(),
alias({
entries: [{ find: /^text!(.*)/, replacement: "./$1" }],
}),
string({
include: [/\.runtime\.js$/, /\.svg$/, /respec-worker\.js$/],
}),
!debug &&
require("rollup-plugin-minify-html-literals").default({
include: [/\.css\.js$/],
options: {
minifyOptions: {
minifyCSS: { format: "keep-breaks" },
},
// disable html`` minification
shouldMinify: () => false,
shouldMinifyCSS: ({ tag }) => !debug && tag === "css",
},
}),
],
onwarn(warning, warn) {
if (warning.code !== "CIRCULAR_DEPENDENCY") {
warn(warning);
}
},
};
/** @type {import("rollup").OutputOptions} */
const outputOptions = {
file: outPath,
inlineDynamicImports: true,
format: "iife",
sourcemap: true,
banner: `window.respecVersion = "${version}";\n`,
};
return { inputOptions, outputOptions };
},
/**
* @param {object} options
* @param {string} options.name Name of the profile (in `/profiles` dierctory) to build.
* @param {boolean} [options.debug] Don't run minifiers if true.
*/
async build({ name, debug = false }) {
const { inputOptions, outputOptions } = this._getOptions(name, { debug });
console.log(`Building ${rel(inputOptions.input)}. Please wait...`);
const bundle = await rollup.rollup(inputOptions);
await bundle.write(outputOptions);
console.log(` Wrote ${rel(outputOptions.file)}.`);
},
watch({ name, debug }) {
const { inputOptions, outputOptions } = this._getOptions(name, { debug });
const watcher = rollup.watch({ ...inputOptions, output: outputOptions });
watcher.on("event", async ev => {
switch (ev.code) {
case "BUNDLE_START":
console.log(`Building ${rel(ev.input)}. Please wait...`);
break;
case "BUNDLE_END":
console.log(
` Wrote ${rel(ev.output[0])} in ${ev.duration}ms.`,
"Watching for file changes..."
);
await ev.result.close();
break;
case "ERROR":
console.log(ev.error);
break;
}
});
return watcher;
},
};
exports.Builder = Builder;
if (require.main === module) {
sade("./tools/builder.cjs <profile>", true)
.describe(
"Builder builds a ReSpec profile. Profile must be in the profiles/ folder (e.g., w3c.js)"
)
.example(`w3c ${colors.dim("# Build W3C profile.")}`)
.example(
`w3c --debug ${colors.dim("# Build W3C profile without optimizations.")}`
)
.option("-d, --debug", "Disable optimization to ease debugging", false)
.option("-w, --watch", "Automatically re-build on file changes", false)
.action(async (profile, opts) => {
if (opts.watch) {
Builder.watch({ name: profile, debug: opts.debug });
return;
}
try {
await Builder.build({ name: profile, debug: opts.debug });
} catch (err) {
console.error(colors.red(err.stack));
return process.exit(1);
}
})
.parse(process.argv, {
unknown: flag => console.error(`Unknown option: ${flag}`),
});
}