@capyclaw/publisher 0.1.0 → 0.1.4
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/README.md +77 -2
- package/client/client.js +717 -0
- package/cordis.patch.yml +4 -15
- package/icon.svg +6 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +26 -14
- package/plugin.mjs +113 -0
- package/server/archive.mjs +289 -0
- package/server/drop.mjs +504 -0
- package/server/impl.mjs +269 -87
- package/server/routes.mjs +339 -0
- package/server/tools.mjs +1 -1
- package/lib/host.mjs +0 -27
- package/server/relay.mjs +0 -70
package/cordis.patch.yml
CHANGED
|
@@ -1,24 +1,13 @@
|
|
|
1
1
|
# @capyclaw/publisher bundle patch
|
|
2
2
|
# npm 发布执行器:把 capyclaw 插件工程的发布流水线搬进 dsh。
|
|
3
3
|
#
|
|
4
|
-
#
|
|
5
|
-
#
|
|
6
|
-
#
|
|
7
|
-
# strictPort 端口占用即失败 DSH_PUBLISHER_STRICT false(默认复用已健康实例)
|
|
4
|
+
# foundation ABI 迁移后不再需要 loopback /mcp 行:publisher_* 工具通过
|
|
5
|
+
# tool-provider 注册到 dsh 原生工具面。tool-host 是 os.tools 的实现,
|
|
6
|
+
# 因此这里把它和 publisher 一起插入;与 suite 中的同名行按 id 合并。
|
|
8
7
|
#
|
|
9
8
|
# 工作区路径(要发布的仓库 checkout)优先级:工具参数 root → DSH_PUBLISHER_ROOT。
|
|
10
9
|
# 发布凭据沿用宿主环境:npm whoami 已登录或 NODE_AUTH_TOKEN。
|
|
11
10
|
|
|
12
11
|
- insert:
|
|
13
|
-
- id: publisher
|
|
12
|
+
- id: publisher
|
|
14
13
|
name: "@capyclaw/publisher"
|
|
15
|
-
config:
|
|
16
|
-
port: 39700
|
|
17
|
-
- id: mcp-capyclaw-publisher
|
|
18
|
-
name: '@deepseek-ai/dsh-mcp-client'
|
|
19
|
-
config:
|
|
20
|
-
serverName: capyclaw-publisher
|
|
21
|
-
transport: streamable-http
|
|
22
|
-
url: 'http://127.0.0.1:39700/mcp'
|
|
23
|
-
failOnStartupError: false
|
|
24
|
-
toolCallTimeoutMs: 600000
|
package/icon.svg
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="npm publisher">
|
|
2
|
+
<rect width="64" height="64" rx="14" fill="#4c6ef5"/>
|
|
3
|
+
<path d="M32 16v20" stroke="#fff" stroke-width="4.2" stroke-linecap="round"/>
|
|
4
|
+
<path d="M23 25l9-9 9 9" stroke="#fff" stroke-width="4.2" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
|
|
5
|
+
<path d="M18 38v6a4 4 0 0 0 4 4h20a4 4 0 0 0 4-4v-6" stroke="#fff" stroke-width="4.2" stroke-linecap="round" fill="none" opacity="0.85"/>
|
|
6
|
+
</svg>
|
package/locale/en.json
ADDED
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@capyclaw/publisher",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"description": "npm
|
|
3
|
+
"version": "0.1.4",
|
|
4
|
+
"description": "npm 发布器:插件页里把打包好的插件包拖进来就能发布或更新到 npm,发布后可就地更新本机安装;同时保留 publisher_* 原生工具做批量预演与真发布",
|
|
5
5
|
"type": "module",
|
|
6
|
-
"main": "./
|
|
6
|
+
"main": "./plugin.mjs",
|
|
7
7
|
"exports": {
|
|
8
|
-
".": "./
|
|
8
|
+
".": "./plugin.mjs",
|
|
9
|
+
"./client": "./client/client.js",
|
|
10
|
+
"./locale/*.json": "./locale/*.json",
|
|
11
|
+
"./icon": "./icon.svg",
|
|
9
12
|
"./package.json": "./package.json"
|
|
10
13
|
},
|
|
11
14
|
"dsh": {
|
|
@@ -13,26 +16,35 @@
|
|
|
13
16
|
"patch": "./cordis.patch.yml"
|
|
14
17
|
},
|
|
15
18
|
"category": "tool",
|
|
16
|
-
"platform": "both"
|
|
19
|
+
"platform": "both",
|
|
20
|
+
"client": {
|
|
21
|
+
"platform": "web",
|
|
22
|
+
"immediately": true
|
|
23
|
+
},
|
|
24
|
+
"requires": {
|
|
25
|
+
"capabilities": {
|
|
26
|
+
"os.tools": "^1.0.0"
|
|
27
|
+
}
|
|
28
|
+
}
|
|
17
29
|
},
|
|
18
30
|
"meta": {
|
|
19
31
|
"title": "npm 发布器",
|
|
20
|
-
"description": "
|
|
32
|
+
"description": "把打好的插件包拖进插件页即可发布或更新到 npm,发布后可就地更新本机安装;也提供 publisher_* 工具做批量预演与真发布。"
|
|
21
33
|
},
|
|
22
34
|
"files": [
|
|
23
|
-
"
|
|
35
|
+
"plugin.mjs",
|
|
24
36
|
"server/",
|
|
37
|
+
"client/",
|
|
38
|
+
"locale/",
|
|
39
|
+
"icon.svg",
|
|
25
40
|
"cordis.patch.yml",
|
|
26
41
|
"README.md"
|
|
27
42
|
],
|
|
28
|
-
"scripts": {
|
|
29
|
-
"test": "node --test \"test/*.test.mjs\""
|
|
30
|
-
},
|
|
31
43
|
"dependencies": {
|
|
32
44
|
"@capyclaw/plugin-kit": "^0.2.0",
|
|
33
45
|
"@capyclaw/plugin-validator": "^1.0.0",
|
|
34
|
-
"@capyclaw/
|
|
35
|
-
"@capyclaw/
|
|
46
|
+
"@capyclaw/tool-host": "^0.3.0",
|
|
47
|
+
"@capyclaw/foundation": "^0.1.1"
|
|
36
48
|
},
|
|
37
49
|
"engines": {
|
|
38
50
|
"node": ">=18",
|
|
@@ -45,7 +57,7 @@
|
|
|
45
57
|
"repository": {
|
|
46
58
|
"type": "git",
|
|
47
59
|
"url": "git+https://github.com/Maple496/capyclaw.git",
|
|
48
|
-
"directory": "
|
|
60
|
+
"directory": "B/official/capyclaw-publisher"
|
|
49
61
|
},
|
|
50
62
|
"keywords": [
|
|
51
63
|
"dsh",
|
|
@@ -56,5 +68,5 @@
|
|
|
56
68
|
"bugs": {
|
|
57
69
|
"url": "https://github.com/Maple496/capyclaw/issues"
|
|
58
70
|
},
|
|
59
|
-
"homepage": "https://github.com/Maple496/capyclaw/tree/main/
|
|
71
|
+
"homepage": "https://github.com/Maple496/capyclaw/tree/main/B/official/capyclaw-publisher#readme"
|
|
60
72
|
}
|
package/plugin.mjs
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @capyclaw/publisher:foundation ABI 入口。
|
|
3
|
+
*
|
|
4
|
+
* 历史上这里只声明「我提供 publisher_* 工具」。现在它还要承接浏览器里拖进来的包,
|
|
5
|
+
* 也就是要在 DSH 自带 webServer 上挂同源路由——foundation 的 http-router@1 只能另起
|
|
6
|
+
* 独立 origin(浏览器侧要跨域 + CORS + 端口发现),所以这一层用 raw@1 逃生舱:
|
|
7
|
+
* 插件仍然经 createPlugin 挂载(保留 kernel 的能力检查/生命周期),apply 里拿到原生
|
|
8
|
+
* ctx,同时注册工具面(走 toolHost.registerWithDsh,行为与 tool-provider@1 一致)
|
|
9
|
+
* 与 /publisher-drop/* 路由。
|
|
10
|
+
*
|
|
11
|
+
* raw@1 必须在 meta/foundation.allowlist.json 的 raw 段登记(准入表会校验)。
|
|
12
|
+
*/
|
|
13
|
+
import fs from 'node:fs'
|
|
14
|
+
import path from 'node:path'
|
|
15
|
+
import { fileURLToPath } from 'node:url'
|
|
16
|
+
|
|
17
|
+
import { createPlugin, rawPlugin } from '@capyclaw/foundation/abi'
|
|
18
|
+
import { registry } from './server/tools.mjs'
|
|
19
|
+
import { createRoutes } from './server/routes.mjs'
|
|
20
|
+
|
|
21
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
|
22
|
+
const PKG = JSON.parse(fs.readFileSync(path.join(HERE, 'package.json'), 'utf8'))
|
|
23
|
+
|
|
24
|
+
const INSTRUCTIONS = [
|
|
25
|
+
'先调用 publisher_capabilities 确认 contractVersion 为 1.x。',
|
|
26
|
+
'先 publisher_whoami 确认 npm 凭据可用,再 publisher_preview 预演。',
|
|
27
|
+
'publisher_execute 需要显式 confirm: true,发布不可撤销。',
|
|
28
|
+
].join('\n')
|
|
29
|
+
|
|
30
|
+
const CAPABILITIES = { publisher: '1.0.0' }
|
|
31
|
+
|
|
32
|
+
export const { name, inject, apply, spec } = createPlugin({
|
|
33
|
+
name: 'publisher',
|
|
34
|
+
requires: ['os.tools@^1'],
|
|
35
|
+
/* 只有 raw@1 允许声明额外 inject;webServer 是宿主自带服务的名字。 */
|
|
36
|
+
inject: ['webServer'],
|
|
37
|
+
implements: [rawPlugin(({ ctx, log }) => {
|
|
38
|
+
const disposers = []
|
|
39
|
+
|
|
40
|
+
/* 工具面:与 tool-provider@1 适配器同一条注册路径,命名空间不重复加前缀
|
|
41
|
+
* (工具名已经自带 publisher_)。 */
|
|
42
|
+
const tools = getService(ctx, 'tools')
|
|
43
|
+
const toolHost = getService(ctx, 'toolHost')
|
|
44
|
+
if (toolHost?.registerWithDsh && tools) {
|
|
45
|
+
const dispose = toolHost.registerWithDsh({ tools }, registry, {
|
|
46
|
+
namespace: '',
|
|
47
|
+
instructions: INSTRUCTIONS,
|
|
48
|
+
capabilities: CAPABILITIES,
|
|
49
|
+
})
|
|
50
|
+
if (typeof dispose === 'function') disposers.push(dispose)
|
|
51
|
+
} else if (tools?.register) {
|
|
52
|
+
log?.debug?.('[publisher] toolHost 不可用,退回逐条注册工具')
|
|
53
|
+
for (const tool of registry.TOOLS) disposers.push(tools.register(toHostTool(tool)))
|
|
54
|
+
} else {
|
|
55
|
+
log?.warn?.('[publisher] tools 服务不可用:publisher_* 工具面未注册')
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/* 拖拽发布:同源 HTTP 面。 */
|
|
59
|
+
const webServer = ctx.webServer
|
|
60
|
+
if (!webServer?.register) {
|
|
61
|
+
throw new Error('publisher 需要 ctx.webServer:拖拽发布依赖 DSH 自带 Web 服务')
|
|
62
|
+
}
|
|
63
|
+
const routes = createRoutes({
|
|
64
|
+
webServer,
|
|
65
|
+
log,
|
|
66
|
+
packageVersion: PKG.version,
|
|
67
|
+
})
|
|
68
|
+
for (const [routeName, handler] of Object.entries(routes.handlers)) {
|
|
69
|
+
disposers.push(webServer.register({ kind: 'exact', path: `/publisher-drop/${routeName}`, handler }))
|
|
70
|
+
}
|
|
71
|
+
disposers.push(routes.dispose)
|
|
72
|
+
log?.debug?.(`[publisher] 已挂载 ${Object.keys(routes.handlers).length} 条拖拽发布路由`)
|
|
73
|
+
|
|
74
|
+
return () => {
|
|
75
|
+
for (const dispose of disposers.reverse()) {
|
|
76
|
+
try {
|
|
77
|
+
if (typeof dispose === 'function') dispose()
|
|
78
|
+
} catch (error) {
|
|
79
|
+
log?.warn?.(`[publisher] 卸载失败:${error && error.message ? error.message : error}`)
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
})],
|
|
84
|
+
}, import.meta.url)
|
|
85
|
+
|
|
86
|
+
/** Cordis 的 ctx 是 Proxy:没在 inject 里声明过的服务要用 ctx.get() 读。 */
|
|
87
|
+
function getService(ctx, name) {
|
|
88
|
+
if (!ctx) return undefined
|
|
89
|
+
if (typeof ctx.get === 'function') {
|
|
90
|
+
try {
|
|
91
|
+
const service = ctx.get(name)
|
|
92
|
+
if (service !== undefined) return service
|
|
93
|
+
} catch { /* 继续尝试属性访问 */ }
|
|
94
|
+
}
|
|
95
|
+
try {
|
|
96
|
+
return ctx[name]
|
|
97
|
+
} catch {
|
|
98
|
+
return undefined
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function toHostTool(tool) {
|
|
103
|
+
return {
|
|
104
|
+
name: tool.name,
|
|
105
|
+
description: tool.description,
|
|
106
|
+
parameters: tool.inputSchema,
|
|
107
|
+
output: {
|
|
108
|
+
schema: { type: 'object', additionalProperties: true },
|
|
109
|
+
render: (args, value) => value?.content ?? [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value) }],
|
|
110
|
+
},
|
|
111
|
+
execute: (args) => registry.TOOL_IMPL[tool.name]?.(args),
|
|
112
|
+
}
|
|
113
|
+
}
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 压缩包处理:把拖进来的 .zip / .tgz / .tar.gz 读成条目表,再落到本机 staging 目录。
|
|
3
|
+
*
|
|
4
|
+
* 纯函数层:不碰 HTTP、不碰 Cordis。拖拽上传的字节只有在这里被解释,
|
|
5
|
+
* 发布引擎(drop.mjs)只看见「一个已经解开的普通目录」。
|
|
6
|
+
*
|
|
7
|
+
* 与 @capyclaw/plugin-drop 的 archive.js 同源(同一套手写 zip/tar 解析),
|
|
8
|
+
* 差别只有两处:storeRoot 换成 publisher 自己的 staging 区;检查包时不再要求
|
|
9
|
+
* dsh.bundle.patch(发布闸会给出更具体的错误),只要求 name + version。
|
|
10
|
+
*/
|
|
11
|
+
import path from 'node:path'
|
|
12
|
+
import os from 'node:os'
|
|
13
|
+
import { mkdir, rename, rm, writeFile } from 'node:fs/promises'
|
|
14
|
+
import { gunzipSync, inflateRawSync } from 'node:zlib'
|
|
15
|
+
|
|
16
|
+
const MAX_DEPTH = 3
|
|
17
|
+
/* 解压上限(与 @capyclaw/plugin-drop 的 archive.js 同源):zip bomb 靠「压缩态很小、
|
|
18
|
+
* 解压态巨大」吃光内存,必须在解压这一步就掐断,而不是等落盘。 */
|
|
19
|
+
const MAX_UNPACKED_BYTES = 128 * 1024 * 1024
|
|
20
|
+
const MAX_ENTRIES = 4096
|
|
21
|
+
|
|
22
|
+
function tooManyEntries() {
|
|
23
|
+
return new Error(`压缩包里的文件太多,超出 ${MAX_ENTRIES} 的上限。`)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function tooLarge() {
|
|
27
|
+
return new Error(`压缩包解压后超过 ${Math.round(MAX_UNPACKED_BYTES / 1024 / 1024)} MB 上限。`)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** 读 .zip / .tgz / .tar.gz(或裸 .tar)为一个扁平条目表。 */
|
|
31
|
+
export function unpack(buffer, filename) {
|
|
32
|
+
if (buffer.length > 2 && buffer[0] === 0x1f && buffer[1] === 0x8b) return untar(gunzipSync(buffer, { maxOutputLength: MAX_UNPACKED_BYTES }))
|
|
33
|
+
if (buffer.length > 4 && buffer[0] === 0x50 && buffer[1] === 0x4b && buffer[2] === 0x03 && buffer[3] === 0x04) {
|
|
34
|
+
return unzip(buffer)
|
|
35
|
+
}
|
|
36
|
+
if (/\.tar$/i.test(filename)) return untar(buffer)
|
|
37
|
+
throw new Error('无法识别的压缩格式,请用 .zip、.tgz 或 .tar.gz。')
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function untar(buffer) {
|
|
41
|
+
const entries = []
|
|
42
|
+
let offset = 0
|
|
43
|
+
let pendingPath = null
|
|
44
|
+
|
|
45
|
+
while (offset + 512 <= buffer.length) {
|
|
46
|
+
const header = buffer.subarray(offset, offset + 512)
|
|
47
|
+
if (header.every((byte) => byte === 0)) break
|
|
48
|
+
if (entries.length >= MAX_ENTRIES) throw tooManyEntries()
|
|
49
|
+
|
|
50
|
+
const name = readCString(header, 0, 100)
|
|
51
|
+
const prefix = readCString(header, 345, 155)
|
|
52
|
+
const size = readOctal(header, 124, 12)
|
|
53
|
+
const type = String.fromCharCode(header[156] || 0x30)
|
|
54
|
+
const dataStart = offset + 512
|
|
55
|
+
const data = buffer.subarray(dataStart, Math.min(dataStart + size, buffer.length))
|
|
56
|
+
offset = dataStart + Math.ceil(size / 512) * 512
|
|
57
|
+
|
|
58
|
+
if (type === 'x') {
|
|
59
|
+
const pax = parsePax(data)
|
|
60
|
+
if (pax.path) pendingPath = pax.path
|
|
61
|
+
continue
|
|
62
|
+
}
|
|
63
|
+
if (type === 'g') continue
|
|
64
|
+
if (type === 'L') {
|
|
65
|
+
pendingPath = readCString(data, 0, data.length)
|
|
66
|
+
continue
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const entryPath = pendingPath || (prefix ? `${prefix}/${name}` : name)
|
|
70
|
+
pendingPath = null
|
|
71
|
+
if (!entryPath) continue
|
|
72
|
+
|
|
73
|
+
if (type === '5' || entryPath.endsWith('/')) {
|
|
74
|
+
entries.push({ path: entryPath, dir: true })
|
|
75
|
+
continue
|
|
76
|
+
}
|
|
77
|
+
if (type === '0' || type === '7') entries.push({ path: entryPath, data: Buffer.from(data) })
|
|
78
|
+
}
|
|
79
|
+
return entries
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function parsePax(data) {
|
|
83
|
+
const result = {}
|
|
84
|
+
let cursor = 0
|
|
85
|
+
while (cursor < data.length) {
|
|
86
|
+
const space = data.indexOf(0x20, cursor)
|
|
87
|
+
if (space < 0) break
|
|
88
|
+
const length = Number.parseInt(data.subarray(cursor, space).toString('utf8'), 10)
|
|
89
|
+
if (!Number.isFinite(length) || length <= 0) break
|
|
90
|
+
const record = data.subarray(space + 1, cursor + length - 1).toString('utf8')
|
|
91
|
+
const equals = record.indexOf('=')
|
|
92
|
+
if (equals > 0) result[record.slice(0, equals)] = record.slice(equals + 1)
|
|
93
|
+
cursor += length
|
|
94
|
+
}
|
|
95
|
+
return result
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function unzip(buffer) {
|
|
99
|
+
const eocd = findEndOfCentralDirectory(buffer)
|
|
100
|
+
if (eocd < 0) throw new Error('ZIP 结构损坏:找不到目录结尾。')
|
|
101
|
+
|
|
102
|
+
const count = buffer.readUInt16LE(eocd + 10)
|
|
103
|
+
const directoryOffset = buffer.readUInt32LE(eocd + 16)
|
|
104
|
+
const entries = []
|
|
105
|
+
let cursor = directoryOffset
|
|
106
|
+
let total = 0
|
|
107
|
+
|
|
108
|
+
for (let index = 0; index < count; index += 1) {
|
|
109
|
+
if (cursor + 46 > buffer.length || buffer.readUInt32LE(cursor) !== 0x02014b50) break
|
|
110
|
+
if (entries.length >= MAX_ENTRIES) throw tooManyEntries()
|
|
111
|
+
const method = buffer.readUInt16LE(cursor + 10)
|
|
112
|
+
const compressedSize = buffer.readUInt32LE(cursor + 20)
|
|
113
|
+
const nameLength = buffer.readUInt16LE(cursor + 28)
|
|
114
|
+
const extraLength = buffer.readUInt16LE(cursor + 30)
|
|
115
|
+
const commentLength = buffer.readUInt16LE(cursor + 32)
|
|
116
|
+
const localOffset = buffer.readUInt32LE(cursor + 42)
|
|
117
|
+
const name = buffer.subarray(cursor + 46, cursor + 46 + nameLength).toString('utf8')
|
|
118
|
+
cursor += 46 + nameLength + extraLength + commentLength
|
|
119
|
+
|
|
120
|
+
if (!name) continue
|
|
121
|
+
if (name.endsWith('/')) {
|
|
122
|
+
entries.push({ path: name, dir: true })
|
|
123
|
+
continue
|
|
124
|
+
}
|
|
125
|
+
if (buffer.readUInt32LE(localOffset) !== 0x04034b50) throw new Error('ZIP 结构损坏:本地文件头无效。')
|
|
126
|
+
const localNameLength = buffer.readUInt16LE(localOffset + 26)
|
|
127
|
+
const localExtraLength = buffer.readUInt16LE(localOffset + 28)
|
|
128
|
+
const dataStart = localOffset + 30 + localNameLength + localExtraLength
|
|
129
|
+
const raw = buffer.subarray(dataStart, Math.min(dataStart + compressedSize, buffer.length))
|
|
130
|
+
|
|
131
|
+
let data
|
|
132
|
+
if (method === 0) {
|
|
133
|
+
if (total + raw.length > MAX_UNPACKED_BYTES) throw tooLarge()
|
|
134
|
+
data = Buffer.from(raw)
|
|
135
|
+
total += raw.length
|
|
136
|
+
} else if (method === 8) {
|
|
137
|
+
/* 剩余配额逐条目递减:炸弹不必是单个大文件,几个「看似无害」的条目加起来
|
|
138
|
+
* 也能超限。配额为 0 时 maxOutputLength 会报 ERR_OUT_OF_RANGE,先拦下给可读错误。 */
|
|
139
|
+
if (total >= MAX_UNPACKED_BYTES) throw tooLarge()
|
|
140
|
+
data = inflateRawSync(raw, { maxOutputLength: MAX_UNPACKED_BYTES - total })
|
|
141
|
+
total += data.length
|
|
142
|
+
} else throw new Error(`不支持的 ZIP 压缩方式(method ${method})。`)
|
|
143
|
+
|
|
144
|
+
entries.push({ path: name, data })
|
|
145
|
+
}
|
|
146
|
+
return entries
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function findEndOfCentralDirectory(buffer) {
|
|
150
|
+
const minimum = Math.max(0, buffer.length - 0xffff - 22)
|
|
151
|
+
for (let cursor = buffer.length - 22; cursor >= minimum; cursor -= 1) {
|
|
152
|
+
if (buffer.readUInt32LE(cursor) === 0x06054b50) return cursor
|
|
153
|
+
}
|
|
154
|
+
return -1
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function readCString(buffer, start, length) {
|
|
158
|
+
const slice = buffer.subarray(start, Math.min(start + length, buffer.length))
|
|
159
|
+
const end = slice.indexOf(0)
|
|
160
|
+
return (end < 0 ? slice : slice.subarray(0, end)).toString('utf8').trim()
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function readOctal(buffer, start, length) {
|
|
164
|
+
const value = Number.parseInt(readCString(buffer, start, length), 8)
|
|
165
|
+
return Number.isFinite(value) && value > 0 ? value : 0
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// ---------------------------------------------------------------------------
|
|
169
|
+
// 包发现与落地
|
|
170
|
+
// ---------------------------------------------------------------------------
|
|
171
|
+
|
|
172
|
+
/** 归一化压缩包内路径;绝对路径、盘符、NUL、`..` 一律丢弃。 */
|
|
173
|
+
export function safeRelative(entryPath) {
|
|
174
|
+
const normalized = entryPath.replace(/\\/g, '/').replace(/^\/+/, '')
|
|
175
|
+
if (!normalized || normalized.includes('\0') || /^[a-zA-Z]:/.test(normalized)) return undefined
|
|
176
|
+
const parts = normalized.split('/').filter((part) => part.length > 0 && part !== '.')
|
|
177
|
+
if (parts.length === 0 || parts.includes('..')) return undefined
|
|
178
|
+
return parts.join('/')
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function indexEntries(entries) {
|
|
182
|
+
const files = new Map()
|
|
183
|
+
for (const entry of entries) {
|
|
184
|
+
const relative = safeRelative(entry.path)
|
|
185
|
+
if (!relative) continue
|
|
186
|
+
files.set(relative, entry)
|
|
187
|
+
}
|
|
188
|
+
return files
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* 找到包根:最浅的、带 name 的 package.json;优先声明了 dsh.bundle 的那一个。
|
|
193
|
+
* (发布闸会检查 dsh.bundle.patch 是否存在,所以这里不做硬性要求。)
|
|
194
|
+
*/
|
|
195
|
+
export function inspectArchive(entries) {
|
|
196
|
+
const files = indexEntries(entries)
|
|
197
|
+
const candidates = []
|
|
198
|
+
|
|
199
|
+
for (const [key, entry] of files) {
|
|
200
|
+
if (entry.dir || !key.endsWith('package.json')) continue
|
|
201
|
+
const parts = key.split('/')
|
|
202
|
+
const depth = parts.length - 1
|
|
203
|
+
if (depth > MAX_DEPTH) continue
|
|
204
|
+
let manifest
|
|
205
|
+
try {
|
|
206
|
+
manifest = JSON.parse(entry.data.toString('utf8'))
|
|
207
|
+
} catch {
|
|
208
|
+
continue
|
|
209
|
+
}
|
|
210
|
+
if (!manifest || typeof manifest !== 'object' || typeof manifest.name !== 'string') continue
|
|
211
|
+
candidates.push({ dir: parts.slice(0, -1).join('/'), depth, manifest })
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
if (candidates.length === 0) {
|
|
215
|
+
throw new Error('压缩包里没有找到带 name 的 package.json,请把包目录本身压缩后再拖进来。')
|
|
216
|
+
}
|
|
217
|
+
candidates.sort((left, right) => left.depth - right.depth)
|
|
218
|
+
const root = candidates.find((candidate) => candidate.manifest.dsh && candidate.manifest.dsh.bundle) || candidates[0]
|
|
219
|
+
const manifest = root.manifest
|
|
220
|
+
if (typeof manifest.version !== 'string' || !manifest.version.trim()) {
|
|
221
|
+
throw new Error(`${manifest.name} 的 package.json 缺少 version,无法比较 npm 上的版本。`)
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
return { dir: root.dir, manifest, name: manifest.name, version: manifest.version }
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** staging 根目录:每次拖拽都解到独立子目录,发布成功后由调用方回收。 */
|
|
228
|
+
export function storeRoot() {
|
|
229
|
+
const base = process.env.LOCALAPPDATA || process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share')
|
|
230
|
+
return path.join(base, 'capyclaw-publisher', 'drop')
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* 新 staging 目录的候选名。时间戳之外再挂随机后缀:两个请求落在同一毫秒时
|
|
235
|
+
* 不会写进同一个目录(否则后到的包会污染前一个包的文件清单)。
|
|
236
|
+
*/
|
|
237
|
+
function stageCandidate() {
|
|
238
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
|
|
239
|
+
const suffix = Math.random().toString(36).slice(2, 8)
|
|
240
|
+
return path.join(storeRoot(), `${stamp}-${suffix}`)
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* 把条目表写到 staging 下的一个新目录,返回包目录的绝对路径。
|
|
245
|
+
* 先全部写进 .tmp- 目录、成功后原子 rename 成正式名:写一半失败不会留下
|
|
246
|
+
* 「看似有效却缺文件」的 staging(那会被预检/发布当成真包);失败时清掉 tmp,
|
|
247
|
+
* 磁盘上不落垃圾。与 plugin-drop 的差别:这里每次上传都要独立目录(发布后回收),
|
|
248
|
+
* 不做内容地址化复用。
|
|
249
|
+
*/
|
|
250
|
+
export async function materialize(entries, packageDir) {
|
|
251
|
+
await mkdir(storeRoot(), { recursive: true })
|
|
252
|
+
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
253
|
+
const base = stageCandidate()
|
|
254
|
+
const tmp = `${base}.tmp-${process.pid}`
|
|
255
|
+
try {
|
|
256
|
+
await mkdir(tmp)
|
|
257
|
+
try {
|
|
258
|
+
for (const entry of entries) {
|
|
259
|
+
const relative = safeRelative(entry.path)
|
|
260
|
+
if (!relative) continue
|
|
261
|
+
const target = path.join(tmp, ...relative.split('/'))
|
|
262
|
+
if (!isInside(tmp, target)) continue
|
|
263
|
+
if (entry.dir) {
|
|
264
|
+
await mkdir(target, { recursive: true })
|
|
265
|
+
continue
|
|
266
|
+
}
|
|
267
|
+
await mkdir(path.dirname(target), { recursive: true })
|
|
268
|
+
await writeFile(target, entry.data)
|
|
269
|
+
}
|
|
270
|
+
if (packageDir) await mkdir(path.join(tmp, ...packageDir.split('/')), { recursive: true })
|
|
271
|
+
await rename(tmp, base)
|
|
272
|
+
} catch (error) {
|
|
273
|
+
await rm(tmp, { recursive: true, force: true }).catch(() => {})
|
|
274
|
+
throw error
|
|
275
|
+
}
|
|
276
|
+
return packageDir ? path.join(base, ...packageDir.split('/')) : base
|
|
277
|
+
} catch (error) {
|
|
278
|
+
/* 撞名(EEXIST):换一个候选名重试;其它错误原样抛出。 */
|
|
279
|
+
if (error?.code === 'EEXIST' && attempt < 4) continue
|
|
280
|
+
throw error
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
throw new Error(`无法在 ${storeRoot()} 下创建临时目录,请检查磁盘权限。`)
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function isInside(parent, target) {
|
|
287
|
+
const relative = path.relative(parent, target)
|
|
288
|
+
return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative)
|
|
289
|
+
}
|