@matreshka/bff 0.28.1 → 0.29.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.
- package/dist/components/for-each.d.ts +2 -2
- package/dist/components/for-each.js +1 -1
- package/dist/components/item-list/list-from-ref-context.d.ts +2 -2
- package/dist/components/item-list/list-from-ref-context.js +1 -1
- package/dist/core/context/assert-client-update-schema.d.ts +6 -0
- package/dist/core/context/assert-client-update-schema.js +45 -0
- package/dist/core/context/context-ref.d.ts +4 -3
- package/dist/core/context/context.d.ts +83 -16
- package/dist/core/context/context.js +95 -51
- package/dist/core/utils/assert-non-overlapping-context-paths.d.ts +5 -0
- package/dist/core/utils/assert-non-overlapping-context-paths.js +17 -0
- package/dist/core/utils/assert-safe-dotted-path.d.ts +5 -0
- package/dist/core/utils/assert-safe-dotted-path.js +21 -0
- package/dist/core/utils/deep-pick.js +25 -4
- package/dist/core/utils/incoming-message-observer.d.ts +1 -1
- package/dist/core/utils/incoming-message-observer.js +6 -1
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { ServerComponentClass } from "@matreshka/client-bff-protocol/enums/server-component-class";
|
|
2
2
|
import type { ForEachConfig } from "@matreshka/client-bff-protocol/types/for-each-config";
|
|
3
3
|
import { Paths, PathValue } from "ts-essentials";
|
|
4
|
-
import {
|
|
4
|
+
import { ComponentInstance, ComponentTreeNode, Context, ContextRef, ContextRefValue, JsonObject, StandaloneComponent } from "../core";
|
|
5
5
|
import { Component, ComponentInitConfig, ComponentProperties } from "./component";
|
|
6
6
|
type ForEachArrayValue = readonly unknown[] | unknown[];
|
|
7
7
|
type ForEachItemArray<RefType extends ContextRef<any, any>> = Extract<ContextRefValue<RefType>, ForEachArrayValue>;
|
|
@@ -36,7 +36,7 @@ export type ForEachGeneratorProperties<RefType extends ContextRef<any, any>, Com
|
|
|
36
36
|
*/
|
|
37
37
|
export type ForEachProperties = {
|
|
38
38
|
ref: ContextRef;
|
|
39
|
-
componentContext:
|
|
39
|
+
componentContext: Context<any>;
|
|
40
40
|
components?: (ComponentTreeNode | ComponentTreeNode[])[];
|
|
41
41
|
divider?: ComponentTreeNode[];
|
|
42
42
|
} & ComponentProperties;
|
|
@@ -46,7 +46,7 @@ class ForEachContext extends core_1.Context {
|
|
|
46
46
|
super({
|
|
47
47
|
data: async () => ({}),
|
|
48
48
|
preload: preload,
|
|
49
|
-
schema: core_1.
|
|
49
|
+
schema: core_1.contextClientUpdatesForbiddenSchema, // Запрет изменения из внешних источников
|
|
50
50
|
});
|
|
51
51
|
}
|
|
52
52
|
}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { Context, type
|
|
1
|
+
import { Context, type ContextClientUpdatesForbiddenSchema, type JsonObject } from "../../core";
|
|
2
2
|
type ItemListIndexContext = Record<string, {
|
|
3
3
|
index: `${number}`;
|
|
4
4
|
}>;
|
|
5
5
|
/** Контекст индексов элементов ItemList; данные не загружаются снаружи. */
|
|
6
|
-
export declare class ItemListIndexStore<T extends JsonObject = ItemListIndexContext> extends Context<T,
|
|
6
|
+
export declare class ItemListIndexStore<T extends JsonObject = ItemListIndexContext> extends Context<T, ContextClientUpdatesForbiddenSchema> {
|
|
7
7
|
/**
|
|
8
8
|
* Синхронно поднимает хранилище до async {@link init}, чтобы `replace` в serialize
|
|
9
9
|
* не перезаписывался пустым `{}` из `initDataCallback`.
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/**
|
|
3
|
+
* Клиентские dotted-patch проходят {@link zodDeepPick} только до leaf-поля.
|
|
4
|
+
* Object-level pipe (transform) и checks (refine) на вложенных объектах не поддерживаются.
|
|
5
|
+
*/
|
|
6
|
+
export declare function assertClientUpdateSchemaSupported(schema: z.ZodObject, path?: string): void;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.assertClientUpdateSchemaSupported = assertClientUpdateSchemaSupported;
|
|
4
|
+
const zod_1 = require("zod");
|
|
5
|
+
function unwrapOptionalNullable(schema) {
|
|
6
|
+
let current = schema;
|
|
7
|
+
while (current instanceof zod_1.z.ZodOptional || current instanceof zod_1.z.ZodNullable) {
|
|
8
|
+
current = current.unwrap();
|
|
9
|
+
}
|
|
10
|
+
return current;
|
|
11
|
+
}
|
|
12
|
+
function formatPath(path) {
|
|
13
|
+
return path || "(root)";
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Клиентские dotted-patch проходят {@link zodDeepPick} только до leaf-поля.
|
|
17
|
+
* Object-level pipe (transform) и checks (refine) на вложенных объектах не поддерживаются.
|
|
18
|
+
*/
|
|
19
|
+
function assertClientUpdateSchemaSupported(schema, path = "") {
|
|
20
|
+
for (const [key, fieldSchema] of Object.entries(schema.shape)) {
|
|
21
|
+
const fieldPath = path ? `${path}.${key}` : key;
|
|
22
|
+
assertClientUpdateFieldSupported(fieldSchema, fieldPath);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function assertClientUpdateFieldSupported(schema, path) {
|
|
26
|
+
const unwrapped = unwrapOptionalNullable(schema);
|
|
27
|
+
if (unwrapped instanceof zod_1.z.ZodPipe) {
|
|
28
|
+
const inner = unwrapped._def.in;
|
|
29
|
+
if (inner instanceof zod_1.z.ZodObject) {
|
|
30
|
+
throw new Error(`Context validation schema: object-level transform at "${formatPath(path)}" is not supported for dotted-path client updates. Use leaf-level transforms only.`);
|
|
31
|
+
}
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
if (unwrapped instanceof zod_1.z.ZodObject) {
|
|
35
|
+
const checks = unwrapped._def.checks;
|
|
36
|
+
if (checks && checks.length > 0) {
|
|
37
|
+
throw new Error(`Context validation schema: object-level refine at "${formatPath(path)}" is not supported for dotted-path client updates. Use leaf-level refinements only.`);
|
|
38
|
+
}
|
|
39
|
+
assertClientUpdateSchemaSupported(unwrapped, path);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (unwrapped instanceof zod_1.z.ZodArray) {
|
|
43
|
+
assertClientUpdateFieldSupported(unwrapped.element, `${path}[]`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { JsonObject } from "@matreshka/client-bff-protocol/types/json";
|
|
2
2
|
import { Observable } from "rxjs";
|
|
3
3
|
import { Paths, PathValue } from "ts-essentials";
|
|
4
|
+
import { z } from "zod";
|
|
4
5
|
import { ActionConfig } from "../actions/action";
|
|
5
6
|
import { DecContextValue } from "../actions/dec-context-value";
|
|
6
7
|
import { IncContextValue } from "../actions/inc-context-value";
|
|
@@ -8,7 +9,7 @@ import { SetContext } from "../actions/set-context";
|
|
|
8
9
|
import { ToggleContextValue } from "../actions/toggle-context-value";
|
|
9
10
|
import type { ContextUpdateDelivery } from "../types/context-update-delivery";
|
|
10
11
|
import { ContextValueOrRef } from "../types/context-value-ref";
|
|
11
|
-
import {
|
|
12
|
+
import { Context } from "./context";
|
|
12
13
|
type ContextRefLocalSet<ContextType extends JsonObject, PathType extends string> = {
|
|
13
14
|
set: (value: ContextValueOrRef<PathValue<ContextType, PathType>>, config?: ActionConfig) => SetContext<ContextType>;
|
|
14
15
|
};
|
|
@@ -25,11 +26,11 @@ export type ContextRefValue<R extends ContextRef> = R extends {
|
|
|
25
26
|
readonly __valueType?: infer ValueType;
|
|
26
27
|
} ? Exclude<ValueType, undefined> : R extends ContextRef<infer ContextType, infer PathType> ? PathValue<ContextType, PathType> : never;
|
|
27
28
|
export declare class ContextRef<ContextType extends JsonObject = JsonObject, PathType extends string = string> {
|
|
28
|
-
readonly context:
|
|
29
|
+
readonly context: Context<ContextType, z.ZodObject | undefined>;
|
|
29
30
|
readonly path: PathType;
|
|
30
31
|
/** Локальные (client-only) действия по этому ref. */
|
|
31
32
|
readonly local: ContextRefLocalActions<ContextType, PathType>;
|
|
32
|
-
constructor(context:
|
|
33
|
+
constructor(context: Context<ContextType, z.ZodObject | undefined>, path: PathType);
|
|
33
34
|
/**
|
|
34
35
|
* Продолжение пути в рамках того же контекста.
|
|
35
36
|
* Строго типизировано: K должен быть путём внутри значения по текущему PathType.
|
|
@@ -17,41 +17,92 @@ export type ContextPathPatch<T extends JsonObject> = Partial<{
|
|
|
17
17
|
* Пустая strict-схема: клиент не может менять данные контекста через `context-values`.
|
|
18
18
|
* Используется во внутренних контекстах (ForEach, ItemList).
|
|
19
19
|
*/
|
|
20
|
-
export type
|
|
21
|
-
readonly
|
|
20
|
+
export type ContextClientUpdatesForbiddenSchema = z.ZodObject<Record<string, never>, z.core.$strict> & {
|
|
21
|
+
readonly __contextClientUpdatesForbidden?: unique symbol;
|
|
22
22
|
};
|
|
23
|
-
/** @see
|
|
24
|
-
export declare const
|
|
23
|
+
/** @see ContextClientUpdatesForbiddenSchema */
|
|
24
|
+
export declare const contextClientUpdatesForbiddenSchema: ContextClientUpdatesForbiddenSchema;
|
|
25
|
+
type StripNullish<T> = Exclude<T, null | undefined>;
|
|
26
|
+
type ArrayElement<T> = T extends readonly (infer E)[] ? E : never;
|
|
27
|
+
/** `true`, если output допускает null/undefined как значение, а поле `T` — нет. */
|
|
28
|
+
type NullishValueMismatch<TField, IField> = (null extends IField ? (null extends TField ? never : true) : never) | (undefined extends IField ? undefined extends TField ? never : true : never);
|
|
29
|
+
type FieldExtraSchemaKeysOne<TField, IField> = [StripNullish<IField>] extends [
|
|
30
|
+
JsonObject
|
|
31
|
+
] ? [StripNullish<TField>] extends [JsonObject] ? ExtraSchemaKeys<StripNullish<TField>, StripNullish<IField>> : never : [StripNullish<IField>] extends [readonly unknown[]] ? [StripNullish<TField>] extends [readonly unknown[]] ? ExtraSchemaKeys<ArrayElement<StripNullish<TField>>, ArrayElement<StripNullish<IField>>> : never : never;
|
|
32
|
+
/** Лишние ключи внутри поля (union, optional/nullable, массивы объектов). */
|
|
33
|
+
type FieldExtraSchemaKeys<TField, IField> = IField extends any ? FieldExtraSchemaKeysOne<TField, IField> : never;
|
|
34
|
+
/** Лишние ключи для одной пары object-веток (коррелированные поля). `true` — есть лишние ключи. */
|
|
35
|
+
type ExtraSchemaKeysObjectExact<T extends JsonObject, Input extends JsonObject> = Exclude<keyof Input, keyof T> extends never ? {
|
|
36
|
+
[K in keyof Input & keyof T]: FieldExtraSchemaKeys<T[K], Input[K]>;
|
|
37
|
+
}[keyof Input & keyof T] extends never ? never : true : true;
|
|
38
|
+
/** Есть ветка `T`, для которой `Input` не содержит лишних ключей. */
|
|
39
|
+
type SomeExtraSchemaKeysBranchOk<T, Input extends JsonObject> = T extends JsonObject ? ExtraSchemaKeysObjectExact<T, Input> extends never ? true : never : never;
|
|
25
40
|
/**
|
|
26
|
-
*
|
|
27
|
-
*
|
|
41
|
+
* Лишние ключи в shape схемы относительно `T` (рекурсивно).
|
|
42
|
+
* Union в `Input` и `T` проверяется по отдельным веткам. `true` — есть лишние ключи.
|
|
43
|
+
*/
|
|
44
|
+
type ExtraSchemaKeys<T, Input> = Input extends JsonObject ? SomeExtraSchemaKeysBranchOk<T, Input> extends true ? never : true : never;
|
|
45
|
+
type FieldSchemaCompatibleOne<TField, IField> = NullishValueMismatch<TField, IField> extends never ? FieldSchemaCompatibleShape<TField, IField> : true;
|
|
46
|
+
type FieldSchemaCompatibleShape<TField, IField> = [
|
|
47
|
+
StripNullish<IField>
|
|
48
|
+
] extends [JsonObject] ? [StripNullish<TField>] extends [JsonObject] ? SchemaCompatible<StripNullish<TField>, StripNullish<IField>> : true : [StripNullish<IField>] extends [readonly unknown[]] ? [StripNullish<TField>] extends [readonly unknown[]] ? FieldSchemaCompatible<ArrayElement<StripNullish<TField>>, ArrayElement<StripNullish<IField>>> : true : [StripNullish<IField>] extends [StripNullish<TField>] ? never : true;
|
|
49
|
+
/** Совместимость типа поля с полем контекста (union на входе — по веткам). */
|
|
50
|
+
type FieldSchemaCompatible<TField, IField> = IField extends any ? FieldSchemaCompatibleOne<TField, IField> : never;
|
|
51
|
+
/** Совместимость для одной пары object-веток. `true` — несовместимость. */
|
|
52
|
+
type SchemaCompatibleObjectExact<T extends JsonObject, Input extends JsonObject> = Exclude<keyof Input, keyof T> extends never ? {
|
|
53
|
+
[K in keyof Input & keyof T]: FieldSchemaCompatible<T[K], Input[K]>;
|
|
54
|
+
}[keyof Input & keyof T] extends never ? never : true : true;
|
|
55
|
+
type SomeSchemaCompatibleBranchOk<T, Input extends JsonObject> = T extends JsonObject ? SchemaCompatibleObjectExact<T, Input> extends never ? true : never : never;
|
|
56
|
+
/**
|
|
57
|
+
* Типы полей shape схемы совместимы с `T` (рекурсивно; для клиентской схемы — {@link z.output}).
|
|
58
|
+
* Подмножество ключей на любой глубине; union — по веткам. `true` — несовместимость.
|
|
59
|
+
*/
|
|
60
|
+
type SchemaCompatible<T, Input> = Input extends JsonObject ? SomeSchemaCompatibleBranchOk<T, Input> extends true ? never : true : never;
|
|
61
|
+
/**
|
|
62
|
+
* Zod-схема для {@link context}: без лишних ключей во {@link z.input} и {@link z.output}
|
|
63
|
+
* ({@link ExtraSchemaKeys}, union по веткам); {@link z.output} совместим с `T`
|
|
64
|
+
* ({@link SchemaCompatible}, вложенные подмножества). В контекст попадает output после `parse()`.
|
|
28
65
|
*/
|
|
29
66
|
export type ContextSchema<T extends JsonObject, S extends z.ZodObject> = [
|
|
30
67
|
S
|
|
31
|
-
] extends [
|
|
32
|
-
/** Конфиг {@link
|
|
68
|
+
] extends [ContextClientUpdatesForbiddenSchema] ? S : ExtraSchemaKeys<T, z.input<S>> extends never ? ExtraSchemaKeys<T, z.output<S>> extends never ? SchemaCompatible<T, z.output<S>> extends never ? S : never : never : never;
|
|
69
|
+
/** Конфиг {@link context} без клиентской Zod-схемы. */
|
|
33
70
|
export type ContextInitWithoutSchema<T extends JsonObject> = {
|
|
34
71
|
data: () => Promise<T>;
|
|
35
72
|
schema?: undefined;
|
|
36
73
|
preload?: boolean;
|
|
37
74
|
persistent?: boolean;
|
|
38
75
|
};
|
|
39
|
-
/** Конфиг {@link
|
|
76
|
+
/** Конфиг {@link context} с Zod-схемой клиентских изменений. */
|
|
40
77
|
export type ContextInitWithSchema<T extends JsonObject, S extends z.ZodObject> = {
|
|
41
78
|
data: () => Promise<T>;
|
|
42
79
|
schema: ContextSchema<T, S>;
|
|
43
80
|
preload?: boolean;
|
|
44
81
|
persistent?: boolean;
|
|
45
82
|
};
|
|
46
|
-
/** Конфигурация {@link
|
|
83
|
+
/** Конфигурация {@link context} (единственный аргумент). */
|
|
47
84
|
export type ContextInitConfig<T extends JsonObject, S extends z.ZodObject | undefined = undefined> = S extends z.ZodObject ? ContextInitWithSchema<T, S> : ContextInitWithoutSchema<T>;
|
|
48
|
-
/**
|
|
49
|
-
|
|
85
|
+
/** Минимальная форма аргумента {@link context}. */
|
|
86
|
+
type ContextInitShape = {
|
|
87
|
+
data: () => Promise<JsonObject>;
|
|
88
|
+
schema?: z.ZodObject;
|
|
89
|
+
preload?: boolean;
|
|
90
|
+
persistent?: boolean;
|
|
91
|
+
};
|
|
92
|
+
/** Тип данных `T` из поля `data` конфига. */
|
|
93
|
+
export type ContextDataFromInit<C extends ContextInitShape> = Awaited<ReturnType<C["data"]>>;
|
|
94
|
+
/** Zod-схема из поля `schema` конфига (или `undefined`). */
|
|
95
|
+
export type ContextSchemaFromInit<C extends ContextInitShape> = C extends {
|
|
96
|
+
schema: z.ZodObject;
|
|
97
|
+
} ? C["schema"] : undefined;
|
|
98
|
+
/** Экземпляр {@link Context} по форме конфига {@link context}. */
|
|
99
|
+
export type ContextFromInit<C extends ContextInitShape> = ContextSchemaFromInit<C> extends z.ZodObject ? Context<ContextDataFromInit<C>, ContextSchemaFromInit<C>> : Context<ContextDataFromInit<C>, undefined>;
|
|
100
|
+
type ValidatedContextInit<C extends ContextInitShape> = ContextInitConfig<ContextDataFromInit<C>, ContextSchemaFromInit<C> extends z.ZodObject ? ContextSchemaFromInit<C> : undefined>;
|
|
101
|
+
type StoredContext = Context<JsonObject, z.ZodObject | undefined>;
|
|
50
102
|
/**
|
|
51
103
|
* Контекст данных, связанных с клиентом.
|
|
52
104
|
*
|
|
53
|
-
*
|
|
54
|
-
* а также для отслеживания ошибок валидации и управления реактивными изменениями.
|
|
105
|
+
* @internal Создавайте экземпляры через {@link context}.
|
|
55
106
|
*
|
|
56
107
|
* @template T Тип структуры данных контекста.
|
|
57
108
|
* @template S Zod-схема валидации клиентских изменений (см. {@link ContextSchema}).
|
|
@@ -94,14 +145,18 @@ export declare class Context<T extends JsonObject, S extends z.ZodObject | undef
|
|
|
94
145
|
private clientSubscriptions;
|
|
95
146
|
/** Серверный set/replace уже сам отправил diff; в subscribeToDataChanges повторять не нужно. */
|
|
96
147
|
private skipNextDataSync;
|
|
148
|
+
/** Очередь входящих targeted-сообщений всех клиентов (последовательная обработка). */
|
|
149
|
+
private incomingClientMessages$;
|
|
97
150
|
private assertNotDestroyed;
|
|
98
151
|
private assertInitialized;
|
|
99
152
|
/**
|
|
100
153
|
* Клиентское `context-values` разрешено только по ключам {@link schema}.
|
|
101
154
|
* Нет схемы или ключ вне неё — `Error`, patch не применяется.
|
|
102
|
-
*
|
|
155
|
+
* Валидация через {@link zodDeepPick}: output **конечного** поля (leaf transform/refine).
|
|
156
|
+
* Transform/refine родительского object при dotted-patch не поддерживаются.
|
|
103
157
|
*/
|
|
104
|
-
private
|
|
158
|
+
private parseClientChange;
|
|
159
|
+
private handleTargetedClientMessage;
|
|
105
160
|
/** Ошибка загрузки initDataCallback — в error$ всех клиентов, привязанных к контексту. */
|
|
106
161
|
private reportInitFailureToClients;
|
|
107
162
|
/**
|
|
@@ -219,3 +274,15 @@ export declare class Context<T extends JsonObject, S extends z.ZodObject | undef
|
|
|
219
274
|
strictRef<OtherContextType extends JsonObject, OtherPathType extends Paths<OtherContextType>>(other: ContextRef<OtherContextType, OtherPathType>): ContextRef<T, PathValue<OtherContextType, OtherPathType> & Paths<T>>;
|
|
220
275
|
toJSON(): `${string}-${string}-${string}-${string}-${string}`;
|
|
221
276
|
}
|
|
277
|
+
/** Любой зарегистрированный контекст (с Zod-схемой или без). */
|
|
278
|
+
export type AnyContext = StoredContext;
|
|
279
|
+
/**
|
|
280
|
+
* Создаёт контекст данных BFF: хранилище состояния с синхронизацией клиент ↔ сервер.
|
|
281
|
+
*
|
|
282
|
+
* Тип данных выводится из `data`, тип Zod-схемы — из `schema`. Связь проверяется через
|
|
283
|
+
* {@link ContextSchema}. Generic-параметры у вызова не задаются.
|
|
284
|
+
*
|
|
285
|
+
* Если в начальном `data` нет части полей (например опциональных), укажите тип на колбэке:
|
|
286
|
+
* `data: async (): Promise<MyT> => ({ … })`.
|
|
287
|
+
*/
|
|
288
|
+
export declare function context<C extends ContextInitShape>(config: C & ValidatedContextInit<C>): ContextFromInit<C>;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.Context = exports.
|
|
3
|
+
exports.Context = exports.contextClientUpdatesForbiddenSchema = void 0;
|
|
4
|
+
exports.context = context;
|
|
4
5
|
const index_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/context/index");
|
|
5
6
|
const index_2 = require("@matreshka/client-bff-protocol/messages/client-to-bff/context/index");
|
|
6
7
|
const targeted_message_1 = require("@matreshka/client-bff-protocol/messages/targeted-message");
|
|
@@ -13,13 +14,15 @@ const inc_context_value_1 = require("../actions/inc-context-value");
|
|
|
13
14
|
const set_context_1 = require("../actions/set-context");
|
|
14
15
|
const toggle_context_value_1 = require("../actions/toggle-context-value");
|
|
15
16
|
const client_context_1 = require("../client-context");
|
|
17
|
+
const assert_non_overlapping_context_paths_1 = require("../utils/assert-non-overlapping-context-paths");
|
|
18
|
+
const assert_safe_dotted_path_1 = require("../utils/assert-safe-dotted-path");
|
|
16
19
|
const deep_pick_1 = require("../utils/deep-pick");
|
|
17
|
-
const incoming_message_observer_1 = require("../utils/incoming-message-observer");
|
|
18
20
|
const objects_diff_1 = require("../utils/objects-diff");
|
|
19
21
|
const replace_context_keys_1 = require("../utils/replace-context-keys");
|
|
22
|
+
const assert_client_update_schema_1 = require("./assert-client-update-schema");
|
|
20
23
|
const context_ref_1 = require("./context-ref");
|
|
21
|
-
/** @see
|
|
22
|
-
exports.
|
|
24
|
+
/** @see ContextClientUpdatesForbiddenSchema */
|
|
25
|
+
exports.contextClientUpdatesForbiddenSchema = zod_1.z.strictObject({});
|
|
23
26
|
/** Отделяет чтение через {@link Context.get} от живого дерева в хранилище. */
|
|
24
27
|
function cloneGetResult(value) {
|
|
25
28
|
if (value !== null && typeof value === "object") {
|
|
@@ -69,11 +72,13 @@ function unbindClient(contextId, client) {
|
|
|
69
72
|
entry.clients.delete(client);
|
|
70
73
|
return entry.clients.size === 0;
|
|
71
74
|
}
|
|
75
|
+
function isClientBound(contextId, client) {
|
|
76
|
+
return getRegistryEntry(contextId)?.clients.has(client) ?? false;
|
|
77
|
+
}
|
|
72
78
|
/**
|
|
73
79
|
* Контекст данных, связанных с клиентом.
|
|
74
80
|
*
|
|
75
|
-
*
|
|
76
|
-
* а также для отслеживания ошибок валидации и управления реактивными изменениями.
|
|
81
|
+
* @internal Создавайте экземпляры через {@link context}.
|
|
77
82
|
*
|
|
78
83
|
* @template T Тип структуры данных контекста.
|
|
79
84
|
* @template S Zod-схема валидации клиентских изменений (см. {@link ContextSchema}).
|
|
@@ -92,9 +97,11 @@ class Context {
|
|
|
92
97
|
/**
|
|
93
98
|
* Клиентское `context-values` разрешено только по ключам {@link schema}.
|
|
94
99
|
* Нет схемы или ключ вне неё — `Error`, patch не применяется.
|
|
95
|
-
*
|
|
100
|
+
* Валидация через {@link zodDeepPick}: output **конечного** поля (leaf transform/refine).
|
|
101
|
+
* Transform/refine родительского object при dotted-patch не поддерживаются.
|
|
96
102
|
*/
|
|
97
|
-
|
|
103
|
+
async parseClientChange(key, value) {
|
|
104
|
+
(0, assert_safe_dotted_path_1.assertSafeDottedPath)(key);
|
|
98
105
|
if (!this.schema) {
|
|
99
106
|
throw new Error(`Context ${this.id} rejected client update for "${key}": validation schema is not set`);
|
|
100
107
|
}
|
|
@@ -106,7 +113,40 @@ class Context {
|
|
|
106
113
|
const reason = cause instanceof Error ? cause.message : String(cause);
|
|
107
114
|
throw new Error(`Context ${this.id} rejected client update for "${key}": key is not described in the validation schema (${reason})`);
|
|
108
115
|
}
|
|
109
|
-
keySchema.
|
|
116
|
+
return keySchema.parseAsync(value);
|
|
117
|
+
}
|
|
118
|
+
async handleTargetedClientMessage(client, unsafeMessage) {
|
|
119
|
+
if (this.destroyed) {
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if (unsafeMessage instanceof index_2.ContextInitMessage) {
|
|
123
|
+
await this.init();
|
|
124
|
+
if (this.destroyed || !isClientBound(this.id, client)) {
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
this.sendContextInit(client);
|
|
128
|
+
if (!isInitSent(this.id, client)) {
|
|
129
|
+
markInitSent(this.id, client);
|
|
130
|
+
}
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
if (unsafeMessage instanceof index_2.ContextValuesMessage) {
|
|
134
|
+
const payloadSchema = zod_1.z.array(zod_1.z.strictObject({ key: zod_1.z.string(), value: zod_1.z.unknown() }));
|
|
135
|
+
const changes = payloadSchema.parse(unsafeMessage.payload);
|
|
136
|
+
(0, assert_non_overlapping_context_paths_1.assertNonOverlappingContextPaths)(changes.map((change) => change.key));
|
|
137
|
+
const patch = {};
|
|
138
|
+
for (const change of changes) {
|
|
139
|
+
patch[change.key] = await this.parseClientChange(change.key, change.value);
|
|
140
|
+
if (this.destroyed || !isClientBound(this.id, client)) {
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (this.destroyed || !isClientBound(this.id, client)) {
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
this.dataChangedByClient = client;
|
|
148
|
+
this.set(patch);
|
|
149
|
+
}
|
|
110
150
|
}
|
|
111
151
|
/** Ошибка загрузки initDataCallback — в error$ всех клиентов, привязанных к контексту. */
|
|
112
152
|
reportInitFailureToClients(error) {
|
|
@@ -139,11 +179,22 @@ class Context {
|
|
|
139
179
|
this.clientSubscriptions = new Map();
|
|
140
180
|
/** Серверный set/replace уже сам отправил diff; в subscribeToDataChanges повторять не нужно. */
|
|
141
181
|
this.skipNextDataSync = false;
|
|
182
|
+
/** Очередь входящих targeted-сообщений всех клиентов (последовательная обработка). */
|
|
183
|
+
this.incomingClientMessages$ = new rxjs_1.Subject();
|
|
142
184
|
this.schema = ("schema" in config ? config.schema : undefined);
|
|
185
|
+
if (this.schema) {
|
|
186
|
+
(0, assert_client_update_schema_1.assertClientUpdateSchemaSupported)(this.schema);
|
|
187
|
+
}
|
|
143
188
|
registerContext(this);
|
|
144
189
|
this.initDataCallback = config.data;
|
|
145
190
|
this.preload = config.preload ?? false;
|
|
146
191
|
this.persistent = config.persistent ?? false;
|
|
192
|
+
this.subscriptions.add(this.incomingClientMessages$
|
|
193
|
+
.pipe((0, rxjs_1.concatMap)(({ client, message }) => (0, rxjs_1.from)(this.handleTargetedClientMessage(client, message)).pipe((0, rxjs_1.catchError)((error) => {
|
|
194
|
+
client.error$.next(error);
|
|
195
|
+
return rxjs_1.EMPTY;
|
|
196
|
+
}))))
|
|
197
|
+
.subscribe());
|
|
147
198
|
}
|
|
148
199
|
/** `data$` создан (init мог ещё выполняться — см. {@link init}). */
|
|
149
200
|
inited() {
|
|
@@ -162,6 +213,7 @@ class Context {
|
|
|
162
213
|
return;
|
|
163
214
|
}
|
|
164
215
|
this.destroyed = true;
|
|
216
|
+
this.incomingClientMessages$.complete();
|
|
165
217
|
getRegistryEntry(this.id)?.clients.forEach((_, client) => {
|
|
166
218
|
client.outcomingMessage$.next(new index_1.ContextDestroyMessage(this.id));
|
|
167
219
|
});
|
|
@@ -197,13 +249,15 @@ class Context {
|
|
|
197
249
|
return;
|
|
198
250
|
}
|
|
199
251
|
if (this.preload) {
|
|
200
|
-
void this.init()
|
|
201
|
-
|
|
252
|
+
void this.init()
|
|
253
|
+
.then(() => {
|
|
254
|
+
if (this.destroyed || !isClientBound(this.id, client)) {
|
|
202
255
|
return;
|
|
203
256
|
}
|
|
204
257
|
this.sendContextInit(client);
|
|
205
258
|
markInitSent(this.id, client);
|
|
206
|
-
})
|
|
259
|
+
})
|
|
260
|
+
.catch(() => { });
|
|
207
261
|
}
|
|
208
262
|
const clientSubscription = new rxjs_1.Subscription();
|
|
209
263
|
this.clientSubscriptions.set(client, clientSubscription);
|
|
@@ -220,37 +274,12 @@ class Context {
|
|
|
220
274
|
clientSubscription.add(client.incomingMessage$
|
|
221
275
|
.pipe((0, rxjs_1.filter)((unsafeMessage) => unsafeMessage instanceof targeted_message_1.TargetedMessage &&
|
|
222
276
|
unsafeMessage.target === this.id))
|
|
223
|
-
.subscribe((
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
if (this.destroyed) {
|
|
230
|
-
return;
|
|
231
|
-
}
|
|
232
|
-
this.sendContextInit(client);
|
|
233
|
-
if (!isInitSent(this.id, client)) {
|
|
234
|
-
markInitSent(this.id, client);
|
|
235
|
-
}
|
|
236
|
-
});
|
|
237
|
-
return;
|
|
238
|
-
}
|
|
239
|
-
if (unsafeMessage instanceof index_2.ContextValuesMessage) {
|
|
240
|
-
const payloadSchema = zod_1.z.array(zod_1.z.strictObject({ key: zod_1.z.string(), value: zod_1.z.unknown() }));
|
|
241
|
-
const changes = payloadSchema.parse(unsafeMessage.payload);
|
|
242
|
-
for (const change of changes) {
|
|
243
|
-
this.assertClientChangeAllowed(change.key, change.value);
|
|
244
|
-
}
|
|
245
|
-
const patch = {};
|
|
246
|
-
for (const change of changes) {
|
|
247
|
-
patch[change.key] = change.value;
|
|
248
|
-
}
|
|
249
|
-
this.dataChangedByClient = client;
|
|
250
|
-
this.set(patch);
|
|
251
|
-
return;
|
|
252
|
-
}
|
|
253
|
-
})));
|
|
277
|
+
.subscribe((unsafeMessage) => {
|
|
278
|
+
this.incomingClientMessages$.next({
|
|
279
|
+
client,
|
|
280
|
+
message: unsafeMessage,
|
|
281
|
+
});
|
|
282
|
+
}));
|
|
254
283
|
}
|
|
255
284
|
subscribeToDataChanges() {
|
|
256
285
|
let prevData; // pairwise() из rxjs имеет сцефику, если в next передать измененный объект, то prev и active совпадут, поэтому лучше хранить копию самому
|
|
@@ -350,8 +379,9 @@ class Context {
|
|
|
350
379
|
updateDataAndWait(mutator) {
|
|
351
380
|
this.assertNotDestroyed();
|
|
352
381
|
this.assertInitialized();
|
|
353
|
-
const
|
|
354
|
-
const
|
|
382
|
+
const currentData = this.data$.getValue();
|
|
383
|
+
const prevData = structuredClone(currentData);
|
|
384
|
+
const nextData = mutator(structuredClone(currentData));
|
|
355
385
|
const diff = (0, objects_diff_1.objectsDiff)(prevData, nextData);
|
|
356
386
|
this.skipNextDataSync = true;
|
|
357
387
|
this.data$.next(nextData);
|
|
@@ -440,12 +470,14 @@ class Context {
|
|
|
440
470
|
* См. `docs/architecture/context-update-delivery.md`.
|
|
441
471
|
*/
|
|
442
472
|
set(patch) {
|
|
473
|
+
const paths = Object.keys(patch).filter((path) => Object.prototype.hasOwnProperty.call(patch, path));
|
|
474
|
+
(0, assert_non_overlapping_context_paths_1.assertNonOverlappingContextPaths)(paths);
|
|
475
|
+
for (const path of paths) {
|
|
476
|
+
(0, assert_safe_dotted_path_1.assertSafeDottedPath)(path);
|
|
477
|
+
}
|
|
443
478
|
return this.updateDataAndWait((data) => {
|
|
444
|
-
for (const path of
|
|
445
|
-
|
|
446
|
-
if (Object.prototype.hasOwnProperty.call(patch, path)) {
|
|
447
|
-
(0, set_object_property_1.setObjectProperty)(data, path, patch[path]);
|
|
448
|
-
}
|
|
479
|
+
for (const path of paths) {
|
|
480
|
+
(0, set_object_property_1.setObjectProperty)(data, path, patch[path]);
|
|
449
481
|
}
|
|
450
482
|
return data;
|
|
451
483
|
});
|
|
@@ -457,7 +489,7 @@ class Context {
|
|
|
457
489
|
* Возвращает тот же hot {@link Observable}, что и {@link set}.
|
|
458
490
|
*/
|
|
459
491
|
replace(data) {
|
|
460
|
-
return this.updateDataAndWait(() => data);
|
|
492
|
+
return this.updateDataAndWait(() => structuredClone(data));
|
|
461
493
|
}
|
|
462
494
|
/**
|
|
463
495
|
* Глубокая копия всего `T` (structured clone корня).
|
|
@@ -539,3 +571,15 @@ class Context {
|
|
|
539
571
|
}
|
|
540
572
|
}
|
|
541
573
|
exports.Context = Context;
|
|
574
|
+
/**
|
|
575
|
+
* Создаёт контекст данных BFF: хранилище состояния с синхронизацией клиент ↔ сервер.
|
|
576
|
+
*
|
|
577
|
+
* Тип данных выводится из `data`, тип Zod-схемы — из `schema`. Связь проверяется через
|
|
578
|
+
* {@link ContextSchema}. Generic-параметры у вызова не задаются.
|
|
579
|
+
*
|
|
580
|
+
* Если в начальном `data` нет части полей (например опциональных), укажите тип на колбэке:
|
|
581
|
+
* `data: async (): Promise<MyT> => ({ … })`.
|
|
582
|
+
*/
|
|
583
|
+
function context(config) {
|
|
584
|
+
return new Context(config);
|
|
585
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.assertNonOverlappingContextPaths = assertNonOverlappingContextPaths;
|
|
4
|
+
/**
|
|
5
|
+
* Запрещает дубли и вложенные dotted-пути в одном patch
|
|
6
|
+
* (например `user` и `user.name` вместе).
|
|
7
|
+
*/
|
|
8
|
+
function assertNonOverlappingContextPaths(paths) {
|
|
9
|
+
const sorted = [...paths].sort();
|
|
10
|
+
for (let i = 1; i < sorted.length; i++) {
|
|
11
|
+
const previous = sorted[i - 1];
|
|
12
|
+
const current = sorted[i];
|
|
13
|
+
if (current === previous || current.startsWith(`${previous}.`)) {
|
|
14
|
+
throw new Error(`Overlapping context paths: "${previous}" and "${current}"`);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.assertSafeDottedPath = assertSafeDottedPath;
|
|
4
|
+
const forbiddenPathSegments = new Set([
|
|
5
|
+
"__proto__",
|
|
6
|
+
"prototype",
|
|
7
|
+
"constructor",
|
|
8
|
+
]);
|
|
9
|
+
/**
|
|
10
|
+
* Проверяет dotted-путь данных контекста (сегменты между точками).
|
|
11
|
+
* Запрещены пустые сегменты и prototype pollution.
|
|
12
|
+
*/
|
|
13
|
+
function assertSafeDottedPath(key) {
|
|
14
|
+
if (!key) {
|
|
15
|
+
throw new Error(`Invalid context path: "${key}"`);
|
|
16
|
+
}
|
|
17
|
+
const parts = key.split(".");
|
|
18
|
+
if (parts.some((part) => !part || forbiddenPathSegments.has(part))) {
|
|
19
|
+
throw new Error(`Invalid context path: "${key}"`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -8,14 +8,35 @@ function isZodObject(schema) {
|
|
|
8
8
|
function isZodArray(schema) {
|
|
9
9
|
return schema instanceof zod_1.z.ZodArray;
|
|
10
10
|
}
|
|
11
|
+
/** Объектная shape для навигации по dotted-пути (без object-level pipe/transform). */
|
|
12
|
+
function objectShapeForPick(schema) {
|
|
13
|
+
let current = schema;
|
|
14
|
+
for (;;) {
|
|
15
|
+
if (isZodObject(current)) {
|
|
16
|
+
return current;
|
|
17
|
+
}
|
|
18
|
+
if (current instanceof zod_1.z.ZodOptional || current instanceof zod_1.z.ZodNullable) {
|
|
19
|
+
current = current.unwrap();
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
if (current instanceof zod_1.z.ZodPipe) {
|
|
23
|
+
const inner = current._def.in;
|
|
24
|
+
if (isZodObject(inner)) {
|
|
25
|
+
return inner;
|
|
26
|
+
}
|
|
27
|
+
break;
|
|
28
|
+
}
|
|
29
|
+
break;
|
|
30
|
+
}
|
|
31
|
+
throw Error("Not a zod object");
|
|
32
|
+
}
|
|
11
33
|
function pickObject(schema, path) {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
const newSchema = schema.shape?.[path];
|
|
34
|
+
const objectSchema = objectShapeForPick(schema);
|
|
35
|
+
const newSchema = objectSchema.shape?.[path];
|
|
15
36
|
if (!newSchema)
|
|
16
37
|
throw Error(
|
|
17
38
|
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
|
18
|
-
`${path} does not exist on schema with keys: ${Object.keys(
|
|
39
|
+
`${path} does not exist on schema with keys: ${Object.keys(objectSchema.shape)}`);
|
|
19
40
|
return newSchema;
|
|
20
41
|
}
|
|
21
42
|
function pickArray(schema) {
|
|
@@ -3,7 +3,7 @@ import type { Client } from "../client";
|
|
|
3
3
|
* Observer для подписок на `incomingMessage$`: синхронные ошибки в `next`
|
|
4
4
|
* и ошибки потока перенаправляются в `client.error$`.
|
|
5
5
|
*/
|
|
6
|
-
export declare function incomingMessageObserver<T>(client: Client, next: (value: T) => void): {
|
|
6
|
+
export declare function incomingMessageObserver<T>(client: Client, next: (value: T) => void | Promise<void>): {
|
|
7
7
|
next: (value: T) => void;
|
|
8
8
|
error: (error: unknown) => void;
|
|
9
9
|
};
|
|
@@ -10,7 +10,12 @@ function incomingMessageObserver(client, next) {
|
|
|
10
10
|
return {
|
|
11
11
|
next: (value) => {
|
|
12
12
|
try {
|
|
13
|
-
next(value);
|
|
13
|
+
const result = next(value);
|
|
14
|
+
if (result instanceof Promise) {
|
|
15
|
+
void result.catch((error) => {
|
|
16
|
+
client.error$.next(error);
|
|
17
|
+
});
|
|
18
|
+
}
|
|
14
19
|
}
|
|
15
20
|
catch (error) {
|
|
16
21
|
client.error$.next(error);
|
package/package.json
CHANGED