@cslug/core 0.10.0 → 0.11.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/docs/README.md +1 -1
- package/docs/api.md +14 -0
- package/package.json +2 -2
- package/src/index.ts +1 -0
- package/src/states.ts +85 -0
package/docs/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# @cslug/core
|
|
2
2
|
|
|
3
3
|
The application, the container with `@inject`, service providers, the ambient context, config and env, typed
|
|
4
|
-
errors, `Clock`, `Money`, events, the logger, i18n, the `Cache`/`Lock`/`RateLimiter`/`SessionStore` contracts
|
|
4
|
+
errors, `Clock`, `Money`, state machines (`states()`), events, the logger, i18n, the `Cache`/`Lock`/`RateLimiter`/`SessionStore` contracts
|
|
5
5
|
with in-memory drivers, and the server side of MCP (`handleMcpMessage`, `serveMcpStdio`) that `@cslug/ai` and
|
|
6
6
|
`cslug mcp:dev` share.
|
|
7
7
|
|
package/docs/api.md
CHANGED
|
@@ -127,6 +127,20 @@ Bound as a singleton; its time zone is `config('app.timezone')` (default UTC). A
|
|
|
127
127
|
|
|
128
128
|
`parseDuration('1h30m')` → ms. Units: `ms s m h d w`. Invalid input throws (never a silent 0).
|
|
129
129
|
|
|
130
|
+
## States
|
|
131
|
+
|
|
132
|
+
`states(transitions, { name?, onEnter?, onLeave? })`: each state lists the states it may move to; a target that is
|
|
133
|
+
not a state is a type error (and throws `states.unknown_state`).
|
|
134
|
+
|
|
135
|
+
| | |
|
|
136
|
+
|---|---|
|
|
137
|
+
| `.values` | Every state, for `text().oneOf(Status.values)` |
|
|
138
|
+
| `.type` | The union type: `type BookingStatus = typeof BookingStatus.type` |
|
|
139
|
+
| `.is(value)` | Type guard |
|
|
140
|
+
| `.can(from, to)` / `.next(from)` / `.final(state)` | Allowed? / reachable in one step / no way out |
|
|
141
|
+
| `.assert(from, to)` | Throws `ConflictError('<name>.invalid_transition', { from, to })` (409); name defaults to `state` |
|
|
142
|
+
| `.transition(from, to, change, row?)` | Assert, `onLeave[from]({ from, to, row })`, `change()`, `onEnter[to]({ from, to, row: result })`; what `repo.transition()` in `@cslug/database` calls inside its transaction |
|
|
143
|
+
|
|
130
144
|
## Money
|
|
131
145
|
|
|
132
146
|
Immutable; integer minor units (`bigint`) + ISO 4217 currency; no floating point anywhere.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cslug/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"description": "Application, container and @inject, providers, config, events, logger, errors, context, Clock, Money, i18n, contracts.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -28,6 +28,6 @@
|
|
|
28
28
|
"bun": ">=1.3.14"
|
|
29
29
|
},
|
|
30
30
|
"peerDependencies": {
|
|
31
|
-
"@cslug/validation": "0.
|
|
31
|
+
"@cslug/validation": "0.11.0"
|
|
32
32
|
}
|
|
33
33
|
}
|
package/src/index.ts
CHANGED
|
@@ -124,6 +124,7 @@ export {
|
|
|
124
124
|
} from './mcp'
|
|
125
125
|
export { Money, minorDigits } from './money'
|
|
126
126
|
export { type ProviderClass, type ProviderHooks, ServiceProvider } from './provider'
|
|
127
|
+
export { type StateChange, type StateHook, type StateMachine, type StatesOptions, states } from './states'
|
|
127
128
|
export {
|
|
128
129
|
type Attributes,
|
|
129
130
|
BasicMetrics,
|
package/src/states.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { ConflictError, CslugError } from './errors'
|
|
2
|
+
|
|
3
|
+
/** What a hook gets: the states, and the row (before the change for `onLeave`, after it for `onEnter`). */
|
|
4
|
+
export type StateChange<S extends string> = { from: S; to: S; row?: unknown }
|
|
5
|
+
export type StateHook<S extends string> = (change: StateChange<S>) => unknown
|
|
6
|
+
|
|
7
|
+
export type StatesOptions<S extends string> = {
|
|
8
|
+
/** Used in the error code: `booking` → `booking.invalid_transition` (default `state`). */
|
|
9
|
+
name?: string
|
|
10
|
+
/** Run after a row enters a state, in the caller's transaction (`repo.transition`). */
|
|
11
|
+
onEnter?: Partial<Record<S, StateHook<S>>>
|
|
12
|
+
/** Run before a row leaves a state, in the caller's transaction. */
|
|
13
|
+
onLeave?: Partial<Record<S, StateHook<S>>>
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** A set of states and the transitions allowed between them (`states()`). */
|
|
17
|
+
export type StateMachine<S extends string> = {
|
|
18
|
+
readonly name: string
|
|
19
|
+
/** Every state, for `text().oneOf(Status.values)`. */
|
|
20
|
+
readonly values: readonly S[]
|
|
21
|
+
/** The union of the states, as a type: `type BookingStatus = typeof BookingStatus.type`. Undefined at runtime. */
|
|
22
|
+
readonly type: S
|
|
23
|
+
/** Whether `value` is one of the states. */
|
|
24
|
+
is(value: unknown): value is S
|
|
25
|
+
/** Whether `from → to` is allowed. */
|
|
26
|
+
can(from: string, to: string): boolean
|
|
27
|
+
/** The states reachable from `from` in one step. */
|
|
28
|
+
next(from: S): readonly S[]
|
|
29
|
+
/** True for a state with no way out (`completed`, `cancelled`). */
|
|
30
|
+
final(state: S): boolean
|
|
31
|
+
/** Throw `ConflictError('<name>.invalid_transition', { from, to })` (409) unless `from → to` is allowed. */
|
|
32
|
+
assert(from: string, to: string): void
|
|
33
|
+
/**
|
|
34
|
+
* Check `from → to`, run `onLeave[from]`, `change()`, then `onEnter[to]` with its result; returns that result.
|
|
35
|
+
* `repo.transition()` calls it inside the transaction.
|
|
36
|
+
*/
|
|
37
|
+
transition<R>(from: S, to: S, change: () => R | Promise<R>, row?: unknown): Promise<R>
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* A state machine in plain TypeScript: each state lists the states it may move to.
|
|
42
|
+
*
|
|
43
|
+
* ```ts
|
|
44
|
+
* export const BookingStatus = states(
|
|
45
|
+
* { requested: ['proposed', 'cancelled'], proposed: ['accepted', 'cancelled'], accepted: [], cancelled: [] },
|
|
46
|
+
* { name: 'booking' },
|
|
47
|
+
* )
|
|
48
|
+
* export type BookingStatus = typeof BookingStatus.type
|
|
49
|
+
* BookingStatus.assert('requested', 'accepted') // ConflictError('booking.invalid_transition'), 409
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
52
|
+
export function states<const M extends { [K in keyof M]: readonly (keyof M & string)[] }>(
|
|
53
|
+
transitions: M,
|
|
54
|
+
options: StatesOptions<keyof M & string> = {},
|
|
55
|
+
): StateMachine<keyof M & string> {
|
|
56
|
+
type S = keyof M & string
|
|
57
|
+
const name = options.name ?? 'state'
|
|
58
|
+
const table = transitions as Record<string, readonly string[]>
|
|
59
|
+
const values = Object.keys(table) as S[]
|
|
60
|
+
for (const [from, targets] of Object.entries(table))
|
|
61
|
+
for (const to of targets)
|
|
62
|
+
if (!(to in table))
|
|
63
|
+
throw new CslugError('states.unknown_state', `${name}: "${from}" lists "${to}", which is not a state`)
|
|
64
|
+
const has = (value: unknown): value is S => typeof value === 'string' && Object.hasOwn(table, value)
|
|
65
|
+
const machine: StateMachine<S> = {
|
|
66
|
+
name,
|
|
67
|
+
values,
|
|
68
|
+
type: undefined as unknown as S,
|
|
69
|
+
is: has,
|
|
70
|
+
can: (from, to) => has(from) && (table[from] as readonly string[]).includes(to),
|
|
71
|
+
next: (from) => (table[from] ?? []) as readonly S[],
|
|
72
|
+
final: (state) => (table[state]?.length ?? 0) === 0,
|
|
73
|
+
assert(from, to) {
|
|
74
|
+
if (!machine.can(from, to)) throw new ConflictError(`${name}.invalid_transition`, { from, to })
|
|
75
|
+
},
|
|
76
|
+
async transition(from, to, change, row) {
|
|
77
|
+
machine.assert(from, to)
|
|
78
|
+
await options.onLeave?.[from]?.({ from, to, row })
|
|
79
|
+
const result = await change()
|
|
80
|
+
await options.onEnter?.[to]?.({ from, to, row: result })
|
|
81
|
+
return result
|
|
82
|
+
},
|
|
83
|
+
}
|
|
84
|
+
return Object.freeze(machine)
|
|
85
|
+
}
|