| 36 | * Throws ZRUI_INVALID_STATE on illegal transition attempts. |
| 37 | */ |
| 38 | export class AppStateMachine { |
| 39 | private state0: AppRuntimeState = "Created"; |
| 40 | |
| 41 | get state(): AppRuntimeState { |
| 42 | return this.state0; |
| 43 | } |
| 44 | |
| 45 | /** Assert current state is one of allowed states; throw with detail on violation. */ |
| 46 | assertOneOf(allowed: readonly AppRuntimeState[], detail: string): void { |
| 47 | for (const s of allowed) { |
| 48 | if (this.state0 === s) return; |
| 49 | } |
| 50 | invalidState(detail); |
| 51 | } |
| 52 | |
| 53 | /** Transition to Running; valid from Created or Stopped. */ |
| 54 | toRunning(): void { |
| 55 | if (this.state0 === "Created" || this.state0 === "Stopped") { |
| 56 | this.state0 = "Running"; |
| 57 | return; |
| 58 | } |
| 59 | invalidState(`cannot transition ${this.state0} -> Running`); |
| 60 | } |
| 61 | |
| 62 | /** Transition to Stopped; valid only from Running. */ |
| 63 | toStopped(): void { |
| 64 | if (this.state0 === "Running") { |
| 65 | this.state0 = "Stopped"; |
| 66 | return; |
| 67 | } |
| 68 | invalidState(`cannot transition ${this.state0} -> Stopped`); |
| 69 | } |
| 70 | |
| 71 | /** Transition to Faulted; valid only from Running. */ |
| 72 | toFaulted(): void { |
| 73 | if (this.state0 === "Running") { |
| 74 | this.state0 = "Faulted"; |
| 75 | return; |
| 76 | } |
| 77 | invalidState(`cannot transition ${this.state0} -> Faulted`); |
| 78 | } |
| 79 | |
| 80 | /** Transition to Disposed; valid from any state. Idempotent if already Disposed. */ |
| 81 | dispose(): void { |
| 82 | if (this.state0 === "Disposed") return; |
| 83 | if ( |
| 84 | this.state0 === "Faulted" || |
| 85 | this.state0 === "Created" || |
| 86 | this.state0 === "Running" || |
| 87 | this.state0 === "Stopped" |
| 88 | ) { |
| 89 | this.state0 = "Disposed"; |
| 90 | return; |
| 91 | } |
| 92 | invalidState(`cannot transition ${this.state0} -> Disposed`); |
| 93 | } |
| 94 | } |
nothing calls this directly
no outgoing calls
no test coverage detected