@matreshka/bff 0.19.0 → 0.21.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.
Files changed (36) hide show
  1. package/dist/components/board.d.ts +4 -4
  2. package/dist/components/board.js +4 -40
  3. package/dist/components/camera.d.ts +1 -1
  4. package/dist/components/camera.js +2 -15
  5. package/dist/components/component.d.ts +9 -4
  6. package/dist/components/component.js +16 -0
  7. package/dist/components/dialog.d.ts +1 -1
  8. package/dist/components/dialog.js +1 -10
  9. package/dist/components/for-each.d.ts +3 -3
  10. package/dist/components/for-each.js +18 -26
  11. package/dist/components/inputs/text-editor.d.ts +14 -14
  12. package/dist/components/inputs/text-editor.js +14 -154
  13. package/dist/components/item-list/item-list.js +11 -11
  14. package/dist/components/item-list/list-from-ref-context.d.ts +4 -1
  15. package/dist/components/item-list/list-from-ref-context.js +6 -4
  16. package/dist/components/item-list/types.d.ts +5 -5
  17. package/dist/components/item-list/types.js +1 -1
  18. package/dist/components/map.d.ts +4 -4
  19. package/dist/components/map.js +4 -40
  20. package/dist/components/popover.d.ts +1 -1
  21. package/dist/components/popover.js +1 -10
  22. package/dist/components/stack.d.ts +1 -1
  23. package/dist/components/stack.js +2 -17
  24. package/dist/components/utils/targeted-client-component-action.d.ts +5 -0
  25. package/dist/components/utils/targeted-client-component-action.js +25 -0
  26. package/dist/core/context/context-ref.d.ts +5 -4
  27. package/dist/core/context/context-ref.js +9 -8
  28. package/dist/core/context/context.d.ts +42 -10
  29. package/dist/core/context/context.js +76 -13
  30. package/dist/core/types/context-value-ref.d.ts +3 -3
  31. package/dist/core/utils/replace-context-keys.js +1 -2
  32. package/dist/core/utils/targeted-client-action.d.ts +19 -0
  33. package/dist/core/utils/targeted-client-action.js +68 -0
  34. package/dist/platforms/utils/targeted-client-platform-action.js +9 -64
  35. package/dist/platforms/utils/targeted-client-platform-stream.js +2 -2
  36. package/package.json +2 -2
@@ -106,10 +106,11 @@ class ItemList {
106
106
  }
107
107
  const contextSubscription = new rxjs_1.Subscription();
108
108
  this.contextSubscription = contextSubscription;
109
- contextSubscription.add(this.config.ref.context.init$.subscribe(() => {
110
- contextSubscription.add(this.config.ref.context.data$.pipe((0, rxjs_1.skip)(1)).subscribe(() => {
111
- this.syncToHost(true);
112
- }));
109
+ contextSubscription.add(this.config.ref.context
110
+ .watch()
111
+ .pipe((0, rxjs_1.skip)(1))
112
+ .subscribe(() => {
113
+ this.syncToHost(true);
113
114
  }));
114
115
  }
115
116
  /**
@@ -179,13 +180,14 @@ class ItemList {
179
180
  generateItems(instance) {
180
181
  const cache = this.getInstanceState(instance).itemsCache;
181
182
  const value = (0, types_1.getItemListValue)(this.config.ref);
182
- const store = this.indexContext.data$.getValue();
183
- for (const key of Object.keys(store)) {
184
- delete store[key];
183
+ const store = {};
184
+ for (let index = 0; index < value.length; index++) {
185
+ const cacheKey = this.itemCacheKey(value[index]);
186
+ store[cacheKey] = { index: `${index}` };
185
187
  }
186
- const items = value.map((data, index) => {
188
+ this.indexContext.replace(store);
189
+ return value.map((data) => {
187
190
  const cacheKey = this.itemCacheKey(data);
188
- store[cacheKey] = { index: `${index}` };
189
191
  let item = cache.get(cacheKey);
190
192
  if (!item) {
191
193
  item = this.config.generator({
@@ -196,8 +198,6 @@ class ItemList {
196
198
  }
197
199
  return { id: this.trackId(data), item };
198
200
  });
199
- this.indexContext.syncIndexStoreFromMutations();
200
- return items;
201
201
  }
202
202
  }
203
203
  exports.ItemList = ItemList;
@@ -4,8 +4,11 @@ type ItemListIndexContext = Record<string, {
4
4
  }>;
5
5
  /** Контекст индексов элементов ItemList; данные не загружаются снаружи. */
6
6
  export declare class ItemListIndexStore<T extends JsonObject = ItemListIndexContext> extends Context<T> {
7
+ /**
8
+ * Синхронно поднимает хранилище до async {@link init}, чтобы `replace` в serialize
9
+ * не перезаписывался пустым `{}` из `initDataCallback`.
10
+ */
7
11
  initSync(): this;
8
- syncIndexStoreFromMutations(): void;
9
12
  constructor(preload: boolean);
10
13
  }
11
14
  export {};
@@ -6,16 +6,18 @@ const v4_1 = require("zod/v4");
6
6
  const core_1 = require("../../core");
7
7
  /** Контекст индексов элементов ItemList; данные не загружаются снаружи. */
8
8
  class ItemListIndexStore extends core_1.Context {
9
+ /**
10
+ * Синхронно поднимает хранилище до async {@link init}, чтобы `replace` в serialize
11
+ * не перезаписывался пустым `{}` из `initDataCallback`.
12
+ */
9
13
  initSync() {
10
- if (this.inited())
14
+ if (this.inited()) {
11
15
  return this;
16
+ }
12
17
  this.data$ = new rxjs_1.BehaviorSubject({});
13
18
  this.subscribeToDataChanges();
14
19
  return this;
15
20
  }
16
- syncIndexStoreFromMutations() {
17
- super.emitAfterInPlaceMutation();
18
- }
19
21
  constructor(preload) {
20
22
  super({
21
23
  data: async () => ({}),
@@ -1,16 +1,16 @@
1
1
  import type { Paths, PathValue } from "ts-essentials";
2
2
  import type { ComponentTreeNode, ContextRef, JsonObject } from "../../core";
3
3
  export type ListArrayValue = readonly unknown[] | unknown[];
4
- type ItemArray<RefType extends ContextRef<any, any>> = Extract<ReturnType<RefType["value"]>, ListArrayValue>;
4
+ type ItemArray<RefType extends ContextRef<any, any>> = Extract<ReturnType<RefType["get"]>, ListArrayValue>;
5
5
  export type CompatibleItemListRef<RefType extends ContextRef<any, any>> = [
6
6
  ItemArray<RefType>
7
7
  ] extends [never] ? never : RefType;
8
8
  export type ItemListItemData<RefType extends ContextRef<any, any>> = ItemArray<RefType>[number];
9
- export type ItemListTypedItemRef<ContextType extends JsonObject, PathType extends string, ValueType> = Omit<ContextRef<any, any>, "path" | "ref" | "value"> & {
9
+ export type ItemListTypedItemRef<ContextType extends JsonObject, PathType extends string, ValueType> = Omit<ContextRef<any, any>, "path" | "ref" | "get"> & {
10
10
  readonly path: PathType;
11
11
  readonly __valueType?: ValueType;
12
- value(): ValueType;
13
- value(): JsonObject;
12
+ get(): ValueType;
13
+ get(): JsonObject;
14
14
  ref<K extends Paths<ValueType>>(path: K): ItemListTypedItemRef<ContextType, `${PathType}.${K & string}`, PathValue<ValueType, K>>;
15
15
  ref<P2 extends string>(path: ContextRef<ContextType, P2>): ContextRef<ContextType, `${PathType}.${P2}`>;
16
16
  };
@@ -35,6 +35,6 @@ type ItemListIndexContextRecord = Record<string, {
35
35
  index: `${number}`;
36
36
  }>;
37
37
  export declare function createItemListItemLink<ContextType extends JsonObject, PathType extends string, RefType extends ContextRef<ContextType, PathType> & {
38
- value(): ListArrayValue | undefined;
38
+ get(): ListArrayValue | undefined;
39
39
  }>(ref: RefType, indexRef: ContextRef<ItemListIndexContextRecord, `${string}.index`>): ItemListItemLink<RefType>;
40
40
  export {};
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getItemListValue = getItemListValue;
4
4
  exports.createItemListItemLink = createItemListItemLink;
5
5
  function getItemListValue(ref) {
6
- const rawValue = ref.value();
6
+ const rawValue = ref.get();
7
7
  return Array.isArray(rawValue)
8
8
  ? rawValue
9
9
  : [];
@@ -61,10 +61,10 @@ export declare class Map<InitConfigType extends MapInitConfig<any> = DefaultInit
61
61
  latitude: number;
62
62
  longitude: number;
63
63
  altitude?: number;
64
- }, instances?: ComponentInstance[]): void;
65
- setZoom(zoom: number, instances?: ComponentInstance[]): void;
66
- zoomIn(instances?: ComponentInstance[]): void;
67
- zoomOut(instances?: ComponentInstance[]): void;
64
+ }, instances?: ComponentInstance[]): import("rxjs").Observable<void>;
65
+ setZoom(zoom: number, instances?: ComponentInstance[]): import("rxjs").Observable<void>;
66
+ zoomIn(instances?: ComponentInstance[]): import("rxjs").Observable<void>;
67
+ zoomOut(instances?: ComponentInstance[]): import("rxjs").Observable<void>;
68
68
  constructor(config: InitConfigType);
69
69
  get hostInstances(): readonly ComponentInstance[];
70
70
  syncNestedItems(slot: string, items: NestedItemBase[]): void;
@@ -14,52 +14,16 @@ const map = (config) => new Map(config);
14
14
  exports.map = map;
15
15
  class Map extends component_1.Component {
16
16
  setCenter(center, instances) {
17
- if (instances) {
18
- instances
19
- .filter((instance) => instance.client)
20
- .forEach((instance) => {
21
- instance.client.outcomingMessage$.next(new map_set_center_message_1.MapSetCenterMessage(instance.id, center));
22
- });
23
- }
24
- else {
25
- this.broadcast(new map_set_center_message_1.MapSetCenterMessage(this.id, center));
26
- }
17
+ return this.dispatchComponentCommand(instances, (target, actionScope) => new map_set_center_message_1.MapSetCenterMessage(target, { ...center, actionScope }));
27
18
  }
28
19
  setZoom(zoom, instances) {
29
- if (instances) {
30
- instances
31
- .filter((instance) => instance.client)
32
- .forEach((instance) => {
33
- instance.client.outcomingMessage$.next(new map_set_zoom_message_1.MapSetZoomMessage(instance.id, zoom));
34
- });
35
- }
36
- else {
37
- this.broadcast(new map_set_zoom_message_1.MapSetZoomMessage(this.id, zoom));
38
- }
20
+ return this.dispatchComponentCommand(instances, (target, actionScope) => new map_set_zoom_message_1.MapSetZoomMessage(target, { zoom, actionScope }));
39
21
  }
40
22
  zoomIn(instances) {
41
- if (instances) {
42
- instances
43
- .filter((instance) => instance.client)
44
- .forEach((instance) => {
45
- instance.client.outcomingMessage$.next(new map_zoom_in_message_1.MapZoomInMessage(instance.id));
46
- });
47
- }
48
- else {
49
- this.broadcast(new map_zoom_in_message_1.MapZoomInMessage(this.id));
50
- }
23
+ return this.dispatchComponentCommand(instances, (target, actionScope) => new map_zoom_in_message_1.MapZoomInMessage(target, actionScope));
51
24
  }
52
25
  zoomOut(instances) {
53
- if (instances) {
54
- instances
55
- .filter((instance) => instance.client)
56
- .forEach((instance) => {
57
- instance.client.outcomingMessage$.next(new map_zoom_out_message_1.MapZoomOutMessage(instance.id));
58
- });
59
- }
60
- else {
61
- this.broadcast(new map_zoom_out_message_1.MapZoomOutMessage(this.id));
62
- }
26
+ return this.dispatchComponentCommand(instances, (target, actionScope) => new map_zoom_out_message_1.MapZoomOutMessage(target, actionScope));
63
27
  }
64
28
  constructor(config) {
65
29
  const markersSlot = (0, item_list_1.createNestedItemsSlotState)(config.markers);
@@ -45,7 +45,7 @@ export declare class Popover<InitConfigType extends PopoverInitConfig<any> = Def
45
45
  /**
46
46
  * Закрывает всплывающее окно, инициируя действие "close".
47
47
  */
48
- close(instances?: ComponentInstance[]): void;
48
+ close(instances?: ComponentInstance[]): import("rxjs").Observable<void>;
49
49
  /**
50
50
  * Инициализирует свойства компонента.
51
51
  *
@@ -40,16 +40,7 @@ class Popover extends entry_component_1.EntryComponent {
40
40
  * Закрывает всплывающее окно, инициируя действие "close".
41
41
  */
42
42
  close(instances) {
43
- if (instances) {
44
- instances
45
- .filter((instance) => instance.client)
46
- .forEach((instance) => {
47
- instance.client.outcomingMessage$.next(new popover_close_message_1.PopoverCloseMessage(instance.id));
48
- });
49
- }
50
- else {
51
- this.broadcast(new popover_close_message_1.PopoverCloseMessage(this.id));
52
- }
43
+ return this.dispatchComponentCommand(instances, (target, actionScope) => new popover_close_message_1.PopoverCloseMessage(target, actionScope));
53
44
  }
54
45
  /**
55
46
  * Инициализирует свойства компонента.
@@ -163,7 +163,7 @@ export declare class Stack<InitConfigType extends StackInitConfig<any> = Default
163
163
  * - {@link ScrollToPosition.End} — в конец;
164
164
  * - иное отрицательное `value` — отступ от конца (например `-16`).
165
165
  */
166
- scrollTo(value: number | ScrollToPosition, smooth?: boolean, instances?: ComponentInstance[]): this;
166
+ scrollTo(value: number | ScrollToPosition, smooth?: boolean, instances?: ComponentInstance[]): import("rxjs").Observable<void>;
167
167
  protected serializeRuleOverrides(overrides: Partial<PropertiesType>): Record<string, unknown>;
168
168
  serialize(instance?: ComponentInstance<this>): StackConfig;
169
169
  }
@@ -104,23 +104,8 @@ class Stack extends component_1.Component {
104
104
  * - иное отрицательное `value` — отступ от конца (например `-16`).
105
105
  */
106
106
  scrollTo(value, smooth = false, instances) {
107
- if (instances) {
108
- instances
109
- .filter((instance) => instance.client)
110
- .forEach((instance) => {
111
- instance.client.outcomingMessage$.next(new component_scroll_to_message_1.ComponentScrollToMessage(instance.id, {
112
- value,
113
- smooth,
114
- }));
115
- });
116
- }
117
- else {
118
- this.broadcast(new component_scroll_to_message_1.ComponentScrollToMessage(this.id, {
119
- value,
120
- smooth,
121
- }));
122
- }
123
- return this;
107
+ const payload = { value, smooth };
108
+ return this.dispatchComponentCommand(instances, (target, actionScope) => new component_scroll_to_message_1.ComponentScrollToMessage(target, { ...payload, actionScope }));
124
109
  }
125
110
  serializeRuleOverrides(overrides) {
126
111
  const out = super.serializeRuleOverrides(overrides);
@@ -0,0 +1,5 @@
1
+ import { ComponentCommandMessage } from "@matreshka/shared/messages/bff-to-client/component-command-message";
2
+ import { Observable } from "rxjs";
3
+ import { Client } from "../../core";
4
+ export declare const COMPONENT_ACTION_SCOPE_PREFIX = "component-action-";
5
+ export declare function targetedClientComponentAction(client: Client, outgoingMessage: (actionScope: string) => ComponentCommandMessage): Observable<void>;
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.COMPONENT_ACTION_SCOPE_PREFIX = void 0;
4
+ exports.targetedClientComponentAction = targetedClientComponentAction;
5
+ const rxjs_1 = require("rxjs");
6
+ const targeted_client_action_1 = require("../../core/utils/targeted-client-action");
7
+ exports.COMPONENT_ACTION_SCOPE_PREFIX = "component-action-";
8
+ function targetedClientComponentAction(client, outgoingMessage) {
9
+ const result$ = new rxjs_1.ReplaySubject(1);
10
+ (0, targeted_client_action_1.startTargetedClientAction)(client, {
11
+ scopePrefix: exports.COMPONENT_ACTION_SCOPE_PREFIX,
12
+ start: (scope) => {
13
+ client.outcomingMessage$.next(outgoingMessage(scope));
14
+ },
15
+ }, {
16
+ next: () => {
17
+ result$.next(undefined);
18
+ result$.complete();
19
+ },
20
+ error: (error) => result$.error(error),
21
+ complete: () => result$.complete(),
22
+ closed: () => result$.closed,
23
+ });
24
+ return result$.asObservable();
25
+ }
@@ -23,7 +23,7 @@ export declare class ContextRef<ContextType extends JsonObject = JsonObject, Pat
23
23
  * `@{<id контекста other>.<путь other>}` (через `other.toString()`), без подстановки
24
24
  * значения на момент вызова.
25
25
  *
26
- * При каждом чтении `Context.value` подставляет в эту строку актуальное значение по
26
+ * При каждом чтении {@link Context.get} подставляет в эту строку актуальное значение по
27
27
  * ссылке `other` (тот же механизм, что и для обычных путей с плейсхолдерами).
28
28
  * Если во втором контексте меняется строка-сегмент пути или индекс, одна и та же
29
29
  * ссылка `ContextRef` продолжает указывать на корректные данные.
@@ -42,12 +42,13 @@ export declare class ContextRef<ContextType extends JsonObject = JsonObject, Pat
42
42
  * @experimental
43
43
  */
44
44
  strictRef<OtherContextType extends JsonObject, OtherPathType extends Paths<OtherContextType>>(other: ContextRef<OtherContextType, OtherPathType>): ContextRef<ContextType, `${PathType}.${PathValue<OtherContextType, OtherPathType> & string}`>;
45
- value(): PathValue<ContextType, PathType>;
45
+ /** Значение по текущему пути (делегирует {@link Context.get}). */
46
+ get(): PathValue<ContextType, PathType>;
46
47
  /**
47
- * Запись значения по текущему пути через {@link Context.setValue}.
48
+ * Запись значения по текущему пути через {@link Context.set}.
48
49
  * Если контекст уже уничтожен, вызов игнорируется (без исключения).
49
50
  */
50
- setValue(value: PathValue<ContextType, PathType>): void;
51
+ set(value: PathValue<ContextType, PathType>): void;
51
52
  toString(): string;
52
53
  toJSON(): string;
53
54
  }
@@ -20,7 +20,7 @@ class ContextRef {
20
20
  * `@{<id контекста other>.<путь other>}` (через `other.toString()`), без подстановки
21
21
  * значения на момент вызова.
22
22
  *
23
- * При каждом чтении `Context.value` подставляет в эту строку актуальное значение по
23
+ * При каждом чтении {@link Context.get} подставляет в эту строку актуальное значение по
24
24
  * ссылке `other` (тот же механизм, что и для обычных путей с плейсхолдерами).
25
25
  * Если во втором контексте меняется строка-сегмент пути или индекс, одна и та же
26
26
  * ссылка `ContextRef` продолжает указывать на корректные данные.
@@ -42,20 +42,21 @@ class ContextRef {
42
42
  const fullPath = `${this.path}.${other.toString()}`;
43
43
  return new ContextRef(this.context, fullPath);
44
44
  }
45
- // Строгое значение по текущему пути
46
- value() {
47
- // Явно выбираем перегрузку Context.value(string): unknown и приводим к ожидаемому типу
48
- return this.context.value(this.path);
45
+ /** Значение по текущему пути (делегирует {@link Context.get}). */
46
+ get() {
47
+ return this.context.get(this.path);
49
48
  }
50
49
  /**
51
- * Запись значения по текущему пути через {@link Context.setValue}.
50
+ * Запись значения по текущему пути через {@link Context.set}.
52
51
  * Если контекст уже уничтожен, вызов игнорируется (без исключения).
53
52
  */
54
- setValue(value) {
53
+ set(value) {
55
54
  if (this.context.isDestroyed()) {
56
55
  return;
57
56
  }
58
- this.context.setValue(this.path, value);
57
+ this.context.set({
58
+ [this.path]: value,
59
+ });
59
60
  }
60
61
  toString() {
61
62
  return `@{${this.context.id}.${this.path}}`;
@@ -1,9 +1,13 @@
1
1
  import { JsonObject } from "@matreshka/shared/types/json";
2
- import { BehaviorSubject } from "rxjs";
2
+ import { BehaviorSubject, Observable } from "rxjs";
3
3
  import { Paths, PathValue } from "ts-essentials";
4
4
  import { ZodObject } from "zod/v4";
5
5
  import type { Client } from "../client";
6
6
  import { ContextRef } from "./context-ref";
7
+ /** Частичное обновление данных контекста по dotted-путям (см. {@link Context.set}). */
8
+ export type ContextPathPatch<T extends JsonObject> = Partial<{
9
+ [K in Paths<T>]: PathValue<T, K>;
10
+ }>;
7
11
  /**
8
12
  * Контекст данных, связанных с клиентом.
9
13
  *
@@ -16,7 +20,7 @@ export declare class Context<T extends JsonObject> {
16
20
  /** Уникальный идентификатор контекста */
17
21
  readonly id: `${string}-${string}-${string}-${string}-${string}`;
18
22
  /** Реактивное хранилище данных контекста. */
19
- data$?: BehaviorSubject<T>;
23
+ protected data$?: BehaviorSubject<T>;
20
24
  /** Схема валидации данных контекста */
21
25
  readonly schema?: ZodObject;
22
26
  /** Флаг, указывающий, что контекст должен быть инициализирован при авторизации клиента */
@@ -28,7 +32,7 @@ export declare class Context<T extends JsonObject> {
28
32
  readonly persistent: boolean;
29
33
  /** Реактивное хранилище инициализации контекста */
30
34
  private _init$;
31
- readonly init$: import("rxjs").Observable<void>;
35
+ readonly init$: Observable<void>;
32
36
  /**
33
37
  * Отслеживает, было ли изменение данных инициировано клиентом.
34
38
  * Если да — синхронизация с клиентом не требуется.
@@ -42,6 +46,7 @@ export declare class Context<T extends JsonObject> {
42
46
  private dataSubscription?;
43
47
  private clientSubscriptions;
44
48
  private assertNotDestroyed;
49
+ private assertInitialized;
45
50
  /** Ошибка загрузки initDataCallback — в error$ всех клиентов, привязанных к контексту. */
46
51
  private reportInitFailureToClients;
47
52
  /**
@@ -85,18 +90,45 @@ export declare class Context<T extends JsonObject> {
85
90
  * Возвращает значение из контекста по указанному пути.
86
91
  *
87
92
  * Путь может содержать плейсхолдеры, которые будут заменены актуальными значениями.
93
+ * Объекты и массивы — **копия** ({@link structuredClone}); in-place мутация результата
94
+ * не меняет контекст. Для снимка всего `T` — {@link snapshot}.
88
95
  *
89
96
  * @param path Строка с путём до значения.
90
97
  * @returns Значение по заданному пути или undefined.
91
98
  */
92
- value<K extends Paths<T>>(path: K): PathValue<T, K>;
93
- setValue<K extends Paths<T>>(path: K, value: PathValue<T, K>): void;
99
+ get<K extends Paths<T>>(path: K): PathValue<T, K>;
94
100
  /**
95
- * После мутаций объекта из `data$!.getValue()` in-place без вызовов `next()`
96
- * подписчики и клиенты не получают обновление. Метод публикует в поток глубокую
97
- * копию текущего состояния и запускает обычную цепочку (diff → сообщения клиенту).
101
+ * Частичное обновление данных по dotted-путям одним вызовом `next`.
102
+ *
103
+ * Предпочтительный способ правки нескольких полей на BFF. Ключ с явным
104
+ * `undefined` применяется (отличие от отсутствующего ключа в patch).
105
+ * Для целого снимка после load — {@link replace}.
106
+ */
107
+ set(patch: ContextPathPatch<T>): void;
108
+ /**
109
+ * Полная замена корня контекста (результат load, `{ ...loaded, field }`).
110
+ *
111
+ * Не merge patch: переданный объект становится новым состоянием целиком.
112
+ */
113
+ replace(data: T): void;
114
+ /**
115
+ * Глубокая копия всего `T` (structured clone корня).
116
+ *
117
+ * Для одного поля — {@link get}. Нужен, когда на время async нужен отсоединённый
118
+ * снимок всего состояния, а не ссылка на живые данные.
119
+ */
120
+ snapshot(): T;
121
+ /**
122
+ * Read-only поток данных контекста для подписок и RxJS-операторов.
123
+ *
124
+ * Если {@link init} ещё не создал хранилище, подписка **ждёт** успешного init
125
+ * ({@link init$}), затем ведёт себя как после init. При {@link destroy} до init
126
+ * поток завершается без эмиссий.
127
+ *
128
+ * После подключения сразу эмитит текущее состояние, затем каждое обновление
129
+ * через {@link set}, {@link replace} и т.п.
98
130
  */
99
- emitAfterInPlaceMutation(): void;
131
+ watch(): Observable<T>;
100
132
  /**
101
133
 
102
134
  * @param path Путь до значения.
@@ -107,7 +139,7 @@ export declare class Context<T extends JsonObject> {
107
139
  * Ссылка на значение в **этом** контексте по пути, который задаётся **во втором**
108
140
  * контексте строкой и меняется во времени.
109
141
  *
110
- * В отличие от прямого чтения `other.value()` при создании ссылки, в путь записывается
142
+ * В отличие от прямого чтения `other.get()` при создании ссылки, в путь записывается
111
143
  * только плейсхолдер `@{<id контекста other>.<путь other>}` (см. `ContextRef.toString`).
112
144
  * При каждом обращении `Context.value` подставляет актуальное значение поля `other`;
113
145
  * это уже строка-путь относительно корня текущего контекста (например `cards.1.balance`).
@@ -14,6 +14,13 @@ const objects_diff_1 = require("../utils/objects-diff");
14
14
  const replace_context_keys_1 = require("../utils/replace-context-keys");
15
15
  const set_object_property_1 = require("../utils/set-object-property");
16
16
  const context_ref_1 = require("./context-ref");
17
+ /** Отделяет чтение через {@link Context.get} от живого дерева в хранилище. */
18
+ function cloneGetResult(value) {
19
+ if (value !== null && typeof value === "object") {
20
+ return structuredClone(value);
21
+ }
22
+ return value;
23
+ }
17
24
  /** Глобальный реестр контекстов: lookup по id, привязки к клиентам, учёт init. */
18
25
  const contextRegistry = new Map();
19
26
  function registerContext(context) {
@@ -70,6 +77,11 @@ class Context {
70
77
  throw new Error(`Context ${this.id} has been destroyed`);
71
78
  }
72
79
  }
80
+ assertInitialized() {
81
+ if (!this.data$) {
82
+ throw new Error(`Context ${this.id} is not initialized`);
83
+ }
84
+ }
73
85
  /** Ошибка загрузки initDataCallback — в error$ всех клиентов, привязанных к контексту. */
74
86
  reportInitFailureToClients(error) {
75
87
  getRegistryEntry(this.id)?.clients.forEach((_, client) => {
@@ -202,7 +214,7 @@ class Context {
202
214
  (0, set_object_property_1.setObjectProperty)(data, change.key, change.value);
203
215
  });
204
216
  this.dataChangedByClient = client;
205
- this.data$.next(data);
217
+ this.replace(data);
206
218
  return;
207
219
  }
208
220
  })));
@@ -302,27 +314,78 @@ class Context {
302
314
  void this.initPromise.catch(() => { });
303
315
  return this.initPromise;
304
316
  }
305
- value(path) {
317
+ get(path) {
306
318
  this.assertNotDestroyed();
307
- return (0, fetch_from_object_1.fetchFromObject)(this.data$.getValue(), (0, replace_context_keys_1.replaceContextKeys)(path, getContextById));
319
+ this.assertInitialized();
320
+ const value = (0, fetch_from_object_1.fetchFromObject)(this.data$.getValue(), (0, replace_context_keys_1.replaceContextKeys)(path, getContextById));
321
+ return cloneGetResult(value);
308
322
  }
309
- setValue(path, value) {
323
+ /**
324
+ * Частичное обновление данных по dotted-путям одним вызовом `next`.
325
+ *
326
+ * Предпочтительный способ правки нескольких полей на BFF. Ключ с явным
327
+ * `undefined` применяется (отличие от отсутствующего ключа в patch).
328
+ * Для целого снимка после load — {@link replace}.
329
+ */
330
+ set(patch) {
310
331
  this.assertNotDestroyed();
332
+ this.assertInitialized();
311
333
  const data = this.data$.getValue();
312
- (0, set_object_property_1.setObjectProperty)(data, path, value);
334
+ for (const path of Object.keys(patch)) {
335
+ // hasOwnProperty: «loading: undefined» пишем, пропущенный ключ — не трогаем.
336
+ if (Object.prototype.hasOwnProperty.call(patch, path)) {
337
+ (0, set_object_property_1.setObjectProperty)(data, path, patch[path]);
338
+ }
339
+ }
313
340
  this.data$.next(data);
314
341
  }
315
342
  /**
316
- * После мутаций объекта из `data$!.getValue()` in-place без вызовов `next()`
317
- * подписчики и клиенты не получают обновление. Метод публикует в поток глубокую
318
- * копию текущего состояния и запускает обычную цепочку (diff → сообщения клиенту).
343
+ * Полная замена корня контекста (результат load, `{ ...loaded, field }`).
344
+ *
345
+ * Не merge patch: переданный объект становится новым состоянием целиком.
319
346
  */
320
- emitAfterInPlaceMutation() {
347
+ replace(data) {
321
348
  this.assertNotDestroyed();
322
- if (!this.data$) {
323
- return;
349
+ this.assertInitialized();
350
+ this.data$.next(data);
351
+ }
352
+ /**
353
+ * Глубокая копия всего `T` (structured clone корня).
354
+ *
355
+ * Для одного поля — {@link get}. Нужен, когда на время async нужен отсоединённый
356
+ * снимок всего состояния, а не ссылка на живые данные.
357
+ */
358
+ snapshot() {
359
+ this.assertNotDestroyed();
360
+ this.assertInitialized();
361
+ return structuredClone(this.data$.getValue());
362
+ }
363
+ /**
364
+ * Read-only поток данных контекста для подписок и RxJS-операторов.
365
+ *
366
+ * Если {@link init} ещё не создал хранилище, подписка **ждёт** успешного init
367
+ * ({@link init$}), затем ведёт себя как после init. При {@link destroy} до init
368
+ * поток завершается без эмиссий.
369
+ *
370
+ * После подключения сразу эмитит текущее состояние, затем каждое обновление
371
+ * через {@link set}, {@link replace} и т.п.
372
+ */
373
+ watch() {
374
+ this.assertNotDestroyed();
375
+ // asObservable() — без .next у подписчиков; тот же поток, что у внутреннего Subject.
376
+ const connect = () => {
377
+ if (this.destroyed || !this.data$) {
378
+ // destroy до init: init$ уже complete, подписчик не должен висеть.
379
+ return rxjs_1.EMPTY;
380
+ }
381
+ return this.data$.asObservable();
382
+ };
383
+ // init уже создал Subject (в т.ч. промежуточный `{}` во время await load).
384
+ if (this.data$) {
385
+ return connect();
324
386
  }
325
- this.data$.next(structuredClone(this.data$.getValue()));
387
+ // boot() до init(): ждём успешный init, затем обычные эмиссии BehaviorSubject.
388
+ return this.init$.pipe((0, rxjs_1.take)(1), (0, rxjs_1.switchMap)(() => connect()));
326
389
  }
327
390
  /**
328
391
 
@@ -337,7 +400,7 @@ class Context {
337
400
  * Ссылка на значение в **этом** контексте по пути, который задаётся **во втором**
338
401
  * контексте строкой и меняется во времени.
339
402
  *
340
- * В отличие от прямого чтения `other.value()` при создании ссылки, в путь записывается
403
+ * В отличие от прямого чтения `other.get()` при создании ссылки, в путь записывается
341
404
  * только плейсхолдер `@{<id контекста other>.<путь other>}` (см. `ContextRef.toString`).
342
405
  * При каждом обращении `Context.value` подставляет актуальное значение поля `other`;
343
406
  * это уже строка-путь относительно корня текущего контекста (например `cards.1.balance`).
@@ -9,7 +9,7 @@ import { ContextRef, ContextRefValue } from "../context/context-ref";
9
9
  * @example
10
10
  * ```ts
11
11
  * function bindAmount(ref: ContextValueRef<number | undefined>) {
12
- * ref.value(); // number | undefined
12
+ * ref.get(); // number | undefined
13
13
  * }
14
14
  *
15
15
  * bindAmount(pageContext.ref("amount"));
@@ -17,8 +17,8 @@ import { ContextRef, ContextRefValue } from "../context/context-ref";
17
17
  */
18
18
  export type ContextValueRef<ValueType> = ContextRef<any, any> & {
19
19
  readonly __valueType?: ValueType;
20
- value(): ValueType;
21
- setValue(value: ValueType): void;
20
+ get(): ValueType;
21
+ set(value: ValueType): void;
22
22
  };
23
23
  /**
24
24
  * Ref `R` совместим с ожидаемым типом значения `ValueType` (проверка на call site).
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.replaceContextKeys = replaceContextKeys;
4
- const fetch_from_object_1 = require("@matreshka/shared/utils/fetch-from-object");
5
4
  const parse_context_path_1 = require("./parse-context-path");
6
5
  /**
7
6
  * Заменяет плейсхолдеры вида `{ключ}` в строке значениями из объекта контекста.
@@ -27,7 +26,7 @@ function replaceContextKeys(str, resolveContext) {
27
26
  if (!context.inited()) {
28
27
  throw new Error(`Context ${pathInfo.contextId} not initialized`);
29
28
  }
30
- const value = (0, fetch_from_object_1.fetchFromObject)(context.data$.getValue(), pathInfo.key);
29
+ const value = context.get(pathInfo.key);
31
30
  str = replaceAll(str, `@{${path}}`, value ?? defaultValue);
32
31
  });
33
32
  const restContextKeys = findContextKeys(str);