@matreshka/bff 0.30.0 → 0.31.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/inputs/input-component.d.ts +4 -4
- package/dist/components/outputs/output-component.d.ts +5 -5
- package/dist/components/types/component-sequence.d.ts +2 -2
- package/dist/core/actions/dec-context-value.d.ts +3 -3
- package/dist/core/actions/inc-context-value.d.ts +4 -4
- package/dist/core/actions/set-context.d.ts +2 -2
- package/dist/core/actions/toggle-context-value.d.ts +2 -2
- package/dist/core/conditions/condition-operand.d.ts +7 -7
- package/dist/core/context/context-create.d.ts +91 -0
- package/dist/core/context/context-create.js +7 -0
- package/dist/core/context/context-ref.d.ts +5 -5
- package/dist/core/context/context.d.ts +13 -90
- package/dist/core/context/context.js +25 -13
- package/dist/core/types/context-value-ref.d.ts +6 -6
- package/dist/platforms/platform.d.ts +5 -5
- package/package.json +1 -1
|
@@ -1,10 +1,10 @@
|
|
|
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 { ComponentInstance, ComponentTreeNode, Context, ContextRef,
|
|
4
|
+
import { ComponentInstance, ComponentTreeNode, Context, ContextRef, ContextRefValueType, JsonObject, StandaloneComponent } from "../core";
|
|
5
5
|
import { Component, ComponentInitConfig, ComponentProperties } from "./component";
|
|
6
6
|
type ForEachArrayValue = readonly unknown[] | unknown[];
|
|
7
|
-
type ForEachItemArray<RefType extends ContextRef<any, any>> = Extract<
|
|
7
|
+
type ForEachItemArray<RefType extends ContextRef<any, any>> = Extract<ContextRefValueType<RefType>, ForEachArrayValue>;
|
|
8
8
|
export type CompatibleForEachRef<RefType extends ContextRef<any, any>> = [
|
|
9
9
|
ForEachItemArray<RefType>
|
|
10
10
|
] extends [never] ? never : RefType;
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { CompatibleContextRefOfValue, Componentable, ContextRefOfValue, StandaloneComponent } from "../../core";
|
|
2
2
|
import { Component, ComponentInitConfig, ComponentProperties } from "../component";
|
|
3
3
|
/** Ref на поле ввода: значение `ValueType | undefined`. */
|
|
4
|
-
export type InputContextRef<ValueType> =
|
|
4
|
+
export type InputContextRef<ValueType> = ContextRefOfValue<ValueType | undefined>;
|
|
5
5
|
/** Ref на строковое поле ввода. */
|
|
6
6
|
export type StringInputContextRef = InputContextRef<string>;
|
|
7
7
|
/**
|
|
8
8
|
* Конфигурация инициализации компонента ввода.
|
|
9
9
|
* @property ref Ссылка в контексте.
|
|
10
10
|
*/
|
|
11
|
-
/** @see
|
|
12
|
-
export type CompatibleInputRef<ValueType, RefType extends InputContextRef<ValueType>> =
|
|
11
|
+
/** @see CompatibleContextRefOfValue */
|
|
12
|
+
export type CompatibleInputRef<ValueType, RefType extends InputContextRef<ValueType>> = CompatibleContextRefOfValue<ValueType, RefType>;
|
|
13
13
|
export type InputInitConfig<ValueType, ComponentType extends Componentable = InputComponent, RefType extends InputContextRef<ValueType> = InputContextRef<ValueType>, PropertiesType extends InputProperties = InputProperties> = {
|
|
14
14
|
ref: CompatibleInputRef<ValueType, RefType>;
|
|
15
15
|
} & ComponentInitConfig<ComponentType, PropertiesType>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Componentable,
|
|
1
|
+
import { Componentable, ContextRefOfValue, ContextRefValueType, StandaloneComponent } from "../../core";
|
|
2
2
|
import { Component, ComponentInitConfig, ComponentProperties } from "../component";
|
|
3
3
|
/**
|
|
4
4
|
* Конфигурация инициализации для компонента вывода.
|
|
@@ -8,13 +8,13 @@ import { Component, ComponentInitConfig, ComponentProperties } from "../componen
|
|
|
8
8
|
* @property ref Ссылка на значение в контексте, откуда будет браться значение.
|
|
9
9
|
* @property value Статическое значение.
|
|
10
10
|
*/
|
|
11
|
-
/** Ref на поле вывода (`
|
|
12
|
-
export type OutputContextRef<ValueType> =
|
|
11
|
+
/** Ref на поле вывода (`ContextRefOfValue` для scalar `ValueType` компонента). */
|
|
12
|
+
export type OutputContextRef<ValueType> = ContextRefOfValue<ValueType | undefined>;
|
|
13
13
|
/** Ref на строковое поле вывода. */
|
|
14
14
|
export type StringOutputContextRef = OutputContextRef<string>;
|
|
15
15
|
/** Ref на числовое поле вывода. */
|
|
16
16
|
export type NumberOutputContextRef = OutputContextRef<number>;
|
|
17
|
-
export type CompatibleOutputRef<ValueType, RefType extends OutputContextRef<ValueType>> = ValueType extends
|
|
17
|
+
export type CompatibleOutputRef<ValueType, RefType extends OutputContextRef<ValueType>> = ValueType extends ContextRefValueType<RefType> ? RefType : never;
|
|
18
18
|
export type OutputInitConfig<ValueType, ComponentType extends Componentable = OutputComponent, RefType extends OutputContextRef<ValueType> = OutputContextRef<ValueType>, PropertiesType extends OutputProperties = OutputProperties> = ({
|
|
19
19
|
ref: CompatibleOutputRef<ValueType, RefType>;
|
|
20
20
|
} | {
|
|
@@ -56,7 +56,7 @@ export declare abstract class OutputComponent<InitConfigType extends OutputInitC
|
|
|
56
56
|
* Первая аргумент-мост для фабрик output: литерал `value` или экземпляр {@link ContextRef}.
|
|
57
57
|
*/
|
|
58
58
|
export declare function outputValueRefToConfig<TOpts extends object>(valueOrRef: unknown, opts: TOpts): TOpts & ({
|
|
59
|
-
ref:
|
|
59
|
+
ref: ContextRefOfValue<unknown>;
|
|
60
60
|
} | {
|
|
61
61
|
value: unknown;
|
|
62
62
|
});
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { ForEach } from "@matreshka/bff/components/for-each";
|
|
2
|
-
import type { ComponentTreeNode,
|
|
3
|
-
export type ComponentSequence<DataType, T extends ComponentTreeNode = ComponentTreeNode> = (T | ForEach<
|
|
2
|
+
import type { ComponentTreeNode, ContextArrayValueRef } from "@matreshka/bff/core";
|
|
3
|
+
export type ComponentSequence<DataType, T extends ComponentTreeNode = ComponentTreeNode> = (T | ForEach<ContextArrayValueRef<DataType>, T>)[];
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ValueOrContextRef } from "../types/context-value-ref";
|
|
2
2
|
import { ActionConfig } from "./action";
|
|
3
3
|
import { NumberValueRef } from "./inc-context-value";
|
|
4
4
|
import { LocalAction } from "./local-action";
|
|
@@ -9,7 +9,7 @@ import { LocalAction } from "./local-action";
|
|
|
9
9
|
export declare class DecContextValue extends LocalAction {
|
|
10
10
|
private readonly ref;
|
|
11
11
|
private readonly step;
|
|
12
|
-
constructor(ref: NumberValueRef, step:
|
|
12
|
+
constructor(ref: NumberValueRef, step: ValueOrContextRef<number>, config?: ActionConfig);
|
|
13
13
|
class(): string;
|
|
14
14
|
payload(): object;
|
|
15
15
|
}
|
|
@@ -18,4 +18,4 @@ export declare class DecContextValue extends LocalAction {
|
|
|
18
18
|
* Принимает только `ContextRef` с числовым значением.
|
|
19
19
|
* Без `step` клиент вычитает 1.
|
|
20
20
|
*/
|
|
21
|
-
export declare function decContextValue(ref: NumberValueRef, step?:
|
|
21
|
+
export declare function decContextValue(ref: NumberValueRef, step?: ValueOrContextRef<number>, config?: ActionConfig): DecContextValue;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ContextRefOfValue, ValueOrContextRef } from "../types/context-value-ref";
|
|
2
2
|
import { ActionConfig } from "./action";
|
|
3
3
|
import { LocalAction } from "./local-action";
|
|
4
4
|
/** Ref на числовое поле контекста. */
|
|
5
|
-
export type NumberValueRef =
|
|
5
|
+
export type NumberValueRef = ContextRefOfValue<number | undefined>;
|
|
6
6
|
/**
|
|
7
7
|
* Изменение числового значения в Context на клиенте на `step`
|
|
8
8
|
* (с sync на BFF через `context-values`).
|
|
@@ -10,7 +10,7 @@ export type NumberValueRef = ContextValueRef<number | undefined>;
|
|
|
10
10
|
export declare class IncContextValue extends LocalAction {
|
|
11
11
|
private readonly ref;
|
|
12
12
|
private readonly step;
|
|
13
|
-
constructor(ref: NumberValueRef, step:
|
|
13
|
+
constructor(ref: NumberValueRef, step: ValueOrContextRef<number>, config?: ActionConfig);
|
|
14
14
|
class(): string;
|
|
15
15
|
payload(): object;
|
|
16
16
|
}
|
|
@@ -19,4 +19,4 @@ export declare class IncContextValue extends LocalAction {
|
|
|
19
19
|
* Принимает только `ContextRef` с числовым значением.
|
|
20
20
|
* Без `step` клиент прибавляет 1.
|
|
21
21
|
*/
|
|
22
|
-
export declare function incContextValue(ref: NumberValueRef, step?:
|
|
22
|
+
export declare function incContextValue(ref: NumberValueRef, step?: ValueOrContextRef<number>, config?: ActionConfig): IncContextValue;
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { JsonObject } from "@matreshka/client-bff-protocol/types/json";
|
|
2
2
|
import { Context, ContextPathPatch } from "../context/context";
|
|
3
|
-
import {
|
|
3
|
+
import { ValueOrContextRef } from "../types/context-value-ref";
|
|
4
4
|
import { ActionConfig } from "./action";
|
|
5
5
|
import { LocalAction } from "./local-action";
|
|
6
6
|
export type LocalContextPathPatch<T extends JsonObject> = Partial<{
|
|
7
|
-
[K in keyof ContextPathPatch<T>]:
|
|
7
|
+
[K in keyof ContextPathPatch<T>]: ValueOrContextRef<ContextPathPatch<T>[K]>;
|
|
8
8
|
}>;
|
|
9
9
|
/**
|
|
10
10
|
* Локальная запись patch в Context на клиенте (с sync на BFF через `context-values`).
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ContextRefOfValue } from "../types/context-value-ref";
|
|
2
2
|
import { ActionConfig } from "./action";
|
|
3
3
|
import { LocalAction } from "./local-action";
|
|
4
4
|
/** Ref на boolean-поле контекста. */
|
|
5
|
-
export type BooleanValueRef =
|
|
5
|
+
export type BooleanValueRef = ContextRefOfValue<boolean | undefined>;
|
|
6
6
|
/**
|
|
7
7
|
* Инверсия boolean-значения в Context на клиенте (с sync на BFF через `context-values`).
|
|
8
8
|
*/
|
|
@@ -1,28 +1,28 @@
|
|
|
1
1
|
import type { Json, JsonObject, JsonPrimitive } from "@matreshka/client-bff-protocol/types/json";
|
|
2
2
|
import type { SerializedOperand } from "@matreshka/client-bff-protocol/types/serialized-operand";
|
|
3
3
|
import { Paths, PathValue } from "ts-essentials";
|
|
4
|
-
import { ContextRef,
|
|
5
|
-
import type {
|
|
4
|
+
import { ContextRef, ContextRefValueType } from "../context/context-ref";
|
|
5
|
+
import type { CompatibleContextRefOfValue } from "../types/context-value-ref";
|
|
6
6
|
type ContextArrayValue = readonly unknown[] | unknown[];
|
|
7
7
|
/** Элемент массива по значению `ContextRef`. */
|
|
8
|
-
export type ContextRefArrayElement<R extends ContextRef<any, any>> = Extract<
|
|
8
|
+
export type ContextRefArrayElement<R extends ContextRef<any, any>> = Extract<ContextRefValueType<R>, ContextArrayValue>[number];
|
|
9
9
|
/** Ref на массив в контексте (значение по ref — массив или readonly-массив). */
|
|
10
10
|
export type CompatibleArrayContextRef<R extends ContextRef<any, any>> = [
|
|
11
|
-
Extract<
|
|
11
|
+
Extract<ContextRefValueType<R>, ContextArrayValue>
|
|
12
12
|
] extends [never] ? never : R;
|
|
13
13
|
/**
|
|
14
14
|
* Операнд сравнения по известному типу значения: JSON-примитив или совместимая `ContextRef`.
|
|
15
15
|
*
|
|
16
|
-
* Ref-операнд: {@link
|
|
16
|
+
* Ref-операнд: {@link CompatibleContextRefOfValue} с `ContextRef<any, any>` (item-ref из `forEach`
|
|
17
17
|
* и ref из другого контекста). Без `| undefined` у ValueType — иначе `(T | undefined) extends T`
|
|
18
18
|
* отсекает ref↔ref сравнения.
|
|
19
19
|
*/
|
|
20
|
-
export type ConditionOperandFor<ValueType> = (ValueType & JsonPrimitive) |
|
|
20
|
+
export type ConditionOperandFor<ValueType> = (ValueType & JsonPrimitive) | CompatibleContextRefOfValue<ValueType, ContextRef<any, any>>;
|
|
21
21
|
/**
|
|
22
22
|
* Операнд условия на BFF: JSON-примитив того же типа, что значение по `ref`,
|
|
23
23
|
* либо другая ссылка с совместимым типом значения (сравнение в рантайме через `===`).
|
|
24
24
|
*/
|
|
25
|
-
export type ConditionOperand<R extends ContextRef<any, any>> = ConditionOperandFor<
|
|
25
|
+
export type ConditionOperand<R extends ContextRef<any, any>> = ConditionOperandFor<ContextRefValueType<R>>;
|
|
26
26
|
/** Значение поля элемента массива по `itemPath` (пустой путь — сам элемент). */
|
|
27
27
|
export type ArrayIncludesItemValue<Item, P extends string> = P extends "" ? Item : Item extends JsonObject ? PathValue<Item, P & Paths<Item>> : never;
|
|
28
28
|
/** Операнд {@link ContextArrayIncludes} / {@link ContextArrayNotIncludes}. */
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { JsonObject } from "@matreshka/client-bff-protocol/types/json";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { Context } from "./context";
|
|
4
|
+
/** Карта файла:
|
|
5
|
+
* 1) type-хелперы валидации schema↔data (extra-keys, compatibility)
|
|
6
|
+
* 2) публичные типы createContext
|
|
7
|
+
* 3) overload-ы и runtime-реализация createContext
|
|
8
|
+
*/
|
|
9
|
+
type StripNullish<T> = Exclude<T, null | undefined>;
|
|
10
|
+
type ArrayElement<T> = T extends readonly (infer E)[] ? E : never;
|
|
11
|
+
type FieldExtraSchemaKeysOne<TField, IField> = [StripNullish<IField>] extends [
|
|
12
|
+
readonly unknown[]
|
|
13
|
+
] ? [StripNullish<TField>] extends [readonly unknown[]] ? ExtraSchemaKeys<ArrayElement<StripNullish<TField>>, ArrayElement<StripNullish<IField>>> : never : [StripNullish<IField>] extends [JsonObject] ? [StripNullish<TField>] extends [JsonObject] ? ExtraSchemaKeys<StripNullish<TField>, StripNullish<IField>> : never : never;
|
|
14
|
+
/** Лишние ключи внутри поля (union, optional/nullable, массивы объектов). */
|
|
15
|
+
type FieldExtraSchemaKeys<TField, IField> = IField extends any ? FieldExtraSchemaKeysOne<TField, IField> : never;
|
|
16
|
+
/** Лишние ключи для одной пары object-веток (коррелированные поля). `true` — есть лишние ключи. */
|
|
17
|
+
type ExtraSchemaKeysObjectExact<T extends JsonObject, Input extends JsonObject> = Exclude<keyof Input, keyof T> extends never ? {
|
|
18
|
+
[K in keyof Input & keyof T]: FieldExtraSchemaKeys<T[K], Input[K]>;
|
|
19
|
+
}[keyof Input & keyof T] extends never ? never : true : true;
|
|
20
|
+
/** Есть ветка `T`, для которой `Input` не содержит лишних ключей. */
|
|
21
|
+
type SomeExtraSchemaKeysBranchOk<T, Input extends JsonObject> = T extends JsonObject ? ExtraSchemaKeysObjectExact<T, Input> extends never ? true : never : never;
|
|
22
|
+
/**
|
|
23
|
+
* Лишние ключи в shape схемы относительно `T` (рекурсивно).
|
|
24
|
+
* Union в `Input` и `T` проверяется по отдельным веткам. `true` — есть лишние ключи.
|
|
25
|
+
*/
|
|
26
|
+
type ExtraSchemaKeys<T, Input> = Input extends JsonObject ? SomeExtraSchemaKeysBranchOk<T, Input> extends true ? never : true : never;
|
|
27
|
+
type DeepPartial<T> = T extends readonly (infer E)[] ? readonly DeepPartial<E>[] : T extends object ? {
|
|
28
|
+
[K in keyof T]?: DeepPartial<T[K]>;
|
|
29
|
+
} : T;
|
|
30
|
+
type SchemaOutputCompatible<T extends JsonObject, S extends z.ZodObject> = z.output<S> extends DeepPartial<T> ? true : false;
|
|
31
|
+
/**
|
|
32
|
+
* Zod-схема для {@link createContext}: без лишних ключей во {@link z.input} и {@link z.output}
|
|
33
|
+
* ({@link ExtraSchemaKeys}, union по веткам); {@link z.output} совместим с `T`
|
|
34
|
+
* ({@link SchemaOutputCompatible}, через deep partial). В контекст попадает output после `parse()`.
|
|
35
|
+
*/
|
|
36
|
+
export type ContextSchema<T extends JsonObject, S extends z.ZodObject> = SchemaOutputCompatible<T, S> extends false ? never : ExtraSchemaKeys<T, z.input<S>> extends never ? ExtraSchemaKeys<T, z.output<S>> extends never ? S : never : never;
|
|
37
|
+
/** Конфиг {@link createContext} без клиентской Zod-схемы. */
|
|
38
|
+
export type ContextInitWithoutSchema<T extends JsonObject> = {
|
|
39
|
+
data: () => Promise<T>;
|
|
40
|
+
schema?: undefined;
|
|
41
|
+
preload?: boolean;
|
|
42
|
+
persistent?: boolean;
|
|
43
|
+
};
|
|
44
|
+
/** Конфиг {@link createContext} с Zod-схемой клиентских изменений. */
|
|
45
|
+
export type ContextInitWithSchema<T extends JsonObject, S extends z.ZodObject> = {
|
|
46
|
+
data: () => Promise<T>;
|
|
47
|
+
schema: ContextSchema<T, S>;
|
|
48
|
+
preload?: boolean;
|
|
49
|
+
persistent?: boolean;
|
|
50
|
+
};
|
|
51
|
+
/** Конфигурация {@link createContext} (единственный аргумент). */
|
|
52
|
+
export type ContextInitConfig<T extends JsonObject, S extends z.ZodObject | undefined = undefined> = S extends z.ZodObject ? ContextInitWithSchema<T, S> : ContextInitWithoutSchema<T>;
|
|
53
|
+
/** Минимальная форма аргумента {@link createContext}. */
|
|
54
|
+
type ContextInitShape = {
|
|
55
|
+
data: () => Promise<JsonObject>;
|
|
56
|
+
schema?: z.ZodObject;
|
|
57
|
+
preload?: boolean;
|
|
58
|
+
persistent?: boolean;
|
|
59
|
+
};
|
|
60
|
+
/** Тип данных `T` из поля `data` конфига. */
|
|
61
|
+
export type ContextDataFromInit<C extends ContextInitShape> = Awaited<ReturnType<C["data"]>>;
|
|
62
|
+
/** Zod-схема из поля `schema` конфига (или `undefined`). */
|
|
63
|
+
export type ContextSchemaFromInit<C extends ContextInitShape> = C extends {
|
|
64
|
+
schema: z.ZodObject;
|
|
65
|
+
} ? C["schema"] : undefined;
|
|
66
|
+
/** Экземпляр {@link Context} по форме конфига {@link createContext}. */
|
|
67
|
+
export type ContextFromInit<C extends ContextInitShape> = Context<ContextDataFromInit<C>>;
|
|
68
|
+
type ContextSchemaCompatibilityGuard<C extends ContextInitShape> = C extends {
|
|
69
|
+
schema: z.ZodObject;
|
|
70
|
+
} ? ContextSchema<ContextDataFromInit<C>, NoInfer<C["schema"]>> extends never ? {
|
|
71
|
+
/**
|
|
72
|
+
* Type helper for better diagnostics:
|
|
73
|
+
* schema must be a subset of data keys and have output-compatible field types.
|
|
74
|
+
*/
|
|
75
|
+
__contextSchemaError__: "createContext(schema): schema is incompatible with data";
|
|
76
|
+
} : unknown : unknown;
|
|
77
|
+
type ContextCreateConfig<C extends ContextInitShape> = C & ContextSchemaCompatibilityGuard<C>;
|
|
78
|
+
/**
|
|
79
|
+
* Создаёт контекст данных BFF: хранилище состояния с синхронизацией клиент ↔ сервер.
|
|
80
|
+
*
|
|
81
|
+
* Тип данных выводится из `data`, тип Zod-схемы — из `schema`. Связь проверяется через
|
|
82
|
+
* {@link ContextSchema}.
|
|
83
|
+
*
|
|
84
|
+
* Если в начальном `data` нет части полей (например опциональных), укажите тип на колбэке:
|
|
85
|
+
* `data: async (): Promise<MyT> => ({ … })`.
|
|
86
|
+
*/
|
|
87
|
+
export declare function createContext<const T extends JsonObject>(config: ContextInitWithoutSchema<T>): Context<T>;
|
|
88
|
+
export declare function createContext<const C extends ContextInitShape & {
|
|
89
|
+
schema: z.ZodObject;
|
|
90
|
+
}>(config: ContextCreateConfig<C>): Context<ContextDataFromInit<C>>;
|
|
91
|
+
export {};
|
|
@@ -7,21 +7,21 @@ import { IncContextValue } from "../actions/inc-context-value";
|
|
|
7
7
|
import { SetContext } from "../actions/set-context";
|
|
8
8
|
import { ToggleContextValue } from "../actions/toggle-context-value";
|
|
9
9
|
import type { ContextUpdateDelivery } from "../types/context-update-delivery";
|
|
10
|
-
import {
|
|
10
|
+
import { ValueOrContextRef } from "../types/context-value-ref";
|
|
11
11
|
import { Context } from "./context";
|
|
12
12
|
type ContextRefLocalSet<ContextType extends JsonObject, PathType extends string> = {
|
|
13
|
-
set: (value:
|
|
13
|
+
set: (value: ValueOrContextRef<PathValue<ContextType, PathType>>, config?: ActionConfig) => SetContext<ContextType>;
|
|
14
14
|
};
|
|
15
15
|
type ContextRefLocalToggle = {
|
|
16
16
|
toggle: (config?: ActionConfig) => ToggleContextValue;
|
|
17
17
|
};
|
|
18
18
|
type ContextRefLocalNumeric = {
|
|
19
|
-
inc: (step?:
|
|
20
|
-
dec: (step?:
|
|
19
|
+
inc: (step?: ValueOrContextRef<number>, config?: ActionConfig) => IncContextValue;
|
|
20
|
+
dec: (step?: ValueOrContextRef<number>, config?: ActionConfig) => DecContextValue;
|
|
21
21
|
};
|
|
22
22
|
/** Локальные действия по ref; `toggle` / `inc` / `dec` — по типу значения по пути. */
|
|
23
23
|
export type ContextRefLocalActions<ContextType extends JsonObject, PathType extends string> = ContextRefLocalSet<ContextType, PathType> & (PathValue<ContextType, PathType> extends boolean | undefined ? ContextRefLocalToggle : {}) & (PathValue<ContextType, PathType> extends number | undefined ? ContextRefLocalNumeric : {});
|
|
24
|
-
export type
|
|
24
|
+
export type ContextRefValueType<R extends ContextRef> = R extends {
|
|
25
25
|
readonly __valueType?: infer ValueType;
|
|
26
26
|
} ? Exclude<ValueType, undefined> : R extends ContextRef<infer ContextType, infer PathType> ? PathValue<ContextType, PathType> : never;
|
|
27
27
|
export declare class ContextRef<ContextType extends JsonObject = JsonObject, PathType extends string = string> {
|
|
@@ -6,9 +6,10 @@ import { ActionConfig } from "../actions/action";
|
|
|
6
6
|
import { LocalContextPathPatch } from "../actions/set-context";
|
|
7
7
|
import type { Client } from "../client";
|
|
8
8
|
import { ContextUpdateDelivery } from "../types/context-update-delivery";
|
|
9
|
-
import {
|
|
9
|
+
import { ValueOrContextRef } from "../types/context-value-ref";
|
|
10
10
|
import { ContextRef } from "./context-ref";
|
|
11
11
|
export type { ContextUpdateDelivery } from "../types/context-update-delivery";
|
|
12
|
+
export * from "./context-create";
|
|
12
13
|
/** Частичное обновление данных контекста по dotted-путям (см. {@link Context.set}). */
|
|
13
14
|
export type ContextPathPatch<T extends JsonObject> = Partial<{
|
|
14
15
|
[K in Paths<T>]: PathValue<T, K>;
|
|
@@ -22,88 +23,12 @@ export type ContextClientUpdatesForbiddenSchema = z.ZodObject<Record<string, nev
|
|
|
22
23
|
};
|
|
23
24
|
/** @see ContextClientUpdatesForbiddenSchema */
|
|
24
25
|
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;
|
|
40
|
-
/**
|
|
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 createContext}: без лишних ключей во {@link z.input} и {@link z.output}
|
|
63
|
-
* ({@link ExtraSchemaKeys}, union по веткам); {@link z.output} совместим с `T`
|
|
64
|
-
* ({@link SchemaCompatible}, вложенные подмножества). В контекст попадает output после `parse()`.
|
|
65
|
-
*/
|
|
66
|
-
export type ContextSchema<T extends JsonObject, S extends z.ZodObject> = [
|
|
67
|
-
S
|
|
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 createContext} без клиентской Zod-схемы. */
|
|
70
|
-
export type ContextInitWithoutSchema<T extends JsonObject> = {
|
|
71
|
-
data: () => Promise<T>;
|
|
72
|
-
schema?: undefined;
|
|
73
|
-
preload?: boolean;
|
|
74
|
-
persistent?: boolean;
|
|
75
|
-
};
|
|
76
|
-
/** Конфиг {@link createContext} с Zod-схемой клиентских изменений. */
|
|
77
|
-
export type ContextInitWithSchema<T extends JsonObject, S extends z.ZodObject> = {
|
|
78
|
-
data: () => Promise<T>;
|
|
79
|
-
schema: ContextSchema<T, S>;
|
|
80
|
-
preload?: boolean;
|
|
81
|
-
persistent?: boolean;
|
|
82
|
-
};
|
|
83
|
-
/** Конфигурация {@link createContext} (единственный аргумент). */
|
|
84
|
-
export type ContextInitConfig<T extends JsonObject, S extends z.ZodObject | undefined = undefined> = S extends z.ZodObject ? ContextInitWithSchema<T, S> : ContextInitWithoutSchema<T>;
|
|
85
|
-
/** Минимальная форма аргумента {@link createContext}. */
|
|
86
|
-
type ContextInitShape = {
|
|
87
|
-
data: () => Promise<JsonObject>;
|
|
88
|
-
schema?: z.ZodObject;
|
|
89
|
-
preload?: boolean;
|
|
90
|
-
persistent?: boolean;
|
|
91
|
-
};
|
|
92
26
|
type ContextRuntimeInit<T extends JsonObject> = {
|
|
93
27
|
data: () => Promise<T>;
|
|
94
28
|
schema?: z.ZodObject;
|
|
95
29
|
preload?: boolean;
|
|
96
30
|
persistent?: boolean;
|
|
97
31
|
};
|
|
98
|
-
/** Тип данных `T` из поля `data` конфига. */
|
|
99
|
-
export type ContextDataFromInit<C extends ContextInitShape> = Awaited<ReturnType<C["data"]>>;
|
|
100
|
-
/** Zod-схема из поля `schema` конфига (или `undefined`). */
|
|
101
|
-
export type ContextSchemaFromInit<C extends ContextInitShape> = C extends {
|
|
102
|
-
schema: z.ZodObject;
|
|
103
|
-
} ? C["schema"] : undefined;
|
|
104
|
-
/** Экземпляр {@link Context} по форме конфига {@link createContext}. */
|
|
105
|
-
export type ContextFromInit<C extends ContextInitShape> = Context<ContextDataFromInit<C>>;
|
|
106
|
-
type ValidatedContextInit<C extends ContextInitShape> = ContextInitConfig<ContextDataFromInit<C>, ContextSchemaFromInit<C> extends z.ZodObject ? ContextSchemaFromInit<C> : undefined>;
|
|
107
32
|
/**
|
|
108
33
|
* Контекст данных, связанных с клиентом.
|
|
109
34
|
*
|
|
@@ -132,8 +57,8 @@ export declare class Context<T extends JsonObject> {
|
|
|
132
57
|
readonly local: {
|
|
133
58
|
set: (patch: LocalContextPathPatch<T>, config?: ActionConfig) => import("../actions/set-context").SetContext<T>;
|
|
134
59
|
toggle: <K extends Paths<T>>(path: PathValue<T, K> extends boolean | undefined ? K : never, config?: ActionConfig) => import("../actions/toggle-context-value").ToggleContextValue;
|
|
135
|
-
inc: <K extends Paths<T>>(path: PathValue<T, K> extends number | undefined ? K : never, step?:
|
|
136
|
-
dec: <K extends Paths<T>>(path: PathValue<T, K> extends number | undefined ? K : never, step?:
|
|
60
|
+
inc: <K extends Paths<T>>(path: PathValue<T, K> extends number | undefined ? K : never, step?: ValueOrContextRef<number>, config?: ActionConfig) => import("../actions/inc-context-value").IncContextValue;
|
|
61
|
+
dec: <K extends Paths<T>>(path: PathValue<T, K> extends number | undefined ? K : never, step?: ValueOrContextRef<number>, config?: ActionConfig) => import("../actions/dec-context-value").DecContextValue;
|
|
137
62
|
};
|
|
138
63
|
/** Реактивное хранилище инициализации контекста */
|
|
139
64
|
private _init$;
|
|
@@ -166,13 +91,21 @@ export declare class Context<T extends JsonObject> {
|
|
|
166
91
|
private handleTargetedClientMessage;
|
|
167
92
|
/** Ошибка загрузки initDataCallback — в error$ всех клиентов, привязанных к контексту. */
|
|
168
93
|
private reportInitFailureToClients;
|
|
94
|
+
/**
|
|
95
|
+
* Фабричный runtime-вход для {@link createContext}.
|
|
96
|
+
* Не используйте напрямую в прикладном коде — это обходит compile-time проверку schema↔data.
|
|
97
|
+
*
|
|
98
|
+
* @internal
|
|
99
|
+
* @deprecated Internal API. Use createContext(...) instead.
|
|
100
|
+
*/
|
|
101
|
+
static createRuntime<U extends JsonObject>(config: ContextRuntimeInit<U>): Context<U>;
|
|
169
102
|
/**
|
|
170
103
|
* Создаёт экземпляр контекста, привязанный к конкретному клиенту.
|
|
171
104
|
*
|
|
172
105
|
* Подписывается на входящие сообщения от клиента и ошибки, связанные с этим контекстом.
|
|
173
106
|
|
|
174
107
|
*/
|
|
175
|
-
constructor(config: ContextRuntimeInit<T>);
|
|
108
|
+
protected constructor(config: ContextRuntimeInit<T>);
|
|
176
109
|
/** `data$` создан (init мог ещё выполняться — см. {@link init}). */
|
|
177
110
|
inited(): boolean;
|
|
178
111
|
/** Данные загружены: `initDataCallback` завершился. */
|
|
@@ -283,13 +216,3 @@ export declare class Context<T extends JsonObject> {
|
|
|
283
216
|
}
|
|
284
217
|
/** Любой зарегистрированный контекст (с Zod-схемой или без). */
|
|
285
218
|
export type AnyContext = Context<any>;
|
|
286
|
-
/**
|
|
287
|
-
* Создаёт контекст данных BFF: хранилище состояния с синхронизацией клиент ↔ сервер.
|
|
288
|
-
*
|
|
289
|
-
* Тип данных выводится из `data`, тип Zod-схемы — из `schema`. Связь проверяется через
|
|
290
|
-
* {@link ContextSchema}. Generic-параметры у вызова не задаются.
|
|
291
|
-
*
|
|
292
|
-
* Если в начальном `data` нет части полей (например опциональных), укажите тип на колбэке:
|
|
293
|
-
* `data: async (): Promise<MyT> => ({ … })`.
|
|
294
|
-
*/
|
|
295
|
-
export declare function createContext<C extends ContextInitShape>(config: C & ValidatedContextInit<C>): ContextFromInit<C>;
|
|
@@ -1,7 +1,20 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
2
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
17
|
exports.Context = exports.contextClientUpdatesForbiddenSchema = void 0;
|
|
4
|
-
exports.createContext = createContext;
|
|
5
18
|
const index_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/context/index");
|
|
6
19
|
const index_2 = require("@matreshka/client-bff-protocol/messages/client-to-bff/context/index");
|
|
7
20
|
const targeted_message_1 = require("@matreshka/client-bff-protocol/messages/targeted-message");
|
|
@@ -21,6 +34,7 @@ const objects_diff_1 = require("../utils/objects-diff");
|
|
|
21
34
|
const replace_context_keys_1 = require("../utils/replace-context-keys");
|
|
22
35
|
const assert_client_update_schema_1 = require("./assert-client-update-schema");
|
|
23
36
|
const context_ref_1 = require("./context-ref");
|
|
37
|
+
__exportStar(require("./context-create"), exports);
|
|
24
38
|
/** @see ContextClientUpdatesForbiddenSchema */
|
|
25
39
|
exports.contextClientUpdatesForbiddenSchema = zod_1.z.strictObject({});
|
|
26
40
|
/** Отделяет чтение через {@link Context.get} от живого дерева в хранилище. */
|
|
@@ -156,6 +170,16 @@ class Context {
|
|
|
156
170
|
client.error$.next(error);
|
|
157
171
|
});
|
|
158
172
|
}
|
|
173
|
+
/**
|
|
174
|
+
* Фабричный runtime-вход для {@link createContext}.
|
|
175
|
+
* Не используйте напрямую в прикладном коде — это обходит compile-time проверку schema↔data.
|
|
176
|
+
*
|
|
177
|
+
* @internal
|
|
178
|
+
* @deprecated Internal API. Use createContext(...) instead.
|
|
179
|
+
*/
|
|
180
|
+
static createRuntime(config) {
|
|
181
|
+
return new Context(config);
|
|
182
|
+
}
|
|
159
183
|
/**
|
|
160
184
|
* Создаёт экземпляр контекста, привязанный к конкретному клиенту.
|
|
161
185
|
*
|
|
@@ -573,15 +597,3 @@ class Context {
|
|
|
573
597
|
}
|
|
574
598
|
}
|
|
575
599
|
exports.Context = Context;
|
|
576
|
-
/**
|
|
577
|
-
* Создаёт контекст данных BFF: хранилище состояния с синхронизацией клиент ↔ сервер.
|
|
578
|
-
*
|
|
579
|
-
* Тип данных выводится из `data`, тип Zod-схемы — из `schema`. Связь проверяется через
|
|
580
|
-
* {@link ContextSchema}. Generic-параметры у вызова не задаются.
|
|
581
|
-
*
|
|
582
|
-
* Если в начальном `data` нет части полей (например опциональных), укажите тип на колбэке:
|
|
583
|
-
* `data: async (): Promise<MyT> => ({ … })`.
|
|
584
|
-
*/
|
|
585
|
-
function createContext(config) {
|
|
586
|
-
return new Context(config);
|
|
587
|
-
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ContextRef,
|
|
1
|
+
import { ContextRef, ContextRefValueType } from "../context/context-ref";
|
|
2
2
|
/**
|
|
3
3
|
* Ссылка на поле контекста с известным типом значения.
|
|
4
4
|
*
|
|
@@ -8,14 +8,14 @@ import { ContextRef, ContextRefValue } from "../context/context-ref";
|
|
|
8
8
|
*
|
|
9
9
|
* @example
|
|
10
10
|
* ```ts
|
|
11
|
-
* function bindAmount(ref:
|
|
11
|
+
* function bindAmount(ref: ContextRefOfValue<number | undefined>) {
|
|
12
12
|
* ref.get(); // number | undefined
|
|
13
13
|
* }
|
|
14
14
|
*
|
|
15
15
|
* bindAmount(pageContext.ref("amount"));
|
|
16
16
|
* ```
|
|
17
17
|
*/
|
|
18
|
-
export type
|
|
18
|
+
export type ContextRefOfValue<ValueType> = ContextRef<any, any> & {
|
|
19
19
|
readonly __valueType?: ValueType;
|
|
20
20
|
get(): ValueType;
|
|
21
21
|
set(value: ValueType): void;
|
|
@@ -23,12 +23,12 @@ export type ContextValueRef<ValueType> = ContextRef<any, any> & {
|
|
|
23
23
|
/**
|
|
24
24
|
* Ref `R` совместим с ожидаемым типом значения `ValueType` (проверка на call site).
|
|
25
25
|
*/
|
|
26
|
-
export type
|
|
26
|
+
export type CompatibleContextRefOfValue<ValueType, R extends ContextRef> = ValueType extends ContextRefValueType<R> ? R : never;
|
|
27
27
|
/** Статическое значение или ссылка на совместимое значение в контексте. */
|
|
28
|
-
export type
|
|
28
|
+
export type ValueOrContextRef<ValueType> = ValueType | ContextRefOfValue<Exclude<ValueType, undefined>>;
|
|
29
29
|
/**
|
|
30
30
|
* Ссылка на массив элементов в контексте (`ItemType[] | undefined`).
|
|
31
31
|
*
|
|
32
32
|
* Generic задаёт тип **элемента**, как в {@link CompatibleForEachRef} / `forEach`.
|
|
33
33
|
*/
|
|
34
|
-
export type
|
|
34
|
+
export type ContextArrayValueRef<ItemType> = ContextRefOfValue<ItemType[] | undefined>;
|
|
@@ -3,7 +3,7 @@ import type { Observable } from "rxjs";
|
|
|
3
3
|
import { Dialog, Popover } from "../components";
|
|
4
4
|
import { Overlay } from "../components/types/container-overlay";
|
|
5
5
|
import { type WebMcpTool } from "../components/webmcp/web-mcp-tool";
|
|
6
|
-
import { Client, Componentable, ComponentInstance,
|
|
6
|
+
import { Client, Componentable, ComponentInstance, ContextRefOfValue } from "../core";
|
|
7
7
|
import { type PopoverShowComponent, type PopoverShowPlacement } from "./popover-show";
|
|
8
8
|
import { type NavigateResult } from "./utils/client-navigate-platform-action";
|
|
9
9
|
export type { NavigateResult };
|
|
@@ -55,10 +55,10 @@ export declare abstract class Platform {
|
|
|
55
55
|
*/
|
|
56
56
|
showPopover(source: PopoverShowComponent, popover: Popover): Observable<void>;
|
|
57
57
|
showPopover(placement: PopoverShowPlacement, popover: Popover): Observable<void>;
|
|
58
|
-
showDatePicker(anchor: ComponentInstance | Componentable, ref:
|
|
59
|
-
showColorPicker(anchor: ComponentInstance | Componentable, ref:
|
|
60
|
-
showTimePicker(anchor: ComponentInstance | Componentable, ref:
|
|
61
|
-
showDateTimePicker(anchor: ComponentInstance | Componentable, ref:
|
|
58
|
+
showDatePicker(anchor: ComponentInstance | Componentable, ref: ContextRefOfValue<string | undefined>): Observable<void>;
|
|
59
|
+
showColorPicker(anchor: ComponentInstance | Componentable, ref: ContextRefOfValue<string | undefined>): Observable<void>;
|
|
60
|
+
showTimePicker(anchor: ComponentInstance | Componentable, ref: ContextRefOfValue<string | undefined>): Observable<void>;
|
|
61
|
+
showDateTimePicker(anchor: ComponentInstance | Componentable, ref: ContextRefOfValue<string | undefined>): Observable<void>;
|
|
62
62
|
private showNativePicker;
|
|
63
63
|
/**
|
|
64
64
|
* Задаёт платформенные WebMCP-тулзы. Новый список заменяет предыдущий.
|
package/package.json
CHANGED