@cslug/core 0.0.0-stage → 0.2.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/README.md CHANGED
@@ -1,3 +1,9 @@
1
- # Temporary Holding Version
1
+ # @cslug/core
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
+ The application, the container with standard `@inject(A, B)`, service providers, the ambient context, config and
4
+ env validation, typed errors, `Clock`, `Money`, events, the logger, i18n, and the `Cache`/`Lock`/`RateLimiter`/
5
+ `SessionStore` contracts with in-memory drivers.
6
+
7
+ Part of [cslug](https://github.com/cslugts/cslug). Docs: [docs/README.md](docs/README.md), [docs/api.md](docs/api.md),
8
+ guides [02](../../guides/02-container-and-di.md), [03](../../guides/03-service-providers.md),
9
+ [04](../../guides/04-configuration.md), [13](../../guides/13-events.md), [16](../../guides/16-i18n.md).
package/docs/README.md ADDED
@@ -0,0 +1,31 @@
1
+ # @cslug/core
2
+
3
+ The application, the container with `@inject`, service providers, the ambient context, config and env, typed
4
+ errors, `Clock`, `Money`, events, the logger, i18n, and the `Cache`/`Lock`/`RateLimiter`/`SessionStore` contracts
5
+ with in-memory drivers.
6
+
7
+ ```ts
8
+ import { Application, inject, ServiceProvider } from '@cslug/core'
9
+
10
+ abstract class PaymentGateway {
11
+ abstract createHold(input: HoldInput): Promise<Hold>
12
+ }
13
+
14
+ @inject(BookingRepository, PaymentGateway) // checked against the constructor by tsc
15
+ export class EscrowService {
16
+ constructor(private bookings: BookingRepository, private gateway: PaymentGateway) {}
17
+ }
18
+
19
+ export class PaymentServiceProvider extends ServiceProvider {
20
+ static dependsOn = [DatabaseProvider]
21
+ register() {
22
+ this.app.singleton(PaymentGateway, MangopayGateway)
23
+ }
24
+ }
25
+
26
+ const app = await new Application({ root: import.meta.dir }).useProviders([DatabaseProvider, PaymentServiceProvider]).start()
27
+ const escrow = app.createScope().resolve(EscrowService)
28
+ ```
29
+
30
+ - Full reference: [api.md](./api.md)
31
+ - Guides: [02 Container & `@inject`](../../../guides/02-container-and-di.md), [03 Service providers](../../../guides/03-service-providers.md)
package/docs/api.md ADDED
@@ -0,0 +1,197 @@
1
+ # @cslug/core: API
2
+
3
+ ## `@inject`
4
+
5
+ | | |
6
+ |---|---|
7
+ | `@inject(A, B, …)` | The class is buildable by the container; the list names its constructor dependencies in order, and `tsc` checks the list against the constructor. Lifetime: **scoped** |
8
+ | `@inject.singleton(…)` | One instance per application |
9
+ | `@inject.transient(…)` | A new instance on every resolve |
10
+ | `@inject()` | No dependencies |
11
+
12
+ Registrations are inherited: a subclass without its own `@inject` uses its parent's. Standard (TC39) decorators;
13
+ no `experimentalDecorators`, no metadata.
14
+
15
+ ## Tokens
16
+
17
+ | | |
18
+ |---|---|
19
+ | a class / abstract class | `PaymentGateway`: abstract classes are the "interfaces" |
20
+ | `token<T>(name)` | `InjectionToken<T>` for values: `const COMMISSION = token<number>('payments.commission_percent')` |
21
+ | `Token<T>`, `Resolved<K>`, `Class<T>` | Types |
22
+
23
+ ## `Container`
24
+
25
+ | Method | |
26
+ |---|---|
27
+ | `singleton(token, impl?)` | `impl` = a class (built with its `@inject` deps) or a factory `(container) => value`; omitted = the token itself |
28
+ | `scoped(token, impl?)` | One per scope |
29
+ | `bind(token, impl)` | Transient |
30
+ | `instance(token, value)` | An existing value |
31
+ | `resolve(token)` | A binding, else an `@inject` class, else `BindingNotFoundError` |
32
+ | `has(token)` | Bound here or in a parent, or an `@inject` class |
33
+ | `when(Consumer).needs(token).give(impl)` | Contextual binding |
34
+ | `tag(tokens, name)` / `tagged(name)` | Collections |
35
+ | `swap(token, value)` / `restoreSwaps()` | Test overrides (on the root) |
36
+ | `createScope()` | Child container for one request, job or command |
37
+ | `dispose()` | Disposes the scope's own instances (`Symbol.asyncDispose` / `Symbol.dispose`), newest first |
38
+ | `build(Class)` | Construct a class with its `@inject` deps, without caching |
39
+
40
+ Rules: singletons are cached on the container that owns the binding (normally the root) and get their
41
+ dependencies from it, never from a request scope. A singleton that depends on a scoped class throws
42
+ `ScopeViolationError`. A cycle throws `CircularDependencyError`, also through factories.
43
+
44
+ ## `ServiceProvider`
45
+
46
+ ```ts
47
+ export class XProvider extends ServiceProvider /* implements ProviderHooks */ {
48
+ static dependsOn = [OtherProvider] // optional
49
+ register() {} // bind only; resolving here throws ProviderError
50
+ async boot() {} // after every register(), in dependency order
51
+ async shutdown() {} // reverse boot order
52
+ }
53
+ ```
54
+
55
+ The hooks and `dependsOn` are not declared on the base class, so apps using `noImplicitOverride` don't need
56
+ `override`. `ProviderHooks` gives the hook signatures for `implements`.
57
+
58
+ ## `Application` (extends `Container`)
59
+
60
+ | | |
61
+ |---|---|
62
+ | `new Application({ root?, configs? })` | `rootDir`, `configs`; the app is bound to itself (`@inject(Application)`) |
63
+ | `useProviders(list)` | Before `start()` |
64
+ | `start({ signals? })` | `register()` all, then `boot()` in order. On a failed boot: shuts down the booted ones in reverse, then throws `ProviderError` with the original error as `cause`. `signals: true` installs SIGTERM/SIGINT → `shutdown()` → exit |
65
+ | `shutdown()` | Reverse order; idempotent; collects errors into an `AggregateError` |
66
+ | `isRunning` | |
67
+ | `sortProviders(list)` | The boot order (Kahn; listed order kept where dependencies allow). Throws on duplicates, providers missing from the list, and cycles (with the path) |
68
+
69
+ ## Ambient context
70
+
71
+ | | |
72
+ |---|---|
73
+ | `runInContext({ app, scope, … }, fn)` | Kernels and the test kit run each unit of work in a context |
74
+ | `currentContext()` | The context, or undefined |
75
+ | `currentApp()` | The context's app, else the last started app |
76
+ | `resolve(token)` | From the container building the current object (field initialisers), else the context scope, else the current app |
77
+
78
+ ## Errors
79
+
80
+ All extend `CslugError` (`code`, `message`): `BindingNotFoundError` (`container.binding_not_found`),
81
+ `CircularDependencyError`, `ScopeViolationError`, `ProviderError` (`app.provider`).
82
+
83
+ ## Config and env
84
+
85
+ | | |
86
+ |---|---|
87
+ | `defineEnv(shape, source = process.env)` | Validates immediately with `v` schemas; typed, frozen result. Empty values count as missing. Throws `EnvError` listing **every** problem (`name message`), with hints (`APP_KEY` → `cslug key:generate`). Secret values are never printed |
88
+ | `secretKeys(shape)` | Names of `v.secret()` variables, for redaction |
89
+ | `defineConfig(object)` | A config file's default export; returns the object, typed |
90
+ | `config(path)` | Typed read from the current app: `config('payments.commissionPercent')`. Paths and value types come from the app's `Config` (see below). Arrays are leaves |
91
+ | `app.config(path)` | Untyped read (`unknown` by default), used by packages |
92
+ | `app.setConfig(path, value)` | Override before `start()` (the test kit); config is deep-frozen at start |
93
+ | `Config`, `Typed<T>`, `ConfigPath<T>`, `ConfigValue<T, P>` | `declare module '@cslug/core' { interface Config extends Typed<typeof configs> {} }` |
94
+
95
+ `v` and `ValidationError` are re-exported from `@cslug/validation`.
96
+
97
+ ## Errors
98
+
99
+ | Class | Status | Code |
100
+ |---|---|---|
101
+ | `CslugError(code, message)` | — | base of everything cslug throws |
102
+ | `AppError(code, message?, { status?, params?, cause? })` | 500 by default | base for errors shown to users; `code` is the translation key |
103
+ | `HttpError` | — | base for the classes below |
104
+ | `NotFoundError(resource?, id?)` | 404 | `<resource>.not_found` |
105
+ | `ForbiddenError(code?, message?)` | 403 | `auth.forbidden` |
106
+ | `UnauthorizedError(code?, message?)` | 401 | `auth.unauthenticated` |
107
+ | `ConflictError(code, params?, message?)` | 409 | yours, e.g. `booking.invalid_transition` |
108
+ | `BadRequestError(code?, message?)` | 400 | `http.bad_request` |
109
+ | `TooManyRequestsError(retryAfter?)` | 429 | `http.too_many_requests` |
110
+ | `ValidationError` | 422 | `validation.failed` (from `@cslug/validation`) |
111
+
112
+ ## Clock
113
+
114
+ Bound as a singleton; its time zone is `config('app.timezone')` (default UTC). At `start()` the app points
115
+ `v.date().future()/past()` at it.
116
+
117
+ | | |
118
+ |---|---|
119
+ | `now()` | `Date` |
120
+ | `today(offsetDays = 0, tz?)` | `'YYYY-MM-DD'` in the time zone |
121
+ | `add(duration)` / `subtract(duration)` | `Date` relative to now |
122
+ | `atLocal(date, 'HH:mm', tz?)` | The instant of a local wall-clock time; DST-safe |
123
+ | `FakeClock(tz?, start?)` | For tests: frozen time; `travelTo(instant)`, `advance(duration)`, `freeze()` |
124
+
125
+ `parseDuration('1h30m')` → ms. Units: `ms s m h d w`. Invalid input throws (never a silent 0).
126
+
127
+ ## Money
128
+
129
+ Immutable; integer minor units (`bigint`) + ISO 4217 currency; no floating point anywhere.
130
+
131
+ | | |
132
+ |---|---|
133
+ | `Money.of(amount, currency)` | Amount: bigint, safe integer, or digit string. Currency checked against Intl's list |
134
+ | `Money.from({ amount, currency })` / `Money.zero(c)` / `Money.sum(list, c?)` | |
135
+ | `add`, `subtract` | Same currency only (`money.currency_mismatch`) |
136
+ | `multiply(factor)` / `percent(p)` | Decimal factors (`'1.005'`, `2.5`); rounded **half away from zero** to the minor unit |
137
+ | `allocate([30, 40, 30])` | Splits without losing a cent; the remainder goes to the first shares |
138
+ | `negate`, `isZero`, `isPositive`, `isNegative`, `equals`, `compare` | |
139
+ | `toDecimal()` | `'2200.00'` (digits from Intl: EUR 2, JPY 0, KWD 3) |
140
+ | `format(locale, options?)` | `2 200,00 €` (fr), `€2,200.00` (en); exact for any size |
141
+ | `toJSON()` | `{ amount: '220000', currency: 'EUR' }` |
142
+ | `minorDigits(currency)` | |
143
+
144
+ ## Events
145
+
146
+ | | |
147
+ |---|---|
148
+ | `class X extends Event<Payload>('dot.case_name') {}` | Define an event. `X['payload']` is the payload type |
149
+ | `X.emit(payload)` | On the current app's `EventBus`. Closures, then class listeners, in order. A synchronous listener's error rejects `emit` (so the emitter's transaction can roll back) |
150
+ | `X.on(fn)` | Function listener; returns an unsubscribe function |
151
+ | `@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 |
152
+ | 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 |
153
+ | `afterCommit(fn)` | Run once the current transaction commits; outside a transaction, soon after the current task. `@cslug/database` provides the hook (`TransactionHooks`) |
154
+ | `registeredListeners()` | For `cslug events` |
155
+
156
+ ## Logger
157
+
158
+ Bound as a singleton from `config('log')` (`{ level?, format?, redact? }`); inject `Logger`.
159
+
160
+ | | |
161
+ |---|---|
162
+ | `debug/info/warn/error(message, fields?)` | One JSON line (`time`, `level`, `msg`, fields); `format: 'pretty'` for terminals |
163
+ | `child(fields)` | Adds fields to every entry |
164
+ | context fields | `requestId`, `jobId`, `userId` from the ambient context, automatically |
165
+ | redaction | Keys containing `password`, `secret`, `token`, `authorization`, `cookie`, `apikey`, `api_key`, `cardnumber`, `cvv` (case-insensitive, any depth), plus `redact` (e.g. `secretKeys(envShape)`) |
166
+ | safe serialisation | bigint → string, Date → ISO, `toJSON()` (Money), errors with `code`/`status`/`cause`/`stack`, cycles cut |
167
+ | `Logger.null()` | Writes nothing |
168
+
169
+ ## i18n
170
+
171
+ `Translator` is bound from `resources/lang/` and `config('i18n')` (`{ locales, default, fallback }`).
172
+ Files: `<locale>.json`, and `<locale>/<namespace>.json` merged under the file name.
173
+
174
+ | | |
175
+ |---|---|
176
+ | `t(key, params?, locale?)` | In the current locale (the context's `locale`, else the default). Missing key → the key |
177
+ | messages | ICU subset: `{name}`, `{count, plural, =0 {…} one {# x} other {# xs}}`, `{gender, select, female {…} other {…}}`, nesting |
178
+ | fallback | `chain('it')` → `['it', 'en']` from `fallback`, then the default |
179
+ | `withLocale(locale, fn)` | Run with another locale (mail to a recipient, a job for a user) |
180
+ | `currentLocale()` | |
181
+ | `tr(value)` | Pick a locale from translated content (`{ fr, en, it }`), with the fallback chain |
182
+ | `validationTranslator(locale?)` | Pass to `ValidationError.messages(…)`; built-in English when a key is missing |
183
+ | `formatMoney(amount \| Money, currency?, locale?)` | |
184
+ | `formatDate(value, style?, { tz?, locale? })` | `'YYYY-MM-DD'` shown as is; a `Date` in `tz` (default `config('app.timezone')`). Styles: `short`, `medium`, `long`, `full`, or Intl options |
185
+ | `Translator`: `translate`, `has`, `keys`, `add`, `fromDirectory` | |
186
+
187
+ ## Contracts (in-memory drivers by default; `@cslug/redis` replaces them)
188
+
189
+ | Contract | Methods |
190
+ |---|---|
191
+ | `Cache` | `get`, `set(key, value, ttl?)`, `has`, `forget`, `increment`/`decrement`, `remember(key, ttl, fn)` (concurrent misses run `fn` once), `flexible(key, [fresh, stale], fn)`, `tags([...])` (+ `flush()`), `flush()` |
192
+ | `Lock` | `acquire(key, ttl)` → handle or null; `run(key, { ttl, wait? }, fn)`; released only by its owner; expires; `LockTimeoutError` |
193
+ | `RateLimiter` | `hit(key, '5/min')` → `{ allowed, remaining, retryAfter }`; `attempt(key, limit, fn)` → boolean; `enforce(key, limit)` → throws `TooManyRequestsError`; `reset(key)`. `parseRate('3/10min')` |
194
+ | `SessionStore` | `read(id)`, `write(id, data, ttl)`, `destroy(id)` |
195
+
196
+ Memory drivers: `MemoryCache` (values cloned, bigint and Date supported), `MemoryLock`, `MemoryRateLimiter`
197
+ (sliding window), `MemorySessionStore`. Each is one per application.
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@cslug/core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Application, container and @inject, providers, config, events, logger, errors, context, Clock, Money, i18n, contracts.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/cslugts/cslug.git",
10
+ "directory": "packages/core"
11
+ },
12
+ "homepage": "https://github.com/cslugts/cslug/tree/main/packages/core",
13
+ "keywords": [
14
+ "cslug",
15
+ "bun",
16
+ "framework"
17
+ ],
18
+ "exports": {
19
+ ".": "./src/index.ts"
20
+ },
21
+ "files": [
22
+ "src",
23
+ "docs",
24
+ "stubs",
25
+ "README.md"
26
+ ],
27
+ "engines": {
28
+ "bun": ">=1.3.14"
29
+ },
30
+ "peerDependencies": {
31
+ "@cslug/validation": "0.2.0"
32
+ }
33
+ }
@@ -0,0 +1,237 @@
1
+ import { configure as configureValidation } from '@cslug/validation'
2
+ import { Clock } from './clock'
3
+ import { ConsoleIO } from './command'
4
+ import { deepFreeze, getPath, setPath } from './config'
5
+ import { Container } from './container'
6
+ import { setDefaultApp } from './context'
7
+ import {
8
+ Cache,
9
+ Lock,
10
+ MemoryCache,
11
+ MemoryLock,
12
+ MemoryRateLimiter,
13
+ MemorySessionStore,
14
+ RateLimiter,
15
+ SessionStore,
16
+ } from './contracts'
17
+ import { ProviderError } from './errors'
18
+ import { EventBus } from './events'
19
+ import { type I18nConfig, Translator } from './i18n'
20
+ import { Logger, type LoggerOptions } from './logger'
21
+ import { dependenciesOf, type ProviderClass, type ProviderHooks, type ServiceProvider } from './provider'
22
+
23
+ export type ApplicationOptions = {
24
+ /** The app's root directory (where bootstrap/, config/, routes/ live). */
25
+ root?: string
26
+ /** Config objects, by section (config/index.ts → `configs`). */
27
+ configs?: Record<string, unknown>
28
+ }
29
+
30
+ type State = 'created' | 'registered' | 'starting' | 'running' | 'stopping' | 'stopped'
31
+
32
+ /**
33
+ * The application: the root container plus provider orchestration. Built in `bootstrap/app.ts`, started by a
34
+ * kernel (`cslug serve`, `queue:work`, …) or by the test kit.
35
+ */
36
+ export class Application extends Container {
37
+ /** The app's root directory. */
38
+ readonly rootDir: string
39
+ protected _configs: Record<string, unknown>
40
+ protected providerClasses: ProviderClass[] = []
41
+ protected booted: (ServiceProvider & ProviderHooks)[] = []
42
+ protected state: State = 'created'
43
+ private signalHandler?: () => void
44
+
45
+ constructor(options: ApplicationOptions = {}) {
46
+ super()
47
+ this.rootDir = options.root ?? process.cwd()
48
+ this._configs = options.configs ?? {}
49
+ this.instance(Application, this)
50
+ this.singleton(Clock, () => new Clock((this.config('app.timezone') as string | undefined) ?? 'UTC'))
51
+ this.singleton(Logger, () => new Logger((this.config('log') as LoggerOptions | undefined) ?? {}))
52
+ this.singleton(EventBus, (c) => new EventBus(this, c.resolve(Logger)))
53
+ this.singleton(Translator, () =>
54
+ Translator.fromDirectory(`${this.rootDir}/resources/lang`, (this.config('i18n') as I18nConfig | undefined) ?? {}),
55
+ )
56
+ // in-memory drivers; @cslug/redis replaces them
57
+ this.singleton(Cache, () => new MemoryCache())
58
+ this.singleton(Lock, () => new MemoryLock())
59
+ this.singleton(RateLimiter, () => new MemoryRateLimiter())
60
+ this.singleton(SessionStore, () => new MemorySessionStore())
61
+ this.singleton(ConsoleIO, () => new ConsoleIO())
62
+ }
63
+
64
+ /** All config sections. Read-only once the app has started. */
65
+ get configs(): Readonly<Record<string, unknown>> {
66
+ return this._configs
67
+ }
68
+
69
+ /** Config at a dotted path (`'payments.stages'`), or undefined. App code uses the typed `config()` helper. */
70
+ config<T = unknown>(path: string): T {
71
+ return getPath(this._configs, path) as T
72
+ }
73
+
74
+ /**
75
+ * Override a config value before start (the test kit does this: `testApp({ config: { 'payments.driver': 'fake' } })`).
76
+ * After start, config is frozen.
77
+ */
78
+ setConfig(path: string, value: unknown): this {
79
+ if (this.state !== 'created') throw new ProviderError(`Config is read-only after start (tried to set "${path}").`)
80
+ this._configs = setPath(this._configs, path, value)
81
+ return this
82
+ }
83
+
84
+ get isRunning(): boolean {
85
+ return this.state === 'running'
86
+ }
87
+
88
+ /** The providers to run, from `bootstrap/providers.ts`. Order matters only where `dependsOn` doesn't decide. */
89
+ useProviders(providers: readonly ProviderClass[]): this {
90
+ if (this.state !== 'created') throw new ProviderError('useProviders() must be called before start().')
91
+ this.providerClasses = [...providers]
92
+ return this
93
+ }
94
+
95
+ /**
96
+ * Register every provider, then boot them in dependency order. If a boot() throws, providers that already
97
+ * booted are shut down in reverse order and the error is rethrown.
98
+ */
99
+ /**
100
+ * Run every provider's `register()` without booting (no connections). The CLI does this to list commands and
101
+ * to run those with `static boot = false`; `start()` does it if needed.
102
+ */
103
+ registerProviders(): this {
104
+ if (this.state !== 'created') return this
105
+ deepFreeze(this._configs)
106
+ // dates validated with v.date().future() follow the app clock and time zone
107
+ configureValidation({ today: () => this.resolve(Clock).today() })
108
+ this.instances_ = sortProviders(this.providerClasses).map((P) => new P(this) as ServiceProvider & ProviderHooks)
109
+ this.registering = true
110
+ try {
111
+ for (const p of this.instances_) p.register?.()
112
+ } finally {
113
+ this.registering = false
114
+ }
115
+ this.state = 'registered'
116
+ setDefaultApp(this)
117
+ return this
118
+ }
119
+ private instances_: (ServiceProvider & ProviderHooks)[] = []
120
+
121
+ async start(options: { signals?: boolean } = {}): Promise<this> {
122
+ this.registerProviders()
123
+ if (this.state !== 'registered') throw new ProviderError(`Cannot start an application that is ${this.state}.`)
124
+ this.state = 'starting'
125
+ for (const p of this.instances_) {
126
+ try {
127
+ await p.boot?.()
128
+ this.booted.push(p)
129
+ } catch (error) {
130
+ const rollback = await this.shutdownBooted()
131
+ this.state = 'stopped'
132
+ throw new ProviderError(
133
+ `${p.constructor.name}.boot() failed: ${error instanceof Error ? error.message : String(error)}${
134
+ rollback.length ? ` (and ${rollback.length} provider(s) failed to shut down during rollback)` : ''
135
+ }`,
136
+ { cause: error },
137
+ )
138
+ }
139
+ }
140
+ this.state = 'running'
141
+ setDefaultApp(this)
142
+ if (options.signals) this.handleSignals()
143
+ return this
144
+ }
145
+
146
+ /** Shut providers down in reverse boot order. Safe to call twice. Errors are collected, then thrown together. */
147
+ async shutdown(): Promise<void> {
148
+ if (this.state === 'stopped' || this.state === 'stopping' || this.state === 'created') return
149
+ if (this.state === 'registered') {
150
+ this.state = 'stopped'
151
+ await this.dispose()
152
+ setDefaultApp(undefined)
153
+ return
154
+ }
155
+ this.state = 'stopping'
156
+ if (this.signalHandler) {
157
+ process.off('SIGTERM', this.signalHandler)
158
+ process.off('SIGINT', this.signalHandler)
159
+ }
160
+ const errors = await this.shutdownBooted()
161
+ await this.dispose()
162
+ this.state = 'stopped'
163
+ setDefaultApp(undefined)
164
+ if (errors.length) throw new AggregateError(errors, `${errors.length} provider(s) failed to shut down`)
165
+ }
166
+
167
+ protected async shutdownBooted(): Promise<unknown[]> {
168
+ const errors: unknown[] = []
169
+ for (const p of [...this.booted].reverse()) {
170
+ try {
171
+ await p.shutdown?.()
172
+ } catch (e) {
173
+ errors.push(e)
174
+ }
175
+ }
176
+ this.booted = []
177
+ return errors
178
+ }
179
+
180
+ /** On SIGTERM/SIGINT: shut down, then exit (0 if clean, 1 otherwise). Kernels enable this. */
181
+ handleSignals(): void {
182
+ if (this.signalHandler) return
183
+ this.signalHandler = () => {
184
+ this.shutdown().then(
185
+ () => process.exit(0),
186
+ (e) => {
187
+ console.error(e)
188
+ process.exit(1)
189
+ },
190
+ )
191
+ }
192
+ process.once('SIGTERM', this.signalHandler)
193
+ process.once('SIGINT', this.signalHandler)
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Topological order by `dependsOn`, keeping the listed order where dependencies don't decide (Kahn's algorithm).
199
+ * Throws on duplicates, dependencies missing from the list, and cycles.
200
+ */
201
+ export function sortProviders(providers: readonly ProviderClass[]): ProviderClass[] {
202
+ const seen = new Set<ProviderClass>()
203
+ for (const p of providers) {
204
+ if (seen.has(p)) throw new ProviderError(`${p.name} is listed twice in the providers.`)
205
+ seen.add(p)
206
+ }
207
+ for (const p of providers) {
208
+ for (const d of dependenciesOf(p)) {
209
+ if (!seen.has(d))
210
+ throw new ProviderError(
211
+ `${p.name} depends on ${d.name}, which is not in the provider list (bootstrap/providers.ts).`,
212
+ )
213
+ }
214
+ }
215
+ const order: ProviderClass[] = []
216
+ const done = new Set<ProviderClass>()
217
+ const remaining = [...providers]
218
+ while (remaining.length) {
219
+ const i = remaining.findIndex((p) => dependenciesOf(p).every((d) => done.has(d)))
220
+ if (i === -1) throw new ProviderError(`Circular provider dependencies: ${describeCycle(remaining)}.`)
221
+ const [next] = remaining.splice(i, 1) as [ProviderClass]
222
+ order.push(next)
223
+ done.add(next)
224
+ }
225
+ return order
226
+ }
227
+
228
+ function describeCycle(remaining: ProviderClass[]): string {
229
+ const left = new Set(remaining)
230
+ let current = remaining[0] as ProviderClass
231
+ const path: ProviderClass[] = []
232
+ while (!path.includes(current)) {
233
+ path.push(current)
234
+ current = dependenciesOf(current).find((d) => left.has(d)) ?? current
235
+ }
236
+ return [...path.slice(path.indexOf(current)), current].map((p) => p.name).join(' → ')
237
+ }
package/src/clock.ts ADDED
@@ -0,0 +1,144 @@
1
+ import { type Duration, parseDuration } from './duration'
2
+ import { CslugError } from './errors'
3
+
4
+ const dateFormatters = new Map<string, Intl.DateTimeFormat>()
5
+ const partsFormatters = new Map<string, Intl.DateTimeFormat>()
6
+
7
+ /** `'YYYY-MM-DD'` of an instant in a time zone. */
8
+ function dateIn(instant: Date, timezone: string): string {
9
+ let f = dateFormatters.get(timezone)
10
+ if (!f) {
11
+ f = new Intl.DateTimeFormat('en-CA', { timeZone: timezone, year: 'numeric', month: '2-digit', day: '2-digit' })
12
+ dateFormatters.set(timezone, f)
13
+ }
14
+ return f.format(instant)
15
+ }
16
+
17
+ /** Offset (ms) of a time zone at an instant: local wall time minus UTC. */
18
+ function offsetAt(instant: number, timezone: string): number {
19
+ let f = partsFormatters.get(timezone)
20
+ if (!f) {
21
+ f = new Intl.DateTimeFormat('en-US', {
22
+ timeZone: timezone,
23
+ hourCycle: 'h23',
24
+ year: 'numeric',
25
+ month: 'numeric',
26
+ day: 'numeric',
27
+ hour: 'numeric',
28
+ minute: 'numeric',
29
+ second: 'numeric',
30
+ })
31
+ partsFormatters.set(timezone, f)
32
+ }
33
+ const p = Object.fromEntries(f.formatToParts(instant).map((x) => [x.type, Number(x.value)]))
34
+ const wall = Date.UTC(
35
+ p.year as number,
36
+ (p.month as number) - 1,
37
+ p.day as number,
38
+ p.hour as number,
39
+ p.minute as number,
40
+ p.second as number,
41
+ )
42
+ return wall - (instant - (instant % 1000))
43
+ }
44
+
45
+ /**
46
+ * The time source for domain code. Inject it instead of calling `new Date()`, so tests control time.
47
+ * The default time zone comes from `config/app.ts` → `timezone`.
48
+ */
49
+ export class Clock {
50
+ constructor(readonly timezone: string = 'UTC') {
51
+ try {
52
+ new Intl.DateTimeFormat('en', { timeZone: timezone })
53
+ } catch {
54
+ throw new CslugError(
55
+ 'clock.invalid_timezone',
56
+ `Unknown time zone "${timezone}" (use an IANA name such as "Indian/Antananarivo")`,
57
+ )
58
+ }
59
+ }
60
+
61
+ /** The current instant. */
62
+ now(): Date {
63
+ return new Date()
64
+ }
65
+
66
+ /** Today's date as `'YYYY-MM-DD'` in a time zone, optionally shifted by whole days. */
67
+ today(offsetDays = 0, timezone: string = this.timezone): string {
68
+ const local = dateIn(this.now(), timezone)
69
+ if (!offsetDays) return local
70
+ const d = new Date(`${local}T00:00:00Z`)
71
+ d.setUTCDate(d.getUTCDate() + offsetDays)
72
+ return d.toISOString().slice(0, 10)
73
+ }
74
+
75
+ /** Now plus a duration (`'2h'`, `'3d'`). */
76
+ add(duration: Duration): Date {
77
+ return new Date(this.now().getTime() + parseDuration(duration))
78
+ }
79
+
80
+ /** Now minus a duration (`'90d'`). */
81
+ subtract(duration: Duration): Date {
82
+ return new Date(this.now().getTime() - parseDuration(duration))
83
+ }
84
+
85
+ /**
86
+ * The instant of a local wall-clock time on a date in a time zone:
87
+ * `atLocal('2027-05-14', '07:00', 'Indian/Antananarivo')` → 04:00 UTC. Handles daylight saving time.
88
+ */
89
+ atLocal(date: string, time: string, timezone: string = this.timezone): Date {
90
+ const d = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date)
91
+ const t = /^(\d{2}):(\d{2})(?::(\d{2}))?$/.exec(time)
92
+ if (!d || !t)
93
+ throw new CslugError(
94
+ 'clock.invalid_input',
95
+ `atLocal() expects 'YYYY-MM-DD' and 'HH:mm', got '${date}', '${time}'`,
96
+ )
97
+ const wall = Date.UTC(
98
+ +(d[1] as string),
99
+ +(d[2] as string) - 1,
100
+ +(d[3] as string),
101
+ +(t[1] as string),
102
+ +(t[2] as string),
103
+ +(t[3] ?? 0),
104
+ )
105
+ // first guess with the offset at the wall time, then correct once with the offset at the result (DST edges)
106
+ let instant = wall - offsetAt(wall, timezone)
107
+ instant = wall - offsetAt(instant, timezone)
108
+ return new Date(instant)
109
+ }
110
+ }
111
+
112
+ /**
113
+ * A Clock for tests. Time is frozen: it moves only when you move it.
114
+ * `travelTo('2027-05-15T05:00:00Z')`, `advance('3d')`, `freeze()` (freeze at the real current time).
115
+ */
116
+ export class FakeClock extends Clock {
117
+ private current: number
118
+
119
+ constructor(timezone?: string, start: Date | string | number = Date.now()) {
120
+ super(timezone)
121
+ this.current = new Date(start).getTime()
122
+ }
123
+
124
+ override now(): Date {
125
+ return new Date(this.current)
126
+ }
127
+
128
+ travelTo(instant: Date | string | number): this {
129
+ const t = new Date(instant).getTime()
130
+ if (Number.isNaN(t)) throw new CslugError('clock.invalid_input', `travelTo(): invalid date ${String(instant)}`)
131
+ this.current = t
132
+ return this
133
+ }
134
+
135
+ advance(duration: Duration): this {
136
+ this.current += parseDuration(duration)
137
+ return this
138
+ }
139
+
140
+ freeze(): this {
141
+ this.current = Date.now()
142
+ return this
143
+ }
144
+ }