@coopenomics/extension-kit 2026.9.30 → 2026.10.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,48 +1,10 @@
1
- import { PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, Entity, Index } from 'typeorm';
2
1
  import { randomUUID } from 'crypto';
3
2
  import { Field, ObjectType } from '@nestjs/graphql';
4
3
  import { Injectable, Inject } from '@nestjs/common';
5
- import { InjectRepository } from '@nestjs/typeorm';
4
+ import { K as KYSELY, q as inTransaction, m as moreThan, d as affectedCount } from '../shared/extension-kit.d5437cba.mjs';
6
5
  import { t } from '@coopenomics/i18n/server';
7
-
8
- var __defProp$a = Object.defineProperty;
9
- var __getOwnPropDesc$a = Object.getOwnPropertyDescriptor;
10
- var __decorateClass$a = (decorators, target, key, kind) => {
11
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$a(target, key) : target;
12
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
13
- if (decorator = decorators[i])
14
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
15
- if (kind && result)
16
- __defProp$a(target, key, result);
17
- return result;
18
- };
19
- class BaseTypeormEntity {
20
- /**
21
- * Получить имя таблицы для сущности
22
- * ДОЛЖЕН БЫТЬ ПЕРЕОПРЕДЕЛЕН в каждом наследнике!
23
- */
24
- static getTableName() {
25
- throw new Error("getTableName() must be implemented in subclass");
26
- }
27
- }
28
- __decorateClass$a([
29
- PrimaryGeneratedColumn("uuid")
30
- ], BaseTypeormEntity.prototype, "_id", 2);
31
- __decorateClass$a([
32
- Column({ type: "integer", default: 0 })
33
- ], BaseTypeormEntity.prototype, "block_num", 2);
34
- __decorateClass$a([
35
- Column({ type: "boolean", default: false })
36
- ], BaseTypeormEntity.prototype, "present", 2);
37
- __decorateClass$a([
38
- Column({ type: "varchar", default: "UNDEFINED" })
39
- ], BaseTypeormEntity.prototype, "status", 2);
40
- __decorateClass$a([
41
- CreateDateColumn({ type: "timestamp" })
42
- ], BaseTypeormEntity.prototype, "_created_at", 2);
43
- __decorateClass$a([
44
- UpdateDateColumn({ type: "timestamp" })
45
- ], BaseTypeormEntity.prototype, "_updated_at", 2);
6
+ import 'kysely';
7
+ import 'node:async_hooks';
46
8
 
47
9
  class BaseDomainEntity {
48
10
  // Дата последнего обновления в базе данных
@@ -77,46 +39,46 @@ class BaseDomainEntity {
77
39
  }
78
40
  }
79
41
 
80
- var __defProp$9 = Object.defineProperty;
81
- var __getOwnPropDesc$9 = Object.getOwnPropertyDescriptor;
82
- var __decorateClass$9 = (decorators, target, key, kind) => {
83
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$9(target, key) : target;
42
+ var __defProp$3 = Object.defineProperty;
43
+ var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
44
+ var __decorateClass$3 = (decorators, target, key, kind) => {
45
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$3(target, key) : target;
84
46
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
85
47
  if (decorator = decorators[i])
86
48
  result = (kind ? decorator(target, key, result) : decorator(result)) || result;
87
49
  if (kind && result)
88
- __defProp$9(target, key, result);
50
+ __defProp$3(target, key, result);
89
51
  return result;
90
52
  };
91
53
  let BaseOutputDTO = class {
92
54
  };
93
- __decorateClass$9([
55
+ __decorateClass$3([
94
56
  Field(() => String, {
95
57
  description: "\u0412\u043D\u0443\u0442\u0440\u0435\u043D\u043D\u0438\u0439 ID \u0431\u0430\u0437\u044B \u0434\u0430\u043D\u043D\u044B\u0445"
96
58
  })
97
59
  ], BaseOutputDTO.prototype, "_id", 2);
98
- __decorateClass$9([
60
+ __decorateClass$3([
99
61
  Field(() => Boolean, {
100
62
  description: "\u0424\u043B\u0430\u0433 \u043F\u0440\u0438\u0441\u0443\u0442\u0441\u0442\u0432\u0438\u044F \u0437\u0430\u043F\u0438\u0441\u0438 \u0432 \u0431\u043B\u043E\u043A\u0447\u0435\u0439\u043D\u0435"
101
63
  })
102
64
  ], BaseOutputDTO.prototype, "present", 2);
103
- __decorateClass$9([
65
+ __decorateClass$3([
104
66
  Field(() => Number, {
105
67
  nullable: true,
106
68
  description: "\u041D\u043E\u043C\u0435\u0440 \u0431\u043B\u043E\u043A\u0430 \u043A\u0440\u0430\u0439\u043D\u0435\u0439 \u0441\u0438\u043D\u0445\u0440\u043E\u043D\u0438\u0437\u0430\u0446\u0438\u0438 \u0441 \u0431\u043B\u043E\u043A\u0447\u0435\u0439\u043D\u043E\u043C"
107
69
  })
108
70
  ], BaseOutputDTO.prototype, "block_num", 2);
109
- __decorateClass$9([
71
+ __decorateClass$3([
110
72
  Field(() => Date, {
111
73
  description: "\u0414\u0430\u0442\u0430 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u044F \u0437\u0430\u043F\u0438\u0441\u0438"
112
74
  })
113
75
  ], BaseOutputDTO.prototype, "_created_at", 2);
114
- __decorateClass$9([
76
+ __decorateClass$3([
115
77
  Field(() => Date, {
116
78
  description: "\u0414\u0430\u0442\u0430 \u043F\u043E\u0441\u043B\u0435\u0434\u043D\u0435\u0433\u043E \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F \u0437\u0430\u043F\u0438\u0441\u0438"
117
79
  })
118
80
  ], BaseOutputDTO.prototype, "_updated_at", 2);
119
- BaseOutputDTO = __decorateClass$9([
81
+ BaseOutputDTO = __decorateClass$3([
120
82
  ObjectType("BaseEntity", {
121
83
  description: "\u0411\u0430\u0437\u043E\u0432\u044B\u0435 \u043F\u043E\u043B\u044F \u0441\u0443\u0449\u043D\u043E\u0441\u0442\u0438"
122
84
  })
@@ -170,15 +132,15 @@ function syncPolicy() {
170
132
  return policy;
171
133
  }
172
134
 
173
- var __defProp$8 = Object.defineProperty;
174
- var __getOwnPropDesc$8 = Object.getOwnPropertyDescriptor;
175
- var __decorateClass$8 = (decorators, target, key, kind) => {
176
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$8(target, key) : target;
135
+ var __defProp$2 = Object.defineProperty;
136
+ var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
137
+ var __decorateClass$2 = (decorators, target, key, kind) => {
138
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$2(target, key) : target;
177
139
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
178
140
  if (decorator = decorators[i])
179
141
  result = (kind ? decorator(target, key, result) : decorator(result)) || result;
180
142
  if (kind && result)
181
- __defProp$8(target, key, result);
143
+ __defProp$2(target, key, result);
182
144
  return result;
183
145
  };
184
146
  var _a;
@@ -358,310 +320,12 @@ let AbstractEntitySyncService = class {
358
320
  return "fork::*";
359
321
  }
360
322
  };
361
- AbstractEntitySyncService = __decorateClass$8([
323
+ AbstractEntitySyncService = __decorateClass$2([
362
324
  Injectable()
363
325
  ], AbstractEntitySyncService);
364
326
 
365
- var __defProp$7 = Object.defineProperty;
366
- var __getOwnPropDesc$7 = Object.getOwnPropertyDescriptor;
367
- var __decorateClass$7 = (decorators, target, key, kind) => {
368
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$7(target, key) : target;
369
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
370
- if (decorator = decorators[i])
371
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
372
- if (kind && result)
373
- __defProp$7(target, key, result);
374
- return result;
375
- };
376
- let EntityVersionTypeormEntity = class {
377
- };
378
- __decorateClass$7([
379
- PrimaryGeneratedColumn("uuid")
380
- ], EntityVersionTypeormEntity.prototype, "id", 2);
381
- __decorateClass$7([
382
- Column({ type: "varchar", length: 100 })
383
- ], EntityVersionTypeormEntity.prototype, "entity_table", 2);
384
- __decorateClass$7([
385
- Column({ type: "varchar", length: 36 })
386
- ], EntityVersionTypeormEntity.prototype, "entity_id", 2);
387
- __decorateClass$7([
388
- Column({ type: "jsonb" })
389
- ], EntityVersionTypeormEntity.prototype, "previous_data", 2);
390
- __decorateClass$7([
391
- Column({ type: "integer", nullable: true })
392
- ], EntityVersionTypeormEntity.prototype, "block_num", 2);
393
- __decorateClass$7([
394
- Column({ type: "varchar", length: 50 })
395
- ], EntityVersionTypeormEntity.prototype, "change_type", 2);
396
- __decorateClass$7([
397
- Column({ type: "jsonb", nullable: true })
398
- ], EntityVersionTypeormEntity.prototype, "metadata", 2);
399
- __decorateClass$7([
400
- CreateDateColumn({ type: "timestamp" })
401
- ], EntityVersionTypeormEntity.prototype, "created_at", 2);
402
- EntityVersionTypeormEntity = __decorateClass$7([
403
- Entity("entity_versions"),
404
- Index("idx_entity_versions_entity_table_id", ["entity_table", "entity_id"]),
405
- Index("idx_entity_versions_block_num", ["block_num"])
406
- ], EntityVersionTypeormEntity);
407
-
408
- var __defProp$6 = Object.defineProperty;
409
- var __getOwnPropDesc$6 = Object.getOwnPropertyDescriptor;
410
- var __decorateClass$6 = (decorators, target, key, kind) => {
411
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$6(target, key) : target;
412
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
413
- if (decorator = decorators[i])
414
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
415
- if (kind && result)
416
- __defProp$6(target, key, result);
417
- return result;
418
- };
419
- var __decorateParam$3 = (index, decorator) => (target, key) => decorator(target, key, index);
420
- let EntityVersionRepository = class {
421
- constructor(repository) {
422
- this.repository = repository;
423
- }
424
- /**
425
- * Соединение, на котором работает репозиторий.
426
- *
427
- * Нужно тем, кому требуется транзакция на несколько таблиц. Инжектить
428
- * `DataSource` через `@InjectDataSource()` в пакете нельзя: pnpm вшивает в
429
- * путь хэш peer-зависимостей, у пакета и контроллера оказываются разные
430
- * экземпляры `@nestjs/typeorm`, и токен не совпадает — Nest не находит
431
- * провайдера. Токен `@InjectRepository` такой беды не знает: он считается от
432
- * класса сущности, а она в пакете одна.
433
- */
434
- get dataSource() {
435
- return this.repository.manager.connection;
436
- }
437
- /**
438
- * Сохранить предыдущую версию сущности
439
- */
440
- async saveVersion(entityTable, entityId, previousData, blockNum, changeType, metadata) {
441
- const version = this.repository.create({
442
- entity_table: entityTable,
443
- entity_id: entityId,
444
- previous_data: previousData,
445
- block_num: blockNum,
446
- change_type: changeType,
447
- metadata
448
- });
449
- return await this.repository.save(version);
450
- }
451
- /**
452
- * Получить последнюю версию сущности до указанного блока
453
- */
454
- async getLastVersionBeforeBlock(entityTable, entityId, blockNum) {
455
- return await this.repository.createQueryBuilder("version").where("version.entity_table = :entityTable", { entityTable }).andWhere("version.entity_id = :entityId", { entityId }).andWhere("version.block_num <= :blockNum", { blockNum }).orderBy("version.block_num", "DESC").addOrderBy("version.created_at", "DESC").getOne();
456
- }
457
- /**
458
- * Удалить все версии после указанного блока (локальные изменения остаются)
459
- */
460
- async deleteVersionsAfterBlock(blockNum) {
461
- const result = await this.repository.createQueryBuilder().delete().from(EntityVersionTypeormEntity).where("block_num > :blockNum AND block_num IS NOT NULL", { blockNum }).execute();
462
- return result.affected || 0;
463
- }
464
- /**
465
- * Получить все версии для сущностей, которые нужно восстановить
466
- */
467
- async getVersionsForRecovery(entityTable, maxBlockNum) {
468
- return await this.repository.createQueryBuilder("version").where("version.entity_table = :entityTable", { entityTable }).andWhere("(version.block_num <= :maxBlockNum OR version.block_num IS NULL)", { maxBlockNum }).orderBy("version.entity_table", "ASC").addOrderBy("version.entity_id", "ASC").addOrderBy("version.block_num", "DESC").addOrderBy("version.created_at", "DESC").getMany();
469
- }
470
- /**
471
- * Очистить версии для указанной сущности
472
- */
473
- async clearVersionsForEntity(entityTable, entityId) {
474
- const result = await this.repository.createQueryBuilder().delete().from(EntityVersionTypeormEntity).where("entity_table = :entityTable", { entityTable }).andWhere("entity_id = :entityId", { entityId }).execute();
475
- return result.affected || 0;
476
- }
477
- };
478
- EntityVersionRepository = __decorateClass$6([
479
- Injectable(),
480
- __decorateParam$3(0, InjectRepository(EntityVersionTypeormEntity))
481
- ], EntityVersionRepository);
482
-
483
- var __defProp$5 = Object.defineProperty;
484
- var __getOwnPropDesc$5 = Object.getOwnPropertyDescriptor;
485
- var __decorateClass$5 = (decorators, target, key, kind) => {
486
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$5(target, key) : target;
487
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
488
- if (decorator = decorators[i])
489
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
490
- if (kind && result)
491
- __defProp$5(target, key, result);
492
- return result;
493
- };
494
- let InvalidatedEntityTypeormEntity = class {
495
- };
496
- __decorateClass$5([
497
- PrimaryGeneratedColumn("uuid")
498
- ], InvalidatedEntityTypeormEntity.prototype, "id", 2);
499
- __decorateClass$5([
500
- Column({ type: "varchar", length: 100 })
501
- ], InvalidatedEntityTypeormEntity.prototype, "entity_table", 2);
502
- __decorateClass$5([
503
- Column({ type: "varchar", length: 64 })
504
- ], InvalidatedEntityTypeormEntity.prototype, "entity_id", 2);
505
- __decorateClass$5([
506
- Column({ type: "jsonb" })
507
- ], InvalidatedEntityTypeormEntity.prototype, "data", 2);
508
- __decorateClass$5([
509
- Column({ type: "integer" })
510
- ], InvalidatedEntityTypeormEntity.prototype, "invalidated_by_block", 2);
511
- __decorateClass$5([
512
- Column({ type: "varchar", length: 128, nullable: true })
513
- ], InvalidatedEntityTypeormEntity.prototype, "fork_event_id", 2);
514
- __decorateClass$5([
515
- CreateDateColumn({ type: "timestamp" })
516
- ], InvalidatedEntityTypeormEntity.prototype, "created_at", 2);
517
- InvalidatedEntityTypeormEntity = __decorateClass$5([
518
- Entity("invalidated_entities"),
519
- Index("idx_invalidated_entities_block", ["invalidated_by_block"]),
520
- Index("idx_invalidated_entities_fork_event", ["fork_event_id"]),
521
- Index("idx_invalidated_entities_table_id", ["entity_table", "entity_id"])
522
- ], InvalidatedEntityTypeormEntity);
523
-
524
- var __defProp$4 = Object.defineProperty;
525
- var __getOwnPropDesc$4 = Object.getOwnPropertyDescriptor;
526
- var __decorateClass$4 = (decorators, target, key, kind) => {
527
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$4(target, key) : target;
528
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
529
- if (decorator = decorators[i])
530
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
531
- if (kind && result)
532
- __defProp$4(target, key, result);
533
- return result;
534
- };
535
- var __decorateParam$2 = (index, decorator) => (target, key) => decorator(target, key, index);
536
- let InvalidatedEntityRepository = class {
537
- constructor(repository) {
538
- this.repository = repository;
539
- }
540
- async bulkInsert(records) {
541
- if (records.length === 0)
542
- return 0;
543
- const entities = records.map((r) => this.repository.create(r));
544
- const saved = await this.repository.save(entities);
545
- return saved.length;
546
- }
547
- /**
548
- * Retention: удалить архив старше указанного блока. Делается отдельной транзакцией,
549
- * не транзакционно с архивированием — это фоновая очистка.
550
- */
551
- async deleteOlderThan(minInvalidatedByBlock) {
552
- const result = await this.repository.createQueryBuilder().delete().where("invalidated_by_block < :minInvalidatedByBlock", { minInvalidatedByBlock }).execute();
553
- return result.affected ?? 0;
554
- }
555
- /**
556
- * Forensic-read для AC «список из invalidated_entities, сгруппированный по fork_event_id».
557
- * UI/CLI обёртка — Epic 9 (out of scope 4.4); сам repository-метод доступен из backend-кода.
558
- */
559
- async findGroupedByForkEventId(opts) {
560
- const qb = this.repository.createQueryBuilder("inv").orderBy("inv.fork_event_id", "ASC").addOrderBy("inv.created_at", "DESC");
561
- if (opts.blockNum != null) {
562
- qb.where("inv.invalidated_by_block = :blockNum", { blockNum: opts.blockNum });
563
- }
564
- if (opts.limit != null) {
565
- qb.limit(opts.limit);
566
- }
567
- const rows = await qb.getMany();
568
- const grouped = /* @__PURE__ */ new Map();
569
- for (const row of rows) {
570
- const key = row.fork_event_id ?? null;
571
- const bucket = grouped.get(key) ?? [];
572
- bucket.push(row);
573
- grouped.set(key, bucket);
574
- }
575
- return grouped;
576
- }
577
- };
578
- InvalidatedEntityRepository = __decorateClass$4([
579
- Injectable(),
580
- __decorateParam$2(0, InjectRepository(InvalidatedEntityTypeormEntity))
581
- ], InvalidatedEntityRepository);
582
-
583
- var __defProp$3 = Object.defineProperty;
584
- var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
585
- var __decorateClass$3 = (decorators, target, key, kind) => {
586
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$3(target, key) : target;
587
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
588
- if (decorator = decorators[i])
589
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
590
- if (kind && result)
591
- __defProp$3(target, key, result);
592
- return result;
593
- };
594
- let InvalidatedEntityVersionTypeormEntity = class {
595
- };
596
- __decorateClass$3([
597
- PrimaryGeneratedColumn("uuid")
598
- ], InvalidatedEntityVersionTypeormEntity.prototype, "id", 2);
599
- __decorateClass$3([
600
- Column({ type: "varchar", length: 100 })
601
- ], InvalidatedEntityVersionTypeormEntity.prototype, "entity_table", 2);
602
- __decorateClass$3([
603
- Column({ type: "varchar", length: 64 })
604
- ], InvalidatedEntityVersionTypeormEntity.prototype, "entity_id", 2);
605
- __decorateClass$3([
606
- Column({ type: "jsonb" })
607
- ], InvalidatedEntityVersionTypeormEntity.prototype, "previous_data", 2);
608
- __decorateClass$3([
609
- Column({ type: "integer", nullable: true })
610
- ], InvalidatedEntityVersionTypeormEntity.prototype, "original_block_num", 2);
611
- __decorateClass$3([
612
- Column({ type: "integer" })
613
- ], InvalidatedEntityVersionTypeormEntity.prototype, "invalidated_by_block", 2);
614
- __decorateClass$3([
615
- Column({ type: "varchar", length: 128, nullable: true })
616
- ], InvalidatedEntityVersionTypeormEntity.prototype, "fork_event_id", 2);
617
- __decorateClass$3([
618
- Column({ type: "varchar", length: 50 })
619
- ], InvalidatedEntityVersionTypeormEntity.prototype, "change_type", 2);
620
- __decorateClass$3([
621
- Column({ type: "jsonb", nullable: true })
622
- ], InvalidatedEntityVersionTypeormEntity.prototype, "metadata", 2);
623
- __decorateClass$3([
624
- CreateDateColumn({ type: "timestamp" })
625
- ], InvalidatedEntityVersionTypeormEntity.prototype, "created_at", 2);
626
- InvalidatedEntityVersionTypeormEntity = __decorateClass$3([
627
- Entity("invalidated_entity_versions"),
628
- Index("idx_invalidated_versions_block", ["invalidated_by_block"]),
629
- Index("idx_invalidated_versions_fork_event", ["fork_event_id"]),
630
- Index("idx_invalidated_versions_table_id", ["entity_table", "entity_id"])
631
- ], InvalidatedEntityVersionTypeormEntity);
632
-
633
- var __defProp$2 = Object.defineProperty;
634
- var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
635
- var __decorateClass$2 = (decorators, target, key, kind) => {
636
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$2(target, key) : target;
637
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
638
- if (decorator = decorators[i])
639
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
640
- if (kind && result)
641
- __defProp$2(target, key, result);
642
- return result;
643
- };
644
- var __decorateParam$1 = (index, decorator) => (target, key) => decorator(target, key, index);
645
- let InvalidatedEntityVersionRepository = class {
646
- constructor(repository) {
647
- this.repository = repository;
648
- }
649
- async bulkInsert(records) {
650
- if (records.length === 0)
651
- return 0;
652
- const entities = records.map((r) => this.repository.create(r));
653
- const saved = await this.repository.save(entities);
654
- return saved.length;
655
- }
656
- async deleteOlderThan(minInvalidatedByBlock) {
657
- const result = await this.repository.createQueryBuilder().delete().where("invalidated_by_block < :minInvalidatedByBlock", { minInvalidatedByBlock }).execute();
658
- return result.affected ?? 0;
659
- }
660
- };
661
- InvalidatedEntityVersionRepository = __decorateClass$2([
662
- Injectable(),
663
- __decorateParam$1(0, InjectRepository(InvalidatedEntityVersionTypeormEntity))
664
- ], InvalidatedEntityVersionRepository);
327
+ class ChainRecord {
328
+ }
665
329
 
666
330
  var __defProp$1 = Object.defineProperty;
667
331
  var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
@@ -675,170 +339,123 @@ var __decorateClass$1 = (decorators, target, key, kind) => {
675
339
  return result;
676
340
  };
677
341
  var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
678
- let EntityVersioningService = class {
679
- // Токены зависимостей указаны явно, а не выведены из типов: пакет собирается
680
- // unbuild/esbuild, а esbuild не умеет `emitDecoratorMetadata`. Без `@Inject`
681
- // Nest не нашёл бы `design:paramtypes` и упал бы на инстанцировании сервиса.
682
- constructor(entityVersionRepository, invalidatedEntityRepository, invalidatedEntityVersionRepository) {
683
- this.entityVersionRepository = entityVersionRepository;
684
- this.invalidatedEntityRepository = invalidatedEntityRepository;
685
- this.invalidatedEntityVersionRepository = invalidatedEntityVersionRepository;
686
- }
687
- /**
688
- * Соединение берём у репозитория, а не инъекцией `@InjectDataSource()`:
689
- * у пакета и контроллера разные экземпляры `@nestjs/typeorm`, и токен
690
- * источника данных не совпал бы — Nest не нашёл бы провайдера.
691
- */
692
- get dataSource() {
693
- return this.entityVersionRepository.dataSource;
694
- }
695
- /**
696
- * Сохранить версию сущности перед её изменением
697
- */
698
- async saveVersionBeforeUpdate(repository, entityTable, updatedEntity, blockNum, changeType, metadata) {
699
- const existingEntity = await repository.findOne({
700
- where: { _id: updatedEntity._id }
701
- });
702
- if (!existingEntity) {
342
+ let ChainVersioningService = class {
343
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
344
+ constructor(db) {
345
+ this.db = db;
346
+ }
347
+ /** Кладёт в версии состояние записи перед её изменением; новой записи версионировать нечего. */
348
+ async saveVersionBeforeUpdate(store, updated, blockNum, changeType, metadata) {
349
+ if (!updated._id)
703
350
  return;
704
- }
705
- await this.entityVersionRepository.saveVersion(
706
- entityTable,
707
- existingEntity._id,
708
- { ...existingEntity },
709
- // Глубокая копия предыдущих данных
710
- blockNum,
711
- changeType,
712
- metadata
713
- );
714
- }
715
- /**
716
- * Восстановить версии сущностей после форка
717
- */
718
- async restoreVersionsAfterFork(repository, entityTable, forkBlockNum) {
719
- const versionsToRestore = await this.entityVersionRepository.getVersionsForRecovery(entityTable, forkBlockNum);
720
- const latestVersions = /* @__PURE__ */ new Map();
721
- for (const version of versionsToRestore) {
722
- const existingVersion = latestVersions.get(version.entity_id);
723
- if (!existingVersion) {
724
- latestVersions.set(version.entity_id, version);
725
- continue;
726
- }
727
- const shouldReplace = this.shouldReplaceVersion(existingVersion, version);
728
- if (shouldReplace) {
729
- latestVersions.set(version.entity_id, version);
730
- }
731
- }
732
- for (const [entityId, version] of latestVersions) {
733
- const existingEntity = await repository.findOne({
734
- where: { _id: entityId }
735
- });
736
- if (existingEntity) {
737
- Object.assign(existingEntity, version.previous_data);
738
- await repository.save(existingEntity);
739
- } else {
740
- const restoredEntity = repository.create(version.previous_data);
741
- await repository.save(restoredEntity);
742
- }
743
- }
351
+ const existing = await store.findOne({ _id: updated._id });
352
+ if (!existing)
353
+ return;
354
+ await this.db.insertInto("entity_versions").values({
355
+ entity_table: store.table,
356
+ entity_id: existing._id,
357
+ previous_data: JSON.stringify(existing),
358
+ block_num: blockNum,
359
+ change_type: changeType,
360
+ metadata: metadata ? JSON.stringify(metadata) : null
361
+ }).execute();
744
362
  }
745
363
  /**
746
- * Определить, должна ли новая версия заменить существующую
747
- */
748
- shouldReplaceVersion(existingVersion, newVersion) {
749
- const existingBlockNum = existingVersion.block_num;
750
- const newBlockNum = newVersion.block_num;
751
- if (existingBlockNum === null && newBlockNum === null) {
752
- return newVersion.created_at > existingVersion.created_at;
753
- }
754
- if (newBlockNum === null && existingBlockNum !== null) {
755
- return true;
756
- }
757
- if (existingBlockNum === null && newBlockNum !== null) {
758
- return false;
364
+ * Возвращает записи таблицы к состоянию на блоке форка.
365
+ *
366
+ * Версия хранит состояние записи ДО изменения и блок самого изменения. После
367
+ * форка недействительны изменения с блоком больше блока форка, поэтому для
368
+ * каждой записи берётся самое раннее такое изменение: состояние перед ним и
369
+ * есть состояние на блоке форка. Запись без изменений после форка остаётся
370
+ * как есть.
371
+ */
372
+ async restoreVersionsAfterFork(store, forkBlockNum) {
373
+ const invalidated = await this.db.selectFrom("entity_versions").selectAll().where("entity_table", "=", store.table).where("block_num", ">", forkBlockNum).orderBy("entity_id", "asc").orderBy("block_num", "asc").orderBy("created_at", "asc").execute();
374
+ const firstInvalidated = /* @__PURE__ */ new Map();
375
+ for (const version of invalidated) {
376
+ if (!firstInvalidated.has(version.entity_id))
377
+ firstInvalidated.set(version.entity_id, version);
759
378
  }
760
- if (existingBlockNum !== null && newBlockNum !== null) {
761
- return newBlockNum > existingBlockNum;
379
+ for (const [entityId, version] of firstInvalidated) {
380
+ const state = version.previous_data;
381
+ if (!state || appearedAfter(state, forkBlockNum))
382
+ continue;
383
+ const existing = await store.findOne({ _id: entityId });
384
+ await store.save(Object.assign(existing ?? {}, state));
762
385
  }
763
- return newVersion.created_at > existingVersion.created_at;
764
386
  }
765
387
  /**
766
- * Очистить версии после успешного восстановления
388
+ * Переносит записи таблицы с блоком больше блока форка в архив
389
+ * `invalidated_entities` и убирает их из таблицы — одной транзакцией.
390
+ * Возвращает число перенесённых записей.
767
391
  */
768
- async clearVersionsAfterBlock(blockNum) {
769
- return await this.entityVersionRepository.deleteVersionsAfterBlock(blockNum);
770
- }
771
- /**
772
- * Story 4.4: атомарно перенести live-ряды WHERE block_num > forkBlockNum в архив
773
- * `invalidated_entities` и удалить их из исходной таблицы. Возвращает количество
774
- * перенесённых рядов. Транзакция через DataSource — INSERT и DELETE либо оба
775
- * успешны, либо оба откатываются.
776
- *
777
- * Заменяет прежнюю пару findByBlockNumGreaterThan + deleteByBlockNumGreaterThan
778
- * в hot-path handleFork (sequence сейчас: archive → restoreFromVersions →
779
- * archiveVersions).
780
- */
781
- async archiveAndDeleteLiveAfterFork(repository, entityTable, forkBlockNum, forkEventId) {
782
- return this.dataSource.transaction(async (manager) => {
783
- const txRepo = manager.getRepository(repository.target);
784
- const txInvalidated = manager.getRepository(InvalidatedEntityTypeormEntity);
785
- const rows = await txRepo.createQueryBuilder("e").where("e.block_num > :forkBlockNum", { forkBlockNum }).getMany();
392
+ async archiveAndDeleteLiveAfterFork(store, forkBlockNum, forkEventId) {
393
+ return inTransaction(this.db, async (trx) => {
394
+ const live = store.on(trx);
395
+ const rows = await live.find({ block_num: moreThan(forkBlockNum) });
786
396
  if (rows.length === 0)
787
397
  return 0;
788
- const archiveRecords = rows.map(
789
- (row) => txInvalidated.create({
790
- entity_table: entityTable,
398
+ await trx.insertInto("invalidated_entities").values(
399
+ rows.map((row) => ({
400
+ entity_table: store.table,
791
401
  entity_id: row._id,
792
- data: { ...row },
402
+ data: JSON.stringify(row),
793
403
  invalidated_by_block: forkBlockNum,
794
404
  fork_event_id: forkEventId ?? null
795
- })
796
- );
797
- await txInvalidated.save(archiveRecords);
798
- await txRepo.createQueryBuilder().delete().where("block_num > :forkBlockNum", { forkBlockNum }).execute();
405
+ }))
406
+ ).execute();
407
+ await live.delete({ block_num: moreThan(forkBlockNum) });
799
408
  return rows.length;
800
409
  });
801
410
  }
802
411
  /**
803
- * Story 4.4: атомарно перенести entity_versions WHERE entity_table=... AND block_num > forkBlockNum
804
- * в архив `invalidated_entity_versions` и удалить их из entity_versions.
805
- * Возвращает количество перенесённых рядов.
806
- *
807
- * Запускается ПОСЛЕ restoreFromVersions — иначе restore не сможет прочитать
808
- * ещё-живые версии.
412
+ * Чистит архив форка: записи и версии, отменённые блоком раньше заданного.
413
+ * Возвращает число удалённых записей и версий.
414
+ */
415
+ async deleteArchiveOlderThan(minInvalidatedByBlock) {
416
+ const entities = await this.db.deleteFrom("invalidated_entities").where("invalidated_by_block", "<", minInvalidatedByBlock).execute();
417
+ const versions = await this.db.deleteFrom("invalidated_entity_versions").where("invalidated_by_block", "<", minInvalidatedByBlock).execute();
418
+ return { entities: affectedCount(entities), versions: affectedCount(versions) };
419
+ }
420
+ /**
421
+ * Переносит версии таблицы с блоком больше блока форка в архив
422
+ * `invalidated_entity_versions` и убирает их из `entity_versions` — одной
423
+ * транзакцией. Зовётся ПОСЛЕ восстановления: оно читает эти версии.
809
424
  */
810
425
  async archiveAndDeleteVersionsAfterFork(entityTable, forkBlockNum, forkEventId) {
811
- return this.dataSource.transaction(async (manager) => {
812
- const txVersions = manager.getRepository(EntityVersionTypeormEntity);
813
- const txArchive = manager.getRepository(InvalidatedEntityVersionTypeormEntity);
814
- const versions = await txVersions.createQueryBuilder("v").where("v.entity_table = :entityTable", { entityTable }).andWhere("v.block_num > :forkBlockNum", { forkBlockNum }).getMany();
426
+ return inTransaction(this.db, async (trx) => {
427
+ const versions = await trx.selectFrom("entity_versions").selectAll().where("entity_table", "=", entityTable).where("block_num", ">", forkBlockNum).execute();
815
428
  if (versions.length === 0)
816
429
  return 0;
817
- const archiveRecords = versions.map(
818
- (v) => txArchive.create({
819
- entity_table: v.entity_table,
820
- entity_id: v.entity_id,
821
- previous_data: v.previous_data,
822
- original_block_num: v.block_num ?? null,
430
+ await trx.insertInto("invalidated_entity_versions").values(
431
+ versions.map((version) => ({
432
+ entity_table: version.entity_table,
433
+ entity_id: version.entity_id,
434
+ previous_data: JSON.stringify(version.previous_data),
435
+ original_block_num: version.block_num ?? null,
823
436
  invalidated_by_block: forkBlockNum,
824
437
  fork_event_id: forkEventId ?? null,
825
- change_type: v.change_type,
826
- metadata: v.metadata ?? null
827
- })
828
- );
829
- await txArchive.save(archiveRecords);
830
- const ids = versions.map((v) => v.id);
831
- await txVersions.createQueryBuilder().delete().from(EntityVersionTypeormEntity).whereInIds(ids).execute();
438
+ change_type: version.change_type,
439
+ metadata: version.metadata ? JSON.stringify(version.metadata) : null
440
+ }))
441
+ ).execute();
442
+ await trx.deleteFrom("entity_versions").where(
443
+ "id",
444
+ "in",
445
+ versions.map((version) => version.id)
446
+ ).execute();
832
447
  return versions.length;
833
448
  });
834
449
  }
835
450
  };
836
- EntityVersioningService = __decorateClass$1([
451
+ ChainVersioningService = __decorateClass$1([
837
452
  Injectable(),
838
- __decorateParam(0, Inject(EntityVersionRepository)),
839
- __decorateParam(1, Inject(InvalidatedEntityRepository)),
840
- __decorateParam(2, Inject(InvalidatedEntityVersionRepository))
841
- ], EntityVersioningService);
453
+ __decorateParam(0, Inject(KYSELY))
454
+ ], ChainVersioningService);
455
+ function appearedAfter(state, forkBlockNum) {
456
+ const block = state.block_num;
457
+ return block !== null && block !== void 0 && Number(block) > forkBlockNum;
458
+ }
842
459
 
843
460
  var __defProp = Object.defineProperty;
844
461
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -851,176 +468,83 @@ var __decorateClass = (decorators, target, key, kind) => {
851
468
  __defProp(target, key, result);
852
469
  return result;
853
470
  };
854
- let BaseBlockchainRepository = class {
855
- constructor(repository, entityVersioningService) {
471
+ let BaseChainRepository = class {
472
+ constructor(repository, versioning) {
856
473
  this.repository = repository;
857
- this.entityVersioningService = entityVersioningService;
474
+ this.versioning = versioning;
858
475
  }
859
- /**
860
- * Получить имя таблицы сущности
861
- */
862
476
  getEntityTableName() {
863
- const entityClass = this.repository.target;
864
- if (typeof entityClass.getTableName === "function") {
865
- return entityClass.getTableName();
866
- }
867
- return this.repository.metadata.tableName;
477
+ return this.repository.table;
868
478
  }
869
- /**
870
- * Найти сущность по кастомному ключу синхронизации
871
- */
872
479
  async findBySyncKey(syncKey, syncValue) {
873
- const whereCondition = { [syncKey]: String(syncValue).toLowerCase() };
874
- const entity = await this.repository.findOne({
875
- where: whereCondition
876
- });
877
- return entity ? this.getMapper().toDomain(entity) : null;
480
+ const record = await this.repository.findOne({ [syncKey]: String(syncValue).toLowerCase() });
481
+ return record ? this.getMapper().toDomain(record) : null;
878
482
  }
879
- /**
880
- * Найти сущности с номером блока больше указанного
881
- */
882
483
  async findByBlockNumGreaterThan(blockNum) {
883
- const entities = await this.repository.createQueryBuilder("entity").where("entity.block_num > :blockNum", { blockNum }).getMany();
884
- return entities.map((entity) => this.getMapper().toDomain(entity));
484
+ const records = await this.repository.find({ block_num: moreThan(blockNum) });
485
+ return records.map((record) => this.getMapper().toDomain(record));
885
486
  }
886
- /**
887
- * Создать сущность если не существует
888
- * Используется для синхронизации данных из блокчейна
889
- */
487
+ /** Создаёт запись из данных цепи либо обновляет существующую. */
488
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
890
489
  async createIfNotExists(blockchainData, blockNum, present = true) {
891
490
  const syncKey = this.getSyncKey();
892
491
  const syncValue = this.extractSyncValueFromBlockchainData(blockchainData, syncKey);
893
492
  const existing = await this.findBySyncKey(syncKey, syncValue);
894
- if (existing) {
895
- const existingBlockNum = existing.getBlockNum();
896
- if (existingBlockNum != null && Number(blockNum) < Number(existingBlockNum)) {
897
- return existing;
898
- }
899
- existing.updateFromBlockchain(blockchainData, blockNum, present);
900
- return await this.save(existing);
901
- } else {
493
+ if (!existing) {
902
494
  const now = /* @__PURE__ */ new Date();
903
- const minimalDatabaseData = {
904
- _id: "",
905
- block_num: blockNum,
906
- present,
907
- _created_at: now,
908
- _updated_at: now,
909
- [syncKey]: String(syncValue).toLowerCase()
910
- // ключ синхронизации
911
- };
912
- const newEntity = this.createDomainEntity(minimalDatabaseData, blockchainData);
913
- return await this.save(newEntity);
495
+ const created = this.createDomainEntity(
496
+ { _id: "", block_num: blockNum, present, _created_at: now, _updated_at: now, [syncKey]: String(syncValue).toLowerCase() },
497
+ blockchainData
498
+ );
499
+ return this.save(created);
914
500
  }
501
+ const existingBlockNum = existing.getBlockNum();
502
+ if (existingBlockNum != null && Number(blockNum) < Number(existingBlockNum))
503
+ return existing;
504
+ existing.updateFromBlockchain(blockchainData, blockNum, present);
505
+ return this.save(existing);
915
506
  }
916
- /**
917
- * Удалить сущности с номером блока больше указанного (для обработки форков)
918
- */
919
507
  async deleteByBlockNumGreaterThan(blockNum) {
920
- await this.repository.createQueryBuilder().delete().where("block_num > :blockNum", { blockNum }).execute();
508
+ await this.repository.delete({ block_num: moreThan(blockNum) });
921
509
  }
922
- /**
923
- * Восстановить сущности из версий после форка
924
- */
925
510
  async restoreFromVersions(forkBlockNum) {
926
- await this.entityVersioningService.restoreVersionsAfterFork(this.repository, this.getEntityTableName(), forkBlockNum);
511
+ await this.versioning.restoreVersionsAfterFork(this.repository, forkBlockNum);
927
512
  }
928
- /**
929
- * Story 4.4: архивировать live-ряды WHERE block_num > forkBlockNum в invalidated_entities
930
- * и удалить из исходной таблицы (атомарно). Возвращает count. Заменяет в hot-path
931
- * handleFork прежнюю пару findByBlockNumGreaterThan + deleteByBlockNumGreaterThan.
932
- */
513
+ /** Переносит записи после блока форка в архив и убирает их из таблицы. */
933
514
  async archiveInvalidatedSince(forkBlockNum, forkEventId) {
934
- return this.entityVersioningService.archiveAndDeleteLiveAfterFork(
935
- this.repository,
936
- this.getEntityTableName(),
937
- forkBlockNum,
938
- forkEventId
939
- );
515
+ return this.versioning.archiveAndDeleteLiveAfterFork(this.repository, forkBlockNum, forkEventId);
940
516
  }
941
- /**
942
- * Story 4.4: архивировать entity_versions WHERE entity_table=... AND block_num > forkBlockNum
943
- * в invalidated_entity_versions и удалить из entity_versions (атомарно). Возвращает count.
944
- * Должен вызываться ПОСЛЕ restoreFromVersions — иначе restore не сможет прочитать ещё-живые версии.
945
- */
517
+ /** Переносит версии после блока форка в архив; зовётся после восстановления. */
946
518
  async archiveInvalidatedVersionsSince(forkBlockNum, forkEventId) {
947
- return this.entityVersioningService.archiveAndDeleteVersionsAfterFork(
948
- this.getEntityTableName(),
949
- forkBlockNum,
950
- forkEventId
951
- );
519
+ return this.versioning.archiveAndDeleteVersionsAfterFork(this.getEntityTableName(), forkBlockNum, forkEventId);
952
520
  }
953
- /**
954
- * Обновить сущность
955
- */
956
521
  async update(entity) {
957
- const typeormEntity = this.getMapper().toEntity(entity);
958
- await this.entityVersioningService.saveVersionBeforeUpdate(
959
- this.repository,
960
- this.getEntityTableName(),
961
- typeormEntity,
962
- typeormEntity.block_num || null,
963
- "update"
964
- );
965
- const savedEntity = await this.repository.save(typeormEntity);
966
- return this.getMapper().toDomain(savedEntity);
522
+ return this.persist(entity, "update");
967
523
  }
968
- /**
969
- * Создание и валидация сущности без сохранения в базу данных
970
- */
971
- async create(entity) {
972
- const typeormEntity = this.getMapper().toEntity(entity);
973
- return this.repository.create(typeormEntity);
524
+ async save(entity) {
525
+ return this.persist(entity, "save");
974
526
  }
975
- /**
976
- * Сохранение созданной сущности в базу данных
977
- */
978
- async saveCreated(entity) {
979
- const savedEntity = await this.repository.save(entity);
980
- return this.getMapper().toDomain(savedEntity);
527
+ /** Заготовка записи без сохранения в базу. */
528
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
529
+ async create(entity) {
530
+ return this.repository.create(this.getMapper().toEntity(entity));
981
531
  }
982
- /**
983
- * Сохранить сущность
984
- */
985
- async save(entity) {
986
- const typeormEntity = this.getMapper().toEntity(entity);
987
- if (typeormEntity._id) {
988
- await this.entityVersioningService.saveVersionBeforeUpdate(
989
- this.repository,
990
- this.getEntityTableName(),
991
- typeormEntity,
992
- typeormEntity.block_num || null,
993
- "save"
994
- );
995
- }
996
- const savedEntity = await this.repository.save(typeormEntity);
997
- return this.getMapper().toDomain(savedEntity);
532
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
533
+ async saveCreated(record) {
534
+ return this.getMapper().toDomain(await this.repository.save(withoutEmptyKey(record)));
998
535
  }
999
- /**
1000
- * Найти все сущности
1001
- */
1002
536
  async findAll() {
1003
- const entities = await this.repository.find();
1004
- return entities.map((entity) => this.getMapper().toDomain(entity));
537
+ const records = await this.repository.find();
538
+ return records.map((record) => this.getMapper().toDomain(record));
1005
539
  }
1006
- /**
1007
- * Найти сущность по внутреннему ID базы данных
1008
- */
1009
540
  async findById(_id) {
1010
- const entity = await this.repository.findOne({
1011
- where: { _id }
1012
- });
1013
- return entity ? this.getMapper().toDomain(entity) : null;
541
+ const record = await this.repository.findOne({ _id });
542
+ return record ? this.getMapper().toDomain(record) : null;
1014
543
  }
1015
- /**
1016
- * Удалить сущность по внутреннему ID базы данных
1017
- */
1018
544
  async delete(_id) {
1019
- await this.repository.delete(_id);
545
+ await this.repository.delete({ _id });
1020
546
  }
1021
- /**
1022
- * Извлечь значение ключа синхронизации из блокчейн данных
1023
- */
547
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1024
548
  extractSyncValueFromBlockchainData(blockchainData, syncKey) {
1025
549
  const value = blockchainData[syncKey];
1026
550
  if (value === null || value === void 0) {
@@ -1028,10 +552,23 @@ let BaseBlockchainRepository = class {
1028
552
  }
1029
553
  return value.toString().toLowerCase();
1030
554
  }
555
+ /** Сохраняет запись; у существующей перед изменением кладёт прежнее состояние в версии. */
556
+ async persist(entity, changeType) {
557
+ const record = withoutEmptyKey(this.getMapper().toEntity(entity));
558
+ if (record._id) {
559
+ await this.versioning.saveVersionBeforeUpdate(this.repository, record, record.block_num || null, changeType);
560
+ }
561
+ return this.getMapper().toDomain(await this.repository.save(record));
562
+ }
1031
563
  };
1032
- BaseBlockchainRepository = __decorateClass([
564
+ BaseChainRepository = __decorateClass([
1033
565
  Injectable()
1034
- ], BaseBlockchainRepository);
566
+ ], BaseChainRepository);
567
+ function withoutEmptyKey(record) {
568
+ if (!record._id)
569
+ delete record._id;
570
+ return record;
571
+ }
1035
572
 
1036
573
  function auditUnknownStatus(entityName, receivedStatus, logger, allowedStatuses) {
1037
574
  if (receivedStatus === void 0 || receivedStatus === null || receivedStatus === "") {
@@ -1057,4 +594,4 @@ function auditLogger() {
1057
594
  return currentAuditLogger;
1058
595
  }
1059
596
 
1060
- export { AbstractBlockchainDeltaMapper, AbstractEntitySyncService, BaseBlockchainRepository, BaseDomainEntity, BaseOutputDTO, BaseTypeormEntity, EntityVersionRepository, EntityVersionTypeormEntity, EntityVersioningService, FORK_AWARE_MARKER, InvalidatedEntityRepository, InvalidatedEntityTypeormEntity, InvalidatedEntityVersionRepository, InvalidatedEntityVersionTypeormEntity, UnsupportedContractVersionError, auditLogger, auditUnknownStatus, configureAuditLogger, configureSyncPolicy, isForkAware, syncPolicy };
597
+ export { AbstractBlockchainDeltaMapper, AbstractEntitySyncService, BaseChainRepository, BaseDomainEntity, BaseOutputDTO, ChainRecord, ChainVersioningService, FORK_AWARE_MARKER, UnsupportedContractVersionError, auditLogger, auditUnknownStatus, configureAuditLogger, configureSyncPolicy, isForkAware, syncPolicy };