import assert from 'node:assert/strict'
import { createHash } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { createRequire, registerHooks } from 'node:module'
import { join, resolve, sep } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
assert.equal(process.argv.length, 3, 'Usage: node event-dispatch.mjs <pinned trusted checkout>')
const repo = resolve(process.argv[2])
const base = pathToFileURL(repo + sep).href
const require = createRequire(import.meta.url)
const ts = require(join(repo, 'node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/typescript.js'))
const vendor = {
'@deepseek-ai/cordis': 'vendor/cordis/src/index.ts',
'@deepseek-ai/cosmokit': 'vendor/cosmokit/src/index.ts',
'@deepseek-ai/schemastery': 'vendor/schemastery/src/index.ts',
}
registerHooks({
resolve(specifier, context, next) {
return next(vendor[specifier] ? base + vendor[specifier] : specifier, context)
},
load(url, context, next) {
if (url.startsWith(base) && url.endsWith('.ts')) {
const source = readFileSync(fileURLToPath(url), 'utf8')
return {
format: 'module', shortCircuit: true,
source: ts.transpile(source, { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 }),
}
}
return next(url, context)
},
})
const { Context } = await import('@deepseek-ai/cordis')
const context = new Context()
const cases = []
function check(name, input, expected, actual) {
assert.deepEqual(actual, expected, name)
cases.push({ name, input, expected, actual, passed: true })
}
try {
const trace = []
const gate = Promise.withResolvers()
const finished = Promise.withResolvers()
context.on('lesson/notice', async value => {
trace.push('start:' + value)
await gate.promise
trace.push('finish:' + value)
finished.resolve()
return 'ignored'
})
context.on('lesson/notice', value => trace.push('second:' + value))
const emit = context.emit('lesson/notice', 'sample')
check('emit_returns_before_async_listener_finishes', 'sample with a gated listener',
{ noResult: true, trace: ['start:sample', 'second:sample'] }, { noResult: emit === undefined, trace: [...trace] })
gate.resolve()
await finished.promise
check('emit_async_listener_can_complete_later', 'release the listener gate', 'finish:sample', trace.at(-1))
const bailTrace = []
for (const [label, value] of [['null', null], ['false', false], ['undefined', undefined], ['zero', 0], ['late', 4]]) {
context.on('lesson/decision', () => {
bailTrace.push(label)
return value
})
}
check('bail_accepts_zero_after_three_sentinels', 'listeners return null, false, undefined, 0, 4',
{ result: 0, trace: ['null', 'false', 'undefined', 'zero'] },
{ result: context.bail('lesson/decision'), trace: bailTrace })
const serialTrace = []
const serialGate = Promise.withResolvers()
context.on('lesson/order', async () => {
serialTrace.push('start')
await serialGate.promise
serialTrace.push('finish')
return false
})
context.on('lesson/order', () => {
serialTrace.push('stop')
return ''
})
context.on('lesson/order', () => serialTrace.push('should not run'))
const serial = context.serial('lesson/order')
check('serial_waits_before_starting_next_listener', 'first async listener still gated', ['start'], [...serialTrace])
serialGate.resolve()
check('serial_accepts_empty_string_and_skips_later_listeners', 'release first listener, second returns empty string',
{ result: '', trace: ['start', 'finish', 'stop'] }, { result: await serial, trace: serialTrace })
const waterfallTrace = []
context.on('lesson/label', async (input, next) => {
waterfallTrace.push('outer')
return '[' + await next() + ']'
})
context.on('lesson/label', async (input, next) => {
waterfallTrace.push('inner')
return input === 'skip' ? 'local' : (await next()).trim()
})
const tail = () => {
waterfallTrace.push('default')
return ' text '
}
const wrapping = context.waterfall('lesson/label', 'wrap', tail)
check('waterfall_propagates_async_return_and_wraps_tail', 'wrap, async callbacks, default value includes spaces',
{ thenable: true, result: '[text]', trace: ['outer', 'inner', 'default'] },
{ thenable: typeof wrapping.then === 'function', result: await wrapping, trace: [...waterfallTrace] })
waterfallTrace.length = 0
check('waterfall_short_circuit_preserves_outer_listener', 'skip, inner returns without calling next',
{ result: '[local]', trace: ['outer', 'inner'] },
{ result: await context.waterfall('lesson/label', 'skip', tail), trace: [...waterfallTrace] })
check('waterfall_sync_tail_returns_plain_value', 'unregistered event with synchronous tail',
'plain', context.waterfall('lesson/plain', () => 'plain'))
const concurrent = []
const parallelGate = Promise.withResolvers()
context.on('lesson/parallel', async () => {
concurrent.push('first:start')
await parallelGate.promise
concurrent.push('first:finish')
throw new Error('first failed')
})
context.on('lesson/parallel', async () => {
concurrent.push('second:start')
await parallelGate.promise
concurrent.push('second:finish')
throw new Error('second failed')
})
const parallel = context.parallel('lesson/parallel').catch(error => error)
check('parallel_starts_both_before_either_finishes', 'both listeners wait on the same gate',
['first:start', 'second:start'], [...concurrent])
parallelGate.resolve()
const failure = await parallel
check('parallel_collects_failures_after_both_listeners_settle', 'release both listeners, both throw',
{ aggregate: true, errors: ['first failed', 'second failed'], finished: ['first:finish', 'second:finish'] },
{ aggregate: failure instanceof AggregateError, errors: failure.errors.map(error => error.message),
finished: concurrent.slice(2) })
const messages = []
const plugin = context.plugin(ctx => { ctx.on('lesson/owned', value => messages.push(value)) })
await plugin
context.emit('lesson/owned', 'mounted')
await plugin.dispose()
context.emit('lesson/owned', 'disposed')
check('listener_is_removed_with_owning_plugin', 'emit once mounted and once after dispose',
['mounted'], messages)
} finally {
await context.fiber.dispose()
}
const hash = path => createHash('sha256').update(readFileSync(path)).digest('hex')
const files = ['vendor/cordis/src/events.ts', 'vendor/cordis/src/fiber.ts',
'docs/cordis-api/events.md', 'docs/cordis-tutorial/04-events.zh.md', 'docs/event-producer-consumer.md']
console.log(JSON.stringify({
checked_at: new Date().toISOString(),
source_key: 'e02f29da22809fbd3f36b9f9',
environment: { node: process.version, typescript: ts.version, platform: process.platform },
source_hashes: Object.fromEntries(files.map(path => [path, hash(join(repo, path))])),
authored_code_sha256: hash(fileURLToPath(import.meta.url)),
source_tutorial_scripts_executed: false,
agent_or_session_runtime_executed: false,
type_diagnostics_checked: false,
cases,
}, null, 2))
本例需在 Node.js 24.22.3,固定提交的本地 DeepSeek Harness 源码与 TypeScript 6.0.3。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Node.js 24.22.3,固定提交的本地 DeepSeek Harness 源码与 TypeScript 6.0.3。
入口文件:projects/deepseek-harness-events/event-dispatch.mjs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
event-dispatch.mjs,或下载右侧课程工程包。 - 确认本地已准备 Node.js 24.22.3,固定提交的本地 DeepSeek Harness 源码与 TypeScript 6.0.3。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a135.zip
课程关联工程包(登记关联33章) · 含当前章节或实例 · mbskycom202612a128.zip