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 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 | 24x 24x 8x 8x 8x 10x 10x 10x 7x 7x 7x 24x 302x 302x 302x 302x 302x 302x 302x 86x 89x 279x 10x 276x 9x 9x 87x 3x 1x 1x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 3x 1x 2x 2x 2x 2x 2x 2x 2x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 5x 136x 136x 136x 136x 136x 136x 136x 136x 57x 6x 1x 18x 18x 23x 23x 31x 136x 89x 20x 63x 89x 272x 272x 272x 272x 272x 238x 2x 2x 236x 238x 231x 228x 7x 44x 44x 44x 271x 271x 271x 271x 271x 155x 155x 5x 155x 271x 271x 271x 150x 271x 271x 271x 121x 121x 121x 121x 121x 121x 89x 121x 121x 121x 121x 121x 121x 121x 129x 129x 297x 297x 17x 17x 2x 2x 15x 15x 4x 4x 11x 4x 11x 129x 89x 266x 266x 266x 266x 266x 266x 147x 266x 3x 89x 579x 579x 579x 579x 448x 448x 448x 448x 448x 448x 448x 277x 277x 171x 140x 89x 137x 11x 9x 11x 126x 89x 12x 12x 12x 12x 12x 3x 3x 4x 4x 1x 12x 12x 89x 850x 850x 850x 850x 89x 323x 89x 528x 528x 528x 51x 55x 55x 55x 528x 89x 51x 88x 51x 26x 89x 138x 138x 137x 89x 81x 89x 345x 219x 219x 219x 219x 338x 338x 338x 193x 338x 219x 89x 4x 4x 4x 4x 4x 4x 5x 5x 5x 4x 1x 3x 89x 49x 55x 15x 89x 49x 49x 81x 49x 81x 81x 61x 42x 19x 1x 1x 18x 18x 49x 89x 131x 349x 4x 4x 345x 345x 345x 49x 49x 296x 296x 131x 131x 89x 263x 104x 263x 89x 528x 528x 528x 528x 190x 89x 138x 138x 138x 89x 116x 116x 113x 112x 89x 3x 3x 8x 8x 3x 89x 51x 51x 51x 89x 2x 89x 3x 3x 89x 18x 18x 18x 18x 18x 18x 18x 18x 10x 10x 10x 10x 3x 10x 18x 18x 18x 18x 6x 6x 3x 3x 3x 3x 18x 89x 19x 19x 19x 19x 19x 18x 18x 19x 19x 19x 89x 1x 1x 1x 1x 1x 1x 1x 1x 1x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 7x 1x 1x 6x 4x 4x 2x 2x 2x 1x 72x 72x 72x 75x 75x 75x 75x 75x 3x 3x 3x 1x 71x 71x 24x | /*
Copyright (C) 2023 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.
*/
import {makeURIByBaseURI} from '../tools/uri.mjs';
import {
checkIsObject,
createChildPath,
createRepositoryIDfromURI,
getImportsDifferences,
getStorePath
} from './helpers.mjs';
import {extractFrontmatter} from '@global/manifest/tools/yamlHeader.mjs';
import { validateManifestData } from './manifestValidator.mjs';
import {getLoggerWithTag} from '@global/logger/v2/logger.mjs';
const LOG_TAG = 'parser3.index.mjs';
const logger = getLoggerWithTag(LOG_TAG);
// Один и тот же URI манифеста импортирован повторно
class DuplicateImportError extends Error {
constructor(uri, message) {
super(message);
this.name = 'DuplicateImport';
this.uri = uri;
}
}
// Дефект объявления $package: нет обязательного поля либо один packageId объявлен с разными
// версиями в пределах дерева
class PackageDeclarationError extends Error {
constructor(uri, message) {
super(message);
this.name = 'PackageDeclaration';
this.uri = uri;
}
}
class SyntaxError extends Error {
constructor(uri, message) {
super(message);
this.name = 'syntax';
this.uri = uri;
}
}
// метка для объекта похожего на SourceItem (утиная типизация)
// Когда сервер работает как кластер, SourceItem вытаскиваются из БД и преобразуются через JSON stringify
// из-за этого тип теряется. Поэтому эта метка проставляется в методе fromExistData
// для объектов созданных через конструктор тоже. Работает корректно, в отличие от instanceof
const SOURCE_ITEM_TAG = Symbol('SourceItem');
export class SourceItem {
constructor({ ownerUri, uri, data }) {
this.uri = uri;
this.ownerUri = ownerUri;
this.manifest = data;
const imports = data?.imports ?? [];
this.imports = imports.map((path) => makeURIByBaseURI(path, uri));
delete this.manifest.imports;
// отмечаем объект symbol меткой
Object.defineProperty(this, SOURCE_ITEM_TAG, { value: true, enumerable: false });
}
}
export function isSourceItem(source) { return Boolean(source && source[SOURCE_ITEM_TAG]); }
class RepositorySource {
constructor() {
this.repositorySources = new Set();
}
_checkIsRepositoryURI(uri) {
return uri.startsWith('bitbucket:') || uri.startsWith('gitlab:');
}
_createRepositoryIDfromURI(uri) {
return createRepositoryIDfromURI(uri);
}
addRepositorySource(uri) {
if(this._checkIsRepositoryURI(uri)) {
const repositoryID = this._createRepositoryIDfromURI(uri);
this.repositorySources.add(repositoryID);
}
}
/**
* Сбрасывает набор. Обязателен при переиспользовании парсера под другой манифест: экземпляр
* Parser - модульный синглтон, и без сброса репозитории предыдущей загрузки утекают в следующую.
*/
clearRepositorySources() {
this.repositorySources.clear();
}
removeRepositorySource(uri) {
if(this._checkIsRepositoryURI(uri)) {
const repositoryID = this._createRepositoryIDfromURI(uri);
this.repositorySources.delete(repositoryID);
}
}
}
export class Parser extends RepositorySource {
constructor(options = {}) {
super();
const {
strictMode = false
} = options;
this.strictMode = strictMode;
this.parserVersion = 'v3';
this.rootImports = [];
this.imports = [];
this.sources = {};
this.metamodels = {};
this.sourceMap = {};
this.mergeMap = {};
this.manifest = {};
this.changes = new Set();
this.errors = {};
this.isManifestBuilded = false;
// признак того, что манифест в процесс загрузки
this.manifestLoadInProgress = true;
this.afterLoadedCallbacks = [];
}
static fromExistData(manifest, anotherParser) {
if (anotherParser.parserVersion !== 'v3') {
throw `unsupported parser version, need v3 but exist ${anotherParser.parserVersion}`;
}
let parser = new Parser();
parser.strictMode = anotherParser.strictMode;
parser.parserVersion = 'v3';
parser.rootImports = anotherParser.rootImports;
parser.imports = anotherParser.imports;
parser.sources = anotherParser.sources;
for (const uri in parser.sources) {
Object.defineProperty(parser.sources[uri], SOURCE_ITEM_TAG, { value: true, enumerable: false });
}
parser.metamodels = anotherParser.metamodels;
parser.sourceMap = anotherParser.sourceMap;
parser.mergeMap = anotherParser.mergeMap;
parser.manifest = manifest;
parser.changes = new Set();
parser.errors = anotherParser.errors;
parser.isManifestBuilded = anotherParser.isManifestBuilded;
// признак того, что манифест в процесс загрузки
parser.manifestLoadInProgress = anotherParser.manifestLoadInProgress;
parser.afterLoadedCallbacks = [];
return parser;
}
// Явный allowlist полей, которые реально читает fromExistData - единственный источник истины
// о том, что нужно для восстановления парсера. manifest сюда намеренно не входит - он персистится
// отдельно и передаётся в fromExistData первым аргументом; changes/afterLoadedCallbacks
// fromExistData всегда создаёт заново, а не восстанавливает.
static toPersistedData(parser) {
return {
parserVersion: parser.parserVersion,
strictMode: parser.strictMode,
rootImports: parser.rootImports,
imports: parser.imports,
sources: parser.sources,
metamodels: parser.metamodels,
sourceMap: parser.sourceMap,
mergeMap: parser.mergeMap,
errors: parser.errors,
isManifestBuilded: parser.isManifestBuilded,
manifestLoadInProgress: parser.manifestLoadInProgress
};
}
// ***************************** ОБРАБОТКА ОШИБОК *****************************
// ****************************************************************************
registerError(e, uri) {
const errorURI = uri || e.uri;
if(!this.errors[errorURI]) this.errors[errorURI] = {
code: e.code,
message: e.message,
name: e.name
};
const errorPath = `$errors/requests/${new Date().getTime()}`;
this.pushToMergeMap({ path: errorPath, location: uri });
try {
if (typeof e === 'string') e = JSON.parse(e);
} catch (e) {
true;
}
let errorType = (() => {
switch (e.name) {
case 'SyntaxError':
case 'YAMLSyntaxError':
case 'YAMLSemanticError':
return 'syntax';
case 'TypeError':
return 'core';
case 'EntryIsADirectory (FileSystemError)':
return 'file-system';
case 'DuplicateImport':
uri = e.uri;
return 'duplicate-import';
case 'PackageDeclaration':
uri = e.uri;
return 'package';
default:
return 'net';
}
})();
this.onError &&
this.onError(errorType, {
uri,
error: e
});
}
refreshErrors = () => {
for(let uri in this.errors) {
this.registerError(this.errors[uri], uri);
}
}
// ********************************* ЗАГРУЗКА *********************************
// ****************************************************************************
pushRequest = async(uri, baseURI) => {
const sourceUri = makeURIByBaseURI(uri, baseURI);
this.errors[sourceUri] && delete this.errors[sourceUri];
const request = this.onPullSource
? this.onPullSource(uri, baseURI ?? '/', this)
: this.cache.request(uri, '/');
return new Promise((res, rej) => {
request
.then((response) => {
let data;
if (uri?.toLowerCase()?.endsWith('.md')) {
let markdownData = extractFrontmatter(response.data);
data = markdownData.header ? markdownData.header : {};
} else {
data = typeof response.data === 'object'
? response.data
: JSON.parse(response.data);
}
if (data) {
validateManifestData(data);
res(data);
} else {
throw new SyntaxError(sourceUri, 'Файл пустой или содержит ошибку в манифесте');
}
})
.catch((err) => {
Iif(this.strictMode) {
// todo: систематизировать ошибки в парсере [ERA-1330]
const error = err instanceof SyntaxError || err instanceof DuplicateImportError || err.response
? err
: new SyntaxError(sourceUri, 'Файл пустой или содержит ошибку в манифесте');
rej(error);
}
this.isManifestBuilded
? this.errors[sourceUri] = err
: this.registerError(err, sourceUri);
res({});
});
});
};
_loadSourceTree({ uri, baseURI, ownerUri = null, root, sources, imports }) {
this.pushRequest(uri, baseURI)
.then((data) => {
imports.push(uri);
this.addRepositorySource(uri);
const source = new SourceItem({
ownerUri,
uri: baseURI ? makeURIByBaseURI(uri, baseURI): uri,
data
});
source.imports = source.imports.filter((importUri) => {
const isDoubleImport = Boolean(sources[importUri]);
if(isDoubleImport) {
this.registerError(
new DuplicateImportError(
uri,
`Дублирование импорта манифеста:\n${importUri}\nимпортирован в\n${sources[importUri].ownerUri}`
)
);
}
return !isDoubleImport;
});
sources[uri] = source;
root.importStack += source.imports.length;
source.imports.forEach((childUri) => {
this._loadSourceTree({
uri: makeURIByBaseURI(childUri, source.uri),
ownerUri: source.uri,
root,
sources,
imports
});
});
})
.catch((err) => {
this.registerError(
err,
uri
);
})
.finally(() => {
root.isRootImport = false;
root.importStack -= 1;
if (root.importStack <= 0) {
// Загрузка дерева импортов упешно завершена
root.res({ sources, imports });
}
});
}
loadSourceTree({ uri, baseURI, ownerUri = null }) {
const sources = {};
const imports = [];
return new Promise((res, rej) => {
const root = { importStack: 1, res, rej, isRootImport: true };
this._loadSourceTree({ uri, baseURI, ownerUri, root, sources, imports });
});
}
import = async(uri, baseURI) => {
try {
const { sources, imports } = await this.loadSourceTree({ uri, baseURI });
let startIndex = this.imports.indexOf(uri) + this.imports.length + 1;
this.imports.splice(startIndex, 0, ...imports);
Object.assign(this.sources, sources);
Object.assign(this.metamodels, this._getMetamodelVersions());
this.rootImports.push(uri);
} catch (e) {
if(this.strictMode) throw e;
this.registerError(e, e?.uri || uri);
}
};
/**
* Собирает {packageId: version} по дереву источников и валидирует объявления $package
* (обязательность packageId/version, конфликт версий одного packageId). Нарушения не
* прерывают загрузку - уходят в this.errors через registerError
*/
_getMetamodelVersions() {
const metamodels = {};
for (const uri in this.sources) {
const pkg = this.sources[uri].manifest.$package;
if (!pkg) continue;
const packageId = Object.keys(pkg)[0];
if (!packageId) {
this.registerError(new PackageDeclarationError(uri, `Раздел $package (${uri}) не содержит идентификатора пакета`), uri);
continue;
}
const version = pkg[packageId].version;
if (!version) {
this.registerError(new PackageDeclarationError(uri, `Пакет "${packageId}" (${uri}) не содержит обязательного поля version`), uri);
continue;
}
if (metamodels[packageId] !== undefined && metamodels[packageId] !== version) {
this.registerError(
new PackageDeclarationError(uri, `Пакет "${packageId}" подключён с разными версиями: ${metamodels[packageId]} и ${version} (${uri})`),
uri
);
}
// При конфликте побеждает версия из последнего по порядку импорта источника (детерминированно)
metamodels[packageId] = version;
}
return metamodels;
}
// ****************************** ОБХОД ДЕРЕВА ********************************
// ****************************************************************************
forEachTree = ({ uri, manifest = null, callbacks }) => {
const source = this.sources[uri];
Iif (!source) return;
Eif (callbacks?.eachTree) {
callbacks.eachTree({ source, manifest, sourceUri: uri });
}
this.forEachTreeItem({
source: source.manifest,
manifest,
path: '/',
structuredPath: [],
sourceUri: uri,
callbacks,
parents: null
});
source.imports.forEach((childUri) =>
this.forEachTree({ uri: childUri, manifest, callbacks })
);
if (callbacks?.afterEachTree) {
callbacks.afterEachTree({ uri });
}
};
forEachTreeItem = ({
source,
manifest = null,
path,
structuredPath,
sourceUri,
callbacks,
parents
}) => {
Eif (callbacks?.eachObject) {
callbacks.eachObject({
source,
manifest,
path,
structuredPath,
sourceUri,
parents
});
}
const params = { source, manifest, path, sourceUri, callbacks, parents };
for (let key in source) {
const childPath = createChildPath(path, key);
params.parents = { source, manifest, key, path };
params.path = childPath;
params.source = source[key];
params.manifest = manifest === null ? manifest : manifest[key];
params.structuredPath = [...structuredPath, key];
if (checkIsObject(source[key])) {
Iif (callbacks?.beforeEachObject) {
callbacks.beforeEachObject(params);
}
this.forEachTreeItem(params);
} else {
if (callbacks?.eachProp) {
callbacks.eachProp(params);
}
}
}
};
// ********************************** МЕРЖ ************************************
// ****************************************************************************
merge = ({ source, manifest, key }) => {
if (Array.isArray(source[key])) {
if (!manifest[key] || !Array.isArray(manifest[key])) {
manifest[key] = [];
}
this.mergeArray({ source, manifest, key });
} else {
manifest[key] = source[key];
}
};
mergeArray = ({ source, manifest, key }) => {
if (!manifest[key] || !Array.isArray(manifest[key])) manifest[key] = [];
const sourceValue = source[key];
const temp = [];
let result = [];
manifest[key].map((distItem) => {
const distContent = JSON.stringify(distItem);
if (
!sourceValue.find((srcItem, index) => {
!temp[index] && (temp[index] = JSON.stringify(srcItem));
return distContent === temp[index];
})
) {
result.push(distItem);
}
});
result = sourceValue.concat(result);
manifest[key] = result;
};
// *********************************** MAPS ***********************************
// ****************************************************************************
pushToMergeMap = ({ path, sourceUri }) => {
const storePath = getStorePath(path);
let locations = this.mergeMap[storePath];
!locations && (this.mergeMap[storePath] = locations = []);
locations.indexOf(sourceUri) < 0 && locations.push(sourceUri);
};
createSourceMap = (path, structuredPath) => {
this.sourceMap[path] = {
sources: [],
path,
structuredPath,
value: this.isManifestBuilded ? null : {}
};
};
pushObjectToSourceMap = (path, sourceUri, parents) => {
const { sources } = this.sourceMap[path];
sources.push(sourceUri);
if(!this.manifestLoadInProgress) {
sources.sort((a, b) => {
const indexA = this.imports.indexOf(a);
const indexB = this.imports.indexOf(b);
return indexA - indexB;
});
}
Iif (
!this.isManifestBuilded &&
parents &&
this.sourceMap[parents.path].value &&
parents.key in this.sourceMap[parents.path].value
) {
delete this.sourceMap[parents.path].value[parents.key];
}
};
removeObjectFromSourceMap = (uri, path) => {
this.sourceMap[path].sources = this.sourceMap[path].sources.filter(
(sourceUri) => sourceUri !== uri
);
if (this.sourceMap[path]?.sources.length === 0) {
delete this.sourceMap[path];
}
};
updateInitSourceMapValue = (path, sourceUri, parents) => {
Iif (this.sourceMap[path]) {
const sourceItem = {
source: null,
sourceUri
};
this.sourceMap[path].sources.push(sourceItem);
}
if (!this.isManifestBuilded) {
this.merge({
source: parents.source,
manifest: this.sourceMap[parents.path].value,
key: parents.key
});
}
};
getSource = (structuredPath, uri) => {
return structuredPath.reduce((slice, dir) => slice[dir], this.sources[uri].manifest);
};
// *********************** ВНЕСЕНИЕ ИЗМЕНИЙ В МАНИФЕСТ ************************
// ****************************************************************************
getManifestSliceByPath = (keys) => {
if (keys.length === 0) return this.manifest;
let currentSlice = this.manifest;
let parentSlice = null;
let currentKey = null;
for (let i = 0; i < keys.length; i++) {
currentKey = keys[i];
parentSlice = currentSlice;
if (!checkIsObject(parentSlice[currentKey])) {
parentSlice[currentKey] = {};
}
currentSlice = parentSlice[currentKey];
}
return currentSlice;
};
removeManifestSliceByPath = (path) => {
const keys = path.split('/').slice(1);
Iif (keys[0] === '') return;
let currentSlice = this.manifest;
let parentSlice = null;
let currentKey = null;
for (let i = 0; i < keys.length; i++) {
currentKey = keys[i];
parentSlice = currentSlice;
if (checkIsObject(parentSlice[currentKey])) {
currentSlice = parentSlice[currentKey];
} else {
return;
}
}
delete parentSlice[currentKey];
};
removePrimitiveValues = (object) => {
for (let key in object) {
if (!checkIsObject(object[key])) {
delete object[key];
}
}
};
updatePrimitiveValues = (manifest, path) => {
const { sources, structuredPath } = this.sourceMap[path];
const result = {};
const startIndex =
sources.findLastIndex(uri => typeof uri === 'object') + 1;
sources.slice(startIndex).forEach((sourceUri) => {
const source = this.getSource(structuredPath, sourceUri);
for (let key in source) {
if (checkIsObject(source[key])) {
Iif (key in result) {
delete result[key];
}
} else if (Array.isArray(source[key])) {
this.mergeArray({ source, manifest: result, key });
this.pushToMergeMap({
path: createChildPath(path, key),
sourceUri
});
} else {
result[key] = source[key];
this.pushToMergeMap({
path: createChildPath(path, key),
sourceUri
});
}
}
});
Object.assign(manifest, result);
};
applyChanges = async() => {
this.changes.forEach((path) => {
if (
this.sourceMap[path] === undefined ||
this.sourceMap[path]?.sources?.length === 0
) {
this.removeManifestSliceByPath(path); // если есть примитив то не трогаем
return;
}
const { value, structuredPath } = this.sourceMap[path];
const manifestSlice = this.getManifestSliceByPath(structuredPath);
if (this.isManifestBuilded) {
this.removePrimitiveValues(manifestSlice);
this.updatePrimitiveValues(manifestSlice, path);
} else {
Object.assign(manifestSlice, value);
this.sourceMap[path].value = null;
}
});
this.isManifestBuilded = true;
this.changes.clear();
};
// ********************* РЕГИСТРАЦИЯ И ПРИМЕНЕНИЕ ИЗМЕНИЙ *********************
// ****************************************************************************
// ********************************** MOUNT ***********************************
mountEachTree = ({ sourceUri }) => {
if (this.sources[sourceUri].imports.length) {
this.pushToMergeMap({
path: '/imports',
sourceUri
});
}
this.pushToMergeMap({ path: '/', sourceUri });
};
mountEachObject = ({
path,
structuredPath,
sourceUri,
parents
}) => {
this.changes.add(path);
if (!this.sourceMap[path]) this.createSourceMap(path, structuredPath);
this.pushObjectToSourceMap(path, sourceUri, parents);
if (!this.mergeMap[getStorePath(path)]) {
this.pushToMergeMap({ path, sourceUri });
}
};
mountEachProp = ({ path, sourceUri, parents }) => {
Iif (this.changes.has(path)) {
this.changes.delete(path);
}
this.updateInitSourceMapValue(path, sourceUri, parents);
this.pushToMergeMap({ path, sourceUri });
};
registerMountTree = (uri) => {
const callbacks = {
eachObject: this.mountEachObject.bind(this),
eachProp: this.mountEachProp.bind(this),
eachTree: this.mountEachTree.bind(this)
};
this.forEachTree({ uri, callbacks });
};
// Первичная сборка
build() {
this.rootImports.forEach((uri) => this.registerMountTree(uri));
this.applyChanges();
}
// ********************************* UNMOUNT **********************************
unmountEachTree = ({ sourceUri }) => {
const rootPath = '/';
this.mergeMap[rootPath] = this.mergeMap[rootPath].filter(
(uri) => uri !== sourceUri
);
this.imports = this.imports.filter((uri) => uri !== sourceUri);
this.removeRepositorySource(sourceUri);
};
unmountEachObject = ({ path, sourceUri }) => {
Iif (!this.sourceMap[path]) return;
this.removeObjectFromSourceMap(sourceUri, path);
this.changes.add(path);
};
unmountEachProp = ({ path, sourceUri }) => {
Iif (this.sourceMap[path]) {
this.removeObjectFromSourceMap(sourceUri, path);
}
};
removeSource = ({ uri }) => {
this.errors[uri] && delete this.errors[uri];
this.sources[uri] && delete this.sources[uri];
};
// ********************************* UPDATE ***********************************
registerUpdate = async(source) => {
const isDataSource = typeof source === 'object';
const uri = isDataSource
? Object.keys(source)[0]
: source;
this.errors[uri] && delete this.errors[uri];
const ownerUri = this.sources[uri]?.ownerUri;
const rawData = isDataSource
? source[uri]
: await this.pushRequest(uri);
const updatedSource = new SourceItem({ownerUri, uri, data: rawData});
const sourceToUnmount = this.sources[uri];
updatedSource.imports = updatedSource.imports.filter((importUri) => {
const hasInUnmountSource = sourceToUnmount.imports.includes(importUri);
const hasInManifest = Boolean(this.sources[importUri]);
const isDoubleImport = !hasInUnmountSource && hasInManifest;
if(isDoubleImport) {
this.registerError(
new DuplicateImportError(
uri,
`Дублирование импорта манифеста:\n${importUri}\nимпортирован в\n${this.sources[importUri].ownerUri}`
)
);
}
return !isDoubleImport;
});
// Регистрируем Unmount для устаревшего source
this.forEachTreeItem({
source: sourceToUnmount.manifest,
sourceUri: uri,
path: '/',
structuredPath: [],
callbacks: { eachObject: this.unmountEachObject.bind(this) }
});
// Регистрируем Mount для нового source
this.forEachTreeItem({
source: updatedSource.manifest,
sourceUri: uri,
path: '/',
structuredPath: [],
callbacks: { eachObject: this.mountEachObject.bind(this) }
});
// Проверяем изменились ли импорты
const importsDifferences = getImportsDifferences({
new: updatedSource.imports,
old: this.sources[uri].imports
});
for (let i = 0; i < importsDifferences.length; i++) {
const { uri, action } = importsDifferences[i];
if (action === 'remove') {
// Для удаленных импортов регистрируем Unmount
this.forEachTree({
uri,
callbacks: {
eachObject: this.unmountEachObject.bind(this),
eachTree: this.unmountEachTree.bind(this),
eachProp: this.unmountEachProp.bind(this),
afterEachTree: this.removeSource.bind(this)
}
});
} else Eif (action === 'add') {
// Для добавленных импортов регистрируем Mount
await this.import(uri);
this.registerMountTree(uri);
}
}
this.sources[uri] = updatedSource;
};
onChange = async(sources) => {
const list = sources.filter((source) => {
const uri = typeof source === 'object'
? Object.keys(source)[0]
: source;
return this.imports.includes(uri);
});
this.onStartReload && this.onStartReload();
for (let i = 0; i < list.length; i++) {
const uri = list[i];
await this.registerUpdate(uri);
}
this.applyChanges();
this.refreshErrors();
this.onReloaded && this.onReloaded(this);
};
// ********************************* HANDLERS *********************************
// ****************************************************************************
updateSourceData = (parserData) => {
const { manifest, rootImports, sources, sourceMap, mergeMap, errors, imports, metamodels } = parserData;
this.manifest = manifest;
this.rootImports = rootImports;
this.sources = sources;
this.sourceMap = sourceMap;
this.mergeMap = mergeMap;
this.errors = errors;
this.imports = imports;
this.metamodels = metamodels;
}
clean() {
this.rootImports = [];
this.imports = [];
this.sources = {};
this.metamodels = {};
this.sourceMap = {};
this.mergeMap = {};
this.manifest = {};
this.changes = new Set();
// Набор репозиториев тоже относится к загружаемому манифесту, а не к экземпляру парсера.
// Без сброса он накапливался: кластерный воркер грузит все манифесты подряд одним синглтоном,
// и каждый следующий permission получал repositorySources всех предыдущих. А этот набор -
// единственная проверка в getUnconnectedRepositories, то есть allowlist записи (put-content).
this.clearRepositorySources();
this.isManifestBuilded = false;
}
registerAfterLoadedCallback(name, func) {
if (typeof func !== 'function') {
logger.warn(
() => `Функция ${name} переданная для регистрации как callback после загрузки не является функцией и не может быть зарегистрирована`
);
return;
}
if (this.manifestLoadInProgress) {
logger.debug(
() => `Функция ${name} зарегистрирована как callback после загрузки`
);
this.afterLoadedCallbacks.push({
name: name,
func: func
});
} else {
try {
logger.debug(() => `Вызываем функцию [${name}] сейчас т.к. манифест уже загружен`);
func();
} catch (err) {
logger.warn(() => `Ошибка при вызове afterLoadedCallback ${name}`, err);
}
}
}
startLoad() {
logger.debug(() => 'Загрузка манифеста началась');
this.manifestLoadInProgress = true;
this.onStartReload && this.onStartReload(parser);
}
stopLoad() {
this.build();
this.onReloaded && this.onReloaded(this);
logger.debug(() => 'Загрузка манифеста завершена');
this.manifestLoadInProgress = false;
this.afterLoadedCallbacks.forEach(cb => {
try {
logger.debug(() => `Вызываем функцию [${cb.name}] после загрузки манифеста`);
cb.func();
} catch (err) {
logger.warn(() => `Ошибка при вызове afterLoadedCallback ${cb.name}`, err);
}
});
}
checkAwaitedPackages() {
return true;
}
checkLoaded() {
return true;
}
}
const parser = new Parser();
export default parser;
|