All files / global/jsonata functions.mjs

95.83% Statements 161/168
99.42% Branches 173/174
78.26% Functions 18/23
97.91% Lines 141/144

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 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 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328                                                                            7x   7x 7x       96x   89x 1x   88x           88x 92x 92x 92x 92x 92x 92x     88x 88x             2x             88x     5x     88x     2x     88x   1x             94x   81x   81x 81x 81x   1x         14x 14x   14x 14x 20x   14x       579x 371x 365x   357x 357x   351x 351x 351x 351x 351x   351x       347x 347x 347x 504x 419x     417x 28x 16x   405x 99x 99x     403x 403x   397x 88x   397x 8x   397x 397x 397x   397x 397x 397x 349x   277x 277x       182x             182x 182x       101x 101x   97x 97x 97x 6x   91x 91x 91x 45x                 109x     109x 109x 109x 109x 13x 13x     96x 96x 32x 32x   96x       93x 29x             136x 136x     130x     130x 134x 134x 6x 6x   128x       130x   7x     123x           129x   129x     113x   38x     75x       111x   111x 114x         114x 139x 139x 139x 136x 129x 129x 30x 30x 6x 5x 5x   1x   30x   129x 105x               129x 129x 129x 91x 91x       111x    
/*
  Copyright (C) 2021 owner Roman Piontik R.Piontik@mail.ru
 
  Copyright (C) 2022 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
 
  In any derivative products, you must retain the information of
  owner of the original code and provide clear attribution to the project
 
  https://dochub.info
 
  The use of this product or its derivatives for any purpose cannot be a secret.
 
 
  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.
 
  Maintainers:
      R.Piontik <r.piontik@mail.ru>
 
  Contributors:
      R.Piontik <r.piontik@mail.ru> - 2023
      R.Piontik <r.piontik@mail.ru> - 2025
*/
 
// Создает исполняющие ручки функций
 
import ajv from 'ajv';
import {getLoggerWithTag} from '@global/logger/v2/logger.mjs';
 
const logger = getLoggerWithTag('functions.mjs');
// Обработчики разных выражений могут использовать одну декларацию функции.
const validatorsByProfile = new WeakMap();
const schemaMapKeywords = new Set(['properties', 'patternProperties', 'definitions', '$defs', 'dependencies', 'dependentSchemas']);
// Генерирует валидатор входных параметров
function makeParamsValidator(handler) {
    // Если параметров нет, то проверять ничего не будем
    if (!handler.profile.params) return null;
 
    if (!Array.isArray(handler.profile.params))
        throw new Error(`Ошибка описания схемы входных параметров в функции [${handler.id}]!\nПараметры должны описываться массивом.`);
 
    const schema = {
        type: 'object',
        properties: {},
        required: []
    };
    
    handler.profile.params.map((param, index) => {
        const alias = param.alias || `param${index}`;
        const vParam = Object.assign({}, param);
        delete vParam.alias;
        delete vParam.required;
        schema.properties[alias] = vParam;
        param.required && schema.required.push(alias);
    });
 
    try {
        const rules = new ajv(
            { allErrors: true,
                logger: {
                    log: (args) => {
                        logger.info(() => JSON.stringify(args));
                    },
                    warn: (args) => {
                        logger.debug(() => JSON.stringify(args));
                    },
                    error: (args) => {
                        logger.debug(() => JSON.stringify(args));
                    }
                } }
        );
        rules.addKeyword({
            keyword: 'callback',
            compile() {
                return (data) => typeof data === 'function';
            }
        });
        rules.addKeyword({
            keyword: 'params',
            compile() {
                return (data) => typeof data === 'function';
            }
        });
        return rules.compile(schema);
    } catch (e) {
        throw new Error(`Ошибка схемы входных параметров в декларации функции [${handler.id}]\n${e.toString()}`);
    }
}
 
// Генерирует валидатор выходных данных
function makeResultValidator(handler) {
    // Если схемы нет, то проверять ничего не будем
    if (!handler.profile.result) return null;
 
    const schema = handler.profile.result;
 
    try {
        const rules = new ajv({ allErrors: true });
        return rules.compile(schema);
    } catch (e) {
        throw new Error(`Ошибка схемы результата в декларации функции [${handler.id}]\n${e.toString()}`);
    }
}
 
function mayReferenceSchemaMap(reference) {
    const fragment = reference.slice(reference.indexOf('#') + 1);
    Iif (!reference.includes('#') || !fragment.startsWith('/')) return true;
    // Ключ properties в словаре подсхем может быть именем поля, а не следующим словарём.
    let inSchemaMap = false;
    for (const segment of fragment.slice(1).split('/')) {
        inSchemaMap = !inSchemaMap && schemaMapKeywords.has(decodeURIComponent(segment));
    }
    return inSchemaMap;
}
 
function copyJsonSchema(value, scan, isProxy, inComparisonValue = false, inSchemaMap = false, inMapEntry = false) {
    if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;
    if (typeof value === 'number' && Number.isFinite(value) && !Object.is(value, -0)) return value;
    if (typeof value !== 'object' || isProxy(value) || scan.ancestors.has(value)) return undefined;
 
    const isArray = Array.isArray(value);
    if (Object.getPrototypeOf(value) !== (isArray ? Array.prototype : Object.prototype)) return undefined;
 
    const descriptors = Object.getOwnPropertyDescriptors(value);
    const alias = scan.parameterEntries.has(value) ? descriptors.alias?.value : undefined;
    const usesComparisonAlias = alias === 'const' || alias === 'enum' || (alias && typeof alias === 'object');
    const keys = Reflect.ownKeys(descriptors);
    const length = isArray ? descriptors.length.value : 0;
    // JSON заменяет пропуски массива на null и отбрасывает его именованные свойства.
    if (isArray && keys.length !== length + 1) return undefined;
 
    // Дескрипторы позволяют прочитать данные без геттеров. Снимок без прототипа
    // исключает вызов унаследованного toJSON при сериализации.
    const copy = isArray ? Object.setPrototypeOf([], null) : Object.create(null);
    scan.ancestors.add(value);
    for (const key of keys) {
        if (isArray && key === 'length') continue;
        if (typeof key !== 'string') return undefined;
        // AJV проверяет идентичность объектов const до сравнения через
        // constructor, valueOf и toString. Копия может изменить результат.
        if (key === 'constructor' || key === 'valueOf' || key === 'toString') {
            if (inComparisonValue) return undefined;
            if (inMapEntry || usesComparisonAlias) scan.hasSensitiveMapEntry = true;
        }
        if (isArray) {
            const index = Number(key);
            if (!Number.isInteger(index) || index < 0 || index >= length || String(index) !== key) return undefined;
        }
 
        const descriptor = descriptors[key];
        if (!descriptor.enumerable || !Object.prototype.hasOwnProperty.call(descriptor, 'value')) return undefined;
 
        if (value === scan.parameters && descriptor.value && typeof descriptor.value === 'object') {
            scan.parameterEntries.add(descriptor.value);
        }
        if (key === '$ref' && typeof descriptor.value === 'string' && mayReferenceSchemaMap(descriptor.value)) {
            scan.referencesSchemaMap = true;
        }
        const comparisonKey = key === 'const' || key === 'enum';
        const comparisonValue = inComparisonValue || (!inSchemaMap && comparisonKey);
        const schemaMap = !inComparisonValue && !inSchemaMap && schemaMapKeywords.has(key);
        // Ссылка может выбрать весь словарь подсхем и превратить его имя const или enum в ключевое слово.
        const mapEntry = inMapEntry || usesComparisonAlias || (inSchemaMap && comparisonKey);
        const entry = copyJsonSchema(descriptor.value, scan, isProxy, comparisonValue, schemaMap, mapEntry);
        if (entry === undefined) return undefined;
        copy[key] = entry;
    }
    scan.ancestors.delete(value);
    return copy;
}
 
function snapshotSchema(value, isProxy, parameters) {
    const scan = {
        ancestors: new WeakSet(),
        parameters,
        parameterEntries: new WeakSet(),
        referencesSchemaMap: false,
        hasSensitiveMapEntry: false
    };
    const snapshot = copyJsonSchema(value, scan, isProxy);
    return scan.referencesSchemaMap && scan.hasSensitiveMapEntry ? undefined : snapshot;
}
 
function getSchemaKey(profile, isProxy) {
    try {
        if (!profile || isProxy(profile) || Object.getPrototypeOf(profile) !== Object.prototype) return undefined;
 
        const params = Object.getOwnPropertyDescriptor(profile, 'params');
        const result = Object.getOwnPropertyDescriptor(profile, 'result');
        if ((params ? !Object.prototype.hasOwnProperty.call(params, 'value') : 'params' in profile)
            || (result ? !Object.prototype.hasOwnProperty.call(result, 'value') : 'result' in profile)) return undefined;
 
        const paramsCopy = snapshotSchema(params?.value ?? null, isProxy, params?.value);
        const resultCopy = snapshotSchema(result?.value ?? null, isProxy);
        if (paramsCopy === undefined || resultCopy === undefined) return undefined;
        return JSON.stringify(Object.setPrototypeOf([paramsCopy, resultCopy], null));
    } catch {
        // Схемы, которые нельзя скопировать, AJV получает в исходном виде.
        return undefined;
    }
}
 
// Генерирует валидаторы входных и выходных данных
function makeValidators(handler, isProxy) {
    const profile = handler.profile;
    // При обновлении манифеста схемы могут измениться внутри того же объекта декларации.
    // Без проверки Proxy компилируем оригинал: его дескрипторы могут отличаться от чтения свойств.
    const schemaKey = isProxy ? getSchemaKey(profile, isProxy) : undefined;
    const cacheable = schemaKey !== undefined;
    const cached = validatorsByProfile.get(profile);
    if (cacheable && cached?.schemaKey === schemaKey) {
        handler.validators = cached.validators;
        return;
    }
    // AJV может хранить ссылки на вложенные части схемы, поэтому кешируем валидаторы её копии.
    let validatorHandler = handler;
    if (cacheable) {
        const [params, result] = JSON.parse(schemaKey);
        validatorHandler = {id: handler.id, profile: {params, result}};
    }
    handler.validators = {
        input: makeParamsValidator(validatorHandler),
        output: makeResultValidator(validatorHandler)
    };
    if (cacheable && profile && typeof profile === 'object') {
        validatorsByProfile.set(profile, {schemaKey, validators: handler.validators});
    }
}
 
// Подготавливает входящие данные и проверяет из структуру
function prepareParams(handler, params) {
    // Если валидатора нет, ничего не проверяем
    const validator = handler.validators.input;
    if (!validator) return null;
 
    // Готовим параметры на вход
    const result = {
        context: {}
    };
    handler.profile.params.map((param, index) => {
        const alias = param.alias || `param${index}`;
        if (typeof params[index] === 'function') {
            !result.funcs && (result.funcs = {});
            result.funcs[alias] = params[index];
        } else
            result.context[alias] = params[index];
    });
 
    // Проверяем по схеме
    if (!validator({...result.context, ...result.funcs})) {
        // ajv_localize(validator.errors);
        throw new Error(`Ошибка валидации входных параметров функции [${handler.id}]\n${JSON.stringify(validator.errors, null, 4)}`);
    }
 
    return result;
}
 
// Проверяет результат функции по схеме
function prepareResult(handler, result) {
    // Проверяем по схеме
    const validator = handler.validators.output;
    // Если валидатора нет, ничего не проверяем
    if (!validator) return result;
 
    // Проверяем по схеме
    if (!validator(result)) {
        // ajv_localize(validator.errors);
        throw new Error(`Ошибка валидации результата функции [${handler.id}]\n${JSON.stringify(validator.errors, null, 4)}`);
    }
 
    return result;
}
 
export default (queryDriver, functions, performanceLogger, isProxy) => {
    const result = {};
 
    for (const funcId in functions) {
        const func = {
            id: funcId,
            profile: functions[funcId],
            executor: null
        };
        result[funcId] = async(...params) => {
            const logger = performanceLogger?.getJsonataLogger(funcId, params);
            logger?.setStart();
            !func.validators && makeValidators(func, isProxy);
            const input = prepareParams(func, params);  // Подготавливаем параметры и проверяем их на корректность
            let doRebuildQuery = !func.executor;
            if (!doRebuildQuery || input?.funcs || func.funcs) {
                const oldFuncs = Object.assign({}, func.funcs || {});
                for (const funcId in input?.funcs || {}) {
                    if (input.funcs[funcId] !== oldFuncs[funcId]) {
                        doRebuildQuery = true;
                        break;
                    }
                    delete oldFuncs[funcId];
                }
                doRebuildQuery |= Object.keys(oldFuncs).length;
            }
            if (doRebuildQuery) {
                func.executor = queryDriver().expression(
                    func.profile?.code || 'undefined',
                    undefined,
                    undefined,
                    undefined,
                    input?.funcs
                );
            }
            const result = await func.executor.evaluate(input?.context);
            func.funcs = input?.funcs;
            const output = prepareResult(func, result);
            logger?.setEnd(output);
            return output;
        };
    }
 
    return result;
};