subapp.ts 5.05 KB
import {
  busEvents,
  type RemoteRequestFn,
  type SessionSnapshot,
  type SubAppProps,
} from '@uj/contracts';

/**
 * wujie 注入到 iframe 的运行时对象。
 * 这里刻意不写 declare global:子应用自己的 wujie.d.ts 会声明 window.$wujie,
 * 两边重复声明容易在类型合并时打架。局部断言即可。
 */
interface WujieBus {
  $on: (event: string, handler: (...args: unknown[]) => void) => void;
  $off: (event: string, handler: (...args: unknown[]) => void) => void;
  $emit: (event: string, ...args: unknown[]) => void;
}
interface WujieRuntime {
  bus?: WujieBus;
  props?: Record<string, unknown>;
}

export function wujieRuntime(): WujieRuntime | undefined {
  if (typeof window === 'undefined') return undefined;
  return (window as unknown as { $wujie?: WujieRuntime }).$wujie;
}

export function isInWujie(): boolean {
  return Boolean((window as unknown as { __POWERED_BY_WUJIE__?: boolean }).__POWERED_BY_WUJIE__);
}

export function shortName(): string {
  const props = wujieRuntime()?.props;
  return typeof props?.['shortName'] === 'string' ? (props['shortName'] as string) : '';
}

export function subappBus(): WujieBus | undefined {
  return wujieRuntime()?.bus;
}

/** 会话真源:localStorage。wujie 的 iframe 是同源 srcdoc,天然读得到主壳写的那一份。 */
export function readSession(): SessionSnapshot | null {
  try {
    const raw = localStorage.getItem('session');
    if (!raw) return null;
    const s = JSON.parse(raw) as SessionSnapshot;
    if (!s.token || (s.expireAt && new Date(s.expireAt).getTime() <= Date.now())) return null;
    return s;
  } catch {
    return null;
  }
}

/** 权限按钮的唯一依据:与老项目 getUserPermCodes() 同源。 */
export function readPermCodes(): string[] {
  const fromSession = readSession()?.permCodes;
  if (Array.isArray(fromSession) && fromSession.length) return fromSession;
  try {
    const raw = localStorage.getItem('uj-auth-user-info');
    const info = raw ? (JSON.parse(raw) as { permCodes?: unknown }) : null;
    return Array.isArray(info?.permCodes)
      ? info.permCodes.filter((c): c is string => typeof c === 'string')
      : [];
  } catch {
    return [];
  }
}

/** 页面级判定:三段兜底,与 host 的 AccessProvider.can() 逐条对齐。 */
export function canByPoints(points: Set<string>, resource: string): boolean {
  if (points.has(resource)) return true;
  if (points.has(`${resource}:manage`)) return true;
  return [...points].some((p) => p.startsWith(`${resource}:`));
}

/** 按钮级判定:严格命中,无兜底,必须与后端码逐字符一致。 */
export function canPointByPoints(points: Set<string>, point: string): boolean {
  return points.has(point);
}

/** 首屏页名:只认 wujie 注入的 props.page;独立运行时回退到 URL 末段。 */
export function readInitialPage(): string {
  const fromProps = wujieRuntime()?.props?.['page'];
  if (typeof fromProps === 'string') return fromProps;
  if (typeof window !== 'undefined') {
    return window.location.pathname.split('/').filter(Boolean).pop() ?? '';
  }
  return '';
}

/**
 * 唯一的后端出入口。
 * 独立运行(非 wujie)时明确抛错而不是静默返回 undefined —— 子应用单独起 dev server
 * 时看到的是一句人话,而不是「接口没反应」这种最难查的故障。
 */
export function requestViaHost(): RemoteRequestFn {
  const fn = wujieRuntime()?.props?.['request'];
  if (typeof fn !== 'function') {
    return () =>
      Promise.reject(
        new Error(
          '未检测到主壳注入的 props.request。子应用的所有请求必须由主壳代理;请用 pnpm dev 从主壳入口访问,或检查 startApp 的 props。',
        ),
      );
  }
  return fn as RemoteRequestFn;
}

/** 取完整 props(缺字段时补默认值,便于子应用独立调试)。 */
export function subAppProps(): SubAppProps {
  const raw = (wujieRuntime()?.props ?? {}) as Partial<SubAppProps>;
  return {
    request: requestViaHost(),
    session: readSession(),
    permCodes: readPermCodes(),
    theme: (raw.theme as Record<string, unknown>) ?? {},
    page: readInitialPage(),
    navigate:
      typeof raw.navigate === 'function'
        ? raw.navigate
        : (path: string) => {
            const bus = subappBus();
            const name = shortName();
            if (bus && name) bus.$emit(busEvents(name).navigateHost, path);
          },
    shortName: shortName(),
  };
}

/**
 * 子应用内部跳转(曾以相同实现散落在 points / usedcar 各自的 navigate.ts)。
 *
 * 页面切换的真源在主壳地址栏:这里只把「相对路径」拼成 `/<应用名>/<路径>` 交给主壳,
 * 主壳再从地址算出 subPath 广播回来。子应用因此不需要自己的路由表,也不会出现
 * 「iframe 内换了页、地址栏没变」的两种状态。
 *
 * 路径全小写、参数走路径段(/points/order/123),地址栏里不出现驼峰与查询串。
 */
export function goTo(path: string): void {
  const clean = path.replace(/^\/+|\/+$/g, '');
  subAppProps().navigate(`/${shortName()}/${clean}`);
}