koyuki 0.0.0-stage → 0.1.0-alpha.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 yukiharada1228
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,100 @@
1
- # Temporary Holding Version
1
+ # Koyuki
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 業務の状態・検証・遷移を宣言し、接続と実行を任せるTypeScriptフレームワーク。
4
+
5
+ ```sh
6
+ npm install koyuki@alpha
7
+ ```
8
+
9
+ **実験段階のアルファ版です。** APIは変更される可能性があります。ES Modulesと
10
+ Node.js 22以上が必要です。現在の実装は `node:crypto` を使うため、ブラウザや
11
+ エッジランタイムでの動作は保証していません。
12
+
13
+ ## 最初の状態遷移
14
+
15
+ ```ts
16
+ import { ok, err, step, transition, type Result } from 'koyuki';
17
+
18
+ const approve = transition({
19
+ validate: step('validate', (amount: number): Result<number, 'InvalidAmount'> =>
20
+ amount > 0 ? ok(amount) : err('InvalidAmount')),
21
+ require: [] as const,
22
+ evolve: step('approve', (amount: number) =>
23
+ ok({ kind: 'approved' as const, amount })),
24
+ });
25
+
26
+ approve.run(100); // { ok: true, value: { kind: 'approved', amount: 100 } }
27
+ approve.run(-1); // { ok: false, error: 'InvalidAmount' }
28
+ ```
29
+
30
+ `validate` が成功した値を `require`、`evolve` に渡します。
31
+ 失敗すると後続の処理を実行せず、型付きのエラーを返します。
32
+ この例は接続の最小例です。実際の業務では直和型で状態を表し、権限や不変条件を検証します。
33
+
34
+ ## 取得・保存・アプリケーションの実行
35
+
36
+ 経費承認の宣言は次の形です。下記の関数とrepositoryは利用者が実装します。
37
+ [実行できる経費精算サンプル](examples/expenses/README.md)に全コードがあります。
38
+
39
+ ```ts
40
+ import { defineTarget, step } from 'koyuki';
41
+
42
+ const approved = {
43
+ validate: step('authorize-approval', validateApproval),
44
+ require: [] as const,
45
+ evolve: step('approve', approve),
46
+ };
47
+
48
+ const approval = defineTarget({
49
+ operation: 'expense.approve.v1',
50
+ load: input => repository.load(input, authenticatedActor),
51
+ save: change => repository.save(change),
52
+ }).on(approved);
53
+
54
+ await approval.run({ id: 'expense-1', expectedVersion: 2 });
55
+ ```
56
+
57
+ | 利用者が書くもの | Koyukiが実行するもの |
58
+ | --- | --- |
59
+ | 状態の型・検証・純粋な遷移関数 | 型の合う処理を接続し、Resultの失敗を伝播 |
60
+ | データの取得・保存アダプター | load → validate → require → evolve → save |
61
+ | 操作と成功時の業務データ更新 | `defineApplication` による ready / running / failed の管理 |
62
+ | 内部状態から返したい情報 | `view` の再計算、購読通知 |
63
+
64
+ HTTPはHonoなどに任せられます。ReactやJSXは必須ではありません。
65
+ 認証済みの利用者の注入、権限ルール、DBトランザクション、更新競合の防止は利用者が設計します。
66
+ 自動トランザクション・永続的なリトライ・監査ログは現時点では提供しません。
67
+
68
+ ## 経費精算サンプルを試す
69
+
70
+ ```sh
71
+ git clone https://github.com/yukiharada1228/koyuki.git
72
+ cd koyuki/examples/expenses
73
+ npm ci
74
+ npm run check
75
+ npm test
76
+ npm start
77
+ ```
78
+
79
+ サンプルはソース内部の相対importではなく、npmの `koyuki` を使用します。
80
+ 申請 → 上長承認 → 経理承認と、別申請の却下を確認できます。
81
+
82
+ ## フレームワークを開発する
83
+
84
+ リポジトリのルートで実行します。全テストには `node:sqlite` が必要です。
85
+ Node.js 26.12.0で検証しています。
86
+
87
+ ```sh
88
+ npm ci
89
+ npm run check
90
+ npm test
91
+ npm run build
92
+ ```
93
+
94
+ 既存のタグ管理・SQLite/Honoデモは [README.txt](README.txt)、
95
+ APIの検討記録は [PUBLIC-API.txt](PUBLIC-API.txt) を参照してください。
96
+ 将来機能は [Issues](https://github.com/yukiharada1228/koyuki/issues) で管理しています。
97
+
98
+ ## License
99
+
100
+ [MIT](LICENSE) © 2026 yukiharada1228
package/README.txt ADDED
@@ -0,0 +1,36 @@
1
+ Koyuki
2
+
3
+ 業務の状態・検証・遷移を宣言し、Resultの合成と取得・保存・実行管理を任せる
4
+ TypeScriptフレームワークの試作です。安定版APIではありません。
5
+
6
+ 入口
7
+ src/framework/index.ts
8
+ src/tags/events.ts — 業務イベントの宣言
9
+ src/tags/model.ts — 取得・保存の登録
10
+ src/tags/program.ts — 操作と業務状態への反映
11
+ src/expenses/application.ts — 経費申請への適用
12
+
13
+ 起動と検証(Node 26.12.0で確認)
14
+ npm ci
15
+ npm run check
16
+ npm test
17
+ npm run demo:expenses:sqlite
18
+ npm run dev
19
+
20
+ http://127.0.0.1:4317 タグ管理
21
+ http://127.0.0.1:4317/react React表示の利用例
22
+
23
+ 業務の核はReactに依存しません。Reactは表示アダプターの一例です。
24
+ ローカルDBは.data/に生成されます。リポジトリには含めていません。
25
+
26
+ PUBLIC-API.txtと各RESULTS.txtに設計判断・検証結果・制約を記載しています。
27
+ planning/feature-issues.jsonはGitHub Issueの起票原稿です。
28
+
29
+ この試作は伊藤直也氏の以下の発表に着想を得ています。
30
+ https://www.youtube.com/watch?v=izV1h6o3hgQ
31
+ https://www.youtube.com/watch?v=qBf910_YiqA
32
+ https://www.youtube.com/watch?v=w0oLNoGsGLc
33
+ 発表者による実装・監修・推奨を意味しません。
34
+
35
+ 実認証、汎用の永続実行、自動再送等は未実装です。
36
+ ライセンス条件はまだ設定していません。
@@ -0,0 +1,18 @@
1
+ import type { Result } from './result.js';
2
+ import type { Trace } from './workflow.js';
3
+ export interface ActionReport<O, E> {
4
+ readonly result: Result<O, E>;
5
+ readonly trace: readonly Trace[];
6
+ readonly plan: unknown;
7
+ }
8
+ /** Connect host-owned IO to a typed mutation; execute each phase exactly once. */
9
+ export declare function defineAction<I, C, LE, O, ME>(config: {
10
+ loadName: string;
11
+ load: (input: I) => Promise<Result<C, LE>>;
12
+ mutation: {
13
+ runDetailed(input: NoInfer<C>): Promise<ActionReport<O, ME>>;
14
+ };
15
+ }): {
16
+ run: (input: I) => Promise<Result<O, LE | ME>>;
17
+ runDetailed: (input: I) => Promise<ActionReport<O, LE | ME>>;
18
+ };
package/dist/action.js ADDED
@@ -0,0 +1,12 @@
1
+ /** Connect host-owned IO to a typed mutation; execute each phase exactly once. */
2
+ export function defineAction(config) {
3
+ async function runDetailed(input) {
4
+ const loaded = await config.load(input);
5
+ if (!loaded.ok)
6
+ return { result: loaded, trace: [{ step: config.loadName, status: 'error' }], plan: null };
7
+ const detail = await config.mutation.runDetailed(loaded.value);
8
+ return { ...detail, trace: [{ step: config.loadName, status: 'ok' }, ...detail.trace] };
9
+ }
10
+ async function run(input) { return (await runDetailed(input)).result; }
11
+ return { run, runDetailed };
12
+ }
@@ -0,0 +1,62 @@
1
+ import { type Result } from './result.js';
2
+ export interface Operation<S, I, O, E> {
3
+ readonly run: (input: I) => Promise<Result<O, E>>;
4
+ readonly reduce: (state: S, output: O) => S;
5
+ }
6
+ export declare function operation<S, I, O, E>(command: {
7
+ run(input: I): Promise<Result<O, E>>;
8
+ }, reduce: (state: S, output: NoInfer<O>) => S): Operation<S, I, O, E>;
9
+ type AnyOperation<S> = {
10
+ run(input: never): Promise<Result<unknown, unknown>>;
11
+ reduce(state: S, output: never): S;
12
+ };
13
+ type Input<T> = T extends {
14
+ run(input: infer I): unknown;
15
+ } ? I : never;
16
+ type ErrorOf<T> = T extends {
17
+ run(input: never): Promise<Result<unknown, infer E>>;
18
+ } ? E : never;
19
+ type Key<T> = Extract<keyof T, string>;
20
+ export type ApplicationEvent<T> = {
21
+ [K in Key<T>]: {
22
+ readonly type: K;
23
+ readonly input: Input<T[K]>;
24
+ };
25
+ }[Key<T>] | {
26
+ readonly type: 'dismiss';
27
+ };
28
+ export type ApplicationState<S, T> = {
29
+ readonly kind: 'ready';
30
+ readonly data: S;
31
+ } | {
32
+ readonly kind: 'running';
33
+ readonly data: S;
34
+ readonly operation: Key<T>;
35
+ } | {
36
+ [K in Key<T>]: {
37
+ readonly kind: 'failed';
38
+ readonly data: S;
39
+ readonly operation: K;
40
+ readonly error: ErrorOf<T[K]>;
41
+ };
42
+ }[Key<T>];
43
+ /** Standard operation lifecycle belongs to the framework, not each business application. */
44
+ export declare function defineApplication<S, const T extends Record<string, AnyOperation<S>>, V>(definition: {
45
+ initial: () => S;
46
+ operations: T;
47
+ view: (state: ApplicationState<S, T>) => V;
48
+ }): {
49
+ initial: () => ApplicationState<S, T>;
50
+ view: (state: ApplicationState<S, T>) => V;
51
+ start(): Promise<{
52
+ snapshot: () => import("./program.js").ProgramSnapshot<ApplicationState<S, T>, V>;
53
+ subscribe: (listener: (value: import("./program.js").ProgramSnapshot<ApplicationState<S, T>, V>) => void) => () => void;
54
+ trace: () => import("./program.js").ProgramTrace[];
55
+ dispatch(event: ApplicationEvent<T>, expectedRevision?: number): Promise<Result<import("./program.js").ProgramSnapshot<ApplicationState<S, T>, V>, {
56
+ kind: 'StaleRevision';
57
+ } | {
58
+ kind: 'UnexpectedMessage';
59
+ }>>;
60
+ }>;
61
+ };
62
+ export {};
@@ -0,0 +1,56 @@
1
+ import { defineProgram, next, effect } from './program.js';
2
+ import { ok, err } from './result.js';
3
+ export function operation(command, reduce) {
4
+ return { run: command.run, reduce };
5
+ }
6
+ /** Standard operation lifecycle belongs to the framework, not each business application. */
7
+ export function defineApplication(definition) {
8
+ for (const key of Object.keys(definition.operations))
9
+ if (key === 'dismiss' || key.startsWith('@'))
10
+ throw new Error('ReservedOperationName');
11
+ const operations = { ...definition.operations };
12
+ const program = defineProgram({
13
+ init: () => next({ kind: 'ready', data: definition.initial() }),
14
+ update(state, event) {
15
+ if (state.kind === 'ready' && event.type === '@execute') {
16
+ const entry = operations[event.operation];
17
+ if (!entry)
18
+ return err({ kind: 'UnexpectedMessage' });
19
+ // Public dispatch has already selected a type-checked operation/input pair.
20
+ const run = entry.run;
21
+ const command = effect(event.operation, run, (result) => ({ type: '@complete', operation: event.operation, result }));
22
+ return ok(next({ kind: 'running', operation: event.operation, data: state.data }, command(event.input)));
23
+ }
24
+ if (state.kind === 'running' && event.type === '@complete' && event.operation === state.operation) {
25
+ if (!event.result.ok) {
26
+ // This private completion is generated only by the selected operation's command.
27
+ return ok(next({ kind: 'failed', data: state.data, operation: event.operation, error: event.result.error }));
28
+ }
29
+ const reduce = operations[event.operation].reduce;
30
+ return ok(next({ kind: 'ready', data: reduce(state.data, event.result.value) }));
31
+ }
32
+ if (state.kind === 'failed' && event.type === 'dismiss')
33
+ return ok(next({ kind: 'ready', data: state.data }));
34
+ return err({ kind: 'UnexpectedMessage' });
35
+ },
36
+ view: definition.view,
37
+ });
38
+ return {
39
+ initial: () => program.init().state,
40
+ view: definition.view,
41
+ async start() {
42
+ const session = await program.start();
43
+ return {
44
+ snapshot: session.snapshot, subscribe: session.subscribe, trace: session.trace,
45
+ dispatch(event, expectedRevision) {
46
+ if (event.type === 'dismiss')
47
+ return session.dispatch({ type: 'dismiss' }, expectedRevision);
48
+ // Reject forged completion events even from untyped JS callers.
49
+ if (!Object.hasOwn(operations, event.type))
50
+ return Promise.resolve(err({ kind: 'UnexpectedMessage' }));
51
+ return session.dispatch({ type: '@execute', operation: event.type, input: event.input }, expectedRevision);
52
+ },
53
+ };
54
+ },
55
+ };
56
+ }
@@ -0,0 +1,27 @@
1
+ import type { Result } from './result.js';
2
+ import type { Workflow } from './workflow.js';
3
+ /** The common load → pure decision → save convention, declared once. */
4
+ export declare function defineCommand<I, C, LE, O, DE, S, SE>(definition: {
5
+ operation: string;
6
+ loadName?: string;
7
+ load: (input: I) => Promise<Result<C, LE>>;
8
+ decide: Workflow<C, O, DE>;
9
+ save: (decision: NoInfer<O>) => Promise<Result<S, SE>>;
10
+ }): {
11
+ run: (input: I) => Promise<Result<S, DE | LE | SE>>;
12
+ runDetailed: (input: I) => Promise<import("./action.js").ActionReport<S, DE | LE | SE>>;
13
+ mutation: {
14
+ Save: ({ value }: {
15
+ value: O;
16
+ }) => import("./workflow.js").View;
17
+ view: (value: O) => import("./workflow.js").View;
18
+ run: (input: C) => Promise<Result<S, DE | SE>>;
19
+ runDetailed: (input: C) => Promise<{
20
+ result: Result<S, DE | SE>;
21
+ trace: readonly import("./workflow.js").Trace[];
22
+ plan: unknown;
23
+ }>;
24
+ prepare: (input: C) => import("./workflow.js").Evaluation<O, DE>;
25
+ steps: readonly string[];
26
+ };
27
+ };
@@ -0,0 +1,9 @@
1
+ import { bindMutation } from './workflow.js';
2
+ import { defineAction } from './action.js';
3
+ /** The common load → pure decision → save convention, declared once. */
4
+ export function defineCommand(definition) {
5
+ const mutation = bindMutation({ workflow: definition.decide, operation: definition.operation, save: definition.save });
6
+ const action = defineAction({ loadName: definition.loadName ?? `${definition.operation}:load`, load: definition.load, mutation });
7
+ // The mutation escape hatch supports existing prepare/plan and comparison experiments.
8
+ return { ...action, mutation };
9
+ }
@@ -0,0 +1 @@
1
+ export declare function fingerprint(input: unknown): string;
@@ -0,0 +1,29 @@
1
+ import { createHash } from 'node:crypto';
2
+ // Reject values for which JSON would silently lose identity information.
3
+ export function fingerprint(input) {
4
+ const seen = new Set();
5
+ function normalize(value) {
6
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
7
+ return value;
8
+ if (typeof value === 'number' && Number.isFinite(value))
9
+ return value;
10
+ if (typeof value !== 'object' || value === null)
11
+ throw new Error('NonSerializableInput');
12
+ if (seen.has(value))
13
+ throw new Error('CyclicInput');
14
+ seen.add(value);
15
+ try {
16
+ if (Array.isArray(value))
17
+ return value.map(normalize);
18
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)
19
+ throw new Error('NonPlainInput');
20
+ if (Object.getOwnPropertySymbols(value).length)
21
+ throw new Error('SymbolInput');
22
+ return Object.fromEntries(Object.keys(value).sort().map(key => [key, normalize(value[key])]));
23
+ }
24
+ finally {
25
+ seen.delete(value);
26
+ }
27
+ }
28
+ return createHash('sha256').update(JSON.stringify(normalize(input))).digest('hex');
29
+ }
@@ -0,0 +1,14 @@
1
+ export { ok, err } from './result.js';
2
+ export type { Result } from './result.js';
3
+ export { workflow, bindMutation, describeView } from './workflow.js';
4
+ export type { Rule, Trace, Workflow } from './workflow.js';
5
+ export { defineAction } from './action.js';
6
+ export type { ActionReport } from './action.js';
7
+ export { collect } from './validation.js';
8
+ export { process } from './process.js';
9
+ export { defineCommand } from './command.js';
10
+ export { defineTarget, transition, step } from './model.js';
11
+ export { defineProgram, effect, next } from './program.js';
12
+ export type { Command, Update, ProgramSnapshot, ProgramTrace } from './program.js';
13
+ export { defineApplication, operation } from './application.js';
14
+ export type { ApplicationState, ApplicationEvent } from './application.js';
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ // Public entry: consumers need no experiment-specific modules or constructors.
2
+ export { ok, err } from './result.js';
3
+ export { workflow, bindMutation, describeView } from './workflow.js';
4
+ export { defineAction } from './action.js';
5
+ export { collect } from './validation.js';
6
+ export { process } from './process.js';
7
+ export { defineCommand } from './command.js';
8
+ export { defineTarget, transition, step } from './model.js';
9
+ export { defineProgram, effect, next } from './program.js';
10
+ export { defineApplication, operation } from './application.js';
@@ -0,0 +1,50 @@
1
+ import type { Result } from './result.js';
2
+ import { Workflow, type Rule } from './workflow.js';
3
+ export interface Step<I, O, E> {
4
+ readonly name: string;
5
+ readonly rule: Rule<I, O, E>;
6
+ }
7
+ export declare function step<I, O, E>(name: string, rule: Rule<I, O, E>): Step<I, O, E>;
8
+ type AnyStep = Step<never, unknown, unknown>;
9
+ type Output<T> = T extends Step<never, infer O, unknown> ? O : never;
10
+ type Failure<T> = T extends Step<never, unknown, infer E> ? E : never;
11
+ type End<I, T extends readonly AnyStep[]> = T extends readonly [infer H, ...infer R extends readonly AnyStep[]] ? End<Output<H>, R> : I;
12
+ type Connected<I, T extends readonly AnyStep[]> = T extends readonly [infer H extends AnyStep, ...infer R extends readonly AnyStep[]] ? H extends Step<infer A, unknown, unknown> ? [I] extends [A] ? readonly [H, ...Connected<Output<H>, R>] : never : never : readonly [];
13
+ /** A pure event transition: validation, domain requirements, evolution. No IO or manual Result plumbing. */
14
+ export declare function transition<I, V, VE, const T extends readonly AnyStep[], O, E>(definition: {
15
+ validate: Step<I, V, VE>;
16
+ require: T & Connected<NoInfer<V>, T>;
17
+ evolve: Step<NoInfer<End<V, T>>, O, E>;
18
+ }): Workflow<I, O, VE | Failure<T[number]> | E>;
19
+ /** Register an operation's IO at the model boundary, then attach pure event behavior. */
20
+ export declare function defineTarget<I, C, LE, O, S, SE>(adapter: {
21
+ operation: string;
22
+ loadName?: string;
23
+ load: (input: I) => Promise<Result<C, LE>>;
24
+ save: (value: O) => Promise<Result<S, SE>>;
25
+ }): {
26
+ on<VE, V, const T extends readonly AnyStep[], E>(definition: {
27
+ validate: Step<C, V, VE>;
28
+ require: T & Connected<NoInfer<V>, T>;
29
+ evolve: Step<NoInfer<End<V, T>>, NoInfer<O>, E>;
30
+ }): {
31
+ run: (input: I) => Promise<Result<S, E | LE | SE | VE | Failure<(T & Connected<NoInfer<V>, T>)[number]>>>;
32
+ runDetailed: (input: I) => Promise<import("./action.js").ActionReport<S, E | LE | SE | VE | Failure<(T & Connected<NoInfer<V>, T>)[number]>>>;
33
+ mutation: {
34
+ Save: ({ value }: {
35
+ value: NoInfer<O>;
36
+ }) => import("./workflow.js").View;
37
+ view: (value: NoInfer<O>) => import("./workflow.js").View;
38
+ run: (input: C) => Promise<Result<S, E | SE | VE | Failure<(T & Connected<NoInfer<V>, T>)[number]>>>;
39
+ runDetailed: (input: C) => Promise<{
40
+ result: Result<S, E | SE | VE | Failure<(T & Connected<NoInfer<V>, T>)[number]>>;
41
+ trace: readonly import("./workflow.js").Trace[];
42
+ plan: unknown;
43
+ }>;
44
+ prepare: (input: C) => import("./workflow.js").Evaluation<NoInfer<O>, E | VE | Failure<(T & Connected<NoInfer<V>, T>)[number]>>;
45
+ steps: readonly string[];
46
+ };
47
+ decision: Workflow<C, NoInfer<O>, E | VE | Failure<(T & Connected<NoInfer<V>, T>)[number]>>;
48
+ };
49
+ };
50
+ export {};
package/dist/model.js ADDED
@@ -0,0 +1,31 @@
1
+ import { Workflow } from './workflow.js';
2
+ import { defineCommand } from './command.js';
3
+ export function step(name, rule) { return { name, rule }; }
4
+ /** A pure event transition: validation, domain requirements, evolution. No IO or manual Result plumbing. */
5
+ export function transition(definition) {
6
+ // Type checking above proves adjacency. Runtime iteration erases only heterogeneous intermediate states.
7
+ const stages = [definition.validate, ...definition.require, definition.evolve];
8
+ return new Workflow(definition.validate.name, stages.map(stage => stage.name), input => {
9
+ let value = input;
10
+ const trace = [];
11
+ for (const stage of stages) {
12
+ const rule = stage.rule;
13
+ const result = rule(value);
14
+ trace.push({ step: stage.name, status: result.ok ? 'ok' : 'error' });
15
+ if (!result.ok)
16
+ return { result, trace };
17
+ value = result.value;
18
+ }
19
+ return { result: { ok: true, value: value }, trace };
20
+ });
21
+ }
22
+ /** Register an operation's IO at the model boundary, then attach pure event behavior. */
23
+ export function defineTarget(adapter) {
24
+ return {
25
+ on(definition) {
26
+ const decide = transition(definition);
27
+ const command = defineCommand({ ...adapter, decide });
28
+ return { ...command, decision: decide };
29
+ },
30
+ };
31
+ }
@@ -0,0 +1,25 @@
1
+ import { type Result } from './result.js';
2
+ import type { Workflow, Trace } from './workflow.js';
3
+ import type { ActionReport } from './action.js';
4
+ interface Report<O, E> {
5
+ readonly result: Result<O, E>;
6
+ readonly trace: readonly Trace[];
7
+ }
8
+ /** IO orchestration is intentionally separate from the synchronous, pure Workflow API. */
9
+ declare class Process<I, O, E> {
10
+ private readonly evaluate;
11
+ constructor(evaluate: (input: I) => Promise<Report<O, E>>);
12
+ through<N, F>(flow: Workflow<O, N, F>): Process<I, N, E | F>;
13
+ /** An explicit IO boundary; the adapter returns the next workflow's complete input. */
14
+ effect<N, F>(name: string, perform: (value: O) => Promise<Result<N, F>>): Process<I, N, E | F>;
15
+ /** The bound mutation owns its pure final decision and single save. */
16
+ commit<S, F>(mutation: {
17
+ runDetailed(input: NoInfer<O>): Promise<ActionReport<S, F>>;
18
+ }): {
19
+ run: (input: I) => Promise<Result<S, E | F>>;
20
+ runDetailed: (input: I) => Promise<ActionReport<S, E | F>>;
21
+ };
22
+ }
23
+ /** A process executes effects on run; it has no pretend-pure prepare/inspect API. */
24
+ export declare function process<I>(): Process<I, I, never>;
25
+ export {};
@@ -0,0 +1,44 @@
1
+ import { ok } from './result.js';
2
+ /** IO orchestration is intentionally separate from the synchronous, pure Workflow API. */
3
+ class Process {
4
+ evaluate;
5
+ constructor(evaluate) {
6
+ this.evaluate = evaluate;
7
+ }
8
+ through(flow) {
9
+ return new Process(async (input) => {
10
+ const prior = await this.evaluate(input);
11
+ if (!prior.result.ok)
12
+ return { result: prior.result, trace: prior.trace };
13
+ const next = flow.inspect(prior.result.value);
14
+ return { result: next.result, trace: [...prior.trace, ...next.trace] };
15
+ });
16
+ }
17
+ /** An explicit IO boundary; the adapter returns the next workflow's complete input. */
18
+ effect(name, perform) {
19
+ return new Process(async (input) => {
20
+ const prior = await this.evaluate(input);
21
+ if (!prior.result.ok)
22
+ return { result: prior.result, trace: prior.trace };
23
+ const result = await perform(prior.result.value);
24
+ return { result, trace: [...prior.trace, { step: name, status: result.ok ? 'ok' : 'error' }] };
25
+ });
26
+ }
27
+ /** The bound mutation owns its pure final decision and single save. */
28
+ commit(mutation) {
29
+ const evaluate = this.evaluate;
30
+ async function runDetailed(input) {
31
+ const prior = await evaluate(input);
32
+ if (!prior.result.ok)
33
+ return { result: prior.result, trace: prior.trace, plan: null };
34
+ const next = await mutation.runDetailed(prior.result.value);
35
+ return { ...next, trace: [...prior.trace, ...next.trace] };
36
+ }
37
+ async function run(input) { return (await runDetailed(input)).result; }
38
+ return { run, runDetailed };
39
+ }
40
+ }
41
+ /** A process executes effects on run; it has no pretend-pure prepare/inspect API. */
42
+ export function process() {
43
+ return new Process(async (input) => ({ result: ok(input), trace: [] }));
44
+ }
@@ -0,0 +1,43 @@
1
+ import { type Result } from './result.js';
2
+ export interface Command<M> {
3
+ readonly name: string;
4
+ readonly execute: () => Promise<M>;
5
+ }
6
+ export interface Update<S, M> {
7
+ readonly state: S;
8
+ readonly commands: readonly Command<M>[];
9
+ }
10
+ export declare const next: <S, M = never>(state: S, ...commands: Command<M>[]) => Update<S, M>;
11
+ /** Builds a command description. IO starts only when the runtime executes it. */
12
+ export declare function effect<I, O, M>(name: string, perform: (input: I) => Promise<O>, message: (output: O) => M): (input: I) => Command<M>;
13
+ export interface ProgramSnapshot<S, V> {
14
+ readonly revision: number;
15
+ readonly state: S;
16
+ readonly view: V;
17
+ }
18
+ export interface ProgramTrace {
19
+ readonly revision: number;
20
+ readonly kind: 'event' | 'command';
21
+ readonly name: string;
22
+ readonly status: 'ok' | 'error';
23
+ }
24
+ /** One in-process Elm-style event loop. Not a durable job runner. */
25
+ export declare function defineProgram<S, M extends {
26
+ type: string;
27
+ }, E, V>(definition: {
28
+ init: () => Update<S, M>;
29
+ update: (state: S, event: M) => Result<Update<S, M>, E>;
30
+ view: (state: S) => V;
31
+ }): {
32
+ init: () => Update<S, M>;
33
+ update: (state: S, event: M) => Result<Update<S, M>, E>;
34
+ view: (state: S) => V;
35
+ start(): Promise<{
36
+ snapshot: () => ProgramSnapshot<S, V>;
37
+ trace: () => ProgramTrace[];
38
+ subscribe(listener: (value: ProgramSnapshot<S, V>) => void): () => void;
39
+ dispatch(event: M, expectedRevision?: number): Promise<Result<ProgramSnapshot<S, V>, E | {
40
+ kind: 'StaleRevision';
41
+ }>>;
42
+ }>;
43
+ };
@@ -0,0 +1,82 @@
1
+ import { ok, err } from './result.js';
2
+ export const next = (state, ...commands) => ({ state, commands });
3
+ /** Builds a command description. IO starts only when the runtime executes it. */
4
+ export function effect(name, perform, message) {
5
+ return (input) => ({ name, execute: async () => message(await perform(input)) });
6
+ }
7
+ /** One in-process Elm-style event loop. Not a durable job runner. */
8
+ export function defineProgram(definition) {
9
+ return {
10
+ init: definition.init, update: definition.update, view: definition.view,
11
+ async start() {
12
+ const initial = definition.init();
13
+ let state = structuredClone(initial.state), revision = 0;
14
+ const history = [];
15
+ let tail = Promise.resolve();
16
+ const snapshot = () => ({ revision, state: structuredClone(state), view: definition.view(structuredClone(state)) });
17
+ async function settle(commands) {
18
+ const queue = [...commands];
19
+ let count = 0;
20
+ while (queue.length) {
21
+ if (++count > 100)
22
+ throw new Error('ProgramCommandLimit');
23
+ const command = queue.shift();
24
+ let message;
25
+ try {
26
+ message = await command.execute();
27
+ }
28
+ catch (error) {
29
+ history.push({ revision, kind: 'command', name: command.name, status: 'error' });
30
+ throw error;
31
+ }
32
+ history.push({ revision, kind: 'command', name: command.name, status: 'ok' });
33
+ const result = definition.update(structuredClone(state), message);
34
+ history.push({ revision, kind: 'event', name: message.type, status: result.ok ? 'ok' : 'error' });
35
+ if (!result.ok)
36
+ throw new Error('RejectedCommandMessage', { cause: result.error });
37
+ state = structuredClone(result.value.state);
38
+ revision++;
39
+ publish();
40
+ queue.push(...result.value.commands);
41
+ }
42
+ }
43
+ const listeners = new Set();
44
+ function publish() {
45
+ for (const listener of listeners) {
46
+ // Presentation failures must not interrupt an already accepted effect sequence.
47
+ try {
48
+ listener(snapshot());
49
+ }
50
+ catch { /* observer owns its error reporting */ }
51
+ }
52
+ }
53
+ await settle(initial.commands);
54
+ return {
55
+ snapshot,
56
+ trace: () => structuredClone(history),
57
+ subscribe(listener) {
58
+ listeners.add(listener);
59
+ listener(snapshot());
60
+ return () => { listeners.delete(listener); };
61
+ },
62
+ dispatch(event, expectedRevision) {
63
+ const task = tail.then(async () => {
64
+ if (expectedRevision !== undefined && expectedRevision !== revision)
65
+ return err({ kind: 'StaleRevision' });
66
+ const result = definition.update(structuredClone(state), structuredClone(event));
67
+ history.push({ revision, kind: 'event', name: event.type, status: result.ok ? 'ok' : 'error' });
68
+ if (!result.ok)
69
+ return result;
70
+ state = structuredClone(result.value.state);
71
+ revision++;
72
+ publish();
73
+ await settle(result.value.commands);
74
+ return ok(snapshot());
75
+ });
76
+ tail = task.catch(() => undefined);
77
+ return task;
78
+ },
79
+ };
80
+ },
81
+ };
82
+ }
@@ -0,0 +1,9 @@
1
+ export type Result<A, E> = {
2
+ ok: true;
3
+ value: A;
4
+ } | {
5
+ ok: false;
6
+ error: E;
7
+ };
8
+ export declare const ok: <A>(value: A) => Result<A, never>;
9
+ export declare const err: <E>(error: E) => Result<never, E>;
package/dist/result.js ADDED
@@ -0,0 +1,2 @@
1
+ export const ok = (value) => ({ ok: true, value });
2
+ export const err = (error) => ({ ok: false, error });
@@ -0,0 +1,19 @@
1
+ import { type Result } from './result.js';
2
+ type Value<R> = R extends {
3
+ ok: true;
4
+ value: infer A;
5
+ } ? A : never;
6
+ type Failure<R> = R extends {
7
+ ok: false;
8
+ error: infer E;
9
+ } ? E : never;
10
+ /** Combine independent, already-evaluated validations. Never short-circuits. */
11
+ export declare function collect<const T extends Record<string, Result<unknown, unknown>>>(fields: T): Result<{
12
+ readonly [K in keyof T]: Value<T[K]>;
13
+ }, readonly {
14
+ readonly [K in keyof T]: {
15
+ readonly field: K;
16
+ readonly error: Failure<T[K]>;
17
+ };
18
+ }[keyof T][]>;
19
+ export {};
@@ -0,0 +1,14 @@
1
+ import { ok, err } from './result.js';
2
+ /** Combine independent, already-evaluated validations. Never short-circuits. */
3
+ export function collect(fields) {
4
+ const values = {};
5
+ const failures = [];
6
+ for (const [field, result] of Object.entries(fields)) {
7
+ if (result.ok)
8
+ Object.defineProperty(values, field, { value: result.value, enumerable: true });
9
+ else
10
+ failures.push(Object.freeze({ field, error: result.error }));
11
+ }
12
+ // Object.entries loses the relationship between each key and its Result type.
13
+ return (failures.length ? err(Object.freeze(failures)) : ok(Object.freeze(values)));
14
+ }
@@ -0,0 +1,71 @@
1
+ import type { Result } from './result.js';
2
+ export type Rule<I, O, E> = (input: I) => Result<O, E>;
3
+ export interface Trace {
4
+ readonly step: string;
5
+ readonly status: 'ok' | 'error';
6
+ }
7
+ export interface Evaluation<O, E> {
8
+ result: Result<O, E>;
9
+ trace: readonly Trace[];
10
+ }
11
+ export declare class Workflow<I, O, E> {
12
+ readonly name: string;
13
+ readonly steps: readonly string[];
14
+ private readonly evaluate;
15
+ constructor(name: string, steps: readonly string[], evaluate: (input: I) => Evaluation<O, E>);
16
+ run(input: I): Result<O, E>;
17
+ inspect(input: I): Evaluation<O, E>;
18
+ branch<A, B, F, G>(name: string, predicate: (value: O) => boolean, paths: {
19
+ yes: Workflow<O, A, F>;
20
+ no: Workflow<O, B, G>;
21
+ }): Workflow<I, A | B, E | F | G>;
22
+ then<N, F>(name: string, rule: Rule<O, N, F>): Workflow<I, N, E | F>;
23
+ }
24
+ export declare function workflow<I, O, E>(name: string, rule: Rule<I, O, E>): Workflow<I, O, E>;
25
+ type WriteNode = {
26
+ readonly kind: 'write';
27
+ readonly operation: string;
28
+ readonly input: unknown;
29
+ };
30
+ export type View = WriteNode | {
31
+ readonly kind: 'mutation';
32
+ readonly name: string;
33
+ readonly child: View;
34
+ } | {
35
+ readonly kind: 'done';
36
+ };
37
+ export declare function ht<P>(component: (props: P) => View, props: P, ...children: View[]): View;
38
+ export declare namespace ht {
39
+ namespace JSX {
40
+ type Element = View;
41
+ interface ElementChildrenAttribute {
42
+ children: unknown;
43
+ }
44
+ }
45
+ }
46
+ export declare function Mutation({ name, children }: {
47
+ name: string;
48
+ children: View | readonly View[];
49
+ }): View;
50
+ export declare const Done: () => View;
51
+ export declare function describeView(view: View): unknown;
52
+ export declare function bindMutation<I, O, E, S, F>(config: {
53
+ workflow: Workflow<I, O, E>;
54
+ operation: string;
55
+ save: (value: NoInfer<O>) => Promise<Result<S, F>>;
56
+ render?: (value: NoInfer<O>) => View;
57
+ }): {
58
+ Save: ({ value }: {
59
+ value: O;
60
+ }) => View;
61
+ view: (value: O) => View;
62
+ run: (input: I) => Promise<Result<S, E | F>>;
63
+ runDetailed: (input: I) => Promise<{
64
+ result: Result<S, E | F>;
65
+ trace: readonly Trace[];
66
+ plan: unknown;
67
+ }>;
68
+ prepare: (input: I) => Evaluation<O, E>;
69
+ steps: readonly string[];
70
+ };
71
+ export {};
@@ -0,0 +1,86 @@
1
+ import { fingerprint } from './identity.js';
2
+ export class Workflow {
3
+ name;
4
+ steps;
5
+ evaluate;
6
+ constructor(name, steps, evaluate) {
7
+ this.name = name;
8
+ this.steps = steps;
9
+ this.evaluate = evaluate;
10
+ }
11
+ run(input) { return this.evaluate(input).result; }
12
+ inspect(input) { return this.evaluate(input); }
13
+ branch(name, predicate, paths) {
14
+ return new Workflow(this.name, [...this.steps, name], input => {
15
+ const previous = this.evaluate(input);
16
+ if (!previous.result.ok)
17
+ return { result: previous.result, trace: previous.trace };
18
+ const selected = predicate(previous.result.value) ? 'yes' : 'no';
19
+ const next = paths[selected].inspect(previous.result.value);
20
+ return { result: next.result, trace: [...previous.trace, { step: `${name}:${selected}`, status: 'ok' }, ...next.trace] };
21
+ });
22
+ }
23
+ then(name, rule) {
24
+ return new Workflow(this.name, [...this.steps, name], input => {
25
+ const previous = this.evaluate(input);
26
+ if (!previous.result.ok)
27
+ return { result: previous.result, trace: previous.trace };
28
+ const result = rule(previous.result.value);
29
+ return { result, trace: [...previous.trace, { step: name, status: result.ok ? 'ok' : 'error' }] };
30
+ });
31
+ }
32
+ }
33
+ export function workflow(name, rule) {
34
+ return new Workflow(name, [name], input => {
35
+ const result = rule(input);
36
+ return { result, trace: [{ step: name, status: result.ok ? 'ok' : 'error' }] };
37
+ });
38
+ }
39
+ const tasks = new WeakMap();
40
+ export function ht(component, props, ...children) {
41
+ return component({ ...props, ...(children.length ? { children } : {}) });
42
+ }
43
+ export function Mutation({ name, children }) {
44
+ const nodes = Array.isArray(children) ? children : [children];
45
+ if (nodes.length !== 1 || !nodes[0])
46
+ throw new Error('MutationRequiresOneChild');
47
+ return { kind: 'mutation', name, child: nodes[0] };
48
+ }
49
+ export const Done = () => ({ kind: 'done' });
50
+ export function describeView(view) {
51
+ if (view.kind === 'mutation')
52
+ return { kind: view.kind, name: view.name, child: describeView(view.child) };
53
+ if (view.kind === 'done')
54
+ return { kind: 'done' };
55
+ return { kind: view.kind, operation: view.operation, input: structuredClone(view.input) };
56
+ }
57
+ export function bindMutation(config) {
58
+ const identity = Symbol(config.operation);
59
+ function Save({ value }) {
60
+ // Snapshot the visible decision; the domain's opaque immutable value goes to the adapter.
61
+ const node = Object.freeze({ kind: 'write', operation: config.operation, input: structuredClone(value) });
62
+ tasks.set(node, { identity, execute: () => config.save(value) });
63
+ return node;
64
+ }
65
+ function view(value) { return config.render ? config.render(value) : Save({ value }); }
66
+ async function runDetailed(input) {
67
+ const evaluated = config.workflow.inspect(input), decision = evaluated.result;
68
+ if (!decision.ok)
69
+ return { result: decision, trace: evaluated.trace, plan: null };
70
+ const rendered = view(decision.value);
71
+ let node = rendered;
72
+ while (node.kind === 'mutation')
73
+ node = node.child;
74
+ if (node.kind !== 'write')
75
+ throw new Error('WrongMutationBinding');
76
+ const task = tasks.get(node);
77
+ if (!task || task.identity !== identity)
78
+ throw new Error('WrongMutationBinding');
79
+ if (fingerprint(node.input) !== fingerprint(decision.value))
80
+ throw new Error('ChangedDecision');
81
+ const result = await task.execute();
82
+ return { result, trace: [...evaluated.trace, { step: config.operation, status: result.ok ? 'ok' : 'error' }], plan: describeView(rendered) };
83
+ }
84
+ async function run(input) { return (await runDetailed(input)).result; }
85
+ return { Save, view, run, runDetailed, prepare: (input) => config.workflow.inspect(input), steps: config.workflow.steps };
86
+ }
package/package.json CHANGED
@@ -1,6 +1,74 @@
1
1
  {
2
2
  "name": "koyuki",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "type": "module",
4
+ "scripts": {
5
+ "check": "tsc --noEmit",
6
+ "test": "tsx --test src/*.test.ts src/*.test.tsx",
7
+ "compare": "node scripts/compare.mjs",
8
+ "test:comparison": "tsx --test src/comparison.test.tsx",
9
+ "demo": "tsx src/comparison/demo.ts",
10
+ "test:approval": "tsx --test src/approval.test.tsx",
11
+ "demo:approval": "tsx src/approval/demo.ts",
12
+ "test:tags": "tsx --test src/tags.test.tsx",
13
+ "demo:tags": "tsx src/tags/demo.ts",
14
+ "compare:tags": "node scripts/compare-tags.mjs",
15
+ "dev": "npm run build:view && tsx src/web/server.ts",
16
+ "test:web": "tsx --test src/web.test.ts",
17
+ "test:lifecycle": "tsx --test src/lifecycle.test.tsx",
18
+ "test:shipping": "tsx --test src/shipping.test.ts",
19
+ "demo:shipping": "tsx src/shipping/demo.ts",
20
+ "demo:events": "tsx src/examples/tag-events.ts",
21
+ "test:model": "tsx --test src/model.test.ts src/command.test.ts",
22
+ "demo:program": "tsx src/examples/tag-program.ts",
23
+ "test:program": "tsx --test src/program.test.ts",
24
+ "build:view": "node scripts/build-view.mjs",
25
+ "pretest": "npm run build:view",
26
+ "demo:expenses": "tsx src/expenses/demo.ts",
27
+ "test:expenses": "tsx --test src/expenses.test.ts",
28
+ "demo:expenses:sqlite": "tsx src/expenses/sqlite-demo.ts",
29
+ "test:expenses:sqlite": "tsx --test src/expenses-sqlite.test.ts",
30
+ "build": "tsc -p tsconfig.build.json",
31
+ "prepack": "npm run build"
32
+ },
33
+ "devDependencies": {
34
+ "@types/node": "latest",
35
+ "@types/react": "^19.3.0",
36
+ "@types/react-dom": "^19.3.0",
37
+ "esbuild": "^0.28.2",
38
+ "tsx": "latest",
39
+ "typescript": "latest",
40
+ "@hono/node-server": "^2.1.11",
41
+ "hono": "^4.13.21",
42
+ "react": "^19.3.1",
43
+ "react-dom": "^19.3.1"
44
+ },
45
+ "version": "0.1.0-alpha.1",
46
+ "description": "Declarative, functional business workflows for TypeScript",
47
+ "main": "./dist/index.js",
48
+ "types": "./dist/index.d.ts",
49
+ "exports": {
50
+ ".": {
51
+ "types": "./dist/index.d.ts",
52
+ "import": "./dist/index.js"
53
+ }
54
+ },
55
+ "files": [
56
+ "dist"
57
+ ],
58
+ "engines": {
59
+ "node": ">=22"
60
+ },
61
+ "repository": {
62
+ "type": "git",
63
+ "url": "git+https://github.com/yukiharada1228/koyuki.git"
64
+ },
65
+ "publishConfig": {
66
+ "access": "public",
67
+ "tag": "alpha"
68
+ },
69
+ "license": "MIT",
70
+ "homepage": "https://github.com/yukiharada1228/koyuki#readme",
71
+ "bugs": {
72
+ "url": "https://github.com/yukiharada1228/koyuki/issues"
73
+ }
74
+ }