From f5cd2a5912659eeae0330a1024b2f1270ffa812b Mon Sep 17 00:00:00 2001 From: QQ Date: Sat, 14 Nov 2026 14:55:58 +0800 Subject: [PATCH] Import packages/plugin/src/hmr-safe-settings.ts --- packages/plugin/src/hmr-safe-settings.ts | 74 ++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 packages/plugin/src/hmr-safe-settings.ts diff --git a/packages/plugin/src/hmr-safe-settings.ts b/packages/plugin/src/hmr-safe-settings.ts new file mode 100644 index 0000000..816bec4 --- /dev/null +++ b/packages/plugin/src/hmr-safe-settings.ts @@ -0,0 +1,74 @@ +/** + * Serialize settings writes and leave DSH's HMR AsyncLocalStorage context + * before invoking configEditor. Otherwise a callback reached from a reload is + * treated as a nested transaction. The pump is kept on globalThis so a hot + * reload reuses the same queue. + */ + +type Job = { + run: () => Promise + resolve: (value: T | PromiseLike) => void + reject: (reason?: unknown) => void +} + +interface Pump { + enqueue(run: () => Promise): Promise +} + +/** + * The HMR service intentionally keeps its AsyncLocalStorage private. The + * runtime still exposes the storage's `exit()` method, which is the boundary + * configEditor needs when a plugin callback was entered from an HMR reload. + * Keep this structural so older Hosts without HMR continue to use the pump. + */ +export interface HmrContextLike { + executing?: { + exit?(callback: () => T): T + } +} + +const PUMP_KEY = Symbol.for('ds-harness-remote.hmr-safe-settings-pump') + +function createPump(): Pump { + const queue: Job[] = [] + let wake!: () => void + let sleeping = new Promise(resolve => { wake = resolve }) + + // Do not await this from plugin activation. Its continuation is deliberately + // left at module initialization, outside the HMR transaction that may reload + // the plugin later. + void (async () => { + for (;;) { + if (queue.length === 0) { + await sleeping + sleeping = new Promise(resolve => { wake = resolve }) + } + const job = queue.shift() + if (job === undefined) continue + try { + job.resolve(await job.run()) + } catch (error) { + job.reject(error) + } + } + })() + + return { + enqueue(run: () => Promise): Promise { + return new Promise((resolve, reject) => { + queue.push({ run, resolve: resolve as (value: unknown) => void, reject }) + wake() + }) + }, + } +} + +const globalState = globalThis as typeof globalThis & { [PUMP_KEY]?: Pump } +const pump = globalState[PUMP_KEY] ?? (globalState[PUMP_KEY] = createPump()) + +export function runHmrSafe(run: () => Promise, hmr?: HmrContextLike): Promise { + return pump.enqueue(() => { + const executing = hmr?.executing + return typeof executing?.exit === 'function' ? executing.exit(run) : run() + }) +}