ihsm 0.0.26 → 0.1.21

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.
Files changed (103) hide show
  1. package/README.md +105 -113
  2. package/lib/cjs/index.d.ts +8 -1394
  3. package/lib/cjs/index.js +65 -764
  4. package/lib/cjs/index.js.map +1 -1
  5. package/lib/cjs/internal/console-instrumentation.d.ts +34 -0
  6. package/lib/cjs/internal/console-instrumentation.js +71 -0
  7. package/lib/cjs/internal/console-instrumentation.js.map +1 -0
  8. package/lib/cjs/internal/identity.d.ts +16 -0
  9. package/lib/cjs/internal/identity.js +170 -0
  10. package/lib/cjs/internal/identity.js.map +1 -0
  11. package/lib/cjs/internal/instrumentation.d.ts +47 -0
  12. package/lib/cjs/internal/instrumentation.js +201 -0
  13. package/lib/cjs/internal/instrumentation.js.map +1 -0
  14. package/lib/cjs/internal/runtime.d.ts +376 -0
  15. package/lib/cjs/internal/runtime.js +2530 -0
  16. package/lib/cjs/internal/runtime.js.map +1 -0
  17. package/lib/cjs/internal/types.d.ts +515 -0
  18. package/lib/cjs/internal/types.js +9 -0
  19. package/lib/cjs/internal/types.js.map +1 -0
  20. package/lib/cjs/test-only.d.ts +5 -0
  21. package/lib/cjs/test-only.js +21 -0
  22. package/lib/cjs/test-only.js.map +1 -0
  23. package/lib/cjs/testing.d.ts +120 -88
  24. package/lib/cjs/testing.js +126 -38
  25. package/lib/cjs/testing.js.map +1 -1
  26. package/lib/cjs/transition-routines.d.ts +3 -0
  27. package/lib/cjs/transition-routines.js +11 -0
  28. package/lib/cjs/transition-routines.js.map +1 -0
  29. package/lib/cjs/types.d.ts +5 -0
  30. package/lib/cjs/{internal/defs.private.js → types.js} +1 -1
  31. package/lib/cjs/types.js.map +1 -0
  32. package/lib/esm/index.d.ts +8 -1394
  33. package/lib/esm/index.js +5 -742
  34. package/lib/esm/index.js.map +1 -1
  35. package/lib/esm/internal/console-instrumentation.d.ts +34 -0
  36. package/lib/esm/internal/console-instrumentation.js +68 -0
  37. package/lib/esm/internal/console-instrumentation.js.map +1 -0
  38. package/lib/esm/internal/identity.d.ts +16 -0
  39. package/lib/esm/internal/identity.js +159 -0
  40. package/lib/esm/internal/identity.js.map +1 -0
  41. package/lib/esm/internal/instrumentation.d.ts +47 -0
  42. package/lib/esm/internal/instrumentation.js +178 -0
  43. package/lib/esm/internal/instrumentation.js.map +1 -0
  44. package/lib/esm/internal/runtime.d.ts +376 -0
  45. package/lib/esm/internal/runtime.js +2462 -0
  46. package/lib/esm/internal/runtime.js.map +1 -0
  47. package/lib/esm/internal/types.d.ts +515 -0
  48. package/lib/esm/internal/types.js +6 -0
  49. package/lib/esm/internal/types.js.map +1 -0
  50. package/lib/esm/test-only.d.ts +5 -0
  51. package/lib/esm/test-only.js +15 -0
  52. package/lib/esm/test-only.js.map +1 -0
  53. package/lib/esm/testing.d.ts +120 -88
  54. package/lib/esm/testing.js +125 -38
  55. package/lib/esm/testing.js.map +1 -1
  56. package/lib/esm/transition-routines.d.ts +3 -0
  57. package/lib/esm/transition-routines.js +3 -0
  58. package/lib/esm/transition-routines.js.map +1 -0
  59. package/lib/esm/types.d.ts +5 -0
  60. package/lib/esm/types.js +2 -0
  61. package/lib/esm/types.js.map +1 -0
  62. package/package.json +22 -4
  63. package/lib/cjs/internal/defs.private.d.ts +0 -41
  64. package/lib/cjs/internal/defs.private.js.map +0 -1
  65. package/lib/cjs/internal/dispatch.debug.d.ts +0 -4
  66. package/lib/cjs/internal/dispatch.debug.js +0 -332
  67. package/lib/cjs/internal/dispatch.debug.js.map +0 -1
  68. package/lib/cjs/internal/dispatch.production.d.ts +0 -6
  69. package/lib/cjs/internal/dispatch.production.js +0 -241
  70. package/lib/cjs/internal/dispatch.production.js.map +0 -1
  71. package/lib/cjs/internal/dispatch.trace.d.ts +0 -4
  72. package/lib/cjs/internal/dispatch.trace.js +0 -418
  73. package/lib/cjs/internal/dispatch.trace.js.map +0 -1
  74. package/lib/cjs/internal/hsm.d.ts +0 -60
  75. package/lib/cjs/internal/hsm.js +0 -215
  76. package/lib/cjs/internal/hsm.js.map +0 -1
  77. package/lib/cjs/internal/lookup.d.ts +0 -15
  78. package/lib/cjs/internal/lookup.js +0 -32
  79. package/lib/cjs/internal/lookup.js.map +0 -1
  80. package/lib/cjs/internal/utils.d.ts +0 -26
  81. package/lib/cjs/internal/utils.js +0 -63
  82. package/lib/cjs/internal/utils.js.map +0 -1
  83. package/lib/esm/internal/defs.private.d.ts +0 -41
  84. package/lib/esm/internal/defs.private.js +0 -2
  85. package/lib/esm/internal/defs.private.js.map +0 -1
  86. package/lib/esm/internal/dispatch.debug.d.ts +0 -4
  87. package/lib/esm/internal/dispatch.debug.js +0 -328
  88. package/lib/esm/internal/dispatch.debug.js.map +0 -1
  89. package/lib/esm/internal/dispatch.production.d.ts +0 -6
  90. package/lib/esm/internal/dispatch.production.js +0 -237
  91. package/lib/esm/internal/dispatch.production.js.map +0 -1
  92. package/lib/esm/internal/dispatch.trace.d.ts +0 -4
  93. package/lib/esm/internal/dispatch.trace.js +0 -414
  94. package/lib/esm/internal/dispatch.trace.js.map +0 -1
  95. package/lib/esm/internal/hsm.d.ts +0 -60
  96. package/lib/esm/internal/hsm.js +0 -211
  97. package/lib/esm/internal/hsm.js.map +0 -1
  98. package/lib/esm/internal/lookup.d.ts +0 -15
  99. package/lib/esm/internal/lookup.js +0 -29
  100. package/lib/esm/internal/lookup.js.map +0 -1
  101. package/lib/esm/internal/utils.d.ts +0 -26
  102. package/lib/esm/internal/utils.js +0 -52
  103. package/lib/esm/internal/utils.js.map +0 -1
package/lib/esm/index.js CHANGED
@@ -1,746 +1,9 @@
1
- import { HsmObject } from './internal/hsm.js';
2
- import { hasInitialState, quoteError, defineStateName as defineStateNameInternal, getStateName } from './internal/utils.js';
3
- // export type DispatchErrorCallback<Context, Protocol extends {} | undefined> = (hsm: Hsm<Context, Protocol>, traceWriter: TraceWriter, err: Error) => void;
4
1
  /**
5
- * Controls how much diagnostic detail the runtime emits through {@link TraceWriter}.
2
+ * ihsm hierarchical state machines for TypeScript.
6
3
  *
7
- * Set at construction via {@link makeHsm} or mutate {@link Properties.traceLevel} on a
8
- * live instance. Changing the level swaps the internal dispatch tracer implementation.
9
- *
10
- * @category Factory
11
- */
12
- export var TraceLevel;
13
- (function (TraceLevel) {
14
- /**
15
- * Production mode: minimal tracing overhead, no verbose dispatch steps.
16
- * Use in hot paths and shipped bundles when trace output is disabled.
17
- */
18
- TraceLevel[TraceLevel["PRODUCTION"] = 0] = "PRODUCTION";
19
- /**
20
- * Debug mode: transition boundaries, handler entry/exit, and error summaries.
21
- * Default for {@link makeHsm}. Suitable for development and integration tests.
22
- */
23
- TraceLevel[TraceLevel["DEBUG"] = 1] = "DEBUG";
24
- /**
25
- * Verbose debug: includes prototype-chain lookup walks, cache hits/misses, and
26
- * nested trace domains. Use when correlating handler code with tutorial trace panels.
27
- */
28
- TraceLevel[TraceLevel["VERBOSE_DEBUG"] = 2] = "VERBOSE_DEBUG";
29
- })(TraceLevel || (TraceLevel = {}));
30
- /**
31
- * Abstract base class for **any** port — production or test.
32
- *
33
- * It takes the machine's root {@link TopState} as its single type argument and derives the
34
- * context and internal protocol from it (via {@link MachineContext} / {@link MachineInternal}),
35
- * so the `TopState` is the one place those types are declared. Extend {@link Port} (not `BasePort`
36
- * directly) for production ports so timer and random services are available.
37
- *
38
- * The {@link BasePort.actor | actor} link is **bound lazily** by the runtime: construct the port
39
- * with no arguments and pass the instance to a factory, which wires the actor in afterwards.
40
- *
41
- * @typeParam T - The machine's root {@link TopState} subclass (e.g. `ConnTop`)
42
- *
43
- * @category Port
44
- */
45
- export class BasePort {
46
- /**
47
- * @inheritdoc PortHandle.actor
48
- *
49
- * Set once by the runtime right after the machine is built; `undefined` before binding.
50
- */
51
- actor;
52
- /** @inheritdoc PortHandle.hsm */
53
- hsm() {
54
- return this.actor;
55
- }
56
- /**
57
- * Post an internal event inward through the bound {@link BasePort.actor | actor}.
58
- *
59
- * This is the one channel a port (or a test driving the port) uses to feed the machine its
60
- * internal protocol. Because emission is explicit — never a side effect of the outbound call
61
- * the machine made — a single mock works across many tests: the test decides *when* (and
62
- * whether) to push each internal event.
63
- *
64
- * @param eventName - Internal event to post
65
- * @param payload - Arguments for the event
66
- * @throws If called before the actor has been bound by a factory
67
- */
68
- send(eventName, ...payload) {
69
- if (this.actor === undefined) {
70
- throw new Error('ihsm: port.send called before the actor was bound — pass the port to makeActor/makeHsm/makeTestActor first');
71
- }
72
- this.actor.post(eventName, ...payload);
73
- }
74
- }
75
- /**
76
- * Production port base with standard JavaScript timer and random services.
77
- *
78
- * Extend this class for domain ports in production code. It inherits the lazily-bound
79
- * {@link BasePort.actor | actor}, {@link BasePort.hsm | hsm}, and {@link BasePort.send | send}
80
- * from {@link BasePort}, and adds {@link Port.setTimeout | setTimeout} /
81
- * {@link Port.setInterval | setInterval} / {@link Port.clearTimeout | clearTimeout} /
82
- * {@link Port.clearInterval | clearInterval} plus the {@link RandomService} methods
83
- * ({@link Port.random | random}, {@link Port.cryptoRandom | cryptoRandom},
84
- * {@link Port.randomUUID | randomUUID}, {@link Port.getRandomValues | getRandomValues}).
85
- *
86
- * {@link State.deferredPost} delegates to {@link Port.setTimeout}. When no custom port is
87
- * supplied the runtime instantiates a plain `Port` for that purpose.
88
- *
89
- * @typeParam T - The machine's root {@link TopState} subclass (e.g. `ConnTop`)
90
- *
91
- * @example A minimal domain port
92
- * ```ts
93
- * class ConnPortImpl extends ihsm.Port<ConnTop> implements ConnPort {
94
- * private nextId = 1;
95
- * connect(host: string): ihsm.ResultWithSubscription<number> {
96
- * const id = this.nextId++;
97
- * return { value: id, subscription: { dispose: () => {} } };
98
- * }
99
- * disconnect(id: number): void {}
100
- * }
101
- * const port = new ConnPortImpl();
102
- * const conn = ihsm.makeActor(ConnTop, ctx, port); // binds port.actor
103
- * ```
104
- *
105
- * @category Port
106
- */
107
- export class Port extends BasePort {
108
- _timerSeq = 0;
109
- _timeoutHandles = new Map();
110
- _intervalHandles = new Map();
111
- /**
112
- * Schedule `callback` after `millis` milliseconds — same argument order as `globalThis.setTimeout`.
113
- *
114
- * @returns An opaque handle for {@link Port.clearTimeout}
115
- */
116
- setTimeout(callback, millis) {
117
- const id = ++this._timerSeq;
118
- const handle = globalThis.setTimeout(() => {
119
- this._timeoutHandles.delete(id);
120
- callback();
121
- }, Math.max(0, millis ?? 0));
122
- this._timeoutHandles.set(id, handle);
123
- return id;
124
- }
125
- /** Cancel a pending {@link Port.setTimeout} handle. No-op when `id` is `undefined` or unknown. */
126
- clearTimeout(id) {
127
- if (id === undefined) {
128
- return;
129
- }
130
- const handle = this._timeoutHandles.get(id);
131
- if (handle !== undefined) {
132
- globalThis.clearTimeout(handle);
133
- this._timeoutHandles.delete(id);
134
- }
135
- }
136
- /**
137
- * Schedule `callback` every `millis` milliseconds — same argument order as `globalThis.setInterval`.
138
- *
139
- * @returns An opaque handle for {@link Port.clearInterval}
140
- */
141
- setInterval(callback, millis) {
142
- const id = ++this._timerSeq;
143
- const handle = globalThis.setInterval(callback, Math.max(0, millis ?? 0));
144
- this._intervalHandles.set(id, handle);
145
- return id;
146
- }
147
- /** Cancel a pending {@link Port.setInterval} handle. No-op when `id` is `undefined` or unknown. */
148
- clearInterval(id) {
149
- if (id === undefined) {
150
- return;
151
- }
152
- const handle = this._intervalHandles.get(id);
153
- if (handle !== undefined) {
154
- globalThis.clearInterval(handle);
155
- this._intervalHandles.delete(id);
156
- }
157
- }
158
- /** @inheritdoc RandomService.random */
159
- random() {
160
- return Math.random();
161
- }
162
- /** @inheritdoc RandomService.cryptoRandom */
163
- cryptoRandom() {
164
- const crypto = globalThis.crypto;
165
- return crypto.random?.() ?? Math.random();
166
- }
167
- /** @inheritdoc RandomService.randomUUID */
168
- randomUUID() {
169
- return globalThis.crypto.randomUUID();
170
- }
171
- /** @inheritdoc RandomService.getRandomValues */
172
- getRandomValues(array) {
173
- // crypto.getRandomValues accepts a narrower union than ArrayBufferView; the runtime call is safe.
174
- globalThis.crypto.getRandomValues(array);
175
- return array;
176
- }
177
- }
178
- /**
179
- * Abstract root class for every state in the hierarchy.
180
- *
181
- * States are **never constructed directly** — the runtime binds one instance object whose
182
- * prototype moves along the class chain. Subclass `TopState` (or a child state), implement
183
- * your `Protocol` methods, and pass the root class to {@link makeHsm}.
184
- *
185
- * Forwards {@link State} / {@link Properties} APIs and default {@link StateEvents} behavior.
186
- *
187
- * @category State machine
188
- */
189
- export class TopState {
190
- /** Domain context (injected by runtime — do not assign in constructors). */
191
- ctx;
192
- /** Handler view of the machine (`this` inside methods delegates here for core operations). */
193
- hsm;
194
- constructor() {
195
- throw new Error('Fatal error: States cannot be instantiated');
196
- }
197
- /**
198
- * Outbound boundary — the `port` instance passed to {@link makeActor} / {@link testing!makeTestActor};
199
- * all impure I/O flows through here.
200
- *
201
- * Typed `undefined` for machines created without a port (the default), so existing
202
- * port-less machines are unaffected. At runtime a {@link Port} always backs such
203
- * machines — it is what {@link State.deferredPost} uses for its timer service.
204
- */
205
- get port() {
206
- return this.hsm.port;
207
- }
208
- /** @inheritdoc Properties.eventName */
209
- get eventName() {
210
- return this.hsm.eventName;
211
- }
212
- /** @inheritdoc Properties.eventPayload */
213
- get eventPayload() {
214
- return this.hsm.eventPayload;
215
- }
216
- /** @inheritdoc Properties.traceHeader */
217
- get traceHeader() {
218
- return this.hsm.traceHeader;
219
- }
220
- /** @inheritdoc Properties.topState */
221
- get topState() {
222
- return this.hsm.topState;
223
- }
224
- /** @inheritdoc Properties.currentStateName */
225
- get currentStateName() {
226
- return this.hsm.currentStateName;
227
- }
228
- /** @inheritdoc Properties.currentState */
229
- get currentState() {
230
- return this.hsm.currentState;
231
- }
232
- /** @inheritdoc Properties.ctxTypeName */
233
- get ctxTypeName() {
234
- return this.hsm.ctxTypeName;
235
- }
236
- /** @inheritdoc Properties.traceLevel */
237
- set traceLevel(value) {
238
- this.hsm.traceLevel = value;
239
- }
240
- /** @inheritdoc Properties.traceLevel */
241
- get traceLevel() {
242
- return this.hsm.traceLevel;
243
- }
244
- /** @inheritdoc Properties.topStateName */
245
- get topStateName() {
246
- return this.hsm.topStateName;
247
- }
248
- /** @inheritdoc Properties.traceWriter */
249
- get traceWriter() {
250
- return this.hsm.traceWriter;
251
- }
252
- /** @inheritdoc Properties.traceWriter */
253
- set traceWriter(value) {
254
- this.hsm.traceWriter = value;
255
- }
256
- /** @inheritdoc Properties.dispatchErrorCallback */
257
- get dispatchErrorCallback() {
258
- return this.hsm.dispatchErrorCallback;
259
- }
260
- /** @inheritdoc Properties.dispatchErrorCallback */
261
- set dispatchErrorCallback(value) {
262
- this.hsm.dispatchErrorCallback = value;
263
- }
264
- /** @inheritdoc State.transition */
265
- transition(nextState) {
266
- this.hsm.transition(nextState);
267
- }
268
- /** @inheritdoc State.unhandled */
269
- unhandled() {
270
- this.hsm.unhandled();
271
- }
272
- /** @inheritdoc State.sleep */
273
- sleep(millis) {
274
- return this.hsm.sleep(millis);
275
- }
276
- /** @inheritdoc Base.post */
277
- post(eventName, ...eventPayload) {
278
- this.hsm.post(eventName, ...eventPayload);
279
- }
280
- /** @inheritdoc State.deferredPost */
281
- deferredPost(millis, eventName, ...eventPayload) {
282
- this.hsm.deferredPost(millis, eventName, ...eventPayload);
283
- }
284
- /** @inheritdoc State.postNow */
285
- postNow(eventName, ...eventPayload) {
286
- this.hsm.postNow(eventName, ...eventPayload);
287
- }
288
- /** @inheritdoc StateEvents.onExit */
289
- onExit() { }
290
- /** @inheritdoc StateEvents.onEntry */
291
- onEntry() { }
292
- /** @inheritdoc StateEvents.onError */
293
- onError(error) {
294
- throw error;
295
- }
296
- /** @inheritdoc StateEvents.onUnhandled */
297
- onUnhandled(error) {
298
- throw error;
299
- }
300
- }
301
- /**
302
- * Base class for all ihsm runtime errors carrying machine context.
303
- *
304
- * @typeParam Context - Domain context at failure time
305
- * @typeParam Protocol - Vocabulary type (for typed subclasses)
306
- *
307
- * @category Error
308
- */
309
- export class HsmError extends Error {
310
- /** Discriminator matching the class name (`EventHandlerError`, etc.). */
311
- name;
312
- /** {@link Properties.topStateName} when the error was constructed. */
313
- topStateName;
314
- /** {@link Properties.currentStateName} when the error was constructed. */
315
- stateName;
316
- /** Snapshot of {@link State.ctx} when the error was constructed. */
317
- context;
318
- /** Original thrown value when this error wraps a handler or lifecycle failure. */
319
- cause;
320
- constructor(name, hsm, message, cause) {
321
- super(message);
322
- this.name = name;
323
- this.topStateName = hsm.topStateName;
324
- this.stateName = hsm.currentStateName;
325
- this.context = hsm.ctx;
326
- this.cause = cause;
327
- }
328
- }
329
- /**
330
- * Error base for failures during **event dispatch**, with correlated event metadata.
331
- *
332
- * @typeParam Context - Domain context
333
- * @typeParam Protocol - Vocabulary interface
334
- * @typeParam EventName - Event or service key being processed
335
- *
336
- * @category Error
337
- */
338
- export class RuntimeError extends HsmError {
339
- /** Event or service name that was active when the failure occurred. */
340
- eventName;
341
- /** Client-supplied arguments (excluding resolve/reject for services). */
342
- eventPayload;
343
- constructor(errorName, hsm, message, cause) {
344
- super(errorName, hsm, message, cause);
345
- this.eventName = hsm.eventName;
346
- this.eventPayload = hsm.eventPayload;
347
- }
348
- }
349
- /**
350
- * Thrown when {@link StateEvents.onExit} or {@link StateEvents.onEntry} throws during a transition.
351
- *
352
- * @category Error
353
- */
354
- export class TransitionError extends RuntimeError {
355
- failedStateName;
356
- failedCallback;
357
- fromStateName;
358
- toStateName;
359
- /**
360
- * @param hsm - Machine view at failure time
361
- * @param cause - Error thrown from the lifecycle hook
362
- * @param failedStateName - Display name of the state whose hook failed
363
- * @param failedCallback - Which hook failed (`onExit` or `onEntry`)
364
- * @param fromStateName - Leaf state before the transition
365
- * @param toStateName - Requested destination state
366
- */
367
- constructor(hsm, cause, failedStateName, failedCallback, fromStateName, toStateName) {
368
- super('TransitionError', hsm, `${failedStateName}.${failedCallback}() has failed while executing a transition from ${fromStateName} to ${toStateName}`, cause);
369
- this.failedStateName = failedStateName;
370
- this.failedCallback = failedCallback;
371
- this.fromStateName = fromStateName;
372
- this.toStateName = toStateName;
373
- }
374
- }
375
- /**
376
- * Thrown when an event handler body throws and {@link StateEvents.onError} does not recover.
377
- *
378
- * @category Error
379
- */
380
- export class EventHandlerError extends RuntimeError {
381
- /**
382
- * @param hsm - Machine view with {@link eventName} set to the failing handler
383
- * @param cause - Error thrown from handler code
384
- */
385
- constructor(hsm, cause) {
386
- super('EventHandlerError', hsm, `an error was thrown while executing event handler #${hsm.eventName} in state ${hsm.currentStateName}`, cause);
387
- }
388
- }
389
- /**
390
- * Thrown when no handler matches the dispatched event and {@link StateEvents.onUnhandled} rethrows.
391
- *
392
- * @category Error
393
- */
394
- export class UnhandledEventError extends RuntimeError {
395
- /** @param hsm - Machine view with the unmatched {@link eventName} */
396
- constructor(hsm) {
397
- super('UnhandledEventError', hsm, `event #${hsm.eventName} was unhandled in state ${hsm.currentStateName}`);
398
- }
399
- }
400
- /**
401
- * Thrown at **class definition** time when {@link InitialState} is applied twice to one parent.
402
- *
403
- * @category Error
404
- */
405
- export class InitialStateError extends Error {
406
- /** Display name of the state passed to the duplicate {@link InitialState} call. */
407
- targetStateName;
408
- /** @param targetState - The state class whose parent already has an initial substate */
409
- constructor(targetState) {
410
- super(`State '${getStateName(Object.getPrototypeOf(targetState.prototype).constructor)}' must not have more than one initial state`);
411
- this.name = 'InitialStateError';
412
- this.targetStateName = getStateName(targetState);
413
- }
414
- }
415
- /**
416
- * Thrown when {@link StateEvents.onError} itself throws, leaving the machine unrecoverable.
417
- *
418
- * @category Error
419
- */
420
- export class FatalError extends RuntimeError {
421
- /**
422
- * @param hsm - Machine view at failure time
423
- * @param cause - Error thrown from `onError`
424
- */
425
- constructor(hsm, cause) {
426
- super('FatalError', hsm, `onError() has thrown ${quoteError(cause)}`, cause);
427
- }
428
- }
429
- /**
430
- * Thrown when {@link StateEvents.onEntry} fails during the initial `@InitialState` walk at startup.
431
- *
432
- * @category Error
433
- */
434
- export class InitializationError extends HsmError {
435
- failedState;
436
- /**
437
- * @param hsm - Partially initialized machine
438
- * @param failedState - State class whose `onEntry` threw
439
- * @param cause - Original error from `onEntry`
440
- */
441
- constructor(hsm, failedState, cause) {
442
- super('InitializationError', hsm, `state ${getStateName(failedState)} has thrown ${quoteError(cause)} during initialization`, cause);
443
- this.failedState = failedState;
444
- }
445
- }
446
- /**
447
- * Terminal sink state class used when the runtime cannot recover from an error.
448
- *
449
- * Assign or transition here from custom {@link StateEvents.onError} handlers when you need a
450
- * well-defined quiescent state. Display name is pre-registered as `'FatalErrorState'`.
451
- *
452
- * @category State machine
453
- */
454
- export class FatalErrorState extends TopState {
455
- }
456
- defineStateNameInternal(TopState, 'TopState');
457
- defineStateNameInternal(FatalErrorState, 'FatalErrorState');
458
- /**
459
- * Declares `TargetState` as the **initial substate** of its direct parent composite.
460
- *
461
- * Apply as a TypeScript decorator or call as a function at class definition time. Exactly **one**
462
- * initial child is allowed per parent; a second mark throws {@link InitialStateError}.
463
- *
464
- * @typeParam Context - Domain context type
465
- * @typeParam Protocol - Vocabulary interface
466
- * @param TargetState - Child state class whose **parent** is `Object.getPrototypeOf(TargetState.prototype).constructor`
467
- *
468
- * @throws {@link InitialStateError} when the parent already has an initial substate
469
- *
470
- * @remarks
471
- * During {@link makeHsm} initialization, the runtime descends `@InitialState` chains from the
472
- * root until the deepest initial leaf is active, running {@link StateEvents.onEntry} along the path.
473
- *
474
- * @example
475
- * ```ts
476
- * class Composite extends TopState {}
477
- *
478
- * @InitialState
479
- * class Idle extends Composite {}
480
- * ```
481
- */
482
- export function InitialState(TargetState) {
483
- const ParentOfTargetState = Object.getPrototypeOf(TargetState.prototype).constructor;
484
- if (hasInitialState(ParentOfTargetState))
485
- throw new InitialStateError(TargetState);
486
- Object.defineProperty(TargetState, '_isInitialState', {
487
- value: true,
488
- writable: false,
489
- configurable: false,
490
- enumerable: false,
491
- });
492
- Object.defineProperty(ParentOfTargetState, '_initialState', {
493
- value: TargetState,
494
- writable: false,
495
- configurable: false,
496
- enumerable: false,
497
- });
498
- }
499
- /**
500
- * Assigns a stable **display name** to a single state class.
501
- *
502
- * Minifiers rewrite `Class.name` in production browser bundles; explicit registration keeps
503
- * {@link Properties.currentStateName}, trace output, and error messages readable everywhere.
504
- *
505
- * @typeParam Context - Domain context type
506
- * @typeParam Protocol - Vocabulary interface
507
- * @param state - State class constructor to tag
508
- * @param name - Non-empty display string used in traces and errors (not required to match `Class.name`)
509
- *
510
- * @remarks
511
- * Stored as a non-enumerable own property — never inherited by subclasses from the prototype chain.
512
- * {@link registerStateNames} is preferred when every state is a named export from one module.
513
- *
514
- * @example
515
- * ```ts
516
- * class Door extends TopState {}
517
- * defineStateName(Door, 'Door');
518
- * ```
519
- *
520
- * @category State machine
521
- */
522
- export function defineStateName(state, name) {
523
- defineStateNameInternal(state, name);
524
- }
525
- /**
526
- * Registers display names for **every** state class in an exports object, using each **export key** as the name.
527
- *
528
- * @param exports - Module namespace (`import * as machine`) or object literal of state classes.
529
- * Non-constructor exports (constants, functions, types) are silently skipped
530
- *
531
- * @remarks
532
- * Export keys survive minification even when class identifiers are mangled — this is the recommended
533
- * approach for browser bundles without `keep_classnames`. Call once at module load after all state
534
- * classes are defined.
535
- *
536
- * @example Single module
537
- * ```ts
538
- * export class DoorTop extends TopState {}
539
- * export class Open extends DoorTop {}
540
- * export class Closed extends DoorTop {}
541
- * registerStateNames({ DoorTop, Open, Closed });
542
- * ```
543
- *
544
- * @example Re-exporting namespace
545
- * ```ts
546
- * import * as machine from './machine';
547
- * registerStateNames(machine);
548
- * ```
549
- *
550
- * @category State machine
551
- */
552
- export function registerStateNames(exports) {
553
- for (const [exportName, value] of Object.entries(exports)) {
554
- if (isStateClass(value)) {
555
- defineStateNameInternal(value, exportName);
556
- }
557
- }
558
- }
559
- /** @internal — structural guard: a constructor whose prototype derives from {@link TopState}. */
560
- function isStateClass(value) {
561
- if (typeof value !== 'function')
562
- return false;
563
- const prototype = value.prototype;
564
- return typeof prototype === 'object' && prototype !== null && TopState.prototype.isPrototypeOf(prototype);
565
- }
566
- /** @internal */
567
- class ConsoleTraceWriter {
568
- write(hsm, Message) {
569
- if (typeof Message == 'string') {
570
- console.log(`${hsm.traceHeader}${hsm.currentStateName}: ${Message}`);
571
- }
572
- else {
573
- console.log(Message);
574
- }
575
- }
576
- }
577
- /** @internal — shared by the core factories and (via re-export) the `ihsm/testing` factories. */
578
- export function defaultDispatchErrorCallback(hsm, err) {
579
- const writer = hsm.traceWriter;
580
- writer.write(hsm, `An event dispatch has failed; error ${err.name}: ${err.message} has not been managed`);
581
- writer.write(hsm, err);
582
- throw err;
583
- }
584
- /** @internal */
585
- export const defaultTraceWriter = new ConsoleTraceWriter();
586
- const defaultTraceLevel = TraceLevel.DEBUG;
587
- /** @internal */
588
- export const defaultInitialize = true;
589
- /**
590
- * Creates and optionally initializes a hierarchical state machine **actor** bound to `ctx`.
591
- *
592
- * The returned {@link Hsm} is the single runtime object: external clients call `post` / `call` /
593
- * `sync`; the active state is the instance prototype chain updated by {@link State.transition}.
594
- *
595
- * @typeParam Context - Domain context type (inferred from `ctx` when passed inline)
596
- * @typeParam Protocol - Event/service vocabulary (inferred from `topState` when it implements `Protocol`)
597
- * @param topState - Root state **class** constructor (must extend {@link TopState})
598
- * @param ctx - Mutable domain object shared by all states; stored on the instance as {@link Hsm.ctx}
599
- * @param initialize - When `true` (default), enqueue the initial walk: descend `@InitialState`
600
- * chains from `topState` and run {@link StateEvents.onEntry} on each entered state until the
601
- * initial leaf is active. When `false`, prototype starts at `topState` with **no** entry hooks
602
- * @param traceLevel - Initial {@link TraceLevel} (default {@link TraceLevel.DEBUG})
603
- * @param traceWriter - {@link TraceWriter} implementation (default: prefixes strings with state name and logs to `console`)
604
- * @param dispatchErrorCallback - Last-resort error hook (default: trace + rethrow)
605
- * @returns Client handle implementing {@link Hsm} for the same `Context` and `Protocol`
606
- *
607
- * @remarks
608
- * - Await {@link Hsm.sync} after creation when `initialize: true` before asserting initial state
609
- * - Zero runtime npm dependencies; safe to embed in browsers when state names are registered
610
- * - Transition LCA paths are cached per machine instance for the lifetime of the actor
611
- *
612
- * @example Minimal door machine
613
- * ```ts
614
- * const door = makeHsm(DoorTop, { openCount: 0 });
615
- * await door.sync();
616
- * door.post('open');
617
- * await door.sync();
618
- * ```
619
- *
620
- * @example Custom tracing in tests
621
- * ```ts
622
- * const writer = { write: (_hsm, msg) => logs.push(msg) };
623
- * const sm = makeHsm(Top, ctx, true, TraceLevel.VERBOSE_DEBUG, writer);
624
- * await sm.sync();
625
- * ```
626
- *
627
- * @category Factory
628
- */
629
- export function makeHsm(topState, ctx, initialize = defaultInitialize, traceLevel = defaultTraceLevel, traceWriter = defaultTraceWriter, dispatchErrorCallback = defaultDispatchErrorCallback, port) {
630
- return instantiate(topState, ctx, initialize, traceLevel, traceWriter, dispatchErrorCallback, port);
631
- }
632
- /** @internal — single construction path shared by {@link makeHsm}, {@link makeActor}, {@link testing!makeTestActor}. */
633
- function instantiate(topState, ctx, initialize, traceLevel, traceWriter, dispatchErrorCallback, port) {
634
- const instance = {
635
- hsm: undefined,
636
- ctx: ctx,
637
- };
638
- Object.setPrototypeOf(instance, topState.prototype);
639
- instance.hsm = new HsmObject(topState, instance, traceWriter, traceLevel, dispatchErrorCallback, initialize);
640
- // A port is always present: the supplied instance, otherwise a Port that backs
641
- // `deferredPost`'s timer service. Its `actor` is bound here, lazily — synchronously, before
642
- // the queued initialization walk, so `this.port` is available inside the first `onEntry`.
643
- const boundPort = port ?? new Port();
644
- boundPort.actor = instance.hsm;
645
- instance.portRef = boundPort;
646
- return instance.hsm;
647
- }
648
- /**
649
- * @internal
650
- *
651
- * Wrap a live machine in a **structural, public-only** {@link Actor} facade (proposal T5).
652
- *
653
- * Replaces the old `hsm as unknown as Actor<…>` double cast. The returned object is annotated
654
- * `Actor<Context, Public>`, so the compiler verifies it implements **exactly** the public surface —
655
- * a regression that leaked an internal member would fail to compile, and if {@link Hsm} gains a
656
- * member this factory stops compiling until the facade forwards it. Each forwarded `post` / `call`
657
- * is narrowed from the merged-protocol instance down to the public protocol with a single local
658
- * cast; properties delegate through get/set accessors so reads and writes still hit the live machine.
659
- */
660
- function narrowToActor(hsm) {
661
- const actor = {
662
- get ctx() {
663
- return hsm.ctx;
664
- },
665
- get currentState() {
666
- return hsm.currentState;
667
- },
668
- get currentStateName() {
669
- return hsm.currentStateName;
670
- },
671
- get topState() {
672
- return hsm.topState;
673
- },
674
- get topStateName() {
675
- return hsm.topStateName;
676
- },
677
- get ctxTypeName() {
678
- return hsm.ctxTypeName;
679
- },
680
- get traceHeader() {
681
- return hsm.traceHeader;
682
- },
683
- get eventName() {
684
- return hsm.eventName;
685
- },
686
- get eventPayload() {
687
- return hsm.eventPayload;
688
- },
689
- get traceLevel() {
690
- return hsm.traceLevel;
691
- },
692
- set traceLevel(level) {
693
- hsm.traceLevel = level;
694
- },
695
- get traceWriter() {
696
- return hsm.traceWriter;
697
- },
698
- set traceWriter(writer) {
699
- hsm.traceWriter = writer;
700
- },
701
- get dispatchErrorCallback() {
702
- return hsm.dispatchErrorCallback;
703
- },
704
- set dispatchErrorCallback(cb) {
705
- hsm.dispatchErrorCallback = cb;
706
- },
707
- post: hsm.post.bind(hsm),
708
- call: hsm.call.bind(hsm),
709
- sync: hsm.sync.bind(hsm),
710
- restore: hsm.restore.bind(hsm),
711
- };
712
- return actor;
713
- }
714
- /**
715
- * Creates an actor exposing only its **public** protocol, with an optional outbound {@link Port}.
716
- *
717
- * Like {@link makeHsm} but separates the public, client-callable protocol from an
718
- * `InternalProtocol` that only the port may post inward. The returned {@link Actor} surfaces
719
- * just the public events; handlers (and the port) may post the merged {@link Dispatch} protocol.
720
- *
721
- * The trailing `Disjoint` guard is a compile-time gate: if `Public` and `Internal` share an event
722
- * name, the call fails to type-check, pointing at the overlapping keys.
723
- *
724
- * @typeParam Context - Domain context type
725
- * @typeParam Public - Public, client-callable protocol
726
- * @typeParam Internal - Internal protocol — only postable by the port / handlers
727
- * @typeParam P - Concrete {@link Port} type assigned to `this.port`
728
- * @param topState - Root state class; `Context` / `Public` / `Internal` are inferred from it (see {@link TopStateArg})
729
- * @param ctx - Mutable domain object shared by all states
730
- * @param port - Outbound port instance (its `actor` is bound by the factory; use {@link Port} if none)
731
- * @param options - Optional tuning: `initialize` / `traceLevel` / `traceWriter` / … (see {@link ActorOptions})
732
- * @returns A public-only {@link Actor} handle
733
- *
734
- * @example
735
- * ```ts
736
- * const conn = makeActor(ConnTop, new ConnCtx(), port, { traceLevel: TraceLevel.PRODUCTION });
737
- * ```
738
- *
739
- * @category Factory
4
+ * Curated public runtime surface; protocol types live in {@link ./types}.
740
5
  */
741
- export function makeActor(topState, ctx, port, options = {}, ..._disjointGuard) {
742
- const { initialize = defaultInitialize, traceLevel = defaultTraceLevel, traceWriter = defaultTraceWriter, dispatchErrorCallback = defaultDispatchErrorCallback } = options;
743
- const hsm = instantiate(topState, ctx, initialize, traceLevel, traceWriter, dispatchErrorCallback, port);
744
- return narrowToActor(hsm);
745
- }
6
+ export { TraceLevel, asError, quoteUnknown, quoteError, getInitialState, hasInitialState, getTransitionKey, defineStateName, getStateName, Port, RequestingPort, TopState, HsmError, RuntimeError, TransitionError, EventHandlerError, UnhandledEventError, InitialStateError, FatalError, InitializationError, FatalErrorState, InitialState, registerStateNames, ProtocolCollisionError, ReservedNames, buildProtocolIndex, CallTimeoutError, SelfCallDeadlockError, TransitionTableError, planTransitionClasses, executeTransitionRoutine, createTransitionTracer, transitionTraceLines, RuntimeTransitionResolver, isRequestingPort, isServiceCallOptions, splitServiceArgs, serviceCallWithTimeout, currentTraceAnchor, defaultTraceWriter, defaultInitialize, defaultDispatchErrorCallback, makeActor, asParentActor, makeChildActor, kHandlerMachine, kParentLink, configureRunSeed, getRunSeed, getRunNamespace, mintActorIdentity, } from './internal/runtime.js';
7
+ export { createConsoleInstrumentation } from './internal/console-instrumentation.js';
8
+ export { registerCollector, clearCollectors, getCollectorCount } from './internal/instrumentation.js';
746
9
  //# sourceMappingURL=index.js.map