All files / building plugin-descriptors.cjs

100% Statements 55/55
100% Branches 60/60
100% Functions 4/4
100% Lines 54/54

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                  19x 19x     303x                           51x 1x     50x 50x   50x 98x 2x   96x 1x     95x 2x           93x 2x     91x 91x 2x   89x 1x   88x 121x 2x   86x 1x   85x 1x   84x 117x 117x 2x         115x   82x   82x 82x   82x   78x 78x 78x   7x   71x   4x 4x   2x             73x 1x   72x 72x 72x 72x 1x       71x                   19x  
/*
  Copyright (C) 2026 Sber
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
 
          http://www.apache.org/licenses/LICENSE-2.0
 
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
 
// @ts-check
const fs = require('fs');
const path = require('path');
 
/** @param {unknown} value */
const isNonEmptyString = (value) => typeof value === 'string' && Boolean(value.trim());
 
/**
 * Разрешает descriptors в webpack entries. Проверки уникальности действуют в пределах одного вызова.
 * @param {import('../types/plugin-descriptor').PluginsConfiguration} descriptors
 * @param {{ rootDir: string, isPluginMode: boolean, defaultLazyLoading: boolean,
 *   resolvePackage?: typeof require.resolve }} options
 */
function resolvePluginDescriptors(descriptors, {
    rootDir,
    isPluginMode,
    defaultLazyLoading,
    resolvePackage = require.resolve
}) {
    if (!Array.isArray(descriptors)) {
        throw new Error('plugins.json must contain an array of plugin descriptors');
    }
 
    const registeredPluginIds = new Set();
    const documentTypeOwners = new Map();
 
    return descriptors.map((descriptor) => {
        if (descriptor === null || typeof descriptor !== 'object' || Array.isArray(descriptor)) {
            throw new Error('Each plugin descriptor must be an object');
        }
        if (!isNonEmptyString(descriptor.id)) {
            throw new Error('Plugin id is required');
        }
        // ID используется в именах артефактов package.
        if (!/^[a-z0-9][a-z0-9-]*$/.test(descriptor.id)) {
            throw new Error(
                `Plugin id [${descriptor.id}] must start with a lowercase `
                + 'Latin letter or digit and contain only lowercase Latin '
                + 'letters, digits and hyphens'
            );
        }
        if (descriptor.lazy !== undefined && typeof descriptor.lazy !== 'boolean') {
            throw new Error(`Plugin [${descriptor.id}] lazy must be a boolean`);
        }
 
        const source = descriptor.source;
        if (source === null || typeof source !== 'object' || Array.isArray(source)) {
            throw new Error(`Plugin [${descriptor.id}] source must be an object`);
        }
        if (source.type !== 'local' && source.type !== 'package') {
            throw new Error(`Plugin [${descriptor.id}] has unsupported source type [${source.type}]`);
        }
        if (!Array.isArray(descriptor.documents) || !descriptor.documents.length
            || descriptor.documents.some((type) => !isNonEmptyString(type))) {
            throw new Error(`Plugin [${descriptor.id}] must declare document types`);
        }
        if (!isNonEmptyString(source.location)) {
            throw new Error(`Plugin [${descriptor.id}] source location is required`);
        }
        if (registeredPluginIds.has(descriptor.id)) {
            throw new Error(`Plugin id [${descriptor.id}] is declared more than once`);
        }
        for (const documentType of descriptor.documents) {
            const currentOwner = documentTypeOwners.get(documentType);
            if (currentOwner) {
                throw new Error(
                    `Document type [${documentType}] is declared by plugins `
                    + `[${currentOwner}] and [${descriptor.id}]`
                );
            }
            documentTypeOwners.set(documentType, descriptor.id);
        }
        registeredPluginIds.add(descriptor.id);
 
        const isLocal = source.type === 'local';
        let location = source.location;
        let packagePath;
        if (isLocal) {
            // Одинаковые пути дают одинаковые имена chunks; путь не должен выходить за корень core.
            location = path.posix.normalize(location.replace(/\\/g, '/')).replace(/\/$/, '');
            const relative = path.relative(rootDir, path.resolve(rootDir, location));
            if (path.posix.isAbsolute(source.location) || path.win32.isAbsolute(source.location)
                || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
                throw new Error(`Plugin [${descriptor.id}] local location must be relative and stay within core`);
            }
            packagePath = path.resolve(rootDir, location, 'package.json');
        } else {
            try {
                packagePath = resolvePackage(`${location}/package.json`, { paths: [rootDir] });
            } catch (error) {
                throw new Error(
                    `Cannot resolve package for plugin [${descriptor.id}]: [${location}]`,
                    { cause: error }
                );
            }
        }
 
        if (!fs.existsSync(packagePath)) {
            throw new Error(`Package for plugin [${descriptor.id}] was not found at [${packagePath}]`);
        }
        const config = require(packagePath);
        const entry = config.main || 'index.js';
        const absoluteEntryPath = path.resolve(path.dirname(packagePath), entry);
        if (!fs.existsSync(absoluteEntryPath)) {
            throw new Error(`Entry for plugin [${descriptor.id}] was not found at [${absoluteEntryPath}]`);
        }
 
        // Для local имя entry строится из нормализованного location, для package — из id.
        return {
            id: descriptor.id,
            documents: descriptor.documents,
            lazy: !isPluginMode && (descriptor.lazy ?? defaultLazyLoading),
            entryName: isLocal ? `plugins/${location}` : `plugins/packages/${descriptor.id}`,
            entryPath: isLocal ? `./${path.posix.join(location, entry)}` : absoluteEntryPath
        };
    });
}
 
module.exports = { resolvePluginDescriptors };