Open History to see the last commit
1import type { CleanupFn } from '@tanstack/db'
2
3/**
4 * Preserves an adapter cleanup result while retiring wrapper-local state in
5 * the same stack.
6 */
7export function runCleanupWithLocalTeardown(
8 cleanup: CleanupFn | undefined,
9 teardown: () => void,
10): void | Promise<void> {
11 let result: unknown
12 try {
13 result = cleanup?.()
14 } catch (cleanupError) {
15 try {
16 teardown()
17 } catch (teardownError) {
18 throw aggregateCleanupFailures(cleanupError, teardownError)
19 }
20 throw cleanupError
21 }
22
23 try {
24 teardown()
25 } catch (teardownError) {
26 if (!isPromiseLike(result)) throw teardownError
27 return Promise.resolve(result).then(
28 () => {
29 throw teardownError
30 },
31 (cleanupError: unknown) => {
32 throw aggregateCleanupFailures(cleanupError, teardownError)
33 },
34 )
35 }
36 return isPromiseLike(result) ? Promise.resolve(result) : undefined
37}
38
39function isPromiseLike(value: unknown): value is PromiseLike<void> {
40 return (
41 !!value &&
42 (typeof value === `object` || typeof value === `function`) &&
43 typeof (value as { then?: unknown }).then === `function`
44 )
45}
46
47function aggregateCleanupFailures(
48 cleanupError: unknown,
49 teardownError: unknown,
50): AggregateError {
51 return new AggregateError(
52 [cleanupError, teardownError],
53 `Adapter cleanup and local teardown both failed`,
54 { cause: cleanupError },
55 )
56}