@240xu/dsh-message-ops 0.23.0 → 0.47.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.
@@ -0,0 +1,84 @@
1
+ /**
2
+ * 宿主服务解析(0.39.4)。
3
+ *
4
+ * 背景:DSH 0.2.3 的 fiber 隔离下,插件 fiber 里 `ctx.get('sessions'/'agents')`
5
+ * 可能恒为 undefined(真机日志:boot 期全 undefined;写合成 turn 时 agents 仍不可见)。
6
+ * cordis 的 `ctx.inject(deps, fn)` 回调拿到的是**注入命名空间**,服务一定在其同名
7
+ * 属性上 —— 这是隔离 fiber 下唯一可靠的取法。
8
+ *
9
+ * 这里把「捕获 + 解析」收敛到一处,供 index.js(运行中守卫/flush/游标对齐)与
10
+ * session-trash.js(live 会话判定)共用,避免各处各写一套 ctx.get 兜底
11
+ * (srv-audit D1:只有 resolveSession 用捕获时,运行中守卫在真机形态下失效)。
12
+ */
13
+ const captured = { sessions: null, agents: null }
14
+
15
+ function take(scope) {
16
+ if (!scope) return
17
+ let sessions = null
18
+ let agents = null
19
+ try {
20
+ sessions = typeof scope.get === 'function' ? scope.get('sessions') : scope.sessions
21
+ agents = typeof scope.get === 'function' ? scope.get('agents') : scope.agents
22
+ } catch {
23
+ /* 隔离上下文里 get 可能抛 */
24
+ }
25
+ if (sessions && typeof sessions.get === 'function' && captured.sessions !== sessions) {
26
+ captured.sessions = sessions
27
+ console.log('[message-ops] service captured: sessions')
28
+ }
29
+ if (agents && typeof agents.get === 'function' && captured.agents !== agents) {
30
+ captured.agents = agents
31
+ console.log('[message-ops] service captured: agents')
32
+ }
33
+ }
34
+
35
+ /**
36
+ * 在 apply 期捕获 sessions/agents:先试探当前 ctx,再各注册一次 inject。
37
+ * @param {object} ctx 宿主 ctx
38
+ * @returns {{sessions: object|null, agents: object|null}} 捕获结果(可能仍为空)
39
+ */
40
+ export function captureServices(ctx) {
41
+ take(ctx)
42
+ for (const name of ['sessions', 'agents']) {
43
+ try {
44
+ ctx.inject([name], sub => take(sub))
45
+ } catch {
46
+ /* 老宿主没有该服务 / 已卸载 */
47
+ }
48
+ }
49
+ return captured
50
+ }
51
+
52
+ /**
53
+ * 清空捕获(仅供测试:真实运行期捕获一旦成立就不该丢失)。
54
+ * @returns {void}
55
+ */
56
+ export function resetCapturedServicesForTests() {
57
+ captured.sessions = null
58
+ captured.agents = null
59
+ }
60
+
61
+ /**
62
+ * 取宿主服务:捕获实例优先,其次 ctx.get,最后属性访问。
63
+ * @param {object} ctx 宿主 ctx
64
+ * @param {'sessions'|'agents'} name 服务名
65
+ * @returns {object|null} 服务实例
66
+ */
67
+ export function serviceOf(ctx, name) {
68
+ const hit = captured[name]
69
+ if (hit && typeof hit.get === 'function') return hit
70
+ try {
71
+ if (ctx && typeof ctx.get === 'function') {
72
+ const svc = ctx.get(name)
73
+ if (svc) return svc
74
+ }
75
+ } catch {
76
+ /* 隔离上下文 / 老宿主 */
77
+ }
78
+ try {
79
+ if (ctx && ctx[name]) return ctx[name]
80
+ } catch {
81
+ /* getter 抛 */
82
+ }
83
+ return null
84
+ }