mini-three-adapter 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/AGENTS.md +85 -85
  2. package/README.md +159 -159
  3. package/dist/build/rollup.js +60 -9
  4. package/dist/build/rollup.js.map +1 -1
  5. package/dist/build/vite.js +60 -9
  6. package/dist/build/vite.js.map +1 -1
  7. package/dist/{chunk-Z7AMDRN3.js → chunk-3QUEDYTT.js} +12 -5
  8. package/dist/chunk-3QUEDYTT.js.map +1 -0
  9. package/dist/{chunk-WLRQDTSZ.js → chunk-52IMRKOX.js} +3 -3
  10. package/dist/{chunk-WLRQDTSZ.js.map → chunk-52IMRKOX.js.map} +1 -1
  11. package/dist/{chunk-3UGQWFH3.js → chunk-J7VBWZRR.js} +87 -27
  12. package/dist/chunk-J7VBWZRR.js.map +1 -0
  13. package/dist/{chunk-4UEBRAK6.js → chunk-LCJNTN6F.js} +19 -9
  14. package/dist/chunk-LCJNTN6F.js.map +1 -0
  15. package/dist/{chunk-MTBMOFAL.js → chunk-OL7NVZZJ.js} +29 -14
  16. package/dist/chunk-OL7NVZZJ.js.map +1 -0
  17. package/dist/{chunk-LB3WL24R.js → chunk-WZ2HKYC5.js} +8 -4
  18. package/dist/chunk-WZ2HKYC5.js.map +1 -0
  19. package/dist/core/index.d.ts +15 -5
  20. package/dist/core/index.js +2 -2
  21. package/dist/index.d.ts +2 -2
  22. package/dist/index.js +6 -6
  23. package/dist/platforms/browser.d.ts +2 -2
  24. package/dist/platforms/browser.js +3 -3
  25. package/dist/platforms/wechat-game.d.ts +2 -2
  26. package/dist/platforms/wechat-game.js +4 -4
  27. package/dist/platforms/wechat-miniprogram.d.ts +2 -2
  28. package/dist/platforms/wechat-miniprogram.js +4 -4
  29. package/dist/polyfills/index.d.ts +8 -1
  30. package/dist/polyfills/index.js +1 -1
  31. package/dist/{runtime-7uUOoFhC.d.ts → runtime-DnEkKZjo.d.ts} +1 -1
  32. package/dist/scope.d.ts +1 -1
  33. package/dist/{types-BzK0LQMa.d.ts → types-X_5SJh4y.d.ts} +7 -0
  34. package/docs/02-architecture.md +126 -126
  35. package/docs/03-module-map.md +99 -99
  36. package/docs/04-api-reference.md +294 -291
  37. package/docs/05-build-plugin.md +33 -5
  38. package/docs/06-platform-notes.md +116 -108
  39. package/docs/07-integration-guide.md +14 -0
  40. package/docs/09-testing-and-release.md +209 -206
  41. package/docs/10-ai-playbook.md +141 -140
  42. package/docs/11-compat-matrix.md +96 -94
  43. package/docs/adr/0007-capability-probe-fallback.md +57 -0
  44. package/docs/adr/README.md +1 -0
  45. package/llms.txt +69 -65
  46. package/package.json +1 -1
  47. package/dist/chunk-3UGQWFH3.js.map +0 -1
  48. package/dist/chunk-4UEBRAK6.js.map +0 -1
  49. package/dist/chunk-LB3WL24R.js.map +0 -1
  50. package/dist/chunk-MTBMOFAL.js.map +0 -1
  51. package/dist/chunk-Z7AMDRN3.js.map +0 -1
@@ -1,291 +1,294 @@
1
- # 04 · API 参考
2
-
3
- > 版本:0.1.0。所有签名以 `src/**` 与 `npm run build` 生成的 `dist/*.d.ts` 为准。
4
- > 子路径导入可最大化 tree-shaking;`mini-three-adapter` 是汇总入口。
5
-
6
- ## 4.1 子路径
7
-
8
- | 子路径 | 内容 |
9
- | --- | --- |
10
- | `mini-three-adapter` | 全部公开 API |
11
- | `mini-three-adapter/core` | 平台无关运行时 |
12
- | `mini-three-adapter/scope` | `getActiveScope()` 等(**构建插件注入的 import 目标**) |
13
- | `mini-three-adapter/wechat-game` | 小游戏入口 |
14
- | `mini-three-adapter/wechat-miniprogram` | 小程序入口 |
15
- | `mini-three-adapter/browser` | 浏览器 / H5 / Node 测试 |
16
- | `mini-three-adapter/polyfills` | 独立 polyfill |
17
- | `mini-three-adapter/vite` | Vite 插件 |
18
- | `mini-three-adapter/rollup` | Rollup 插件 + 高级 API |
19
- | `mini-three-adapter/plugin` | `vite` 的别名 |
20
- | `mini-three-adapter/package.json` | 读取包元信息(`version`、`exports`) |
21
-
22
- ---
23
-
24
- ## 4.2 生命周期
25
-
26
- ### `createRuntime(platform, options?) => Promise<MiniThreeRuntime>`
27
-
28
- 平台无关的总装配入口。通常不直接调用,而用下面的平台快捷函数。
29
-
30
- ```ts
31
- function createRuntime(
32
- platform: PlatformBinding | PlatformFactory,
33
- options?: RuntimeOptions,
34
- ): Promise<MiniThreeRuntime>;
35
- ```
36
-
37
- ### `createWeChatGameRuntime(options?) => Promise<MiniThreeRuntime>`
38
-
39
- ```ts
40
- interface WeChatGameOptions {
41
- wx?: WxLike; // 注入 wx(测试/非微信宿主)
42
- canvas?: WxCanvas; // 复用已有上屏画布
43
- capabilities?: Partial<Capabilities>;
44
- diagnostics?: Diagnostics;
45
- preferredFps?: number; // wx.setPreferredFramesPerSecond
46
- }
47
- type WeChatGameRuntimeOptions = WeChatGameOptions & RuntimeOptions;
48
- ```
49
-
50
- 另有 `createWeChatGameBinding(options) => PlatformBinding`(同步)、`getScreenCanvas(wx, supplied?)`、`resetScreenCanvasCache()`(测试用)。
51
-
52
- ### `createWeChatMiniProgramRuntime(options) => Promise<MiniThreeRuntime>`
53
-
54
- ```ts
55
- interface WeChatMiniProgramOptions {
56
- wx?: WxLike;
57
- selector: string; // 例如 '#gl'
58
- selectorCtx?: SelectorCtx; // 自定义组件内传 this
59
- queryDelay?: number; // 等待布局的毫秒数
60
- capabilities?: Partial<Capabilities>;
61
- diagnostics?: Diagnostics;
62
- }
63
- ```
64
-
65
- 另有 `createWeChatMiniProgramBinding(options) => Promise<PlatformBinding>`。
66
-
67
- ### `createBrowserRuntime(options?) => Promise<MiniThreeRuntime>`
68
-
69
- ```ts
70
- interface BrowserPlatformOptions {
71
- canvas?: HTMLCanvasElement;
72
- capabilities?: Partial<Capabilities>;
73
- diagnostics?: Diagnostics;
74
- }
75
- ```
76
-
77
- ---
78
-
79
- ### `RuntimeOptions`
80
-
81
- | 选项 | 类型 | 默认 | 说明 |
82
- | --- | --- | --- | --- |
83
- | `pixelRatioCap` | `number` | `2` | 限制 DPR,`0` 表示不封顶 |
84
- | `propagatePointerEvents` | `boolean` | `true` | 是否同时派发到 `document` / `window` |
85
- | `emitMouseEvents` | `boolean` | `true` | 是否额外发 `mouse*` / `click` |
86
- | `defaultContextType` | `'webgl2' \| 'webgl' \| '2d'` | `'webgl2'` | `document.createElement('canvas')` 的默认上下文 |
87
- | `cacheContexts` | `boolean` | `true` | 缓存 `getContext()` 结果,保证上下文身份稳定 |
88
- | `normalizeWebGL` | `boolean` | `true` | 修正 `getExtension` 返回值、`drawingBufferWidth/Height` |
89
- | `fpsCap` | `number` | `0` | 逻辑帧率上限 |
90
- | `slowFrameThreshold` | `number` | `0` | 慢帧告警阈值(ms) |
91
- | `logLevel` | `'silent' \| 'error' \| 'warn' \| 'info' \| 'debug'` | `'warn'` | 日志级别 |
92
- | `reporter` | `Reporter` | console | 自定义日志出口 |
93
- | `capabilities` | `Partial<Capabilities>` | — | 覆盖探测结果 |
94
- | `installGlobals` | `boolean` | `false` | 启动时立即注入全局(可逆) |
95
- | `diagnostics` | `Diagnostics` | — | 平台层注入(平台 options) |
96
-
97
- ### `MiniThreeRuntime`
98
-
99
- | 成员 | 类型 | 说明 |
100
- | --- | --- | --- |
101
- | `canvas` | `HTMLCanvasElement` | 已就地补丁的上屏/节点画布 |
102
- | `scope` | `MiniThreeScope` | 三方代码可见的作用域对象 |
103
- | `document` | `DocumentLike` | `createElement` / `createElementNS` / `body` / `defaultView` |
104
- | `capabilities` | `Capabilities` | 探测结果 |
105
- | `diagnostics` | `Diagnostics` | 日志与报告 |
106
- | `frames` | `FrameScheduler` | rAF / delta / fps |
107
- | `bridge` | `PointerBridge` | 事件桥 |
108
- | `windowInfo` | `WindowInfo` | 实时尺寸与 DPR(getter) |
109
- | `rendererHints` | `RendererHints` | 可直接展开给 `new THREE.WebGLRenderer()` |
110
- | `disposed` | `boolean` | 是否已释放 |
111
- | `handleTouch(event, opts?)` | `(TouchLikeEvent, {propagate?, computeRect?}) => void` | 手动转发触摸(小程序必需) |
112
- | `resize()` | `() => Promise<void>` | 重新测量并广播 resize |
113
- | `installGlobals(opts?)` | `() => Disposer` | 显式全局注入并返回还原函数 |
114
- | `createCanvas(w?, h?, type?)` | `() => HTMLCanvasElement` | 额外的离屏画布 |
115
- | `on(event, listener)` | `() => Disposer` | 见下表 |
116
- | `report()` | `() => string` | 能力报告文本 |
117
- | `dispose()` | `() => void` | 释放全部副作用 |
118
-
119
- `RuntimeEvents`:
120
-
121
- | 事件 | 回调 |
122
- | --- | --- |
123
- | `resize` | `(info: WindowInfo) => void` |
124
- | `visibilitychange` | `(visible: boolean) => void` |
125
- | `contextlost` | `() => void` |
126
- | `dispose` | `() => void` |
127
- | `error` | `(error: Error) => void` |
128
-
129
- `RendererHints`:`{ canvas, antialias: false, alpha: false, powerPreference: 'high-performance', preserveDrawingBuffer: false, outputColorSpace: 'srgb' }`。
130
-
131
- ---
132
-
133
- ## 4.3 作用域
134
-
135
- ```ts
136
- function createScope(overrides?: Partial<MiniThreeScope>): MiniThreeScope;
137
- function getActiveScope(): MiniThreeScope; // 未初始化时返回「可 typeof、取值即抛错」的占位
138
- function setActiveScope(scope: MiniThreeScope | null): () => void;
139
- function hasActiveScope(): boolean;
140
- function installGlobals(scope, options?): () => void;
141
- ```
142
-
143
- `MiniThreeScope` 同时扮演 `window` / `self` / `globalThis`(三者指向自身),并包含:
144
-
145
- - 领域对象:`document`、`navigator`、`screen`、`performance`、`getComputedStyle`、`matchMedia`;
146
- - 尺寸:`innerWidth`、`innerHeight`、`outerWidth`、`outerHeight`、`devicePixelRatio`、`pageXOffset`、`pageYOffset`(均为 live getter);
147
- - 事件:`Event`、`EventTarget`、`CustomEvent`、`PointerEvent`、`MouseEvent`、`TouchEvent`、`MessageEvent`、`ProgressEvent`、`KeyboardEvent`、`DOMException`;
148
- - DOM:`HTMLElement`、`HTMLCanvasElement`、`HTMLImageElement`、`OffscreenCanvas`、`Image`、`ImageData`、`DOMRect`、`WebGLRenderingContext`、`WebGL2RenderingContext`、`AudioContext`;
149
- - 网络/编码:`Blob`、`URL`、`TextEncoder`、`TextDecoder`、`fetch`、`XMLHttpRequest`、`AbortController`、`AbortSignal`、`atob`、`btoa`;
150
- - 帧:`requestAnimationFrame`、`cancelAnimationFrame`;
151
- - 明确不可用:`createImageBitmap`、`FileReader`、`WebSocket` 为 `undefined`(让 three 走降级分支)。
152
-
153
- `installGlobals(scope, { target?, skipExisting?, extraKeys? })` 把上述键定义为 `globalThis` 上的 getter;返回的 disposer 会精确还原原有 descriptor。
154
-
155
- ---
156
-
157
- ## 4.4 core 子路径
158
-
159
- | API | 签名 / 说明 |
160
- | --- | --- |
161
- | `patchElement(instance, options)` | 就地补 DOM 属性,返回 `{ element, updateRect, disposers }` |
162
- | `createMockClass(name)` | 生成带 `Symbol.hasInstance` + `WeakSet` 的构造器 shim |
163
- | `markAs(ctor, obj)` / `isMarked(ctor, obj)` | 注册 / 查询 instanceof 关系 |
164
- | `*Shim` | `HTMLCanvasElementShim`、`HTMLImageElementShim`、`HTMLElementShim`、`OffscreenCanvasShim`、`ImageDataShim`、`WebGLRenderingContextShim`、`WebGL2RenderingContextShim`、`DOMRectShim` |
165
- | `patchCanvas(raw, options)` | 返回 `{ canvas, contexts, updateRect, element, disposers }` |
166
- | `createOffscreenCanvas(wx, w?, h?, options?)` | 直接创建并补丁离屏画布 |
167
- | `createImageFactory(wx, diagnostics?)` | `{ Image, HTMLImageElement, ImageData, createImage, createImageData, createImageBitmap: undefined }` |
168
- | `createDocument(options)` / `createScreen(w, h)` / `ShimDOMRect` | 伪 DOM 容器 |
169
- | `PointerBridge` | `dispatch(event, opts?)`、`dispatchMouse(event)`、`setRect`、`refreshRect`、`setPointerCapture`、`releasePointerCapture`、`activePointerCount`、`dispose` |
170
- | `createFrameScheduler(raf, caf, options)` | `request` / `cancel` / `loop(cb)` / `setFpsCap` / `fps` / `dispose` |
171
- | `createWindowInfoStore(wx, options)` | `info` / `refresh()` / `onChange()` / `setPixelRatioCap()` / `dispose()` |
172
- | `detectCapabilities(wx, platform, options)` / `versionAtLeast(a, b)` | 能力探测 |
173
- | `createDiagnostics(level, reporter)` / `capabilityReport(caps)` | 日志与报告 |
174
- | `currentScope()` | 返回当前作用域或 `null` |
175
-
176
- ### `PlatformBinding`(新增平台时实现)
177
-
178
- ```ts
179
- interface PlatformBinding {
180
- readonly kind: 'wechat-game' | 'wechat-miniprogram' | 'browser' | 'unknown';
181
- readonly wx?: WxLike;
182
- readonly rawCanvas: WxCanvas;
183
- readonly capabilities: Capabilities;
184
- readonly imageFactory: ImageFactory;
185
- getCanvasRect(): Rect | Promise<Rect>;
186
- createOffscreenCanvas(w: number, h: number, type: ContextType): WxCanvas;
187
- watchTouch(handler: (e: TouchLikeEvent) => void): Disposer;
188
- watchVisibility(handler: (visible: boolean) => void): Disposer;
189
- requestAnimationFrame(cb: (time: number) => void): number;
190
- cancelAnimationFrame(id: number): void;
191
- now(): number;
192
- dispose(): void;
193
- }
194
- ```
195
-
196
- ---
197
-
198
- ## 4.5 polyfills 子路径
199
-
200
- | API | 说明 |
201
- | --- | --- |
202
- | `MiniEvent` / `MiniCustomEvent` / `MiniPointerEvent` / `MiniMouseEvent` / `MiniMessageEvent` / `MiniProgressEvent` / `MiniDOMException` | 事件对象 |
203
- | `MiniEventTarget` / `patchEventTarget(obj)` | 事件目标;`patchEventTarget` 不改变对象身份 |
204
- | `MiniBlob` | `bytes()`、`arrayBuffer()`、`text()`、`slice()`、`dataURL()`、`size`、`type` |
205
- | `MiniURL` | `createObjectURL` / `revokeObjectURL` / `resolveObjectURL` / `clearObjectURLs`;构造器支持相对路径解析 |
206
- | `MiniURLSearchParams` | `get` / `set` / `toString` |
207
- | `bytesToBase64` / `base64ToBytes` / `resolveUrl` | 编码与 URL 工具 |
208
- | `atob` / `btoa` / `MiniTextEncoder` / `MiniTextDecoder` | 编码 |
209
- | `createFetch(wx)` / `MiniXMLHttpRequest` / `createXMLHttpRequestFactory(wx)` / `MiniAbortController` / `MiniAbortSignal` | 网络 |
210
-
211
- > 注意:对象 URL 采用 `mini-three-blob:` 前缀并解析为 `data:` URI,而不是浏览器 `blob:` ——因为微信 image loader 只认 `data:` / 本地路径。
212
-
213
- ---
214
-
215
- ## 4.6 构建插件
216
-
217
- ### Vite
218
-
219
- ```ts
220
- import miniThree from 'mini-three-adapter/vite';
221
- plugins: [miniThree(options)];
222
- ```
223
-
224
- 插件额外提供 `config()`,设置 `optimizeDeps.exclude: ['three', 'three-stdlib', 'three/examples/jsm']`,确保 AST 重写见到原始 ESM 模块图。
225
-
226
- ### Rollup
227
-
228
- ```ts
229
- import { miniThree } from 'mini-three-adapter/rollup';
230
- plugins: [miniThree(options)];
231
- ```
232
-
233
- ### `MiniThreePluginOptions`
234
-
235
- | 选项 | 类型 | 默认 | 说明 |
236
- | --- | --- | --- | --- |
237
- | `include` | `(id: string) => boolean` | 匹配 `three` / `three-stdlib` / `@react-three` / `@tresjs` / `.vite/deps/three*` | 需要重写的模块 |
238
- | `exclude` | `(id: string) => boolean` | `() => false` | 排除 |
239
- | `includeUserCode` | `boolean` | `false` | 是否也改写应用代码 |
240
- | `rewrite` | `RewriteOptions` | — | 高级重写配置 |
241
- | `webgpu` | `'warn' \| 'error' \| 'rewrite' \| 'ignore'` | `'warn'` | 遇到 `three/webgpu` 的策略 |
242
- | `roots` | `string[]` | three jsm/libs、`three-stdlib`、`public`、`static` | 资源搜索目录 |
243
- | `outputDir` | `string` | `'assets/three'` | 资源输出目录 |
244
- | `brotli` | `boolean` | `true` | 同时拷贝 `.wasm.br` |
245
- | `manifest` | `boolean` | `true` | 输出 `mini-three-assets.json` |
246
- | `cwd` | `string` | `process.cwd()` | 解析 roots 的根目录 |
247
- | `report` | `boolean` | `true` | 打印构建摘要 |
248
- | `debug` | `boolean` | `false` | 逐模块日志 |
249
-
250
- ### `RewriteOptions`
251
-
252
- | 选项 | 默认 | 说明 |
253
- | --- | --- | --- |
254
- | `globals` | `DEFAULT_GLOBAL_NAMES` | 替换默认清单(而非追加) |
255
- | `extraGlobals` | `[]` | 追加清单 |
256
- | `forceUndef` | `['createImageBitmap']` | 强制走 `__m3().x`(作用域中恒为 `undefined`) |
257
- | `accessor` | `'__m3'` | 注入的 `getActiveScope` 别名 |
258
- | `scopeModule` | `'mini-three-adapter/scope'` | 注入的 import 路径 |
259
-
260
- ### 高级导出(`mini-three-adapter/rollup`)
261
-
262
- `rewriteGlobals(code, id, options)`、`DEFAULT_GLOBAL_NAMES`、`DEFAULT_FORCE_UNDEF`、`collectAssetReferences`、`collectAssets`、`copyAssets`、`miniThreePlugin`。
263
-
264
- `plugin.api.report()` → `BuildReport`:`modulesScanned`、`modulesRewritten`、`rewrites`、`globalsSeen`、`assetReferences`、`missingAssets`、`webgpuWarnings`、`parseFailures`。
265
-
266
- ---
267
-
268
- ## 4.7 类型速查
269
-
270
- ```ts
271
- interface Capabilities {
272
- platform: 'wechat-game' | 'wechat-miniprogram' | 'browser' | 'unknown';
273
- webgl2: boolean; webgl1: boolean; offscreenCanvas: boolean;
274
- worker: boolean; wasm: boolean; brotliWasm: boolean; nativeImage: boolean;
275
- triggerGC: boolean; getWindowInfo: boolean; windowResizeEvent: boolean;
276
- baseLibraryVersion: string;
277
- }
278
-
279
- interface WindowInfo {
280
- width: number; height: number; pixelRatio: number; rawPixelRatio: number;
281
- safeArea?: Rect;
282
- }
283
-
284
- interface Rect { top: number; left: number; width: number; height: number; right: number; bottom: number; }
285
-
286
- interface TouchLikeEvent {
287
- type: string; touches?: ArrayLike<TouchPoint>;
288
- changedTouches?: ArrayLike<TouchPoint>; timeStamp?: number;
289
- [key: string]: unknown;
290
- }
291
- ```
1
+ # 04 · API 参考
2
+
3
+ > 版本:0.1.0。所有签名以 `src/**` 与 `npm run build` 生成的 `dist/*.d.ts` 为准。
4
+ > 子路径导入可最大化 tree-shaking;`mini-three-adapter` 是汇总入口。
5
+
6
+ ## 4.1 子路径
7
+
8
+ | 子路径 | 内容 |
9
+ | --- | --- |
10
+ | `mini-three-adapter` | 全部公开 API |
11
+ | `mini-three-adapter/core` | 平台无关运行时 |
12
+ | `mini-three-adapter/scope` | `getActiveScope()` 等(**构建插件注入的 import 目标**) |
13
+ | `mini-three-adapter/wechat-game` | 小游戏入口 |
14
+ | `mini-three-adapter/wechat-miniprogram` | 小程序入口 |
15
+ | `mini-three-adapter/browser` | 浏览器 / H5 / Node 测试 |
16
+ | `mini-three-adapter/polyfills` | 独立 polyfill |
17
+ | `mini-three-adapter/vite` | Vite 插件 |
18
+ | `mini-three-adapter/rollup` | Rollup 插件 + 高级 API |
19
+ | `mini-three-adapter/plugin` | `vite` 的别名 |
20
+ | `mini-three-adapter/package.json` | 读取包元信息(`version`、`exports`) |
21
+
22
+ ---
23
+
24
+ ## 4.2 生命周期
25
+
26
+ ### `createRuntime(platform, options?) => Promise<MiniThreeRuntime>`
27
+
28
+ 平台无关的总装配入口。通常不直接调用,而用下面的平台快捷函数。
29
+
30
+ ```ts
31
+ function createRuntime(
32
+ platform: PlatformBinding | PlatformFactory,
33
+ options?: RuntimeOptions,
34
+ ): Promise<MiniThreeRuntime>;
35
+ ```
36
+
37
+ ### `createWeChatGameRuntime(options?) => Promise<MiniThreeRuntime>`
38
+
39
+ ```ts
40
+ interface WeChatGameOptions {
41
+ wx?: WxLike; // 注入 wx(测试/非微信宿主)
42
+ canvas?: WxCanvas; // 复用已有上屏画布
43
+ capabilities?: Partial<Capabilities>;
44
+ diagnostics?: Diagnostics;
45
+ preferredFps?: number; // wx.setPreferredFramesPerSecond
46
+ }
47
+ type WeChatGameRuntimeOptions = WeChatGameOptions & RuntimeOptions;
48
+ ```
49
+
50
+ 另有 `createWeChatGameBinding(options) => PlatformBinding`(同步)、`getScreenCanvas(wx, supplied?)`、`resetScreenCanvasCache()`(测试用)。
51
+
52
+ ### `createWeChatMiniProgramRuntime(options) => Promise<MiniThreeRuntime>`
53
+
54
+ ```ts
55
+ interface WeChatMiniProgramOptions {
56
+ wx?: WxLike;
57
+ selector: string; // 例如 '#gl'
58
+ selectorCtx?: SelectorCtx; // 自定义组件内传 this
59
+ queryDelay?: number; // 等待布局的毫秒数
60
+ capabilities?: Partial<Capabilities>;
61
+ diagnostics?: Diagnostics;
62
+ }
63
+ ```
64
+
65
+ 另有 `createWeChatMiniProgramBinding(options) => Promise<PlatformBinding>`。
66
+
67
+ ### `createBrowserRuntime(options?) => Promise<MiniThreeRuntime>`
68
+
69
+ ```ts
70
+ interface BrowserPlatformOptions {
71
+ canvas?: HTMLCanvasElement;
72
+ capabilities?: Partial<Capabilities>;
73
+ diagnostics?: Diagnostics;
74
+ }
75
+ ```
76
+
77
+ ---
78
+
79
+ ### `RuntimeOptions`
80
+
81
+ | 选项 | 类型 | 默认 | 说明 |
82
+ | --- | --- | --- | --- |
83
+ | `pixelRatioCap` | `number` | `2` | 限制 DPR,`0` 表示不封顶 |
84
+ | `propagatePointerEvents` | `boolean` | `true` | 是否同时派发到 `document` / `window` |
85
+ | `emitMouseEvents` | `boolean` | `true` | 是否额外发 `mouse*` / `click` |
86
+ | `defaultContextType` | `'webgl2' \| 'webgl' \| '2d'` | `'webgl2'` | `document.createElement('canvas')` 的默认上下文 |
87
+ | `cacheContexts` | `boolean` | `true` | 缓存 `getContext()` 结果,保证上下文身份稳定 |
88
+ | `normalizeWebGL` | `boolean` | `true` | 修正 `getExtension` 返回值、`drawingBufferWidth/Height` |
89
+ | `fpsCap` | `number` | `0` | 逻辑帧率上限 |
90
+ | `slowFrameThreshold` | `number` | `0` | 慢帧告警阈值(ms) |
91
+ | `logLevel` | `'silent' \| 'error' \| 'warn' \| 'info' \| 'debug'` | `'warn'` | 日志级别 |
92
+ | `reporter` | `Reporter` | console | 自定义日志出口 |
93
+ | `capabilities` | `Partial<Capabilities>` | — | 覆盖探测结果 |
94
+ | `installGlobals` | `boolean` | `false` | 启动时立即注入全局(可逆) |
95
+ | `diagnostics` | `Diagnostics` | — | 平台层注入(平台 options) |
96
+
97
+ ### `MiniThreeRuntime`
98
+
99
+ | 成员 | 类型 | 说明 |
100
+ | --- | --- | --- |
101
+ | `canvas` | `HTMLCanvasElement` | 已就地补丁的上屏/节点画布 |
102
+ | `scope` | `MiniThreeScope` | 三方代码可见的作用域对象 |
103
+ | `document` | `DocumentLike` | `createElement` / `createElementNS` / `body` / `defaultView` |
104
+ | `capabilities` | `Capabilities` | 探测结果 |
105
+ | `diagnostics` | `Diagnostics` | 日志与报告 |
106
+ | `frames` | `FrameScheduler` | rAF / delta / fps |
107
+ | `bridge` | `PointerBridge` | 事件桥 |
108
+ | `windowInfo` | `WindowInfo` | 实时尺寸与 DPR(getter) |
109
+ | `rendererHints` | `RendererHints` | 可直接展开给 `new THREE.WebGLRenderer()` |
110
+ | `disposed` | `boolean` | 是否已释放 |
111
+ | `handleTouch(event, opts?)` | `(TouchLikeEvent, {propagate?, computeRect?}) => void` | 手动转发触摸(小程序必需) |
112
+ | `resize()` | `() => Promise<void>` | 重新测量并广播 resize |
113
+ | `installGlobals(opts?)` | `() => Disposer` | 显式全局注入并返回还原函数 |
114
+ | `createCanvas(w?, h?, type?)` | `() => HTMLCanvasElement` | 额外的离屏画布 |
115
+ | `on(event, listener)` | `() => Disposer` | 见下表 |
116
+ | `report()` | `() => string` | 能力报告文本 |
117
+ | `dispose()` | `() => void` | 释放全部副作用 |
118
+
119
+ `RuntimeEvents`:
120
+
121
+ | 事件 | 回调 |
122
+ | --- | --- |
123
+ | `resize` | `(info: WindowInfo) => void` |
124
+ | `visibilitychange` | `(visible: boolean) => void` |
125
+ | `contextlost` | `() => void` |
126
+ | `dispose` | `() => void` |
127
+ | `error` | `(error: Error) => void` |
128
+
129
+ `RendererHints`:`{ canvas, antialias: false, alpha: false, powerPreference: 'high-performance', preserveDrawingBuffer: false, outputColorSpace: 'srgb' }`。
130
+
131
+ ---
132
+
133
+ ## 4.3 作用域
134
+
135
+ ```ts
136
+ function createScope(overrides?: Partial<MiniThreeScope>): MiniThreeScope;
137
+ function getActiveScope(): MiniThreeScope; // 未初始化时返回「可 typeof、取值即抛错」的占位
138
+ function setActiveScope(scope: MiniThreeScope | null): () => void;
139
+ function hasActiveScope(): boolean;
140
+ function installGlobals(scope, options?): () => void;
141
+ ```
142
+
143
+ `MiniThreeScope` 同时扮演 `window` / `self` / `globalThis`(三者指向自身),并包含:
144
+
145
+ - 领域对象:`document`、`navigator`、`screen`、`performance`、`getComputedStyle`、`matchMedia`;
146
+ - 尺寸:`innerWidth`、`innerHeight`、`outerWidth`、`outerHeight`、`devicePixelRatio`、`pageXOffset`、`pageYOffset`(均为 live getter);
147
+ - 事件:`Event`、`EventTarget`、`CustomEvent`、`PointerEvent`、`MouseEvent`、`TouchEvent`、`MessageEvent`、`ProgressEvent`、`KeyboardEvent`、`DOMException`;
148
+ - DOM:`HTMLElement`、`HTMLCanvasElement`、`HTMLImageElement`、`OffscreenCanvas`、`Image`、`ImageData`、`DOMRect`、`WebGLRenderingContext`、`WebGL2RenderingContext`、`AudioContext`;
149
+ - 网络/编码:`Blob`、`URL`、`TextEncoder`、`TextDecoder`、`fetch`、`XMLHttpRequest`、`AbortController`、`AbortSignal`、`atob`、`btoa`;
150
+ - 帧:`requestAnimationFrame`、`cancelAnimationFrame`;
151
+ - 明确不可用:`createImageBitmap`、`FileReader`、`WebSocket` 为 `undefined`(让 three 走降级分支)。
152
+
153
+ `installGlobals(scope, { target?, skipExisting?, extraKeys? })` 把上述键定义为 `globalThis` 上的 getter;返回的 disposer 会精确还原原有 descriptor。
154
+
155
+ ---
156
+
157
+ ## 4.4 core 子路径
158
+
159
+ | API | 签名 / 说明 |
160
+ | --- | --- |
161
+ | `patchElement(instance, options)` | 就地补 DOM 属性,返回 `{ element, updateRect, disposers }` |
162
+ | `createMockClass(name)` | 生成带 `Symbol.hasInstance` + `WeakSet` 的构造器 shim |
163
+ | `markAs(ctor, obj)` / `isMarked(ctor, obj)` | 注册 / 查询 instanceof 关系 |
164
+ | `*Shim` | `HTMLCanvasElementShim`、`HTMLImageElementShim`、`HTMLElementShim`、`OffscreenCanvasShim`、`ImageDataShim`、`WebGLRenderingContextShim`、`WebGL2RenderingContextShim`、`DOMRectShim` |
165
+ | `patchCanvas(raw, options)` | 返回 `{ canvas, contexts, updateRect, element, disposers }` |
166
+ | `createOffscreenCanvas(wx, w?, h?, options?)` | 直接创建并补丁离屏画布 |
167
+ | `createImageFactory(wx, diagnostics?)` | `{ Image, HTMLImageElement, ImageData, createImage, createImageData, createImageBitmap: undefined }`。工厂会把底层 `wx` 图片的**原生** `onload`/`onerror` 桥接成合成事件:`img.onload = fn` 与 `addEventListener('load', fn)` 都能收到通知,`decode()` 也据此 settle |
168
+ | `createDocument(options)` / `createScreen(w, h)` / `ShimDOMRect` | 伪 DOM 容器 |
169
+ | `PointerBridge` | `dispatch(event, opts?)`、`dispatchMouse(event)`、`setRect`、`refreshRect`、`setPointerCapture`、`releasePointerCapture`、`activePointerCount`、`dispose` |
170
+ | `createFrameScheduler(raf, caf, options)` | `request` / `cancel` / `loop(cb)` / `setFpsCap` / `fps` / `dispose` |
171
+ | `createWindowInfoStore(wx, options)` | `info` / `refresh()` / `onChange()` / `setPixelRatioCap()` / `dispose()` |
172
+ | `detectCapabilities(wx, platform, options)` / `versionAtLeast(a, b)` | 能力探测。`options.probeContext(type)` 返回 `true` / `false` / `undefined`,**`undefined` 表示「探测不到」而不是「不支持」**,此时 `webgl2` 按基础库版本推断并在 `webgl2Source` 里标记为 `'inferred'` |
173
+ | `createDiagnostics(level, reporter)` / `capabilityReport(caps)` | 日志与报告 |
174
+ | `currentScope()` | 返回当前作用域或 `null` |
175
+
176
+ ### `PlatformBinding`(新增平台时实现)
177
+
178
+ ```ts
179
+ interface PlatformBinding {
180
+ readonly kind: 'wechat-game' | 'wechat-miniprogram' | 'browser' | 'unknown';
181
+ readonly wx?: WxLike;
182
+ readonly rawCanvas: WxCanvas;
183
+ readonly capabilities: Capabilities;
184
+ readonly imageFactory: ImageFactory;
185
+ getCanvasRect(): Rect | Promise<Rect>;
186
+ createOffscreenCanvas(w: number, h: number, type: ContextType): WxCanvas;
187
+ watchTouch(handler: (e: TouchLikeEvent) => void): Disposer;
188
+ watchVisibility(handler: (visible: boolean) => void): Disposer;
189
+ requestAnimationFrame(cb: (time: number) => void): number;
190
+ cancelAnimationFrame(id: number): void;
191
+ now(): number;
192
+ dispose(): void;
193
+ }
194
+ ```
195
+
196
+ ---
197
+
198
+ ## 4.5 polyfills 子路径
199
+
200
+ | API | 说明 |
201
+ | --- | --- |
202
+ | `MiniEvent` / `MiniCustomEvent` / `MiniPointerEvent` / `MiniMouseEvent` / `MiniMessageEvent` / `MiniProgressEvent` / `MiniDOMException` | 事件对象 |
203
+ | `MiniEventTarget` / `patchEventTarget(obj)` | 事件目标;`patchEventTarget` 不改变对象身份。监听器被调用时 `this`、`event.target`、`event.currentTarget` 都是**宿主元素**而不是内部载体——three 的 `ImageLoader` 用 `this` 取 `<img>` 当纹理源,拿错对象就等于没有像素 |
204
+ | `MiniBlob` | `bytes()`、`arrayBuffer()`、`text()`、`slice()`、`dataURL()`、`size`、`type` |
205
+ | `MiniURL` | `createObjectURL` / `revokeObjectURL` / `resolveObjectURL` / `clearObjectURLs`;构造器支持相对路径解析 |
206
+ | `MiniURLSearchParams` | `get` / `set` / `toString` |
207
+ | `bytesToBase64` / `base64ToBytes` / `resolveUrl` | 编码与 URL 工具 |
208
+ | `atob` / `btoa` / `MiniTextEncoder` / `MiniTextDecoder` | 编码 |
209
+ | `createFetch(wx)` / `MiniXMLHttpRequest` / `createXMLHttpRequestFactory(wx)` / `MiniAbortController` / `MiniAbortSignal` | 网络 |
210
+
211
+ > 注意:对象 URL 采用 `mini-three-blob:` 前缀并解析为 `data:` URI,而不是浏览器 `blob:` ——因为微信 image loader 只认 `data:` / 本地路径。
212
+
213
+ ---
214
+
215
+ ## 4.6 构建插件
216
+
217
+ ### Vite
218
+
219
+ ```ts
220
+ import miniThree from 'mini-three-adapter/vite';
221
+ plugins: [miniThree(options)];
222
+ ```
223
+
224
+ 插件额外提供 `config()`,设置 `optimizeDeps.exclude: ['three', 'three-stdlib', 'three/examples/jsm']`,确保 AST 重写见到原始 ESM 模块图。
225
+
226
+ ### Rollup
227
+
228
+ ```ts
229
+ import { miniThree } from 'mini-three-adapter/rollup';
230
+ plugins: [miniThree(options)];
231
+ ```
232
+
233
+ ### `MiniThreePluginOptions`
234
+
235
+ | 选项 | 类型 | 默认 | 说明 |
236
+ | --- | --- | --- | --- |
237
+ | `include` | `(id: string) => boolean` | 匹配 `three` / `three-stdlib` / `@react-three` / `@tresjs` / `.vite/deps/three*` | 需要重写的模块 |
238
+ | `exclude` | `(id: string) => boolean` | `() => false` | 排除 |
239
+ | `includeUserCode` | `boolean` | `false` | 是否也改写应用代码 |
240
+ | `rewrite` | `RewriteOptions` | — | 高级重写配置 |
241
+ | `webgpu` | `'warn' \| 'error' \| 'rewrite' \| 'ignore'` | `'warn'` | 遇到 `three/webgpu` 的策略 |
242
+ | `roots` | `string[]` | three jsm/libs、`three-stdlib`、`public`、`static` | 资源搜索目录 |
243
+ | `outputDir` | `string` | `'assets/three'` | 资源输出目录 |
244
+ | `brotli` | `boolean` | `true` | 同时拷贝 `.wasm.br` |
245
+ | `manifest` | `boolean` | `true` | 输出 `mini-three-assets.json` |
246
+ | `cwd` | `string` | `process.cwd()` | 解析 roots 的根目录 |
247
+ | `report` | `boolean` | `true` | 打印构建摘要 |
248
+ | `debug` | `boolean` | `false` | 逐模块日志 |
249
+
250
+ ### `RewriteOptions`
251
+
252
+ | 选项 | 默认 | 说明 |
253
+ | --- | --- | --- |
254
+ | `globals` | `DEFAULT_GLOBAL_NAMES` | 替换默认清单(而非追加) |
255
+ | `extraGlobals` | `[]` | 追加清单 |
256
+ | `forceUndef` | `['createImageBitmap']` | 强制走 `__m3().x`(作用域中恒为 `undefined`) |
257
+ | `accessor` | `'__m3'` | 注入的 `getActiveScope` 别名 |
258
+ | `scopeModule` | `'mini-three-adapter/scope'` | 注入的 import 路径 |
259
+
260
+ ### 高级导出(`mini-three-adapter/rollup`)
261
+
262
+ `rewriteGlobals(code, id, options)`、`DEFAULT_GLOBAL_NAMES`、`DEFAULT_FORCE_UNDEF`、`collectAssetReferences`、`collectAssets`、`copyAssets`、`miniThreePlugin`。
263
+
264
+ `plugin.api.report()` → `BuildReport`:`modulesScanned`、`modulesRewritten`、`rewrites`、`globalsSeen`、`assetReferences`、`missingAssets`、`webgpuWarnings`、`parseFailures`。
265
+
266
+ ---
267
+
268
+ ## 4.7 类型速查
269
+
270
+ ```ts
271
+ interface Capabilities {
272
+ platform: 'wechat-game' | 'wechat-miniprogram' | 'browser' | 'unknown';
273
+ webgl2: boolean;
274
+ /** 'probe' 实测 / 'inferred' 版本推断 / 'override' 调用方覆盖 */
275
+ webgl2Source?: 'probe' | 'inferred' | 'override';
276
+ webgl1: boolean; offscreenCanvas: boolean;
277
+ worker: boolean; wasm: boolean; brotliWasm: boolean; nativeImage: boolean;
278
+ triggerGC: boolean; getWindowInfo: boolean; windowResizeEvent: boolean;
279
+ baseLibraryVersion: string;
280
+ }
281
+
282
+ interface WindowInfo {
283
+ width: number; height: number; pixelRatio: number; rawPixelRatio: number;
284
+ safeArea?: Rect;
285
+ }
286
+
287
+ interface Rect { top: number; left: number; width: number; height: number; right: number; bottom: number; }
288
+
289
+ interface TouchLikeEvent {
290
+ type: string; touches?: ArrayLike<TouchPoint>;
291
+ changedTouches?: ArrayLike<TouchPoint>; timeStamp?: number;
292
+ [key: string]: unknown;
293
+ }
294
+ ```