aboutsummaryrefslogtreecommitdiff
path: root/test/eslint-config.test.js
blob: bddde695f4729d096ae5e74c153641a5033e903c (plain)
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
/*
 * Copyright (C) 2024  Yomitan Authors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

import esbuild from 'esbuild';
import {readFileSync} from 'fs';
import {dirname, join} from 'path';
import {fileURLToPath} from 'url';
import {describe, test} from 'vitest';
import {parseJson} from '../dev/json.js';

const rootDir = join(dirname(fileURLToPath(import.meta.url)), '..');

/**
 * @param {string[]} scriptPaths
 * @returns {Promise<string[]>}
 */
async function getDependencies(scriptPaths) {
    const v = await esbuild.build({
        entryPoints: scriptPaths,
        bundle: true,
        minify: false,
        sourcemap: true,
        target: 'es2022',
        format: 'esm',
        write: false,
        metafile: true
    });
    const dependencies = Object.keys(v.metafile.inputs);
    const stringComparer = new Intl.Collator('en-US'); // Invariant locale
    dependencies.sort((a, b) => stringComparer.compare(a, b));
    return dependencies;
}

/**
 * @param {string[]} dependencies
 * @returns {string[]}
 */
function removeLibraryDependencies(dependencies) {
    const pattern = /^ext\/lib\//;
    return dependencies.filter((v) => !pattern.test(v));
}

/**
 * @param {{[key: string]: boolean}|undefined} env1
 * @param {{[key: string]: boolean}} env2
 * @returns {boolean}
 */
function envMatches(env1, env2) {
    if (typeof env1 !== 'object' || env1 === null) { return false; }
    const map1 = new Map(Object.entries(env1));
    const map2 = new Map(Object.entries(env2));
    if (map1.size !== map2.size) { return false; }
    for (const [k1, v1] of map1) {
        if (map2.get(k1) !== v1) { return false; }
    }
    return true;
}

/**
 * @param {string[]} files1
 * @param {string[]} files2
 * @returns {boolean}
 */
function filesMatch(files1, files2) {
    if (!Array.isArray(files1)) { return false; }
    const set1 = new Set(files1);
    const set2 = new Set(files2);
    if (set1.size !== set2.size) { return false; }
    for (const v of set1) {
        if (!set2.has(v)) { return false; }
    }
    return true;
}

const targets = [
    {
        name: 'sandbox',
        paths: [
            'ext/js/templates/sandbox/template-renderer-frame-main.js'
        ],
        /** @type {{[key: string]: boolean}} */
        env: {
            webextensions: false
        }
    },
    {
        name: 'worker',
        paths: [
            'ext/js/dictionary/dictionary-worker-main.js'
        ],
        /** @type {{[key: string]: boolean}} */
        env: {
            browser: false,
            worker: true
        }
    },
    {
        name: 'serviceworker',
        paths: [
            'ext/js/background/background-main.js'
        ],
        /** @type {{[key: string]: boolean}} */
        env: {
            browser: false,
            serviceworker: true
        }
    }
];

describe('Eslint configuration', () => {
    const eslintConfigPath = '.eslintrc.json';
    /** @type {import('core').SafeAny} */
    const eslintConfig = parseJson(readFileSync(join(rootDir, eslintConfigPath), 'utf8'));
    describe.each(targets)('Environment is $name', ({name, paths, env}) => {
        test('Entry exists', async ({expect}) => {
            const fullPaths = paths.map((v) => join(rootDir, v));
            const dependencies = removeLibraryDependencies(await getDependencies(fullPaths));

            let okay = false;
            const candidates = [];
            const {overrides} = eslintConfig;
            for (let i = 0, ii = overrides.length; i < ii; ++i) {
                const override = overrides[i];
                if (!envMatches(override.env, env)) { continue; }
                const {files} = override;
                if (!Array.isArray(files)) { continue; }
                candidates.push(i);
                if (filesMatch(files, dependencies)) {
                    okay = true;
                    break;
                }
            }

            if (okay) { return; }
            switch (candidates.length) {
                case 0:
                    {
                        const message = `No override found with "${name}" environment: ${JSON.stringify(env)}`;
                        expect(false, message).toStrictEqual(true);
                    }
                    break;
                case 1:
                    {
                        const index = candidates[0];
                        const message = `Override at index ${index} does not have the expected files for the "${name}" environment.`;
                        expect(overrides[index].files, message).toStrictEqual(dependencies);
                    }
                    break;
                default:
                    {
                        const message = `No override found with the correct file list for the "${name}" environment; candidate indices: [${candidates.join(', ')}].`;
                        expect([], message).toStrictEqual(dependencies);
                    }
                    break;
            }
        });
    });
});