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/src/icons.js ADDED
@@ -0,0 +1,123 @@
1
+ import { statSync, realpathSync, readFileSync } from 'node:fs'
2
+ import { mkdir, readFile, writeFile, stat } from 'node:fs/promises'
3
+ import { join, relative, isAbsolute, posix } from 'node:path'
4
+ import { createHash } from 'node:crypto'
5
+ import { marketRoot } from './store.js'
6
+ import { pluginPath } from './market.js'
7
+
8
+ const MAX_BYTES = 2 * 1024 * 1024
9
+ const CACHE_TTL = 7 * 24 * 60 * 60 * 1000
10
+ const memory = new Map()
11
+ const pending = new Map()
12
+ const failures = new Map()
13
+
14
+ export function imageContentType(buffer) {
15
+ if (!buffer?.length) return null
16
+ if (buffer.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return 'image/png'
17
+ if (buffer[0] === 255 && buffer[1] === 216 && buffer[2] === 255) return 'image/jpeg'
18
+ if (/^GIF8[79]a/.test(buffer.subarray(0, 6).toString())) return 'image/gif'
19
+ if (buffer.subarray(0, 4).toString() === 'RIFF' && buffer.subarray(8, 12).toString() === 'WEBP') return 'image/webp'
20
+ if (buffer.subarray(4, 8).toString() === 'ftyp' && /avif|avis/.test(buffer.subarray(8, 32).toString())) return 'image/avif'
21
+ if (buffer[0] === 0 && buffer[1] === 0 && buffer[2] === 1 && buffer[3] === 0) return 'image/x-icon'
22
+ const head = buffer.subarray(0, 4096).toString('utf8').replace(/^\uFEFF/, '').trim()
23
+ if (/^(?:<\?xml[^>]*>\s*)?(?:<!--[\s\S]*?-->\s*)*<svg[\s>]/i.test(head)) return 'image/svg+xml'
24
+ return null
25
+ }
26
+
27
+ export function readLocalIcon(root, path) {
28
+ const file = realpathSync(pluginPath(root, path))
29
+ const rel = relative(realpathSync(root), file)
30
+ if (isAbsolute(rel) || rel === '..' || rel.startsWith('../') || rel.startsWith('..\\')) throw new Error('Icon is outside plugin directory')
31
+ const info = statSync(file)
32
+ if (!info.isFile() || info.size > MAX_BYTES) throw new Error('Invalid icon size')
33
+ const buffer = readFileSync(file)
34
+ const contentType = imageContentType(buffer)
35
+ if (!contentType) throw new Error('Unsupported icon content')
36
+ return { buffer, contentType }
37
+ }
38
+
39
+ /** Carry manifest assets through marketplace rows without exposing filesystem paths. */
40
+ export function buildPluginIcons(meta, { sourceId, name, dir, source } = {}) {
41
+ const ui = meta?.interface || {}
42
+ const proxy = (url) => `/universal-plugin-hub/api/icon?v=2&u=${encodeURIComponent(url)}`
43
+ const toUrl = (value) => {
44
+ if (typeof value !== 'string' || !value.trim()) return null
45
+ if (/^https?:\/\//i.test(value)) return proxy(value)
46
+ if (/^data:image\/(png|jpeg|gif|webp|avif|svg\+xml);/i.test(value) && value.length <= MAX_BYTES) return value
47
+ if (dir) {
48
+ try {
49
+ const file = pluginPath(dir, value)
50
+ const info = statSync(file)
51
+ if (!info.isFile() || info.size > MAX_BYTES) return null
52
+ return `/universal-plugin-hub/api/plugin-icon?sourceId=${encodeURIComponent(sourceId)}&name=${encodeURIComponent(name)}&path=${encodeURIComponent(value)}&v=${info.mtimeMs}-${info.size}`
53
+ } catch { return null }
54
+ }
55
+ const repo = source?.url?.match(/^https:\/\/github\.com\/([^/]+)\/([^/#?]+?)(?:\.git)?\/?$/i)
56
+ if (repo && !isAbsolute(value) && !/^[a-z]:|^\\/i.test(value)) {
57
+ const path = posix.normalize(posix.join(source.path || '', value))
58
+ if (path === '..' || path.startsWith('../')) return null
59
+ const ref = source.sha || source.ref || 'HEAD'
60
+ return proxy(`https://raw.githubusercontent.com/${repo[1]}/${repo[2]}/${encodeURIComponent(ref)}/${path.split('/').map(encodeURIComponent).join('/')}`)
61
+ }
62
+ return null
63
+ }
64
+ const common = [ui.composerIcon, ui.icon, ui.iconSmall, ui.iconLarge, ui.logo, meta?.icon, meta?.iconUrl, meta?.logo]
65
+ const values = (theme) => common.flatMap((v) => typeof v === 'object' && v ? [v[theme], v.default, v.url, v.src, v[theme === 'dark' ? 'light' : 'dark']] : [v])
66
+ const defaults = dir ? ['assets/icon.svg', 'assets/logo.svg', 'assets/icon.png', 'assets/logo.png', 'icon.svg', 'logo.svg', 'icon.png', 'logo.png'] : []
67
+ const light = [...new Set([ui.iconLight, ui.logoLight, meta?.iconLight, ...values('light'), ...defaults].map(toUrl).filter(Boolean))]
68
+ const dark = [...new Set([ui.iconDark, ui.logoDark, meta?.iconDark, ...values('dark'), ...defaults].map(toUrl).filter(Boolean))]
69
+ return { light, dark }
70
+ }
71
+
72
+ function remember(key, value) {
73
+ if (memory.size >= 256) memory.delete(memory.keys().next().value)
74
+ memory.set(key, { ...value, time: Date.now() })
75
+ return value
76
+ }
77
+
78
+ /** Share concurrent loads, cache successful images, and briefly suppress failed URLs. */
79
+ export async function getOrFetchIcon(url) {
80
+ if (typeof url !== 'string' || !/^https?:\/\//i.test(url)) throw new Error('Invalid icon URL')
81
+ // Named paths on the avatar CDN return a generic image; GitHub resolves the
82
+ // account name to the actual numeric avatar URL before redirecting.
83
+ const parsed = new URL(url)
84
+ if (parsed.hostname === 'avatars.githubusercontent.com' && /^\/[a-z0-9_-]+\/?$/i.test(parsed.pathname)) {
85
+ url = `https://github.com/${parsed.pathname.split('/')[1]}.png?size=${parsed.searchParams.get('s') || '80'}`
86
+ }
87
+ const cached = memory.get(url)
88
+ if (cached && Date.now() - cached.time < CACHE_TTL) return cached
89
+ if (failures.get(url) > Date.now()) throw new Error('Icon temporarily unavailable')
90
+ if (pending.has(url)) return pending.get(url)
91
+ const task = (async () => {
92
+ const file = join(marketRoot(), 'icons', `icon_${createHash('md5').update(url).digest('hex')}.bin`)
93
+ try {
94
+ const info = await stat(file)
95
+ if (info.size <= MAX_BYTES && Date.now() - info.mtimeMs < CACHE_TTL) {
96
+ const buffer = await readFile(file)
97
+ const contentType = imageContentType(buffer)
98
+ if (contentType) return remember(url, { buffer, contentType })
99
+ }
100
+ } catch {}
101
+ const response = await fetch(url, { signal: AbortSignal.timeout(4000), headers: { Accept: 'image/avif,image/webp,image/svg+xml,image/*;q=0.8' } })
102
+ if (!response.ok) throw new Error(`Icon request failed: ${response.status}`)
103
+ if (Number(response.headers.get('content-length')) > MAX_BYTES) { await response.body?.cancel(); throw new Error('Icon too large') }
104
+ const chunks = []
105
+ let size = 0
106
+ for await (const chunk of response.body) {
107
+ size += chunk.length
108
+ if (size > MAX_BYTES) throw new Error('Icon too large')
109
+ chunks.push(chunk)
110
+ }
111
+ const buffer = Buffer.concat(chunks)
112
+ const contentType = imageContentType(buffer)
113
+ if (!contentType) throw new Error('Unsupported icon content')
114
+ try { await mkdir(join(marketRoot(), 'icons'), { recursive: true }); await writeFile(file, buffer) } catch {}
115
+ return remember(url, { buffer, contentType })
116
+ })()
117
+ pending.set(url, task)
118
+ try { return await task } catch (error) {
119
+ if (failures.size >= 256) failures.delete(failures.keys().next().value)
120
+ failures.set(url, Date.now() + 60_000)
121
+ throw error
122
+ } finally { pending.delete(url) }
123
+ }
package/src/index.js ADDED
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Plugin entry point: mounts the HTTP routes once the profile composes
3
+ * the webServer service. The 5 host packages that every LSP/hook-bridged
4
+ * plugin will need (dsh-lsp, dsh-lsp-stdio, dsh-tool-lsp, dsh-hooks-claude-code,
5
+ * dsh-hook-protocol) are provisioned on startup; `scripts/postinstall.js`
6
+ * does the same during `dsh plugin add`, but package managers gate install
7
+ * scripts behind an approval prompt, so startup is the reliable path.
8
+ */
9
+ import { mountRoutes } from './routes.js'
10
+ import { syncAllInstalledSkillsToDsh, installProfilePackages, LSP_HOST_PACKAGES, HOOK_HOST_PACKAGES } from './install.js'
11
+
12
+ export const name = 'universal-plugin-hub'
13
+
14
+ export function apply(ctx) {
15
+ // Ensure all installed plugin skills are immediately synced to $DSH_HOME/skills
16
+ try {
17
+ syncAllInstalledSkillsToDsh()
18
+ } catch (err) {
19
+ ctx.logger?.warn?.(`[universal-plugin-hub] skill sync error: ${err.message}`)
20
+ }
21
+
22
+ // Host packages disappear when a package manager re-resolves the profile
23
+ // (pnpm moves unrecognized packages to node_modules/.ignored), so repair
24
+ // them on every start instead of trusting a one-time install step.
25
+ installProfilePackages([...LSP_HOST_PACKAGES, ...HOOK_HOST_PACKAGES]).catch((err) => {
26
+ ctx.logger?.warn?.(`[universal-plugin-hub] host package provisioning skipped: ${err.message}`)
27
+ })
28
+
29
+ ctx.inject(['webServer'], (hostCtx) => {
30
+ hostCtx.effect(() => mountRoutes(hostCtx.webServer), 'universal-plugin-hub: http routes')
31
+ })
32
+ }