/
index.js
230 lines (198 loc) 路 8.8 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
import path from 'path';
import { readFile, rename, rm } from 'fs/promises';
import * as cheerio from 'cheerio';
import { createResult, assignToResult, getMainOutput, getRootDir, getOutputDir, getStdinInput, esbuildFile } from '@chialab/esbuild-helpers';
/**
* @typedef {import('esbuild').Metafile} Metafile
*/
/**
* @typedef {import('esbuild').BuildResult & { metafile: Metafile, outputFiles?: import('esbuild').OutputFile[] }} BuildResult
*/
/**
* Cheerio esm support is unstable for some Node versions.
*/
const load = /** @type {typeof cheerio.load} */ (cheerio.load || cheerio.default?.load);
/**
* Get the common dir of source files.
* @param {string[]} files
* @return The common dir.
*/
function commonDir(files) {
if (files.length === 0) {
return path.sep;
}
if (files.length === 1) {
return path.dirname(files[0]);
}
const res = files.slice(1).reduce((dir, file) => {
const xs = file.split(path.sep);
let i;
for (i = 0; dir[i] === xs[i] && i < Math.min(dir.length, xs.length); i++);
return dir.slice(0, i);
}, files[0].split(path.sep));
// Windows correctly handles paths with forward-slashes
return res.length > 1 ? res.join(path.sep) : path.sep;
}
/**
* @typedef {Object} Build
* @property {import('esbuild').Loader} [loader] The loader to use.
* @property {Partial<import('esbuild').BuildOptions>} options The file name of the referenced file.
* @property {(filePath: string, outputFiles: string[]) => Promise<void>|void} finisher A callback function to invoke when output file has been generated.
*/
/**
* @typedef {Object} PluginOptions
* @property {import('@chialab/rna-config-loader').Target} [scriptsTarget]
* @property {import('@chialab/rna-config-loader').Target} [modulesTarget]
* @property {string} [entryNames]
* @property {string} [chunkNames]
* @property {string} [assetNames]
*/
/**
* A HTML loader plugin for esbuild.
* @param {PluginOptions} options
* @param {typeof import('esbuild')} [esbuildModule]
* @return An esbuild plugin.
*/
export default function({
scriptsTarget = 'es2015',
modulesTarget = 'es2020',
} = {}, esbuildModule) {
/**
* @type {import('esbuild').Plugin}
*/
const plugin = {
name: 'html',
setup(build) {
const { entryPoints = [], assetNames, write } = build.initialOptions;
const stdin = getStdinInput(build);
const rootDir = getRootDir(build);
const outDir = getOutputDir(build);
const sourceFiles = Array.isArray(entryPoints) ? entryPoints : Object.values(entryPoints);
const sourceDir = sourceFiles.length ? commonDir(sourceFiles.map((file) => path.resolve(rootDir, file))) : rootDir;
// force metafile in order to collect output data.
build.initialOptions.metafile = build.initialOptions.metafile || write !== false;
/**
* @type {BuildResult}
*/
let collectedResult;
build.onStart(() => {
collectedResult = createResult();
});
build.onEnd(async (result) => {
if (result.metafile && write !== false) {
const outputs = { ...result.metafile.outputs };
for (const outputKey in outputs) {
const output = outputs[outputKey];
if (path.extname(outputKey) !== '.html') {
if (output.entryPoint && path.extname(output.entryPoint) === '.html') {
await rm(outputKey);
try {
await rm(`${outputKey}.map`);
} catch(err) {
//
}
delete result.metafile.outputs[outputKey];
}
continue;
}
for (const inputKey in output.inputs) {
if (path.extname(inputKey) !== '.html') {
continue;
}
const newOutputKey = path.join(path.dirname(outputKey), path.basename(inputKey));
if (newOutputKey === outputKey) {
continue;
}
await rename(
outputKey,
newOutputKey
);
delete result.metafile.outputs[outputKey];
result.metafile.outputs[newOutputKey] = output;
break;
}
}
}
assignToResult(result, collectedResult);
});
build.onLoad({ filter: /\.html$/ }, async ({ path: filePath }) => {
const [
{ collectStyles },
{ collectScripts },
{ collectAssets },
{ collectWebManifest },
{ collectIcons },
esbuild,
] = await Promise.all([
import('./collectStyles.js'),
import('./collectScripts.js'),
import('./collectAssets.js'),
import('./collectWebManifest.js'),
import('./collectIcons.js'),
esbuildModule || import('esbuild'),
]);
const contents = (stdin && filePath === stdin.path) ?
stdin.contents :
await readFile(filePath, 'utf-8');
const basePath = path.dirname(filePath);
const relativePath = `./${path.relative(sourceDir, basePath)}`;
const relativeOutDir = path.resolve(outDir, relativePath);
const $ = load(contents);
const root = $.root();
const builds = /** @type {Build[]} */ ([
...collectIcons($, root, basePath, relativeOutDir),
...collectWebManifest($, root, basePath, relativeOutDir),
...collectStyles($, root, basePath, relativeOutDir, build.initialOptions),
...collectScripts($, root, basePath, relativeOutDir, { scriptsTarget, modulesTarget }, build.initialOptions),
...collectAssets($, root, basePath, relativeOutDir, build.initialOptions),
]);
for (let i = 0; i < builds.length; i++) {
const currentBuild = builds[i];
/** @type {string[]} */
const outputFiles = [];
const entryPoints = /** @type {string[]|undefined}} */ (currentBuild.options.entryPoints);
if (!entryPoints || entryPoints.length === 0) {
continue;
}
if (currentBuild.loader === 'file') {
const file = entryPoints[0];
const { result, outputFile } = await esbuildFile(file, {
...build.initialOptions,
assetNames: assetNames || '[dir]/[name]',
...currentBuild.options,
});
outputFiles.push(outputFile);
assignToResult(collectedResult, result);
await currentBuild.finisher(outputFile, outputFiles);
continue;
}
/** @type {import('esbuild').BuildOptions} */
const config = {
...build.initialOptions,
outfile: undefined,
outdir: relativeOutDir,
metafile: true,
external: [],
...currentBuild.options,
};
const result = /** @type {BuildResult} */ (await esbuild.build({
assetNames: '[dir]/[name]',
...config,
}));
assignToResult(collectedResult, result);
const outputFile = getMainOutput(entryPoints, result.metafile, rootDir);
await currentBuild.finisher(outputFile, outputFiles);
}
return {
contents: $.html(),
loader: 'file',
watchFiles: builds.reduce((acc, build) => [
...acc,
...(/** @type {string[]} */ (build.options.entryPoints) || []),
], /** @type {string[]} */ ([])),
};
});
},
};
return plugin;
}