@cslug/core 0.10.0 → 0.11.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/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.
@@ -154,7 +168,8 @@ Immutable; integer minor units (`bigint`) + ISO 4217 currency; no floating point
154
168
  | `@listener(X \| [X, Y], { queued?, queue?, tries?, backoff? })` | Class listener with `handle(payload, event)`, built by the container (scoped). Combine with `@inject(...)` in any order |
155
169
  | queued listeners | Run **after the transaction commits** (`afterCommit`), never on rollback. Without `@cslug/queue`: in-process in a fresh scope, errors logged. With it: `EventBus.dispatchQueued` sends them as jobs |
156
170
  | `afterCommit(fn)` | Run once the current transaction commits; outside a transaction, soon after the current task. `@cslug/database` provides the hook (`TransactionHooks`) |
157
- | `registeredListeners()` | For `cslug events` |
171
+ | `registeredListeners()` | The listener classes registered so far, by event |
172
+ | `loadListeners(rootDir)` | Imports `app/listeners/**` (not `*.test.ts`); `Application.start()` calls it before `boot()`, so `@listener` classes are registered in every process |
158
173
 
159
174
  ## Logger
160
175
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cslug/core",
3
- "version": "0.10.0",
3
+ "version": "0.11.1",
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.10.0"
31
+ "@cslug/validation": "0.11.1"
32
32
  }
33
33
  }
@@ -16,7 +16,7 @@ import {
16
16
  } from './contracts'
17
17
  import { Encrypter, parseKeys } from './encrypter'
18
18
  import { ProviderError } from './errors'
19
- import { EventBus } from './events'
19
+ import { EventBus, loadListeners } from './events'
20
20
  import { type I18nConfig, Translator } from './i18n'
21
21
  import { Logger, type LoggerOptions } from './logger'
22
22
  import { dependenciesOf, type ProviderClass, type ProviderHooks, type ServiceProvider } from './provider'
@@ -145,6 +145,8 @@ export class Application extends Container {
145
145
  this.registerProviders()
146
146
  if (this.state !== 'registered') throw new ProviderError(`Cannot start an application that is ${this.state}.`)
147
147
  this.state = 'starting'
148
+ // @listener classes register when their module is imported: do it here, so every process has them
149
+ await loadListeners(this.rootDir)
148
150
  for (const p of this.instances_) {
149
151
  try {
150
152
  await p.boot?.()
package/src/events.ts CHANGED
@@ -162,3 +162,20 @@ export class EventBus {
162
162
  }
163
163
  }
164
164
  }
165
+
166
+ /**
167
+ * Import every module under `<root>/app/listeners/` (subfolders included, not `*.test.ts`), so their `@listener`
168
+ * classes are registered in every process: the web server, workers, commands and tests. `Application.start()`
169
+ * calls it; a folder that does not exist is fine. Returns how many files were imported.
170
+ */
171
+ export async function loadListeners(rootDir: string): Promise<number> {
172
+ const { existsSync, readdirSync } = await import('node:fs')
173
+ const { join } = await import('node:path')
174
+ const dir = join(rootDir, 'app/listeners')
175
+ if (!existsSync(dir)) return 0
176
+ const files = (readdirSync(dir, { recursive: true }) as string[])
177
+ .filter((f) => f.endsWith('.ts') && !f.endsWith('.test.ts') && !f.endsWith('.d.ts'))
178
+ .sort()
179
+ for (const file of files) await import(join(dir, file))
180
+ return files.length
181
+ }
package/src/index.ts CHANGED
@@ -88,6 +88,7 @@ export {
88
88
  type EventInstance,
89
89
  type ListenerOptions,
90
90
  listener,
91
+ loadListeners,
91
92
  type QueuedListenerDispatcher,
92
93
  registeredListeners,
93
94
  } from './events'
@@ -124,6 +125,7 @@ export {
124
125
  } from './mcp'
125
126
  export { Money, minorDigits } from './money'
126
127
  export { type ProviderClass, type ProviderHooks, ServiceProvider } from './provider'
128
+ export { type StateChange, type StateHook, type StateMachine, type StatesOptions, states } from './states'
127
129
  export {
128
130
  type Attributes,
129
131
  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
+ }