• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

rokucommunity / brighterscript / #13604

13 Jan 2025 03:29PM UTC coverage: 86.902%. Remained the same
#13604

push

web-flow
Merge 6255e8be5 into 9d6ef67ba

12080 of 14675 branches covered (82.32%)

Branch coverage included in aggregate %.

94 of 100 new or added lines in 13 files covered. (94.0%)

103 existing lines in 10 files now uncovered.

13052 of 14245 relevant lines covered (91.63%)

31874.8 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

73.64
/src/PluginInterface.ts
1
import type { AnnotationDeclaration, CompilerPlugin } from './interfaces';
2
import { LogLevel, createLogger, type Logger } from './logging';
1✔
3
import type { TypedFunctionType } from './types/TypedFunctionType';
4
/*
5
 * we use `Required` everywhere here because we expect that the methods on plugin objects will
6
 * be optional, and we don't want to deal with `undefined`.
7
 * `extends (...args: any[]) => any` determines whether the thing we're dealing with is a function.
8
 * Returning `never` in the `as` clause of the `[key in object]` step deletes that key from the
9
 * resultant object.
10
 * on the right-hand side of the mapped type we are forced to use a conditional type a second time,
11
 * in order to be able to use the `Parameters` utility type on `Required<T>[K]`. This will always
12
 * be true because of the filtering done by the `[key in object]` clause, but TS requires the duplication.
13
 *
14
 * so put together: we iterate over all of the fields in T, deleting ones which are not (potentially
15
 * optional) functions. For the ones that are, we replace them with their parameters.
16
 *
17
 * this returns the type of an object whose keys are the names of the methods of T and whose values
18
 * are tuples containing the arguments that each method accepts.
19
 */
20
export type PluginEventArgs<T> = {
21
    [K in keyof Required<T> as Required<T>[K] extends (...args: any[]) => any ? K : never]:
22
    Required<T>[K] extends (...args: any[]) => any ? Parameters<Required<T>[K]> : never
23
};
24

25
export default class PluginInterface<T extends CompilerPlugin = CompilerPlugin> {
1✔
26
    constructor(
27
        plugins?: CompilerPlugin[],
28
        options?: {
29
            logger?: Logger;
30
            suppressErrors?: boolean;
31
        }
32
    ) {
33
        this.logger = options?.logger;
1,862✔
34
        this.suppressErrors = (options as any)?.suppressErrors === false ? false : true;
1,862!
35
        for (const plugin of plugins ?? []) {
1,862✔
UNCOV
36
            this.add(plugin);
×
37
        }
38
        if (!this.logger) {
1,862✔
39
            this.logger = createLogger();
1✔
40
        }
41
        if (!this.logger) {
1,862!
UNCOV
42
            this.logger = createLogger();
×
43
        }
44
    }
45

46
    private plugins: CompilerPlugin[] = [];
1,862✔
47
    private logger: Logger;
48

49
    /**
50
     * Should plugin errors cause the program to fail, or should they be caught and simply logged
51
     */
52
    private suppressErrors: boolean | undefined;
53

54
    /**
55
     * Call `event` on plugins
56
     */
57
    public emit<K extends keyof PluginEventArgs<T> & string>(event: K, ...args: PluginEventArgs<T>[K]) {
58
        for (let plugin of this.plugins) {
37,815✔
59
            if ((plugin as any)[event]) {
39,321✔
60
                try {
11,674✔
61
                    this.logger?.time(LogLevel.debug, [plugin.name, event], () => {
11,674!
62
                        (plugin as any)[event](...args);
11,674✔
63
                    });
64
                } catch (err) {
UNCOV
65
                    this.logger?.error(`Error when calling plugin ${plugin.name}.${event}:`, (err as Error).stack);
×
66
                    if (!this.suppressErrors) {
×
67
                        throw err;
×
68
                    }
69
                }
70
            }
71
        }
72
        return args[0];
37,815✔
73
    }
74

75
    /**
76
     * Call `event` on plugins, but allow the plugins to return promises that will be awaited before the next plugin is notified
77
     */
78
    public async emitAsync<K extends keyof PluginEventArgs<T> & string>(event: K, ...args: PluginEventArgs<T>[K]): Promise<PluginEventArgs<T>[K][0]> {
79
        for (let plugin of this.plugins) {
10,893✔
80
            if ((plugin as any)[event]) {
20,796✔
81
                try {
3,921✔
82
                    await this.logger?.time(LogLevel.debug, [plugin.name, event], async () => {
3,921!
83
                        await Promise.resolve(
3,921✔
84
                            (plugin as any)[event](...args)
85
                        );
86
                    });
87
                } catch (err) {
88
                    this.logger?.error(`Error when calling plugin ${plugin.name}.${event}:`, err);
2!
89
                }
90
            }
91
        }
92
        return args[0];
10,893✔
93
    }
94

95
    /**
96
     * Add a plugin to the beginning of the list of plugins
97
     */
98
    public addFirst<T extends CompilerPlugin = CompilerPlugin>(plugin: T) {
99
        if (!this.has(plugin)) {
2,159!
100
            this.plugins.unshift(plugin);
2,159✔
101
        }
102
        return plugin;
2,159✔
103
    }
104

105
    /**
106
     * Add a plugin to the end of the list of plugins
107
     */
108
    public add<T extends CompilerPlugin = CompilerPlugin>(plugin: T) {
109
        if (!this.has(plugin)) {
80✔
110
            this.sanitizePlugin(plugin);
79✔
111
            this.plugins.push(plugin);
79✔
112
        }
113
        return plugin;
80✔
114
    }
115

116
    /**
117
     * Find deprecated or removed historic plugin hooks, and warn about them.
118
     * Some events can be forwards-converted
119
     */
120
    private sanitizePlugin(plugin: CompilerPlugin) {
121
        const removedHooks = [
79✔
122
            'beforePrepublish',
123
            'afterPrepublish'
124
        ];
125
        for (const removedHook of removedHooks) {
79✔
126
            if (plugin[removedHook]) {
158!
UNCOV
127
                this.logger?.error(`Plugin "${plugin.name}": event ${removedHook} is no longer supported and will never be called`);
×
128
            }
129
        }
130

131
        const upgradeWithWarn = {
79✔
132
            beforePublish: 'beforeSerializeProgram',
133
            afterPublish: 'afterSerializeProgram',
134
            beforeProgramTranspile: 'beforeBuildProgram',
135
            afterProgramTranspile: 'afterBuildProgram',
136
            beforeFileParse: 'beforeProvideFile',
137
            afterFileParse: 'afterProvideFile',
138
            beforeFileTranspile: 'beforePrepareFile',
139
            afterFileTranspile: 'afterPrepareFile',
140
            beforeFileDispose: 'beforeFileRemove',
141
            afterFileDispose: 'afterFileRemove'
142
        };
143

144
        for (const [oldEvent, newEvent] of Object.entries(upgradeWithWarn)) {
79✔
145
            if (plugin[oldEvent]) {
790✔
146
                if (!plugin[newEvent]) {
7!
147
                    plugin[newEvent] = plugin[oldEvent];
7✔
148
                    this.logger?.warn(`Plugin '${plugin.name}': event '${oldEvent}' is no longer supported. It has been converted to '${newEvent}' but you may encounter issues as their signatures do not match.`);
7!
149
                } else {
UNCOV
150
                    this.logger?.warn(`Plugin "${plugin.name}": event '${oldEvent}' is no longer supported and will never be called`);
×
151
                }
152
            }
153
        }
154
    }
155

156
    public has(plugin: CompilerPlugin) {
157
        return this.plugins.includes(plugin);
2,562✔
158
    }
159

160
    public remove<T extends CompilerPlugin = CompilerPlugin>(plugin: T) {
161
        if (this.has(plugin)) {
320!
162
            this.plugins.splice(this.plugins.indexOf(plugin), 1);
320✔
163
        }
164
        return plugin;
320✔
165
    }
166

167
    /**
168
     * Remove all plugins
169
     */
170
    public clear() {
UNCOV
171
        this.plugins = [];
×
172
    }
173

174

175
    private annotationMap: Map<string, Array<string | TypedFunctionType | AnnotationDeclaration>>;
176

177
    public getAnnotationMap() {
178
        if (this.annotationMap) {
1,841!
NEW
179
            return this.annotationMap;
×
180
        }
181
        this.annotationMap = new Map<string, Array<string | TypedFunctionType | AnnotationDeclaration>>();
1,841✔
182
        for (let plugin of this.plugins) {
1,841✔
183
            if (plugin.annotations?.length > 0) {
1,881✔
184
                this.annotationMap.set(plugin.name, plugin.annotations);
1✔
185
            }
186
        }
187
        return this.annotationMap;
1,841✔
188
    }
189
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc