@coopenomics/extension-kit 2026.12.2 → 2026.12.3-dev.10

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,595 +1 @@
1
- import { randomUUID } from 'crypto';
2
- import { Field, ObjectType } from '@nestjs/graphql';
3
- import { Injectable, Inject } from '@nestjs/common';
4
- import { KYSELY, inTransaction, moreThan, affectedCount } from '@coopenomics/extension-sdk/database';
5
- import { t } from '@coopenomics/i18n/server';
6
-
7
- class BaseDomainEntity {
8
- // Дата последнего обновления в базе данных
9
- /**
10
- * Конструктор базового класса
11
- *
12
- * @param databaseData - данные из базы данных
13
- * @param defaultStatus - статус по умолчанию, если не указан
14
- */
15
- constructor(databaseData, defaultStatus) {
16
- this._id = databaseData._id === "" ? randomUUID().toString() : databaseData._id;
17
- this.block_num = databaseData.block_num ?? 0;
18
- this.present = databaseData.present;
19
- this.status = databaseData.status ?? defaultStatus;
20
- this._created_at = databaseData._created_at ? new Date(databaseData._created_at) : /* @__PURE__ */ new Date();
21
- this._updated_at = databaseData._updated_at ? new Date(databaseData._updated_at) : /* @__PURE__ */ new Date();
22
- }
23
- /**
24
- * Обновление базовых данных сущности
25
- */
26
- updateBase(data) {
27
- if (data.block_num !== void 0)
28
- this.block_num = data.block_num;
29
- if (data.present !== void 0)
30
- this.present = data.present;
31
- if (data.status !== void 0)
32
- this.status = data.status;
33
- if (data._created_at !== void 0)
34
- this._created_at = data._created_at;
35
- if (data._updated_at !== void 0)
36
- this._updated_at = data._updated_at;
37
- }
38
- }
39
-
40
- var __defProp$3 = Object.defineProperty;
41
- var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
42
- var __decorateClass$3 = (decorators, target, key, kind) => {
43
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$3(target, key) : target;
44
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
45
- if (decorator = decorators[i])
46
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
47
- if (kind && result)
48
- __defProp$3(target, key, result);
49
- return result;
50
- };
51
- let BaseOutputDTO = class {
52
- };
53
- __decorateClass$3([
54
- Field(() => String, {
55
- description: "\u0412\u043D\u0443\u0442\u0440\u0435\u043D\u043D\u0438\u0439 ID \u0431\u0430\u0437\u044B \u0434\u0430\u043D\u043D\u044B\u0445"
56
- })
57
- ], BaseOutputDTO.prototype, "_id", 2);
58
- __decorateClass$3([
59
- Field(() => Boolean, {
60
- 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"
61
- })
62
- ], BaseOutputDTO.prototype, "present", 2);
63
- __decorateClass$3([
64
- Field(() => Number, {
65
- nullable: true,
66
- 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"
67
- })
68
- ], BaseOutputDTO.prototype, "block_num", 2);
69
- __decorateClass$3([
70
- Field(() => Date, {
71
- description: "\u0414\u0430\u0442\u0430 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u044F \u0437\u0430\u043F\u0438\u0441\u0438"
72
- })
73
- ], BaseOutputDTO.prototype, "_created_at", 2);
74
- __decorateClass$3([
75
- Field(() => Date, {
76
- 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"
77
- })
78
- ], BaseOutputDTO.prototype, "_updated_at", 2);
79
- BaseOutputDTO = __decorateClass$3([
80
- ObjectType("BaseEntity", {
81
- description: "\u0411\u0430\u0437\u043E\u0432\u044B\u0435 \u043F\u043E\u043B\u044F \u0441\u0443\u0449\u043D\u043E\u0441\u0442\u0438"
82
- })
83
- ], BaseOutputDTO);
84
-
85
- class AbstractBlockchainDeltaMapper {
86
- /**
87
- * Получение всех возможных паттернов событий для подписки
88
- * Возвращает массив паттернов типа "delta::contract::table"
89
- */
90
- getAllEventPatterns() {
91
- const patterns = [];
92
- const supportedContracts = this.getSupportedContractNames();
93
- const supportedTables = this.getSupportedTableNames();
94
- for (const contractName of supportedContracts) {
95
- for (const tableName of supportedTables) {
96
- patterns.push(`delta::${contractName}::${tableName}`);
97
- }
98
- }
99
- return patterns;
100
- }
101
- }
102
-
103
- const FORK_AWARE_MARKER = Symbol.for("mono.controller.shared.sync.ForkAware");
104
- function isForkAware(candidate) {
105
- if (candidate == null)
106
- return false;
107
- const obj = candidate;
108
- return obj[FORK_AWARE_MARKER] === true && typeof obj.handleFork === "function";
109
- }
110
-
111
- class UnsupportedContractVersionError extends Error {
112
- constructor(entityName, context) {
113
- super(
114
- `Unsupported contract version while mapping delta for ${entityName}: ${JSON.stringify(context)}`
115
- );
116
- this.entityName = entityName;
117
- this.context = context;
118
- this.name = "UnsupportedContractVersionError";
119
- }
120
- }
121
-
122
- const DEFAULTS = {
123
- unsupportedVersionStrict: false
124
- };
125
- let policy = DEFAULTS;
126
- function configureSyncPolicy(next) {
127
- policy = { ...DEFAULTS, ...next };
128
- }
129
- function syncPolicy() {
130
- return policy;
131
- }
132
-
133
- var __defProp$2 = Object.defineProperty;
134
- var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
135
- var __decorateClass$2 = (decorators, target, key, kind) => {
136
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$2(target, key) : target;
137
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
138
- if (decorator = decorators[i])
139
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
140
- if (kind && result)
141
- __defProp$2(target, key, result);
142
- return result;
143
- };
144
- var _a;
145
- let AbstractEntitySyncService = class {
146
- constructor(repository, mapper, logger) {
147
- this.repository = repository;
148
- this.mapper = mapper;
149
- this.logger = logger;
150
- /**
151
- * Symbol-маркер для ForkRegistryService (Story 4.1). Все 20+ наследников
152
- * автоматически попадают в реестр через bootstrap-сканирование Discovery —
153
- * без правок их onModuleInit.
154
- */
155
- this[_a] = true;
156
- this.logger.setContext(`${this.constructor.name}`);
157
- }
158
- static {
159
- _a = FORK_AWARE_MARKER;
160
- }
161
- /**
162
- * Обработка дельты блокчейна
163
- */
164
- async processDelta(delta) {
165
- try {
166
- this.logger.debug(`Processing ${this.entityName} delta for table ${delta.table} with key ${delta.primary_key}`);
167
- const syncValue = this.mapper.extractSyncValue(delta);
168
- const syncKey = this.mapper.extractSyncKey();
169
- const blockchainData = this.mapper.mapDeltaToBlockchainData(delta);
170
- if (!blockchainData) {
171
- const ctx = {
172
- contract: delta.contract ?? delta.code,
173
- table: delta.table,
174
- primary_key: delta.primary_key,
175
- block_num: Number(delta.block_num)
176
- };
177
- this.logger.error(
178
- `UNSUPPORTED_CONTRACT_VERSION: mapDeltaToBlockchainData returned null for ${this.entityName} ${syncValue}`,
179
- { entity: this.entityName, syncValue, ...ctx }
180
- );
181
- if (syncPolicy().unsupportedVersionStrict) {
182
- throw new UnsupportedContractVersionError(this.entityName, ctx);
183
- }
184
- return null;
185
- }
186
- const blockNum = Number(delta.block_num);
187
- const present = delta.present !== false;
188
- return await this.handleSyncDelta(syncKey, syncValue, blockchainData, blockNum, present);
189
- } catch (error) {
190
- if (error instanceof UnsupportedContractVersionError)
191
- throw error;
192
- this.logger.error(`Error processing ${this.entityName} delta: ${error.message}`, error.stack);
193
- return null;
194
- }
195
- }
196
- /**
197
- * Обработка создания/обновления сущности
198
- */
199
- async handleSyncDelta(syncKey, syncValue, blockchainData, blockNum, present = true) {
200
- const existingEntity = await this.repository.findBySyncKey(syncKey, syncValue);
201
- if (existingEntity) {
202
- const currentBlockNum = existingEntity.getBlockNum();
203
- if (currentBlockNum && blockNum < currentBlockNum) {
204
- this.logger.debug(
205
- `Skipping outdated update for ${this.entityName} ${syncValue}: block ${blockNum} <= ${currentBlockNum}`
206
- );
207
- return {
208
- created: false,
209
- updated: false,
210
- blockchainId: syncValue,
211
- blockNum: currentBlockNum
212
- };
213
- }
214
- existingEntity.updateFromBlockchain(blockchainData, blockNum, present);
215
- await this.repository.update(existingEntity);
216
- this.logger.debug(`\u041E\u0431\u043D\u043E\u0432\u043B\u0435\u043D ${this.entityName} ${syncValue} \u0432 \u0431\u043B\u043E\u043A\u0435 ${blockNum}`);
217
- return {
218
- created: false,
219
- updated: true,
220
- blockchainId: syncValue,
221
- blockNum
222
- };
223
- } else {
224
- await this.repository.createIfNotExists(blockchainData, blockNum, present);
225
- this.logger.debug(`\u0421\u043E\u0437\u0434\u0430\u043D ${this.entityName} ${syncValue} \u0432 \u0431\u043B\u043E\u043A\u0435 ${blockNum}`);
226
- return {
227
- created: true,
228
- updated: false,
229
- blockchainId: syncValue,
230
- blockNum
231
- };
232
- }
233
- }
234
- /**
235
- * Обработка удаления сущности
236
- */
237
- async handleEntityDeletion(syncValue, blockNum) {
238
- this.logger.debug(`Entity ${this.entityName} ${syncValue} was deleted at block ${blockNum}`);
239
- return {
240
- created: false,
241
- updated: false,
242
- blockchainId: syncValue,
243
- blockNum
244
- };
245
- }
246
- /**
247
- * Обработка форка — архивирование снесённых сущностей + восстановление из versions
248
- * + архивирование инвалидированных версий.
249
- *
250
- * Story 4.1: ошибки больше НЕ глотаются — обязательный re-throw для контракта
251
- * sequential ForkRegistry.runAll (INV-T03). Если rollback упадёт — parser2 не
252
- * ACK'нет fork-event, повторная доставка пересыграет цепочку. Уже отработавшие
253
- * syncer'ы в цепи будут no-op (versions уже подняты), сбойный — попробует ещё раз.
254
- *
255
- * Story 4.4: hard-delete заменён на «архив + delete» атомарно. Порядок:
256
- * 1) archiveInvalidatedSince — live-ряды WHERE block_num > N переезжают в
257
- * invalidated_entities, оригинал удаляется (одна транзакция).
258
- * 2) restoreFromVersions — поднять previous_data из ещё-живых entity_versions.
259
- * 3) archiveInvalidatedVersionsSince — entity_versions WHERE entity_table=... AND
260
- * block_num > N переезжают в invalidated_entity_versions, оригинал удаляется.
261
- * Запускается ПОСЛЕ restore, иначе restore не сможет прочитать живые версии.
262
- * Если репо не реализует archive методы (off-chain) — graceful no-op + fallback
263
- * на старую findByBlockNumGreaterThan/deleteByBlockNumGreaterThan для бэк-совместимости.
264
- */
265
- async handleFork(forkBlockNum, forkEventId) {
266
- this.logger.log(`Handling fork for ${this.entityName} at block ${forkBlockNum} (eventId=${forkEventId ?? "n/a"})`);
267
- let archivedLive = 0;
268
- if (this.repository.archiveInvalidatedSince) {
269
- archivedLive = await this.repository.archiveInvalidatedSince(forkBlockNum, forkEventId);
270
- this.logger.log(
271
- `\u0410\u0440\u0445\u0438\u0432\u0438\u0440\u043E\u0432\u0430\u043D\u043E ${archivedLive} live-\u0440\u044F\u0434\u043E\u0432 ${this.entityName} \u043D\u0430 \u0444\u043E\u0440\u043A\u0435 ${forkBlockNum}`
272
- );
273
- } else {
274
- const affected = await this.repository.findByBlockNumGreaterThan(forkBlockNum);
275
- await this.repository.deleteByBlockNumGreaterThan(forkBlockNum);
276
- archivedLive = affected.length;
277
- this.logger.warn(
278
- `${this.entityName}: archiveInvalidatedSince \u043D\u0435 \u0440\u0435\u0430\u043B\u0438\u0437\u043E\u0432\u0430\u043D \u2014 fallback \u043D\u0430 hard-delete (${archivedLive} \u0440\u044F\u0434\u043E\u0432)`
279
- );
280
- }
281
- if (this.repository.restoreFromVersions) {
282
- await this.repository.restoreFromVersions(forkBlockNum);
283
- this.logger.log(`Restored ${this.entityName} entities from versions after fork at block ${forkBlockNum}`);
284
- }
285
- if (this.repository.archiveInvalidatedVersionsSince) {
286
- const archivedVersions = await this.repository.archiveInvalidatedVersionsSince(forkBlockNum, forkEventId);
287
- this.logger.log(
288
- `\u0410\u0440\u0445\u0438\u0432\u0438\u0440\u043E\u0432\u0430\u043D\u043E ${archivedVersions} \u0432\u0435\u0440\u0441\u0438\u0439 ${this.entityName} \u043D\u0430 \u0444\u043E\u0440\u043A\u0435 ${forkBlockNum}`
289
- );
290
- }
291
- await this.afterForkProcessing(forkBlockNum, []);
292
- }
293
- /**
294
- * Дополнительные действия после обработки форка
295
- * Может быть переопределен в наследниках
296
- */
297
- async afterForkProcessing(_forkBlockNum, _affectedEntities) {
298
- }
299
- /**
300
- * Получение всех возможных имен событий для подписки
301
- */
302
- getAllEventPatterns() {
303
- return this.mapper.getAllEventPatterns();
304
- }
305
- /**
306
- * Получение всех поддерживаемых таблиц и контрактов для логирования
307
- */
308
- getSupportedVersions() {
309
- return {
310
- contracts: this.mapper.getSupportedContractNames(),
311
- tables: this.mapper.getSupportedTableNames()
312
- };
313
- }
314
- /**
315
- * Получение имени события для подписки на форки
316
- */
317
- getForkEventPattern() {
318
- return "fork::*";
319
- }
320
- };
321
- AbstractEntitySyncService = __decorateClass$2([
322
- Injectable()
323
- ], AbstractEntitySyncService);
324
-
325
- class ChainRecord {
326
- }
327
-
328
- var __defProp$1 = Object.defineProperty;
329
- var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
330
- var __decorateClass$1 = (decorators, target, key, kind) => {
331
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target;
332
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
333
- if (decorator = decorators[i])
334
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
335
- if (kind && result)
336
- __defProp$1(target, key, result);
337
- return result;
338
- };
339
- var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
340
- let ChainVersioningService = class {
341
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
342
- constructor(db) {
343
- this.db = db;
344
- }
345
- /** Кладёт в версии состояние записи перед её изменением; новой записи версионировать нечего. */
346
- async saveVersionBeforeUpdate(store, updated, blockNum, changeType, metadata) {
347
- if (!updated._id)
348
- return;
349
- const existing = await store.findOne({ _id: updated._id });
350
- if (!existing)
351
- return;
352
- await this.db.insertInto("entity_versions").values({
353
- entity_table: store.table,
354
- entity_id: existing._id,
355
- previous_data: JSON.stringify(existing),
356
- block_num: blockNum,
357
- change_type: changeType,
358
- metadata: metadata ? JSON.stringify(metadata) : null
359
- }).execute();
360
- }
361
- /**
362
- * Возвращает записи таблицы к состоянию на блоке форка.
363
- *
364
- * Версия хранит состояние записи ДО изменения и блок самого изменения. После
365
- * форка недействительны изменения с блоком больше блока форка, поэтому для
366
- * каждой записи берётся самое раннее такое изменение: состояние перед ним и
367
- * есть состояние на блоке форка. Запись без изменений после форка остаётся
368
- * как есть.
369
- */
370
- async restoreVersionsAfterFork(store, forkBlockNum) {
371
- 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();
372
- const firstInvalidated = /* @__PURE__ */ new Map();
373
- for (const version of invalidated) {
374
- if (!firstInvalidated.has(version.entity_id))
375
- firstInvalidated.set(version.entity_id, version);
376
- }
377
- for (const [entityId, version] of firstInvalidated) {
378
- const state = version.previous_data;
379
- if (!state || appearedAfter(state, forkBlockNum))
380
- continue;
381
- const existing = await store.findOne({ _id: entityId });
382
- await store.save(Object.assign(existing ?? {}, state));
383
- }
384
- }
385
- /**
386
- * Переносит записи таблицы с блоком больше блока форка в архив
387
- * `invalidated_entities` и убирает их из таблицы — одной транзакцией.
388
- * Возвращает число перенесённых записей.
389
- */
390
- async archiveAndDeleteLiveAfterFork(store, forkBlockNum, forkEventId) {
391
- return inTransaction(this.db, async (trx) => {
392
- const live = store.on(trx);
393
- const rows = await live.find({ block_num: moreThan(forkBlockNum) });
394
- if (rows.length === 0)
395
- return 0;
396
- await trx.insertInto("invalidated_entities").values(
397
- rows.map((row) => ({
398
- entity_table: store.table,
399
- entity_id: row._id,
400
- data: JSON.stringify(row),
401
- invalidated_by_block: forkBlockNum,
402
- fork_event_id: forkEventId ?? null
403
- }))
404
- ).execute();
405
- await live.delete({ block_num: moreThan(forkBlockNum) });
406
- return rows.length;
407
- });
408
- }
409
- /**
410
- * Чистит архив форка: записи и версии, отменённые блоком раньше заданного.
411
- * Возвращает число удалённых записей и версий.
412
- */
413
- async deleteArchiveOlderThan(minInvalidatedByBlock) {
414
- const entities = await this.db.deleteFrom("invalidated_entities").where("invalidated_by_block", "<", minInvalidatedByBlock).execute();
415
- const versions = await this.db.deleteFrom("invalidated_entity_versions").where("invalidated_by_block", "<", minInvalidatedByBlock).execute();
416
- return { entities: affectedCount(entities), versions: affectedCount(versions) };
417
- }
418
- /**
419
- * Переносит версии таблицы с блоком больше блока форка в архив
420
- * `invalidated_entity_versions` и убирает их из `entity_versions` — одной
421
- * транзакцией. Зовётся ПОСЛЕ восстановления: оно читает эти версии.
422
- */
423
- async archiveAndDeleteVersionsAfterFork(entityTable, forkBlockNum, forkEventId) {
424
- return inTransaction(this.db, async (trx) => {
425
- const versions = await trx.selectFrom("entity_versions").selectAll().where("entity_table", "=", entityTable).where("block_num", ">", forkBlockNum).execute();
426
- if (versions.length === 0)
427
- return 0;
428
- await trx.insertInto("invalidated_entity_versions").values(
429
- versions.map((version) => ({
430
- entity_table: version.entity_table,
431
- entity_id: version.entity_id,
432
- previous_data: JSON.stringify(version.previous_data),
433
- original_block_num: version.block_num ?? null,
434
- invalidated_by_block: forkBlockNum,
435
- fork_event_id: forkEventId ?? null,
436
- change_type: version.change_type,
437
- metadata: version.metadata ? JSON.stringify(version.metadata) : null
438
- }))
439
- ).execute();
440
- await trx.deleteFrom("entity_versions").where(
441
- "id",
442
- "in",
443
- versions.map((version) => version.id)
444
- ).execute();
445
- return versions.length;
446
- });
447
- }
448
- };
449
- ChainVersioningService = __decorateClass$1([
450
- Injectable(),
451
- __decorateParam(0, Inject(KYSELY))
452
- ], ChainVersioningService);
453
- function appearedAfter(state, forkBlockNum) {
454
- const block = state.block_num;
455
- return block !== null && block !== void 0 && Number(block) > forkBlockNum;
456
- }
457
-
458
- var __defProp = Object.defineProperty;
459
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
460
- var __decorateClass = (decorators, target, key, kind) => {
461
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
462
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
463
- if (decorator = decorators[i])
464
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
465
- if (kind && result)
466
- __defProp(target, key, result);
467
- return result;
468
- };
469
- let BaseChainRepository = class {
470
- constructor(repository, versioning) {
471
- this.repository = repository;
472
- this.versioning = versioning;
473
- }
474
- getEntityTableName() {
475
- return this.repository.table;
476
- }
477
- async findBySyncKey(syncKey, syncValue) {
478
- const record = await this.repository.findOne({ [syncKey]: String(syncValue).toLowerCase() });
479
- return record ? this.getMapper().toDomain(record) : null;
480
- }
481
- async findByBlockNumGreaterThan(blockNum) {
482
- const records = await this.repository.find({ block_num: moreThan(blockNum) });
483
- return records.map((record) => this.getMapper().toDomain(record));
484
- }
485
- /** Создаёт запись из данных цепи либо обновляет существующую. */
486
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
487
- async createIfNotExists(blockchainData, blockNum, present = true) {
488
- const syncKey = this.getSyncKey();
489
- const syncValue = this.extractSyncValueFromBlockchainData(blockchainData, syncKey);
490
- const existing = await this.findBySyncKey(syncKey, syncValue);
491
- if (!existing) {
492
- const now = /* @__PURE__ */ new Date();
493
- const created = this.createDomainEntity(
494
- { _id: "", block_num: blockNum, present, _created_at: now, _updated_at: now, [syncKey]: String(syncValue).toLowerCase() },
495
- blockchainData
496
- );
497
- return this.save(created);
498
- }
499
- const existingBlockNum = existing.getBlockNum();
500
- if (existingBlockNum != null && Number(blockNum) < Number(existingBlockNum))
501
- return existing;
502
- existing.updateFromBlockchain(blockchainData, blockNum, present);
503
- return this.save(existing);
504
- }
505
- async deleteByBlockNumGreaterThan(blockNum) {
506
- await this.repository.delete({ block_num: moreThan(blockNum) });
507
- }
508
- async restoreFromVersions(forkBlockNum) {
509
- await this.versioning.restoreVersionsAfterFork(this.repository, forkBlockNum);
510
- }
511
- /** Переносит записи после блока форка в архив и убирает их из таблицы. */
512
- async archiveInvalidatedSince(forkBlockNum, forkEventId) {
513
- return this.versioning.archiveAndDeleteLiveAfterFork(this.repository, forkBlockNum, forkEventId);
514
- }
515
- /** Переносит версии после блока форка в архив; зовётся после восстановления. */
516
- async archiveInvalidatedVersionsSince(forkBlockNum, forkEventId) {
517
- return this.versioning.archiveAndDeleteVersionsAfterFork(this.getEntityTableName(), forkBlockNum, forkEventId);
518
- }
519
- async update(entity) {
520
- return this.persist(entity, "update");
521
- }
522
- async save(entity) {
523
- return this.persist(entity, "save");
524
- }
525
- /** Заготовка записи без сохранения в базу. */
526
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
527
- async create(entity) {
528
- return this.repository.create(this.getMapper().toEntity(entity));
529
- }
530
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
531
- async saveCreated(record) {
532
- return this.getMapper().toDomain(await this.repository.save(withoutEmptyKey(record)));
533
- }
534
- async findAll() {
535
- const records = await this.repository.find();
536
- return records.map((record) => this.getMapper().toDomain(record));
537
- }
538
- async findById(_id) {
539
- const record = await this.repository.findOne({ _id });
540
- return record ? this.getMapper().toDomain(record) : null;
541
- }
542
- async delete(_id) {
543
- await this.repository.delete({ _id });
544
- }
545
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
546
- extractSyncValueFromBlockchainData(blockchainData, syncKey) {
547
- const value = blockchainData[syncKey];
548
- if (value === null || value === void 0) {
549
- throw new Error(`Sync key '${syncKey}' not found in blockchain data`);
550
- }
551
- return value.toString().toLowerCase();
552
- }
553
- /** Сохраняет запись; у существующей перед изменением кладёт прежнее состояние в версии. */
554
- async persist(entity, changeType) {
555
- const record = withoutEmptyKey(this.getMapper().toEntity(entity));
556
- if (record._id) {
557
- await this.versioning.saveVersionBeforeUpdate(this.repository, record, record.block_num || null, changeType);
558
- }
559
- return this.getMapper().toDomain(await this.repository.save(record));
560
- }
561
- };
562
- BaseChainRepository = __decorateClass([
563
- Injectable()
564
- ], BaseChainRepository);
565
- function withoutEmptyKey(record) {
566
- if (!record._id)
567
- delete record._id;
568
- return record;
569
- }
570
-
571
- function auditUnknownStatus(entityName, receivedStatus, logger, allowedStatuses) {
572
- if (receivedStatus === void 0 || receivedStatus === null || receivedStatus === "") {
573
- return;
574
- }
575
- const expected = allowedStatuses && allowedStatuses.length > 0 ? `[${allowedStatuses.join(", ")}]` : t("kit.syncAudit.notSpecified");
576
- logger.error(
577
- `UNKNOWN_ENTITY_STATUS ${entityName}: \u043F\u043E\u043B\u0443\u0447\u0435\u043D '${String(receivedStatus)}', \u043E\u0436\u0438\u0434\u0430\u044E\u0442\u0441\u044F ${expected}`,
578
- { entityName, receivedStatus, allowedStatuses }
579
- );
580
- }
581
-
582
- const consoleAuditLogger = {
583
- error(message, ...meta) {
584
- console.error(message, ...meta);
585
- }
586
- };
587
- let currentAuditLogger = consoleAuditLogger;
588
- function configureAuditLogger(logger) {
589
- currentAuditLogger = logger;
590
- }
591
- function auditLogger() {
592
- return currentAuditLogger;
593
- }
594
-
595
- export { AbstractBlockchainDeltaMapper, AbstractEntitySyncService, BaseChainRepository, BaseDomainEntity, BaseOutputDTO, ChainRecord, ChainVersioningService, FORK_AWARE_MARKER, UnsupportedContractVersionError, auditLogger, auditUnknownStatus, configureAuditLogger, configureSyncPolicy, isForkAware, syncPolicy };
1
+ export * from '@coopenomics/extension-sdk/sync';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@coopenomics/extension-kit",
3
3
  "type": "module",
4
- "version": "2026.12.2",
4
+ "version": "2026.12.3-dev.10",
5
5
  "description": "Служебный каркас расширения цифрового кооператива: базовый модуль, сущности и репозитории расширения, авторизация, каркас блокчейн-синхронизации, контракт миграций схемы, контракт реестра",
6
6
  "author": "Alex Ant <dacom.dark.sun@gmail.com>",
7
7
  "license": "MIT",
@@ -38,13 +38,13 @@
38
38
  "typecheck": "tsc --noEmit"
39
39
  },
40
40
  "dependencies": {
41
- "@coopenomics/extension-sdk": "2026.12.2"
41
+ "@coopenomics/extension-sdk": "2026.12.3-dev.10"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "@casl/ability": "^7.0.0",
45
45
  "@coopenomics/docs-templates": "1.6.16",
46
46
  "@coopenomics/i18n": "workspace:*",
47
- "@coopenomics/sdk": "2026.12.2",
47
+ "@coopenomics/sdk": "2026.12.3-dev.10",
48
48
  "@nestjs/common": "^10.0.0",
49
49
  "@nestjs/core": "^10.0.0",
50
50
  "@nestjs/graphql": "^12.2.1",
@@ -66,7 +66,7 @@
66
66
  "devDependencies": {
67
67
  "@casl/ability": "^7.0.0",
68
68
  "@coopenomics/docs-templates": "1.6.16",
69
- "@coopenomics/i18n": "2026.12.2",
69
+ "@coopenomics/i18n": "2026.12.3-dev.10",
70
70
  "@nestjs/common": "^10.0.0",
71
71
  "@nestjs/core": "^10.0.0",
72
72
  "@nestjs/graphql": "^12.2.1",
@@ -75,7 +75,7 @@
75
75
  "@wharfkit/session": "^1.4.0",
76
76
  "class-transformer": "^0.5.1",
77
77
  "class-validator": "^0.14.1",
78
- "cooptypes": "2026.12.2",
78
+ "cooptypes": "2026.12.3-dev.10",
79
79
  "graphql": "^16.9.0",
80
80
  "graphql-type-json": "^0.3.2",
81
81
  "kysely": "0.28.17",
@@ -87,5 +87,5 @@
87
87
  "unbuild": "^2.0.0",
88
88
  "zod": "^3.0.0"
89
89
  },
90
- "gitHead": "7e51e53092c0df79c8d2f240cd678bb465162aca"
90
+ "gitHead": "5502beafaa4cad5606d4861953445052fa4012f1"
91
91
  }