-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.ts
More file actions
52 lines (45 loc) · 1.62 KB
/
Copy pathindex.ts
File metadata and controls
52 lines (45 loc) · 1.62 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
import type { Metadata } from 'userscript-metadata-generator';
import { userscriptMetadataGenerator } from 'userscript-metadata-generator';
import type { Compiler } from 'webpack';
import { Compilation, ModuleFilenameHelpers, sources } from 'webpack';
export type { Metadata } from 'userscript-metadata-generator';
export class UserScriptMetaDataPlugin {
private readonly header: string;
private readonly test: RegExp;
/**
* Plugin to prepend UserScript Metadata.
* @param metadata - metadata object, required
* @param test - file pattern, default `/\.user\.js$/`
*/
constructor({ metadata, test = /\.user\.js$/ }: { metadata: Metadata; test?: string | RegExp }) {
if (metadata === undefined) {
throw new TypeError('Must pass "metadata"');
}
this.header = userscriptMetadataGenerator(metadata) + '\n\n';
if (typeof test === 'string') {
this.test = new RegExp(test);
} else {
this.test = test;
}
}
apply(compiler: Compiler): void {
const tester = { test: this.test };
compiler.hooks.compilation.tap('UserScriptMetaDataPlugin', (compilation) => {
compilation.hooks.processAssets.tap(
{
name: 'UserScriptMetaDataPlugin',
stage: Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE,
},
() => {
for (const chunk of compilation.chunks) {
for (const file of chunk.files) {
if (ModuleFilenameHelpers.matchObject(tester, file)) {
compilation.updateAsset(file, (old) => new sources.ConcatSource(this.header, old));
}
}
}
},
);
});
}
}