dsh-plugin-testkit 0.0.0-stage → 0.1.2

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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +22 -2
  3. package/package.json +30 -4
  4. package/src/index.mjs +139 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dsh-plugin-e2e contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,23 @@
1
- # Temporary Holding Version
1
+ # dsh-plugin-testkit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 轻量单测工具:在沙箱里跑 **DSH 插件客户端半侧**(`client.js`),抓 `slots.register` 并断言——不用起完整 DSH。
4
+
5
+ ```js
6
+ import { loadClientModule, applyAndListSlots, hasSlot } from 'dsh-plugin-testkit'
7
+ import { readFileSync } from 'node:fs'
8
+
9
+ const mod = loadClientModule(readFileSync('client.js', 'utf8'), { id: 'my-plugin' })
10
+ const slots = applyAndListSlots(mod) // [{ name: 'conversation.composer.dock', id: 'my-plugin', order: 5 }]
11
+ ```
12
+
13
+ - 假 `window.__ModuleLoader__.load` + `require('react')` 桩(内置 `createElement` 与常见 hook 桩;hook 是**简化实现**,不驱动真实渲染/副作用),在 `node:vm` 沙箱执行;插件调 `ctx.slots.register(def, comp)` 会被记录。
14
+ - `slots.register` / `slots.inject` **返回 disposer 函数**(与真实 DSH 契约一致)。
15
+ - `applyAndListSlots(mod)` **幂等**:每次 apply 先清空再执行,重复调用不会累加重复注册。
16
+ - `hasSlot(mod, name, id?)`:断言最近一次 apply 是否注册了某 slot。
17
+ - 需要插件用到别的模块时用 `extraRequire: { 'x': stub }` 注入;未提供的模块会明确报错。
18
+
19
+ ## 边界(重要)
20
+ - 这是**逻辑级沙箱**,**不是安全隔离**:只用于**可信测试源码**,不要用它执行不可信插件代码(`node:vm` 可被逃逸)。
21
+ - `window === globalThis`(同浏览器语义);`console` 与定时器是**隔离桩**(日志进 `mod.logs`,定时器不真正计时),避免污染或挂住宿主进程。
22
+ - React hook 为简化桩:`useState/useReducer` 支持函数式更新但不触发重渲染,`useEffect` 为空操作;依赖真实副作用渲染的断言请用 E2E。
23
+ - `opts.id` 只用于对象 id 与 vm 文件名,不会改写源码里的 slot/bundle id(以源码为准)。
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "dsh-plugin-testkit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.2",
4
+ "private": false,
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "description": "Lightweight harness to unit-test a DSH plugin's client half: evaluate client.js in a sandbox with a fake window.__ModuleLoader__ + React stub, capture slot registrations, and assert.",
8
+ "exports": {
9
+ ".": "./src/index.mjs"
10
+ },
11
+ "files": [
12
+ "src/",
13
+ "README.md"
14
+ ],
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/metal-huang/dsh-devtools.git",
18
+ "directory": "packages/dsh-plugin-testkit"
19
+ },
20
+ "publishConfig": {
21
+ "access": "public",
22
+ "registry": "https://registry.npmjs.org/"
23
+ },
24
+ "engines": {
25
+ "dsh": ">=0.2.2-rc.5",
26
+ "node": ">=22.15.0"
27
+ },
28
+ "dshTestedOn": [
29
+ "0.2.2-rc.5",
30
+ "0.2.3-alpha.2"
31
+ ]
32
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,139 @@
1
+ // dsh-plugin-testkit:轻量沙箱跑「插件客户端半侧」,抓 slot 注册并断言——不需要起完整 DSH。
2
+ // 仅用于**可信测试源码**:node:vm 不是安全隔离,不要用它执行不可信代码。
3
+ import vm from 'node:vm'
4
+
5
+ function makeReactStub() {
6
+ const createElement = (type, props, ...children) => ({ type, props: props || {}, children })
7
+ return {
8
+ createElement,
9
+ Fragment: 'Fragment',
10
+ useState(initial) {
11
+ let v = typeof initial === 'function' ? initial() : initial
12
+ const set = (next) => {
13
+ v = typeof next === 'function' ? next(v) : next
14
+ }
15
+ return [v, set]
16
+ },
17
+ useReducer(reducer, init) {
18
+ let s = init
19
+ const dispatch = (action) => {
20
+ s = reducer(s, action)
21
+ }
22
+ return [s, dispatch]
23
+ },
24
+ useEffect() {},
25
+ useLayoutEffect() {},
26
+ useMemo(fn) {
27
+ return fn()
28
+ },
29
+ useCallback(fn) {
30
+ return fn
31
+ },
32
+ useRef(v) {
33
+ return { current: v }
34
+ },
35
+ memo(c) {
36
+ return c
37
+ },
38
+ }
39
+ }
40
+
41
+ /**
42
+ * @param {string} source 插件 client.js 源码
43
+ * @param {{id?:string, extraRequire?:Record<string,any>}} opts
44
+ */
45
+ export function loadClientModule(source, { id = 'plugin', extraRequire = {} } = {}) {
46
+ const registrations = []
47
+ const slots = {
48
+ inject(name, fn) {
49
+ if (typeof fn === 'function') fn()
50
+ return () => {}
51
+ },
52
+ register(def, comp) {
53
+ if (!def || typeof def !== 'object') {
54
+ throw new Error('dsh-plugin-testkit: slots.register 需要定义对象,收到 ' + String(def))
55
+ }
56
+ const rec = { def, comp }
57
+ registrations.push(rec)
58
+ // 与真实 API 一致:返回 disposer 函数
59
+ return () => {
60
+ const i = registrations.indexOf(rec)
61
+ if (i >= 0) registrations.splice(i, 1)
62
+ }
63
+ },
64
+ }
65
+ const logs = []
66
+ const fakeConsole = {
67
+ log: (...a) => logs.push(['log', ...a]),
68
+ info: (...a) => logs.push(['info', ...a]),
69
+ warn: (...a) => logs.push(['warn', ...a]),
70
+ error: (...a) => logs.push(['error', ...a]),
71
+ debug: (...a) => logs.push(['debug', ...a]),
72
+ }
73
+ const noopTimer = () => 0
74
+ const ctx = { slots, logger: fakeConsole, config: {}, on() {}, emit() {} }
75
+ const react = makeReactStub()
76
+ const fakeRequire = (n) => {
77
+ if (Object.prototype.hasOwnProperty.call(extraRequire, n)) return extraRequire[n]
78
+ if (n === 'react') return react
79
+ throw new Error('dsh-plugin-testkit: 未提供 require("' + n + '");用 extraRequire 传入')
80
+ }
81
+ let loaded = false
82
+ let captured = null
83
+ const docStub = {
84
+ createElement: () => ({ style: {}, appendChild() {}, setAttribute() {}, addEventListener() {} }),
85
+ addEventListener() {},
86
+ querySelector: () => null,
87
+ }
88
+ // window === globalThis(同浏览器语义);console/定时器用隔离桩,避免污染或挂住宿主进程。
89
+ const sandbox = {
90
+ console: fakeConsole,
91
+ document: docStub,
92
+ setTimeout: noopTimer,
93
+ clearTimeout() {},
94
+ setInterval: noopTimer,
95
+ clearInterval() {},
96
+ React: react,
97
+ }
98
+ sandbox.window = sandbox
99
+ sandbox.globalThis = sandbox
100
+ sandbox.__ModuleLoader__ = {
101
+ load({ id: lid, factory }) {
102
+ loaded = true
103
+ captured = factory(fakeRequire)
104
+ },
105
+ }
106
+ const context = vm.createContext(sandbox)
107
+ vm.runInContext(source, context, { filename: id + '.client.js' })
108
+ if (!loaded) throw new Error('dsh-plugin-testkit: 客户端未调用 window.__ModuleLoader__.load(...)')
109
+ if (!captured || typeof captured !== 'object') throw new Error('dsh-plugin-testkit: factory 未返回模块对象')
110
+ if (typeof captured.apply !== 'function') throw new Error('dsh-plugin-testkit: 模块对象缺少 apply(ctx) 方法')
111
+ return {
112
+ id,
113
+ module: captured,
114
+ registrations,
115
+ ctx,
116
+ logs,
117
+ // 幂等:每次 apply 先清空再执行,避免重复调用累加出重复注册
118
+ apply() {
119
+ registrations.length = 0
120
+ captured.apply(ctx)
121
+ return registrations
122
+ },
123
+ }
124
+ }
125
+
126
+ /** 跑一次 apply(幂等),返回 [{name,id,order}]。 */
127
+ export function applyAndListSlots(clientModule) {
128
+ clientModule.apply()
129
+ return clientModule.registrations.map((r) => ({
130
+ name: r.def && r.def.name,
131
+ id: r.def && r.def.id,
132
+ order: r.def && r.def.order,
133
+ }))
134
+ }
135
+
136
+ /** 是否注册了指定 slot(可选校验 id)。读取最近一次 apply 的结果。 */
137
+ export function hasSlot(clientModule, name, slotId) {
138
+ return clientModule.registrations.some((r) => r.def && r.def.name === name && (!slotId || r.def.id === slotId))
139
+ }