1
1
import createMarkdownLoader from '../src/loaders/markdown.mjs' ;
2
2
import createMarkdownParser from '../src/parsers/markdown.mjs' ;
3
3
4
- // Instantiate loader and parser once to reuse
5
- const loader = createMarkdownLoader ( ) ;
6
- const parser = createMarkdownParser ( ) ;
4
+ /**
5
+ * Generic lazy initializer.
6
+ * @template T
7
+ * @param {() => T } factory - Function to create the instance.
8
+ * @returns {() => T } - A function that returns the singleton instance.
9
+ */
10
+ export const lazy = factory => {
11
+ let instance ;
12
+ return ( ) => ( instance ??= factory ( ) ) ;
13
+ } ;
14
+
15
+ // Instantiate loader and parser once to reuse,
16
+ // but only if/when we actually need them. No need
17
+ // to create these objects just to load a different
18
+ // utility.
19
+ const loader = lazy ( createMarkdownLoader ) ;
20
+ const parser = lazy ( createMarkdownParser ) ;
7
21
8
22
/**
9
23
* Load and parse markdown API docs.
@@ -12,10 +26,27 @@ const parser = createMarkdownParser();
12
26
* @returns {Promise<ApiDocMetadataEntry[]> } - Parsed documentation objects.
13
27
*/
14
28
export async function loadAndParse ( input , ignore ) {
15
- const files = await loader . loadFiles ( input , ignore ) ;
16
- return parser . parseApiDocs ( files ) ;
29
+ const files = await loader ( ) . loadFiles ( input , ignore ) ;
30
+ return parser ( ) . parseApiDocs ( files ) ;
17
31
}
18
32
33
+ /**
34
+ * Wraps a function to catch both synchronous and asynchronous errors.
35
+ *
36
+ * @param {Function } fn - The function to wrap. Can be synchronous or return a Promise.
37
+ * @returns {Function } A new function that handles errors and logs them.
38
+ */
39
+ export const errorWrap =
40
+ fn =>
41
+ async ( ...args ) => {
42
+ try {
43
+ return await fn ( ...args ) ;
44
+ } catch ( err ) {
45
+ console . error ( err ) ;
46
+ process . exit ( 1 ) ;
47
+ }
48
+ } ;
49
+
19
50
/**
20
51
* Represents a command-line option for the linter CLI.
21
52
* @typedef {Object } Option
0 commit comments