-
-
Notifications
You must be signed in to change notification settings - Fork 75
/
processors.ts
108 lines (92 loc) 路 2.75 KB
/
processors.ts
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
import { concurrent } from "./utils.ts";
import { Exception } from "./errors.ts";
import type { Page } from "../core.ts";
export type Extensions = string[] | "*";
interface ProcessorOptions {
extensions: Extensions;
multiple: boolean;
}
/**
* Class to store and run the (pre)processors
*/
export default class Processors {
/** Processors and the assigned extensions */
processors = new Map<Processor | MultiProcessor, ProcessorOptions>();
/** Assign a processor to some extensions */
set(extensions: Extensions, processor: Processor, multiple: false): void;
set(extensions: Extensions, processor: MultiProcessor, multiple: true): void;
set(
extensions: Extensions,
processor: Processor | MultiProcessor,
multiple = false,
): void {
if (Array.isArray(extensions)) {
extensions.forEach((extension) => {
if (extension.charAt(0) !== ".") {
throw new Exception(
"Invalid extension. It must start with '.'",
{ extension },
);
}
});
}
this.processors.set(processor, { extensions, multiple });
}
/** Apply the processors to the provided pages */
async run(pages: Page[]): Promise<void> {
const removed: Page[] = [];
for (const [process, { extensions, multiple }] of this.processors) {
if (multiple) {
const filtered = pages.filter((page) => pageMatches(extensions, page));
if (await (process as MultiProcessor)(filtered, pages) === false) {
removed.push(...filtered);
}
} else {
await concurrent(
pages,
async (page) => {
try {
if (pageMatches(extensions, page)) {
if (await (process as Processor)(page, pages) === false) {
removed.push(page);
}
}
} catch (cause) {
throw new Exception("Error processing page", {
cause,
page,
processor: process.name,
});
}
},
);
}
}
// Remove the pages that have been removed by the processors
for (const page of removed) {
pages.splice(pages.indexOf(page), 1);
}
}
}
/** A (pre)processor */
export type Processor = (
page: Page,
allpages: Page[],
) => void | false | Promise<void | false>;
export type MultiProcessor = (
page: Page[],
allpages: Page[],
) => void | false | Promise<void | false>;
function pageMatches(exts: Extensions, page: Page): boolean {
if (exts === "*") {
return true;
}
if (page.src.ext && exts.includes(page.src.ext)) {
return true;
}
const url = page.outputPath;
if (typeof url === "string" && exts.some((ext) => url.endsWith(ext))) {
return true;
}
return false;
}