domain-rules 0.0.0-stage → 0.0.1-beta.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/LICENSE +21 -0
- package/README.md +125 -2
- package/dist/index.d.mts +597 -0
- package/dist/index.mjs +573 -0
- package/package.json +39 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 9wick / Kohei Kido
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,126 @@
|
|
|
1
|
-
#
|
|
1
|
+
# domain-rules
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
データの作成・更新・削除やアクション実行前のビジネスルールを小さな単位で定義し、必要なデータだけを取得・検証して、「検証済みであること」を TypeScript の型で保証するライブラリです。
|
|
4
|
+
|
|
5
|
+
> **Status**: 試作段階です。main の最新は npm の `beta` タグで公開しています。より実践的な定義例は [test/blog/domain.ts](test/blog/domain.ts) にあり、型検査とテストで動作を確認しています。
|
|
6
|
+
|
|
7
|
+
## 何ができるか
|
|
8
|
+
|
|
9
|
+
- **ルールを小さな単位で宣言できる**: 「いつ適用するか (`when`)」と「何を検証するか (`check`)」を分けて定義し、モデルごとに 1 本の検証パイプライン (`ruleset`) として組み立てます。
|
|
10
|
+
- **検証結果を型に反映できる(型の昇格)**: 前段のルールで確認した値(採番済みの ID や存在確認済みの値など)を状態へマージして型を絞り込み、保存可能な型を満たしているかをコンパイル時に検証します。
|
|
11
|
+
- **外部依存を分離してテストしやすい**: DB 参照などの副作用は `port` として宣言し、起動時に `bind` で実装 (`provider`) を注入します。テストでは `provide.value` で固定値を渡すだけで、リポジトリのモックは不要です。
|
|
12
|
+
- **未検証データの保存を型で防ぐ**: すべてのルールを通過した値だけが `Persistable` などの検証済みラッパーとして返り、`open()` でのみ中身を取り出せます。
|
|
13
|
+
|
|
14
|
+
## 前提
|
|
15
|
+
|
|
16
|
+
- TypeScript
|
|
17
|
+
- [Standard Schema](https://github.com/standard-schema/spec) 準拠のスキーマライブラリ(例: Valibot)
|
|
18
|
+
- [`@praha/byethrow`](https://github.com/praha-inc/byethrow)(成功・失敗を `Result` / `ResultAsync` で表現)
|
|
19
|
+
|
|
20
|
+
## インストール
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pnpm add domain-rules@beta @praha/byethrow
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
ESM 専用パッケージです(`.d.mts` 型定義同梱)。
|
|
27
|
+
|
|
28
|
+
## クイックスタート
|
|
29
|
+
|
|
30
|
+
全体の流れは **1. 定義(モデル・ポート・ルール) → 2. 注入(`bind`) → 3. 実行と取り出し(`open`)** です。
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
import { Result } from "@praha/byethrow";
|
|
34
|
+
import * as v from "valibot";
|
|
35
|
+
import {
|
|
36
|
+
always,
|
|
37
|
+
bind,
|
|
38
|
+
changed,
|
|
39
|
+
clock,
|
|
40
|
+
domainDefinitionKit,
|
|
41
|
+
modelRules,
|
|
42
|
+
open,
|
|
43
|
+
port,
|
|
44
|
+
provide,
|
|
45
|
+
rule,
|
|
46
|
+
ruleset,
|
|
47
|
+
type Persisted,
|
|
48
|
+
} from "domain-rules";
|
|
49
|
+
|
|
50
|
+
// 1. モデル・ポート・ルールを定義する(ドメイン層)
|
|
51
|
+
// actor の型はここで1回だけ決める。rule の check はこの型の actor を受け取る
|
|
52
|
+
const { model } = domainDefinitionKit<{ actor: { readonly id: string } }>();
|
|
53
|
+
|
|
54
|
+
const articleInput = v.object({
|
|
55
|
+
id: v.optional(v.string()),
|
|
56
|
+
title: v.pipe(v.string(), v.minLength(1)),
|
|
57
|
+
status: v.optional(v.picklist(["DRAFT", "PUBLISHED"]), "DRAFT"),
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
const article = model({
|
|
61
|
+
name: "article",
|
|
62
|
+
schema: {
|
|
63
|
+
input: articleInput,
|
|
64
|
+
persisted: v.object({ ...articleInput.entries, id: v.string() }),
|
|
65
|
+
},
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
const findArticleById = port("findArticleById").of<(id: string) => Persisted<typeof article> | null, never>();
|
|
69
|
+
const newArticleId = port("newArticleId").of<() => string, never>();
|
|
70
|
+
|
|
71
|
+
const publishRequiresLongTitle = rule(article.onSave, {
|
|
72
|
+
name: "公開時はタイトルが5文字以上",
|
|
73
|
+
when: changed("status", { next: "PUBLISHED" }),
|
|
74
|
+
check: ({ next }) => (next.title.length >= 5 ? Result.succeed() : Result.fail("TITLE_TOO_SHORT")),
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
const assignArticleId = rule(article.onSave, {
|
|
78
|
+
name: "ID を確定する",
|
|
79
|
+
requires: { newArticleId },
|
|
80
|
+
when: always,
|
|
81
|
+
check: async ({ pre }, { newArticleId }) => {
|
|
82
|
+
if (pre !== null) return Result.succeed({ next: { id: pre.id } });
|
|
83
|
+
const id = await newArticleId();
|
|
84
|
+
return Result.isFailure(id) ? id : Result.succeed({ next: { id: id.value } });
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
const articleRules = modelRules(article)
|
|
89
|
+
.load(findArticleById)
|
|
90
|
+
.save(ruleset(publishRequiresLongTitle).add(assignArticleId));
|
|
91
|
+
|
|
92
|
+
// 2. provider を注入して呼び出し可能な API を組み立てる(起動時 / DI)
|
|
93
|
+
const domain = bind([articleRules], {
|
|
94
|
+
providers: [
|
|
95
|
+
provide(findArticleById, (id) => articleRepo.findById(id)),
|
|
96
|
+
provide(newArticleId, () => Result.succeed(crypto.randomUUID())),
|
|
97
|
+
provide(clock, () => Date.now()),
|
|
98
|
+
],
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
// 3. 実行し、検証済みの値を取り出して保存する(Usecase)
|
|
102
|
+
const result = await domain.article.create({
|
|
103
|
+
input: { title: "Hello domain-rules" },
|
|
104
|
+
actor: { id: "usr_1" },
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
if (Result.isSuccess(result)) {
|
|
108
|
+
const { next } = open(result.value); // next は Persisted<typeof article> 型
|
|
109
|
+
await articleRepo.save(next);
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
`modelRules` の定義に応じて、`domain.article` には `create` / `update` / `upsert` / `delete` が生成されます。永続化を伴わない操作は `action` / `actionRules`(`decide`)で定義できます。
|
|
114
|
+
|
|
115
|
+
## ドキュメント
|
|
116
|
+
|
|
117
|
+
目的に応じて `docs/` 配下のドキュメントを参照してください。
|
|
118
|
+
|
|
119
|
+
| 知りたいこと | ドキュメント | 主な内容 |
|
|
120
|
+
| -------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
121
|
+
| 使い方と実行時の動作仕様 | [利用ガイド (`docs/guide.md`)](docs/guide.md) | モデル・ルール・`when`・型の昇格・`action`・DI・テストの書き方に加え、実行順序・マージ仕様・失敗の型・`cached` の挙動・`open()`・`plan()` まで実装時に必要なリファレンス |
|
|
122
|
+
| 設計の意図・構成・スコープ | [設計思想とスコープ (`docs/design.md`)](docs/design.md) | 解決したい課題、ドメイン層・DI層・ユースケース層の責務分割、設計原則、スコープ外(TOCTOU や複数レコード更新など)、先行事例、未決定の論点 |
|
|
123
|
+
|
|
124
|
+
## License
|
|
125
|
+
|
|
126
|
+
MIT
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,597 @@
|
|
|
1
|
+
import { Result as Result$1 } from "@praha/byethrow";
|
|
2
|
+
import { OmittableIfEmpty } from "as-free";
|
|
3
|
+
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
4
|
+
type TrackKind = "save" | "delete" | "decide";
|
|
5
|
+
declare const trackState: unique symbol;
|
|
6
|
+
declare class Track<K extends TrackKind, T extends string, S> {
|
|
7
|
+
readonly [trackState]: S;
|
|
8
|
+
readonly kind: K;
|
|
9
|
+
readonly target: T;
|
|
10
|
+
constructor(kind: K, target: T);
|
|
11
|
+
assuming<R>(): Track<K, T, S & R>;
|
|
12
|
+
}
|
|
13
|
+
type Action<N extends string = string, In = unknown, Out = unknown, Act = unknown> = {
|
|
14
|
+
readonly kind: "action";
|
|
15
|
+
readonly name: N;
|
|
16
|
+
readonly input: StandardSchemaV1<In, Out>;
|
|
17
|
+
readonly onDecide: Track<"decide", N, DecideState<Out, Act>>;
|
|
18
|
+
};
|
|
19
|
+
type DecideState<I, Act> = {
|
|
20
|
+
readonly input: I;
|
|
21
|
+
readonly actor: Act;
|
|
22
|
+
readonly now: number;
|
|
23
|
+
};
|
|
24
|
+
type ActionActor<A extends Action> = A["onDecide"] extends Track<"decide", string, DecideState<unknown, infer X>> ? X : never;
|
|
25
|
+
type Entries<Out> = { readonly [K in keyof Out]-?: StandardSchemaV1<unknown, Out[K]>; };
|
|
26
|
+
type ObjectSchema<In = unknown, Out = unknown> = StandardSchemaV1<In, Out> & {
|
|
27
|
+
readonly entries: Entries<Out>;
|
|
28
|
+
};
|
|
29
|
+
type Model<N extends string = string, In = unknown, Out = unknown, P = unknown, Act = unknown> = {
|
|
30
|
+
readonly kind: "model";
|
|
31
|
+
readonly name: N;
|
|
32
|
+
readonly schema: {
|
|
33
|
+
readonly input: ObjectSchema<In, Out>;
|
|
34
|
+
readonly persisted: StandardSchemaV1<unknown, P>;
|
|
35
|
+
};
|
|
36
|
+
readonly onSave: Track<"save", N, SaveState<P | null, Out, Act>>;
|
|
37
|
+
readonly onDelete: Track<"delete", N, DeleteState<P, Act>>;
|
|
38
|
+
};
|
|
39
|
+
type SaveState<Pre, Next, Act> = {
|
|
40
|
+
readonly pre: Pre;
|
|
41
|
+
readonly next: Next;
|
|
42
|
+
readonly actor: Act;
|
|
43
|
+
readonly now: number;
|
|
44
|
+
};
|
|
45
|
+
type DeleteState<Pre, Act> = {
|
|
46
|
+
readonly pre: Pre;
|
|
47
|
+
readonly next: null;
|
|
48
|
+
readonly actor: Act;
|
|
49
|
+
readonly now: number;
|
|
50
|
+
};
|
|
51
|
+
type Value<M extends Model> = StandardSchemaV1.InferOutput<M["schema"]["input"]>;
|
|
52
|
+
type Persisted<M extends Model> = StandardSchemaV1.InferOutput<M["schema"]["persisted"]>;
|
|
53
|
+
type ModelActor<M extends Model> = M["onDelete"] extends Track<"delete", string, DeleteState<unknown, infer A>> ? A : never;
|
|
54
|
+
declare class Provider<N extends string = string> {
|
|
55
|
+
#private;
|
|
56
|
+
readonly name: N;
|
|
57
|
+
constructor(name: N, register: (scope: object) => void);
|
|
58
|
+
readonly registerIn: (scope: object) => void;
|
|
59
|
+
}
|
|
60
|
+
type Providable<N extends string, I> = {
|
|
61
|
+
readonly provider: (impl: I) => Provider<N>;
|
|
62
|
+
};
|
|
63
|
+
type Valuable<N extends string, V> = {
|
|
64
|
+
readonly valued: (v: V) => Provider<N>;
|
|
65
|
+
};
|
|
66
|
+
export declare const provide: (<N extends string, I>(target: Providable<N, I>, impl: NoInfer<I>) => Provider<N>) & {
|
|
67
|
+
value: <N extends string, V>(target: Valuable<N, V>, v: NoInfer<V>) => Provider<N>;
|
|
68
|
+
};
|
|
69
|
+
declare class Clock {
|
|
70
|
+
#private;
|
|
71
|
+
readonly kind = "clock";
|
|
72
|
+
readonly name = "clock";
|
|
73
|
+
constructor();
|
|
74
|
+
readonly provider: (now: () => number) => Provider<"clock">;
|
|
75
|
+
readonly valued: (v: number) => Provider<"clock">;
|
|
76
|
+
readonly providedIn: (scope: object) => boolean;
|
|
77
|
+
readonly nowIn: (scope: object) => number | undefined;
|
|
78
|
+
}
|
|
79
|
+
export declare const clock: Clock;
|
|
80
|
+
type Invocation = {
|
|
81
|
+
readonly scope: object;
|
|
82
|
+
readonly now: number;
|
|
83
|
+
};
|
|
84
|
+
declare const portTypes: unique symbol;
|
|
85
|
+
type ImplOf<A extends readonly unknown[], T, E> = (...args: A) => Result$1.Result<T, E> | Result$1.ResultAsync<T, E>;
|
|
86
|
+
declare class Slots<A extends readonly unknown[], T, E> {
|
|
87
|
+
readonly impls: WeakMap<object, ImplOf<A, T, E>>;
|
|
88
|
+
readonly memos: WeakMap<Invocation, Map<string, Promise<Result$1.Result<T, E>>>>;
|
|
89
|
+
}
|
|
90
|
+
declare class Port<N extends string, in out A extends readonly unknown[], in out T, in out E> {
|
|
91
|
+
#private;
|
|
92
|
+
readonly [portTypes]: {
|
|
93
|
+
readonly args: A;
|
|
94
|
+
readonly value: T;
|
|
95
|
+
readonly error: E;
|
|
96
|
+
};
|
|
97
|
+
readonly kind = "port";
|
|
98
|
+
readonly name: N;
|
|
99
|
+
readonly cached: boolean;
|
|
100
|
+
constructor(name: N, cached: boolean, slots: Slots<A, T, E>);
|
|
101
|
+
readonly provider: (impl: ImplOf<A, T, E>) => Provider<N>;
|
|
102
|
+
readonly valued: (v: T) => Provider<N>;
|
|
103
|
+
readonly providedIn: (scope: object) => boolean;
|
|
104
|
+
readonly withCache: () => Port<N, A, T, E>;
|
|
105
|
+
readonly callIn: (invocation: Invocation, args: A) => Promise<Result$1.Result<T, E>>;
|
|
106
|
+
readonly resolveIn: (invocation: Invocation) => (...args: A) => Promise<Result$1.Result<T, E>>;
|
|
107
|
+
readonly unwrapIn: (invocation: Invocation) => (...args: A) => AsyncGenerator<Result$1.Failure<E>, T>;
|
|
108
|
+
}
|
|
109
|
+
type AnyPort = {
|
|
110
|
+
readonly kind: "port";
|
|
111
|
+
readonly name: string;
|
|
112
|
+
readonly cached: boolean;
|
|
113
|
+
readonly providedIn: (scope: object) => boolean;
|
|
114
|
+
};
|
|
115
|
+
type TypesOf<P> = P extends {
|
|
116
|
+
readonly [portTypes]: infer X;
|
|
117
|
+
} ? X : never;
|
|
118
|
+
type PortArgs<P> = TypesOf<P> extends {
|
|
119
|
+
readonly args: infer A extends readonly unknown[];
|
|
120
|
+
} ? A : never;
|
|
121
|
+
type PortValue<P> = TypesOf<P> extends {
|
|
122
|
+
readonly value: infer T;
|
|
123
|
+
} ? T : never;
|
|
124
|
+
type PortError<P> = TypesOf<P> extends {
|
|
125
|
+
readonly error: infer E;
|
|
126
|
+
} ? E : never;
|
|
127
|
+
type Ports = Readonly<Record<string, AnyPort>>;
|
|
128
|
+
type NoPorts = Readonly<Record<never, AnyPort>>;
|
|
129
|
+
type PortNames<P extends Ports> = { [K in keyof P]: P[K]["name"]; }[keyof P];
|
|
130
|
+
export declare const port: <const N extends string>(name: N) => {
|
|
131
|
+
of: <F extends (...args: never) => unknown, E = never>() => Port<N, Parameters<F>, ReturnType<F>, E>;
|
|
132
|
+
};
|
|
133
|
+
export declare const cached: <N extends string, A extends readonly unknown[], T, E>(p: Port<N, A, T, E>) => Port<N, A, T, E>;
|
|
134
|
+
type Match = string | number | bigint | boolean | symbol | null;
|
|
135
|
+
type WhenDescription = {
|
|
136
|
+
readonly kind: "always";
|
|
137
|
+
} | {
|
|
138
|
+
readonly kind: "onCreate";
|
|
139
|
+
} | {
|
|
140
|
+
readonly kind: "changed";
|
|
141
|
+
readonly field: string;
|
|
142
|
+
readonly pre?: Match | undefined;
|
|
143
|
+
readonly next?: Match | undefined;
|
|
144
|
+
} | {
|
|
145
|
+
readonly kind: "next";
|
|
146
|
+
} | {
|
|
147
|
+
readonly kind: "pre";
|
|
148
|
+
} | {
|
|
149
|
+
readonly kind: "actor";
|
|
150
|
+
} | {
|
|
151
|
+
readonly kind: "and" | "or";
|
|
152
|
+
readonly conditions: readonly WhenDescription[];
|
|
153
|
+
} | {
|
|
154
|
+
readonly kind: "not";
|
|
155
|
+
readonly condition: WhenDescription;
|
|
156
|
+
} | {
|
|
157
|
+
readonly kind: "custom";
|
|
158
|
+
readonly description?: string;
|
|
159
|
+
};
|
|
160
|
+
declare const allowedTracks: unique symbol;
|
|
161
|
+
type When<K extends TrackKind, Need> = ((s: Need) => boolean) & {
|
|
162
|
+
readonly description: WhenDescription;
|
|
163
|
+
readonly [allowedTracks]?: (k: K) => void;
|
|
164
|
+
};
|
|
165
|
+
type WhenParam<K extends TrackKind, S> = ((s: S) => boolean) & {
|
|
166
|
+
readonly description?: WhenDescription;
|
|
167
|
+
readonly [allowedTracks]?: (k: K) => void;
|
|
168
|
+
};
|
|
169
|
+
type AnyWhen = ((s: never) => boolean) & {
|
|
170
|
+
readonly description?: WhenDescription;
|
|
171
|
+
readonly [allowedTracks]?: (k: never) => void;
|
|
172
|
+
};
|
|
173
|
+
type KindsOf<W> = W extends {
|
|
174
|
+
readonly [allowedTracks]?: (k: infer K) => void;
|
|
175
|
+
} ? unknown extends K ? TrackKind : K & TrackKind : TrackKind;
|
|
176
|
+
type NeedOf<W> = W extends ((s: infer N) => boolean) ? N : never;
|
|
177
|
+
type CombinedKinds<Ws, K = TrackKind> = Ws extends readonly [infer W, ...infer Rest] ? CombinedKinds<Rest, K & KindsOf<W>> : K & TrackKind;
|
|
178
|
+
type CombinedNeed<Ws, N = unknown> = Ws extends readonly [infer W, ...infer Rest] ? CombinedNeed<Rest, N & NeedOf<W>> : N;
|
|
179
|
+
type Check<X, V, E> = (s: X) => Promise<Result$1.Result<V, E>>;
|
|
180
|
+
type Always = When<TrackKind, unknown> & {
|
|
181
|
+
readonly description: {
|
|
182
|
+
readonly kind: "always";
|
|
183
|
+
};
|
|
184
|
+
readonly step: <X, V, E>(s: X, check: Check<X, V, E>) => Promise<Result$1.Result<X & V, E>>;
|
|
185
|
+
};
|
|
186
|
+
type IsAlways<W> = W extends {
|
|
187
|
+
readonly description: {
|
|
188
|
+
readonly kind: "always";
|
|
189
|
+
};
|
|
190
|
+
} ? true : false;
|
|
191
|
+
type Requires = Readonly<Record<string, AnyPort & {
|
|
192
|
+
readonly resolveIn: (invocation: Invocation) => unknown;
|
|
193
|
+
readonly unwrapIn: (invocation: Invocation) => unknown;
|
|
194
|
+
}>>;
|
|
195
|
+
type HasIndex<P> = string extends keyof P ? true : number extends keyof P ? true : symbol extends keyof P ? true : false;
|
|
196
|
+
type OptionalKeys<P> = { [K in keyof P]-?: {} extends Pick<P, K> ? K : never; }[keyof P];
|
|
197
|
+
type StrictRecord<P> = HasIndex<P> extends true ? {
|
|
198
|
+
readonly "index signature の record は渡せない": never;
|
|
199
|
+
} : [OptionalKeys<P>] extends [never] ? unknown : {
|
|
200
|
+
readonly "省略できる key は渡せない": OptionalKeys<P>;
|
|
201
|
+
};
|
|
202
|
+
declare const resolvePorts: <P extends Requires>(requires: P, invocation: Invocation) => { readonly [K in keyof P]: (P[K] extends (infer T) ? T extends P[K] ? T extends AnyPort & {
|
|
203
|
+
readonly resolveIn: (invocation: Invocation) => unknown;
|
|
204
|
+
readonly unwrapIn: (invocation: Invocation) => unknown;
|
|
205
|
+
} ? "resolveIn" extends (infer T_1) ? T_1 extends "resolveIn" ? T_1 extends keyof T ? T[T_1] extends (infer T_2) ? T_2 extends T[T_1] ? T_2 extends ((invocation: Invocation) => unknown) ? (T_2 extends (infer T_3) ? T_3 extends T_2 ? T_3 extends ((...args: infer Args) => infer Result) ? [(...args: Args) => Result] extends [T_3] ? true : false : false : never : never) extends true ? T_2 extends ((...args: never) => infer Result) ? Result : never : unknown : never : never : never : unknown : never : never : never : never : never) extends (infer T_4) ? T_4 extends (P[K] extends (infer T) ? T extends P[K] ? T extends AnyPort & {
|
|
206
|
+
readonly resolveIn: (invocation: Invocation) => unknown;
|
|
207
|
+
readonly unwrapIn: (invocation: Invocation) => unknown;
|
|
208
|
+
} ? "resolveIn" extends (infer T_1) ? T_1 extends "resolveIn" ? T_1 extends keyof T ? T[T_1] extends (infer T_2) ? T_2 extends T[T_1] ? T_2 extends ((invocation: Invocation) => unknown) ? (T_2 extends (infer T_3) ? T_3 extends T_2 ? T_3 extends ((...args: infer Args) => infer Result) ? [(...args: Args) => Result] extends [T_3] ? true : false : false : never : never) extends true ? T_2 extends ((...args: never) => infer Result) ? Result : never : unknown : never : never : never : unknown : never : never : never : never : never) ? T_4 extends unknown ? T_4 : never : never : never; };
|
|
209
|
+
type PortFns<P extends Requires> = ReturnType<typeof resolvePorts<P>>;
|
|
210
|
+
declare const unwrapPorts: <P extends Requires>(requires: P, invocation: Invocation) => { readonly [K in keyof P]: (P[K] extends (infer T) ? T extends P[K] ? T extends AnyPort & {
|
|
211
|
+
readonly resolveIn: (invocation: Invocation) => unknown;
|
|
212
|
+
readonly unwrapIn: (invocation: Invocation) => unknown;
|
|
213
|
+
} ? "unwrapIn" extends (infer T_1) ? T_1 extends "unwrapIn" ? T_1 extends keyof T ? T[T_1] extends (infer T_2) ? T_2 extends T[T_1] ? T_2 extends ((invocation: Invocation) => unknown) ? (T_2 extends (infer T_3) ? T_3 extends T_2 ? T_3 extends ((...args: infer Args) => infer Result) ? [(...args: Args) => Result] extends [T_3] ? true : false : false : never : never) extends true ? T_2 extends ((...args: never) => infer Result) ? Result : never : unknown : never : never : never : unknown : never : never : never : never : never) extends (infer T_4) ? T_4 extends (P[K] extends (infer T) ? T extends P[K] ? T extends AnyPort & {
|
|
214
|
+
readonly resolveIn: (invocation: Invocation) => unknown;
|
|
215
|
+
readonly unwrapIn: (invocation: Invocation) => unknown;
|
|
216
|
+
} ? "unwrapIn" extends (infer T_1) ? T_1 extends "unwrapIn" ? T_1 extends keyof T ? T[T_1] extends (infer T_2) ? T_2 extends T[T_1] ? T_2 extends ((invocation: Invocation) => unknown) ? (T_2 extends (infer T_3) ? T_3 extends T_2 ? T_3 extends ((...args: infer Args) => infer Result) ? [(...args: Args) => Result] extends [T_3] ? true : false : false : never : never) extends true ? T_2 extends ((...args: never) => infer Result) ? Result : never : unknown : never : never : never : unknown : never : never : never : never : never) ? T_4 extends unknown ? T_4 : never : never : never; };
|
|
217
|
+
type UnwrappedPortFns<P extends Requires> = ReturnType<typeof unwrapPorts<P>>;
|
|
218
|
+
type SafeTry<U> = <Y extends Result$1.Failure<unknown>, R extends Result$1.Result<unknown, unknown>>(body: (unwrapped: U) => AsyncIterator<Y, R>) => Promise<Y | R>;
|
|
219
|
+
type ConditionalStep<Need> = <X extends Need, V, E>(s: X, check: Check<X, V, E>) => Promise<Result$1.Result<X | (X & V), E>>;
|
|
220
|
+
export declare const always: Always;
|
|
221
|
+
type Checked<V, E> = Result$1.Result<V, E> | Promise<Result$1.Result<V, E>>;
|
|
222
|
+
type CheckResult = Checked<unknown, unknown>;
|
|
223
|
+
type SuccessOf<R> = Awaited<R> extends (infer X) ? (X extends Result$1.Success<infer V> ? V : never) : never;
|
|
224
|
+
type FailureOf<R> = Awaited<R> extends (infer X) ? (X extends Result$1.Failure<infer E> ? E : never) : never;
|
|
225
|
+
type CheckTools<P extends Requires> = {
|
|
226
|
+
readonly safeTry: SafeTry<UnwrappedPortFns<P>>;
|
|
227
|
+
};
|
|
228
|
+
declare const rulePorts: unique symbol;
|
|
229
|
+
type Rule<K extends TrackKind, T extends string, N extends string, S, W extends WhenParam<K, S>, V, E, P> = {
|
|
230
|
+
readonly kind: "rule";
|
|
231
|
+
readonly track?: {
|
|
232
|
+
readonly kind: K;
|
|
233
|
+
readonly target: T;
|
|
234
|
+
};
|
|
235
|
+
readonly [rulePorts]?: P;
|
|
236
|
+
readonly name: N;
|
|
237
|
+
readonly ports: readonly AnyPort[];
|
|
238
|
+
readonly when: W & {
|
|
239
|
+
readonly step: ConditionalStep<S>;
|
|
240
|
+
};
|
|
241
|
+
readonly run: (s: S, invocation: Invocation) => Promise<Result$1.Result<V, E>>;
|
|
242
|
+
};
|
|
243
|
+
export declare function rule<K extends TrackKind, T extends string, S, const N extends string, W extends WhenParam<K, S>, R extends CheckResult, P extends Requires = NoPorts, V = SuccessOf<R>, E = FailureOf<R>>(track: Track<K, T, S>, def: {
|
|
244
|
+
readonly name: N;
|
|
245
|
+
readonly requires?: P & StrictRecord<P>;
|
|
246
|
+
readonly when: W;
|
|
247
|
+
readonly check: (s: S, ports: PortFns<P>, tools: CheckTools<P>) => R & NoInfer<Checked<V, E>>;
|
|
248
|
+
} & OmittableIfEmpty<"requires", P & StrictRecord<P>>): Rule<K, T, N, S, W, V, E, NoInfer<P>>;
|
|
249
|
+
export declare const immutable: <T extends string, S extends {
|
|
250
|
+
readonly pre: object | null;
|
|
251
|
+
readonly next: object;
|
|
252
|
+
}>(track: Track<"save", T, S>, fields: readonly (keyof S["next"] & string)[]) => Rule<"save", T, `作成後に変えられない項目: ${string}`, S, When<"save", S>, void, {
|
|
253
|
+
readonly code: "IMMUTABLE_FIELD_CHANGED";
|
|
254
|
+
readonly field: keyof S["next"] & string;
|
|
255
|
+
}, NoInfer<Readonly<Record<never, AnyPort>>>>;
|
|
256
|
+
export declare const alwaysAllow: Rule<TrackKind, string, "常に許可", unknown, Always, void, never, NoPorts>;
|
|
257
|
+
type Lift<V> = [V] extends [object] ? V : unknown;
|
|
258
|
+
type Delta<V, W> = IsAlways<W> extends true ? Lift<V> : {} | Lift<V>;
|
|
259
|
+
type NextOf<S> = S extends {
|
|
260
|
+
readonly next: infer X;
|
|
261
|
+
} ? X : never;
|
|
262
|
+
type Narrowing<S, O> = { readonly [K in keyof O]: K extends "next" ? { readonly [F in keyof O[K]]: F extends keyof NextOf<S> ? NextOf<S>[F] : unknown; } : K extends keyof S ? S[K] : unknown; };
|
|
263
|
+
type NarrowGuard<S, O> = [O] extends [object] ? O extends Narrowing<S, O> ? unknown : {
|
|
264
|
+
readonly 状態の項目を別の型に置き換えている: O;
|
|
265
|
+
} : unknown;
|
|
266
|
+
type StepFailure<N, E> = {
|
|
267
|
+
readonly step: N;
|
|
268
|
+
readonly error: E;
|
|
269
|
+
};
|
|
270
|
+
type PlannedRule = {
|
|
271
|
+
readonly name: string;
|
|
272
|
+
readonly when: WhenDescription;
|
|
273
|
+
readonly ports: readonly string[];
|
|
274
|
+
};
|
|
275
|
+
declare const portNames: unique symbol;
|
|
276
|
+
declare const rulesetTypes: unique symbol;
|
|
277
|
+
declare const startState: unique symbol;
|
|
278
|
+
type Stepper<Cur, V, E, D> = <X extends Cur>(s: X, check: Check<X, V, E>) => Promise<Result$1.Result<X & D, E>>;
|
|
279
|
+
type RunState<In, D, E> = <X extends In>(s: X, invocation: Invocation) => Promise<Result$1.Result<X & D, E>>;
|
|
280
|
+
declare class Ruleset<K extends TrackKind, T extends string, In extends {}, D, E, PN extends string> {
|
|
281
|
+
readonly [portNames]: PN;
|
|
282
|
+
readonly [rulesetTypes]: {
|
|
283
|
+
readonly delta: D;
|
|
284
|
+
readonly error: E;
|
|
285
|
+
};
|
|
286
|
+
readonly [startState]: (s: In) => void;
|
|
287
|
+
readonly kind = "ruleset";
|
|
288
|
+
readonly plan: readonly PlannedRule[];
|
|
289
|
+
readonly ports: readonly AnyPort[];
|
|
290
|
+
readonly run: RunState<In, D, E>;
|
|
291
|
+
constructor(plan: readonly PlannedRule[], ports: readonly AnyPort[], run: RunState<In, D, E>);
|
|
292
|
+
add<N extends string, W extends WhenParam<K, In & D>, V, E2, P extends Ports>(r: Rule<K, T, N, In & D, W, V, E2, P> & NarrowGuard<In & D, V> & {
|
|
293
|
+
readonly when: {
|
|
294
|
+
readonly step: Stepper<In & D, V, StepFailure<N, E2>, Delta<V, W>>;
|
|
295
|
+
};
|
|
296
|
+
}): Ruleset<K, T, In, D & Delta<V, W>, E | StepFailure<N, E2>, PN | PortNames<P>>;
|
|
297
|
+
}
|
|
298
|
+
declare const start: <K extends TrackKind, T extends string, S, N extends string, W extends WhenParam<K, S & {}>, V, E2, P extends Ports>(first: Rule<K, T, N, S & {}, W, V, E2, P> & NarrowGuard<S & {}, V> & {
|
|
299
|
+
readonly when: {
|
|
300
|
+
readonly step: Stepper<S & {}, V, StepFailure<N, E2>, Delta<V, W>>;
|
|
301
|
+
};
|
|
302
|
+
}) => Ruleset<K, T, S & {}, Delta<V, W>, StepFailure<N, E2>, PortNames<P>>;
|
|
303
|
+
export declare const ruleset: typeof start;
|
|
304
|
+
type RunnableRuleset<In extends {}, D, E, PN extends string> = {
|
|
305
|
+
readonly [portNames]: PN;
|
|
306
|
+
readonly [startState]: (s: In) => void;
|
|
307
|
+
readonly [rulesetTypes]: {
|
|
308
|
+
readonly delta: D;
|
|
309
|
+
readonly error: E;
|
|
310
|
+
};
|
|
311
|
+
readonly plan: readonly PlannedRule[];
|
|
312
|
+
readonly ports: readonly AnyPort[];
|
|
313
|
+
readonly run: RunState<In, D, E>;
|
|
314
|
+
};
|
|
315
|
+
type RulesetOut<R> = R extends {
|
|
316
|
+
readonly [rulesetTypes]: {
|
|
317
|
+
readonly delta: infer D;
|
|
318
|
+
};
|
|
319
|
+
} ? D : never;
|
|
320
|
+
type RulesetError<R> = R extends {
|
|
321
|
+
readonly [rulesetTypes]: {
|
|
322
|
+
readonly error: infer E;
|
|
323
|
+
};
|
|
324
|
+
} ? E : never;
|
|
325
|
+
type RulesetPorts<R> = R extends {
|
|
326
|
+
readonly [portNames]: infer PN;
|
|
327
|
+
} ? PN : never;
|
|
328
|
+
type Decider<In, Out, E, PN extends string> = {
|
|
329
|
+
readonly [portNames]: PN;
|
|
330
|
+
readonly plan: readonly PlannedRule[];
|
|
331
|
+
readonly ports: readonly AnyPort[];
|
|
332
|
+
readonly run: (s: In, invocation: Invocation) => Promise<Result$1.Result<Out, E>>;
|
|
333
|
+
};
|
|
334
|
+
export declare const onCreate: When<"save", {
|
|
335
|
+
readonly pre: unknown;
|
|
336
|
+
}>;
|
|
337
|
+
type Fields<F extends string> = { readonly [P in F]: unknown; };
|
|
338
|
+
type Changed<F extends string> = {
|
|
339
|
+
readonly pre: Fields<F> | null;
|
|
340
|
+
readonly next: Fields<F>;
|
|
341
|
+
};
|
|
342
|
+
export declare const changed: <const F extends string>(field: F, values?: {
|
|
343
|
+
readonly pre?: Match | undefined;
|
|
344
|
+
readonly next?: Match | undefined;
|
|
345
|
+
}) => When<"save", Changed<F>>;
|
|
346
|
+
export declare const next: <V>(predicate: (v: V) => boolean) => When<"save", {
|
|
347
|
+
readonly next: V;
|
|
348
|
+
}>;
|
|
349
|
+
export declare const pre: <V>(predicate: (v: V) => boolean) => When<"save" | "delete", {
|
|
350
|
+
readonly pre: V | null;
|
|
351
|
+
}>;
|
|
352
|
+
type Combinable<Ws> = Ws & readonly ((s: CombinedNeed<Ws>) => boolean)[];
|
|
353
|
+
export declare const and: <const Ws extends readonly AnyWhen[]>(...ws: Combinable<Ws>) => When<CombinedKinds<Ws>, CombinedNeed<Ws>>;
|
|
354
|
+
export declare const or: <const Ws extends readonly AnyWhen[]>(...ws: Combinable<Ws>) => When<CombinedKinds<Ws>, CombinedNeed<Ws>>;
|
|
355
|
+
export declare const not: <K extends TrackKind, N>(w: When<K, N>) => When<K, N>;
|
|
356
|
+
export declare const describe: <S>(description: string, f: (s: S) => boolean) => When<TrackKind, S>;
|
|
357
|
+
declare const sealedAs: unique symbol;
|
|
358
|
+
declare class Sealed<Kind extends string, Target extends string, Op extends string, C> {
|
|
359
|
+
#private;
|
|
360
|
+
readonly [sealedAs]: {
|
|
361
|
+
readonly kind: Kind;
|
|
362
|
+
readonly target: Target;
|
|
363
|
+
readonly op: Op;
|
|
364
|
+
};
|
|
365
|
+
constructor(contents: C);
|
|
366
|
+
static contents<C>(s: Sealed<string, string, string, C>): C;
|
|
367
|
+
}
|
|
368
|
+
type Persistable<M extends Model, Op extends "create" | "update" = "create" | "update", Pre = Persisted<M>, A = ModelActor<M>> = Sealed<"persistable", M["name"], Op, ("create" extends Op ? {
|
|
369
|
+
readonly pre: null;
|
|
370
|
+
readonly next: Readonly<Persisted<M>>;
|
|
371
|
+
readonly actor: A;
|
|
372
|
+
} : never) | ("update" extends Op ? {
|
|
373
|
+
readonly pre: Readonly<Pre>;
|
|
374
|
+
readonly next: Readonly<Persisted<M>>;
|
|
375
|
+
readonly actor: A;
|
|
376
|
+
} : never)>;
|
|
377
|
+
type Deletable<M extends Model, Pre = Persisted<M>, A = ModelActor<M>> = Sealed<"deletable", M["name"], "delete", {
|
|
378
|
+
readonly pre: Readonly<Pre>;
|
|
379
|
+
readonly actor: A;
|
|
380
|
+
}>;
|
|
381
|
+
type Decision<Ac extends Action, T = void, A = ActionActor<Ac>> = Sealed<"decision", Ac["name"], "decide", {
|
|
382
|
+
readonly value: T;
|
|
383
|
+
readonly actor: A;
|
|
384
|
+
}>;
|
|
385
|
+
export declare const open: <C>(s: Sealed<string, string, string, C>) => C;
|
|
386
|
+
type InputFailure = {
|
|
387
|
+
readonly step: "input";
|
|
388
|
+
readonly error: {
|
|
389
|
+
readonly issues: readonly StandardSchemaV1.Issue[];
|
|
390
|
+
};
|
|
391
|
+
};
|
|
392
|
+
type BindCtx = {
|
|
393
|
+
readonly invocation: () => Invocation;
|
|
394
|
+
};
|
|
395
|
+
type Args$1<I, Act> = {
|
|
396
|
+
readonly input: I;
|
|
397
|
+
readonly actor: Act;
|
|
398
|
+
};
|
|
399
|
+
type DecideMethod<N extends string, In, Out, Act, T, A, E> = (args: Args$1<In, Act>) => Result$1.ResultAsync<Decision<Action<N, In, Out, Act>, T, A>, InputFailure | E>;
|
|
400
|
+
type AnyDecider = Decider<never, unknown, unknown, string>;
|
|
401
|
+
type ActionRules<A extends Action = Action, Rs extends AnyDecider = AnyDecider, Ms = unknown> = {
|
|
402
|
+
readonly kind: "actionRules";
|
|
403
|
+
readonly name: A["name"];
|
|
404
|
+
readonly action: A;
|
|
405
|
+
readonly rules: Rs;
|
|
406
|
+
readonly resolveIn: (ctx: BindCtx) => Ms;
|
|
407
|
+
};
|
|
408
|
+
type Decided<End extends {
|
|
409
|
+
readonly actor: unknown;
|
|
410
|
+
}, T> = {
|
|
411
|
+
readonly value: T;
|
|
412
|
+
readonly actor: End["actor"];
|
|
413
|
+
};
|
|
414
|
+
export declare function actionRules<N extends string, In, Out, Act, D, E, PN extends string, T>(a: Action<N, In, Out, Act>, def: {
|
|
415
|
+
readonly rules: RunnableRuleset<DecideState<Out, Act>, D, E, PN>;
|
|
416
|
+
readonly output: (s: DecideState<Out, Act> & D) => T;
|
|
417
|
+
}): ActionRules<Action<N, In, Out, Act>, Decider<DecideState<Out, Act>, Decided<DecideState<Out, Act> & D, T>, E, PN>, {
|
|
418
|
+
readonly decide: DecideMethod<N, In, Out, Act, T, (DecideState<Out, Act> & D)["actor"], E>;
|
|
419
|
+
}>;
|
|
420
|
+
type LoadFailureOf<LE> = {
|
|
421
|
+
readonly step: "load";
|
|
422
|
+
readonly error: "NOT_FOUND" | LE;
|
|
423
|
+
};
|
|
424
|
+
type SaveRun<Pre, Out, P, Act, A, E> = {
|
|
425
|
+
readonly run: (s: SaveState<Pre | null, Out, Act>, invocation: Invocation) => Promise<Result$1.Result<{
|
|
426
|
+
readonly next: P;
|
|
427
|
+
readonly actor: A;
|
|
428
|
+
}, E>>;
|
|
429
|
+
};
|
|
430
|
+
type DeleteRun<Pre, Act, A, E> = {
|
|
431
|
+
readonly run: (s: DeleteState<Pre, Act>, invocation: Invocation) => Promise<Result$1.Result<{
|
|
432
|
+
readonly actor: A;
|
|
433
|
+
}, E>>;
|
|
434
|
+
};
|
|
435
|
+
type IdOf<In> = NonNullable<Partial<In>["id" & keyof Partial<In>]>;
|
|
436
|
+
type CreateMethod<N extends string, In, Out, P, Act, A, E> = (args: Args$1<Omit<Partial<In>, "id">, Act>) => Result$1.ResultAsync<Persistable<Model<N, In, Out, P, Act>, "create", P, A>, InputFailure | E>;
|
|
437
|
+
type UpdateMethod<N extends string, In, Out, P, Act, Pre, A, E, LE> = (args: Args$1<Partial<In> & {
|
|
438
|
+
readonly id: IdOf<In>;
|
|
439
|
+
}, Act>) => Result$1.ResultAsync<Persistable<Model<N, In, Out, P, Act>, "update", Pre, A>, InputFailure | LoadFailureOf<LE> | E>;
|
|
440
|
+
type UpsertMethod<N extends string, In, Out, P, Act, Pre, A, E, LE> = (args: Args$1<Partial<In>, Act>) => Result$1.ResultAsync<Persistable<Model<N, In, Out, P, Act>, "create" | "update", Pre, A>, InputFailure | LoadFailureOf<LE> | E>;
|
|
441
|
+
type DeleteMethod<N extends string, In, Out, P, Act, Pre, A, E, LE> = (args: Args$1<{
|
|
442
|
+
readonly id: IdOf<In>;
|
|
443
|
+
}, Act>) => Result$1.ResultAsync<Deletable<Model<N, In, Out, P, Act>, Pre, A>, InputFailure | LoadFailureOf<LE> | E>;
|
|
444
|
+
type ActorOf<S> = S extends {
|
|
445
|
+
readonly actor: infer A;
|
|
446
|
+
} ? A : never;
|
|
447
|
+
type LoadFailure<L> = LoadFailureOf<PortError<L>>;
|
|
448
|
+
type LoadId<M extends Model> = "id" extends keyof Value<M> ? Exclude<Value<M>["id"], undefined> : never;
|
|
449
|
+
type LoadIdMismatch<M extends Model, L> = [LoadId<M>] extends [never] ? {
|
|
450
|
+
readonly "load には入力スキーマの id が要る": true;
|
|
451
|
+
} : [LoadId<M>] extends [PortArgs<L>[0]] ? unknown : {
|
|
452
|
+
readonly "load が検証済みの id を受け取れない": LoadId<M>;
|
|
453
|
+
};
|
|
454
|
+
type LoadMismatch<M extends Model, L> = [L] extends [never] ? unknown : [PortValue<L>] extends [(Value<M> & Persisted<M>) | null] ? LoadIdMismatch<M, L> : {
|
|
455
|
+
readonly "load の返り値が入力と永続化の型に代入できない": PortValue<L>;
|
|
456
|
+
};
|
|
457
|
+
type PersistedGuard<M extends Model, End> = [End] extends [never] ? unknown : [End] extends [{
|
|
458
|
+
readonly next: Persisted<M>;
|
|
459
|
+
}] ? unknown : {
|
|
460
|
+
readonly "最後の next が永続化の型にならない": End extends {
|
|
461
|
+
readonly next: infer X;
|
|
462
|
+
} ? X : never;
|
|
463
|
+
};
|
|
464
|
+
declare const setPorts: unique symbol;
|
|
465
|
+
type ModelRulesPorts<S> = S extends {
|
|
466
|
+
readonly [setPorts]: infer PN;
|
|
467
|
+
} ? PN : never;
|
|
468
|
+
type Methods<Ms> = (ctx: BindCtx) => Ms;
|
|
469
|
+
type Plans = {
|
|
470
|
+
readonly save?: readonly PlannedRule[];
|
|
471
|
+
readonly delete?: readonly PlannedRule[];
|
|
472
|
+
};
|
|
473
|
+
type ModelRules<N extends string = string, Ms = unknown, PN extends string = string> = {
|
|
474
|
+
readonly [setPorts]: PN;
|
|
475
|
+
readonly kind: "modelRules";
|
|
476
|
+
readonly name: N;
|
|
477
|
+
readonly plans: Plans;
|
|
478
|
+
readonly ports: readonly AnyPort[];
|
|
479
|
+
readonly resolveIn: Methods<Ms>;
|
|
480
|
+
};
|
|
481
|
+
type CreateStart<Out, Act> = SaveState<null, Out, Act>;
|
|
482
|
+
declare class ModelRulesDone<N extends string, Ms, PN extends string> implements ModelRules<N, Ms, PN> {
|
|
483
|
+
readonly [setPorts]: PN;
|
|
484
|
+
readonly kind = "modelRules";
|
|
485
|
+
readonly name: N;
|
|
486
|
+
readonly plans: Plans;
|
|
487
|
+
readonly ports: readonly AnyPort[];
|
|
488
|
+
readonly resolveIn: Methods<Ms>;
|
|
489
|
+
constructor(name: N, plans: Plans, ports: readonly AnyPort[], resolveIn: Methods<Ms>);
|
|
490
|
+
}
|
|
491
|
+
declare class ModelRulesStart<N extends string, In, Out, P, Act> implements ModelRules<N, {}, never> {
|
|
492
|
+
readonly [setPorts]: never;
|
|
493
|
+
readonly kind = "modelRules";
|
|
494
|
+
readonly name: N;
|
|
495
|
+
readonly model: Model<N, In, Out, P, Act>;
|
|
496
|
+
readonly plans: Plans;
|
|
497
|
+
readonly ports: readonly AnyPort[];
|
|
498
|
+
readonly resolveIn: Methods<{}>;
|
|
499
|
+
constructor(model: Model<N, In, Out, P, Act>);
|
|
500
|
+
load<LA, LT extends (O & P) | null, LE, L extends Port<string, [LA], LT, LE>, O extends {
|
|
501
|
+
readonly id?: LA | undefined;
|
|
502
|
+
}>(this: ModelRulesStart<N, In, O, P, Act>, port: L & Port<string, [LA], LT, LE> & LoadMismatch<Model<N, In, O, P, Act>, L>): ModelRulesLoaded<N, In, O, P, Act, LA, LT, LE, L["name"], {}>;
|
|
503
|
+
save<Save extends RunnableRuleset<CreateStart<NoInfer<Out>, NoInfer<Act>>, unknown, unknown, string>, SA = ActorOf<CreateStart<Out, Act> & RulesetOut<Save>>, SE = RulesetError<Save>>(rules: Save & PersistedGuard<Model<N, In, Out, P, Act>, CreateStart<Out, Act> & RulesetOut<NoInfer<Save>>> & SaveRun<never, NoInfer<Out>, NoInfer<P>, NoInfer<Act>, NoInfer<SA>, NoInfer<SE>>): ModelRulesDone<N, {
|
|
504
|
+
readonly create: CreateMethod<N, In, Out, P, Act, SA, SE>;
|
|
505
|
+
}, RulesetPorts<Save>>;
|
|
506
|
+
}
|
|
507
|
+
declare class ModelRulesLoaded<N extends string, In, Out extends {
|
|
508
|
+
readonly id?: LA | undefined;
|
|
509
|
+
}, P, Act, LA, LT extends Out | null, LE, PN extends string, Ms> implements ModelRules<N, Ms, PN> {
|
|
510
|
+
readonly [setPorts]: PN;
|
|
511
|
+
readonly kind = "modelRules";
|
|
512
|
+
readonly name: N;
|
|
513
|
+
readonly model: Model<N, In, Out, P, Act>;
|
|
514
|
+
readonly port: Port<string, [LA], LT, LE>;
|
|
515
|
+
readonly plans: Plans;
|
|
516
|
+
readonly ports: readonly AnyPort[];
|
|
517
|
+
readonly resolveIn: Methods<Ms>;
|
|
518
|
+
constructor(model: Model<N, In, Out, P, Act>, port: Port<string, [LA], LT, LE>, plans: Plans, ports: readonly AnyPort[], resolveIn: Methods<Ms>);
|
|
519
|
+
save<Save extends RunnableRuleset<SaveState<NoInfer<LT & {}> | null, NoInfer<Out>, NoInfer<Act>>, unknown, unknown, string>, SA = ActorOf<SaveState<(LT & {}) | null, Out, Act> & RulesetOut<Save>>, SE = RulesetError<Save>>(this: ModelRulesLoaded<N, In, Out, P, Act, LA, LT, LE, PN, Ms & {
|
|
520
|
+
readonly create?: never;
|
|
521
|
+
}>, rules: Save & PersistedGuard<Model<N, In, Out, P, Act>, SaveState<(LT & {}) | null, Out, Act> & RulesetOut<NoInfer<Save>>> & SaveRun<NoInfer<LT & {}>, NoInfer<Out>, NoInfer<P>, NoInfer<Act>, NoInfer<SA>, NoInfer<SE>>): ModelRulesLoaded<N, In, Out, P, Act, LA, LT, LE, PN | RulesetPorts<Save>, Readonly<Ms & {
|
|
522
|
+
create: CreateMethod<N, In, Out, P, Act, SA, SE>;
|
|
523
|
+
update: UpdateMethod<N, In, Out, P, Act, LT & {}, SA, SE, LE>;
|
|
524
|
+
upsert: UpsertMethod<N, In, Out, P, Act, LT & {}, SA, SE, LE>;
|
|
525
|
+
}>>;
|
|
526
|
+
delete<Del extends RunnableRuleset<DeleteState<NoInfer<LT & {}>, NoInfer<Act>>, unknown, unknown, string>, DA = ActorOf<DeleteState<LT & {}, Act> & RulesetOut<Del>>, DE = RulesetError<Del>>(this: ModelRulesLoaded<N, In, Out, P, Act, LA, LT, LE, PN, Ms & {
|
|
527
|
+
readonly delete?: never;
|
|
528
|
+
}>, rules: Del & DeleteRun<NoInfer<LT & {}>, NoInfer<Act>, NoInfer<DA>, NoInfer<DE>>): ModelRulesLoaded<N, In, Out, P, Act, LA, LT, LE, PN | RulesetPorts<Del>, Readonly<Ms & {
|
|
529
|
+
delete: DeleteMethod<N, In, Out, P, Act, LT & {}, DA, DE, LE>;
|
|
530
|
+
}>>;
|
|
531
|
+
}
|
|
532
|
+
export declare const modelRules: <N extends string, In, Out, P, Act>(m: Model<N, In, Out, P, Act>) => ModelRulesStart<N, In, Out, P, Act>;
|
|
533
|
+
type RuleSet = ModelRules | ActionRules;
|
|
534
|
+
type RuleSetPorts<S> = S extends {
|
|
535
|
+
readonly kind: "modelRules";
|
|
536
|
+
} ? ModelRulesPorts<S> : S extends {
|
|
537
|
+
readonly kind: "actionRules";
|
|
538
|
+
readonly rules: infer Rs;
|
|
539
|
+
} ? RulesetPorts<Rs> : never;
|
|
540
|
+
export declare function plan(set: ModelRules): Plans;
|
|
541
|
+
export declare function plan(set: ActionRules): {
|
|
542
|
+
readonly rules: readonly PlannedRule[];
|
|
543
|
+
};
|
|
544
|
+
type IsUnion<T, U = T> = T extends unknown ? ([U] extends [T] ? false : true) : never;
|
|
545
|
+
type DuplicateName<T extends readonly {
|
|
546
|
+
readonly name: string;
|
|
547
|
+
}[], Seen = never> = T extends readonly [infer H extends {
|
|
548
|
+
readonly name: string;
|
|
549
|
+
}, ...infer R extends readonly {
|
|
550
|
+
readonly name: string;
|
|
551
|
+
}[]] ? H["name"] extends Seen ? H["name"] : DuplicateName<R, Seen | H["name"]> : never;
|
|
552
|
+
type NonLiteralName<T extends readonly {
|
|
553
|
+
readonly name: string;
|
|
554
|
+
}[]> = { [I in keyof T]: string extends T[I]["name"] ? T[I] : true extends IsUnion<T[I]["name"]> ? T[I] : never; }[number];
|
|
555
|
+
type UniqueNames<T extends readonly {
|
|
556
|
+
readonly name: string;
|
|
557
|
+
}[]> = number extends T["length"] ? {
|
|
558
|
+
readonly "長さの決まった tuple を渡す": never;
|
|
559
|
+
} : [NonLiteralName<T>] extends [never] ? [DuplicateName<T>] extends [never] ? unknown : {
|
|
560
|
+
readonly "name が重複している": DuplicateName<T>;
|
|
561
|
+
} : {
|
|
562
|
+
readonly "name は1つの文字列リテラルにする": NonLiteralName<T>;
|
|
563
|
+
};
|
|
564
|
+
type RequiredPorts<Sets extends readonly RuleSet[]> = RuleSetPorts<Sets[number]> | "clock";
|
|
565
|
+
type MissingProviders<Sets extends readonly RuleSet[], Ps extends readonly Provider[]> = Exclude<RequiredPorts<Sets>, Ps[number]["name"]>;
|
|
566
|
+
type Domain<Sets extends readonly RuleSet[]> = ReturnType<typeof bind<Sets, readonly Provider[]>>;
|
|
567
|
+
export declare function bind<const Sets extends readonly RuleSet[], const Ps extends readonly Provider[]>(sets: Sets & UniqueNames<Sets>, options: {
|
|
568
|
+
readonly providers: Ps;
|
|
569
|
+
} & ([MissingProviders<Sets, Ps>] extends [never] ? unknown : {
|
|
570
|
+
readonly "provider が足りない port": MissingProviders<Sets, Ps>;
|
|
571
|
+
})): import("as-free").FromEntries<{ readonly [K in keyof Sets]: readonly [((Sets[K] extends (infer T) ? T extends Sets[K] ? T extends ActionRules ? "name" extends (infer T_1) ? T_1 extends "name" ? T_1 extends keyof T ? T[T_1] : string : never : never : never : never : never) extends (infer T_2) ? T_2 extends (Sets[K] extends (infer T) ? T extends Sets[K] ? T extends ActionRules ? "name" extends (infer T_1) ? T_1 extends "name" ? T_1 extends keyof T ? T[T_1] : string : never : never : never : never : never) ? T_2 extends string | (null | undefined) ? T_2 extends PromiseLike<unknown> ? T_2 | Awaited<T_2> : T_2 : never : never : never) | ((Sets[K] extends (infer T_3) ? T_3 extends Sets[K] ? T_3 extends ModelRules ? "name" extends (infer T_4) ? T_4 extends "name" ? T_4 extends keyof T_3 ? T_3[T_4] : string : never : never : never : never : never) extends (infer T_5) ? T_5 extends (Sets[K] extends (infer T_3) ? T_3 extends Sets[K] ? T_3 extends ModelRules ? "name" extends (infer T_4) ? T_4 extends "name" ? T_4 extends keyof T_3 ? T_3[T_4] : string : never : never : never : never : never) ? T_5 extends string | (null | undefined) ? T_5 extends PromiseLike<unknown> ? T_5 | Awaited<T_5> : T_5 : never : never : never), ((Sets[K] extends (infer T_6) ? T_6 extends Sets[K] ? T_6 extends ActionRules ? "resolveIn" extends (infer T_7) ? T_7 extends "resolveIn" ? T_7 extends keyof T_6 ? T_6[T_7] extends (infer T_8) ? T_8 extends T_6[T_7] ? T_8 extends ((ctx: BindCtx) => unknown) ? (T_8 extends (infer T_9) ? T_9 extends T_8 ? T_9 extends ((...args: infer Args) => infer Result) ? [(...args: Args) => Result] extends [T_9] ? true : false : false : never : never) extends true ? T_8 extends ((...args: never) => infer Result) ? Result : never : unknown : never : never : never : unknown : never : never : never : never : never) extends (infer T_10) ? T_10 extends (Sets[K] extends (infer T_6) ? T_6 extends Sets[K] ? T_6 extends ActionRules ? "resolveIn" extends (infer T_7) ? T_7 extends "resolveIn" ? T_7 extends keyof T_6 ? T_6[T_7] extends (infer T_8) ? T_8 extends T_6[T_7] ? T_8 extends ((ctx: BindCtx) => unknown) ? (T_8 extends (infer T_9) ? T_9 extends T_8 ? T_9 extends ((...args: infer Args) => infer Result) ? [(...args: Args) => Result] extends [T_9] ? true : false : false : never : never) extends true ? T_8 extends ((...args: never) => infer Result) ? Result : never : unknown : never : never : never : unknown : never : never : never : never : never) ? T_10 extends unknown ? T_10 : never : never : never) | ((Sets[K] extends (infer T_11) ? T_11 extends Sets[K] ? T_11 extends ModelRules ? "resolveIn" extends (infer T_12) ? T_12 extends "resolveIn" ? T_12 extends keyof T_11 ? T_11[T_12] extends (infer T_13) ? T_13 extends T_11[T_12] ? T_13 extends ((ctx: BindCtx) => unknown) ? (T_13 extends (infer T_14) ? T_14 extends T_13 ? T_14 extends ((...args: infer Args) => infer Result) ? [(...args: Args) => Result_1] extends [T_14] ? true : false : false : never : never) extends true ? T_13 extends ((...args: never) => infer Result) ? Result : never : unknown : never : never : never : unknown : never : never : never : never : never) extends (infer T_15) ? T_15 extends (Sets[K] extends (infer T_11) ? T_11 extends Sets[K] ? T_11 extends ModelRules ? "resolveIn" extends (infer T_12) ? T_12 extends "resolveIn" ? T_12 extends keyof T_11 ? T_11[T_12] extends (infer T_13) ? T_13 extends T_11[T_12] ? T_13 extends ((ctx: BindCtx) => unknown) ? (T_13 extends (infer T_14) ? T_14 extends T_13 ? T_14 extends ((...args: infer Args) => infer Result) ? [(...args: Args) => Result_1] extends [T_14] ? true : false : false : never : never) extends true ? T_13 extends ((...args: never) => infer Result) ? Result : never : unknown : never : never : never : unknown : never : never : never : never : never) ? T_15 extends unknown ? T_15 : never : never : never)]; }>;
|
|
572
|
+
type DomainTypes = {
|
|
573
|
+
readonly actor: unknown;
|
|
574
|
+
};
|
|
575
|
+
export declare const domainDefinitionKit: <D extends DomainTypes>() => Readonly<{
|
|
576
|
+
model: <const N extends string, In, Out, P>(def: {
|
|
577
|
+
readonly name: N;
|
|
578
|
+
readonly schema: {
|
|
579
|
+
readonly input: import("@standard-schema/spec").StandardSchemaV1<In, Out> & {
|
|
580
|
+
readonly entries: NoInfer<Entries<Out>>;
|
|
581
|
+
} & NoInfer<In extends {
|
|
582
|
+
readonly id: unknown;
|
|
583
|
+
} ? {
|
|
584
|
+
readonly "model の入力スキーマの id は省略可能でなければならない": true;
|
|
585
|
+
} : unknown>;
|
|
586
|
+
readonly persisted: import("@standard-schema/spec").StandardSchemaV1<unknown, P>;
|
|
587
|
+
};
|
|
588
|
+
}) => Model<N, In, Out, P, D["actor"]>;
|
|
589
|
+
action: <const N extends string, In, Out>(def: {
|
|
590
|
+
readonly name: N;
|
|
591
|
+
readonly input: import("@standard-schema/spec").StandardSchemaV1<In, Out>;
|
|
592
|
+
}) => Action<N, In, Out, D["actor"]>;
|
|
593
|
+
actor: <S = unknown>(predicate: (a: D["actor"], s: S) => boolean) => When<TrackKind, {
|
|
594
|
+
readonly actor: D["actor"];
|
|
595
|
+
} & S>;
|
|
596
|
+
}>;
|
|
597
|
+
export type { Action, ActionRules, Clock, Decision, Deletable, Domain, DomainTypes, InputFailure, LoadFailure, Model, ModelRules, Persistable, Persisted, PlannedRule, Port, Provider, Rule, Ruleset, Value, When, WhenDescription };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,573 @@
|
|
|
1
|
+
import { Result } from "@praha/byethrow";
|
|
2
|
+
import { fromEntries, getOrEmpty, mapValues } from "as-free";
|
|
3
|
+
// src/shared/panic.ts
|
|
4
|
+
var Panic = class extends Error {
|
|
5
|
+
name = "Panic";
|
|
6
|
+
};
|
|
7
|
+
// src/port/provider.ts
|
|
8
|
+
const register = (impls, scope, impl, name) => {
|
|
9
|
+
if (impls.has(scope)) throw new Panic(`bind: port "${name}" の provider が重複しています`);
|
|
10
|
+
impls.set(scope, impl);
|
|
11
|
+
};
|
|
12
|
+
var Provider = class {
|
|
13
|
+
name;
|
|
14
|
+
#register;
|
|
15
|
+
constructor(name, register) {
|
|
16
|
+
this.name = name;
|
|
17
|
+
this.#register = register;
|
|
18
|
+
Object.freeze(this);
|
|
19
|
+
}
|
|
20
|
+
registerIn = (scope) => this.#register(scope);
|
|
21
|
+
};
|
|
22
|
+
const provide = Object.assign((target, impl) => target.provider(impl), { value: (target, v) => target.valued(v) });
|
|
23
|
+
// src/port/clock.ts
|
|
24
|
+
var Clock = class {
|
|
25
|
+
kind = "clock";
|
|
26
|
+
name = "clock";
|
|
27
|
+
#impls = /* @__PURE__ */ new WeakMap();
|
|
28
|
+
constructor() {
|
|
29
|
+
Object.freeze(this);
|
|
30
|
+
}
|
|
31
|
+
provider = (now) => new Provider(this.name, (scope) => register(this.#impls, scope, now, this.name));
|
|
32
|
+
valued = (v) => this.provider(() => v);
|
|
33
|
+
providedIn = (scope) => this.#impls.has(scope);
|
|
34
|
+
nowIn = (scope) => this.#impls.get(scope)?.();
|
|
35
|
+
};
|
|
36
|
+
const clock = new Clock();
|
|
37
|
+
// src/port/port.ts
|
|
38
|
+
var Slots = class {
|
|
39
|
+
impls = /* @__PURE__ */ new WeakMap();
|
|
40
|
+
memos = /* @__PURE__ */ new WeakMap();
|
|
41
|
+
};
|
|
42
|
+
var Port = class Port {
|
|
43
|
+
kind = "port";
|
|
44
|
+
name;
|
|
45
|
+
cached;
|
|
46
|
+
#slots;
|
|
47
|
+
constructor(name, cached, slots) {
|
|
48
|
+
this.name = name;
|
|
49
|
+
this.cached = cached;
|
|
50
|
+
this.#slots = slots;
|
|
51
|
+
Object.freeze(this);
|
|
52
|
+
}
|
|
53
|
+
provider = (impl) => new Provider(this.name, (scope) => register(this.#slots.impls, scope, impl, this.name));
|
|
54
|
+
valued = (v) => this.provider(() => Result.succeed(v));
|
|
55
|
+
providedIn = (scope) => this.#slots.impls.has(scope);
|
|
56
|
+
withCache = () => new Port(this.name, true, this.#slots);
|
|
57
|
+
callIn = async (invocation, args) => {
|
|
58
|
+
const impl = this.#slots.impls.get(invocation.scope);
|
|
59
|
+
if (impl === void 0) throw new Panic(`port "${this.name}" の provider がありません`);
|
|
60
|
+
if (!this.cached) return impl(...args);
|
|
61
|
+
const memo = this.#slots.memos.get(invocation) ?? /* @__PURE__ */ new Map();
|
|
62
|
+
this.#slots.memos.set(invocation, memo);
|
|
63
|
+
const key = JSON.stringify(args);
|
|
64
|
+
const hit = memo.get(key);
|
|
65
|
+
if (hit !== void 0) return hit;
|
|
66
|
+
const pending = Promise.resolve(impl(...args));
|
|
67
|
+
memo.set(key, pending);
|
|
68
|
+
return pending;
|
|
69
|
+
};
|
|
70
|
+
resolveIn = (invocation) => (...args) => this.callIn(invocation, args);
|
|
71
|
+
unwrapIn = (invocation) => {
|
|
72
|
+
const call = (args) => this.callIn(invocation, args);
|
|
73
|
+
const name = this.name;
|
|
74
|
+
return async function* (...args) {
|
|
75
|
+
const r = await call(args);
|
|
76
|
+
if (Result.isFailure(r)) {
|
|
77
|
+
yield r;
|
|
78
|
+
throw new Panic(`port "${name}" の失敗を yield した後に再開されました`);
|
|
79
|
+
}
|
|
80
|
+
return r.value;
|
|
81
|
+
};
|
|
82
|
+
};
|
|
83
|
+
};
|
|
84
|
+
const port = (name) => ({ of: () => new Port(name, false, new Slots()) });
|
|
85
|
+
const cached = (p) => p.withCache();
|
|
86
|
+
// src/pipeline/requires.ts
|
|
87
|
+
const resolvePorts = (requires, invocation) => mapValues(requires, (p) => p.resolveIn(invocation));
|
|
88
|
+
const unwrapPorts = (requires, invocation) => mapValues(requires, (p) => p.unwrapIn(invocation));
|
|
89
|
+
// src/pipeline/safe-try.ts
|
|
90
|
+
const safeTryWith = (unwrapped) => async (body) => {
|
|
91
|
+
const it = body(unwrapped);
|
|
92
|
+
const step = await it.next();
|
|
93
|
+
if (step.done === true) return step.value;
|
|
94
|
+
await it.return?.();
|
|
95
|
+
return step.value;
|
|
96
|
+
};
|
|
97
|
+
// src/pipeline/when/step.ts
|
|
98
|
+
const objectOf = (value) => typeof value === "object" && value !== null ? value : void 0;
|
|
99
|
+
const nextOf = (value) => {
|
|
100
|
+
const o = objectOf(value);
|
|
101
|
+
return o === void 0 ? void 0 : objectOf(new Map(Object.entries(o)).get("next"));
|
|
102
|
+
};
|
|
103
|
+
const nestedNext = (s, v) => {
|
|
104
|
+
const before = nextOf(s);
|
|
105
|
+
const added = nextOf(v);
|
|
106
|
+
return before !== void 0 && added !== void 0 ? { next: {
|
|
107
|
+
...before,
|
|
108
|
+
...added
|
|
109
|
+
} } : {};
|
|
110
|
+
};
|
|
111
|
+
const merged = (s, v) => Object.assign({}, s, v, nestedNext(s, v));
|
|
112
|
+
const applied = async (s, check) => {
|
|
113
|
+
const r = await check(s);
|
|
114
|
+
return Result.isFailure(r) ? r : Result.succeed(merged(s, r.value));
|
|
115
|
+
};
|
|
116
|
+
const conditionalStep = (test) => async (s, check) => test(s) ? applied(s, check) : Result.succeed(s);
|
|
117
|
+
const always = Object.freeze(Object.assign(() => true, {
|
|
118
|
+
description: { kind: "always" },
|
|
119
|
+
step: applied
|
|
120
|
+
}));
|
|
121
|
+
// src/pipeline/rule.ts
|
|
122
|
+
function rule(track, def) {
|
|
123
|
+
const requires = getOrEmpty(def, "requires");
|
|
124
|
+
const check = def.check;
|
|
125
|
+
const run = async (s, invocation) => check(s, resolvePorts(requires, invocation), { safeTry: safeTryWith(unwrapPorts(requires, invocation)) });
|
|
126
|
+
return Object.freeze({
|
|
127
|
+
kind: "rule",
|
|
128
|
+
track: {
|
|
129
|
+
kind: track.kind,
|
|
130
|
+
target: track.target
|
|
131
|
+
},
|
|
132
|
+
name: def.name,
|
|
133
|
+
ports: Object.values(requires),
|
|
134
|
+
when: Object.freeze(Object.assign((s) => def.when(s), { step: conditionalStep(def.when) }, def.when)),
|
|
135
|
+
run
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
// src/pipeline/when/when.ts
|
|
139
|
+
const whenOf = (description, f) => Object.freeze(Object.assign((s) => f(s), { description }));
|
|
140
|
+
const describeWhen = (w) => w.description ?? { kind: "custom" };
|
|
141
|
+
// src/pipeline/when/builders.ts
|
|
142
|
+
const onCreate = whenOf({ kind: "onCreate" }, (s) => s.pre === null);
|
|
143
|
+
const fieldOf = (o, field) => o[field];
|
|
144
|
+
const matches = (m, v) => m === void 0 || Object.is(m, v);
|
|
145
|
+
const changed = (field, values = {}) => whenOf({
|
|
146
|
+
kind: "changed",
|
|
147
|
+
field,
|
|
148
|
+
...values
|
|
149
|
+
}, (s) => {
|
|
150
|
+
const after = fieldOf(s.next, field);
|
|
151
|
+
if (s.pre === null) return values.pre === void 0 && matches(values.next, after);
|
|
152
|
+
const before = fieldOf(s.pre, field);
|
|
153
|
+
return !Object.is(before, after) && matches(values.pre, before) && matches(values.next, after);
|
|
154
|
+
});
|
|
155
|
+
const next = (predicate) => whenOf({ kind: "next" }, (s) => predicate(s.next));
|
|
156
|
+
const pre = (predicate) => whenOf({ kind: "pre" }, (s) => s.pre !== null && predicate(s.pre));
|
|
157
|
+
const actor = (predicate) => whenOf({ kind: "actor" }, (s) => predicate(s.actor, s));
|
|
158
|
+
const and = (...ws) => {
|
|
159
|
+
const tests = ws;
|
|
160
|
+
return whenOf({
|
|
161
|
+
kind: "and",
|
|
162
|
+
conditions: ws.map(describeWhen)
|
|
163
|
+
}, (s) => tests.every((w) => w(s)));
|
|
164
|
+
};
|
|
165
|
+
const or = (...ws) => {
|
|
166
|
+
const tests = ws;
|
|
167
|
+
return whenOf({
|
|
168
|
+
kind: "or",
|
|
169
|
+
conditions: ws.map(describeWhen)
|
|
170
|
+
}, (s) => tests.some((w) => w(s)));
|
|
171
|
+
};
|
|
172
|
+
const not = (w) => whenOf({
|
|
173
|
+
kind: "not",
|
|
174
|
+
condition: describeWhen(w)
|
|
175
|
+
}, (s) => !w(s));
|
|
176
|
+
const describe = (description, f) => whenOf({
|
|
177
|
+
kind: "custom",
|
|
178
|
+
description
|
|
179
|
+
}, f);
|
|
180
|
+
// src/pipeline/builtin-rules.ts
|
|
181
|
+
const valueOf = (o, f) => o === null ? void 0 : new Map(Object.entries(o)).get(f);
|
|
182
|
+
const immutable = (track, fields) => {
|
|
183
|
+
const changedField = (s) => fields.find((f) => !Object.is(valueOf(s.pre, f), valueOf(s.next, f)));
|
|
184
|
+
return rule(track, {
|
|
185
|
+
name: `作成後に変えられない項目: ${fields.join(", ")}`,
|
|
186
|
+
when: whenOf({
|
|
187
|
+
kind: "and",
|
|
188
|
+
conditions: [{
|
|
189
|
+
kind: "not",
|
|
190
|
+
condition: describeWhen(onCreate)
|
|
191
|
+
}, {
|
|
192
|
+
kind: "or",
|
|
193
|
+
conditions: fields.map((f) => describeWhen(changed(f)))
|
|
194
|
+
}]
|
|
195
|
+
}, (s) => s.pre !== null && changedField(s) !== void 0),
|
|
196
|
+
check: (s) => {
|
|
197
|
+
const field = changedField(s);
|
|
198
|
+
return field === void 0 ? Result.succeed() : Result.fail({
|
|
199
|
+
code: "IMMUTABLE_FIELD_CHANGED",
|
|
200
|
+
field
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
});
|
|
204
|
+
};
|
|
205
|
+
const alwaysAllow = Object.freeze({
|
|
206
|
+
kind: "rule",
|
|
207
|
+
name: "常に許可",
|
|
208
|
+
ports: [],
|
|
209
|
+
when: always,
|
|
210
|
+
run: async () => Result.succeed()
|
|
211
|
+
});
|
|
212
|
+
// src/pipeline/ruleset.ts
|
|
213
|
+
var Ruleset = class Ruleset {
|
|
214
|
+
kind = "ruleset";
|
|
215
|
+
plan;
|
|
216
|
+
ports;
|
|
217
|
+
run;
|
|
218
|
+
constructor(plan, ports, run) {
|
|
219
|
+
this.plan = plan;
|
|
220
|
+
this.ports = ports;
|
|
221
|
+
this.run = run;
|
|
222
|
+
Object.freeze(this);
|
|
223
|
+
}
|
|
224
|
+
add(r) {
|
|
225
|
+
const previous = this.run;
|
|
226
|
+
const ports = r.ports;
|
|
227
|
+
const step = r.when.step;
|
|
228
|
+
return new Ruleset([...this.plan, {
|
|
229
|
+
name: r.name,
|
|
230
|
+
when: describeWhen(r.when),
|
|
231
|
+
ports: ports.map((p) => p.name)
|
|
232
|
+
}], [...this.ports, ...ports], async (s0, invocation) => {
|
|
233
|
+
const prev = await previous(s0, invocation);
|
|
234
|
+
if (Result.isFailure(prev)) return prev;
|
|
235
|
+
return step(prev.value, async (s) => {
|
|
236
|
+
const out = await r.run(s, invocation);
|
|
237
|
+
return Result.isFailure(out) ? Result.fail({
|
|
238
|
+
step: r.name,
|
|
239
|
+
error: out.error
|
|
240
|
+
}) : out;
|
|
241
|
+
});
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
const start = (first) => new Ruleset([], [], async (s) => Result.succeed(s)).add(first);
|
|
246
|
+
const ruleset = start;
|
|
247
|
+
// src/method/seal.ts
|
|
248
|
+
var Sealed = class {
|
|
249
|
+
#contents;
|
|
250
|
+
constructor(contents) {
|
|
251
|
+
this.#contents = Object.freeze(contents);
|
|
252
|
+
Object.setPrototypeOf(this, null);
|
|
253
|
+
Object.freeze(this);
|
|
254
|
+
}
|
|
255
|
+
static contents(s) {
|
|
256
|
+
if (!(#contents in s)) throw new Panic("open: メソッドが作った封をした値ではありません");
|
|
257
|
+
return s.#contents;
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
const seal = (contents) => new Sealed(contents);
|
|
261
|
+
const open = (s) => Sealed.contents(s);
|
|
262
|
+
// src/method/validate.ts
|
|
263
|
+
const inputFailure = (issues) => ({
|
|
264
|
+
step: "input",
|
|
265
|
+
error: { issues }
|
|
266
|
+
});
|
|
267
|
+
const validate = async (schema, value, path = []) => {
|
|
268
|
+
const r = await schema["~standard"].validate(value);
|
|
269
|
+
return r.issues !== void 0 ? Result.fail(r.issues.map((i) => ({
|
|
270
|
+
...i,
|
|
271
|
+
path: [...path, ...i.path ?? []]
|
|
272
|
+
}))) : Result.succeed(r.value);
|
|
273
|
+
};
|
|
274
|
+
const unknownKeys = (entries, input, allowed) => Object.keys(input).filter((key) => !Object.hasOwn(entries, key) || !allowed(key)).map((key) => ({
|
|
275
|
+
message: `schema にない項目です: ${key}`,
|
|
276
|
+
path: [key]
|
|
277
|
+
}));
|
|
278
|
+
const definedEntries = (input) => Object.fromEntries(Object.entries(input).filter(([, v]) => v !== void 0));
|
|
279
|
+
const validateWhole = async (schema, input) => {
|
|
280
|
+
const defined = definedEntries(input);
|
|
281
|
+
const unknown = unknownKeys(schema.entries, defined, (key) => key !== "id");
|
|
282
|
+
const r = await validate(schema, defined);
|
|
283
|
+
const issues = [...unknown, ...Result.isFailure(r) ? r.error : []];
|
|
284
|
+
if (issues.length > 0 || Result.isFailure(r)) return Result.fail(inputFailure(issues));
|
|
285
|
+
return Result.succeed(r.value);
|
|
286
|
+
};
|
|
287
|
+
const validatePartial = async (entries, input) => {
|
|
288
|
+
const issues = unknownKeys(entries, input, () => true);
|
|
289
|
+
const defined = definedEntries(input);
|
|
290
|
+
const out = {};
|
|
291
|
+
for (const key in entries) {
|
|
292
|
+
if (!Object.hasOwn(defined, key)) continue;
|
|
293
|
+
const r = await validate(entries[key], defined[key], [key]);
|
|
294
|
+
if (Result.isFailure(r)) issues.push(...r.error);
|
|
295
|
+
else out[key] = r.value;
|
|
296
|
+
}
|
|
297
|
+
return issues.length > 0 ? Result.fail(inputFailure(issues)) : Result.succeed(out);
|
|
298
|
+
};
|
|
299
|
+
// src/method/action-method.ts
|
|
300
|
+
const actionMethods = (ctx, input, rules) => {
|
|
301
|
+
const decide = async ({ input: value, actor }) => {
|
|
302
|
+
const validated = await validate(input, value);
|
|
303
|
+
if (Result.isFailure(validated)) return Result.fail(inputFailure(validated.error));
|
|
304
|
+
const inv = ctx.invocation();
|
|
305
|
+
const r = await rules.run({
|
|
306
|
+
input: validated.value,
|
|
307
|
+
actor,
|
|
308
|
+
now: inv.now
|
|
309
|
+
}, inv);
|
|
310
|
+
if (Result.isFailure(r)) return r;
|
|
311
|
+
return Result.succeed(seal(r.value));
|
|
312
|
+
};
|
|
313
|
+
return Object.freeze({ decide });
|
|
314
|
+
};
|
|
315
|
+
// src/rule-set/action-rules.ts
|
|
316
|
+
const actorOf = (x) => x.actor;
|
|
317
|
+
function actionRules(a, def) {
|
|
318
|
+
const { rules, output } = def;
|
|
319
|
+
const decided = {
|
|
320
|
+
...rules,
|
|
321
|
+
run: async (s, call) => {
|
|
322
|
+
const r = await rules.run(s, call);
|
|
323
|
+
return Result.isFailure(r) ? r : Result.succeed({
|
|
324
|
+
value: output(r.value),
|
|
325
|
+
actor: actorOf(r.value)
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
};
|
|
329
|
+
return Object.freeze({
|
|
330
|
+
kind: "actionRules",
|
|
331
|
+
name: a.name,
|
|
332
|
+
action: a,
|
|
333
|
+
rules: Object.freeze(decided),
|
|
334
|
+
resolveIn: (ctx) => actionMethods(ctx, a.input, decided)
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
// src/method/model-methods.ts
|
|
338
|
+
const load = async (inv, port, id) => {
|
|
339
|
+
const r = await port.callIn(inv, [id]);
|
|
340
|
+
if (Result.isFailure(r)) return Result.fail({
|
|
341
|
+
step: "load",
|
|
342
|
+
error: r.error
|
|
343
|
+
});
|
|
344
|
+
const existing = r.value;
|
|
345
|
+
return existing === null || existing === void 0 ? Result.fail({
|
|
346
|
+
step: "load",
|
|
347
|
+
error: "NOT_FOUND"
|
|
348
|
+
}) : Result.succeed(existing);
|
|
349
|
+
};
|
|
350
|
+
const saveWith = async (rules, inv, pre, next, actor) => {
|
|
351
|
+
const r = await rules.run({
|
|
352
|
+
pre,
|
|
353
|
+
next,
|
|
354
|
+
actor,
|
|
355
|
+
now: inv.now
|
|
356
|
+
}, inv);
|
|
357
|
+
if (Result.isFailure(r)) return r;
|
|
358
|
+
return Result.succeed({
|
|
359
|
+
next: Object.freeze(r.value.next),
|
|
360
|
+
actor: r.value.actor
|
|
361
|
+
});
|
|
362
|
+
};
|
|
363
|
+
const createIn = async (ctx, model, rules, input, actor) => {
|
|
364
|
+
const next = await validateWhole(model.schema.input, input);
|
|
365
|
+
if (Result.isFailure(next)) return next;
|
|
366
|
+
const r = await saveWith(rules, ctx.invocation(), null, next.value, actor);
|
|
367
|
+
if (Result.isFailure(r)) return r;
|
|
368
|
+
return Result.succeed(seal({
|
|
369
|
+
pre: null,
|
|
370
|
+
...r.value
|
|
371
|
+
}));
|
|
372
|
+
};
|
|
373
|
+
const loadExisting = async (ctx, model, port, input) => {
|
|
374
|
+
const validated = await validatePartial(model.schema.input.entries, input);
|
|
375
|
+
if (Result.isFailure(validated)) return validated;
|
|
376
|
+
const id = validated.value.id;
|
|
377
|
+
if (id === void 0) return Result.fail(inputFailure([{
|
|
378
|
+
message: "id は必須です",
|
|
379
|
+
path: ["id"]
|
|
380
|
+
}]));
|
|
381
|
+
const inv = ctx.invocation();
|
|
382
|
+
const pre = await load(inv, port, id);
|
|
383
|
+
if (Result.isFailure(pre)) return pre;
|
|
384
|
+
return Result.succeed({
|
|
385
|
+
inv,
|
|
386
|
+
pre: pre.value,
|
|
387
|
+
validated: validated.value
|
|
388
|
+
});
|
|
389
|
+
};
|
|
390
|
+
const updateIn = async (ctx, model, port, rules, input, actor) => {
|
|
391
|
+
const existing = await loadExisting(ctx, model, port, input);
|
|
392
|
+
if (Result.isFailure(existing)) return existing;
|
|
393
|
+
const { inv, pre, validated } = existing.value;
|
|
394
|
+
const next = {
|
|
395
|
+
...pre,
|
|
396
|
+
...validated
|
|
397
|
+
};
|
|
398
|
+
const r = await saveWith(rules, inv, pre, next, actor);
|
|
399
|
+
if (Result.isFailure(r)) return r;
|
|
400
|
+
return Result.succeed(seal({
|
|
401
|
+
pre: Object.freeze({ ...pre }),
|
|
402
|
+
...r.value
|
|
403
|
+
}));
|
|
404
|
+
};
|
|
405
|
+
const createMethod = (model, rules) => (ctx) => ({ input, actor }) => createIn(ctx, model, rules, input, actor);
|
|
406
|
+
const updateMethod = (model, port, rules) => (ctx) => ({ input, actor }) => updateIn(ctx, model, port, rules, input, actor);
|
|
407
|
+
const upsertMethod = (model, port, rules) => (ctx) => ({ input, actor }) => {
|
|
408
|
+
return input["id"] === void 0 ? createIn(ctx, model, rules, input, actor) : updateIn(ctx, model, port, rules, input, actor);
|
|
409
|
+
};
|
|
410
|
+
const deleteMethod = (model, port, rules) => (ctx) => async ({ input, actor }) => {
|
|
411
|
+
const existing = await loadExisting(ctx, model, port, input);
|
|
412
|
+
if (Result.isFailure(existing)) return existing;
|
|
413
|
+
const { inv, pre } = existing.value;
|
|
414
|
+
const r = await rules.run({
|
|
415
|
+
pre,
|
|
416
|
+
next: null,
|
|
417
|
+
actor,
|
|
418
|
+
now: inv.now
|
|
419
|
+
}, inv);
|
|
420
|
+
if (Result.isFailure(r)) return r;
|
|
421
|
+
return Result.succeed(seal({
|
|
422
|
+
pre: Object.freeze({ ...pre }),
|
|
423
|
+
actor: r.value.actor
|
|
424
|
+
}));
|
|
425
|
+
};
|
|
426
|
+
// src/rule-set/model-rules.ts
|
|
427
|
+
var ModelRulesDone = class {
|
|
428
|
+
kind = "modelRules";
|
|
429
|
+
name;
|
|
430
|
+
plans;
|
|
431
|
+
ports;
|
|
432
|
+
resolveIn;
|
|
433
|
+
constructor(name, plans, ports, resolveIn) {
|
|
434
|
+
this.name = name;
|
|
435
|
+
this.plans = plans;
|
|
436
|
+
this.ports = ports;
|
|
437
|
+
this.resolveIn = resolveIn;
|
|
438
|
+
Object.freeze(this);
|
|
439
|
+
}
|
|
440
|
+
};
|
|
441
|
+
var ModelRulesStart = class {
|
|
442
|
+
kind = "modelRules";
|
|
443
|
+
name;
|
|
444
|
+
model;
|
|
445
|
+
plans = {};
|
|
446
|
+
ports = [];
|
|
447
|
+
resolveIn = () => Object.freeze({});
|
|
448
|
+
constructor(model) {
|
|
449
|
+
this.name = model.name;
|
|
450
|
+
this.model = model;
|
|
451
|
+
Object.freeze(this);
|
|
452
|
+
}
|
|
453
|
+
load(port) {
|
|
454
|
+
return new ModelRulesLoaded(this.model, port, {}, [port], this.resolveIn);
|
|
455
|
+
}
|
|
456
|
+
save(rules) {
|
|
457
|
+
const create = createMethod(this.model, rules);
|
|
458
|
+
return new ModelRulesDone(this.name, { save: rules.plan }, rules.ports, (ctx) => Object.freeze({ create: create(ctx) }));
|
|
459
|
+
}
|
|
460
|
+
};
|
|
461
|
+
var ModelRulesLoaded = class ModelRulesLoaded {
|
|
462
|
+
kind = "modelRules";
|
|
463
|
+
name;
|
|
464
|
+
model;
|
|
465
|
+
port;
|
|
466
|
+
plans;
|
|
467
|
+
ports;
|
|
468
|
+
resolveIn;
|
|
469
|
+
constructor(model, port, plans, ports, resolveIn) {
|
|
470
|
+
this.name = model.name;
|
|
471
|
+
this.model = model;
|
|
472
|
+
this.port = port;
|
|
473
|
+
this.plans = plans;
|
|
474
|
+
this.ports = ports;
|
|
475
|
+
this.resolveIn = resolveIn;
|
|
476
|
+
Object.freeze(this);
|
|
477
|
+
}
|
|
478
|
+
save(rules) {
|
|
479
|
+
const { model, port, resolveIn } = this;
|
|
480
|
+
const create = createMethod(model, rules);
|
|
481
|
+
const update = updateMethod(model, port, rules);
|
|
482
|
+
const upsert = upsertMethod(model, port, rules);
|
|
483
|
+
return new ModelRulesLoaded(model, port, {
|
|
484
|
+
...this.plans,
|
|
485
|
+
save: rules.plan
|
|
486
|
+
}, [...this.ports, ...rules.ports], methods);
|
|
487
|
+
function methods(ctx) {
|
|
488
|
+
return Object.freeze({
|
|
489
|
+
...resolveIn(ctx),
|
|
490
|
+
create: create(ctx),
|
|
491
|
+
update: update(ctx),
|
|
492
|
+
upsert: upsert(ctx)
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
delete(rules) {
|
|
497
|
+
const { model, port, resolveIn } = this;
|
|
498
|
+
const remove = deleteMethod(model, port, rules);
|
|
499
|
+
return new ModelRulesLoaded(model, port, {
|
|
500
|
+
...this.plans,
|
|
501
|
+
delete: rules.plan
|
|
502
|
+
}, [...this.ports, ...rules.ports], methods);
|
|
503
|
+
function methods(ctx) {
|
|
504
|
+
return Object.freeze({
|
|
505
|
+
...resolveIn(ctx),
|
|
506
|
+
delete: remove(ctx)
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
};
|
|
511
|
+
const modelRules = (m) => new ModelRulesStart(m);
|
|
512
|
+
// src/rule-set/rule-set.ts
|
|
513
|
+
function plan(set) {
|
|
514
|
+
return set.kind === "actionRules" ? { rules: set.rules.plan } : set.plans;
|
|
515
|
+
}
|
|
516
|
+
// src/bind.ts
|
|
517
|
+
function bind(sets, options) {
|
|
518
|
+
const scope = {};
|
|
519
|
+
for (const p of options.providers) p.registerIn(scope);
|
|
520
|
+
const names = /* @__PURE__ */ new Set();
|
|
521
|
+
for (const set of sets) {
|
|
522
|
+
if (names.has(set.name)) throw new Panic(`bind: "${set.name}" の rule の組が重複しています`);
|
|
523
|
+
names.add(set.name);
|
|
524
|
+
const missing = requiredPorts(set).filter((port) => !port.providedIn(scope)).map((port) => port.name);
|
|
525
|
+
if (missing.length > 0) throw new Panic(`bind: provider が足りない port: ${missing.join(", ")}`);
|
|
526
|
+
}
|
|
527
|
+
const ctx = { invocation: () => invocation(scope) };
|
|
528
|
+
return fromEntries(mapValues(sets, (set) => [set.name, set.resolveIn(ctx)]));
|
|
529
|
+
}
|
|
530
|
+
const requiredPorts = (set) => set.kind === "modelRules" ? [clock, ...set.ports] : [clock, ...set.rules.ports];
|
|
531
|
+
const invocation = (scope) => {
|
|
532
|
+
const now = clock.nowIn(scope);
|
|
533
|
+
if (now === void 0) throw new Panic("bind: clock の provider がありません");
|
|
534
|
+
return {
|
|
535
|
+
scope,
|
|
536
|
+
now
|
|
537
|
+
};
|
|
538
|
+
};
|
|
539
|
+
// src/definition/track.ts
|
|
540
|
+
var Track = class Track {
|
|
541
|
+
kind;
|
|
542
|
+
target;
|
|
543
|
+
constructor(kind, target) {
|
|
544
|
+
this.kind = kind;
|
|
545
|
+
this.target = target;
|
|
546
|
+
Object.freeze(this);
|
|
547
|
+
}
|
|
548
|
+
assuming() {
|
|
549
|
+
return new Track(this.kind, this.target);
|
|
550
|
+
}
|
|
551
|
+
};
|
|
552
|
+
// src/definition/action.ts
|
|
553
|
+
const defineAction = () => (def) => Object.freeze({
|
|
554
|
+
kind: "action",
|
|
555
|
+
name: def.name,
|
|
556
|
+
input: def.input,
|
|
557
|
+
onDecide: new Track("decide", def.name)
|
|
558
|
+
});
|
|
559
|
+
// src/definition/model.ts
|
|
560
|
+
const defineModel = () => (def) => Object.freeze({
|
|
561
|
+
kind: "model",
|
|
562
|
+
name: def.name,
|
|
563
|
+
schema: def.schema,
|
|
564
|
+
onSave: new Track("save", def.name),
|
|
565
|
+
onDelete: new Track("delete", def.name)
|
|
566
|
+
});
|
|
567
|
+
// src/domain-definition-kit.ts
|
|
568
|
+
const domainDefinitionKit = () => Object.freeze({
|
|
569
|
+
model: defineModel(),
|
|
570
|
+
action: defineAction(),
|
|
571
|
+
actor: (predicate) => actor(predicate)
|
|
572
|
+
});
|
|
573
|
+
export { actionRules, always, alwaysAllow, and, bind, cached, changed, clock, describe, domainDefinitionKit, immutable, modelRules, next, not, onCreate, open, or, plan, port, pre, provide, rule, ruleset };
|
package/package.json
CHANGED
|
@@ -1,6 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "domain-rules",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.0.1-beta.0",
|
|
4
|
+
"description": "Define business rules in small units and guarantee validated data with TypeScript types.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/9wick/domain-rules.git"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist"
|
|
12
|
+
],
|
|
13
|
+
"type": "module",
|
|
14
|
+
"exports": {
|
|
15
|
+
".": {
|
|
16
|
+
"types": "./dist/index.d.mts",
|
|
17
|
+
"default": "./dist/index.mjs"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"publishConfig": {
|
|
21
|
+
"access": "public"
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"@standard-schema/spec": "1.1.0",
|
|
25
|
+
"as-free": "0.0.2-beta.1"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@praha/byethrow": "0.13.0",
|
|
29
|
+
"typescript": "7.0.2",
|
|
30
|
+
"valibot": "1.5.0",
|
|
31
|
+
"vite-plus": "1.5.1",
|
|
32
|
+
"vitest": "5.1.0"
|
|
33
|
+
},
|
|
34
|
+
"peerDependencies": {
|
|
35
|
+
"@praha/byethrow": "0.13.0"
|
|
36
|
+
},
|
|
37
|
+
"scripts": {
|
|
38
|
+
"build": "vp pack",
|
|
39
|
+
"check": "vp check",
|
|
40
|
+
"test": "vp test run"
|
|
41
|
+
}
|
|
6
42
|
}
|