@matreshka/bff 0.36.0 → 0.37.0
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.
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ContextDiffBranch, ContextDiffNode } from "@matreshka/client-bff-protocol/messages/bff-to-client/context/context-values-message";
|
|
2
|
+
import type { Json } from "@matreshka/client-bff-protocol/types/json";
|
|
3
|
+
/** Сравнение элементов массива. По умолчанию — уникальный id, затем глубокое равенство. */
|
|
4
|
+
export type ContextDiffIdentity = (previous: Json, next: Json) => boolean;
|
|
5
|
+
/**
|
|
6
|
+
* Partial tree между двумя JSON-значениями.
|
|
7
|
+
*
|
|
8
|
+
* undefined — изменений нет.
|
|
9
|
+
*
|
|
10
|
+
* Входные значения не мутируются.
|
|
11
|
+
*/
|
|
12
|
+
export declare function createContextDiff(previous: Json, next: Json, identity?: ContextDiffIdentity): ContextDiffNode | undefined;
|
|
13
|
+
export declare function isContextDiffBranch(diff: ContextDiffNode): diff is ContextDiffBranch;
|
|
14
|
+
export declare function isEmptyContextDiff(diff: ContextDiffNode | undefined): boolean;
|
|
@@ -0,0 +1,672 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createContextDiff = createContextDiff;
|
|
4
|
+
exports.isContextDiffBranch = isContextDiffBranch;
|
|
5
|
+
exports.isEmptyContextDiff = isEmptyContextDiff;
|
|
6
|
+
const objects_diff_1 = require("@matreshka/shared/utils/objects-diff");
|
|
7
|
+
/**
|
|
8
|
+
* Partial tree между двумя JSON-значениями.
|
|
9
|
+
*
|
|
10
|
+
* undefined — изменений нет.
|
|
11
|
+
*
|
|
12
|
+
* Входные значения не мутируются.
|
|
13
|
+
*/
|
|
14
|
+
function createContextDiff(previous, next, identity) {
|
|
15
|
+
return createNodeDiff(toJsonData(previous), toJsonData(next), identity);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Убирает свойства со значением undefined.
|
|
19
|
+
*
|
|
20
|
+
* В JSON такого значения нет. Иначе diff получает {$set: undefined}
|
|
21
|
+
* и applyContextDiff бросает ContextDiffError.
|
|
22
|
+
* Дыра в массиве становится null, как при JSON.stringify.
|
|
23
|
+
*/
|
|
24
|
+
function toJsonData(value) {
|
|
25
|
+
if (Array.isArray(value)) {
|
|
26
|
+
let copy;
|
|
27
|
+
for (let index = 0; index < value.length; index++) {
|
|
28
|
+
const item = value[index];
|
|
29
|
+
const normalized = item === undefined ? null : toJsonData(item);
|
|
30
|
+
if (copy) {
|
|
31
|
+
copy.push(normalized);
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
if (normalized !== item) {
|
|
35
|
+
copy = value.slice(0, index);
|
|
36
|
+
copy.push(normalized);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return copy ?? value;
|
|
40
|
+
}
|
|
41
|
+
if (!isPlainObject(value)) {
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
let copy;
|
|
45
|
+
for (const key of Object.keys(value)) {
|
|
46
|
+
const item = value[key];
|
|
47
|
+
if (item === undefined) {
|
|
48
|
+
copy ?? (copy = { ...value });
|
|
49
|
+
delete copy[key];
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
const normalized = toJsonData(item);
|
|
53
|
+
if (normalized !== item) {
|
|
54
|
+
copy ?? (copy = { ...value });
|
|
55
|
+
copy[key] = normalized;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return copy ?? value;
|
|
59
|
+
}
|
|
60
|
+
function isContextDiffBranch(diff) {
|
|
61
|
+
return isPlainObject(diff);
|
|
62
|
+
}
|
|
63
|
+
function isEmptyContextDiff(diff) {
|
|
64
|
+
if (diff === undefined) {
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
if (Array.isArray(diff)) {
|
|
68
|
+
return diff.length === 0;
|
|
69
|
+
}
|
|
70
|
+
if (isPlainObject(diff)) {
|
|
71
|
+
return Object.keys(diff).length === 0;
|
|
72
|
+
}
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Создаёт diff для одного узла.
|
|
77
|
+
*
|
|
78
|
+
* Генерирует несколько допустимых вариантов и выбирает
|
|
79
|
+
* наиболее компактный по размеру JSON.
|
|
80
|
+
*/
|
|
81
|
+
function createNodeDiff(previous, next, identity) {
|
|
82
|
+
if (deepEqual(previous, next)) {
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
85
|
+
const candidates = [toCandidate(createSetNode(next), 2)];
|
|
86
|
+
if (isPlainObject(previous) && isPlainObject(next)) {
|
|
87
|
+
const partial = createObjectCandidate(previous, next, identity);
|
|
88
|
+
if (partial && verifyDiff(previous, next, partial)) {
|
|
89
|
+
candidates.push(toCandidate(partial, 0));
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (Array.isArray(previous) && Array.isArray(next)) {
|
|
93
|
+
for (const partial of createArrayCandidates(previous, next, identity)) {
|
|
94
|
+
if (verifyDiff(previous, next, partial)) {
|
|
95
|
+
candidates.push(toCandidate(partial, 0));
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return selectBestCandidate(candidates).diff;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Создаёт представление полной замены узла.
|
|
103
|
+
*
|
|
104
|
+
* Примитивы передаются непосредственно.
|
|
105
|
+
* Массивы и полная замена объекта требуют явного $set:
|
|
106
|
+
* массив в partial tree обновляет элементы по позиции.
|
|
107
|
+
*/
|
|
108
|
+
function createSetNode(next) {
|
|
109
|
+
if (isJsonPrimitive(next)) {
|
|
110
|
+
return next;
|
|
111
|
+
}
|
|
112
|
+
return { $set: structuredClone(next) };
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Запись нового значения.
|
|
116
|
+
*
|
|
117
|
+
* Новый объект — частичное дерево свойств от пустого объекта,
|
|
118
|
+
* если оно короче $set. Пустой объект и массив остаются $set.
|
|
119
|
+
*/
|
|
120
|
+
function createAssignment(next, identity) {
|
|
121
|
+
if (!isPlainObject(next)) {
|
|
122
|
+
return createSetNode(next);
|
|
123
|
+
}
|
|
124
|
+
return createNodeDiff({}, next, identity) ?? createSetNode(next);
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Создаёт частичное обновление объекта.
|
|
128
|
+
*
|
|
129
|
+
* $remove содержит имена непосредственно удаляемых свойств.
|
|
130
|
+
* Остальные свойства содержат дочерние diff.
|
|
131
|
+
*/
|
|
132
|
+
function createObjectCandidate(previous, next, identity) {
|
|
133
|
+
const remove = [];
|
|
134
|
+
const children = new Map();
|
|
135
|
+
for (const key of uniqueKeys(previous, next).sort()) {
|
|
136
|
+
const inPrevious = Object.prototype.hasOwnProperty.call(previous, key);
|
|
137
|
+
const inNext = Object.prototype.hasOwnProperty.call(next, key);
|
|
138
|
+
if (inPrevious && !inNext) {
|
|
139
|
+
remove.push(key);
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
if (!inPrevious && inNext) {
|
|
143
|
+
if (isReservedKey(key)) {
|
|
144
|
+
return undefined;
|
|
145
|
+
}
|
|
146
|
+
children.set(key, createAssignment(next[key], identity));
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
if (deepEqual(previous[key], next[key])) {
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
if (isReservedKey(key)) {
|
|
153
|
+
return undefined;
|
|
154
|
+
}
|
|
155
|
+
const child = createNodeDiff(previous[key], next[key], identity);
|
|
156
|
+
if (child !== undefined) {
|
|
157
|
+
children.set(key, child);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (remove.length === 0 && children.size === 0) {
|
|
161
|
+
return undefined;
|
|
162
|
+
}
|
|
163
|
+
const node = {};
|
|
164
|
+
if (remove.length > 0) {
|
|
165
|
+
node.$remove = remove;
|
|
166
|
+
}
|
|
167
|
+
for (const key of [...children.keys()].sort()) {
|
|
168
|
+
node[key] = children.get(key);
|
|
169
|
+
}
|
|
170
|
+
return node;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Создаёт кандидаты частичного обновления массива.
|
|
174
|
+
*
|
|
175
|
+
* Поддерживаются:
|
|
176
|
+
* - удаление;
|
|
177
|
+
* - перемещение;
|
|
178
|
+
* - вставка последовательности;
|
|
179
|
+
* - обновление существующих элементов;
|
|
180
|
+
* - добавление элементов в конец.
|
|
181
|
+
*
|
|
182
|
+
* Если преобразование невозможно представить корректно,
|
|
183
|
+
* возвращается пустой список кандидатов.
|
|
184
|
+
*/
|
|
185
|
+
function createArrayCandidates(previous, next, identity) {
|
|
186
|
+
const pairs = matchArrayElements(previous, next, identity);
|
|
187
|
+
if (!pairs) {
|
|
188
|
+
return [];
|
|
189
|
+
}
|
|
190
|
+
const removed = detectRemovals(previous.length, pairs);
|
|
191
|
+
const moves = detectMoves(pairs);
|
|
192
|
+
if (!moves) {
|
|
193
|
+
return [];
|
|
194
|
+
}
|
|
195
|
+
const updates = createIndexedUpdates(previous, next, pairs, identity);
|
|
196
|
+
const inserts = detectInserts(next, pairs);
|
|
197
|
+
const candidates = [];
|
|
198
|
+
const branch = createArrayBranch(removed, moves, inserts, updates);
|
|
199
|
+
if (branch) {
|
|
200
|
+
candidates.push(branch);
|
|
201
|
+
}
|
|
202
|
+
if (isPureSuffix(inserts, pairs, next.length)) {
|
|
203
|
+
const suffix = createArrayBranch(removed, moves, [], [...updates, ...suffixUpdates(inserts, identity)]);
|
|
204
|
+
if (suffix) {
|
|
205
|
+
candidates.push(suffix);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
if (removed.length === 0 &&
|
|
209
|
+
moves.length === 0 &&
|
|
210
|
+
next.length === previous.length) {
|
|
211
|
+
const positional = createPositionalArray(updates);
|
|
212
|
+
if (positional) {
|
|
213
|
+
candidates.push(positional);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return candidates;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Плотный префикс до последнего изменённого элемента.
|
|
220
|
+
*
|
|
221
|
+
* {} сохраняет элемент. Хвост без изменений в diff не входит.
|
|
222
|
+
* Используется только для обновления на тех же позициях:
|
|
223
|
+
* удаления и перемещения представляются отдельной веткой.
|
|
224
|
+
*/
|
|
225
|
+
function createPositionalArray(updates) {
|
|
226
|
+
if (updates.length === 0) {
|
|
227
|
+
return undefined;
|
|
228
|
+
}
|
|
229
|
+
const lastIndex = updates[updates.length - 1].index;
|
|
230
|
+
const slots = [];
|
|
231
|
+
for (let index = 0; index <= lastIndex; index++) {
|
|
232
|
+
slots.push({});
|
|
233
|
+
}
|
|
234
|
+
for (const update of updates) {
|
|
235
|
+
slots[update.index] = update.diff;
|
|
236
|
+
}
|
|
237
|
+
return slots;
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Сопоставляет элементы старого и нового массивов.
|
|
241
|
+
*
|
|
242
|
+
* Приоритет:
|
|
243
|
+
* 1. Пользовательская identity-функция.
|
|
244
|
+
* 2. Уникальный id.
|
|
245
|
+
* 3. Глубокое равенство.
|
|
246
|
+
* 4. Позиционное сопоставление оставшихся элементов.
|
|
247
|
+
*
|
|
248
|
+
* Несопоставленные элементы нового массива становятся вставками.
|
|
249
|
+
* Соседние вставки схлопываются в одну последовательность.
|
|
250
|
+
*/
|
|
251
|
+
function matchArrayElements(previous, next, identity) {
|
|
252
|
+
const used = new Set();
|
|
253
|
+
const pairs = [];
|
|
254
|
+
const unmatched = [];
|
|
255
|
+
const ids = identity ? undefined : uniqueIds(previous, next);
|
|
256
|
+
for (let newIndex = 0; newIndex < next.length; newIndex++) {
|
|
257
|
+
const oldIndex = findIdentityMatch(previous, next[newIndex], used, identity, ids);
|
|
258
|
+
if (oldIndex === undefined) {
|
|
259
|
+
unmatched.push(newIndex);
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
used.add(oldIndex);
|
|
263
|
+
pairs.push({
|
|
264
|
+
oldIndex,
|
|
265
|
+
newIndex,
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
const leftovers = [];
|
|
269
|
+
for (const newIndex of unmatched) {
|
|
270
|
+
const oldIndex = findEqualMatch(previous, next[newIndex], used);
|
|
271
|
+
if (oldIndex === undefined) {
|
|
272
|
+
leftovers.push(newIndex);
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
used.add(oldIndex);
|
|
276
|
+
pairs.push({
|
|
277
|
+
oldIndex,
|
|
278
|
+
newIndex,
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
for (const newIndex of leftovers) {
|
|
282
|
+
const oldIndex = findUnused(previous.length, used);
|
|
283
|
+
if (oldIndex === undefined) {
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
used.add(oldIndex);
|
|
287
|
+
pairs.push({
|
|
288
|
+
oldIndex,
|
|
289
|
+
newIndex,
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
return pairs;
|
|
293
|
+
}
|
|
294
|
+
function findIdentityMatch(previous, nextItem, used, identity, ids) {
|
|
295
|
+
if (identity) {
|
|
296
|
+
for (let oldIndex = 0; oldIndex < previous.length; oldIndex++) {
|
|
297
|
+
if (used.has(oldIndex)) {
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
if (identity(previous[oldIndex], nextItem)) {
|
|
301
|
+
return oldIndex;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return undefined;
|
|
305
|
+
}
|
|
306
|
+
const id = readId(nextItem);
|
|
307
|
+
if (id === undefined || !ids) {
|
|
308
|
+
return undefined;
|
|
309
|
+
}
|
|
310
|
+
const oldIndex = ids.get(idKey(id));
|
|
311
|
+
if (oldIndex === undefined || used.has(oldIndex)) {
|
|
312
|
+
return undefined;
|
|
313
|
+
}
|
|
314
|
+
return oldIndex;
|
|
315
|
+
}
|
|
316
|
+
function findEqualMatch(previous, nextItem, used) {
|
|
317
|
+
for (let oldIndex = 0; oldIndex < previous.length; oldIndex++) {
|
|
318
|
+
if (used.has(oldIndex)) {
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
if (deepEqual(previous[oldIndex], nextItem)) {
|
|
322
|
+
return oldIndex;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
return undefined;
|
|
326
|
+
}
|
|
327
|
+
function findUnused(length, used) {
|
|
328
|
+
for (let oldIndex = 0; oldIndex < length; oldIndex++) {
|
|
329
|
+
if (!used.has(oldIndex)) {
|
|
330
|
+
return oldIndex;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
return undefined;
|
|
334
|
+
}
|
|
335
|
+
function uniqueIds(previous, next) {
|
|
336
|
+
const previousCounts = countIds(previous);
|
|
337
|
+
const nextCounts = countIds(next);
|
|
338
|
+
const matches = new Map();
|
|
339
|
+
previous.forEach((item, index) => {
|
|
340
|
+
const id = readId(item);
|
|
341
|
+
if (id === undefined) {
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
const key = idKey(id);
|
|
345
|
+
if (previousCounts.get(key) !== 1 || nextCounts.get(key) !== 1) {
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
matches.set(key, index);
|
|
349
|
+
});
|
|
350
|
+
return matches;
|
|
351
|
+
}
|
|
352
|
+
function countIds(items) {
|
|
353
|
+
const counts = new Map();
|
|
354
|
+
for (const item of items) {
|
|
355
|
+
const id = readId(item);
|
|
356
|
+
if (id === undefined) {
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
const key = idKey(id);
|
|
360
|
+
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
361
|
+
}
|
|
362
|
+
return counts;
|
|
363
|
+
}
|
|
364
|
+
function readId(value) {
|
|
365
|
+
if (!isPlainObject(value)) {
|
|
366
|
+
return undefined;
|
|
367
|
+
}
|
|
368
|
+
const id = value.id;
|
|
369
|
+
if (typeof id === "string") {
|
|
370
|
+
return id;
|
|
371
|
+
}
|
|
372
|
+
if (typeof id === "number" && Number.isFinite(id)) {
|
|
373
|
+
return id;
|
|
374
|
+
}
|
|
375
|
+
return undefined;
|
|
376
|
+
}
|
|
377
|
+
function idKey(id) {
|
|
378
|
+
return typeof id === "number" ? `n:${id}` : `s:${id}`;
|
|
379
|
+
}
|
|
380
|
+
function detectRemovals(length, pairs) {
|
|
381
|
+
const used = new Set(pairs.map((pair) => pair.oldIndex));
|
|
382
|
+
const removed = [];
|
|
383
|
+
for (let index = 0; index < length; index++) {
|
|
384
|
+
if (!used.has(index)) {
|
|
385
|
+
removed.push(index);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
return removed;
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Вычисляет минимальный набор перемещений.
|
|
392
|
+
*
|
|
393
|
+
* Индексы операций относятся к массиву после удаления
|
|
394
|
+
* и применяются последовательно.
|
|
395
|
+
*/
|
|
396
|
+
function detectMoves(pairs) {
|
|
397
|
+
const afterRemove = pairs
|
|
398
|
+
.slice()
|
|
399
|
+
.sort((left, right) => left.oldIndex - right.oldIndex)
|
|
400
|
+
.map((pair) => pair.oldIndex);
|
|
401
|
+
const target = pairs
|
|
402
|
+
.slice()
|
|
403
|
+
.sort((left, right) => left.newIndex - right.newIndex)
|
|
404
|
+
.map((pair) => pair.oldIndex);
|
|
405
|
+
const lisMoves = movesByLis(afterRemove, target);
|
|
406
|
+
const greedyMoves = movesByGreedy(afterRemove, target);
|
|
407
|
+
const workable = [lisMoves, greedyMoves].filter((moves) => sameOrder(simulateMoves(afterRemove, moves), target));
|
|
408
|
+
if (workable.length === 0) {
|
|
409
|
+
return undefined;
|
|
410
|
+
}
|
|
411
|
+
workable.sort((left, right) => left.length - right.length);
|
|
412
|
+
return workable[0];
|
|
413
|
+
}
|
|
414
|
+
function movesByLis(source, target) {
|
|
415
|
+
if (source.length === 0) {
|
|
416
|
+
return [];
|
|
417
|
+
}
|
|
418
|
+
const targetPos = new Map();
|
|
419
|
+
target.forEach((id, index) => {
|
|
420
|
+
targetPos.set(id, index);
|
|
421
|
+
});
|
|
422
|
+
const ranks = source.map((id) => targetPos.get(id) ?? 0);
|
|
423
|
+
const frozen = new Set(lisIndices(ranks).map((index) => source[index]));
|
|
424
|
+
const items = source.slice();
|
|
425
|
+
const moves = [];
|
|
426
|
+
for (const item of target) {
|
|
427
|
+
if (frozen.has(item)) {
|
|
428
|
+
continue;
|
|
429
|
+
}
|
|
430
|
+
const from = items.indexOf(item);
|
|
431
|
+
const to = targetPos.get(item) ?? 0;
|
|
432
|
+
if (from === to) {
|
|
433
|
+
continue;
|
|
434
|
+
}
|
|
435
|
+
items.splice(from, 1);
|
|
436
|
+
items.splice(to, 0, item);
|
|
437
|
+
moves.push([from, to]);
|
|
438
|
+
}
|
|
439
|
+
return moves;
|
|
440
|
+
}
|
|
441
|
+
function movesByGreedy(source, target) {
|
|
442
|
+
const items = source.slice();
|
|
443
|
+
const moves = [];
|
|
444
|
+
for (let index = 0; index < target.length; index++) {
|
|
445
|
+
if (items[index] === target[index]) {
|
|
446
|
+
continue;
|
|
447
|
+
}
|
|
448
|
+
const from = items.indexOf(target[index]);
|
|
449
|
+
const [item] = items.splice(from, 1);
|
|
450
|
+
items.splice(index, 0, item);
|
|
451
|
+
moves.push([from, index]);
|
|
452
|
+
}
|
|
453
|
+
return moves;
|
|
454
|
+
}
|
|
455
|
+
function simulateMoves(source, moves) {
|
|
456
|
+
const items = source.slice();
|
|
457
|
+
for (const [from, to] of moves) {
|
|
458
|
+
if (from < 0 || from >= items.length || to < 0 || to >= items.length) {
|
|
459
|
+
return [];
|
|
460
|
+
}
|
|
461
|
+
const [item] = items.splice(from, 1);
|
|
462
|
+
items.splice(to, 0, item);
|
|
463
|
+
}
|
|
464
|
+
return items;
|
|
465
|
+
}
|
|
466
|
+
function sameOrder(left, right) {
|
|
467
|
+
if (left.length !== right.length) {
|
|
468
|
+
return false;
|
|
469
|
+
}
|
|
470
|
+
return left.every((item, index) => item === right[index]);
|
|
471
|
+
}
|
|
472
|
+
function lisIndices(values) {
|
|
473
|
+
const tails = [];
|
|
474
|
+
const previous = new Array(values.length).fill(-1);
|
|
475
|
+
for (let index = 0; index < values.length; index++) {
|
|
476
|
+
let low = 0;
|
|
477
|
+
let high = tails.length;
|
|
478
|
+
while (low < high) {
|
|
479
|
+
const mid = (low + high) >> 1;
|
|
480
|
+
if (values[tails[mid]] < values[index]) {
|
|
481
|
+
low = mid + 1;
|
|
482
|
+
}
|
|
483
|
+
else {
|
|
484
|
+
high = mid;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
if (low > 0) {
|
|
488
|
+
previous[index] = tails[low - 1];
|
|
489
|
+
}
|
|
490
|
+
if (low === tails.length) {
|
|
491
|
+
tails.push(index);
|
|
492
|
+
}
|
|
493
|
+
else {
|
|
494
|
+
tails[low] = index;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
const result = [];
|
|
498
|
+
if (tails.length === 0) {
|
|
499
|
+
return result;
|
|
500
|
+
}
|
|
501
|
+
for (let index = tails[tails.length - 1]; index !== -1; index = previous[index]) {
|
|
502
|
+
result.push(index);
|
|
503
|
+
}
|
|
504
|
+
result.reverse();
|
|
505
|
+
return result;
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* Создаёт обновления элементов массива.
|
|
509
|
+
*
|
|
510
|
+
* Существующие элементы адресуются по итоговым индексам.
|
|
511
|
+
* Новые элементы передаются отдельно через $insert.
|
|
512
|
+
*/
|
|
513
|
+
function createIndexedUpdates(previous, next, pairs, identity) {
|
|
514
|
+
const updates = [];
|
|
515
|
+
for (const pair of pairs) {
|
|
516
|
+
const child = createNodeDiff(previous[pair.oldIndex], next[pair.newIndex], identity);
|
|
517
|
+
if (child !== undefined) {
|
|
518
|
+
updates.push({
|
|
519
|
+
index: pair.newIndex,
|
|
520
|
+
diff: child,
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
updates.sort((left, right) => left.index - right.index);
|
|
525
|
+
return updates;
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* Группирует соседние несопоставленные элементы.
|
|
529
|
+
*
|
|
530
|
+
* Индекс — позиция в итоговом массиве. При последовательном применении
|
|
531
|
+
* снизу вверх он совпадает с позицией после предыдущих вставок.
|
|
532
|
+
*/
|
|
533
|
+
function detectInserts(next, pairs) {
|
|
534
|
+
const matched = new Set(pairs.map((pair) => pair.newIndex));
|
|
535
|
+
const inserts = [];
|
|
536
|
+
let index = 0;
|
|
537
|
+
while (index < next.length) {
|
|
538
|
+
if (matched.has(index)) {
|
|
539
|
+
index += 1;
|
|
540
|
+
continue;
|
|
541
|
+
}
|
|
542
|
+
const start = index;
|
|
543
|
+
const elements = [];
|
|
544
|
+
while (index < next.length && !matched.has(index)) {
|
|
545
|
+
elements.push(structuredClone(next[index]));
|
|
546
|
+
index += 1;
|
|
547
|
+
}
|
|
548
|
+
inserts.push([start, elements]);
|
|
549
|
+
}
|
|
550
|
+
return inserts;
|
|
551
|
+
}
|
|
552
|
+
function isPureSuffix(inserts, pairs, nextLength) {
|
|
553
|
+
if (inserts.length !== 1) {
|
|
554
|
+
return false;
|
|
555
|
+
}
|
|
556
|
+
const [index, elements] = inserts[0];
|
|
557
|
+
return index === pairs.length && index + elements.length === nextLength;
|
|
558
|
+
}
|
|
559
|
+
function suffixUpdates(inserts, identity) {
|
|
560
|
+
const [start, elements] = inserts[0];
|
|
561
|
+
return elements.map((element, offset) => ({
|
|
562
|
+
index: start + offset,
|
|
563
|
+
diff: createAssignment(element, identity),
|
|
564
|
+
}));
|
|
565
|
+
}
|
|
566
|
+
function createArrayBranch(removed, moves, inserts, updates) {
|
|
567
|
+
if (removed.length === 0 &&
|
|
568
|
+
moves.length === 0 &&
|
|
569
|
+
inserts.length === 0 &&
|
|
570
|
+
updates.length === 0) {
|
|
571
|
+
return undefined;
|
|
572
|
+
}
|
|
573
|
+
const node = {};
|
|
574
|
+
if (removed.length > 0) {
|
|
575
|
+
node.$remove = removed;
|
|
576
|
+
}
|
|
577
|
+
if (moves.length > 0) {
|
|
578
|
+
node.$move = moves;
|
|
579
|
+
}
|
|
580
|
+
if (inserts.length > 0) {
|
|
581
|
+
node.$insert = inserts;
|
|
582
|
+
}
|
|
583
|
+
for (const update of updates) {
|
|
584
|
+
node[String(update.index)] = update.diff;
|
|
585
|
+
}
|
|
586
|
+
return node;
|
|
587
|
+
}
|
|
588
|
+
function verifyDiff(previous, next, diff) {
|
|
589
|
+
return deepEqual((0, objects_diff_1.applyContextDiff)(previous, diff), next);
|
|
590
|
+
}
|
|
591
|
+
function toCandidate(diff, order) {
|
|
592
|
+
return {
|
|
593
|
+
diff,
|
|
594
|
+
size: serializedSize(diff),
|
|
595
|
+
priority: priorityOf(diff),
|
|
596
|
+
order,
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
function selectBestCandidate(candidates) {
|
|
600
|
+
return candidates.sort((left, right) => {
|
|
601
|
+
if (left.size !== right.size) {
|
|
602
|
+
return left.size - right.size;
|
|
603
|
+
}
|
|
604
|
+
if (left.priority !== right.priority) {
|
|
605
|
+
return left.priority - right.priority;
|
|
606
|
+
}
|
|
607
|
+
return left.order - right.order;
|
|
608
|
+
})[0];
|
|
609
|
+
}
|
|
610
|
+
function priorityOf(diff) {
|
|
611
|
+
if (isJsonPrimitive(diff)) {
|
|
612
|
+
return 3;
|
|
613
|
+
}
|
|
614
|
+
if (Array.isArray(diff)) {
|
|
615
|
+
return 1;
|
|
616
|
+
}
|
|
617
|
+
if (Object.prototype.hasOwnProperty.call(diff, "$set")) {
|
|
618
|
+
return 3;
|
|
619
|
+
}
|
|
620
|
+
if (diff.$remove !== undefined ||
|
|
621
|
+
diff.$move !== undefined ||
|
|
622
|
+
diff.$insert !== undefined) {
|
|
623
|
+
return 2;
|
|
624
|
+
}
|
|
625
|
+
return 1;
|
|
626
|
+
}
|
|
627
|
+
function serializedSize(value) {
|
|
628
|
+
return Buffer.byteLength(JSON.stringify(value), "utf8");
|
|
629
|
+
}
|
|
630
|
+
function uniqueKeys(previous, next) {
|
|
631
|
+
return [...new Set([...Object.keys(previous), ...Object.keys(next)])];
|
|
632
|
+
}
|
|
633
|
+
function isReservedKey(key) {
|
|
634
|
+
return key.startsWith("$");
|
|
635
|
+
}
|
|
636
|
+
function deepEqual(left, right) {
|
|
637
|
+
if (Object.is(left, right)) {
|
|
638
|
+
return true;
|
|
639
|
+
}
|
|
640
|
+
if (Array.isArray(left) && Array.isArray(right)) {
|
|
641
|
+
if (left.length !== right.length) {
|
|
642
|
+
return false;
|
|
643
|
+
}
|
|
644
|
+
return left.every((item, index) => deepEqual(item, right[index]));
|
|
645
|
+
}
|
|
646
|
+
if (isPlainObject(left) && isPlainObject(right)) {
|
|
647
|
+
const leftKeys = Object.keys(left);
|
|
648
|
+
const rightKeys = Object.keys(right);
|
|
649
|
+
if (leftKeys.length !== rightKeys.length) {
|
|
650
|
+
return false;
|
|
651
|
+
}
|
|
652
|
+
return leftKeys.every((key) => Object.prototype.hasOwnProperty.call(right, key) &&
|
|
653
|
+
deepEqual(left[key], right[key]));
|
|
654
|
+
}
|
|
655
|
+
return false;
|
|
656
|
+
}
|
|
657
|
+
function isJsonPrimitive(value) {
|
|
658
|
+
if (value === null) {
|
|
659
|
+
return true;
|
|
660
|
+
}
|
|
661
|
+
if (typeof value === "number") {
|
|
662
|
+
return Number.isFinite(value);
|
|
663
|
+
}
|
|
664
|
+
return typeof value === "string" || typeof value === "boolean";
|
|
665
|
+
}
|
|
666
|
+
function isPlainObject(value) {
|
|
667
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
668
|
+
return false;
|
|
669
|
+
}
|
|
670
|
+
const prototype = Object.getPrototypeOf(value);
|
|
671
|
+
return prototype === Object.prototype || prototype === null;
|
|
672
|
+
}
|
|
@@ -30,9 +30,9 @@ const client_context_1 = require("../client-context");
|
|
|
30
30
|
const assert_non_overlapping_context_paths_1 = require("../utils/assert-non-overlapping-context-paths");
|
|
31
31
|
const assert_safe_dotted_path_1 = require("../utils/assert-safe-dotted-path");
|
|
32
32
|
const deep_pick_1 = require("../utils/deep-pick");
|
|
33
|
-
const objects_diff_1 = require("../utils/objects-diff");
|
|
34
33
|
const replace_context_keys_1 = require("../utils/replace-context-keys");
|
|
35
34
|
const assert_client_update_schema_1 = require("./assert-client-update-schema");
|
|
35
|
+
const context_diff_1 = require("./context-diff");
|
|
36
36
|
const context_ref_1 = require("./context-ref");
|
|
37
37
|
__exportStar(require("./context-create"), exports);
|
|
38
38
|
/** @see ContextClientUpdatesForbiddenSchema */
|
|
@@ -322,24 +322,27 @@ class Context {
|
|
|
322
322
|
// Во время init() не шлём diff (сохраняем текущую семантику: первая "реальная" установка данных не должна рассылаться как изменения).
|
|
323
323
|
if (!this.initializing && prevData) {
|
|
324
324
|
let diff;
|
|
325
|
+
let diffReady = false;
|
|
325
326
|
getRegistryEntry(this.id)?.clients.forEach((_, client) => {
|
|
326
327
|
if (this.dataChangedByClient !== client) {
|
|
327
328
|
// Не первое присваивание
|
|
328
329
|
// Сравнение двух объектов, поиск измененных ключей
|
|
329
|
-
if (
|
|
330
|
-
diff = (0,
|
|
330
|
+
if (!diffReady) {
|
|
331
|
+
diff = (0, context_diff_1.createContextDiff)(prevData, data);
|
|
332
|
+
diffReady = true;
|
|
331
333
|
}
|
|
332
|
-
if (
|
|
334
|
+
if (diff &&
|
|
335
|
+
(0, context_diff_1.isContextDiffBranch)(diff) &&
|
|
336
|
+
!(0, context_diff_1.isEmptyContextDiff)(diff)) {
|
|
333
337
|
// Изменения есть
|
|
334
|
-
client.outcomingMessage$.next(new index_1.ContextValuesMessage(this.id,
|
|
335
|
-
key,
|
|
336
|
-
value,
|
|
337
|
-
}))));
|
|
338
|
+
client.outcomingMessage$.next(new index_1.ContextValuesMessage(this.id, diff));
|
|
338
339
|
}
|
|
339
340
|
}
|
|
340
341
|
});
|
|
341
342
|
}
|
|
342
343
|
this.dataChangedByClient = undefined;
|
|
344
|
+
// Снимок отделён от сравнения: копия защищает prev от последующей мутации,
|
|
345
|
+
// а createContextDiff сравнивает структуру, а не ссылки внутри копии.
|
|
343
346
|
prevData = structuredClone(data);
|
|
344
347
|
});
|
|
345
348
|
}
|
|
@@ -361,13 +364,12 @@ class Context {
|
|
|
361
364
|
emitDiffAndWait(diff) {
|
|
362
365
|
const recipients = this.recipientsForDiff();
|
|
363
366
|
this.dataChangedByClient = undefined;
|
|
364
|
-
if (
|
|
367
|
+
if (!diff ||
|
|
368
|
+
!(0, context_diff_1.isContextDiffBranch)(diff) ||
|
|
369
|
+
(0, context_diff_1.isEmptyContextDiff)(diff) ||
|
|
370
|
+
recipients.length === 0) {
|
|
365
371
|
return this.completeImmediately();
|
|
366
372
|
}
|
|
367
|
-
const payload = Object.entries(diff).map(([key, value]) => ({
|
|
368
|
-
key,
|
|
369
|
-
value,
|
|
370
|
-
}));
|
|
371
373
|
const result$ = new rxjs_1.ReplaySubject(recipients.length);
|
|
372
374
|
const delivered = [];
|
|
373
375
|
let finalized = false;
|
|
@@ -393,7 +395,7 @@ class Context {
|
|
|
393
395
|
}
|
|
394
396
|
};
|
|
395
397
|
for (const client of recipients) {
|
|
396
|
-
const message = new index_1.ContextValuesMessage(this.id,
|
|
398
|
+
const message = new index_1.ContextValuesMessage(this.id, diff);
|
|
397
399
|
subscriptions.add(client.waitForDelivery(message).subscribe({
|
|
398
400
|
next: () => finishSuccess(client),
|
|
399
401
|
error: (error) => finishError(error),
|
|
@@ -406,9 +408,8 @@ class Context {
|
|
|
406
408
|
this.assertNotDestroyed();
|
|
407
409
|
this.assertInitialized();
|
|
408
410
|
const currentData = this.data$.getValue();
|
|
409
|
-
const prevData = structuredClone(currentData);
|
|
410
411
|
const nextData = mutator(structuredClone(currentData));
|
|
411
|
-
const diff = (0,
|
|
412
|
+
const diff = (0, context_diff_1.createContextDiff)(currentData, nextData);
|
|
412
413
|
this.skipNextDataSync = true;
|
|
413
414
|
this.data$.next(nextData);
|
|
414
415
|
return this.emitDiffAndWait(diff);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@matreshka/bff",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.37.0",
|
|
4
4
|
"description": "Matreshka BFF: server-driven UI runtime — routing, pages, context, component DSL, and platform APIs",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -62,9 +62,9 @@
|
|
|
62
62
|
"vitest": "^4.1.0"
|
|
63
63
|
},
|
|
64
64
|
"dependencies": {
|
|
65
|
-
"@matreshka/client-bff-protocol": "^0.
|
|
65
|
+
"@matreshka/client-bff-protocol": "^0.6.0",
|
|
66
66
|
"@matreshka/gateway-bff-protocol": "^0.1.0",
|
|
67
|
-
"@matreshka/shared": "^0.
|
|
67
|
+
"@matreshka/shared": "^0.26.0",
|
|
68
68
|
"@simplewebauthn/server": "^13.1.1",
|
|
69
69
|
"@simplewebauthn/types": "^12.0.0",
|
|
70
70
|
"fast-xml-parser": "^5.3.3",
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Вычисляет разницу между двумя объектами и возвращает изменённые поля.
|
|
3
|
-
*
|
|
4
|
-
* Поддерживает вложенные объекты. Если изменились все поля вложенного объекта —
|
|
5
|
-
* возвращает его целиком. В противном случае возвращает только изменённые поля.
|
|
6
|
-
*
|
|
7
|
-
* @param oldObj Исходный объект.
|
|
8
|
-
* @param newObj Новый объект.
|
|
9
|
-
* @param prefix Префикс для формирования ключей (используется при рекурсии).
|
|
10
|
-
* @param diff Промежуточное хранилище отличий (используется при рекурсии).
|
|
11
|
-
* @returns Объект с отличиями, где ключ — путь к полю, значение — новое значение.
|
|
12
|
-
*/
|
|
13
|
-
export declare const objectsDiff: (oldObj: Record<string, any>, newObj: Record<string, any>, prefix?: string, diff?: Record<string, unknown>) => Record<string, unknown>;
|
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.objectsDiff = void 0;
|
|
4
|
-
/**
|
|
5
|
-
* Вычисляет разницу между двумя объектами и возвращает изменённые поля.
|
|
6
|
-
*
|
|
7
|
-
* Поддерживает вложенные объекты. Если изменились все поля вложенного объекта —
|
|
8
|
-
* возвращает его целиком. В противном случае возвращает только изменённые поля.
|
|
9
|
-
*
|
|
10
|
-
* @param oldObj Исходный объект.
|
|
11
|
-
* @param newObj Новый объект.
|
|
12
|
-
* @param prefix Префикс для формирования ключей (используется при рекурсии).
|
|
13
|
-
* @param diff Промежуточное хранилище отличий (используется при рекурсии).
|
|
14
|
-
* @returns Объект с отличиями, где ключ — путь к полю, значение — новое значение.
|
|
15
|
-
*/
|
|
16
|
-
const objectsDiff = (oldObj, newObj, prefix = "", diff = {}) => {
|
|
17
|
-
const oldObjectsKeys = Object.keys(oldObj);
|
|
18
|
-
const newObjectsKeys = Object.keys(newObj);
|
|
19
|
-
new Set(oldObjectsKeys.concat(newObjectsKeys)).forEach((key) => {
|
|
20
|
-
// Перебор всех ключей
|
|
21
|
-
if (typeof oldObj[key] === "object" &&
|
|
22
|
-
typeof newObj[key] === "object" &&
|
|
23
|
-
oldObj[key] !== null &&
|
|
24
|
-
newObj[key] !== null) {
|
|
25
|
-
// Проверка на массивы - если это массивы, сравниваем их по ссылке
|
|
26
|
-
if (Array.isArray(oldObj[key]) || Array.isArray(newObj[key])) {
|
|
27
|
-
// Если один из них массив, а другой нет, или это разные ссылки - считаем измененным
|
|
28
|
-
if (Array.isArray(oldObj[key]) !== Array.isArray(newObj[key]) ||
|
|
29
|
-
oldObj[key] !== newObj[key]) {
|
|
30
|
-
diff[prefix + key] = newObj[key];
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
else {
|
|
34
|
-
// если они оба объекты, могли измениться поля внутри
|
|
35
|
-
const nestedDiff = (0, exports.objectsDiff)(oldObj[key], newObj[key], prefix + key + ".");
|
|
36
|
-
if (Object.keys(nestedDiff).length) {
|
|
37
|
-
// Важно понять тип полей, которые изменились
|
|
38
|
-
if (Object.keys(nestedDiff).length >=
|
|
39
|
-
Math.max(Object.keys(oldObj[key]).length, Object.keys(newObj[key]).length) /
|
|
40
|
-
2) {
|
|
41
|
-
// Изменилось больше половины свойств объекта (можно менять условия), тогда меняем сущность целиком для экономии трафика
|
|
42
|
-
diff[prefix + key] = newObj[key];
|
|
43
|
-
}
|
|
44
|
-
else {
|
|
45
|
-
diff = { ...diff, ...nestedDiff };
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
else if (oldObj[key] !== newObj[key]) {
|
|
51
|
-
diff[prefix + key] = newObj[key];
|
|
52
|
-
}
|
|
53
|
-
});
|
|
54
|
-
return diff;
|
|
55
|
-
};
|
|
56
|
-
exports.objectsDiff = objectsDiff;
|