dsh-pluginmarket-plus 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/refresh.js ADDED
@@ -0,0 +1,186 @@
1
+ /**
2
+ * 抓取与规范化一个插件市场索引 JSON。
3
+ *
4
+ * 官方插件市场(`plugin-market` 服务)在 15 秒内抓不到索引就判失败,而真实的索引
5
+ * 动辄几 MB、跨网络要几十秒,于是「搜索 → 索引超时」。这里用更长的时间窗抓取,
6
+ * 校验格式 1 的基本结构,并把相对 icon 改写为绝对地址——因为镜像会从 localhost
7
+ * 提供这份 JSON,相对地址在镜像源下会指向 localhost 而失效。
8
+ *
9
+ * @module dsh-pluginmarket-plus/lib/refresh
10
+ */
11
+
12
+ /** 抓取时使用的 User-Agent。 */
13
+ const USER_AGENT = 'dsh-pluginmarket-plus/0.1 (+local index cache)'
14
+
15
+ /**
16
+ * @typedef {object} FetchedIndex
17
+ * @property {Buffer} bytes - 规范化后的 JSON 正文。
18
+ * @property {number} plugins - 插件条数。
19
+ * @property {unknown} title - 索引标题(LocalizedText)。
20
+ */
21
+
22
+ /**
23
+ * 把一条拒绝原因压成一行,便于写进状态清单。
24
+ * @param {unknown} error - 任意抛出物。
25
+ * @returns {string} 单行诊断。
26
+ */
27
+ export function messageOf(error) {
28
+ if (error instanceof Error) {
29
+ const cause = error.cause instanceof Error ? `: ${error.cause.message}` : ''
30
+ return `${error.message}${cause}`.replace(/\s+/gu, ' ').trim()
31
+ }
32
+ return String(error).replace(/\s+/gu, ' ').trim()
33
+ }
34
+
35
+ /**
36
+ * 从 LocalizedText 里挑一个用于列表展示的标题。
37
+ * @param {unknown} title - 索引的 title 字段。
38
+ * @returns {string} 可展示文本;没有时返回空串。
39
+ */
40
+ export function indexTitle(title) {
41
+ if (typeof title === 'string') return title
42
+ if (title !== null && typeof title === 'object' && !Array.isArray(title)) {
43
+ const record = /** @type {Record<string, unknown>} */ (title)
44
+ for (const key of ['zh', 'en']) {
45
+ const value = record[key]
46
+ if (typeof value === 'string' && value.trim() !== '') return value
47
+ }
48
+ for (const value of Object.values(record)) {
49
+ if (typeof value === 'string' && value.trim() !== '') return value
50
+ }
51
+ }
52
+ return ''
53
+ }
54
+
55
+ /**
56
+ * 把相对 icon 引用改写成相对「上游索引地址」的绝对地址。
57
+ *
58
+ * 镜像地址与上游地址不同源,相对 icon 在镜像下会解析到 localhost;在缓存前改写,
59
+ * 浏览器就会直接向上游取图。`data:` 与已是绝对地址的 icon 保持原样。
60
+ * @param {unknown} document - 已解析的索引文档(就地修改)。
61
+ * @param {string} indexUrl - 上游索引地址。
62
+ * @returns {void}
63
+ */
64
+ export function absolutizeIcons(document, indexUrl) {
65
+ if (document === null || typeof document !== 'object') return
66
+ const plugins = /** @type {{ plugins?: unknown }} */ (document).plugins
67
+ if (!Array.isArray(plugins)) return
68
+ for (const plugin of plugins) {
69
+ if (plugin === null || typeof plugin !== 'object') continue
70
+ const record = /** @type {Record<string, unknown>} */ (plugin)
71
+ const icon = record.icon
72
+ if (typeof icon !== 'string' || icon === '' || icon.startsWith('data:')) continue
73
+ if (/^[a-z][a-z0-9+.-]*:/iu.test(icon)) {
74
+ // 官方校验只接受 https 的 icon(或与索引同源的地址);镜像源是 localhost,
75
+ // 所以 http 的 icon 在镜像下必然失效,直接丢弃,交给默认图标。
76
+ try {
77
+ if (new URL(icon).protocol === 'http:') delete record.icon
78
+ } catch {
79
+ delete record.icon
80
+ }
81
+ continue
82
+ }
83
+ try {
84
+ const resolved = new URL(icon, indexUrl)
85
+ if (resolved.protocol !== 'https:') {
86
+ delete record.icon
87
+ continue
88
+ }
89
+ record.icon = resolved.href
90
+ } catch {
91
+ delete record.icon
92
+ }
93
+ }
94
+ }
95
+
96
+ /**
97
+ * 校验索引文档的最小结构(完整校验由官方 `plugin-market` 在读取镜像时执行)。
98
+ * @param {unknown} document - JSON.parse 的结果。
99
+ * @param {string} indexUrl - 上游索引地址,用于补默认标题。
100
+ * @returns {void}
101
+ */
102
+ function assertIndexShape(document, indexUrl) {
103
+ if (document === null || typeof document !== 'object' || Array.isArray(document)) throw new Error('索引不是 JSON 对象')
104
+ const record = /** @type {Record<string, unknown>} */ (document)
105
+ if (record.format !== 1) throw new Error(`不支持的索引格式 format=${String(record.format)}`)
106
+ if (!Array.isArray(record.plugins)) throw new Error('索引缺少 plugins 数组')
107
+ // 官方校验要求 title 为 LocalizedText;上游偶尔缺失,补一个宿主名,避免整份索引作废。
108
+ const title = record.title
109
+ const hasTitle = typeof title === 'string'
110
+ ? title.trim() !== ''
111
+ : title !== null && typeof title === 'object' && typeof (/** @type {Record<string, unknown>} */ (title).en) === 'string'
112
+ if (!hasTitle) {
113
+ let host = 'plugin market'
114
+ try {
115
+ host = new URL(indexUrl).hostname || host
116
+ } catch {
117
+ // 保留默认值。
118
+ }
119
+ record.title = { en: host }
120
+ }
121
+ }
122
+
123
+ /**
124
+ * 抓取一次索引。
125
+ * @param {string} url - 上游索引地址。
126
+ * @param {{ timeoutMs: number, maxBytes: number, userAgent?: string }} options - 抓取约束。
127
+ * @returns {Promise<FetchedIndex>} 规范化后的正文与摘要。
128
+ */
129
+ async function fetchOnce(url, options) {
130
+ const signal = AbortSignal.timeout(options.timeoutMs)
131
+ const response = await fetch(url, {
132
+ signal,
133
+ redirect: 'follow',
134
+ headers: { accept: 'application/json', 'user-agent': options.userAgent ?? USER_AGENT },
135
+ })
136
+ if (!response.ok) {
137
+ await response.body?.cancel()
138
+ throw new Error(`HTTP ${String(response.status)}`)
139
+ }
140
+ const declared = Number(response.headers.get('content-length') ?? 0)
141
+ if (declared > options.maxBytes) {
142
+ await response.body?.cancel()
143
+ throw new Error(`响应体 ${String(declared)} 字节,超过上限 ${String(options.maxBytes)}`)
144
+ }
145
+ const buffer = Buffer.from(await response.arrayBuffer())
146
+ if (buffer.byteLength > options.maxBytes) {
147
+ throw new Error(`响应体 ${String(buffer.byteLength)} 字节,超过上限 ${String(options.maxBytes)}`)
148
+ }
149
+ const text = new TextDecoder('utf-8').decode(buffer)
150
+ /** @type {unknown} */
151
+ let document
152
+ try {
153
+ document = JSON.parse(text)
154
+ } catch (error) {
155
+ throw new Error(`响应不是合法 JSON: ${messageOf(error)}`)
156
+ }
157
+ assertIndexShape(document, url)
158
+ absolutizeIcons(document, url)
159
+ const normalized = Buffer.from(JSON.stringify(document), 'utf8')
160
+ return {
161
+ bytes: normalized,
162
+ plugins: Array.isArray(/** @type {{ plugins: unknown[] }} */ (document).plugins) ? /** @type {{ plugins: unknown[] }} */ (document).plugins.length : 0,
163
+ title: /** @type {{ title?: unknown }} */ (document).title,
164
+ }
165
+ }
166
+
167
+ /**
168
+ * 抓取索引,失败时按次数重试(网络抖动很常见,多试一次往往就过了)。
169
+ * @param {string} url - 上游索引地址。
170
+ * @param {{ timeoutMs: number, maxBytes: number, retries?: number, userAgent?: string }} options - 抓取约束。
171
+ * @returns {Promise<FetchedIndex>} 规范化后的正文与摘要。
172
+ */
173
+ export async function fetchIndex(url, options) {
174
+ const retries = Math.max(0, options.retries ?? 0)
175
+ /** @type {unknown} */
176
+ let lastError
177
+ for (let attempt = 0; attempt <= retries; attempt++) {
178
+ try {
179
+ return await fetchOnce(url, options)
180
+ } catch (error) {
181
+ lastError = error
182
+ if (attempt < retries) await new Promise(resolve => setTimeout(resolve, 800 * (attempt + 1)))
183
+ }
184
+ }
185
+ throw lastError
186
+ }
package/lib/store.js ADDED
@@ -0,0 +1,257 @@
1
+ /**
2
+ * 磁盘缓存:每个插件源一份索引 JSON 正文 + 一份状态清单。
3
+ *
4
+ * 目录布局(默认 `<profile>/.pluginmarket-plus/`):
5
+ * - `index-<id>.json` 索引正文(已把相对 icon 改写为绝对地址)
6
+ * - `state.json` `{ version, sources: string[], entries: { [id]: Entry } }`
7
+ *
8
+ * 写正文和写清单都走「临时文件 + rename」的原子替换,任何时刻磁盘上要么是旧副本,
9
+ * 要么是新副本,不会出现被截断的半个 JSON。
10
+ *
11
+ * @module dsh-pluginmarket-plus/lib/store
12
+ */
13
+
14
+ import { createHash } from 'node:crypto'
15
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
16
+ import { join } from 'node:path'
17
+ import { normalizeIndexGitSource } from './updates.js'
18
+
19
+ /** 状态清单版本;结构不兼容变更时递增。 */
20
+ const STATE_VERSION = 1
21
+
22
+ /**
23
+ * 一个索引源的稳定短 id:URL 的 sha256 前 16 位十六进制。
24
+ *
25
+ * 同一 URL 永远得到同一 id,所以镜像地址在重启后保持不变。
26
+ * @param {string} url - 上游索引地址。
27
+ * @returns {string} 16 位十六进制 id。
28
+ */
29
+ export function sourceId(url) {
30
+ return createHash('sha256').update(url, 'utf8').digest('hex').slice(0, 16)
31
+ }
32
+
33
+ /** 一个索引源的缓存状态。 */
34
+ /**
35
+ * @typedef {object} CacheEntry
36
+ * @property {string} url - 上游索引地址。
37
+ * @property {number} [fetchedAt] - 最近一次成功抓取的 Unix 毫秒时间。
38
+ * @property {number} [bytes] - 正文字节数。
39
+ * @property {number} [plugins] - 插件条数。
40
+ * @property {unknown} [title] - 索引自带的标题(LocalizedText)。
41
+ * @property {string|null} [error] - 最近一次失败原因;成功后清空。
42
+ * @property {number} [errorAt] - 最近一次失败的 Unix 毫秒时间。
43
+ */
44
+
45
+ /** 正文与清单的读写。 */
46
+ export class CacheStore {
47
+ /**
48
+ * @param {string} dir - 缓存目录绝对路径。
49
+ */
50
+ constructor(dir) {
51
+ this.dir = dir
52
+ this.state = { version: STATE_VERSION, sources: [], entries: {} }
53
+ /** @type {{signature: string, size: number, names: Map<string, object[]>}|undefined} 上次解析出来的索引查询表。 */
54
+ this.#indexCache = undefined
55
+ mkdirSync(dir, { recursive: true })
56
+ this.#load()
57
+ }
58
+
59
+ /** @type {{signature: string, size: number, names: Map<string, object[]>}|undefined} */
60
+ #indexCache
61
+
62
+ /** 读取清单;损坏或缺失时以空清单开始(缓存是派生数据,可以重建)。 */
63
+ #load() {
64
+ try {
65
+ const raw = readFileSync(join(this.dir, 'state.json'), 'utf8')
66
+ const parsed = JSON.parse(raw)
67
+ if (parsed === null || typeof parsed !== 'object' || parsed.version !== STATE_VERSION) return
68
+ const entries = parsed.entries !== null && typeof parsed.entries === 'object' && !Array.isArray(parsed.entries)
69
+ ? parsed.entries
70
+ : {}
71
+ this.state = {
72
+ version: STATE_VERSION,
73
+ sources: Array.isArray(parsed.sources) ? parsed.sources.filter(url => typeof url === 'string') : [],
74
+ entries,
75
+ }
76
+ } catch {
77
+ // 首次运行或清单损坏:保持空状态。旧正文文件会被下一次抓取覆盖。
78
+ }
79
+ }
80
+
81
+ /** 原子写回清单。 */
82
+ save() {
83
+ const target = join(this.dir, 'state.json')
84
+ const tmp = `${target}.tmp-${String(process.pid)}-${String(Date.now())}`
85
+ writeFileSync(tmp, JSON.stringify(this.state, null, 2), 'utf8')
86
+ renameSync(tmp, target)
87
+ }
88
+
89
+ /** @returns {string[]} 没有活跃配置时保留的源列表(首次从插件市场接管时写入)。 */
90
+ get sources() {
91
+ return this.state.sources.slice()
92
+ }
93
+
94
+ /**
95
+ * @param {string[]} urls - 要记住的源列表。
96
+ */
97
+ set sources(urls) {
98
+ this.state.sources = urls.slice()
99
+ }
100
+
101
+ /**
102
+ * @param {string} id - 源 id。
103
+ * @returns {CacheEntry|undefined} 该源的缓存状态。
104
+ */
105
+ entry(id) {
106
+ return this.state.entries[id]
107
+ }
108
+
109
+ /**
110
+ * 合并写入一条状态。
111
+ * @param {string} id - 源 id。
112
+ * @param {Partial<CacheEntry>} patch - 要合并的字段。
113
+ * @returns {void}
114
+ */
115
+ update(id, patch) {
116
+ this.state.entries[id] = { ...this.state.entries[id], ...patch }
117
+ }
118
+
119
+ /**
120
+ * @param {string} id - 源 id。
121
+ * @returns {boolean} 是否有可用的正文文件。
122
+ */
123
+ hasBody(id) {
124
+ return existsSync(join(this.dir, `index-${id}.json`))
125
+ }
126
+
127
+ /**
128
+ * @param {string} id - 源 id。
129
+ * @returns {Buffer|undefined} 正文;缺失时 undefined。
130
+ */
131
+ readBody(id) {
132
+ try {
133
+ return readFileSync(join(this.dir, `index-${id}.json`))
134
+ } catch {
135
+ return undefined
136
+ }
137
+ }
138
+
139
+ /**
140
+ * 原子写入正文。
141
+ * @param {string} id - 源 id。
142
+ * @param {Buffer} bytes - 正文。
143
+ * @returns {void}
144
+ */
145
+ writeBody(id, bytes) {
146
+ const target = join(this.dir, `index-${id}.json`)
147
+ const tmp = `${target}.tmp-${String(process.pid)}-${String(Date.now())}`
148
+ writeFileSync(tmp, bytes)
149
+ renameSync(tmp, target)
150
+ this.#indexCache = undefined
151
+ }
152
+
153
+ /**
154
+ * 删除一个源的正文与状态(源被移除时调用)。
155
+ * @param {string} id - 源 id。
156
+ * @returns {void}
157
+ */
158
+ remove(id) {
159
+ delete this.state.entries[id]
160
+ try {
161
+ rmSync(join(this.dir, `index-${id}.json`), { force: true })
162
+ } catch {
163
+ // 删除失败不影响后续逻辑;下次写入会覆盖。
164
+ }
165
+ this.#indexCache = undefined
166
+ }
167
+
168
+ /**
169
+ * 所有已缓存正文的源 id。
170
+ *
171
+ * 先按源列表与状态清单的顺序取,再扫一遍目录补上清单里没记到的正文文件——这样清单损坏或
172
+ * 被别的进程改写时,已下载的索引仍然可用。
173
+ * @returns {string[]} 源 id 列表。
174
+ */
175
+ cachedIds() {
176
+ /** @type {string[]} */
177
+ const ids = []
178
+ const push = (id) => {
179
+ if (!ids.includes(id) && this.hasBody(id)) ids.push(id)
180
+ }
181
+ for (const url of this.state.sources) push(sourceId(url))
182
+ for (const id of Object.keys(this.state.entries)) push(id)
183
+ let names = []
184
+ try {
185
+ names = readdirSync(this.dir)
186
+ } catch {
187
+ names = []
188
+ }
189
+ for (const name of names) {
190
+ const match = /^index-([a-f0-9]{16})\.json$/u.exec(name)
191
+ if (match !== null) push(match[1])
192
+ }
193
+ return ids
194
+ }
195
+
196
+ /**
197
+ * 一份已缓存索引的签名:正文文件的大小与修改时间。
198
+ *
199
+ * 索引动辄几 MB,解析一次要几百毫秒;用签名判断「有没有变过」,没变就直接复用上次解析结果。
200
+ * @returns {string} 形如 `id:bytes:mtime` 的签名串。
201
+ */
202
+ indexSignature() {
203
+ const parts = []
204
+ for (const id of this.cachedIds()) {
205
+ try {
206
+ const stat = statSync(join(this.dir, `index-${id}.json`))
207
+ parts.push(`${id}:${String(stat.size)}:${String(stat.mtimeMs)}`)
208
+ } catch {
209
+ parts.push(`${id}:missing`)
210
+ }
211
+ }
212
+ return parts.join('|')
213
+ }
214
+
215
+ /**
216
+ * 把已缓存的索引读成「包名 → 版本来源」的查询表。
217
+ *
218
+ * 只读取 `plugins[].versions[]` 里更新判断需要的字段(版本号、发布时间、`source`),
219
+ * 正文损坏或格式不符的源直接跳过——缓存是派生数据,坏一份不该影响其它源。
220
+ * @returns {{signature: string, size: number, names: Map<string, object[]>}} 查询表;`size` 是收录的包数量。
221
+ */
222
+ cachedIndex() {
223
+ const signature = this.indexSignature()
224
+ if (this.#indexCache !== undefined && this.#indexCache.signature === signature) return this.#indexCache
225
+ /** @type {Map<string, object[]>} */
226
+ const names = new Map()
227
+ for (const id of this.cachedIds()) {
228
+ let document
229
+ try {
230
+ document = JSON.parse(readFileSync(join(this.dir, `index-${id}.json`), 'utf8'))
231
+ } catch {
232
+ continue
233
+ }
234
+ if (document === null || typeof document !== 'object' || document.format !== 1 || !Array.isArray(document.plugins)) continue
235
+ for (const plugin of document.plugins) {
236
+ if (plugin === null || typeof plugin !== 'object' || typeof plugin.name !== 'string' || !Array.isArray(plugin.versions)) continue
237
+ const versions = names.get(plugin.name) ?? []
238
+ for (const version of plugin.versions) {
239
+ if (version === null || typeof version !== 'object' || typeof version.version !== 'string') continue
240
+ const source = version.source
241
+ if (source === null || typeof source !== 'object') continue
242
+ if (source.type === 'npm') {
243
+ versions.push({ version: version.version, type: 'npm', publishTimestamp: Number(version.publishTimestamp ?? 0) })
244
+ continue
245
+ }
246
+ if (source.type !== 'git') continue
247
+ const git = normalizeIndexGitSource(source)
248
+ if (git === undefined) continue
249
+ versions.push({ version: version.version, type: 'git', publishTimestamp: Number(version.publishTimestamp ?? 0), git })
250
+ }
251
+ names.set(plugin.name, versions)
252
+ }
253
+ }
254
+ this.#indexCache = { signature, size: names.size, names }
255
+ return this.#indexCache
256
+ }
257
+ }