dsh-skill-harbor 0.5.3 → 0.5.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.
@@ -1,68 +1,68 @@
1
- /**
2
- * 同名遮蔽判定。
3
- *
4
- * 规则:同名技能在多个 source 出现时,rank 最小(数字最小)者为胜者,
5
- * 败者携带 `shadowedBy: { source, rank }` 指向胜者。rank 相同视为并列,
6
- * **都不标记遮蔽**(谁也没赢,报遮蔽会误导用户)。
7
- *
8
- * Windows 路径大小写不敏感 —— 但遮蔽判定按 **技能名** 而非路径,
9
- * 因此这里只对名字做大小写不敏感比较(Windows 上 `Foo` 与 `foo` 是同一个技能)。
10
- */
11
- import { rankOf } from './ranks.js'
12
-
13
- /** 名字归一化:Windows 语义下大小写不敏感。 */
14
- function normalizeName(name) {
15
- return String(name).trim().toLowerCase()
16
- }
17
-
18
- /**
19
- * @param {Array<object>} observations
20
- * @param {{ caseInsensitive?: boolean }} [options]
21
- * @returns {Array<object>} 新数组,胜者 shadowedBy 为 undefined
22
- */
23
- export function applyShadowing(observations, options = {}) {
24
- const { caseInsensitive = true } = options
25
- const keyOf = caseInsensitive ? normalizeName : name => String(name).trim()
26
-
27
- // name-key -> 当前胜者
28
- const winners = new Map()
29
-
30
- for (const observation of observations) {
31
- const key = keyOf(observation.name)
32
- const current = winners.get(key)
33
- if (current === undefined) {
34
- winners.set(key, observation)
35
- continue
36
- }
37
- // rank 更小者胜;相等则保持先到者,且不互相遮蔽
38
- if (rankOf(observation.source) < rankOf(current.source)) {
39
- winners.set(key, observation)
40
- }
41
- }
42
-
43
- return observations.map(observation => {
44
- const key = keyOf(observation.name)
45
- const winner = winners.get(key)
46
- if (winner === undefined) {
47
- return { ...observation, shadowedBy: undefined }
48
- }
49
- // 只有胜者 rank **严格更小**才算遮蔽;并列不遮蔽(谁也没赢)
50
- if (rankOf(winner.source) < rankOf(observation.source)) {
51
- return {
52
- ...observation,
53
- shadowedBy: { source: winner.source, rank: rankOf(winner.source) },
54
- }
55
- }
56
- return { ...observation, shadowedBy: undefined }
57
- })
58
- }
59
-
60
- /** 只保留胜者(未被遮蔽的)。 */
61
- export function visibleSkills(observations) {
62
- return observations.filter(observation => observation.shadowedBy === undefined)
63
- }
64
-
65
- /** 是否真能被模型看见:胜者 且 未被 disable-model-invocation 关掉。 */
66
- export function modelVisibleSkills(observations) {
67
- return visibleSkills(observations).filter(observation => observation.modelInvocable === true)
68
- }
1
+ /**
2
+ * 同名遮蔽判定。
3
+ *
4
+ * 规则:同名技能在多个 source 出现时,rank 最小(数字最小)者为胜者,
5
+ * 败者携带 `shadowedBy: { source, rank }` 指向胜者。rank 相同视为并列,
6
+ * **都不标记遮蔽**(谁也没赢,报遮蔽会误导用户)。
7
+ *
8
+ * Windows 路径大小写不敏感 —— 但遮蔽判定按 **技能名** 而非路径,
9
+ * 因此这里只对名字做大小写不敏感比较(Windows 上 `Foo` 与 `foo` 是同一个技能)。
10
+ */
11
+ import { rankOf } from './ranks.js'
12
+
13
+ /** 名字归一化:Windows 语义下大小写不敏感。 */
14
+ function normalizeName(name) {
15
+ return String(name).trim().toLowerCase()
16
+ }
17
+
18
+ /**
19
+ * @param {Array<object>} observations
20
+ * @param {{ caseInsensitive?: boolean }} [options]
21
+ * @returns {Array<object>} 新数组,胜者 shadowedBy 为 undefined
22
+ */
23
+ export function applyShadowing(observations, options = {}) {
24
+ const { caseInsensitive = true } = options
25
+ const keyOf = caseInsensitive ? normalizeName : name => String(name).trim()
26
+
27
+ // name-key -> 当前胜者
28
+ const winners = new Map()
29
+
30
+ for (const observation of observations) {
31
+ const key = keyOf(observation.name)
32
+ const current = winners.get(key)
33
+ if (current === undefined) {
34
+ winners.set(key, observation)
35
+ continue
36
+ }
37
+ // rank 更小者胜;相等则保持先到者,且不互相遮蔽
38
+ if (rankOf(observation.source) < rankOf(current.source)) {
39
+ winners.set(key, observation)
40
+ }
41
+ }
42
+
43
+ return observations.map(observation => {
44
+ const key = keyOf(observation.name)
45
+ const winner = winners.get(key)
46
+ if (winner === undefined) {
47
+ return { ...observation, shadowedBy: undefined }
48
+ }
49
+ // 只有胜者 rank **严格更小**才算遮蔽;并列不遮蔽(谁也没赢)
50
+ if (rankOf(winner.source) < rankOf(observation.source)) {
51
+ return {
52
+ ...observation,
53
+ shadowedBy: { source: winner.source, rank: rankOf(winner.source) },
54
+ }
55
+ }
56
+ return { ...observation, shadowedBy: undefined }
57
+ })
58
+ }
59
+
60
+ /** 只保留胜者(未被遮蔽的)。 */
61
+ export function visibleSkills(observations) {
62
+ return observations.filter(observation => observation.shadowedBy === undefined)
63
+ }
64
+
65
+ /** 是否真能被模型看见:胜者 且 未被 disable-model-invocation 关掉。 */
66
+ export function modelVisibleSkills(observations) {
67
+ return visibleSkills(observations).filter(observation => observation.modelInvocable === true)
68
+ }
@@ -1,86 +1,86 @@
1
- /**
2
- * 技能目录 watcher —— 增量感知,替代「每次请求全量重扫」。
3
- *
4
- * 设计取舍:
5
- * - 不做「精确到文件的 diff」:那需要维护一棵完整树,且 fs.watch 在 Windows 上
6
- * 对深层目录的事件并不可靠。这里只做**代数(generation)递增**:
7
- * 任何目录变动 → 代数 +1 → 快照缓存失效。
8
- * - 事件做 debounce 合并:一次保存会触发多个事件(创建/重命名/写入),
9
- * 不合并会连打多次重扫。
10
- * - watcher 失败(目录不存在 / 权限)不致命:降级为「无 watcher」,
11
- * 此时只靠 TTL 兜底,并把这个降级状态如实报告给调用方。
12
- */
13
- import { watch } from 'node:fs'
14
- import { existsSync } from 'node:fs'
15
-
16
- export const DEBOUNCE_MS = 250
17
-
18
- /**
19
- * 观察一组根目录。
20
- * @param {Array<{path:string, source:string}>} roots
21
- * @param {() => void} onInvalidate 变动时调用(已 debounce)
22
- * @param {{ debounceMs?: number }} [options]
23
- * @returns {{ generation: () => number, watching: string[], degraded: Array<{path:string,reason:string}>, close: () => void }}
24
- */
25
- export function watchRoots(roots, onInvalidate, options = {}) {
26
- const debounceMs = options.debounceMs ?? DEBOUNCE_MS
27
-
28
- let generation = 0
29
- let timer = null
30
- const watchers = []
31
- const watching = []
32
- const degraded = []
33
-
34
- const bump = () => {
35
- if (timer !== null) clearTimeout(timer)
36
- timer = setTimeout(() => {
37
- timer = null
38
- generation += 1
39
- try {
40
- onInvalidate(generation)
41
- } catch {
42
- /* 回调失败不应影响 watcher 本身 */
43
- }
44
- }, debounceMs)
45
- // 允许进程退出,不被 timer 挂住
46
- if (typeof timer.unref === 'function') timer.unref()
47
- }
48
-
49
- for (const root of roots) {
50
- if (!existsSync(root.path)) {
51
- degraded.push({ path: root.path, reason: 'not-exists' })
52
- continue
53
- }
54
- try {
55
- const watcher = watch(root.path, { recursive: true, persistent: false }, bump)
56
- watcher.on('error', error => {
57
- degraded.push({ path: root.path, reason: String(error?.code ?? error?.message ?? error) })
58
- })
59
- watchers.push(watcher)
60
- watching.push(root.path)
61
- } catch (error) {
62
- // recursive 在某些平台/网络盘不支持 → 记录降级,不抛
63
- degraded.push({ path: root.path, reason: String(error?.code ?? error?.message ?? error) })
64
- }
65
- }
66
-
67
- return {
68
- generation: () => generation,
69
- watching,
70
- degraded,
71
- close() {
72
- if (timer !== null) {
73
- clearTimeout(timer)
74
- timer = null
75
- }
76
- for (const watcher of watchers) {
77
- try {
78
- watcher.close()
79
- } catch {
80
- /* ignore */
81
- }
82
- }
83
- watchers.length = 0
84
- },
85
- }
86
- }
1
+ /**
2
+ * 技能目录 watcher —— 增量感知,替代「每次请求全量重扫」。
3
+ *
4
+ * 设计取舍:
5
+ * - 不做「精确到文件的 diff」:那需要维护一棵完整树,且 fs.watch 在 Windows 上
6
+ * 对深层目录的事件并不可靠。这里只做**代数(generation)递增**:
7
+ * 任何目录变动 → 代数 +1 → 快照缓存失效。
8
+ * - 事件做 debounce 合并:一次保存会触发多个事件(创建/重命名/写入),
9
+ * 不合并会连打多次重扫。
10
+ * - watcher 失败(目录不存在 / 权限)不致命:降级为「无 watcher」,
11
+ * 此时只靠 TTL 兜底,并把这个降级状态如实报告给调用方。
12
+ */
13
+ import { watch } from 'node:fs'
14
+ import { existsSync } from 'node:fs'
15
+
16
+ export const DEBOUNCE_MS = 250
17
+
18
+ /**
19
+ * 观察一组根目录。
20
+ * @param {Array<{path:string, source:string}>} roots
21
+ * @param {() => void} onInvalidate 变动时调用(已 debounce)
22
+ * @param {{ debounceMs?: number }} [options]
23
+ * @returns {{ generation: () => number, watching: string[], degraded: Array<{path:string,reason:string}>, close: () => void }}
24
+ */
25
+ export function watchRoots(roots, onInvalidate, options = {}) {
26
+ const debounceMs = options.debounceMs ?? DEBOUNCE_MS
27
+
28
+ let generation = 0
29
+ let timer = null
30
+ const watchers = []
31
+ const watching = []
32
+ const degraded = []
33
+
34
+ const bump = () => {
35
+ if (timer !== null) clearTimeout(timer)
36
+ timer = setTimeout(() => {
37
+ timer = null
38
+ generation += 1
39
+ try {
40
+ onInvalidate(generation)
41
+ } catch {
42
+ /* 回调失败不应影响 watcher 本身 */
43
+ }
44
+ }, debounceMs)
45
+ // 允许进程退出,不被 timer 挂住
46
+ if (typeof timer.unref === 'function') timer.unref()
47
+ }
48
+
49
+ for (const root of roots) {
50
+ if (!existsSync(root.path)) {
51
+ degraded.push({ path: root.path, reason: 'not-exists' })
52
+ continue
53
+ }
54
+ try {
55
+ const watcher = watch(root.path, { recursive: true, persistent: false }, bump)
56
+ watcher.on('error', error => {
57
+ degraded.push({ path: root.path, reason: String(error?.code ?? error?.message ?? error) })
58
+ })
59
+ watchers.push(watcher)
60
+ watching.push(root.path)
61
+ } catch (error) {
62
+ // recursive 在某些平台/网络盘不支持 → 记录降级,不抛
63
+ degraded.push({ path: root.path, reason: String(error?.code ?? error?.message ?? error) })
64
+ }
65
+ }
66
+
67
+ return {
68
+ generation: () => generation,
69
+ watching,
70
+ degraded,
71
+ close() {
72
+ if (timer !== null) {
73
+ clearTimeout(timer)
74
+ timer = null
75
+ }
76
+ for (const watcher of watchers) {
77
+ try {
78
+ watcher.close()
79
+ } catch {
80
+ /* ignore */
81
+ }
82
+ }
83
+ watchers.length = 0
84
+ },
85
+ }
86
+ }
package/src/config.js CHANGED
@@ -1,42 +1,42 @@
1
- /**
2
- * 插件配置 schema(0.1.7+ 形态)。
3
- *
4
- * 按 Phase 0 实测:`installSection` 在 0.1.7 已移除,设置卡由 Config 字段
5
- * 标 `.volatile()` 自动生成。这里只声明字段语义;具体 schema 对象由宿主
6
- * 的 config schema 机制消费。
7
- */
8
-
9
- /** 单技能公告字符上限的默认值。 */
10
- export const DEFAULT_BUDGET_LIMIT = 4000
11
-
12
- /** systemPrompt 公告的硬上限(checklist:开启时 ≤200 字)。 */
13
- export const ANNOUNCEMENT_HARD_LIMIT = 200
14
-
15
- /**
16
- * 配置的默认值与归一化。
17
- * `managementOnly` 为 true 时**不注册 provider、不注册工具、不碰技能目录**。
18
- */
19
- export function normalizeConfig(input = {}) {
20
- return {
21
- cwd: typeof input.cwd === 'string' ? input.cwd : process.cwd(),
22
- dshHome: typeof input.dshHome === 'string' ? input.dshHome : undefined,
23
- agentsHome: typeof input.agentsHome === 'string' ? input.agentsHome : undefined,
24
- customSkillDirs: Array.isArray(input.customSkillDirs) ? input.customSkillDirs : [],
25
- bundledSkillDir: typeof input.bundledSkillDir === 'string' ? input.bundledSkillDir : undefined,
26
-
27
- budgetLimit: Number.isFinite(input.budgetLimit) && input.budgetLimit > 0
28
- ? input.budgetLimit
29
- : DEFAULT_BUDGET_LIMIT,
30
-
31
- // 默认**不**往 systemPrompt 写公告
32
- announceToSystemPrompt: input.announceToSystemPrompt === true,
33
-
34
- managementOnly: input.managementOnly === true,
35
- }
36
- }
37
-
38
- /** 公告文本裁剪到硬上限(按码点,不切坏 emoji)。 */
39
- export function clampAnnouncement(text) {
40
- const chars = [...String(text ?? '')]
41
- return chars.length <= ANNOUNCEMENT_HARD_LIMIT ? chars.join('') : chars.slice(0, ANNOUNCEMENT_HARD_LIMIT).join('')
42
- }
1
+ /**
2
+ * 插件配置 schema(0.1.7+ 形态)。
3
+ *
4
+ * 按 Phase 0 实测:`installSection` 在 0.1.7 已移除,设置卡由 Config 字段
5
+ * 标 `.volatile()` 自动生成。这里只声明字段语义;具体 schema 对象由宿主
6
+ * 的 config schema 机制消费。
7
+ */
8
+
9
+ /** 单技能公告字符上限的默认值。 */
10
+ export const DEFAULT_BUDGET_LIMIT = 4000
11
+
12
+ /** systemPrompt 公告的硬上限(checklist:开启时 ≤200 字)。 */
13
+ export const ANNOUNCEMENT_HARD_LIMIT = 200
14
+
15
+ /**
16
+ * 配置的默认值与归一化。
17
+ * `managementOnly` 为 true 时**不注册 provider、不注册工具、不碰技能目录**。
18
+ */
19
+ export function normalizeConfig(input = {}) {
20
+ return {
21
+ cwd: typeof input.cwd === 'string' ? input.cwd : process.cwd(),
22
+ dshHome: typeof input.dshHome === 'string' ? input.dshHome : undefined,
23
+ agentsHome: typeof input.agentsHome === 'string' ? input.agentsHome : undefined,
24
+ customSkillDirs: Array.isArray(input.customSkillDirs) ? input.customSkillDirs : [],
25
+ bundledSkillDir: typeof input.bundledSkillDir === 'string' ? input.bundledSkillDir : undefined,
26
+
27
+ budgetLimit: Number.isFinite(input.budgetLimit) && input.budgetLimit > 0
28
+ ? input.budgetLimit
29
+ : DEFAULT_BUDGET_LIMIT,
30
+
31
+ // 默认**不**往 systemPrompt 写公告
32
+ announceToSystemPrompt: input.announceToSystemPrompt === true,
33
+
34
+ managementOnly: input.managementOnly === true,
35
+ }
36
+ }
37
+
38
+ /** 公告文本裁剪到硬上限(按码点,不切坏 emoji)。 */
39
+ export function clampAnnouncement(text) {
40
+ const chars = [...String(text ?? '')]
41
+ return chars.length <= ANNOUNCEMENT_HARD_LIMIT ? chars.join('') : chars.slice(0, ANNOUNCEMENT_HARD_LIMIT).join('')
42
+ }
package/src/index.js CHANGED
@@ -10,14 +10,47 @@
10
10
  * - `ctx.fiber.uid` 为 `number | null`,dispose 后置 `null`
11
11
  * - `SkillSummary.path` 自 0.1.7-alpha.1 起存在(engines 下界依据)
12
12
  */
13
+ import z from '@deepseek-ai/schemastery'
13
14
  import { installProvider } from './provider/lifecycle.js'
14
15
  import { registerRoutes } from './routes/index.js'
15
- import { normalizeConfig } from './config.js'
16
+ import { DEFAULT_BUDGET_LIMIT, normalizeConfig } from './config.js'
16
17
 
17
18
  export const name = 'dsh-skill-harbor'
18
19
 
19
20
  export const inject = ['skills']
20
21
 
22
+ /**
23
+ * 宿主 Loader row 的 Config —— 设置面的**唯一**入口。
24
+ *
25
+ * 宿主的设置表单只从插件模块导出的 schemastery schema 派生:
26
+ * `packages/settings/settings/src/index.ts:426-429` 读 `entry.fiber.runtime.Config`,
27
+ * `describe()` 里 schema 为 undefined 直接返回 [],再由 `volatileForm(schema)`
28
+ * 收窄成表单(`schema.ts:37-49`,只收 `.volatile()` 字段)。没有 Config 就没有
29
+ * `section[data-plugin-config]`,客户端半注册的槽也永远不会被派发。
30
+ *
31
+ * 为什么 `customSkillDirs` **不**标 volatile:它要重挂 provider 与路由才生效,
32
+ * 标成热改会得到一个「改了没反应」的假面(比没有开关更糟)。
33
+ */
34
+ export const Config = z.object({
35
+ budgetLimit: z.number()
36
+ .default(DEFAULT_BUDGET_LIMIT)
37
+ .min(1)
38
+ .max(1_000_000)
39
+ .description('单技能公告字符上限')
40
+ .volatile(),
41
+ announceToSystemPrompt: z.boolean()
42
+ .default(false)
43
+ .description('把技能公告写进 systemPrompt(开启时 ≤200 字)')
44
+ .volatile(),
45
+ managementOnly: z.boolean()
46
+ .default(false)
47
+ .description('只保留只读路由,不注册 provider / 工具')
48
+ .volatile(),
49
+ customSkillDirs: z.array(z.string())
50
+ .default([])
51
+ .description('自定义技能目录(改动需重新挂载)'),
52
+ })
53
+
21
54
  export function apply(ctx, rawConfig = {}) {
22
55
  const config = normalizeConfig(rawConfig)
23
56
 
@@ -1,94 +1,94 @@
1
- /**
2
- * 仓库抓取与更新检查。
3
- *
4
- * 安全纪律:
5
- * - 只接受 http(s),且只拼接受信主机(GitHub 系)——不跟随任意 URL
6
- * - 归档下载后**不执行任何仓库代码**,只解包 + 审计
7
- * - 更新检查只读 ref → sha 的映射,不改盘
8
- */
9
- import { createHash } from 'node:crypto'
10
-
11
- import { isCommitSha, makeSource, checkUpdate, applySync } from './source.js'
12
-
13
- /** 允许的主机白名单(不跟随任意 URL)。 */
14
- export const ALLOWED_HOSTS = new Set([
15
- 'github.com',
16
- 'api.github.com',
17
- 'codeload.github.com',
18
- 'raw.githubusercontent.com',
19
- ])
20
-
21
- const FETCH_TIMEOUT_MS = 20_000
22
- const MAX_ARCHIVE_BYTES = 8 * 1024 * 1024
23
-
24
- /** 校验并构造一个 GitHub 归档 URL;非白名单主机一律拒绝。 */
25
- export function archiveUrl({ owner, repo, sha }) {
26
- if (!isCommitSha(sha)) return { ok: false, reason: 'invalid-sha' }
27
- if (!/^[\w.-]+$/.test(owner) || !/^[\w.-]+$/.test(repo)) {
28
- return { ok: false, reason: 'invalid-owner-or-repo' }
29
- }
30
- const host = 'codeload.github.com'
31
- if (!ALLOWED_HOSTS.has(host)) return { ok: false, reason: 'host-not-allowed' }
32
- return { ok: true, url: `https://${host}/${owner}/${repo}/zip/${sha}` }
33
- }
34
-
35
- /** 校验一个远端 URL 是否可信。 */
36
- export function isAllowedUrl(raw) {
37
- try {
38
- const url = new URL(raw)
39
- if (url.protocol !== 'https:') return false
40
- return ALLOWED_HOSTS.has(url.hostname.toLowerCase())
41
- } catch {
42
- return false
43
- }
44
- }
45
-
46
- /**
47
- * 下载归档到内存(带超时与体积上限)。
48
- * @returns {{ ok: true, buffer: Buffer, sha256: string } | { ok: false, reason: string }}
49
- */
50
- export async function fetchArchive(url, fetchImpl = globalThis.fetch) {
51
- if (!isAllowedUrl(url)) return { ok: false, reason: 'url-not-allowed' }
52
- if (typeof fetchImpl !== 'function') return { ok: false, reason: 'fetch-unavailable' }
53
-
54
- const controller = new AbortController()
55
- const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS)
56
- try {
57
- const response = await fetchImpl(url, { signal: controller.signal, redirect: 'follow' })
58
- if (!response.ok) return { ok: false, reason: `http-${response.status}` }
59
-
60
- const declared = Number(response.headers?.get?.('content-length') ?? '0')
61
- if (declared > MAX_ARCHIVE_BYTES) {
62
- return { ok: false, reason: 'archive-too-large', declared }
63
- }
64
-
65
- const buffer = Buffer.from(await response.arrayBuffer())
66
- if (buffer.length > MAX_ARCHIVE_BYTES) {
67
- return { ok: false, reason: 'archive-too-large', actual: buffer.length }
68
- }
69
- return { ok: true, buffer, sha256: createHash('sha256').update(buffer).digest('hex') }
70
- } catch (error) {
71
- const reason = error?.name === 'AbortError' ? 'timeout' : 'fetch-failed'
72
- return { ok: false, reason, message: String(error?.message ?? error) }
73
- } finally {
74
- clearTimeout(timer)
75
- }
76
- }
77
-
78
- /** 解析 GitHub commit API 的响应,取出完整 sha。 */
79
- export function parseCommitResponse(payload) {
80
- if (payload === null || typeof payload !== 'object') {
81
- return { ok: false, reason: 'not-an-object' }
82
- }
83
- const sha = payload.sha
84
- if (!isCommitSha(sha)) return { ok: false, reason: 'invalid-sha' }
85
- return { ok: true, sha: String(sha).toLowerCase() }
86
- }
87
-
88
- /** 由一次成功的 ref 解析生成钉死的源记录。 */
89
- export function sourceFromResolve({ owner, repo, ref, sha }) {
90
- if (!isCommitSha(sha)) return { ok: false, reason: 'invalid-sha' }
91
- return { ok: true, source: makeSource({ owner, repo, ref, commitSha: sha }) }
92
- }
93
-
94
- export { checkUpdate, applySync }
1
+ /**
2
+ * 仓库抓取与更新检查。
3
+ *
4
+ * 安全纪律:
5
+ * - 只接受 http(s),且只拼接受信主机(GitHub 系)——不跟随任意 URL
6
+ * - 归档下载后**不执行任何仓库代码**,只解包 + 审计
7
+ * - 更新检查只读 ref → sha 的映射,不改盘
8
+ */
9
+ import { createHash } from 'node:crypto'
10
+
11
+ import { isCommitSha, makeSource, checkUpdate, applySync } from './source.js'
12
+
13
+ /** 允许的主机白名单(不跟随任意 URL)。 */
14
+ export const ALLOWED_HOSTS = new Set([
15
+ 'github.com',
16
+ 'api.github.com',
17
+ 'codeload.github.com',
18
+ 'raw.githubusercontent.com',
19
+ ])
20
+
21
+ const FETCH_TIMEOUT_MS = 20_000
22
+ const MAX_ARCHIVE_BYTES = 8 * 1024 * 1024
23
+
24
+ /** 校验并构造一个 GitHub 归档 URL;非白名单主机一律拒绝。 */
25
+ export function archiveUrl({ owner, repo, sha }) {
26
+ if (!isCommitSha(sha)) return { ok: false, reason: 'invalid-sha' }
27
+ if (!/^[\w.-]+$/.test(owner) || !/^[\w.-]+$/.test(repo)) {
28
+ return { ok: false, reason: 'invalid-owner-or-repo' }
29
+ }
30
+ const host = 'codeload.github.com'
31
+ if (!ALLOWED_HOSTS.has(host)) return { ok: false, reason: 'host-not-allowed' }
32
+ return { ok: true, url: `https://${host}/${owner}/${repo}/zip/${sha}` }
33
+ }
34
+
35
+ /** 校验一个远端 URL 是否可信。 */
36
+ export function isAllowedUrl(raw) {
37
+ try {
38
+ const url = new URL(raw)
39
+ if (url.protocol !== 'https:') return false
40
+ return ALLOWED_HOSTS.has(url.hostname.toLowerCase())
41
+ } catch {
42
+ return false
43
+ }
44
+ }
45
+
46
+ /**
47
+ * 下载归档到内存(带超时与体积上限)。
48
+ * @returns {{ ok: true, buffer: Buffer, sha256: string } | { ok: false, reason: string }}
49
+ */
50
+ export async function fetchArchive(url, fetchImpl = globalThis.fetch) {
51
+ if (!isAllowedUrl(url)) return { ok: false, reason: 'url-not-allowed' }
52
+ if (typeof fetchImpl !== 'function') return { ok: false, reason: 'fetch-unavailable' }
53
+
54
+ const controller = new AbortController()
55
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS)
56
+ try {
57
+ const response = await fetchImpl(url, { signal: controller.signal, redirect: 'follow' })
58
+ if (!response.ok) return { ok: false, reason: `http-${response.status}` }
59
+
60
+ const declared = Number(response.headers?.get?.('content-length') ?? '0')
61
+ if (declared > MAX_ARCHIVE_BYTES) {
62
+ return { ok: false, reason: 'archive-too-large', declared }
63
+ }
64
+
65
+ const buffer = Buffer.from(await response.arrayBuffer())
66
+ if (buffer.length > MAX_ARCHIVE_BYTES) {
67
+ return { ok: false, reason: 'archive-too-large', actual: buffer.length }
68
+ }
69
+ return { ok: true, buffer, sha256: createHash('sha256').update(buffer).digest('hex') }
70
+ } catch (error) {
71
+ const reason = error?.name === 'AbortError' ? 'timeout' : 'fetch-failed'
72
+ return { ok: false, reason, message: String(error?.message ?? error) }
73
+ } finally {
74
+ clearTimeout(timer)
75
+ }
76
+ }
77
+
78
+ /** 解析 GitHub commit API 的响应,取出完整 sha。 */
79
+ export function parseCommitResponse(payload) {
80
+ if (payload === null || typeof payload !== 'object') {
81
+ return { ok: false, reason: 'not-an-object' }
82
+ }
83
+ const sha = payload.sha
84
+ if (!isCommitSha(sha)) return { ok: false, reason: 'invalid-sha' }
85
+ return { ok: true, sha: String(sha).toLowerCase() }
86
+ }
87
+
88
+ /** 由一次成功的 ref 解析生成钉死的源记录。 */
89
+ export function sourceFromResolve({ owner, repo, ref, sha }) {
90
+ if (!isCommitSha(sha)) return { ok: false, reason: 'invalid-sha' }
91
+ return { ok: true, source: makeSource({ owner, repo, ref, commitSha: sha }) }
92
+ }
93
+
94
+ export { checkUpdate, applySync }