@matreshka/bff 0.22.1 → 0.23.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.
@@ -6,7 +6,7 @@ import { PlatformId } from "@matreshka/shared/enums/platform-id";
6
6
  import { AnyBffToClientMessage, BffToClientMessage } from "@matreshka/shared/messages/bff-to-client/bff-to-client-message";
7
7
  import { AnyClientToBffMessage } from "@matreshka/shared/messages/client-to-bff/client-to-bff-message";
8
8
  import { ClientState } from "@matreshka/shared/types/client-state";
9
- import { BehaviorSubject, Subject } from "rxjs";
9
+ import { BehaviorSubject, Observable, Subject } from "rxjs";
10
10
  import { z } from "zod/v4";
11
11
  import { Page } from "../components";
12
12
  import { App } from "../components/app";
@@ -82,6 +82,11 @@ export declare class Client {
82
82
  * Отключает transport-слой без уничтожения клиента (grace period).
83
83
  */
84
84
  detachTransport(): void;
85
+ /**
86
+ * Ждёт transport-level receipt для outgoing reliable-сообщения.
87
+ * Если клиент уничтожается раньше receipt, ожидание завершается как terminal.
88
+ */
89
+ waitForDelivery(message: AnyBffToClientMessage): Observable<void>;
85
90
  /**
86
91
  * Entry instance для сериализации глобальных App-оверлеев (platform.setOverlays).
87
92
  */
@@ -116,6 +116,34 @@ class Client {
116
116
  detachTransport() {
117
117
  delete this.transportSend;
118
118
  }
119
+ /**
120
+ * Ждёт transport-level receipt для outgoing reliable-сообщения.
121
+ * Если клиент уничтожается раньше receipt, ожидание завершается как terminal.
122
+ */
123
+ waitForDelivery(message) {
124
+ return new rxjs_1.Observable((subscriber) => {
125
+ const receiptSubscription = this.reliableDelivery
126
+ .waitForReceipt(message)
127
+ .subscribe({
128
+ next: () => {
129
+ subscriber.next(undefined);
130
+ subscriber.complete();
131
+ },
132
+ error: (error) => subscriber.error(error),
133
+ });
134
+ const destroySubscription = this.destroy$.subscribe(() => {
135
+ if (subscriber.closed) {
136
+ return;
137
+ }
138
+ subscriber.next(undefined);
139
+ subscriber.complete();
140
+ });
141
+ return () => {
142
+ receiptSubscription.unsubscribe();
143
+ destroySubscription.unsubscribe();
144
+ };
145
+ });
146
+ }
119
147
  /**
120
148
  * Entry instance для сериализации глобальных App-оверлеев (platform.setOverlays).
121
149
  */
@@ -1,10 +1,12 @@
1
1
  import { JsonObject } from "@matreshka/shared/types/json";
2
+ import { Observable } from "rxjs";
2
3
  import { Paths, PathValue } from "ts-essentials";
3
4
  import { ActionConfig } from "../actions/action";
4
5
  import { DecContextValue } from "../actions/dec-context-value";
5
6
  import { IncContextValue } from "../actions/inc-context-value";
6
7
  import { SetContext } from "../actions/set-context";
7
8
  import { ToggleContextValue } from "../actions/toggle-context-value";
9
+ import type { ContextUpdateDelivery } from "../types/context-update-delivery";
8
10
  import { ContextValueOrRef } from "../types/context-value-ref";
9
11
  import { Context } from "./context";
10
12
  type ContextRefLocalSet<ContextType extends JsonObject, PathType extends string> = {
@@ -66,9 +68,10 @@ export declare class ContextRef<ContextType extends JsonObject = JsonObject, Pat
66
68
  get(): PathValue<ContextType, PathType>;
67
69
  /**
68
70
  * Запись значения по текущему пути через {@link Context.set}.
69
- * Если контекст уже уничтожен, вызов игнорируется (без исключения).
71
+ * Hot Observable стартует в момент вызова. Уничтоженный контекст —
72
+ * та же ошибка, что у {@link Context.set}.
70
73
  */
71
- set(value: PathValue<ContextType, PathType>): void;
74
+ set(value: PathValue<ContextType, PathType>): Observable<ContextUpdateDelivery>;
72
75
  toString(): string;
73
76
  toJSON(): string;
74
77
  }
@@ -64,13 +64,11 @@ class ContextRef {
64
64
  }
65
65
  /**
66
66
  * Запись значения по текущему пути через {@link Context.set}.
67
- * Если контекст уже уничтожен, вызов игнорируется (без исключения).
67
+ * Hot Observable стартует в момент вызова. Уничтоженный контекст —
68
+ * та же ошибка, что у {@link Context.set}.
68
69
  */
69
70
  set(value) {
70
- if (this.context.isDestroyed()) {
71
- return;
72
- }
73
- this.context.set({
71
+ return this.context.set({
74
72
  [this.path]: value,
75
73
  });
76
74
  }
@@ -5,8 +5,10 @@ import { ZodObject } from "zod/v4";
5
5
  import { ActionConfig } from "../actions/action";
6
6
  import { LocalContextPathPatch } from "../actions/set-context";
7
7
  import type { Client } from "../client";
8
+ import { ContextUpdateDelivery } from "../types/context-update-delivery";
8
9
  import { ContextValueOrRef } from "../types/context-value-ref";
9
10
  import { ContextRef } from "./context-ref";
11
+ export type { ContextUpdateDelivery } from "../types/context-update-delivery";
10
12
  /** Частичное обновление данных контекста по dotted-путям (см. {@link Context.set}). */
11
13
  export type ContextPathPatch<T extends JsonObject> = Partial<{
12
14
  [K in Paths<T>]: PathValue<T, K>;
@@ -55,6 +57,8 @@ export declare class Context<T extends JsonObject> {
55
57
  private subscriptions;
56
58
  private dataSubscription?;
57
59
  private clientSubscriptions;
60
+ /** Серверный set/replace уже сам отправил diff; в subscribeToDataChanges повторять не нужно. */
61
+ private skipNextDataSync;
58
62
  private assertNotDestroyed;
59
63
  private assertInitialized;
60
64
  /** Ошибка загрузки initDataCallback — в error$ всех клиентов, привязанных к контексту. */
@@ -82,6 +86,10 @@ export declare class Context<T extends JsonObject> {
82
86
  private releaseClientBinding;
83
87
  authorizeClient(client: Client): void;
84
88
  protected subscribeToDataChanges(): void;
89
+ private completeImmediately;
90
+ private recipientsForDiff;
91
+ private emitDiffAndWait;
92
+ private updateDataAndWait;
85
93
  /**
86
94
  * Инициализирует контекст: создаёт `data$`, загружает начальные данные через
87
95
  * `initDataCallback` и запускает синхронизацию с клиентами.
@@ -113,14 +121,20 @@ export declare class Context<T extends JsonObject> {
113
121
  * Предпочтительный способ правки нескольких полей на BFF. Ключ с явным
114
122
  * `undefined` применяется (отличие от отсутствующего ключа в patch).
115
123
  * Для целого снимка после load — {@link replace}.
124
+ *
125
+ * Возвращает hot {@link Observable}: на каждый receipt — {@link ContextUpdateDelivery}
126
+ * с накопительным `delivered`; `complete` после всех адресатов. Пустой diff /
127
+ * нет получателей — один `next({ delivered: [] })` и `complete`.
128
+ * См. `docs/architecture/context-update-delivery.md`.
116
129
  */
117
- set(patch: ContextPathPatch<T>): void;
130
+ set(patch: ContextPathPatch<T>): Observable<ContextUpdateDelivery>;
118
131
  /**
119
132
  * Полная замена корня контекста (результат load, `{ ...loaded, field }`).
120
133
  *
121
134
  * Не merge patch: переданный объект становится новым состоянием целиком.
135
+ * Возвращает тот же hot {@link Observable}, что и {@link set}.
122
136
  */
123
- replace(data: T): void;
137
+ replace(data: T): Observable<ContextUpdateDelivery>;
124
138
  /**
125
139
  * Глубокая копия всего `T` (structured clone корня).
126
140
  *
@@ -115,6 +115,8 @@ class Context {
115
115
  this.destroyed = false;
116
116
  this.subscriptions = new rxjs_1.Subscription();
117
117
  this.clientSubscriptions = new Map();
118
+ /** Серверный set/replace уже сам отправил diff; в subscribeToDataChanges повторять не нужно. */
119
+ this.skipNextDataSync = false;
118
120
  this.schema = config.schema;
119
121
  registerContext(this);
120
122
  this.initDataCallback = config.data;
@@ -215,17 +217,16 @@ class Context {
215
217
  if (unsafeMessage instanceof index_2.ContextValuesMessage) {
216
218
  const payloadSchema = v4_1.z.array(v4_1.z.strictObject({ key: v4_1.z.string(), value: v4_1.z.unknown() }));
217
219
  const changes = payloadSchema.parse(unsafeMessage.payload);
218
- const data = this.data$.getValue();
220
+ const patch = {};
219
221
  changes.forEach((change) => {
220
222
  if (this.schema) {
221
223
  const keySchema = (0, deep_pick_1.zodDeepPick)(this.schema, change.key);
222
224
  keySchema.parse(change.value);
223
225
  }
224
- // @ts-expect-error Проверка типа происходит при помощи zod, так что ошибка не актуальна
225
- (0, set_object_property_1.setObjectProperty)(data, change.key, change.value);
226
+ patch[change.key] = change.value;
226
227
  });
227
228
  this.dataChangedByClient = client;
228
- this.replace(data);
229
+ this.set(patch);
229
230
  return;
230
231
  }
231
232
  })));
@@ -237,6 +238,11 @@ class Context {
237
238
  if (this.destroyed) {
238
239
  return;
239
240
  }
241
+ if (this.skipNextDataSync) {
242
+ this.skipNextDataSync = false;
243
+ prevData = structuredClone(data);
244
+ return;
245
+ }
240
246
  // Во время init() не шлём diff (сохраняем текущую семантику: первая "реальная" установка данных не должна рассылаться как изменения).
241
247
  if (!this.initializing && prevData) {
242
248
  let diff;
@@ -261,6 +267,75 @@ class Context {
261
267
  prevData = structuredClone(data);
262
268
  });
263
269
  }
270
+ completeImmediately() {
271
+ const result$ = new rxjs_1.ReplaySubject(1);
272
+ result$.next({ delivered: [] });
273
+ result$.complete();
274
+ return result$.asObservable();
275
+ }
276
+ recipientsForDiff() {
277
+ const recipients = [];
278
+ getRegistryEntry(this.id)?.clients.forEach((_, client) => {
279
+ if (this.dataChangedByClient !== client) {
280
+ recipients.push(client);
281
+ }
282
+ });
283
+ return recipients;
284
+ }
285
+ emitDiffAndWait(diff) {
286
+ const recipients = this.recipientsForDiff();
287
+ this.dataChangedByClient = undefined;
288
+ if (Object.keys(diff).length === 0 || recipients.length === 0) {
289
+ return this.completeImmediately();
290
+ }
291
+ const payload = Object.entries(diff).map(([key, value]) => ({
292
+ key,
293
+ value,
294
+ }));
295
+ const result$ = new rxjs_1.ReplaySubject(recipients.length);
296
+ const delivered = [];
297
+ let finalized = false;
298
+ const subscriptions = new rxjs_1.Subscription();
299
+ const finishError = (error) => {
300
+ if (finalized) {
301
+ return;
302
+ }
303
+ finalized = true;
304
+ subscriptions.unsubscribe();
305
+ result$.error(error);
306
+ };
307
+ const finishSuccess = (client) => {
308
+ if (finalized) {
309
+ return;
310
+ }
311
+ delivered.push(client);
312
+ result$.next({ delivered: [...delivered] });
313
+ if (delivered.length === recipients.length) {
314
+ finalized = true;
315
+ subscriptions.unsubscribe();
316
+ result$.complete();
317
+ }
318
+ };
319
+ for (const client of recipients) {
320
+ const message = new index_1.ContextValuesMessage(this.id, payload);
321
+ subscriptions.add(client.waitForDelivery(message).subscribe({
322
+ next: () => finishSuccess(client),
323
+ error: (error) => finishError(error),
324
+ }));
325
+ client.outcomingMessage$.next(message);
326
+ }
327
+ return result$.asObservable();
328
+ }
329
+ updateDataAndWait(mutator) {
330
+ this.assertNotDestroyed();
331
+ this.assertInitialized();
332
+ const prevData = structuredClone(this.data$.getValue());
333
+ const nextData = mutator(this.data$.getValue());
334
+ const diff = (0, objects_diff_1.objectsDiff)(prevData, nextData);
335
+ this.skipNextDataSync = true;
336
+ this.data$.next(nextData);
337
+ return this.emitDiffAndWait(diff);
338
+ }
264
339
  /**
265
340
  * Инициализирует контекст: создаёт `data$`, загружает начальные данные через
266
341
  * `initDataCallback` и запускает синхронизацию с клиентами.
@@ -337,28 +412,31 @@ class Context {
337
412
  * Предпочтительный способ правки нескольких полей на BFF. Ключ с явным
338
413
  * `undefined` применяется (отличие от отсутствующего ключа в patch).
339
414
  * Для целого снимка после load — {@link replace}.
415
+ *
416
+ * Возвращает hot {@link Observable}: на каждый receipt — {@link ContextUpdateDelivery}
417
+ * с накопительным `delivered`; `complete` после всех адресатов. Пустой diff /
418
+ * нет получателей — один `next({ delivered: [] })` и `complete`.
419
+ * См. `docs/architecture/context-update-delivery.md`.
340
420
  */
341
421
  set(patch) {
342
- this.assertNotDestroyed();
343
- this.assertInitialized();
344
- const data = this.data$.getValue();
345
- for (const path of Object.keys(patch)) {
346
- // hasOwnProperty: «loading: undefined» пишем, пропущенный ключ — не трогаем.
347
- if (Object.prototype.hasOwnProperty.call(patch, path)) {
348
- (0, set_object_property_1.setObjectProperty)(data, path, patch[path]);
422
+ return this.updateDataAndWait((data) => {
423
+ for (const path of Object.keys(patch)) {
424
+ // hasOwnProperty: «loading: undefined» пишем, пропущенный ключ — не трогаем.
425
+ if (Object.prototype.hasOwnProperty.call(patch, path)) {
426
+ (0, set_object_property_1.setObjectProperty)(data, path, patch[path]);
427
+ }
349
428
  }
350
- }
351
- this.data$.next(data);
429
+ return data;
430
+ });
352
431
  }
353
432
  /**
354
433
  * Полная замена корня контекста (результат load, `{ ...loaded, field }`).
355
434
  *
356
435
  * Не merge patch: переданный объект становится новым состоянием целиком.
436
+ * Возвращает тот же hot {@link Observable}, что и {@link set}.
357
437
  */
358
438
  replace(data) {
359
- this.assertNotDestroyed();
360
- this.assertInitialized();
361
- this.data$.next(data);
439
+ return this.updateDataAndWait(() => data);
362
440
  }
363
441
  /**
364
442
  * Глубокая копия всего `T` (structured clone корня).
@@ -21,6 +21,7 @@ export * from "@matreshka/shared/types/json";
21
21
  export * from "./types/component-instance";
22
22
  export * from "./types/component-tree-node";
23
23
  export * from "./types/componentable";
24
+ export * from "./types/context-update-delivery";
24
25
  export * from "./types/context-value-ref";
25
26
  export * from "./types/message";
26
27
  export * from "./types/mixed-with-callbacks-array";
@@ -40,6 +40,7 @@ __exportStar(require("@matreshka/shared/types/json"), exports);
40
40
  __exportStar(require("./types/component-instance"), exports);
41
41
  __exportStar(require("./types/component-tree-node"), exports);
42
42
  __exportStar(require("./types/componentable"), exports);
43
+ __exportStar(require("./types/context-update-delivery"), exports);
43
44
  __exportStar(require("./types/context-value-ref"), exports);
44
45
  __exportStar(require("./types/message"), exports);
45
46
  __exportStar(require("./types/mixed-with-callbacks-array"), exports);
@@ -0,0 +1,5 @@
1
+ import type { Client } from "../client";
2
+ /** Прогресс transport-level доставки diff контекста (накопительный список клиентов с receipt). */
3
+ export type ContextUpdateDelivery = {
4
+ delivered: Client[];
5
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@matreshka/bff",
3
- "version": "0.22.1",
3
+ "version": "0.23.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,7 +62,7 @@
62
62
  "vitest": "^4.1.0"
63
63
  },
64
64
  "dependencies": {
65
- "@matreshka/shared": "^0.21.0",
65
+ "@matreshka/shared": "^0.22.0",
66
66
  "@simplewebauthn/server": "^13.1.1",
67
67
  "@simplewebauthn/types": "^12.0.0",
68
68
  "fast-xml-parser": "^5.3.3",