export class AbortContext {
	public get running() {
		return !this.stopped
	}

	private stopped = false
	private promise: Promise<void>
	private resolve: () => void

	constructor() {
		this.resolve = () => {
			throw new Error('resolve() not available yet')
		}
		this.promise = new Promise((resolve) => {
			this.resolve = resolve
		})
	}

	public abort() {
		this.stopped = true
		this.resolve()
	}

	public async wait(promise?: Promise<unknown>) {
		if (promise) {
			await Promise.race([this.promise, promise])
		} else {
			await this.promise
		}
	}
}
