@makoojs/core 0.3.1 → 0.4.0

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.
package/README.CN.md CHANGED
@@ -1,718 +1,287 @@
1
- # 核心 API
1
+ # @makoojs/core
2
2
 
3
- ## API 索引
3
+ `@makoojs/core` 是 Makoo 的框架无关运行时核心。它负责声明注入任务、启动任务批次、等待目标 DOM、挂载 artifact、管理 alive 重新注入、绑定事件监听,并提供生命周期观察、日志和错误基础设施。
4
4
 
5
- ### 任务
5
+ > [!NOTE]
6
+ > `@makoojs/core` 提供 Makoo 的公共运行时协议,其他 Makoo 包会直接或间接使用这里的类型和能力。
6
7
 
7
- - [`createMakoo()`](#createmakoo):创建运行时
8
- - [`inject()`](#inject):声明 component 任务
9
- - [`listen()`](#listen):声明 listener 任务
8
+ ## 使用场景
10
9
 
11
- ### 观察和状态
10
+ - 编写自定义 `ResolvableMountAdapter`,让 Makoo 挂载新的 artifact 类型。
11
+ - 使用 `createMakoo()` 创建运行时,并显式启动任务声明。
12
+ - 监听注入生命周期事件,用于调试、埋点、错误上报或可视化开发工具。
13
+ - 使用 `DOMWatcher`、`createActivityStore` 等底层工具构建自定义运行时集成。
12
14
 
13
- - [`createObserverHub()`](#createobserverhub):创建生命周期事件中心
14
- - [`createActivityStore()`](#createactivitystore):创建可订阅状态
15
- - [`DOMWatcher`](#domwatcher):观察 DOM 目标
15
+ ## 安装
16
16
 
17
- ### 基础能力
18
-
19
- - [`Logger`](#logger):日志实现
20
- - [错误类](#错误类):结构化错误
21
- - [常量](#常量):动作、事件名和错误码
22
-
23
- ### TypeScript 类型
24
-
25
- - [Adapter 类型](#adapter-类型)
26
- - [任务类型](#任务类型)
27
- - [观察类型](#观察类型)
28
- - [Signal 类型](#signal-类型)
29
- - [日志类型](#日志类型)
30
- - [错误类型](#错误类型)
31
-
32
- ## `createMakoo()`
33
-
34
- 创建一个 Makoo 运行时。
35
-
36
- ### Type
37
-
38
- ```ts
39
- function createMakoo(options?: CreateMakooOptions): MakooRuntime;
17
+ ```bash
18
+ # npm install @makoojs/core
19
+ # yarn add @makoojs/core
20
+ pnpm add @makoojs/core
40
21
  ```
41
22
 
42
- ### Parameters
43
-
44
- `options` 使用 `CreateMakooOptions`:
45
-
46
- | 字段 | 类型 | 默认值 | 说明 |
47
- | --- | --- | --- | --- |
48
- | `defaults` | `Partial<MakooDefaults>` | `{}` | 设置 injection 的默认选项 |
49
- | `adapters` | `ResolvableMountAdapter[]` | `[]` | 注册可用于挂载 artifact 的 adapter |
50
- | `hooks` | `LifecycleHookMap` | `undefined` | 注册全局生命周期 hooks |
51
- | `logger` | `ILogger` | `new Logger()` | 设置日志实现 |
52
- | `observer` | `ObserverHub` | `createObserverHub(logger)` | 设置生命周期事件中心 |
53
-
54
- ### Details
55
-
56
- `defaults` 的最终默认值:
23
+ ## 最小运行时示例
57
24
 
58
25
  ```ts
59
- {
60
- alive: false,
61
- scope: 'local',
62
- timeout: 5000
63
- }
64
- ```
65
-
66
- ### Returns
67
-
68
- 返回 `MakooRuntime`:
26
+ import {
27
+ createMakoo,
28
+ inject,
29
+ type ResolvableMountAdapter
30
+ } from '@makoojs/core';
69
31
 
70
- | 方法 | 返回值 | 说明 |
71
- | --- | --- | --- |
72
- | `start(tasks)` | `StartedTasks` | 注册并启动一批 `MakooTaskDeclaration`;空数组会抛出 `TaskError` |
73
- | `reset(taskId)` | `void` | 重置指定任务并释放当前资源 |
74
- | `destroy(taskId)` | `void` | 销毁并移除指定任务 |
75
- | `resetAll()` | `void` | 重置当前运行时中的全部任务 |
76
- | `destroyAll()` | `void` | 销毁当前运行时中的全部任务 |
77
- | `enableAlive(taskId)` | `void` | 为 component 任务启用 alive 观察 |
78
- | `disableAlive(taskId)` | `void` | 为 component 任务关闭 alive 观察 |
79
- | `on(event, hook)` | `() => void` | 监听指定事件,返回取消监听函数 |
80
- | `onTask(taskId, event, hook)` | `() => void` | 监听指定任务的指定事件,返回取消监听函数 |
81
- | `onAny(hook)` | `() => void` | 监听全部事件,返回取消监听函数 |
82
- | `off(event, hook?)` | `void` | 移除指定事件的一个或全部 hook |
83
- | `offTask(taskId, event?, hook?)` | `void` | 按任务移除 hook |
84
- | `offAny(hook)` | `void` | 移除通过 `onAny()` 注册的 hook |
85
- | `getLogger()` | `ILogger` | 返回当前日志实现 |
86
-
87
- 重复的任务 ID 不会再次注册,也不会出现在本次 `start()` 返回的 `StartedTasks.tasks` 中。
32
+ type TextArtifact = {
33
+ kind: 'text';
34
+ text: string;
35
+ };
88
36
 
89
- ### Example
37
+ const textAdapter: ResolvableMountAdapter<TextArtifact, HTMLElement> = {
38
+ name: 'text',
39
+ matches(artifact): artifact is TextArtifact {
40
+ return (
41
+ typeof artifact === 'object' &&
42
+ artifact !== null &&
43
+ (artifact as { kind?: unknown }).kind === 'text'
44
+ );
45
+ },
46
+ mount({ mountPoint, artifact }) {
47
+ const el = document.createElement('span');
48
+ el.textContent = artifact.text;
49
+ mountPoint.appendChild(el);
50
+
51
+ return { handle: el };
52
+ },
53
+ unmount({ handle }) {
54
+ handle.remove();
55
+ }
56
+ };
90
57
 
91
- ```ts
92
58
  const makoo = createMakoo({
93
- adapters: [adapter]
59
+ defaults: {
60
+ alive: true,
61
+ scope: 'local',
62
+ timeout: 5000
63
+ },
64
+ adapters: [textAdapter]
94
65
  });
95
66
 
96
- const started = makoo.start([
97
- inject({ injectAt: '#app', artifact })
67
+ makoo.start([
68
+ inject({
69
+ id: 'text',
70
+ injectAt: '#app',
71
+ artifact: {
72
+ kind: 'text',
73
+ text: 'Hello from Makoo core'
74
+ }
75
+ })
98
76
  ]);
99
77
  ```
100
78
 
101
- ## `inject()`
102
-
103
- 创建 component 任务声明。调用 `inject()` 不会注册或启动任务,返回值需要传给
104
- `MakooRuntime.start()`。
105
-
106
- ### Type
107
-
108
- ```ts
109
- function inject<TArtifact>(
110
- input: MakooInjectionInput<TArtifact>
111
- ): MakooInjectionDeclaration<TArtifact>;
112
- ```
113
-
114
- ### Parameters
79
+ ## 运行时基础
115
80
 
116
- ```ts
117
- type MakooInjectionInput<TArtifact = unknown> = {
118
- id?: string;
119
- injectAt: string;
120
- artifact: TArtifact;
121
- options?: ArtifactOptions;
122
- };
123
- ```
81
+ `inject()` 和 `listen()` 用于声明任务。它们不会触碰 DOM,也不会自己注册任务。`makoo.start([...])` 会注册传入批次里的声明,并立即调度这些任务。
124
82
 
125
- `id` 省略时,运行时会根据 artifact 和 `injectAt` 生成任务 ID。
126
-
127
- #### `ArtifactOptions`
128
-
129
- | 字段 | 类型 | 说明 |
130
- | --- | --- | --- |
131
- | `alive` | `boolean` | 是否在目标被替换后尝试重新挂载 |
132
- | `scope` | `'local' \| 'global'` | alive 观察范围 |
133
- | `timeout` | `number` | 等待目标元素的毫秒数 |
134
- | `on` | `MakooListenerDeclaration` | 随 component 一起注册的事件监听 |
135
- | `hooks` | `LifecycleHookMap` | 当前任务的生命周期 hooks |
136
-
137
- ### Returns
138
-
139
- 返回 `MakooInjectionDeclaration<TArtifact>`。
140
-
141
- ### Example
83
+ `inject()` 接收包含目标、artifact 和任务选项的对象。可选的 `id` 会作为任务 ID,适合后续需要查找或控制这个任务的场景:
142
84
 
143
85
  ```ts
144
- const declaration = inject({
86
+ inject({
145
87
  id: 'settings-panel',
146
88
  injectAt: '#settings',
147
- artifact: settingsPanel,
89
+ artifact: settingsArtifact,
148
90
  options: {
149
- alive: true,
150
- scope: 'global'
91
+ alive: true
151
92
  }
152
93
  });
153
94
  ```
154
95
 
155
- ## `listen()`
156
-
157
- 创建 listener 任务声明。调用 `listen()` 不会注册或启动任务,返回值需要传给
158
- `MakooRuntime.start()`,或者作为 `ArtifactOptions.on` 使用。
159
-
160
- ### Type
161
-
162
- ```ts
163
- function listen(input: MakooListenerInput): MakooListenerDeclaration;
164
- ```
165
-
166
- ### Parameters
167
-
168
- ```ts
169
- type MakooListenerInput = {
170
- id?: string;
171
- listenAt: string;
172
- type: string;
173
- callback: EventListener;
174
- capture?: boolean;
175
- activitySignal?: () => ActivitySignalSource<boolean>;
176
- };
177
- ```
178
-
179
- `id` 省略时,运行时使用 `listener-${listenAt}-${type}` 作为任务 ID。
180
- `capture` 为 `true` 时会在 DOM 捕获阶段监听事件;默认保持浏览器行为,即 `false`,
181
- 在冒泡阶段监听。listener 使用的 abort signal 仍由 Makoo 内部管理。
182
-
183
- ### Returns
184
-
185
- 返回 `MakooListenerDeclaration`。它可以作为独立任务启动,也可以赋给 `ArtifactOptions.on`。
186
-
187
- ### Example
188
-
189
- ```ts
190
- const declaration = listen({
191
- id: 'escape-close',
192
- listenAt: 'body',
193
- type: 'keydown',
194
- capture: true,
195
- callback: onEscape
196
- });
197
- ```
198
-
199
- ## `createObserverHub()`
200
-
201
- 创建事件中心。`logger` 默认使用 `new Logger()`。
202
-
203
- ### Type
204
-
205
- ```ts
206
- function createObserverHub(logger?: ILogger): ObserverHub;
207
- ```
208
-
209
- ### Parameters
210
-
211
- - `logger`:可选的 `ILogger`。省略时创建 `Logger`。
212
-
213
- ### Returns
214
-
215
- 返回 `ObserverHub`:
216
-
217
- | 方法 | 返回值 | 说明 |
218
- | --- | --- | --- |
219
- | `on(event, hook)` | `() => void` | 注册指定事件的 hook |
220
- | `onTask(taskId, event, hook)` | `() => void` | 注册指定任务的 hook |
221
- | `onAny(hook)` | `() => void` | 注册接收全部事件的 hook |
222
- | `off(event, hook?)` | `void` | 移除指定事件的 hook |
223
- | `offTask(taskId, event?, hook?)` | `void` | 移除指定任务的 hook |
224
- | `offAny(hook)` | `void` | 移除一个全局 hook |
225
- | `clear()` | `void` | 移除全部 hook |
226
- | `hasHooks(event?)` | `boolean` | 检查全部或指定事件是否存在 hook |
227
- | `emit(event)` | `void` | 发出事件 |
228
- | `emitOnTask(taskId, event)` | `void` | 为指定任务发出事件 |
229
-
230
- 任务事件的调用顺序是:任务 hook、同名事件 hook、`onAny()` hook。
231
- `stopPropagation()` 会阻止进入下一层;`stopImmediatePropagation()` 还会停止当前层剩余 hook。
232
- 某个 hook 抛出异常时,异常会写入 logger,其他 hook 继续执行。
233
-
234
- ### Example
235
-
236
- ```ts
237
- const observer = createObserverHub();
238
- const off = observer.on('artifact:mountSuccess', (event) => {
239
- console.log(event.taskId);
240
- });
241
-
242
- off();
243
- ```
244
-
245
- ## `createActivityStore()`
246
-
247
- 创建一个可读取、订阅和修改的状态对象。
248
-
249
- ### Type
250
-
251
- ```ts
252
- function createActivityStore<T>(initialValue: T): {
253
- get(): T;
254
- subscribe(listener: (value: T) => void): SignalUnsubscribe;
255
- set(value: T): void;
256
- update(updater: (value: T) => T): void;
257
- };
258
- ```
259
-
260
- ### Parameters
261
-
262
- - `initialValue`:状态的初始值。
263
-
264
- ### Returns
265
-
266
- 返回包含 `get()`、`subscribe()`、`set()` 和 `update()` 的状态对象。
267
-
268
- ### Details
269
-
270
- `set()` 或 `update()` 产生的新值与当前值通过 `Object.is()` 比较;值没有变化时不会通知订阅者。
271
-
272
- ### Example
273
-
274
- ```ts
275
- const active = createActivityStore(true);
276
- const unsubscribe = active.subscribe((value) => {
277
- console.log(value);
278
- });
279
-
280
- active.set(false);
281
- active.update((value) => !value);
282
- unsubscribe();
283
- ```
284
-
285
- ## `DOMWatcher`
286
-
287
- ### `DOMWatcher.onDomReady()`
288
-
289
- 立即查找匹配元素,并通过 `MutationObserver` 监听后续新增元素。
290
-
291
- #### Type
96
+ 没有传 `id` 时,Makoo 会根据 artifact 和目标 selector 推导任务 ID。
292
97
 
293
98
  ```ts
294
- DOMWatcher.onDomReady(
295
- selector: string,
296
- callback: (element: HTMLElement, observer?: MutationObserver) => void,
297
- root: Document | HTMLElement = document,
298
- options: { once: boolean; timeout?: number } | { once?: boolean; timeout: number },
299
- runtime?: {
300
- logger: ILogger;
301
- emit: (name:
302
- | 'dom:targetFound'
303
- | 'dom:targetTimeout'
304
- | 'dom:targetRemoved'
305
- | 'dom:targetRestored'
306
- ) => void;
307
- }
308
- ): () => void;
309
- ```
99
+ import { createMakoo, inject, listen } from '@makoojs/core';
310
100
 
311
- #### Details
312
-
313
- - 找到元素时调用 `callback`。
314
- - `once: true` 会在首次找到元素后停止观察。
315
- - 设置 `timeout` 后,超时会停止观察。
316
- - 返回值用于手动停止观察。
317
-
318
- ### `DOMWatcher.onDomAlive()`
319
-
320
- 监听 `target` 被移除,并在 `selector` 对应的新元素出现时调用 `onRestore`。
321
-
322
- #### Type
323
-
324
- ```ts
325
- DOMWatcher.onDomAlive(
326
- target: HTMLElement,
327
- selector: string,
328
- onRemove: () => void,
329
- onRestore: (element: HTMLElement, observer?: MutationObserver) => void,
330
- root: Document | HTMLElement = document,
331
- options: { once: boolean; timeout?: number } | { once?: boolean; timeout: number },
332
- runtime?: {
333
- logger: ILogger;
334
- emit: (name:
335
- | 'dom:targetFound'
336
- | 'dom:targetTimeout'
337
- | 'dom:targetRemoved'
338
- | 'dom:targetRestored'
339
- ) => void;
101
+ const makoo = createMakoo({
102
+ defaults: {
103
+ alive: false,
104
+ scope: 'local',
105
+ timeout: 5000
106
+ },
107
+ adapters: [myAdapter],
108
+ hooks: {
109
+ 'start:requested': (event) => {
110
+ console.log(event.name);
111
+ }
340
112
  }
341
- ): () => void;
342
- ```
343
-
344
- #### Returns
345
-
346
- 返回一个停止函数,用于停止移除和恢复观察。
347
-
348
- ## `Logger`
349
-
350
- Makoo 默认提供的日志实现。
351
-
352
- ### Type
353
-
354
- ```ts
355
- class Logger implements ILogger {
356
- static readonly PREFIX = '[Makoo]';
357
-
358
- constructor(level?: LoggerLevel);
359
- setLevel(level: LoggerLevel): void;
360
- getLevel(): LoggerLevel;
361
- log(level: LoggerLevel, message: string, ...args: unknown[]): void;
362
- debug(message: string, ...args: unknown[]): void;
363
- info(message: string, ...args: unknown[]): void;
364
- warn(message: string, ...args: unknown[]): void;
365
- error(message: string, ...args: unknown[]): void;
366
- }
367
- ```
368
-
369
- 默认日志等级为 `info`。等级顺序为 `debug`、`info`、`warn`、`error`;低于当前等级的日志不会输出。
370
-
371
- ## 错误类
372
-
373
- ### `MakooError`
374
-
375
- ```ts
376
- class MakooError extends Error {
377
- readonly code: string;
378
- readonly issues: MakooIssue[];
379
- override readonly cause?: Error;
380
-
381
- constructor(
382
- message: string,
383
- issues?: MakooIssue[],
384
- code?: string,
385
- cause?: Error
386
- );
387
- }
388
- ```
389
-
390
- `message` 会添加 `[makoo]` 前缀,并包含 `issues` 和 `cause` 错误链。
391
-
392
- ### `AdapterError`
393
-
394
- ```ts
395
- class AdapterError extends MakooError;
396
- ```
397
-
398
- 默认错误码:`ErrorCode.ADAPTER_NOT_FOUND`。
399
-
400
- ### `SignalError`
401
-
402
- ```ts
403
- class SignalError extends MakooError;
404
- ```
405
-
406
- 默认错误码:`ErrorCode.TASK_SIGNAL_INVALID`。
407
-
408
- ### `TaskError`
409
-
410
- ```ts
411
- class TaskError extends MakooError;
412
- ```
413
-
414
- 默认错误码:`ErrorCode.TASK_NO_REGISTERED`。
415
-
416
- ## 常量
417
-
418
- ### `Action`
419
-
420
- ```ts
421
- enum Action {
422
- OPEN = 'OPEN',
423
- CLOSE = 'CLOSE'
424
- }
113
+ });
425
114
 
426
- type ActionEvent = `${Action}`;
115
+ const started = makoo.start([
116
+ inject({
117
+ id: 'toolbar',
118
+ injectAt: '#toolbar',
119
+ artifact: toolbarArtifact,
120
+ options: {
121
+ alive: true
122
+ }
123
+ }),
124
+ inject({
125
+ id: 'settings-panel',
126
+ injectAt: '#settings',
127
+ artifact: settingsArtifact,
128
+ options: {
129
+ alive: true
130
+ }
131
+ }),
132
+ inject({
133
+ id: 'save-tip',
134
+ injectAt: '#save-tip',
135
+ artifact: saveTipArtifact,
136
+ options: {
137
+ on: listen({
138
+ listenAt: '#save',
139
+ type: 'click',
140
+ callback: () => {
141
+ console.log('save clicked');
142
+ }
143
+ })
144
+ }
145
+ }),
146
+ listen({
147
+ id: 'escape-close',
148
+ listenAt: '#escape',
149
+ type: 'keydown',
150
+ callback: onEscape
151
+ })
152
+ ]);
427
153
  ```
428
154
 
429
- ### `OBSERVE_EVENT_NAMES`
155
+ `start()` 返回 `StartedTasks`,用于控制本批次任务:
430
156
 
431
157
  ```ts
432
- const OBSERVE_EVENT_NAMES = [
433
- 'register:start',
434
- 'register:success',
435
- 'register:duplicate',
436
- 'register:error',
437
- 'start:requested',
438
- 'start:taskScheduled',
439
- 'start:taskSkipped',
440
- 'artifact:mountStart',
441
- 'artifact:mountSuccess',
442
- 'artifact:mountFail',
443
- 'listener:attached',
444
- 'listener:detached',
445
- 'listener:attachFail',
446
- 'alive:enabled',
447
- 'alive:disabled',
448
- 'alive:observerStarted',
449
- 'alive:observerStopped',
450
- 'task:targetReady',
451
- 'task:statusChange',
452
- 'task:beforeReset',
453
- 'task:afterReset',
454
- 'task:beforeDestroy',
455
- 'task:afterDestroy',
456
- 'signal:watcherReleased',
457
- 'resource:listenerReleased',
458
- 'artifact:unmounted',
459
- 'dom:targetFound',
460
- 'dom:targetTimeout',
461
- 'dom:targetRemoved',
462
- 'dom:targetRestored'
463
- ] as const;
464
- ```
465
-
466
- ### `ErrorCode`
158
+ const toolbar = started.get('toolbar');
467
159
 
468
- | 字段 | 值 |
469
- | --- | --- |
470
- | `UNKNOWN` | `MAKOO_UNKNOWN` |
471
- | `ADAPTER_NOT_FOUND` | `MAKOO_ADAPTER_NOT_FOUND` |
472
- | `ADAPTER_MOUNT_FAIL` | `MAKOO_ADAPTER_MOUNT_FAIL` |
473
- | `ADAPTER_UNMOUNT_FAIL` | `MAKOO_ADAPTER_UNMOUNT_FAIL` |
474
- | `TASK_NO_REGISTERED` | `MAKOO_TASK_NO_REGISTERED` |
475
- | `TASK_NOT_FOUND` | `MAKOO_TASK_NOT_FOUND` |
476
- | `TASK_INJECT_FAIL` | `MAKOO_TASK_INJECT_FAIL` |
477
- | `TASK_ALREADY_MOUNTED` | `MAKOO_TASK_ALREADY_MOUNTED` |
478
- | `TASK_TARGET_DETACHED` | `MAKOO_TASK_TARGET_DETACHED` |
479
- | `TASK_LISTENER_ATTACH_FAIL` | `MAKOO_TASK_LISTENER_ATTACH_FAIL` |
480
- | `TASK_SIGNAL_INVALID` | `MAKOO_TASK_SIGNAL_INVALID` |
481
- | `TASK_SIGNAL_BIND_FAIL` | `MAKOO_TASK_SIGNAL_BIND_FAIL` |
482
- | `CLI_SOURCE_DIR_NOT_FOUND` | `MAKOO_CLI_SOURCE_DIR_NOT_FOUND` |
483
- | `CLI_MANIFEST_LOAD_FAIL` | `MAKOO_CLI_MANIFEST_LOAD_FAIL` |
484
- | `CLI_MODULE_MANIFEST_LOAD_FAIL` | `MAKOO_CLI_MODULE_MANIFEST_LOAD_FAIL` |
485
- | `CLI_MANIFEST_NOT_FOUND` | `MAKOO_CLI_MANIFEST_NOT_FOUND` |
486
- | `CLI_MANIFEST_BINDING_NOT_FOUND` | `MAKOO_CLI_MANIFEST_BINDING_NOT_FOUND` |
487
- | `CLI_MANIFEST_IMPORT_NOT_FOUND` | `MAKOO_CLI_MANIFEST_IMPORT_NOT_FOUND` |
488
- | `CLI_FUNCTION_SERIALIZATION_UNSUPPORTED` | `MAKOO_CLI_FUNCTION_SERIALIZATION_UNSUPPORTED` |
489
- | `CLI_NO_ENABLED_TASKS` | `MAKOO_CLI_NO_ENABLED_TASKS` |
490
- | `CLI_COMPONENT_NOT_FOUND` | `MAKOO_CLI_COMPONENT_NOT_FOUND` |
491
- | `CLI_CONFIG_INVALID` | `MAKOO_CLI_CONFIG_INVALID` |
492
- | `CLI_UNKNOWN_FRAMEWORK` | `MAKOO_CLI_UNKNOWN_FRAMEWORK` |
493
- | `CLI_UNSUPPORTED_FRAMEWORK` | `MAKOO_CLI_UNSUPPORTED_FRAMEWORK` |
494
- | `CLI_MODULE_ALREADY_EXISTS` | `MAKOO_CLI_MODULE_ALREADY_EXISTS` |
495
- | `CLI_MANIFEST_VALIDATION_FAIL` | `MAKOO_CLI_MANIFEST_VALIDATION_FAIL` |
496
- | `CLI_VITE_CONFIG_NOT_FOUND` | `MAKOO_CLI_VITE_CONFIG_NOT_FOUND` |
497
- | `CLI_PLUGIN_NOT_FOUND` | `MAKOO_CLI_PLUGIN_NOT_FOUND` |
498
- | `CLI_RUNTIME_SETUP_NOT_FOUND` | `MAKOO_CLI_RUNTIME_SETUP_NOT_FOUND` |
499
-
500
- ## Adapter 类型
501
-
502
- ### `MountAdapter`
503
-
504
- ```ts
505
- interface MountAdapter<TArtifact = unknown, THandle = unknown, TInstance = unknown> {
506
- name: string;
507
- mount(input: AdapterMountInput<TArtifact>): AdapterMountResult<THandle, TInstance>;
508
- unmount(input: AdapterUnmountInput<THandle>): void;
160
+ if (toolbar?.kind === 'component') {
161
+ toolbar.disableAlive();
162
+ toolbar.enableAlive();
509
163
  }
510
- ```
511
164
 
512
- ### `ResolvableMountAdapter`
513
-
514
- ```ts
515
- interface ResolvableMountAdapter<TArtifact = unknown, THandle = unknown, TInstance = unknown>
516
- extends MountAdapter<TArtifact, THandle, TInstance> {
517
- matches(artifact: unknown): artifact is TArtifact;
518
- }
165
+ started.destroyAll();
519
166
  ```
520
167
 
521
- ### `AdapterMountInput`
168
+ `started.destroyAll()` 只影响本次启动产生的任务。`makoo.destroyAll()` 会影响整个运行时中的全部任务。
522
169
 
523
- | 字段 | 类型 |
524
- | --- | --- |
525
- | `host` | `HTMLElement` |
526
- | `mountPoint` | `HTMLElement` |
527
- | `artifact` | `TArtifact` |
528
- | `taskId` | `string` |
529
- | `injectAt` | `string` |
530
- | `makoo` | `MakooContext` |
170
+ ## Adapter 协议
531
171
 
532
- ### `AdapterMountResult`
172
+ core 不关心 artifact 是 Vue 组件、React 组件还是其他对象。它只要求 adapter 实现统一挂载协议。
533
173
 
534
174
  ```ts
535
- type AdapterMountResult<THandle = unknown, TInstance = unknown> = {
536
- handle: THandle;
537
- instance?: TInstance;
538
- };
539
- ```
540
-
541
- ### `AdapterUnmountInput`
542
-
543
- | 字段 | 类型 |
544
- | --- | --- |
545
- | `host` | `HTMLElement \| undefined` |
546
- | `mountPoint` | `HTMLElement` |
547
- | `handle` | `THandle` |
548
- | `taskId` | `string` |
549
- | `injectAt` | `string` |
550
- | `reason` | `AdapterUnmountReason` |
175
+ import type { ResolvableMountAdapter } from '@makoojs/core';
551
176
 
552
- ```ts
553
- type AdapterUnmountReason = 'destroy' | 'reset' | 'remount' | 'manual';
554
- type AdapterResolver = (artifact: unknown) => MountAdapter | undefined;
555
- ```
556
-
557
- ### `MakooContext`
558
-
559
- ```ts
560
- type MakooContext = {
561
- taskId: string;
562
- injectAt: string;
563
- enableAlive(): void;
564
- disableAlive(): void;
565
- reset(): void;
566
- destroy(): void;
567
- on(event: ObserveEventName, hook: ObserveHook): () => void;
568
- onTask(event: ObserveEventName, hook: ObserveHook): () => void;
569
- off(event: ObserveEventName, hook?: ObserveHook): void;
570
- offTask(event?: ObserveEventName, hook?: ObserveHook): void;
571
- getLogger(): ILogger;
572
- bindListenerSignal(source: ActivitySignalSource<boolean>): boolean;
573
- controlListener(event: ActionEvent): boolean;
177
+ const adapter: ResolvableMountAdapter<MyArtifact, MyHandle, MyInstance> = {
178
+ name: 'my-adapter',
179
+ matches(artifact): artifact is MyArtifact {
180
+ return isMyArtifact(artifact);
181
+ },
182
+ mount(input) {
183
+ return {
184
+ handle,
185
+ instance
186
+ };
187
+ },
188
+ unmount(input) {
189
+ // 根据 input.reason 清理资源。
190
+ }
574
191
  };
575
192
  ```
576
193
 
577
- ## 任务类型
194
+ `mount(input)` 会收到目标宿主节点、生成的挂载点、artifact、taskId、selector,以及任务级 `makoo` 上下文。
578
195
 
579
- ```ts
580
- type MakooDefaults = {
581
- alive: boolean;
582
- scope: 'local' | 'global';
583
- timeout: number;
584
- };
585
-
586
- type MakooInjectionDeclaration<TArtifact = unknown> = {
587
- kind: 'component';
588
- id?: string;
589
- injectAt: string;
590
- artifact: TArtifact;
591
- options?: ArtifactOptions;
592
- };
593
-
594
- type MakooListenerDeclaration = {
595
- kind: 'listener';
596
- id?: string;
597
- listenAt: string;
598
- event: string;
599
- type: string;
600
- callback: EventListener;
601
- capture?: boolean;
602
- activitySignal?: () => ActivitySignalSource<boolean>;
603
- };
196
+ ## Listener 和 activity signal
604
197
 
605
- type MakooTaskDeclaration<TArtifact = unknown> =
606
- | MakooInjectionDeclaration<TArtifact>
607
- | MakooListenerDeclaration;
608
- ```
198
+ 独立监听任务使用 `listen()` 的对象形式声明。可选的 `id` 是任务 ID;后续需要稳定地查找或控制任务时应提供它。组件的 `on` listener 归属于组件任务本身,不需要单独的 ID。
609
199
 
610
- ### `StartedTasks`
200
+ `capture` 默认为 `false`;设置为 `true` 后,监听器会在 DOM 捕获阶段执行。
611
201
 
612
202
  ```ts
613
- type StartedComponentTask = {
614
- kind: 'component';
615
- taskId: string;
616
- enableAlive(): void;
617
- disableAlive(): void;
618
- reset(): void;
619
- destroy(): void;
620
- };
203
+ import { createActivityStore, createMakoo, listen } from '@makoojs/core';
621
204
 
622
- type StartedListenerTask = {
623
- kind: 'listener';
624
- taskId: string;
625
- open(): boolean;
626
- close(): boolean;
627
- destroy(): void;
628
- };
205
+ const enabled = createActivityStore(true);
206
+ const makoo = createMakoo();
629
207
 
630
- type StartedTask = StartedComponentTask | StartedListenerTask;
208
+ makoo.start([
209
+ listen({
210
+ id: 'save-listener',
211
+ listenAt: '#save',
212
+ type: 'click',
213
+ callback: () => {
214
+ console.log('save clicked');
215
+ },
216
+ activitySignal: () => enabled
217
+ })
218
+ ]);
631
219
 
632
- type StartedTasks = {
633
- tasks: StartedTask[];
634
- get(taskId: string): StartedTask | undefined;
635
- resetAll(): void;
636
- destroyAll(): void;
637
- };
220
+ enabled.set(false);
221
+ enabled.set(true);
638
222
  ```
639
223
 
640
- `StartedTasks.resetAll()` 和 `StartedTasks.destroyAll()` 只操作当前 `start()` 返回的任务批次。
224
+ ## 观察事件
641
225
 
642
- ### `InjectionConfig`
226
+ core 会在声明注册、启动、挂载、监听、alive 模式、DOM 观察和任务状态变化时发出观察事件。
643
227
 
644
228
  ```ts
645
- type InjectionConfig = MakooDefaults & {
646
- logger: ILogger;
647
- observer?: ObserverHub;
648
- hooks?: LifecycleHookMap;
649
- };
650
- ```
651
-
652
- ## 观察类型
653
-
654
- ```ts
655
- type ObserveEventName = (typeof OBSERVE_EVENT_NAMES)[number];
656
-
657
- type ObserveEvent = {
658
- name: ObserveEventName;
659
- ts: number;
660
- taskId?: string;
661
- kind?: 'component' | 'listener';
662
- injectAt?: string;
663
- status?: 'idle' | 'pending' | 'active';
664
- durationMs?: number;
665
- error?: unknown;
666
- preStatus?: 'idle' | 'pending' | 'active';
667
- meta?: Record<string, unknown>;
668
- };
229
+ const off = makoo.on('artifact:mountSuccess', (event) => {
230
+ console.log(event.taskId, event.injectAt);
231
+ });
669
232
 
670
- type ObserveHook = (
671
- event: ObserveEvent,
672
- ctrl: {
673
- stopPropagation(): void;
674
- stopImmediatePropagation(): void;
233
+ makoo.onAny((event, ctrl) => {
234
+ if (event.name === 'artifact:mountFail') {
235
+ ctrl.stopPropagation();
675
236
  }
676
- ) => void;
237
+ });
677
238
 
678
- type LifecycleHookMap = Partial<
679
- Record<ObserveEventName, ObserveHook | ObserveHook[]>
680
- >;
239
+ off();
681
240
  ```
682
241
 
683
- ## Signal 类型
242
+ 常见事件包括:
684
243
 
685
- ```ts
686
- type SignalUnsubscribe = (() => void) | { unsubscribe(): void };
244
+ - `register:start`
245
+ - `register:success`
246
+ - `start:requested`
247
+ - `start:taskScheduled`
248
+ - `artifact:mountStart`
249
+ - `artifact:mountSuccess`
250
+ - `artifact:mountFail`
251
+ - `listener:attached`
252
+ - `alive:enabled`
253
+ - `alive:observerStarted`
254
+ - `task:statusChange`
255
+ - `dom:targetFound`
256
+ - `dom:targetTimeout`
687
257
 
688
- type ActivitySignalSource<T = boolean> = {
689
- get(): T;
690
- subscribe(listener: (value: T) => void): SignalUnsubscribe;
691
- };
258
+ 完整事件名列表可从 `OBSERVE_EVENT_NAMES` 获取。
692
259
 
693
- type ActivitySignalSubscribable<T = boolean> = ActivitySignalSource<T>;
694
- ```
260
+ ## DOMWatcher
695
261
 
696
- ## 日志类型
262
+ `DOMWatcher` 是 core 的底层 DOM 观察工具。通常你不需要直接使用它,因为 `makoo.start()` 和 alive 模式已经封装了目标等待和恢复逻辑。
697
263
 
698
- ```ts
699
- type LoggerLevel = 'debug' | 'info' | 'warn' | 'error';
264
+ ## 日志和错误
700
265
 
701
- interface ILogger {
702
- info(message: string, ...args: unknown[]): void;
703
- warn(message: string, ...args: unknown[]): void;
704
- error(message: string, ...args: unknown[]): void;
705
- debug(message: string, ...args: unknown[]): void;
706
- }
707
- ```
266
+ core 默认使用 `Logger`,并用 `[Makoo]` 前缀打印日志。你可以通过 `createMakoo({ logger })` 传入自定义 logger。
708
267
 
709
- ## 错误类型
268
+ core 也导出这些错误相关类型:
710
269
 
711
- ```ts
712
- type MakooIssue = {
713
- path: string;
714
- message: string;
715
- };
270
+ - `MakooError`
271
+ - `AdapterError`
272
+ - `TaskError`
273
+ - `SignalError`
274
+ - `ErrorCode`
275
+ - `MakooIssue`
716
276
 
717
- type ErrorCodeValue = (typeof ErrorCode)[keyof typeof ErrorCode];
718
- ```
277
+ ## Public Exports 概览
278
+
279
+ | 分类 | 代表导出 |
280
+ | --- | --- |
281
+ | 运行时 API | `createMakoo`, `inject`, `listen`, `MakooRuntime`, `StartedTasks` |
282
+ | Adapter 协议 | `MountAdapter`, `ResolvableMountAdapter`, `AdapterMountInput`, `AdapterUnmountInput`, `MakooContext` |
283
+ | 生命周期观察 | `ObserverHub`, `OBSERVE_EVENT_NAMES`, `ObserveEvent`, `ObserveHook`, `LifecycleHookMap` |
284
+ | DOM 观察 | `DOMWatcher` |
285
+ | 监听 signal | `createActivityStore`, `ActivitySignalSource` |
286
+ | 日志 | `Logger`, `ILogger`, `LoggerLevel` |
287
+ | 错误 | `MakooError`, `AdapterError`, `TaskError`, `SignalError`, `ErrorCode` |