# 公开参考

查阅组合、通信、状态和扩展 API 的 imports、参数、返回值及示例。

版本、变更与要求见 [Framework 3.2 与 CLI 1.0](/zh-cn/docs/guides/releases/)。


<span id="import-principal"></span>

<span class="section-anchor" id="section-1"></span>

## 主导入

```js
import { wu } from 'wu-framework';
// Equivalente para el singleton:
// import wu from 'wu-framework';
```

软件包定义 ESM、CommonJS 和 UMD 入口。适配器、集成、服务器、sandbox 和 AI 子路径在 `package.json` 中声明。导入未导出的内部路径不属于分发约定。

<span id="core-y-lifecycle"></span>

<span class="section-anchor" id="section-2"></span>

## Core 与生命周期

| API | 输入 / 返回值 | 用途 |
| --- | --- | --- |
| `wu.init(config)` | 含 `apps` 的对象；`Promise<void>` | 初始化一次 |
| `wu.whenReady()` | `Promise<boolean>` | 等待进行中的 init |
| `wu.define(name, lifecycle)` | `mount` 必填 | 注册实现 |
| `wu.mount(name, selector)` | 选择器字符串；Promise | 挂载到 `document.querySelector` 可访问的节点 |
| `wu.unmount(name, options?)` | `{ force?, keepAlive? }`；Promise | 释放或隐藏 |
| `wu.update(name, props)` | Record；`Promise<boolean>` | 动态 props |
| `wu.hide(name)` / `show(name)` | Promises | 保留或重新激活应用 |
| `wu.isHidden(name)` | 布尔值 | keep-alive 状态 |
| `wu.destroy()` | Promise | 释放整个 runtime |
| `wu.app(name, config)` | `WuApp` | 可复用身份和配置，挂载时注册 |

导出的 helper `init(apps)` **接收数组**，而 `wu.init({ apps })` 接收对象，语法不能互换。导出的 `mount`、`unmount`、`define`、`app`、`hide`、`show`、`isHidden` 和 `destroy` helpers 委托 singleton。

<span id="inicialización-tipada"></span>

<span class="section-anchor" id="section-3"></span>

### 带类型的初始化

```ts
import { wu, type WuAppConfig } from 'wu-framework';

const catalog: WuAppConfig = {
  name: 'catalog',
  url: '/apps/catalog',
  grants: [{ capability: 'store.read', resource: 'catalog' }],
};

await wu.init({ apps: [catalog], sandbox: 'module' });
await wu.mount(catalog.name, '#catalog-slot');
// Al retirar este consumidor del shell:
await wu.unmount(catalog.name);
```

`mount` 前 slot 必须存在，manifest 必须声明相同身份并申请应用将使用的资源。`unmount` 释放一个引用并应用 keep-alive 规则；`{ force: true }` 请求完整卸载。

<span id="comunicación"></span>

<span class="section-anchor" id="section-4"></span>

## 通信

| Singleton/facade API | 返回值 |
| --- | --- |
| `emit(event, data, opts?)` | 表示是否接受的布尔值 |
| `on(event, callback)` | unsubscribe 函数 |
| `once(event, callback)` | unsubscribe 函数 |
| `off(event, callback)` | 总线布尔值 |
| `request(channel, data, opts?)` | 响应 Promise |
| `handle(channel, handler)` | 释放函数；eventBus/facade 支持选项 |
| `provide(name, impl, opts?)` | 带 `revoke()` 的 handle |
| `consume(name, range?, opts?)` | Proxy；`wait: true` 时为 Promise |

`WuEvent` 包含 `name`、`data`、`timestamp`、`appName`、`meta`、`verified`。`WuRpcOptions` 支持 `timeout`、`signal`、`version` 和 `range`；`WuRpcHandleOptions` 支持 `version`、`allow` 和 `replace`。

`request` 和 `handle` 是 `wu`、`wu.eventBus` 和 facade 的方法，不作为主包独立函数导出。`emit`、`on`、`once`、`off`、`provide` 和 `consume` 也有导出 helper。

`wu.handle(channel, handler, options)` 保留 `version`、`allow` 和 `replace`。在生命周期中，`context.wu.handle` 还加入应用身份和 grants；微应用 handlers 应使用该 facade。

<span id="elegir-evento-o-petición"></span>

<span class="section-anchor" id="section-5"></span>

### 选择事件还是请求

```js
const unsubscribe = wu.on('catalog:selected', (event) => {
  console.log(event.data.productId);
});
wu.emit('catalog:selected', { productId: 'p-42' });

const stopLookup = wu.handle('catalog:lookup', ({ productId }) => {
  return { productId, available: true };
});
const result = await wu.request('catalog:lookup', { productId: 'p-42' });
console.log(result.available);

unsubscribe();
stopLookup();
```

事件回调接收 `WuEvent` envelope，RPC handler 直接接收请求 payload。在安装 listener/提供方的生命周期中保存取消函数。应用内部使用带对应 grants 的 `context.wu`。

<span class="section-anchor" id="section-6"></span>

## Store

| 方法 | 返回值 / 说明 |
| --- | --- |
| `get(path?)` / `getSnapshot(path?)` | 独立快照；不同读取之间对象身份不稳定 |
| `set(path, value)` | 序列号 |
| `update(path, updater)` | 数字；同步 updater |
| `on(pattern, callback)` | Cleanup；wildcard 使用不同 payload |
| `batch(record)` | 序列号数组；预检全部条目 |
| `tap(fn)` | Cleanup；同步观察 commits |
| `hydrate(state, options?)` | 替换状态，可配置通知 |
| `sync(options?)` | 带 `ready`、`stop`、`status` 的 handle |
| `getMetrics()` | Store 计数器 |
| `reset()` / `dispose()` / `clear()` | Store 生命周期操作，不是持久化 API |

根导出的 `store` 指向 `wu.store`。`getState`、`setState`、`onStateChange` 和 `syncStore` helpers 使用同一实例。`new WuCore()` 默认创建独立 store，构造函数也允许为有意组合注入其他 store。

<span id="inspección-rendimiento-y-extensiones"></span>

<span class="section-anchor" id="section-7"></span>

## 检查、性能与扩展

| API | 功能 |
| --- | --- |
| `wu.inspect({ events? })` | 应用、状态和诊断快照 |
| `wu.getAppInfo(name)` | 已注册应用信息 |
| `wu.getSandboxInfo(name)` | 请求与实际模式，以及所有权 |
| `wu.getManifestDiagnostics()` | 无效声明式依赖 |
| `wu.getStats()` | 运行摘要 |
| `wu.showInspector()` / `hideInspector()` | 按需加载的检查界面 |
| `wu.performance.startMeasure(name, app?)` | 开始测量 |
| `wu.performance.endMeasure(name, app?)` | 结束并返回耗时 |
| `wu.performance.generateReport()` | 测量报告 |
| `wu.prefetch` / `prefetchAll` | 提前请求资源 |
| `wu.use('app.component')` | 加载 `wu.exports` 声明的 default export 或 namespace；参阅类型说明 |
| `wu.override` / `removeOverride` / `getOverrides` / `clearOverrides` | URL 替换 |
| `wu.pluginSystem.use(plugin, options)` | 异步安装 |
| `wu.hooks.use(phase, middleware, options?)` | 生命周期中间件 |
| `wu.aiReady()` / `timelineReady()` | 加载延迟子系统 |

导出类包括 `WuCore`、`WuCompatibility`、`WuLoader`、`WuSandbox`、`WuManifest`、`WuStore`、`WuApp`、`WuStyleBridge`、`WuCache`、`WuEventBus`、`WuPerformance`、`WuProxySandbox`、`WuPluginSystem`、`WuLoadingStrategy`、`WuPrefetch`、`WuOverrides`、`WuErrorBoundary`、`WuContracts` 和 `WuLifecycleHooks`。直接使用底层类需要自行配置保障：`new WuEventBus()` 默认 permissive，`wu.init()` 为 core 总线启用 strict。

<span id="tipos-que-conviene-conocer"></span>

<span class="section-anchor" id="section-8"></span>

## 值得了解的类型

`WuAppConfig` 描述宿主配置。`WuLifecycle` 和 `WuAppLifecycleContext` 描述挂载。`WuAppFacade`/`WuScopedStore` 描述应用权限。`WuPermissionRequest`、`WuCapabilityGrant` 和 `WuCompiledPolicy` 描述策略。`WuSyncHandle`、`WuTimelineFacade` 和 `WuInspectSnapshot` 描述可选子系统。

<span id="compatibilidad-de-las-declaraciones-typescript"></span>

<span class="section-anchor" id="section-9"></span>

### TypeScript 声明兼容性

以下说明帮助编写有效输入并正确处理返回值，尤其适用于类型声明未表达完整约定的地方：

- requests/grants 的 `resource?` 类型为可选，但解析器要求该属性。
- 输入 union 允许只写 capability，但字符串解析器要求 `capability:resource`。
- runtime 读取 `strategy` 和 `fullBleed`，但 `WuAppConfig` 未声明。
- core 存在 `wu.use`，但 `WuCore` 公开声明缺失。
- `WuLifecycleHooks.use` 声明返回 `void`，实现实际返回 cleanup。
- store 泛型签名未正确表达 wildcard envelope。
- 宿主类型提供 `styleMode`；有效值应在 manifest 配置。

<span id="referencia-de-implementación"></span>

<span class="section-anchor" id="section-10"></span>

## 实现参考

实际 exports：`src/index.js`；helpers：`src/index.js`；公开类型：`src/index.d.ts`、`src/index.d.ts`、`src/index.d.ts`、`src/index.d.ts`；子路径：`package.json`。测试：`tests/unit/package-exports.test.js`、`tests/unit/adapter-conformance.test.js`、`tests/unit/store-subscription-semantics.test.js`。

<span id="apis-de-la-versión-32"></span>

<span class="section-anchor" id="section-11"></span>

## 3.2 版本 API

目录涵盖声明式清单、焦点、过渡、窗口、拖放、影子部署、端口与可安装应用。[升级教程](/zh-cn/docs/guides/releases/) 链接完整契约、可选导入和错误处理。原有状态、事件、AI 与生命周期 API 仍位于对应参考中。

参阅[监督、恢复与 replay](/zh-cn/docs/framework/runtime-reliability/)，了解 `superviseApp`、`createReplaySession` 和 scoped 方法 `reportError`、`now`、`random`。

可选入口 `ai`、`timeline`、`devtools`、`mcp`、`store-sync`、`shadow`、`windows`、`dnd`、`ports`、`wuapp`、`sandbox/iframe` 和 `sandbox/html-parser` 具有公共类型声明。`typesVersions` 也支持使用 `moduleResolution: "node10"` 解析。请从已发布子路径导入类型，而非内部文件。