cordis-testkit 0.0.0-stage → 0.1.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/DESIGN.md +191 -0
- package/LICENSE +202 -0
- package/README.md +198 -2
- package/package.json +43 -4
- package/src/core.js +606 -0
package/DESIGN.md
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
# cordis-testkit —— 设计说明
|
|
2
|
+
|
|
3
|
+
> 非官方测试替身。不是 Cordis 官方实现,不隶属 cordiverse / DeepSeek。Apache-2.0。
|
|
4
|
+
|
|
5
|
+
## 1. 问题
|
|
6
|
+
|
|
7
|
+
写 Cordis 插件单测时,真实 `Context` 会把 fiber、依赖注入、服务反射、配置校验、HMR 等一起带进来。测试通常只关心三件事:
|
|
8
|
+
|
|
9
|
+
1. 我注册的 listener 能不能被事件触发?
|
|
10
|
+
2. 我通过 `ctx.effect()` / `ctx.plugin()` 申请的资源,在 `dispose()` 时有没有被释放?
|
|
11
|
+
3. 测试结束时,有没有漏掉的 listener/effect/plugin?
|
|
12
|
+
|
|
13
|
+
真运行时的这些机制会掩盖简单的泄漏:context 一销毁,所有资源都没了,测试不会告诉你**插件是否真的自己管理了生命周期**。本包用一个可观察的资源表替代运行时,专门回答上面三个问题。
|
|
14
|
+
|
|
15
|
+
## 2. 目标与非目标
|
|
16
|
+
|
|
17
|
+
### 目标
|
|
18
|
+
|
|
19
|
+
- `createMockContext()` 提供与 Cordis 形似的 `on` / `emit` / `effect` / `set` / `get` / `plugin` / `dispose`。
|
|
20
|
+
- 所有注册都进表,可快照、可断言。
|
|
21
|
+
- `dispose()` 逆序执行 cleanup、清空 listener,且重复调用幂等。
|
|
22
|
+
- `assertNoLeaks()` 给出**分类 + 名称**的泄漏清单,而不只是 boolean。
|
|
23
|
+
- 纯 ESM + JSDoc,零第三方依赖,Node 22/24 可离线跑。
|
|
24
|
+
- 明确声明非官方、命名状态和限制,避免被误当成 Cordis 发行版。
|
|
25
|
+
|
|
26
|
+
### 非目标
|
|
27
|
+
|
|
28
|
+
- 不做 Cordis 运行时(无 fiber、inject、service、reflect、HMR)。
|
|
29
|
+
- 不做异步 effect / Promise cleanup / async iterator。
|
|
30
|
+
- 不做事件系统的完整语义(once、prepend、parallel/serial/waterfall、过滤)。
|
|
31
|
+
- 不做配置 schema 校验;config 原样传给插件。
|
|
32
|
+
- 不做性能优化或跨线程安全;它是测试工具,单线程同步即可。
|
|
33
|
+
|
|
34
|
+
## 3. 数据模型
|
|
35
|
+
|
|
36
|
+
每个 context 持有内部状态(挂在 `Symbol.for('cordis-testkit.state')` 上,避免污染公开字段):
|
|
37
|
+
|
|
38
|
+
```text
|
|
39
|
+
{
|
|
40
|
+
listeners: ListenerRecord[], // { event, callback, active }
|
|
41
|
+
effects: EffectRecord[], // { label, active, disposed, cleanup }
|
|
42
|
+
plugins: PluginRecord[], // { name, active, disposed, cleanup }
|
|
43
|
+
cleanups: CleanupEntry[], // LIFO:{ kind:'effect'|'plugin', record }
|
|
44
|
+
store: Map, // set/get
|
|
45
|
+
disposed: boolean,
|
|
46
|
+
sequence: number // 默认 effect/plugin 名称
|
|
47
|
+
}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
为什么 listener 不进 cleanup 栈?因为 listener 的「释放」只是从表中删除,没有用户 cleanup 回调;而 effect/plugin 可能带用户函数,必须在 `dispose()` 中按逆序调用。listener 表在所有 cleanup 完成后统一清空,保证 cleanup 期间仍可通过返回的 disposer 删除 listener。
|
|
51
|
+
|
|
52
|
+
`snapshot()` 只暴露活跃资源的**名称**(listener 是 event,effect 是 label,plugin 是 name),因为:
|
|
53
|
+
|
|
54
|
+
- 测试断言通常只关心「哪个资源没清」;
|
|
55
|
+
- 不把内部 record 暴露出去,避免测试依赖实现细节;
|
|
56
|
+
- 返回新数组,调用方修改快照不会污染 context。
|
|
57
|
+
|
|
58
|
+
## 4. 生命周期
|
|
59
|
+
|
|
60
|
+
### 4.1 注册
|
|
61
|
+
|
|
62
|
+
- `ctx.on(event, cb)`:校验 event 为 string/symbol、cb 为函数;压入 listener;返回幂等 disposer。
|
|
63
|
+
- `ctx.effect(fn, label)`:先建 record 和 LIFO entry,再**同步执行** `fn`。
|
|
64
|
+
- `fn` 返回函数:保存为 cleanup。
|
|
65
|
+
- 返回 `undefined` / `null`:合法的无 cleanup effect,仍算活跃资源(严格模式)。
|
|
66
|
+
- 返回其他值(包括 Promise):抛 `TypeError`,并回滚 record/entry,不留下幽灵注册。
|
|
67
|
+
- `fn` 自身抛错:同样回滚后重抛。
|
|
68
|
+
- `ctx.plugin(plugin, config)`:校验插件形态,记录名称,同步 apply。
|
|
69
|
+
- 函数插件:`plugin(ctx, config)`,`this = ctx`。
|
|
70
|
+
- 对象插件:`plugin.apply(ctx, config)`,`this = plugin`。
|
|
71
|
+
- 返回函数:作为 plugin cleanup;其他非空返回值抛 `TypeError`(明确不支持异步插件)。
|
|
72
|
+
- apply 抛错:移除 plugin record 后重抛。已经注册到 context 的 listener/effect 仍保留,由调用方 `ctx.dispose()` 清理;`runPlugin()` 会自动做这件事。
|
|
73
|
+
- 成功后压入 plugin 的 LIFO entry,使 plugin cleanup 先于它注册的 effect 执行。
|
|
74
|
+
|
|
75
|
+
`ctx.plugin()` 返回 `ctx`(便于链式调用),而不是 Cordis 的 fiber 句柄。这是已知差异,README 中列明。
|
|
76
|
+
|
|
77
|
+
### 4.2 事件
|
|
78
|
+
|
|
79
|
+
`ctx.emit(event, ...args)` 先复制 listener 数组,再逐个检查 `active` 和 event 匹配:
|
|
80
|
+
|
|
81
|
+
- emit 期间新增的 listener 不会在本轮触发;
|
|
82
|
+
- emit 期间被移除的 listener 会跳过;
|
|
83
|
+
- 某个 listener 抛错会立即中断本轮并向上抛,与 Cordis 的同步 emit 行为一致;
|
|
84
|
+
- `this` 绑定为 mock context,方便插件里的普通函数写法;
|
|
85
|
+
- 返回值是 listener 结果数组,仅为测试便利(Cordis 返回 void)。
|
|
86
|
+
|
|
87
|
+
### 4.3 释放
|
|
88
|
+
|
|
89
|
+
`ctx.dispose()`:
|
|
90
|
+
|
|
91
|
+
```text
|
|
92
|
+
if (already disposed) return
|
|
93
|
+
disposed = true
|
|
94
|
+
while (cleanups 非空):
|
|
95
|
+
entry = cleanups.pop() // LIFO
|
|
96
|
+
if effect: disposeEffect(record)
|
|
97
|
+
if plugin: disposePlugin(record)
|
|
98
|
+
清空 listeners(标记 inactive)
|
|
99
|
+
清空 effects/plugins 表
|
|
100
|
+
若有 cleanup 错误: 抛 AggregateError(errors, ...)
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
关键点:
|
|
104
|
+
|
|
105
|
+
- **先执行再清表**:cleanup 期间还能通过保存的 disposer 释放 listener;所有 cleanup 结束后才统一清空。
|
|
106
|
+
- **错误不短路**:所有 cleanup 都会跑;错误收集后一次抛出。这样即使一个 cleanup 写错,也不会让后面的资源滞留。
|
|
107
|
+
- **幂等**:`disposed = true` 在第一次进入时立即设置;即使第一次抛 `AggregateError`,第二次调用也直接返回。`dispose()` 也可从 cleanup 内部安全调用(空操作)。
|
|
108
|
+
- **record 级幂等**:`disposeEffect` / `disposePlugin` 在调用 cleanup 前先置 `disposed = true`;effect 返回的 disposer 也通过 `removed` 标记保证只执行一次。
|
|
109
|
+
|
|
110
|
+
### 4.4 泄漏判定
|
|
111
|
+
|
|
112
|
+
`assertNoLeaks(ctx)`:
|
|
113
|
+
|
|
114
|
+
1. `snapshot(ctx)`;
|
|
115
|
+
2. 三类都为空 → 返回;
|
|
116
|
+
3. 否则构造 `Error`,message 含每类的计数与名称,附 `code = 'ERR_CORDIS_LEAK'` 和 `leaks = snapshot`。
|
|
117
|
+
|
|
118
|
+
判定的是「活跃注册」而不是 `disposed` 标志,因此两种测试写法都成立:
|
|
119
|
+
|
|
120
|
+
```js
|
|
121
|
+
// A. 释放整个 context
|
|
122
|
+
ctx.dispose()
|
|
123
|
+
assertNoLeaks(ctx)
|
|
124
|
+
|
|
125
|
+
// B. 逐个释放,context 仍活着
|
|
126
|
+
const off = ctx.on('tick', fn)
|
|
127
|
+
off()
|
|
128
|
+
assertNoLeaks(ctx)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
effect 即使没有 cleanup 也算活跃:这会让「注册了但没人负责」在测试里显形,而不是静默通过。代价是偏向严格,README 已注明。
|
|
132
|
+
|
|
133
|
+
## 5. 与 Cordis 4 的兼容面
|
|
134
|
+
|
|
135
|
+
| 能力 | Cordis 4 | cordis-testkit |
|
|
136
|
+
|---|---|---|
|
|
137
|
+
| `ctx.on` 返回 disposer | 是 | 是 |
|
|
138
|
+
| listener `this` | 事件派发约定 | 绑定 ctx(模拟便利) |
|
|
139
|
+
| `ctx.effect` 立即执行 | 是 | 是 |
|
|
140
|
+
| effect cleanup 逆序 | 是 | 是 |
|
|
141
|
+
| effect 支持 Promise/iterator | 是 | **否**(同步替身) |
|
|
142
|
+
| `ctx.plugin` 子 fiber | 是 | **否**,同 ctx |
|
|
143
|
+
| plugin 返回 cleanup | 支持 effect 语义 | 只支持同步函数 |
|
|
144
|
+
| `ctx.emit` 返回 | void | 结果数组(便利) |
|
|
145
|
+
| `ctx.plugin` 返回 | fiber 句柄 | ctx |
|
|
146
|
+
| inject/provide/reflect/service | 是 | 否 |
|
|
147
|
+
| `once`/`prepend`/`parallel`/`waterfall` | 是 | 否 |
|
|
148
|
+
| HMR / update / restart | 是 | 否 |
|
|
149
|
+
| 配置校验 | 是 | 否(原样传递) |
|
|
150
|
+
|
|
151
|
+
这张表就是本包的「不要误用」清单。需要真实行为时请用官方 `cordis`。
|
|
152
|
+
|
|
153
|
+
## 6. 命名与法律
|
|
154
|
+
|
|
155
|
+
- 官方项目:`cordiverse/cordis`;官方 npm 包:`cordis`(核验时 `4.0.0-rc.13`)。
|
|
156
|
+
- `cordis-testkit` 于 2026-11-14 查询 npm registry 返回 404;官方 `packages/` 列表无 `testkit`。因此它不是官方保留名或官包,只是当前未被占用的社区名。
|
|
157
|
+
- 同类名 `@cordisjs/testkit`、`cordis-test-utils`、`@cordisjs/test-utils`、`cordis-mock` 当时也均为 404。
|
|
158
|
+
- 本包不复用官方源码;官方是 MIT,本包是 Apache-2.0。名称与商标归各自权利人。
|
|
159
|
+
- DeepSeek Harness 生态中带 `@deepseek-ai/*testkit` scope 的包与本包无关。
|
|
160
|
+
|
|
161
|
+
更完整的查询命令与证据见 README「命名核验」。
|
|
162
|
+
|
|
163
|
+
## 7. 测试策略
|
|
164
|
+
|
|
165
|
+
测试用 `node:test`,按行为分层:
|
|
166
|
+
|
|
167
|
+
- `test/context.test.js`:on/emit、过滤与顺序、set/get、listener disposer、snapshot 副本、dispose 后禁止注册。
|
|
168
|
+
- `test/effects.test.js`:立即执行、cleanup、逆序、disposer 幂等、setup 失败回滚、cleanup 错误汇总、无 cleanup effect 仍计活跃。
|
|
169
|
+
- `test/leaks.test.js`:dispose 后通过、listener/effect/plugin 三类泄漏、清单完整性、显式释放也可通过、非法 ctx。
|
|
170
|
+
- `test/plugin.test.js`:函数/对象插件、config、plugin cleanup 顺序、plugin 资源释放、runPlugin、apply 失败自动清理、非法返回值。
|
|
171
|
+
|
|
172
|
+
当前共 **27 个测试**,运行:
|
|
173
|
+
|
|
174
|
+
```sh
|
|
175
|
+
node --test packages/cordis-testkit/test/*.test.js
|
|
176
|
+
node --check packages/cordis-testkit/src/core.js
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
## 8. 迭代方向(未实现)
|
|
180
|
+
|
|
181
|
+
- 可选开启的异步 effect/cleanup(保持默认同步);
|
|
182
|
+
- plugin 级 dispose 句柄(当前只能整体 dispose);
|
|
183
|
+
- listener options(prepend/once)与事件过滤;
|
|
184
|
+
- 与真实 Cordis 的 contract test(同一组断言分别在 mock 与真 ctx 上跑);
|
|
185
|
+
- 更细的泄漏归因(哪个 plugin 注册了哪个资源)。
|
|
186
|
+
|
|
187
|
+
这些都需要先确认不会把「简单可预测的测试替身」做成半个运行时。当前版本刻意保持小。
|
|
188
|
+
|
|
189
|
+
## 9. License
|
|
190
|
+
|
|
191
|
+
Apache-2.0,见 [LICENSE](./LICENSE)。
|
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,199 @@
|
|
|
1
|
-
#
|
|
1
|
+
# cordis-testkit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
## 是什么
|
|
4
|
+
|
|
5
|
+
> **非官方项目**:这是社区独立编写的 **Cordis 测试替身(test double)**,不是 Cordis 官方实现,也不由 cordiverse / Cordis 作者背书。
|
|
6
|
+
> 与 DeepSeek 同样没有隶属关系。本包代码使用 **Apache-2.0**;Cordis 本身是 cordiverse 的 MIT 项目。
|
|
7
|
+
|
|
8
|
+
`cordis-testkit` 给 Cordis 插件测试提供两件事:
|
|
9
|
+
|
|
10
|
+
1. **一个可预测的 mock context**:可以手动 `emit` 事件、注册/释放 listener、effect 和 plugin;
|
|
11
|
+
2. **资源泄漏断言**:`assertNoLeaks(ctx)` 会列出没清理的 listener / effect / plugin,并让测试失败。
|
|
12
|
+
|
|
13
|
+
它面向单元测试,不试图复刻 Cordis 运行时。
|
|
14
|
+
|
|
15
|
+
## 为什么
|
|
16
|
+
|
|
17
|
+
Cordis 插件的约定是「通过 `ctx` 注册的东西,由 `ctx.dispose()` 统一释放」。但用一个真实 Cordis 实例测插件,会同时引入 fiber、依赖注入、服务反射、配置解析等大量与本次测试无关的行为。很多泄漏(忘了 return effect cleanup、listener 没随插件释放)在普通断言里也看不出来。
|
|
18
|
+
|
|
19
|
+
这个包把 `ctx` 缩成一张资源表:
|
|
20
|
+
|
|
21
|
+
- 测试需要的事件派发:`on` / `emit`;
|
|
22
|
+
- 测试需要的生命周期:`effect` / `plugin` / `dispose`;
|
|
23
|
+
- 测试需要的状态:`set` / `get` / `snapshot`;
|
|
24
|
+
- 测试需要的验收:`assertNoLeaks`。
|
|
25
|
+
|
|
26
|
+
## 安装
|
|
27
|
+
|
|
28
|
+
0.1.0,**尚未发布到 npm**。在本仓库内直接使用:
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
cd packages/cordis-testkit
|
|
32
|
+
npm test
|
|
33
|
+
node --check src/core.js
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
发布后才可用:
|
|
37
|
+
|
|
38
|
+
```sh
|
|
39
|
+
npm install --save-dev cordis-testkit
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
要求 Node `^22.19.0 || >=24.9.0`。纯 ESM,无第三方依赖,可离线测试。
|
|
43
|
+
|
|
44
|
+
本包**没有 CLI**,因此没有进程退出码契约;测试通过/失败由 `node:test` 与
|
|
45
|
+
`assertNoLeaks` 抛错决定(`error.code = 'ERR_CORDIS_LEAK'`)。
|
|
46
|
+
|
|
47
|
+
## 用法
|
|
48
|
+
|
|
49
|
+
```js
|
|
50
|
+
import test from 'node:test'
|
|
51
|
+
import assert from 'node:assert/strict'
|
|
52
|
+
import {
|
|
53
|
+
assertNoLeaks,
|
|
54
|
+
createMockContext,
|
|
55
|
+
runPlugin,
|
|
56
|
+
snapshot,
|
|
57
|
+
} from 'cordis-testkit'
|
|
58
|
+
|
|
59
|
+
test('plugin registers and releases its timer', () => {
|
|
60
|
+
const ctx = runPlugin((inner, config) => {
|
|
61
|
+
inner.effect(() => {
|
|
62
|
+
const timer = setInterval(() => {}, config.interval)
|
|
63
|
+
return () => clearInterval(timer)
|
|
64
|
+
}, 'timer')
|
|
65
|
+
}, { interval: 1000 })
|
|
66
|
+
|
|
67
|
+
assert.deepEqual(snapshot(ctx).effects, ['timer'])
|
|
68
|
+
ctx.dispose()
|
|
69
|
+
assertNoLeaks(ctx)
|
|
70
|
+
})
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
事件:
|
|
74
|
+
|
|
75
|
+
```js
|
|
76
|
+
const ctx = createMockContext()
|
|
77
|
+
const seen = []
|
|
78
|
+
|
|
79
|
+
ctx.on('ready', (value) => seen.push(value))
|
|
80
|
+
ctx.emit('ready', 42)
|
|
81
|
+
assert.deepEqual(seen, [42])
|
|
82
|
+
|
|
83
|
+
ctx.dispose()
|
|
84
|
+
assertNoLeaks(ctx)
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
泄漏测试(故意失败):
|
|
88
|
+
|
|
89
|
+
```js
|
|
90
|
+
const ctx = createMockContext()
|
|
91
|
+
ctx.on('tick', () => {})
|
|
92
|
+
|
|
93
|
+
assert.throws(
|
|
94
|
+
() => assertNoLeaks(ctx),
|
|
95
|
+
(error) => {
|
|
96
|
+
assert.equal(error.code, 'ERR_CORDIS_LEAK')
|
|
97
|
+
assert.match(error.message, /listener/)
|
|
98
|
+
assert.match(error.message, /tick/)
|
|
99
|
+
return true
|
|
100
|
+
},
|
|
101
|
+
)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
`error.leaks` 是结构化清单:
|
|
105
|
+
|
|
106
|
+
```js
|
|
107
|
+
{ listeners: ['tick'], effects: [], plugins: [], disposed: false }
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
### API
|
|
111
|
+
|
|
112
|
+
| API | 说明 |
|
|
113
|
+
|---|---|
|
|
114
|
+
| `createMockContext()` | 创建 `MockContext`。所有注册都记录在 context 内。 |
|
|
115
|
+
| `ctx.on(event, cb)` | 注册 listener。`event` 为 string 或 symbol;返回幂等 disposer。 |
|
|
116
|
+
| `ctx.emit(event, ...args)` | 同步派发。listener 以 `ctx` 为 `this`。返回 listener 返回值数组(见「与 Cordis 的差异」)。 |
|
|
117
|
+
| `ctx.effect(fn, label?)` | 立即执行 `fn`,接收其同步 cleanup。返回幂等 disposer。默认标签 `effect#N`。 |
|
|
118
|
+
| `ctx.set(key, value)` / `ctx.get(key)` | 简单的 `Map` 存储,用于断言插件读到的配置/服务。 |
|
|
119
|
+
| `ctx.plugin(plugin, config?)` | 同步应用函数插件或 `{ name, apply }` 对象插件,记录 plugin 名称。返回 `ctx`。 |
|
|
120
|
+
| `ctx.dispose()` | 逆序释放 cleanup,清空 listener/effect/plugin 表。幂等。cleanup 错误汇总为 `AggregateError`。 |
|
|
121
|
+
| `snapshot(ctx)` | 返回 `{ listeners, effects, plugins, disposed }`;数组只含**仍活跃**资源,且是副本。 |
|
|
122
|
+
| `assertNoLeaks(ctx)` | 有活跃 listener/effect/plugin 时抛 `Error`,带分类清单;全部释放则通过。 |
|
|
123
|
+
| `runPlugin(plugin, config?)` | `createMockContext()` + `ctx.plugin()`,返回 live ctx;apply 抛错时先释放半成品再抛出。 |
|
|
124
|
+
|
|
125
|
+
### 释放顺序
|
|
126
|
+
|
|
127
|
+
`dispose()` 维护一条 LIFO cleanup 栈:
|
|
128
|
+
|
|
129
|
+
1. effect 的 cleanup 按**注册逆序**执行(后注册先清理);
|
|
130
|
+
2. plugin 成功 apply 后登记自己的 cleanup,因此它会先于它注册的 effect 执行;
|
|
131
|
+
3. 所有 cleanup 跑完后才清空 listener 表;
|
|
132
|
+
4. 某个 cleanup 抛错不会中断其余 cleanup;全部跑完后抛 `AggregateError`,`error.code = 'ERR_CORDIS_DISPOSE'`。
|
|
133
|
+
5. 第一次 `dispose()` 即使抛错,context 也已标记 disposed,后续调用直接返回(幂等)。
|
|
134
|
+
|
|
135
|
+
### 泄漏判定
|
|
136
|
+
|
|
137
|
+
`assertNoLeaks(ctx)` 检查的是**仍活跃的注册**,不是「是否调用过 dispose」:
|
|
138
|
+
|
|
139
|
+
- `ctx.dispose()` 之后一定通过;
|
|
140
|
+
- 从未 dispose、但每个 listener/effect 都用返回的 disposer 释放了,也通过;
|
|
141
|
+
- 一个 effect 即使没有返回 cleanup,只要没释放仍算活跃资源(严格模式,避免「注册了却没人管」);
|
|
142
|
+
- plugin 只要 apply 成功、尚未 dispose,就算活跃 plugin。
|
|
143
|
+
|
|
144
|
+
## 限制
|
|
145
|
+
|
|
146
|
+
### 与 Cordis 的差异(重要限制)
|
|
147
|
+
|
|
148
|
+
这是为测试写的**同步替身**,不是 drop-in replacement:
|
|
149
|
+
|
|
150
|
+
- **没有 fiber / 子 context / scope**:插件拿到的是同一个 context,不是 Cordis fork 出来的子 context。
|
|
151
|
+
- **没有依赖注入**:`inject`、`provide`、service、`reflect`、配置 schema 校验、logger 均未实现。
|
|
152
|
+
- **effects 仅同步**:只接受「返回 cleanup 函数或 undefined/null」;Promise、async cleanup、iterator/async iterator 会抛 `TypeError`。
|
|
153
|
+
- **不支持热重载**:没有 `ctx.update()`、`restart()`、`fiber.await()`、HMR 语义。
|
|
154
|
+
- **事件能力有限**:没有 `once`、`prepend`、`parallel`/`serial`/`bail`/`waterfall`、事件过滤和 `internal/*` 生命周期事件。
|
|
155
|
+
- **返回值是 mock 的便利约定**:`ctx.emit()` 返回 listener 返回值数组(Cordis 返回 void);`ctx.plugin()` 返回 `ctx`(Cordis 返回 fiber 句柄)。
|
|
156
|
+
- **listener 的 `this`**:本实现绑定为 `ctx`;这不是 Cordis 公开保证的一部分。
|
|
157
|
+
- **单线程、无并发保护**:不要跨测试共享一个 context。
|
|
158
|
+
- **不能证明真实资源已释放**:它只追踪通过 mock context 注册的 listener/effect/plugin;定时器、socket、文件句柄等需要插件自己的 cleanup 去释放,替身只能证明 cleanup 被调用了。
|
|
159
|
+
|
|
160
|
+
如果测试需要真实的 Cordis 行为(fiber、inject、HMR),请用官方 `cordis` 运行时,而不是本包。
|
|
161
|
+
|
|
162
|
+
## 命名核验
|
|
163
|
+
|
|
164
|
+
核验日期:**2026-11-14**。结论:`cordis-testkit` 当时**未在 npm 注册**,也不是 Cordis 官方包名,但这是一个非保留名称,未来仍可能被他人占用;本包与官方无关联。
|
|
165
|
+
|
|
166
|
+
证据与命令:
|
|
167
|
+
|
|
168
|
+
```sh
|
|
169
|
+
npm view cordis-testkit version
|
|
170
|
+
# npm error 404 Not Found - GET https://registry.npmjs.org/cordis-testkit
|
|
171
|
+
|
|
172
|
+
npm view cordis version
|
|
173
|
+
# 4.0.0-rc.13 (cordiverse 官方包)
|
|
174
|
+
|
|
175
|
+
npm view @cordisjs/testkit version
|
|
176
|
+
npm view cordis-test-utils version
|
|
177
|
+
npm view @cordisjs/test-utils version
|
|
178
|
+
npm view cordis-mock version
|
|
179
|
+
# 以上均 404(核验当日)
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
- 官方仓库:<https://github.com/cordiverse/cordis>;官方 npm 包名是 `cordis`,不是 `cordis-testkit`。
|
|
183
|
+
- 官方仓库 `packages/` 目录(核验当日)为:`cli-cordis, cli, core, create, env, fs-node, fs, group, hmr, http-socks, http, include, loader, logger-console, package-manager, timer`,其中没有 `testkit`。
|
|
184
|
+
- DeepSeek Harness 生态里另有 `@deepseek-ai/dsh-tool-testkit`、`@deepseek-ai/dsh-agent-loop-testkit` 等带 scope 的包,与本包无关;本包也不代表 DeepSeek。
|
|
185
|
+
- 本项目只借用公开 API 形状做测试替身,不复用官方源码。官方 Cordis 为 MIT;本包为 Apache-2.0。
|
|
186
|
+
|
|
187
|
+
如果上游未来发布同名/近似名包,应以官方命名为准,本包可随时更名。
|
|
188
|
+
|
|
189
|
+
## 非官方声明
|
|
190
|
+
|
|
191
|
+
本项目是社区独立项目,**不是 Cordis 官方实现**,也不由 cordiverse / Cordis
|
|
192
|
+
作者或 DeepSeek 背书。`cordis`、`Cordis` 等名称属于其各自权利人;本包仅作为
|
|
193
|
+
非官方的社区测试工具。Cordis 本身是 MIT 项目,本包使用 Apache-2.0。
|
|
194
|
+
|
|
195
|
+
## License
|
|
196
|
+
|
|
197
|
+
Apache-2.0,见 [LICENSE](./LICENSE)。
|
|
198
|
+
|
|
199
|
+
`cordis`、`Cordis` 等名称属于其各自权利人。本包仅为非官方的社区测试工具。
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cordis-testkit",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Unofficial mock Cordis context and effect-leak assertions for plugin unit tests.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./src/core.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"src",
|
|
12
|
+
"README.md",
|
|
13
|
+
"DESIGN.md",
|
|
14
|
+
"LICENSE"
|
|
15
|
+
],
|
|
16
|
+
"engines": {
|
|
17
|
+
"node": "^22.19.0 || >=24.9.0"
|
|
18
|
+
},
|
|
19
|
+
"scripts": {
|
|
20
|
+
"test": "node --test test/*.test.js",
|
|
21
|
+
"check": "node --check src/core.js"
|
|
22
|
+
},
|
|
23
|
+
"keywords": [
|
|
24
|
+
"cordis",
|
|
25
|
+
"testkit",
|
|
26
|
+
"mock-context",
|
|
27
|
+
"effect",
|
|
28
|
+
"leak-detection",
|
|
29
|
+
"unit-testing"
|
|
30
|
+
],
|
|
31
|
+
"sideEffects": false,
|
|
32
|
+
"repository": {
|
|
33
|
+
"type": "git",
|
|
34
|
+
"url": "git+https://github.com/PerryLink/dsh-next-suite.git",
|
|
35
|
+
"directory": "packages/cordis-testkit"
|
|
36
|
+
},
|
|
37
|
+
"homepage": "https://github.com/PerryLink/dsh-next-suite/tree/main/packages/cordis-testkit#readme",
|
|
38
|
+
"bugs": {
|
|
39
|
+
"url": "https://github.com/PerryLink/dsh-next-suite/issues"
|
|
40
|
+
},
|
|
41
|
+
"author": "PerryLink",
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public"
|
|
44
|
+
}
|
|
45
|
+
}
|
package/src/core.js
ADDED
|
@@ -0,0 +1,606 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unofficial, dependency-free test double for a Cordis context.
|
|
3
|
+
*
|
|
4
|
+
* This module is intentionally small: it records listeners, effects and
|
|
5
|
+
* plugins so plugin tests can (a) drive `ctx.emit()` deterministically and
|
|
6
|
+
* (b) fail when a plugin forgets to release something. It is **not** a
|
|
7
|
+
* Cordis runtime and does not implement fibers, dependency injection,
|
|
8
|
+
* service reflection or asynchronous effects. See README.md / DESIGN.md.
|
|
9
|
+
*
|
|
10
|
+
* @module cordis-testkit
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* State slot. Registered with `Symbol.for` so several copies of this module
|
|
15
|
+
* can still recognise each other's contexts in a test process.
|
|
16
|
+
*/
|
|
17
|
+
const STATE = Symbol.for('cordis-testkit.state')
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @typedef {object} ListenerRecord
|
|
21
|
+
* @property {string | symbol} event
|
|
22
|
+
* @property {Function} callback
|
|
23
|
+
* @property {boolean} active
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @typedef {object} EffectRecord
|
|
28
|
+
* @property {string} label
|
|
29
|
+
* @property {boolean} active
|
|
30
|
+
* @property {boolean} disposed
|
|
31
|
+
* @property {(() => void) | null} cleanup
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @typedef {object} PluginRecord
|
|
36
|
+
* @property {string} name
|
|
37
|
+
* @property {boolean} active
|
|
38
|
+
* @property {boolean} disposed
|
|
39
|
+
* @property {(() => void) | null} cleanup
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* LIFO cleanup entry. Listeners are removed en masse at the end of
|
|
44
|
+
* `dispose()`, so they do not need an entry here.
|
|
45
|
+
*
|
|
46
|
+
* @typedef {{ kind: 'effect', record: EffectRecord }
|
|
47
|
+
* | { kind: 'plugin', record: PluginRecord }} CleanupEntry
|
|
48
|
+
*/
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @typedef {object} MockContextState
|
|
52
|
+
* @property {ListenerRecord[]} listeners
|
|
53
|
+
* @property {EffectRecord[]} effects
|
|
54
|
+
* @property {PluginRecord[]} plugins
|
|
55
|
+
* @property {CleanupEntry[]} cleanups
|
|
56
|
+
* @property {Map<unknown, unknown>} store
|
|
57
|
+
* @property {boolean} disposed
|
|
58
|
+
* @property {number} sequence
|
|
59
|
+
*/
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Active resources of a mock context, in registration order.
|
|
63
|
+
*
|
|
64
|
+
* @typedef {object} ContextSnapshot
|
|
65
|
+
* @property {(string | symbol)[]} listeners Active listener event names.
|
|
66
|
+
* @property {string[]} effects Active effect labels.
|
|
67
|
+
* @property {string[]} plugins Active plugin names.
|
|
68
|
+
* @property {boolean} disposed Whether `ctx.dispose()` has run.
|
|
69
|
+
*/
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Read and validate internal state.
|
|
73
|
+
*
|
|
74
|
+
* @param {unknown} ctx
|
|
75
|
+
* @returns {MockContextState}
|
|
76
|
+
*/
|
|
77
|
+
function stateOf(ctx) {
|
|
78
|
+
const state =
|
|
79
|
+
ctx !== null && typeof ctx === 'object'
|
|
80
|
+
? /** @type {Record<symbol, MockContextState | undefined>} */ (ctx)[STATE]
|
|
81
|
+
: undefined
|
|
82
|
+
if (!state) {
|
|
83
|
+
throw new TypeError(
|
|
84
|
+
'expected a mock context created by createMockContext()',
|
|
85
|
+
)
|
|
86
|
+
}
|
|
87
|
+
return state
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* @param {MockContextState} state
|
|
92
|
+
* @param {string} operation
|
|
93
|
+
*/
|
|
94
|
+
function assertActive(state, operation) {
|
|
95
|
+
if (state.disposed) {
|
|
96
|
+
throw new Error(`cannot ${operation} on a disposed Cordis mock context`)
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* @param {unknown} event
|
|
102
|
+
* @returns {asserts event is string | symbol}
|
|
103
|
+
*/
|
|
104
|
+
function assertEvent(event) {
|
|
105
|
+
if (typeof event !== 'string' && typeof event !== 'symbol') {
|
|
106
|
+
throw new TypeError('event must be a string or a symbol')
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Resolve a plugin's display name and check that it is applicable.
|
|
112
|
+
*
|
|
113
|
+
* @param {unknown} plugin
|
|
114
|
+
* @param {MockContextState} state
|
|
115
|
+
* @returns {{ name: string, callback: Function, thisArg: unknown }}
|
|
116
|
+
*/
|
|
117
|
+
function normalizePlugin(plugin, state) {
|
|
118
|
+
if (typeof plugin === 'function') {
|
|
119
|
+
return {
|
|
120
|
+
name: plugin.name || `plugin#${++state.sequence}`,
|
|
121
|
+
callback: plugin,
|
|
122
|
+
thisArg: undefined,
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (
|
|
127
|
+
plugin !== null &&
|
|
128
|
+
typeof plugin === 'object' &&
|
|
129
|
+
typeof /** @type {{ apply?: unknown }} */ (plugin).apply === 'function'
|
|
130
|
+
) {
|
|
131
|
+
const object = /** @type {{ name?: unknown, apply: Function }} */ (plugin)
|
|
132
|
+
let name = typeof object.name === 'string' ? object.name : ''
|
|
133
|
+
if (!name && object.apply.name && object.apply.name !== 'apply') {
|
|
134
|
+
name = object.apply.name
|
|
135
|
+
}
|
|
136
|
+
return {
|
|
137
|
+
name: name || `plugin#${++state.sequence}`,
|
|
138
|
+
callback: object.apply,
|
|
139
|
+
thisArg: object,
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
throw new TypeError(
|
|
144
|
+
'plugin must be a function or an object with an apply(ctx, config) method',
|
|
145
|
+
)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Dispose one effect and (optionally) collect its cleanup error.
|
|
150
|
+
*
|
|
151
|
+
* The record is marked disposed before the cleanup runs, so a re-entrant or
|
|
152
|
+
* repeated disposal cannot call the cleanup twice.
|
|
153
|
+
*
|
|
154
|
+
* @param {MockContextState} state
|
|
155
|
+
* @param {EffectRecord} record
|
|
156
|
+
* @param {unknown[] | null} errors Collect errors when non-null; otherwise
|
|
157
|
+
* rethrow immediately (used by the disposer returned from `ctx.effect()`).
|
|
158
|
+
*/
|
|
159
|
+
function disposeEffect(state, record, errors) {
|
|
160
|
+
if (record.disposed) return
|
|
161
|
+
record.disposed = true
|
|
162
|
+
record.active = false
|
|
163
|
+
|
|
164
|
+
const index = state.effects.indexOf(record)
|
|
165
|
+
if (index !== -1) state.effects.splice(index, 1)
|
|
166
|
+
|
|
167
|
+
if (!record.cleanup) return
|
|
168
|
+
try {
|
|
169
|
+
record.cleanup()
|
|
170
|
+
} catch (error) {
|
|
171
|
+
if (errors) errors.push(error)
|
|
172
|
+
else throw error
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Dispose one plugin instance and optionally collect its cleanup error.
|
|
178
|
+
*
|
|
179
|
+
* @param {MockContextState} state
|
|
180
|
+
* @param {PluginRecord} record
|
|
181
|
+
* @param {unknown[] | null} errors
|
|
182
|
+
*/
|
|
183
|
+
function disposePlugin(state, record, errors) {
|
|
184
|
+
if (record.disposed) return
|
|
185
|
+
record.disposed = true
|
|
186
|
+
record.active = false
|
|
187
|
+
|
|
188
|
+
const index = state.plugins.indexOf(record)
|
|
189
|
+
if (index !== -1) state.plugins.splice(index, 1)
|
|
190
|
+
|
|
191
|
+
if (!record.cleanup) return
|
|
192
|
+
try {
|
|
193
|
+
record.cleanup()
|
|
194
|
+
} catch (error) {
|
|
195
|
+
if (errors) errors.push(error)
|
|
196
|
+
else throw error
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* @param {unknown[]} names
|
|
202
|
+
* @returns {string}
|
|
203
|
+
*/
|
|
204
|
+
function formatNames(names) {
|
|
205
|
+
return names
|
|
206
|
+
.map((name) =>
|
|
207
|
+
typeof name === 'symbol' ? name.toString() : JSON.stringify(name),
|
|
208
|
+
)
|
|
209
|
+
.join(', ')
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* A minimal, synchronous mock of a Cordis context.
|
|
214
|
+
*
|
|
215
|
+
* Create one with {@link createMockContext}. Do not construct it directly in
|
|
216
|
+
* tests: `createMockContext()` is the stable entry point.
|
|
217
|
+
*/
|
|
218
|
+
export class MockContext {
|
|
219
|
+
constructor() {
|
|
220
|
+
/** @type {MockContextState} */
|
|
221
|
+
this[STATE] = {
|
|
222
|
+
listeners: [],
|
|
223
|
+
effects: [],
|
|
224
|
+
plugins: [],
|
|
225
|
+
cleanups: [],
|
|
226
|
+
store: new Map(),
|
|
227
|
+
disposed: false,
|
|
228
|
+
sequence: 0,
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** @returns {boolean} */
|
|
233
|
+
get disposed() {
|
|
234
|
+
return this[STATE].disposed
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Register an event listener.
|
|
239
|
+
*
|
|
240
|
+
* The listener is invoked with the mock context as `this`. Registering the
|
|
241
|
+
* same callback twice creates two independent registrations.
|
|
242
|
+
*
|
|
243
|
+
* @param {string | symbol} event
|
|
244
|
+
* @param {(...args: unknown[]) => unknown} callback
|
|
245
|
+
* @returns {() => void} Idempotent disposer for this registration.
|
|
246
|
+
*/
|
|
247
|
+
on(event, callback) {
|
|
248
|
+
const state = stateOf(this)
|
|
249
|
+
assertActive(state, 'register a listener')
|
|
250
|
+
assertEvent(event)
|
|
251
|
+
if (typeof callback !== 'function') {
|
|
252
|
+
throw new TypeError('listener must be a function')
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** @type {ListenerRecord} */
|
|
256
|
+
const record = { event, callback, active: true }
|
|
257
|
+
state.listeners.push(record)
|
|
258
|
+
|
|
259
|
+
let removed = false
|
|
260
|
+
return () => {
|
|
261
|
+
if (removed) return
|
|
262
|
+
removed = true
|
|
263
|
+
record.active = false
|
|
264
|
+
const index = state.listeners.indexOf(record)
|
|
265
|
+
if (index !== -1) state.listeners.splice(index, 1)
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Emit an event synchronously.
|
|
271
|
+
*
|
|
272
|
+
* Listeners are snapshotted before dispatch: listeners added during the
|
|
273
|
+
* emit are not called by this emit, while listeners removed during it are
|
|
274
|
+
* skipped. Errors propagate and stop the dispatch, matching Cordis.
|
|
275
|
+
*
|
|
276
|
+
* Unlike Cordis (which returns `void`), this returns the listeners' return
|
|
277
|
+
* values as a convenience for tests.
|
|
278
|
+
*
|
|
279
|
+
* @param {string | symbol} event
|
|
280
|
+
* @param {...unknown} args
|
|
281
|
+
* @returns {unknown[]}
|
|
282
|
+
*/
|
|
283
|
+
emit(event, ...args) {
|
|
284
|
+
const state = stateOf(this)
|
|
285
|
+
assertEvent(event)
|
|
286
|
+
|
|
287
|
+
const results = []
|
|
288
|
+
for (const record of state.listeners.slice()) {
|
|
289
|
+
if (!record.active || record.event !== event) continue
|
|
290
|
+
results.push(Reflect.apply(record.callback, this, args))
|
|
291
|
+
}
|
|
292
|
+
return results
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Run a setup callback immediately and remember its cleanup.
|
|
297
|
+
*
|
|
298
|
+
* Supported return values are a synchronous cleanup function or
|
|
299
|
+
* `undefined`/`null`. Promises, iterators and other asynchronous forms are
|
|
300
|
+
* rejected: this test double is deliberately synchronous.
|
|
301
|
+
*
|
|
302
|
+
* Effects are considered owned resources even when they return no cleanup;
|
|
303
|
+
* `dispose()` or the returned disposer must be called before
|
|
304
|
+
* {@link assertNoLeaks} passes.
|
|
305
|
+
*
|
|
306
|
+
* @param {() => (() => void) | void | null} callback
|
|
307
|
+
* @param {string | symbol} [label] Diagnostic label; defaults to `effect#N`.
|
|
308
|
+
* @returns {() => void} Idempotent disposer for this effect.
|
|
309
|
+
*/
|
|
310
|
+
effect(callback, label) {
|
|
311
|
+
const state = stateOf(this)
|
|
312
|
+
assertActive(state, 'register an effect')
|
|
313
|
+
if (typeof callback !== 'function') {
|
|
314
|
+
throw new TypeError('effect callback must be a function')
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** @type {EffectRecord} */
|
|
318
|
+
const record = {
|
|
319
|
+
label:
|
|
320
|
+
label === undefined || label === null
|
|
321
|
+
? `effect#${++state.sequence}`
|
|
322
|
+
: String(label),
|
|
323
|
+
active: true,
|
|
324
|
+
disposed: false,
|
|
325
|
+
cleanup: null,
|
|
326
|
+
}
|
|
327
|
+
/** @type {CleanupEntry} */
|
|
328
|
+
const entry = { kind: 'effect', record }
|
|
329
|
+
state.effects.push(record)
|
|
330
|
+
state.cleanups.push(entry)
|
|
331
|
+
|
|
332
|
+
try {
|
|
333
|
+
const cleanup = callback()
|
|
334
|
+
if (cleanup !== undefined && cleanup !== null) {
|
|
335
|
+
if (typeof cleanup !== 'function') {
|
|
336
|
+
throw new TypeError(
|
|
337
|
+
'effect callback must return a synchronous cleanup function, ' +
|
|
338
|
+
'undefined or null',
|
|
339
|
+
)
|
|
340
|
+
}
|
|
341
|
+
record.cleanup = cleanup
|
|
342
|
+
}
|
|
343
|
+
} catch (error) {
|
|
344
|
+
// A failed setup must not leave a phantom effect behind.
|
|
345
|
+
record.active = false
|
|
346
|
+
record.disposed = true
|
|
347
|
+
const effectIndex = state.effects.indexOf(record)
|
|
348
|
+
if (effectIndex !== -1) state.effects.splice(effectIndex, 1)
|
|
349
|
+
const cleanupIndex = state.cleanups.indexOf(entry)
|
|
350
|
+
if (cleanupIndex !== -1) state.cleanups.splice(cleanupIndex, 1)
|
|
351
|
+
throw error
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
let removed = false
|
|
355
|
+
return () => {
|
|
356
|
+
if (removed) return
|
|
357
|
+
removed = true
|
|
358
|
+
disposeEffect(state, record, null)
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Store a value on the mock context.
|
|
364
|
+
*
|
|
365
|
+
* @param {unknown} key
|
|
366
|
+
* @param {unknown} value
|
|
367
|
+
* @returns {unknown} The stored value.
|
|
368
|
+
*/
|
|
369
|
+
set(key, value) {
|
|
370
|
+
stateOf(this).store.set(key, value)
|
|
371
|
+
return value
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Read a value previously stored with {@link set}.
|
|
376
|
+
*
|
|
377
|
+
* @param {unknown} key
|
|
378
|
+
* @returns {unknown}
|
|
379
|
+
*/
|
|
380
|
+
get(key) {
|
|
381
|
+
return stateOf(this).store.get(key)
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* Apply a plugin synchronously.
|
|
386
|
+
*
|
|
387
|
+
* Function plugins are called as `plugin(ctx, config)` with `this` bound to
|
|
388
|
+
* the mock context. Object plugins are called as `plugin.apply(ctx, config)`
|
|
389
|
+
* with `this` bound to the plugin object. A returned function is treated as
|
|
390
|
+
* the plugin's cleanup function and runs during `ctx.dispose()`.
|
|
391
|
+
*
|
|
392
|
+
* The plugin receives the same context (there is no forked child fiber),
|
|
393
|
+
* and its listeners/effects are therefore owned by this context.
|
|
394
|
+
*
|
|
395
|
+
* @param {Function | { name?: string, apply: Function }} plugin
|
|
396
|
+
* @param {unknown} [config]
|
|
397
|
+
* @returns {this} The context, for optional chaining.
|
|
398
|
+
*/
|
|
399
|
+
plugin(plugin, config) {
|
|
400
|
+
const state = stateOf(this)
|
|
401
|
+
assertActive(state, 'load a plugin')
|
|
402
|
+
const target = normalizePlugin(plugin, state)
|
|
403
|
+
|
|
404
|
+
/** @type {PluginRecord} */
|
|
405
|
+
const record = {
|
|
406
|
+
name: target.name,
|
|
407
|
+
active: true,
|
|
408
|
+
disposed: false,
|
|
409
|
+
cleanup: null,
|
|
410
|
+
}
|
|
411
|
+
state.plugins.push(record)
|
|
412
|
+
|
|
413
|
+
let result
|
|
414
|
+
try {
|
|
415
|
+
result = Reflect.apply(target.callback, target.thisArg ?? this, [
|
|
416
|
+
this,
|
|
417
|
+
config,
|
|
418
|
+
])
|
|
419
|
+
} catch (error) {
|
|
420
|
+
// The plugin never finished loading, so it has no instance to dispose.
|
|
421
|
+
record.active = false
|
|
422
|
+
const index = state.plugins.indexOf(record)
|
|
423
|
+
if (index !== -1) state.plugins.splice(index, 1)
|
|
424
|
+
throw error
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
if (result !== undefined && result !== null) {
|
|
428
|
+
if (typeof result !== 'function') {
|
|
429
|
+
record.active = false
|
|
430
|
+
record.disposed = true
|
|
431
|
+
const index = state.plugins.indexOf(record)
|
|
432
|
+
if (index !== -1) state.plugins.splice(index, 1)
|
|
433
|
+
throw new TypeError(
|
|
434
|
+
'plugin must return a synchronous cleanup function, ' +
|
|
435
|
+
'undefined or null',
|
|
436
|
+
)
|
|
437
|
+
}
|
|
438
|
+
record.cleanup = result
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// Register the plugin's lifecycle after its apply completed, so cleanup
|
|
442
|
+
// runs before the effects it registered (LIFO disposal).
|
|
443
|
+
state.cleanups.push({ kind: 'plugin', record })
|
|
444
|
+
return this
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* Dispose the context.
|
|
449
|
+
*
|
|
450
|
+
* Cleanup entries (effects and plugin cleanups) run in reverse registration
|
|
451
|
+
* order; listener tables are cleared last. All cleanup errors are collected
|
|
452
|
+
* and rethrown together after every resource has been released, so a
|
|
453
|
+
* failing cleanup cannot leave the context half-alive.
|
|
454
|
+
*
|
|
455
|
+
* The call is idempotent: the second and later calls are no-ops, even if
|
|
456
|
+
* the first call threw. It is safe to call `dispose()` from inside a
|
|
457
|
+
* cleanup.
|
|
458
|
+
*
|
|
459
|
+
* @returns {void}
|
|
460
|
+
* @throws {AggregateError} When one or more cleanup functions threw.
|
|
461
|
+
*/
|
|
462
|
+
dispose() {
|
|
463
|
+
const state = stateOf(this)
|
|
464
|
+
if (state.disposed) return
|
|
465
|
+
state.disposed = true
|
|
466
|
+
|
|
467
|
+
/** @type {unknown[]} */
|
|
468
|
+
const errors = []
|
|
469
|
+
while (state.cleanups.length > 0) {
|
|
470
|
+
const entry = /** @type {CleanupEntry} */ (state.cleanups.pop())
|
|
471
|
+
if (entry.kind === 'effect') {
|
|
472
|
+
disposeEffect(state, entry.record, errors)
|
|
473
|
+
} else {
|
|
474
|
+
disposePlugin(state, entry.record, errors)
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
for (const listener of state.listeners) listener.active = false
|
|
479
|
+
state.listeners.length = 0
|
|
480
|
+
state.effects.length = 0
|
|
481
|
+
state.plugins.length = 0
|
|
482
|
+
|
|
483
|
+
if (errors.length > 0) {
|
|
484
|
+
const error = new AggregateError(
|
|
485
|
+
errors,
|
|
486
|
+
`context disposal failed: ${errors.length} cleanup step(s) threw`,
|
|
487
|
+
)
|
|
488
|
+
// @ts-expect-error -- expando used by tests and tooling.
|
|
489
|
+
error.code = 'ERR_CORDIS_DISPOSE'
|
|
490
|
+
throw error
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* Create a fresh mock context.
|
|
497
|
+
*
|
|
498
|
+
* @returns {MockContext}
|
|
499
|
+
*/
|
|
500
|
+
export function createMockContext() {
|
|
501
|
+
return new MockContext()
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* Capture the context's active resources.
|
|
506
|
+
*
|
|
507
|
+
* The arrays are freshly allocated copies of the active resources (disposed
|
|
508
|
+
* registrations are omitted), so callers may mutate them freely.
|
|
509
|
+
*
|
|
510
|
+
* @param {MockContext} ctx
|
|
511
|
+
* @returns {ContextSnapshot}
|
|
512
|
+
*/
|
|
513
|
+
export function snapshot(ctx) {
|
|
514
|
+
const state = stateOf(ctx)
|
|
515
|
+
return {
|
|
516
|
+
listeners: state.listeners
|
|
517
|
+
.filter((listener) => listener.active)
|
|
518
|
+
.map((listener) => listener.event),
|
|
519
|
+
effects: state.effects
|
|
520
|
+
.filter((effect) => effect.active)
|
|
521
|
+
.map((effect) => effect.label),
|
|
522
|
+
plugins: state.plugins
|
|
523
|
+
.filter((plugin) => plugin.active)
|
|
524
|
+
.map((plugin) => plugin.name),
|
|
525
|
+
disposed: state.disposed,
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/**
|
|
530
|
+
* Assert that the context has no active listeners, effects or plugins.
|
|
531
|
+
*
|
|
532
|
+
* Typical use is after `ctx.dispose()`:
|
|
533
|
+
*
|
|
534
|
+
* ```js
|
|
535
|
+
* const ctx = runPlugin(plugin)
|
|
536
|
+
* ctx.dispose()
|
|
537
|
+
* assertNoLeaks(ctx)
|
|
538
|
+
* ```
|
|
539
|
+
*
|
|
540
|
+
* A context that was never disposed still passes when every registration was
|
|
541
|
+
* explicitly released. `disposed` itself is not a requirement.
|
|
542
|
+
*
|
|
543
|
+
* @param {MockContext} ctx
|
|
544
|
+
* @returns {void}
|
|
545
|
+
* @throws {Error & { code: string, leaks: ContextSnapshot }} With a
|
|
546
|
+
* human-readable inventory when resources remain.
|
|
547
|
+
*/
|
|
548
|
+
export function assertNoLeaks(ctx) {
|
|
549
|
+
const leaks = snapshot(ctx)
|
|
550
|
+
if (
|
|
551
|
+
leaks.listeners.length === 0 &&
|
|
552
|
+
leaks.effects.length === 0 &&
|
|
553
|
+
leaks.plugins.length === 0
|
|
554
|
+
) {
|
|
555
|
+
return
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
const parts = []
|
|
559
|
+
if (leaks.listeners.length > 0) {
|
|
560
|
+
parts.push(
|
|
561
|
+
`listeners: ${leaks.listeners.length} [${formatNames(leaks.listeners)}]`,
|
|
562
|
+
)
|
|
563
|
+
}
|
|
564
|
+
if (leaks.effects.length > 0) {
|
|
565
|
+
parts.push(`effects: ${leaks.effects.length} [${formatNames(leaks.effects)}]`)
|
|
566
|
+
}
|
|
567
|
+
if (leaks.plugins.length > 0) {
|
|
568
|
+
parts.push(
|
|
569
|
+
`plugins: ${leaks.plugins.length} [${formatNames(leaks.plugins)}]`,
|
|
570
|
+
)
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
const error = new Error(
|
|
574
|
+
`Cordis mock context leak detected: ${parts.join('; ')}. ` +
|
|
575
|
+
'Call ctx.dispose() or release each registration before asserting.',
|
|
576
|
+
)
|
|
577
|
+
Object.assign(error, { code: 'ERR_CORDIS_LEAK', leaks })
|
|
578
|
+
throw error
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/**
|
|
582
|
+
* Create a context, apply one plugin to it and return the live context.
|
|
583
|
+
*
|
|
584
|
+
* The caller owns disposal: call `ctx.dispose()` and then
|
|
585
|
+
* {@link assertNoLeaks} when the test is done. If applying the plugin throws,
|
|
586
|
+
* this helper disposes the partial context before rethrowing, so a failed
|
|
587
|
+
* setup cannot leak listeners/effects.
|
|
588
|
+
*
|
|
589
|
+
* @param {Function | { name?: string, apply: Function }} plugin
|
|
590
|
+
* @param {unknown} [config]
|
|
591
|
+
* @returns {MockContext}
|
|
592
|
+
*/
|
|
593
|
+
export function runPlugin(plugin, config) {
|
|
594
|
+
const ctx = createMockContext()
|
|
595
|
+
try {
|
|
596
|
+
ctx.plugin(plugin, config)
|
|
597
|
+
} catch (error) {
|
|
598
|
+
try {
|
|
599
|
+
ctx.dispose()
|
|
600
|
+
} catch {
|
|
601
|
+
// Preserve the plugin's original error; cleanup errors are secondary.
|
|
602
|
+
}
|
|
603
|
+
throw error
|
|
604
|
+
}
|
|
605
|
+
return ctx
|
|
606
|
+
}
|