| 1 | // Preparation is a backend lifecycle state, not a transport/storage failure. |
| 2 | export class HistoryPreparingError extends Error { |
| 3 | constructor() { super("Session history is preparing"); } |
| 4 | } |
| 5 | |
| 6 | export type HistoryPreparationWait = () => Promise<void>; |
| 7 | export const waitForHistoryPreparation: HistoryPreparationWait = () => new Promise(resolve => setTimeout(resolve, 250)); |
| 8 | |
| 9 | export async function loadPreparedHistory<T>( |
| 10 | load: () => Promise<T>, current: () => boolean, |
| 11 | wait: HistoryPreparationWait = waitForHistoryPreparation, |
| 12 | ): Promise<T | undefined> { |
| 13 | while (current()) { |
| 14 | try { |
| 15 | const result = await load(); |
| 16 | return current() ? result : undefined; |
| 17 | } catch (error) { |
| 18 | if (!current()) return undefined; |
| 19 | if (!(error instanceof HistoryPreparingError)) throw error; |
| 20 | } |
| 21 | await wait(); |
| 22 | } |
| 23 | return undefined; |
| 24 | } |
| 25 |