universal-plugin-hub 0.0.0-stage → 1.0.5
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/LICENSE +21 -0
- package/README.md +91 -2
- package/README.zh.md +92 -0
- package/assets/hero.png +0 -0
- package/client/client.js +10504 -0
- package/cordis.patch.yml +4 -0
- package/package.json +69 -4
- package/scripts/postinstall.js +23 -0
- package/src/agents-map.js +515 -0
- package/src/http.js +46 -0
- package/src/icons.js +123 -0
- package/src/index.js +32 -0
- package/src/install.js +2017 -0
- package/src/local.js +251 -0
- package/src/market.js +218 -0
- package/src/parser.js +1038 -0
- package/src/routes.js +559 -0
- package/src/store.js +254 -0
package/src/local.js
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { existsSync, readdirSync, statSync, cpSync, mkdirSync, writeFileSync, mkdtempSync } from 'node:fs'
|
|
2
|
+
import { join, basename, resolve, dirname, relative, isAbsolute } from 'node:path'
|
|
3
|
+
import { fileURLToPath } from 'node:url'
|
|
4
|
+
import { execFile } from 'node:child_process'
|
|
5
|
+
import { promisify } from 'node:util'
|
|
6
|
+
import { sourceCacheDir, readState, writeState, safeRmDir } from './store.js'
|
|
7
|
+
import { safeSegment } from './market.js'
|
|
8
|
+
import { parsePluginRowFromDir, parseMarketplaceFromDisk, listSkills, listAgents, readPluginManifest, invalidateMarketplaceCache } from './parser.js'
|
|
9
|
+
|
|
10
|
+
const execFileAsync = promisify(execFile)
|
|
11
|
+
|
|
12
|
+
const TEMP_ROOT = () => join(sourceCacheDir('local'), '.temp')
|
|
13
|
+
|
|
14
|
+
/** Delete stale .temp artifacts (uploaded zips, inspect extraction dirs) older than 1h. */
|
|
15
|
+
function sweepTemp() {
|
|
16
|
+
const root = TEMP_ROOT()
|
|
17
|
+
try {
|
|
18
|
+
for (const entry of readdirSync(root)) {
|
|
19
|
+
try { if (Date.now() - statSync(join(root, entry)).mtimeMs > 3_600_000) safeRmDir(join(root, entry)) } catch {}
|
|
20
|
+
}
|
|
21
|
+
} catch {}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Native archive extraction (Windows bsdtar also handles ZIP). */
|
|
25
|
+
export async function extractZip(zipPath, destDir) {
|
|
26
|
+
sweepTemp()
|
|
27
|
+
mkdirSync(destDir, { recursive: true })
|
|
28
|
+
const tar = process.platform === 'win32' ? join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'tar.exe') : 'tar'
|
|
29
|
+
await execFileAsync(tar, ['-xf', zipPath, '-C', destDir], { windowsHide: true })
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// ponytail: base64-in-JSON upload (uniform with the all-JSON API, capped at ~22MB decoded);
|
|
33
|
+
// switch to multipart/octet-stream streaming if large archives ever become a real use case.
|
|
34
|
+
/** Persist an uploaded archive or SKILL.md for the path-based import flow. */
|
|
35
|
+
export function saveUploadedZip(dataBase64, filename) {
|
|
36
|
+
if (!/\.(zip|tgz|tar\.gz)$/i.test(filename || '') && !/^skill\.md$/i.test(filename || '')) {
|
|
37
|
+
throw new Error('支持 .zip、.tgz、.tar.gz 压缩包或 SKILL.md 文件')
|
|
38
|
+
}
|
|
39
|
+
const data = Buffer.from(String(dataBase64 || ''), 'base64')
|
|
40
|
+
if (data.length > 22 * 1024 * 1024) throw new Error('上传文件大小上限为 22MB')
|
|
41
|
+
const safe = String(filename || 'plugin.zip').replace(/[^a-zA-Z0-9._-]/g, '_') || 'plugin.zip'
|
|
42
|
+
mkdirSync(TEMP_ROOT(), { recursive: true })
|
|
43
|
+
const uploadDir = mkdtempSync(join(TEMP_ROOT(), 'upload-'))
|
|
44
|
+
const file = join(uploadDir, /^skill\.md$/i.test(filename) ? 'SKILL.md' : safe)
|
|
45
|
+
writeFileSync(file, data)
|
|
46
|
+
return file
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function isPluginDir(dir) {
|
|
50
|
+
if (!dir || !existsSync(dir)) return false
|
|
51
|
+
const rootSkill = existsSync(join(dir, 'SKILL.md')) || existsSync(join(dir, 'skill.md'))
|
|
52
|
+
const hasSkillsDir = existsSync(join(dir, 'skills'))
|
|
53
|
+
const hasManifest = existsSync(join(dir, '.codex-plugin', 'plugin.json')) || existsSync(join(dir, '.claude-plugin', 'plugin.json')) || existsSync(join(dir, 'plugin.json')) || existsSync(join(dir, 'package.json'))
|
|
54
|
+
const hasMcp = existsSync(join(dir, 'mcp.json')) || existsSync(join(dir, '.mcp.json')) || existsSync(join(dir, 'server.json'))
|
|
55
|
+
const hasAgents = existsSync(join(dir, 'agents'))
|
|
56
|
+
const hasCommands = existsSync(join(dir, 'commands'))
|
|
57
|
+
return Boolean(rootSkill || hasSkillsDir || hasManifest || hasMcp || hasAgents || hasCommands)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function resolvePluginDir(rootDir) {
|
|
61
|
+
if (!existsSync(rootDir) || !statSync(rootDir).isDirectory()) return null
|
|
62
|
+
if (existsSync(join(rootDir, '.agents', 'plugins', 'marketplace.json')) || existsSync(join(rootDir, '.claude-plugin', 'marketplace.json')) || existsSync(join(rootDir, 'marketplace.json'))) return rootDir
|
|
63
|
+
if (isPluginDir(rootDir)) return rootDir
|
|
64
|
+
|
|
65
|
+
// Unwrap nested directory wrappers (common in repository archives).
|
|
66
|
+
try {
|
|
67
|
+
const subs = readdirSync(rootDir, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith('.'))
|
|
68
|
+
if (subs.length === 1) {
|
|
69
|
+
return resolvePluginDir(join(rootDir, subs[0].name))
|
|
70
|
+
}
|
|
71
|
+
if (subs.some((e) => isPluginDir(join(rootDir, e.name)))) return rootDir
|
|
72
|
+
} catch {}
|
|
73
|
+
return null
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export async function inspectLocalPlugin(rawPath) {
|
|
77
|
+
let targetPath = String(rawPath || '').trim().replace(/^["']|["']$/g, '')
|
|
78
|
+
if (/^file:/i.test(targetPath)) targetPath = fileURLToPath(targetPath)
|
|
79
|
+
if (!existsSync(targetPath)) {
|
|
80
|
+
return { ok: false, error: '指定的本地路径或文件不存在' }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
let inspectDir = targetPath
|
|
84
|
+
const isZip = /\.(zip|tgz|tar\.gz)$/i.test(targetPath)
|
|
85
|
+
let tempExtractDir = null
|
|
86
|
+
|
|
87
|
+
if (isZip) {
|
|
88
|
+
mkdirSync(TEMP_ROOT(), { recursive: true })
|
|
89
|
+
tempExtractDir = mkdtempSync(join(TEMP_ROOT(), 'inspect-'))
|
|
90
|
+
try {
|
|
91
|
+
await extractZip(targetPath, tempExtractDir)
|
|
92
|
+
inspectDir = tempExtractDir
|
|
93
|
+
} catch (e) {
|
|
94
|
+
if (tempExtractDir) safeRmDir(tempExtractDir)
|
|
95
|
+
return { ok: false, error: `解压压缩包失败: ${e.message}` }
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (!isZip && statSync(targetPath).isFile()) {
|
|
100
|
+
if (!/^skill\.md$/i.test(basename(targetPath))) return { ok: false, error: '请选择插件或技能文件夹、压缩包,或 SKILL.md 文件' }
|
|
101
|
+
inspectDir = dirname(targetPath)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const effectiveDir = resolvePluginDir(inspectDir)
|
|
105
|
+
if (!effectiveDir) {
|
|
106
|
+
if (tempExtractDir) safeRmDir(tempExtractDir)
|
|
107
|
+
return { ok: false, error: '不符合规范,不可以上传:未检测到有效 skill.md 或插件配置结构' }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const rawFallbackName = (isZip && effectiveDir === tempExtractDir ? basename(targetPath).replace(/\.(zip|tgz|tar\.gz)$/i, '') : basename(effectiveDir)).toLowerCase().replace(/[^a-z0-9_-]/g, '') || 'local-plugin'
|
|
111
|
+
const fallbackName = safeSegment(rawFallbackName, 'plugin name')
|
|
112
|
+
const isMarket = ['.agents/plugins/marketplace.json', '.claude-plugin/marketplace.json', 'marketplace.json'].some((p) => existsSync(join(effectiveDir, p)))
|
|
113
|
+
&& !existsSync(join(effectiveDir, '.codex-plugin', 'plugin.json')) && !existsSync(join(effectiveDir, '.claude-plugin', 'plugin.json'))
|
|
114
|
+
let entries
|
|
115
|
+
try {
|
|
116
|
+
if (isMarket) {
|
|
117
|
+
entries = parseMarketplaceFromDisk('local-upload', effectiveDir).map((row) => {
|
|
118
|
+
if (typeof row.source !== 'string' || !row.source.startsWith('./')) throw new Error(`市场条目「${row.name}」需要远程下载,请通过“添加插件市场”导入仓库`)
|
|
119
|
+
const dir = resolve(effectiveDir, row.source)
|
|
120
|
+
const rel = relative(resolve(effectiveDir), dir)
|
|
121
|
+
if (rel.startsWith('..') || isAbsolute(rel) || !isPluginDir(dir)) throw new Error(`市场条目「${row.name}」缺少有效的本地插件目录`)
|
|
122
|
+
return { row, dir }
|
|
123
|
+
})
|
|
124
|
+
} else {
|
|
125
|
+
const row = parsePluginRowFromDir(effectiveDir, fallbackName, 'local')
|
|
126
|
+
entries = row ? [{ row, dir: effectiveDir }] : []
|
|
127
|
+
if (!row) {
|
|
128
|
+
entries = readdirSync(effectiveDir, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith('.')).map((e) => ({ row: parsePluginRowFromDir(join(effectiveDir, e.name), e.name, 'local'), dir: join(effectiveDir, e.name) })).filter((e) => e.row)
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
} catch (e) {
|
|
132
|
+
if (tempExtractDir) safeRmDir(tempExtractDir)
|
|
133
|
+
return { ok: false, error: e.message }
|
|
134
|
+
}
|
|
135
|
+
if (new Set(entries.map((e) => e.row.name)).size !== entries.length) {
|
|
136
|
+
if (tempExtractDir) safeRmDir(tempExtractDir)
|
|
137
|
+
return { ok: false, error: '集合中存在同名插件或技能,请使用不同的名称' }
|
|
138
|
+
}
|
|
139
|
+
const row = entries.length === 1 ? entries[0].row : (entries.length ? { name: fallbackName, displayName: `本地集合(${entries.length} 项)`, description: entries.map((e) => e.row.displayName || e.row.name).join('、'), version: '1.0.0' } : null)
|
|
140
|
+
if (!row) {
|
|
141
|
+
if (tempExtractDir) safeRmDir(tempExtractDir)
|
|
142
|
+
return { ok: false, error: '不符合规范,不可以上传:未检测到有效 skill.md 或插件配置结构' }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const cleanPluginName = safeSegment(row.name, 'plugin name')
|
|
146
|
+
row.name = cleanPluginName
|
|
147
|
+
|
|
148
|
+
const skills = entries.flatMap((e) => listSkills(e.dir))
|
|
149
|
+
const agents = entries.flatMap((e) => listAgents(e.dir))
|
|
150
|
+
|
|
151
|
+
const duplicate = entries.find((e) => existsSync(join(sourceCacheDir('local'), safeSegment(e.row.name, 'plugin name'))))
|
|
152
|
+
const localDest = duplicate ? join(sourceCacheDir('local'), duplicate.row.name) : join(sourceCacheDir('local'), cleanPluginName)
|
|
153
|
+
let exists = false
|
|
154
|
+
let existingVersion = undefined
|
|
155
|
+
let existingUpdatedAt = undefined
|
|
156
|
+
if (duplicate) {
|
|
157
|
+
exists = true
|
|
158
|
+
try {
|
|
159
|
+
const existingStat = statSync(localDest)
|
|
160
|
+
existingUpdatedAt = existingStat.mtimeMs
|
|
161
|
+
const existingManifest = readPluginManifest(localDest)
|
|
162
|
+
existingVersion = existingManifest?.version || '1.0.0'
|
|
163
|
+
} catch {}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
return {
|
|
167
|
+
ok: true,
|
|
168
|
+
effectiveDir,
|
|
169
|
+
tempExtractDir,
|
|
170
|
+
entries,
|
|
171
|
+
plugins: entries.map((e) => e.row),
|
|
172
|
+
plugin: {
|
|
173
|
+
...row,
|
|
174
|
+
skillsCount: skills.length,
|
|
175
|
+
agentsCount: agents.length,
|
|
176
|
+
},
|
|
177
|
+
exists,
|
|
178
|
+
existingVersion,
|
|
179
|
+
existingUpdatedAt,
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export async function importLocalPlugin({ path: rawPath, overwrite = false, sourceName = '' }) {
|
|
184
|
+
const inspectRes = await inspectLocalPlugin(rawPath)
|
|
185
|
+
if (!inspectRes.ok) {
|
|
186
|
+
throw new Error(inspectRes.error)
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const { plugin, entries, tempExtractDir, exists } = inspectRes
|
|
190
|
+
const cleanPluginName = safeSegment(plugin.name, 'plugin name')
|
|
191
|
+
|
|
192
|
+
if (exists && !overwrite) {
|
|
193
|
+
if (tempExtractDir) safeRmDir(tempExtractDir)
|
|
194
|
+
throw new Error(`已存在同名插件「${cleanPluginName}」`)
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const localDir = sourceCacheDir('local')
|
|
198
|
+
mkdirSync(localDir, { recursive: true })
|
|
199
|
+
for (const { row, dir } of entries) {
|
|
200
|
+
const destDir = resolve(localDir, safeSegment(row.name, 'plugin name'))
|
|
201
|
+
const srcDir = resolve(dir)
|
|
202
|
+
const contains = (root, child) => {
|
|
203
|
+
const rel = relative(root, child)
|
|
204
|
+
return !isAbsolute(rel) && rel !== '..' && !rel.startsWith('..\\') && !rel.startsWith('../')
|
|
205
|
+
}
|
|
206
|
+
if (destDir !== srcDir && (contains(destDir, srcDir) || contains(srcDir, destDir))) {
|
|
207
|
+
if (tempExtractDir) safeRmDir(tempExtractDir)
|
|
208
|
+
throw new Error('导入源与目标目录重叠,请从独立文件夹导入')
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
try {
|
|
212
|
+
for (const { row, dir } of entries) {
|
|
213
|
+
const destDir = join(localDir, safeSegment(row.name, 'plugin name'))
|
|
214
|
+
if (resolve(destDir) !== resolve(dir)) {
|
|
215
|
+
safeRmDir(destDir)
|
|
216
|
+
cpSync(dir, destDir, { recursive: true, force: true })
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
} finally {
|
|
220
|
+
if (tempExtractDir) safeRmDir(tempExtractDir)
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// Ensure 'local' source exists in state.sources; apply the user-chosen tab name if given
|
|
224
|
+
const srcName = String(sourceName || '').trim().slice(0, 30)
|
|
225
|
+
const state = readState()
|
|
226
|
+
let localSource = state.sources.find((s) => s.id === 'local')
|
|
227
|
+
if (localSource) {
|
|
228
|
+
if (srcName && localSource.name !== srcName) {
|
|
229
|
+
localSource.name = srcName
|
|
230
|
+
writeState(state)
|
|
231
|
+
}
|
|
232
|
+
} else {
|
|
233
|
+
localSource = {
|
|
234
|
+
id: 'local',
|
|
235
|
+
name: srcName || '本地插件',
|
|
236
|
+
url: 'local://',
|
|
237
|
+
addedAt: Date.now(),
|
|
238
|
+
}
|
|
239
|
+
state.sources.push(localSource)
|
|
240
|
+
writeState(state)
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
invalidateMarketplaceCache('local')
|
|
244
|
+
|
|
245
|
+
return {
|
|
246
|
+
ok: true,
|
|
247
|
+
sourceId: 'local',
|
|
248
|
+
plugin,
|
|
249
|
+
plugins: entries.map((e) => e.row),
|
|
250
|
+
}
|
|
251
|
+
}
|
package/src/market.js
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* git operations for market sources and remote plugins.
|
|
3
|
+
*
|
|
4
|
+
* Every command runs through execFile (no shell), and every path argument
|
|
5
|
+
* is derived from a slug validated with `safeSegment`. Errors carry a
|
|
6
|
+
* user-facing message; network/git failures are retryable at the UI level.
|
|
7
|
+
*/
|
|
8
|
+
import { execFile } from 'node:child_process'
|
|
9
|
+
import { existsSync, mkdirSync, readFileSync } from 'node:fs'
|
|
10
|
+
import { join, resolve, relative, isAbsolute } from 'node:path'
|
|
11
|
+
import { sourceCacheDir, safeRmDir } from './store.js'
|
|
12
|
+
|
|
13
|
+
const SEGMENT_RE = /^[a-z0-9][a-z0-9._-]*$/i
|
|
14
|
+
|
|
15
|
+
/** In-flight git operations per cache key, so concurrent requests share one clone. */
|
|
16
|
+
const GIT_LOCKS = new Map()
|
|
17
|
+
|
|
18
|
+
async function withGitLock(key, fn) {
|
|
19
|
+
const prev = GIT_LOCKS.get(key) || Promise.resolve()
|
|
20
|
+
const next = prev.catch(() => {}).then(fn)
|
|
21
|
+
GIT_LOCKS.set(key, next)
|
|
22
|
+
try {
|
|
23
|
+
return await next
|
|
24
|
+
} finally {
|
|
25
|
+
if (GIT_LOCKS.get(key) === next) GIT_LOCKS.delete(key)
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function safeSegment(value, label) {
|
|
30
|
+
if (typeof value !== 'string' || !SEGMENT_RE.test(value)) {
|
|
31
|
+
throw new Error(`invalid ${label}: ${JSON.stringify(value)}`)
|
|
32
|
+
}
|
|
33
|
+
return value
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Resolve a marketplace-relative path while keeping it inside its repository. */
|
|
37
|
+
export function pluginPath(root, path) {
|
|
38
|
+
if (typeof path !== 'string' || !path || isAbsolute(path) || /^[a-z]:|^\\/i.test(path)) throw new Error(`unsafe plugin path: ${path}`)
|
|
39
|
+
const dir = resolve(root, path)
|
|
40
|
+
const rel = relative(resolve(root), dir)
|
|
41
|
+
if (rel === '..' || rel.startsWith(`..${process.platform === 'win32' ? '\\' : '/'}`) || isAbsolute(rel)) throw new Error(`unsafe plugin path: ${path}`)
|
|
42
|
+
return dir
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** A marketplace can point back to its own checkout (including a subdirectory). */
|
|
46
|
+
export function sourceRepositoryDir(cache, source) {
|
|
47
|
+
if (!source || !['url', 'git-subdir'].includes(source.source) || typeof source.url !== 'string') return null
|
|
48
|
+
const repoKey = (value) => {
|
|
49
|
+
try {
|
|
50
|
+
const url = new URL(value)
|
|
51
|
+
return `${url.hostname.toLowerCase()}${url.pathname.replace(/\/+$/, '').replace(/\.git$/i, '').toLowerCase()}`
|
|
52
|
+
} catch { return null }
|
|
53
|
+
}
|
|
54
|
+
try {
|
|
55
|
+
const config = readFileSync(join(cache, '.git', 'config'), 'utf8')
|
|
56
|
+
const origin = config.match(/\[remote "origin"\]([^\[]*)/)?.[1].match(/^\s*url\s*=\s*(.+)$/m)?.[1].trim()
|
|
57
|
+
if (!origin || !repoKey(source.url) || repoKey(origin) !== repoKey(source.url)) return null
|
|
58
|
+
const head = readFileSync(join(cache, '.git', 'HEAD'), 'utf8').trim()
|
|
59
|
+
// Reuse only the requested revision; another branch is a different plugin snapshot.
|
|
60
|
+
if (source.ref && head !== `ref: refs/heads/${source.ref}` && head !== source.ref) return null
|
|
61
|
+
if (source.sha) {
|
|
62
|
+
const commit = head.startsWith('ref: ') ? readFileSync(join(cache, '.git', head.slice(5)), 'utf8').trim() : head
|
|
63
|
+
if (commit !== source.sha) return null
|
|
64
|
+
}
|
|
65
|
+
const dir = source.path ? pluginPath(cache, source.path) : cache
|
|
66
|
+
return existsSync(dir) ? dir : null
|
|
67
|
+
} catch { return null }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function formatGitError(stderr, errorMsg) {
|
|
71
|
+
const text = String(stderr || errorMsg || '').toLowerCase()
|
|
72
|
+
if (text.includes('repository not found') || text.includes('not found')) {
|
|
73
|
+
return 'Git 仓库未找到,请检查名称是否拼写正确或为私有仓库'
|
|
74
|
+
}
|
|
75
|
+
if (text.includes('could not resolve host') || text.includes('unable to access')) {
|
|
76
|
+
return '网络连接失败,无法访问 Git 远程仓库'
|
|
77
|
+
}
|
|
78
|
+
if (text.includes('could not read username') || text.includes('authentication failed')) {
|
|
79
|
+
return '无访问权限,请确认仓库是否为公开仓库'
|
|
80
|
+
}
|
|
81
|
+
const lines = String(stderr || errorMsg || '').trim().split('\n').filter(Boolean)
|
|
82
|
+
const last = lines.pop() || 'Git 操作失败'
|
|
83
|
+
return last.length > 50 ? last.slice(0, 48) + '…' : last
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function runGit(args, cwd) {
|
|
87
|
+
return new Promise((resolve, reject) => {
|
|
88
|
+
execFile('git', args, { cwd, maxBuffer: 64 * 1024 * 1024, windowsHide: true }, (error, stdout, stderr) => {
|
|
89
|
+
if (error) {
|
|
90
|
+
const detail = formatGitError(stderr, error.message)
|
|
91
|
+
reject(new Error(detail))
|
|
92
|
+
return
|
|
93
|
+
}
|
|
94
|
+
resolve(String(stdout))
|
|
95
|
+
})
|
|
96
|
+
})
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Clone a source repository into its cache dir (idempotent, concurrency-safe). */
|
|
100
|
+
export async function ensureSourceCloned(sourceId, url) {
|
|
101
|
+
safeSegment(sourceId, 'source id')
|
|
102
|
+
const dir = sourceCacheDir(sourceId)
|
|
103
|
+
if (sourceId === 'local') {
|
|
104
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
|
|
105
|
+
return dir
|
|
106
|
+
}
|
|
107
|
+
if (existsSync(join(dir, '.git'))) return dir
|
|
108
|
+
|
|
109
|
+
return withGitLock(`src:${sourceId}`, async () => {
|
|
110
|
+
// Another request may have completed the clone while we waited on the lock.
|
|
111
|
+
if (existsSync(join(dir, '.git'))) return dir
|
|
112
|
+
|
|
113
|
+
// Clean incomplete cache if previous clone failed
|
|
114
|
+
if (existsSync(dir)) {
|
|
115
|
+
try {
|
|
116
|
+
safeRmDir(dir)
|
|
117
|
+
} catch {
|
|
118
|
+
// ignore rm error
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
try {
|
|
123
|
+
await runGit(['clone', '--depth', '1', url, dir])
|
|
124
|
+
} catch (err) {
|
|
125
|
+
if (existsSync(dir) && !existsSync(join(dir, '.git'))) {
|
|
126
|
+
try {
|
|
127
|
+
safeRmDir(dir)
|
|
128
|
+
} catch {
|
|
129
|
+
// ignore rm error
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
throw err
|
|
133
|
+
}
|
|
134
|
+
return dir
|
|
135
|
+
})
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** git pull in a source cache dir (waits for any in-flight clone of the same source). */
|
|
139
|
+
export async function pullSource(sourceId) {
|
|
140
|
+
safeSegment(sourceId, 'source id')
|
|
141
|
+
if (sourceId === 'local') return
|
|
142
|
+
const dir = sourceCacheDir(sourceId)
|
|
143
|
+
const inFlight = GIT_LOCKS.get(`src:${sourceId}`)
|
|
144
|
+
if (inFlight) {
|
|
145
|
+
try { await inFlight } catch { /* clone failure surfaces on the pull's own git call */ }
|
|
146
|
+
}
|
|
147
|
+
if (!existsSync(join(dir, '.git'))) throw new Error('插件源尚未克隆')
|
|
148
|
+
await runGit(['pull', '--ff-only'], dir)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Materialize a plugin directory for installation.
|
|
153
|
+
*
|
|
154
|
+
* The official marketplace lists three source shapes:
|
|
155
|
+
* "./plugins/x" | "./external_plugins/x" → already inside the cache clone
|
|
156
|
+
* { source: "url", url } → clone the repo, use its root
|
|
157
|
+
* { source: "git-subdir", url, path } → clone the repo, use a subdir
|
|
158
|
+
*
|
|
159
|
+
* Returns { dir } of a materialized checkout for the plugin, or throws with
|
|
160
|
+
* a user-facing message.
|
|
161
|
+
*/
|
|
162
|
+
export async function materializePlugin(sourceId, pluginName, source, { refresh = false } = {}) {
|
|
163
|
+
safeSegment(sourceId, 'source id')
|
|
164
|
+
safeSegment(pluginName, 'plugin name')
|
|
165
|
+
|
|
166
|
+
if (sourceId === 'local') {
|
|
167
|
+
const dir = join(sourceCacheDir('local'), pluginName)
|
|
168
|
+
if (!existsSync(dir)) throw new Error(`本地插件 ${pluginName} 不存在`)
|
|
169
|
+
return { dir }
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
if (typeof source === 'string' && (source === './' || source === '.' || source === '' || source.startsWith('./'))) {
|
|
173
|
+
const cache = sourceCacheDir(sourceId)
|
|
174
|
+
const rel = source.replace(/^\.\/?/, '')
|
|
175
|
+
const dir = pluginPath(cache, source)
|
|
176
|
+
if (!existsSync(dir)) throw new Error(`plugin ${pluginName} not found in cache (${rel || 'root'})`)
|
|
177
|
+
return { dir }
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (source && typeof source === 'object') {
|
|
181
|
+
if (source.source === 'url' || source.source === 'git-subdir') {
|
|
182
|
+
if (typeof source.url !== 'string' || !/^https?:\/\//.test(source.url)) {
|
|
183
|
+
throw new Error(`plugin ${pluginName}: unsupported remote url`)
|
|
184
|
+
}
|
|
185
|
+
const remoteKey = slugFromUrl(source.url)
|
|
186
|
+
const checkout = join(sourceCacheDir('remote'), remoteKey)
|
|
187
|
+
await withGitLock(`remote:${remoteKey}`, async () => {
|
|
188
|
+
if (!existsSync(join(checkout, '.git'))) {
|
|
189
|
+
// --depth 1 keeps clones small; `ref` (branch/tag) is honored when
|
|
190
|
+
// the marketplace pins one. Exact sha checkout needs a full clone;
|
|
191
|
+
// first version installs the pinned ref's head.
|
|
192
|
+
const args = ['clone', '--depth', '1']
|
|
193
|
+
if (source.ref) args.push('--branch', String(source.ref))
|
|
194
|
+
args.push(source.url, checkout)
|
|
195
|
+
await runGit(args)
|
|
196
|
+
} else if (refresh) {
|
|
197
|
+
// The cached checkout is otherwise reused forever, so updates would
|
|
198
|
+
// reinstall the first clone's commit. Re-fetch the tracked ref.
|
|
199
|
+
const args = ['fetch', '--depth', '1', 'origin']
|
|
200
|
+
if (source.ref) args.push(String(source.ref))
|
|
201
|
+
await runGit(args, checkout)
|
|
202
|
+
await runGit(['reset', '--hard', 'FETCH_HEAD'], checkout)
|
|
203
|
+
}
|
|
204
|
+
})
|
|
205
|
+
const dir = source.path ? pluginPath(checkout, source.path) : checkout
|
|
206
|
+
if (!existsSync(dir)) throw new Error(`plugin ${pluginName}: path ${source.path} not found in remote repo`)
|
|
207
|
+
return { dir }
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
throw new Error(`plugin ${pluginName}: unsupported source shape`)
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function slugFromUrl(url) {
|
|
215
|
+
const clean = String(url).replace(/^https?:\/\//, '').replace(/\.git$/, '')
|
|
216
|
+
const slug = clean.replace(/[^a-z0-9]+/gi, '-').replace(/^-+|-+$/g, '').toLowerCase()
|
|
217
|
+
return slug || 'repo'
|
|
218
|
+
}
|