| 10 | const recordsByKey = new Map<string, Map<any, Entry>>() |
| 11 | |
| 12 | export function create<S>(root: () => string, init: () => S, dispose?: (state: Awaited<S>) => Promise<void>) { |
| 13 | return () => { |
| 14 | const key = root() |
| 15 | let entries = recordsByKey.get(key) |
| 16 | if (!entries) { |
| 17 | entries = new Map<string, Entry>() |
| 18 | recordsByKey.set(key, entries) |
| 19 | } |
| 20 | const exists = entries.get(init) |
| 21 | if (exists) return exists.state as S |
| 22 | const state = init() |
| 23 | entries.set(init, { |
| 24 | state, |
| 25 | dispose, |
| 26 | }) |
| 27 | return state |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | export async function dispose(key: string) { |
| 32 | const entries = recordsByKey.get(key) |