wujie-lifecycle.ts 2.18 KB
import { destroyApp, refreshApp, startApp, type startOptions } from 'wujie';

/**
 * 同名子应用的 wujie 操作串行闸。
 *
 * wujie@2.1.0 的 sync.js 里 `iframeWindow.__WUJIE.sync` 是无保护解引用:
 * 只要两个 startApp(同名) 并发,或 destroyApp 还没落地就再次 startApp,
 * 第二个 active() 就会在沙箱注入 __WUJIE 之前读到 undefined,抛
 * `Cannot read properties of undefined (reading 'sync')`。
 *
 * MicroApp 的宿主 WeakMap 只能挡住「同一个 el 重入」,挡不住:
 *   - StrictMode / 快速切路由产生的新 el 并发启动同名应用;
 *   - 失败自愈里 un-await 的 destroyApp 与紧随其后的 startApp。
 * 因此把 start / destroy / refresh 统一收进「按 shortName 排队」的闸:
 * 同一名字在任意时刻只有一个 wujie 操作在飞,后续操作等前一个 settle 再执行。
 */
const pending = new Map<string, Promise<unknown>>();

/** 把任务接在该名字的队尾;前一个失败不阻断后一个(先吞掉再执行)。 */
function withAppLock<T>(name: string, task: () => Promise<T>): Promise<T> {
  const previous = pending.get(name) ?? Promise.resolve();
  const next = previous.then(task, task);
  pending.set(name, next);
  // 清理必须在调用方拿到 reject 之前完成,保证 catch 里发起的重启已排到下一轮。
  const release = () => {
    if (pending.get(name) === next) pending.delete(name);
  };
  void next.then(release, release);
  return next;
}

/** 首次启动 / alive 复用激活:进闸。 */
export function startAppLocked(options: startOptions): Promise<unknown> {
  return withAppLock(options.name, () => startApp(options));
}

/** 正常销毁:进闸,避免与正在进行的启动互相踩踏。 */
export function destroyAppLocked(name: string): Promise<void> {
  return withAppLock(name, () => destroyApp(name));
}

/**
 * 失败自愈:wujie 自带的 refreshApp 就是「先 destroy 再 start」,
 * 放进同一把锁后整段原子执行;拆成两次进闸会让别的路由切换插队再起一次。
 */
export function restartAppLocked(options: startOptions): Promise<unknown> {
  return withAppLock(options.name, () => refreshApp(options));
}