| 30 | const DEFAULT_MIN_INTERVAL_MS = 700; |
| 31 | |
| 32 | export class TeamsMessageStream { |
| 33 | private buffer = ""; |
| 34 | private posted = ""; |
| 35 | private id: string | undefined; |
| 36 | private queue: Promise<void> = Promise.resolve(); |
| 37 | private lastFlushedAt = 0; |
| 38 | private flushTimer: ReturnType<typeof setTimeout> | undefined; |
| 39 | private readonly minIntervalMs: number; |
| 40 | private readonly config: TeamsMessageStreamConfig; |
| 41 | |
| 42 | constructor(config: TeamsMessageStreamConfig) { |
| 43 | this.config = config; |
| 44 | this.minIntervalMs = config.minIntervalMs ?? DEFAULT_MIN_INTERVAL_MS; |
| 45 | } |
| 46 | |
| 47 | /** Replace the in-flight buffer (callers pass the accumulated text). */ |
| 48 | append(text: string): void { |
| 49 | if (text === this.buffer) return; |
| 50 | this.buffer = text; |
| 51 | this.scheduleFlush(); |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * Mark the stream done: cancel any pending throttled flush, enqueue a final |
| 56 | * flush, and resolve once the whole queue has drained. The posted activity |
| 57 | * then reflects the final buffer. Returns the activity id (or `undefined` if |
| 58 | * nothing was ever posted, e.g. an empty stream). |
| 59 | */ |
| 60 | async finish(): Promise<string | undefined> { |
| 61 | if (this.flushTimer) { |
| 62 | clearTimeout(this.flushTimer); |
| 63 | this.flushTimer = undefined; |
| 64 | } |
| 65 | this.enqueueFlush(); |
| 66 | await this.queue; |
| 67 | return this.id; |
| 68 | } |
| 69 | |
| 70 | private scheduleFlush(): void { |
| 71 | if (this.flushTimer) return; |
| 72 | const elapsed = Date.now() - this.lastFlushedAt; |
| 73 | const delay = Math.max(0, this.minIntervalMs - elapsed); |
| 74 | this.flushTimer = setTimeout(() => { |
| 75 | this.flushTimer = undefined; |
| 76 | this.enqueueFlush(); |
| 77 | }, delay); |
| 78 | } |
| 79 | |
| 80 | private enqueueFlush(): void { |
| 81 | this.queue = this.queue.then(() => this.flushNow()); |
| 82 | } |
| 83 | |
| 84 | private async flushNow(): Promise<void> { |
| 85 | const text = this.buffer; |
| 86 | if (text === this.posted) return; |
| 87 | // Don't post an empty first message; wait for real content. |
| 88 | if (this.id === undefined && text.trim().length === 0) return; |
| 89 | this.posted = text; |
nothing calls this directly
no test coverage detected
searching dependent graphs…