@capyclaw/foundation 0.1.4 → 0.1.10

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 (61) hide show
  1. package/README.md +23 -9
  2. package/abi/bridge.mjs +86 -0
  3. package/abi/errors.mjs +4 -0
  4. package/abi/index.mjs +16 -0
  5. package/abi/kinds.mjs +90 -2
  6. package/abi/loader.mjs +285 -184
  7. package/abi/spec.mjs +67 -7
  8. package/abi/version.mjs +63 -5
  9. package/kit/index.mjs +3 -4
  10. package/lib/adapters/client-panel.mjs +98 -0
  11. package/lib/adapters/host-event.mjs +35 -0
  12. package/lib/adapters/http-router.mjs +26 -3
  13. package/lib/adapters/lifecycle-hook.mjs +6 -13
  14. package/lib/adapters/own-server.mjs +113 -0
  15. package/lib/adapters/raw.mjs +69 -0
  16. package/lib/adapters/runtime-driver.mjs +55 -15
  17. package/lib/adapters/service-provider.mjs +77 -0
  18. package/lib/adapters/tool-provider.mjs +11 -4
  19. package/lib/adapters/ui-panel.mjs +11 -4
  20. package/lib/ctx-service.mjs +21 -0
  21. package/lib/host/caps.mjs +13 -5
  22. package/lib/host/contract.mjs +85 -0
  23. package/lib/host/dsh.mjs +10 -1
  24. package/lib/host/memory.mjs +71 -0
  25. package/lib/host.mjs +6 -5
  26. package/lib/kernel.mjs +92 -7
  27. package/lib/skill/scan.mjs +31 -3
  28. package/lib/subsystems/events.mjs +6 -1
  29. package/lib/subsystems/log.mjs +23 -1
  30. package/lib/subsystems/net.mjs +164 -15
  31. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  32. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  33. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  34. package/node_modules/@capyclaw/plugin-kit/package.json +69 -0
  35. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  36. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  37. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +129 -0
  38. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
  39. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  40. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  41. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  42. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  43. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  44. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  45. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  46. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  47. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  48. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  49. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  50. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  51. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  52. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  53. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  54. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  55. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +656 -0
  59. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  60. package/package.json +6 -3
  61. package/runtime/index.mjs +4 -1
package/abi/spec.mjs CHANGED
@@ -31,6 +31,10 @@ const KINDS = Object.freeze({
31
31
  'http-router': 'http-router@1',
32
32
  'ui-panel': 'ui-panel@1',
33
33
  'lifecycle-hook': 'lifecycle-hook@1',
34
+ 'host-event': 'host-event@1',
35
+ 'client-panel': 'client-panel@1',
36
+ 'own-server': 'own-server@1',
37
+ 'service-provider': 'service-provider@1',
34
38
  raw: 'raw@1',
35
39
  })
36
40
 
@@ -68,6 +72,39 @@ export const runtimeDriver = (options) => defineInterface(KINDS['runtime-driver'
68
72
  export const httpRouter = (options) => defineInterface(KINDS['http-router'], options)
69
73
  export const uiPanel = (options) => defineInterface(KINDS['ui-panel'], options)
70
74
  export const lifecycleHook = (options) => defineInterface(KINDS['lifecycle-hook'], options)
75
+ export const hostEvent = (options) => defineInterface(KINDS['host-event'], options)
76
+ export const clientPanel = (options) => defineInterface(KINDS['client-panel'], options)
77
+ export const ownServer = (options) => defineInterface(KINDS['own-server'], options)
78
+ export const serviceProvider = (options) => defineInterface(KINDS['service-provider'], options)
79
+
80
+ /**
81
+ * 驱动层统一入口:基建插件用 defineDriver 声明「我提供哪个 ctx 服务」。
82
+ *
83
+ * 与 createPlugin 的关键区别:不 inject os。驱动必须能在 foundation 之前/之后
84
+ * 独立激活,否则 foundation 的 os.net/os.tools/os.proc 会失去服务来源。
85
+ * apply 仍拿到原生 Cordis ctx,因为提供 ctx.provide 是驱动层的职责。
86
+ */
87
+ export function defineDriver(options = {}) {
88
+ const { name, service, inject = [], apply } = options
89
+ if (!PLUGIN_NAME_RE.test(String(name || ''))) {
90
+ throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, `driver 名必须是 kebab-case:${name}`, { name })
91
+ }
92
+ if (typeof service !== 'string' || !service.trim()) {
93
+ throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, 'driver.service 必须是非空字符串', { name, service })
94
+ }
95
+ if (!Array.isArray(inject) || inject.some((item) => typeof item !== 'string' || !item.trim())) {
96
+ throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, 'driver.inject 必须是非空字符串数组', { name })
97
+ }
98
+ if (typeof apply !== 'function') {
99
+ throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, 'driver.apply 必须是函数', { name, service })
100
+ }
101
+ return Object.freeze({
102
+ name,
103
+ inject: Object.freeze([...inject]),
104
+ apply,
105
+ driver: Object.freeze({ service }),
106
+ })
107
+ }
71
108
 
72
109
  /** 逃生舱:必须同时导出 apply,且不得与其他接口混用。 */
73
110
  export const rawPlugin = (apply) => defineInterface(KINDS.raw, { apply })
@@ -106,7 +143,9 @@ function parseCapability(entry, field) {
106
143
  * }} options
107
144
  */
108
145
  export function definePlugin(options = {}) {
109
- const { name, apiVersion = ABI_MAJOR, description, requires = [], provides = [], implements: impls } = options
146
+ const {
147
+ name, apiVersion = ABI_MAJOR, description, requires = [], provides = [], inject = [], implements: impls,
148
+ } = options
110
149
 
111
150
  if (!PLUGIN_NAME_RE.test(String(name || ''))) {
112
151
  throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, `插件名必须是 kebab-case:${name}`, { name })
@@ -121,6 +160,14 @@ export function definePlugin(options = {}) {
121
160
  if (description !== undefined && typeof description !== 'string') {
122
161
  throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, 'description 必须是字符串', { name })
123
162
  }
163
+ /* 附加 Cordis inject 只给 raw@1 逃生舱使用:它需要保留原插件的宿主服务依赖。
164
+ * 普通描述符不接受这个字段,避免把宿主服务名泄漏进应用 ABI。 */
165
+ if (!Array.isArray(inject) || inject.some((item) => typeof item !== 'string' || !item.trim())) {
166
+ throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, 'inject 必须是非空字符串数组', { name })
167
+ }
168
+ if (inject.length && !impls?.some((impl) => impl?.kind === 'raw@1')) {
169
+ throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, '只有 raw@1 插件可以声明额外 inject', { name })
170
+ }
124
171
 
125
172
  for (const impl of impls) {
126
173
  if (!impl || typeof impl !== 'object' || typeof impl.kind !== 'string') {
@@ -144,9 +191,12 @@ export function definePlugin(options = {}) {
144
191
  const requiresEntries = requires.map((entry) => parseCapability(entry, 'requires'))
145
192
  const providesEntries = provides.map((entry) => parseCapability(entry, 'provides'))
146
193
  for (const entry of providesEntries) {
147
- if (/^[\^~<>=]/.test(entry.range)) {
194
+ /* 白名单而非黑名单:provides 必须是完整 x.y.z(可带 prerelease)。旧实现只拒
195
+ * ^~<>= 前缀,'1.x' / '1.*' / 裸 '1' 漏网被当成版本发布,消费方 parseVersion
196
+ * 解析不了 → satisfies 恒 false,能力永远「不可用」。 */
197
+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(entry.range)) {
148
198
  throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE,
149
- `provides 必须写精确版本,不能写范围:${entry.raw}`, { entry: entry.raw })
199
+ `provides 必须写精确版本(x.y.z),不能写范围:${entry.raw}`, { entry: entry.raw })
150
200
  }
151
201
  }
152
202
 
@@ -157,6 +207,7 @@ export function definePlugin(options = {}) {
157
207
  description,
158
208
  requires: Object.freeze(requiresEntries),
159
209
  provides: Object.freeze(providesEntries),
210
+ inject: Object.freeze([...inject]),
160
211
  implements: Object.freeze([...impls]),
161
212
  })
162
213
  }
@@ -182,17 +233,26 @@ export function createPlugin(definition, baseUrl) {
182
233
  const os = ctx?.os
183
234
  if (!os || typeof os.mount !== 'function') {
184
235
  throw new AbiError(ERROR_CODES.E_KERNEL_MISSING,
185
- 'ctx.os 不可用:请先安装并启用 @capyclaw/foundation', { plugin: spec.name })
236
+ 'ctx.os 不可用:请先安装并启用 @capyclaw/core(公共基建唯一声明者),它会连同 @capyclaw/foundation 一起挂上 os 内核', { plugin: spec.name })
186
237
  }
187
238
  if (!baseUrl) {
188
239
  throw new AbiError(ERROR_CODES.E_BASE_URL_MISSING,
189
240
  'createPlugin 需要第二参数 baseUrl(传 import.meta.url)', { plugin: spec.name })
190
241
  }
191
- const handle = os.mount(spec, config, { baseUrl })
192
- return () => handle.dispose()
242
+ const handle = os.mount(spec, config, { baseUrl, ctx })
243
+ const dispose = () => handle.dispose()
244
+ // Cordis 只认 ctx.effect 登记的 disposer,apply 的返回值并不可靠:
245
+ // 不显式登记的话,关掉插件再启用时旧记录还占着 name,会撞 E_DUP_PLUGIN。
246
+ if (typeof ctx?.effect === 'function') ctx.effect(() => () => { void dispose() })
247
+ return dispose
193
248
  }
194
249
 
195
- return Object.freeze({ name: spec.name, inject: ['os'], apply, spec })
250
+ return Object.freeze({
251
+ name: spec.name,
252
+ inject: Object.freeze(['os', ...spec.inject.filter((service) => service !== 'os')]),
253
+ apply,
254
+ spec,
255
+ })
196
256
  }
197
257
 
198
258
  export { toAbiError }
package/abi/version.mjs CHANGED
@@ -2,25 +2,57 @@
2
2
  * 版本与范围:能力声明用 `^1` / `^1.2.0` / `>=1.2` / `1.x` / 精确版本。
3
3
  *
4
4
  * 只实现这份 ABI 需要的语义,不引入 semver 依赖:
5
- * - `^1.2.3` → >=1.2.3 且同主版本;`^0.2.3` → >=0.2.3 且同次版本(0.x 约定)
5
+ * - `^1.2.3` → >=1.2.3 且同主版本;`^0.2.3` → >=0.2.3 且同次版本;
6
+ * `^0.0.3` → >=0.0.3 且同补丁(0.0.x 约定,semver 标准)
6
7
  * - `~1.2.3` → >=1.2.3 且同次版本
7
8
  * - `1.x` / `1.*` → 同主版本
8
9
  * - `>=` `>` `<=` `<` `=` 前缀
9
10
  * - 裸版本 → 精确匹配(比较时忽略末位 0)
11
+ * - prerelease 保留并参与比较:1.0.0-beta < 1.0.0;带 prerelease 的版本只满足
12
+ * 同 [major,minor,patch] 且同样带 prerelease 的范围(semver 标准,避免预发布
13
+ * 版本被当成正式版本放行)。
10
14
  */
11
15
 
12
16
  export function parseVersion(text) {
13
17
  if (typeof text !== 'string') return null
14
- const match = /^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-[0-9A-Za-z.-]+)?$/.exec(text.trim())
18
+ const match = /^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?$/.exec(text.trim())
15
19
  if (!match) return null
16
- return [Number(match[1]), Number(match[2] || 0), Number(match[3] || 0)]
20
+ const parts = [Number(match[1]), Number(match[2] || 0), Number(match[3] || 0)]
21
+ parts.prerelease = match[4] || null
22
+ return parts
23
+ }
24
+
25
+ function comparePrerelease(a, b) {
26
+ /* 无 prerelease > 有 prerelease(1.0.0 > 1.0.0-beta)。 */
27
+ if (!a && !b) return 0
28
+ if (!a) return 1
29
+ if (!b) return -1
30
+ const left = a.split('.')
31
+ const right = b.split('.')
32
+ for (let i = 0; i < Math.max(left.length, right.length); i++) {
33
+ const x = left[i]
34
+ const y = right[i]
35
+ if (x === undefined) return -1
36
+ if (y === undefined) return 1
37
+ const xn = /^\d+$/.test(x)
38
+ const yn = /^\d+$/.test(y)
39
+ if (xn && yn) {
40
+ const d = Number(x) - Number(y)
41
+ if (d !== 0) return d < 0 ? -1 : 1
42
+ } else if (xn !== yn) {
43
+ return xn ? -1 : 1 // 数字标识符 < 字母数字标识符
44
+ } else if (x !== y) {
45
+ return x < y ? -1 : 1
46
+ }
47
+ }
48
+ return 0
17
49
  }
18
50
 
19
51
  function compareParts(a, b) {
20
52
  for (let i = 0; i < 3; i++) {
21
53
  if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1
22
54
  }
23
- return 0
55
+ return comparePrerelease(a.prerelease || null, b.prerelease || null)
24
56
  }
25
57
 
26
58
  export function compareVersions(a, b) {
@@ -44,12 +76,23 @@ export function satisfies(version, range) {
44
76
  if (raw.startsWith('^')) {
45
77
  const base = parseVersion(raw.slice(1))
46
78
  if (!base) return false
79
+ /* prerelease 只满足同 [major,minor,patch] 且带 prerelease 的范围(semver 标准),
80
+ * 避免 1.1.0-beta 被 ^1.0.0 当正式版本放行。 */
81
+ if (current.prerelease && (!base.prerelease
82
+ || current[0] !== base[0] || current[1] !== base[1] || current[2] !== base[2])) return false
47
83
  if (compareParts(current, base) < 0) return false
48
- return base[0] === 0 ? current[0] === 0 && current[1] === base[1] : current[0] === base[0]
84
+ if (base[0] === 0) {
85
+ /* 0.0.x caret 收紧到补丁位:^0.0.3 只容 0.0.3,不容 0.0.9。 */
86
+ if (base[1] === 0) return current[0] === 0 && current[1] === 0 && current[2] === base[2]
87
+ return current[0] === 0 && current[1] === base[1]
88
+ }
89
+ return current[0] === base[0]
49
90
  }
50
91
  if (raw.startsWith('~')) {
51
92
  const base = parseVersion(raw.slice(1))
52
93
  if (!base) return false
94
+ if (current.prerelease && (!base.prerelease
95
+ || current[0] !== base[0] || current[1] !== base[1] || current[2] !== base[2])) return false
53
96
  return compareParts(current, base) >= 0 && current[0] === base[0] && current[1] === base[1]
54
97
  }
55
98
  if (raw.startsWith('>=')) {
@@ -80,3 +123,18 @@ export function satisfies(version, range) {
80
123
  const exact = parseVersion(raw)
81
124
  return Boolean(exact) && compareParts(current, exact) === 0
82
125
  }
126
+
127
+ /**
128
+ * 范围是否「语义合法」(区别于「合法但不满足」)。供加载器把非法范围单独报
129
+ * E_SCHEMA,而不是误归因成「能力不可用」误导排障。空范围视为「任意」,合法。
130
+ */
131
+ export function isValidRange(range) {
132
+ const raw = String(range ?? '').trim()
133
+ if (!raw || raw === '*' || raw === 'x') return true
134
+ if (/^[\^~]/.test(raw)) return Boolean(parseVersion(raw.slice(1)))
135
+ if (/^(>=|<=)/.test(raw)) return Boolean(parseVersion(raw.slice(2)))
136
+ if (/^[><]/.test(raw)) return Boolean(parseVersion(raw.slice(1)))
137
+ if (raw.startsWith('=')) return isValidRange(raw.slice(1))
138
+ if (/^(\d+)(?:\.(\d+))?\.[x*]$/.test(raw)) return true
139
+ return Boolean(parseVersion(raw))
140
+ }
package/kit/index.mjs CHANGED
@@ -1,7 +1,6 @@
1
1
  /**
2
- * libc 入口:纯函数基建,零副作用。
3
- *
4
- * 迁移期直接复用 @capyclaw/plugin-kit;后续把这些实现内联进 foundation 时,
5
- * 这个入口的导出面保持不变,应用侧一行都不用改。
2
+ * Legacy plugin-kit compatibility exports. Includes Node resource helpers and
3
+ * dsh runtime-context conventions; importing this entry is not a portability proof.
4
+ * Preserve existing exports; new applications should prefer the descriptor ABI.
6
5
  */
7
6
  export * from '@capyclaw/plugin-kit'
@@ -0,0 +1,98 @@
1
+ /**
2
+ * client-panel@1 适配器:页面开机全局变量 + 可选静态面板。
3
+ *
4
+ * - bootGlobals 必须是同步函数;异步准备放在 prepare(start 阶段)里,
5
+ * 结果通过 state 传给 bootGlobals,避免事件发射器无法 await 的竞态。
6
+ * - 静态 root 与 ui-panel 共用 editorHost + serviceHost 共享前缀。
7
+ */
8
+ import { fileURLToPath } from 'node:url'
9
+
10
+ import { AbiError, ERROR_CODES } from '../../abi/errors.mjs'
11
+
12
+ export const kind = 'client-panel@1'
13
+
14
+ export function createClientPanelAdapter({ host, net, log }) {
15
+ return {
16
+ kind,
17
+ compile(impl, { spec, config, context }) {
18
+ const ctx = context?.ctx
19
+ if (typeof ctx?.on !== 'function') {
20
+ throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
21
+ 'client-panel@1 需要支持 ctx.on 的 Cordis 宿主', { plugin: spec.name })
22
+ }
23
+
24
+ let unmount
25
+ let editor
26
+ let app
27
+ if (impl.root) {
28
+ const serviceHost = host.http()
29
+ const editorHost = host.ui()
30
+ if (!serviceHost?.createApp || !editorHost?.createEditorHost) {
31
+ throw new AbiError(ERROR_CODES.E_CAP_MISSING,
32
+ 'ctx.editorHost / ctx.serviceHost 不可用:无法挂静态面板',
33
+ { plugin: spec.name, capability: 'os.ui' })
34
+ }
35
+ if (!context?.baseUrl) {
36
+ throw new AbiError(ERROR_CODES.E_BASE_URL_MISSING,
37
+ `插件 ${spec.name} 缺少 baseUrl,无法解析 ${impl.root}`, { plugin: spec.name })
38
+ }
39
+ const dir = fileURLToPath(new URL(impl.root, context.baseUrl))
40
+ editor = editorHost.createEditorHost({
41
+ id: spec.name,
42
+ dir,
43
+ basePath: '',
44
+ index: impl.index,
45
+ })
46
+ app = serviceHost.createApp({ id: spec.name, title: spec.name })
47
+ try {
48
+ for (const route of editor.routes()) app.use(route)
49
+ unmount = net.mount(impl.mount, app)
50
+ } catch (error) {
51
+ /* 装配/挂载失败回收已建 app(editor 静态宿主无 close,GC 回收)。 */
52
+ try { app.close?.() } catch { /* 尽力回收 */ }
53
+ throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
54
+ `挂载客户端面板 ${impl.mount} 失败:${error.message}`,
55
+ { plugin: spec.name, prefix: impl.mount, cause: error })
56
+ }
57
+ }
58
+
59
+ const panelState = { ready: typeof impl.prepare !== 'function', value: undefined }
60
+ const off = ctx.on('webserver/index-inject', (table) => {
61
+ if (!impl.bootGlobals || !panelState.ready || !Array.isArray(table)) return
62
+ let globals
63
+ try {
64
+ globals = impl.bootGlobals({
65
+ spec, config, log, os: context.os, state: panelState.value,
66
+ })
67
+ } catch (error) {
68
+ log?.error?.(`[foundation] ${spec.name} bootGlobals 失败:${error.message}`)
69
+ return
70
+ }
71
+ if (!globals || typeof globals !== 'object') return
72
+ for (const [name, value] of Object.entries(globals)) {
73
+ if (value !== undefined) table.push({ kind: 'global', name, value })
74
+ }
75
+ })
76
+
77
+ return {
78
+ editor,
79
+ async start() {
80
+ if (typeof impl.prepare === 'function') {
81
+ panelState.value = await impl.prepare({
82
+ spec, config, log, os: context.os,
83
+ })
84
+ panelState.ready = true
85
+ }
86
+ if (unmount) await net.ready()
87
+ },
88
+ dispose() {
89
+ const errors = []
90
+ try { if (typeof off === 'function') off() } catch (error) { errors.push(error) }
91
+ try { if (typeof unmount === 'function') unmount() } catch (error) { errors.push(error) }
92
+ try { app?.close?.() } catch (error) { errors.push(error) }
93
+ if (errors.length) throw errors[0]
94
+ },
95
+ }
96
+ },
97
+ }
98
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * host-event@1 适配器:把宿主事件订阅交给插件自己的 Cordis ctx。
3
+ *
4
+ * 应用插件只声明事件名与 handler,不接触 ctx;注销由 loader 统一回收。
5
+ */
6
+ import { AbiError, ERROR_CODES } from '../../abi/errors.mjs'
7
+
8
+ export const kind = 'host-event@1'
9
+
10
+ export function createHostEventAdapter({ log }) {
11
+ return {
12
+ kind,
13
+ compile(impl, { spec, context }) {
14
+ const ctx = context?.ctx
15
+ if (!ctx || typeof ctx.on !== 'function') {
16
+ throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
17
+ 'host-event@1 需要支持 ctx.on 的 Cordis 宿主', { plugin: spec.name, event: impl.event })
18
+ }
19
+
20
+ let dispose
21
+ try {
22
+ const off = ctx.on(impl.event, impl.handler)
23
+ dispose = typeof off === 'function'
24
+ ? off
25
+ : () => { if (typeof ctx.off === 'function') ctx.off(impl.event, impl.handler) }
26
+ } catch (error) {
27
+ throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
28
+ `订阅宿主事件 ${impl.event} 失败:${error.message}`, { plugin: spec.name, event: impl.event, cause: error })
29
+ }
30
+
31
+ log?.debug?.(`[foundation] ${spec.name} 订阅宿主事件 ${impl.event}`)
32
+ return { dispose }
33
+ },
34
+ }
35
+ }
@@ -3,15 +3,22 @@
3
3
  *
4
4
  * 前缀冲突由 service-host 的 sharedHost.mount 检测(重复前缀直接抛错),
5
5
  * 应用侧不接触 server、不选端口。
6
+ *
7
+ * 增量(STANDARD v2 V2-1/V2-4 配套,纯向后兼容):
8
+ * - routes 第二参新增 service(name):跨隔离探测公共服务(getService),
9
+ * 让路由插件拿到 ctx.workStore 这类驱动提供的服务,而不必私开句柄;
10
+ * - routes() 返回函数时登记为 disposer:dispose 先 unmount 再调用,
11
+ * 路由层起的定时器/句柄有官方回收点。
6
12
  */
7
13
  import { AbiError, ERROR_CODES } from '../../abi/errors.mjs'
14
+ import { getService } from '../ctx-service.mjs'
8
15
 
9
16
  export const kind = 'http-router@1'
10
17
 
11
18
  export function createHttpRouterAdapter({ host, net, log }) {
12
19
  return {
13
20
  kind,
14
- compile(impl, { spec, config }) {
21
+ compile(impl, { spec, config, context }) {
15
22
  const serviceHost = host.http()
16
23
  if (!serviceHost?.createApp) {
17
24
  throw new AbiError(ERROR_CODES.E_CAP_MISSING,
@@ -19,9 +26,15 @@ export function createHttpRouterAdapter({ host, net, log }) {
19
26
  }
20
27
 
21
28
  const app = serviceHost.createApp({ id: spec.name, title: spec.name })
29
+ const service = (name) => getService(context?.ctx, name)
30
+ let cleanup
22
31
  try {
23
- impl.routes(app, { spec, config, log })
32
+ const returned = impl.routes(app, { spec, config, log, os: context?.os, service })
33
+ if (typeof returned === 'function') cleanup = returned
24
34
  } catch (error) {
35
+ /* routes 抛错时 app 已创建:此 entry 尚未入 loader entries,编译回滚够不到,
36
+ * 必须就地回收,否则子 app/句柄泄漏。 */
37
+ try { app.close?.() } catch { /* 尽力回收 */ }
25
38
  throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
26
39
  `路由注册失败:${error.message}`, { plugin: spec.name, cause: error })
27
40
  }
@@ -30,6 +43,9 @@ export function createHttpRouterAdapter({ host, net, log }) {
30
43
  try {
31
44
  unmount = net.mount(impl.mount, app)
32
45
  } catch (error) {
46
+ /* mount 失败同样回收已建的 app 与 routes 返回的 cleanup。 */
47
+ try { if (cleanup) cleanup() } catch { /* 尽力回收 */ }
48
+ try { app.close?.() } catch { /* 尽力回收 */ }
33
49
  throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
34
50
  `挂载前缀 ${impl.mount} 失败:${error.message}`, { plugin: spec.name, prefix: impl.mount, cause: error })
35
51
  }
@@ -37,8 +53,15 @@ export function createHttpRouterAdapter({ host, net, log }) {
37
53
  log?.debug?.(`[foundation] ${spec.name} 路由挂到 ${impl.mount}`)
38
54
  return {
39
55
  app,
56
+ start: () => net.ready(),
40
57
  dispose: () => {
41
- if (typeof unmount === 'function') unmount()
58
+ /* unmount 与 cleanup 都要执行;cleanup 错误不再吞掉(旧实现 log.warn 后
59
+ * 假装成功,loader 会释放 claims 但定时器/句柄实际泄漏)。错误上抛进
60
+ * loader cleanupErrors,保留「失败保留所有权」语义。 */
61
+ const errors = []
62
+ try { if (typeof unmount === 'function') unmount() } catch (error) { errors.push(error) }
63
+ if (cleanup) { try { cleanup() } catch (error) { errors.push(error) } }
64
+ if (errors.length) throw errors[0]
42
65
  },
43
66
  }
44
67
  },
@@ -31,7 +31,7 @@ export function createHookRegistry() {
31
31
  export function createLifecycleAdapter({ hooks, log }) {
32
32
  return {
33
33
  kind,
34
- compile(impl, { spec }) {
34
+ compile(impl, { spec, config, context }) {
35
35
  const removers = []
36
36
  if (typeof impl.onInstall === 'function') {
37
37
  removers.push(hooks.register('install', { plugin: spec.name, run: impl.onInstall }))
@@ -39,22 +39,15 @@ export function createLifecycleAdapter({ hooks, log }) {
39
39
  if (typeof impl.onUpgrade === 'function') {
40
40
  removers.push(hooks.register('upgrade', { plugin: spec.name, run: impl.onUpgrade }))
41
41
  }
42
+ let entered = false
42
43
  return {
43
- async start() {
44
- if (typeof impl.onStart === 'function') await impl.onStart({ plugin: spec.name })
44
+ async start({ signal } = {}) {
45
+ entered = true
46
+ if (typeof impl.onStart === 'function') await impl.onStart({ plugin: spec.name, config, log, os: context?.os, signal })
45
47
  },
46
48
  dispose() {
47
- if (typeof impl.onStop === 'function') {
48
- try {
49
- const result = impl.onStop({ plugin: spec.name })
50
- if (result && typeof result.then === 'function') {
51
- result.catch((error) => log?.error?.(`[foundation] ${spec.name} onStop 失败: ${error.message}`))
52
- }
53
- } catch (error) {
54
- log?.error?.(`[foundation] ${spec.name} onStop 失败: ${error.message}`)
55
- }
56
- }
57
49
  for (const remove of removers) remove()
50
+ if (entered && typeof impl.onStop === 'function') return impl.onStop({ plugin: spec.name, config, log, os: context?.os })
58
51
  },
59
52
  }
60
53
  },
@@ -0,0 +1,113 @@
1
+ /**
2
+ * own-server@1 适配器:托管一个 HTTP 面。
3
+ *
4
+ * 宿主提供 `web()`(dsh 即 `ctx.webServer`)时,这个面挂到宿主网页端口的路径前缀
5
+ * (`impl.mount`,默认 `/plugins/<id>`)下,**不再新起端口**;只有拿不到 web() 的
6
+ * 宿主才退回 service-host 的独立 loopback origin(凭据中转等必须独立 origin 的场景)。
7
+ *
8
+ * 应用只提供 handler(req,res,api) 与可选 start/stop;监听、端口、锁、健康检查、
9
+ * 关闭全部由宿主 service-host 负责。
10
+ */
11
+ import { AbiError, ERROR_CODES } from '../../abi/errors.mjs'
12
+
13
+ export const kind = 'own-server@1'
14
+
15
+ function resolvePort(impl, spec, config, fallback) {
16
+ const value = typeof impl.port === 'function' ? impl.port({ spec, config }) : impl.port
17
+ if (value === 'auto') return 0
18
+ if (Number.isInteger(value) && value >= 0 && value <= 65535) return value
19
+ throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE,
20
+ `own-server port 必须是 0-65535 整数或 "auto",收到 ${String(value)}`,
21
+ { plugin: spec.name, id: impl.id, port: value, fallback })
22
+ }
23
+
24
+ export function createOwnServerAdapter({ host, log }) {
25
+ return {
26
+ kind,
27
+ compile(impl, { spec, config, context }) {
28
+ const serviceHost = host.http()
29
+ if (!serviceHost?.createApp) {
30
+ throw new AbiError(ERROR_CODES.E_CAP_MISSING,
31
+ 'ctx.serviceHost 不可用:无法托管自有 origin',
32
+ { plugin: spec.name, capability: 'os.net' })
33
+ }
34
+
35
+ const app = serviceHost.createApp({ id: impl.id, title: spec.name })
36
+ const web = typeof host.web === 'function' ? host.web() : null
37
+ const canEmbed = !!(web && typeof web.register === 'function')
38
+ const mount = typeof impl.mount === 'string' && impl.mount
39
+ ? impl.mount
40
+ : `/plugins/${impl.id}`
41
+ /* 错误响应必须防 write-after-end:handler 已 res.end() 后再失败(流式响应后
42
+ * 异步出错是常见形态)时,再写会抛 ERR_STREAM_WRITE_AFTER_END——在 .catch 回调
43
+ * 里就是未捕获 rejection,可拖垮整个宿主。已结束只记日志;写本身也包 try/catch。 */
44
+ const failResponse = (res, error) => {
45
+ log?.error?.(`[foundation] ${spec.name} own-server handler 失败:${error?.message || error}`)
46
+ try {
47
+ if (res.writableEnded || res.destroyed) return
48
+ if (!res.headersSent) res.writeHead(500, { 'content-type': 'application/json' })
49
+ res.end(JSON.stringify({ error: 'handler failed' }))
50
+ } catch (writeError) {
51
+ log?.error?.(`[foundation] ${spec.name} own-server 错误响应写入失败:${writeError?.message || writeError}`)
52
+ }
53
+ }
54
+ app.use((req, res, url) => {
55
+ try {
56
+ const result = impl.handler(req, res, {
57
+ spec, config, log, os: context?.os, url, mount, embedded: canEmbed,
58
+ })
59
+ if (result && typeof result.then === 'function') {
60
+ result.catch((error) => failResponse(res, error))
61
+ }
62
+ } catch (error) {
63
+ failResponse(res, error)
64
+ }
65
+ return true
66
+ })
67
+
68
+ let info
69
+ let started = false
70
+ let stopped = false
71
+ return {
72
+ app,
73
+ /** true = 挂在宿主网页端口的前缀下,没有新起端口。 */
74
+ embedded: canEmbed,
75
+ mount,
76
+ async start() {
77
+ started = true
78
+ info = await app.listen(canEmbed
79
+ ? { webServer: web, basePath: mount }
80
+ : { port: resolvePort(impl, spec, config), host: impl.host })
81
+ if (typeof impl.start === 'function') {
82
+ await impl.start({ app, info, spec, config, log, os: context?.os, embedded: canEmbed, mount })
83
+ }
84
+ log?.info?.(`[foundation] ${spec.name} own-server ${impl.id} ${canEmbed ? '挂载' : '监听'} ${info.url}`)
85
+ },
86
+ async dispose() {
87
+ if (stopped) return
88
+ stopped = true
89
+ /* 资源闭合必须在 finally:impl.stop 抛错不能跳过 app.close,否则端口/
90
+ * 监听器永久泄漏且 stopped=true 使重试 no-op(HMR 重挂 EADDRINUSE)。
91
+ * 与 service-provider 的 try{stop}finally{withdraw} 同构。错误仍上抛,
92
+ * 让 loader 记 cleanupErrors(保留所有权语义),但资源已经释放。 */
93
+ const errors = []
94
+ try {
95
+ if (typeof impl.stop === 'function') {
96
+ await impl.stop({ app, info, spec, config, log, os: context?.os, embedded: canEmbed, mount })
97
+ }
98
+ } catch (error) {
99
+ errors.push(error)
100
+ } finally {
101
+ if (started) {
102
+ try { await app.close() } catch (error) { errors.push(error) }
103
+ }
104
+ }
105
+ if (errors.length > 1) {
106
+ log?.error?.(`[foundation] ${spec.name} own-server dispose 多个错误:${errors.map((e) => e?.message || e).join(';')}`)
107
+ }
108
+ if (errors.length) throw errors[0]
109
+ },
110
+ }
111
+ },
112
+ }
113
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * raw@1 适配器:逃生舱。
3
+ *
4
+ * 描述符只提供 apply;适配器把插件自己的 Cordis ctx 交给它,并统一处理
5
+ * 同步/异步返回值与 dispose。raw 插件必须登记在 meta/foundation.allowlist.json
6
+ * 的 raw 段,准入闸会把它与普通应用插件分开统计。
7
+ */
8
+ import { AbiError, ERROR_CODES } from '../../abi/errors.mjs'
9
+
10
+ export const kind = 'raw@1'
11
+
12
+ const thenable = (value) => value && typeof value.then === 'function'
13
+
14
+ function normalize(value) {
15
+ if (typeof value === 'function') return { dispose: value }
16
+ if (value && typeof value === 'object') {
17
+ const instance = {}
18
+ if (typeof value.start === 'function') instance.start = value.start.bind(value)
19
+ if (typeof value.dispose === 'function') instance.dispose = value.dispose.bind(value)
20
+ return instance
21
+ }
22
+ return {}
23
+ }
24
+
25
+ export function createRawAdapter({ log }) {
26
+ return {
27
+ kind,
28
+ compile(impl, { spec, config, context }) {
29
+ const ctx = context?.ctx
30
+ if (!ctx) {
31
+ throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
32
+ 'raw@1 需要 Cordis ctx:请通过 createPlugin 挂载', { plugin: spec.name })
33
+ }
34
+
35
+ let result
36
+ try {
37
+ result = impl.apply({
38
+ ctx, spec, config, log, baseUrl: context.baseUrl, os: context.os,
39
+ })
40
+ } catch (error) {
41
+ throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
42
+ `raw apply 失败:${error.message}`, { plugin: spec.name, cause: error })
43
+ }
44
+
45
+ if (thenable(result)) {
46
+ let instance = {}
47
+ /* apply 结算只做归一化,绝不在此 eagerly 跑 instance.start()——旧实现
48
+ * 在 compile 返回的 promise resolve 时就启动,绕过 loader 的 start 阶段与
49
+ * stopRequested:loader 正在回滚/已请求卸载时 raw 仍会起进程/监听。
50
+ * start 交给 loader 在 start 阶段显式触发(此时才尊重 stopRequested)。 */
51
+ const ready = Promise.resolve(result).then((value) => { instance = normalize(value) })
52
+ return {
53
+ start: async ({ signal } = {}) => {
54
+ await ready
55
+ /* 转发 loader 的卸载 signal,让 raw 实例的 start 也能感知取消。 */
56
+ return instance.start ? instance.start({ signal }) : undefined
57
+ },
58
+ dispose: async () => {
59
+ try { await ready } catch { /* apply 失败由 loader 记录 */ }
60
+ if (typeof instance.dispose === 'function') return instance.dispose()
61
+ },
62
+ }
63
+ }
64
+
65
+ log?.debug?.(`[foundation] ${spec.name} 使用 raw@1 逃生舱`)
66
+ return normalize(result)
67
+ },
68
+ }
69
+ }