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/store.js ADDED
@@ -0,0 +1,254 @@
1
+ /**
2
+ * Shared paths + state persistence for the plugin hub.
3
+ *
4
+ * Layout (all under DSH_HOME / agent-skills):
5
+ * state.json — sources + install records
6
+ * market/<sourceId>/ — per-source git clone cache
7
+ * installed/<name>/ — installed plugin copies
8
+ */
9
+ import { homedir } from 'node:os'
10
+ import { dirname, join } from 'node:path'
11
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, statSync, rmSync } from 'node:fs'
12
+ import { execFileSync } from 'node:child_process'
13
+
14
+ /** Robust directory deletion handling Windows readonly/locked files. */
15
+ export function safeRmDir(dir) {
16
+ if (!dir || !existsSync(dir)) return
17
+ try {
18
+ rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 })
19
+ return
20
+ } catch (err) {
21
+ if (process.platform === 'win32') {
22
+ try {
23
+ execFileSync('cmd.exe', ['/c', `attrib -r -s -h "${dir}\\*" /s /d`], { stdio: 'ignore', windowsHide: true })
24
+ rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 })
25
+ return
26
+ } catch {}
27
+ try {
28
+ execFileSync('cmd.exe', ['/c', `rd /s /q "${dir}"`], { stdio: 'ignore', windowsHide: true })
29
+ if (!existsSync(dir)) return
30
+ } catch {}
31
+ try {
32
+ const trash = `${dir}.trash-${Date.now()}`
33
+ renameSync(dir, trash)
34
+ try {
35
+ execFileSync('cmd.exe', ['/c', `rd /s /q "${trash}"`], { stdio: 'ignore', windowsHide: true })
36
+ } catch {}
37
+ return
38
+ } catch {}
39
+ }
40
+ }
41
+ }
42
+
43
+ let STATE_CACHE = null
44
+ let STATE_CACHE_MTIME = 0
45
+
46
+ export const ROOT_DIR_NAME = 'universal-plugin-hub'
47
+
48
+ export function dshHome() {
49
+ return process.env.DSH_HOME || join(homedir(), '.dsh')
50
+ }
51
+
52
+ export function dshSkillsDir() {
53
+ return join(dshHome(), 'skills')
54
+ }
55
+
56
+ export function marketRoot() {
57
+ return join(dshHome(), 'agent-skills', ROOT_DIR_NAME)
58
+ }
59
+
60
+ export function statePath() {
61
+ return join(marketRoot(), 'state.json')
62
+ }
63
+
64
+ export function sourceCacheDir(sourceId) {
65
+ return join(marketRoot(), 'market', sourceId)
66
+ }
67
+
68
+ export function installedDir(name) {
69
+ return join(marketRoot(), 'installed', name)
70
+ }
71
+
72
+ /** Default state: the built-in Anthropic source. */
73
+ export function defaultState() {
74
+ return {
75
+ version: 1,
76
+ sources: [
77
+ {
78
+ id: 'anthropic',
79
+ name: 'Anthropic',
80
+ url: 'https://github.com/anthropics/claude-plugins-official.git',
81
+ builtin: true,
82
+ addedAt: Date.now(),
83
+ },
84
+ ],
85
+ plugins: [],
86
+ }
87
+ }
88
+
89
+ /** Read state.json with 0ms in-memory cache and mtime invalidation. */
90
+ export function readState() {
91
+ const path = statePath()
92
+ if (!existsSync(path)) {
93
+ const fresh = defaultState()
94
+ writeState(fresh)
95
+ return fresh
96
+ }
97
+ try {
98
+ const stat = statSync(path)
99
+ if (STATE_CACHE && STATE_CACHE_MTIME === stat.mtimeMs) {
100
+ return STATE_CACHE
101
+ }
102
+ const parsed = JSON.parse(readFileSync(path, 'utf8'))
103
+ const base = defaultState()
104
+ const merged = {
105
+ ...base,
106
+ ...parsed,
107
+ sources: Array.isArray(parsed.sources) ? parsed.sources : base.sources,
108
+ plugins: Array.isArray(parsed.plugins) ? parsed.plugins : [],
109
+ }
110
+ STATE_CACHE = merged
111
+ STATE_CACHE_MTIME = stat.mtimeMs
112
+ return merged
113
+ } catch {
114
+ return defaultState()
115
+ }
116
+ }
117
+
118
+ export function writeState(state) {
119
+ const file = statePath()
120
+ mkdirSync(dirname(file), { recursive: true })
121
+ const tmp = join(dirname(file), `.state.${process.pid}.${Date.now().toString(36)}.tmp`)
122
+ writeFileSync(tmp, JSON.stringify(state, null, 2), 'utf8')
123
+ renameSync(tmp, file)
124
+ STATE_CACHE = state
125
+ try {
126
+ STATE_CACHE_MTIME = statSync(file).mtimeMs
127
+ } catch {
128
+ STATE_CACHE_MTIME = Date.now()
129
+ }
130
+ }
131
+
132
+ /** Safe slug: only [a-z0-9-], lowercased; used for ids and directory names. */
133
+ export function slugify(value) {
134
+ return String(value)
135
+ .toLowerCase()
136
+ .replace(/[^a-z0-9]+/g, '-')
137
+ .replace(/^-+|-+$/g, '')
138
+ }
139
+
140
+ /** Normalize shorthand (e.g. anthropics/claude-plugins-community) and various git URL formats to standard https */
141
+ export function normalizeGitRepoUrl(raw) {
142
+ let s = String(raw || '').trim().replace(/^['"]|['"]$/g, '')
143
+ if (!s) return ''
144
+
145
+ // 1. SSH format: git@github.com:owner/repo.git -> https://github.com/owner/repo.git
146
+ const sshMatch = s.match(/^git@([^:]+):([^/]+)\/(.+?)(\.git)?$/)
147
+ if (sshMatch) {
148
+ return `https://${sshMatch[1]}/${sshMatch[2]}/${sshMatch[3]}.git`
149
+ }
150
+
151
+ // 2. Full HTTP(S) URL
152
+ if (/^https?:\/\//i.test(s)) {
153
+ // Handle GitHub tree/blob URLs: https://github.com/owner/repo/tree/main -> https://github.com/owner/repo.git
154
+ const treeMatch = s.match(/^(https?:\/\/[^/]+\/[^/]+\/[^/]+)\/(?:tree|blob)\/.+$/i)
155
+ if (treeMatch) {
156
+ s = treeMatch[1]
157
+ }
158
+ if (!s.endsWith('.git') && /github\.com|gitlab\.com|gitee\.com/i.test(s)) {
159
+ s = `${s}.git`
160
+ }
161
+ return s
162
+ }
163
+
164
+ // 3. Domain prefix without protocol: github.com/owner/repo
165
+ const domainMatch = s.match(/^([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})\/([^/]+)\/([^/]+?)(\.git)?$/)
166
+ if (domainMatch) {
167
+ return `https://${domainMatch[1]}/${domainMatch[2]}/${domainMatch[3]}.git`
168
+ }
169
+
170
+ // 4. Shorthand owner/repo: anthropics/claude-plugins-community
171
+ const shorthandMatch = s.match(/^([a-zA-Z0-9._-]+)\/([a-zA-Z0-9._-]+?)(\.git)?$/)
172
+ if (shorthandMatch) {
173
+ return `https://github.com/${shorthandMatch[1]}/${shorthandMatch[2]}.git`
174
+ }
175
+
176
+ return s
177
+ }
178
+
179
+ /** Parse a git URL into { owner, repo } when possible. */
180
+ export function parseGitUrl(url) {
181
+ const norm = normalizeGitRepoUrl(url)
182
+ const match = norm.match(/(?:github\.com|gitlab\.com|gitee\.com)[:/]([^/]+)\/([^/]+?)(?:\.git)?$/i)
183
+ if (match) {
184
+ return { owner: match[1], repo: match[2] }
185
+ }
186
+ const genericMatch = norm.match(/https?:\/\/[^/]+\/([^/]+)\/([^/]+?)(?:\.git)?$/i)
187
+ if (genericMatch) {
188
+ return { owner: genericMatch[1], repo: genericMatch[2] }
189
+ }
190
+ return null
191
+ }
192
+
193
+ /** Suggested display name for a source: repo name simplified & capitalized; official repo → "Anthropic". */
194
+ export function suggestSourceName(url) {
195
+ const parsed = parseGitUrl(url)
196
+ if (!parsed) {
197
+ const raw = String(url).split('/').pop()?.replace(/\.git$/, '') || 'Custom'
198
+ return raw.charAt(0).toUpperCase() + raw.slice(1)
199
+ }
200
+ const { owner, repo } = parsed
201
+ const ownerLower = (owner || '').toLowerCase()
202
+ const repoLower = (repo || '').toLowerCase()
203
+
204
+ if (repoLower === 'claude-plugins-official' || ownerLower === 'anthropics') return 'Anthropic'
205
+ if (repoLower === 'claude-plugins-community') return 'Community'
206
+
207
+ const genericRepoNames = new Set([
208
+ 'skills', 'plugins', 'agents', 'tools', 'marketplace', 'hub',
209
+ 'claude-skills', 'claude-plugins', 'claude-agents', 'dsh-plugins', 'extensions', 'packages',
210
+ ])
211
+
212
+ // If repo is generic (e.g. "skills", "plugins", "tools"), use capitalized owner (e.g. Mattpocock)
213
+ if (genericRepoNames.has(repoLower) && owner) {
214
+ return owner.charAt(0).toUpperCase() + owner.slice(1)
215
+ }
216
+
217
+ const simplified = repo
218
+ .replace(/^(claude|dsh|anthropic)[-_]?(plugins?)?[-_]?/i, '')
219
+ .replace(/[-_]?(plugins?|skills?|agents?|official|marketplace)$/i, '')
220
+ const name = simplified || repo
221
+ return name.charAt(0).toUpperCase() + name.slice(1)
222
+ }
223
+
224
+ /** Find an existing source that duplicates the given id, normalized URL, or git repo. */
225
+ export function findDuplicateSource(state, id, url) {
226
+ if (!state || !Array.isArray(state.sources)) return null
227
+ const normUrl = normalizeGitRepoUrl(url).toLowerCase()
228
+ const parsed = parseGitUrl(normUrl)
229
+ const normId = slugify(id || '').toLowerCase()
230
+
231
+ for (const s of state.sources) {
232
+ if (!s) continue
233
+ // 1. Exact or case-insensitive ID match
234
+ if (s.id && normId && s.id.toLowerCase() === normId) return s
235
+
236
+ // 2. Normalized Git URL match
237
+ const sNormUrl = normalizeGitRepoUrl(s.url).toLowerCase()
238
+ if (sNormUrl && normUrl && sNormUrl === normUrl) return s
239
+
240
+ // 3. Same Git owner & repo
241
+ if (parsed && s.url) {
242
+ const sParsed = parseGitUrl(s.url)
243
+ if (
244
+ sParsed &&
245
+ sParsed.owner.toLowerCase() === parsed.owner.toLowerCase() &&
246
+ sParsed.repo.toLowerCase() === parsed.repo.toLowerCase()
247
+ ) {
248
+ return s
249
+ }
250
+ }
251
+ }
252
+ return null
253
+ }
254
+