@vibedev-si/dsh-vibedev 0.7.3 → 0.8.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.
@@ -1,326 +0,0 @@
1
- /**
2
- * The live update reader for the VibeDev plugins the catalogue names.
3
- *
4
- * The catalogue answers "what do we know about these plugins"; this module answers the other question — what npm
5
- * has now — for the packages it names. Which packages those are comes from ONE of two places, never from the
6
- * request:
7
- *
8
- * - with no catalogue reader wired in, the fixed allow-list below (the three official plugins and this center,
9
- * each with the repository its metadata must name);
10
- * - with a catalogue reader (the host half passes one), the packages of the validated ONLINE catalogue it
11
- * returns: `catalog.plugins` entries that are `origin: 'official'` and are not this center, taking each
12
- * entry's `links.repo` as the repository its npm metadata must name. The reader is trusted to have validated
13
- * those entries (identity, repository shape, no paths); this module only consumes the list, and still
14
- * verifies every package it reads.
15
- * This center itself is always read with its constant repository and is never taken from the catalogue: it
16
- * cannot replace itself while it runs.
17
- *
18
- * Because the catalogue is read through the reader on every handler call, a plugin added to the online catalogue
19
- * becomes visible without a new release of this center. That is also why the update cache is keyed on the
20
- * package-list signature (names, expected repositories, catalogue versions) instead of a fixed list: adding,
21
- * removing or repinning a package starts a fresh read rather than serving the previous set from cache.
22
- *
23
- * Official first: only registry.npmjs.org decides what the newest version is. A mirror answers only when the
24
- * official read failed at the transport level (network error, timeout, a non-ok HTTP status, a body that is
25
- * not JSON), and its answer must pass exactly the same checks; it is reported with `degraded: true` and the
26
- * registry that supplied it. Metadata that arrived and then failed a check is a refusal — not a reason to
27
- * ask somebody else. No answer is ever combined across registries, and no version is compared between them.
28
- *
29
- * One package is accepted only when every one of these holds:
30
- * - the packument names that package;
31
- * - `dist-tags.latest` is a stable `x.y.z` (a prerelease or a range is never an update target);
32
- * - that version exists in `versions`, and its own `name`/`version` are the ones asked for;
33
- * - it carries a non-empty `dsh.bundle.patch` (the plugin manager refuses anything else);
34
- * - its `repository` normalises to the expected https GitHub repository;
35
- * - its `dist.integrity` is a sha512 in npm's shape;
36
- * - npm's publish time for that version parses (a missing or unreadable time is a refusal).
37
- * `sizeKB` comes from `dist.unpackedSize` when that is a positive finite number; a size that differs from
38
- * the catalogue's snapshot is NOT a refusal, because a newer version may legitimately be a different size.
39
- *
40
- * Nothing here runs on import: the only outbound requests are the packuments `read()` asks for, which the
41
- * `/vdc/updates` handler calls for a GET. A fully successful answer is cached for a minute; a failure is never
42
- * cached, so the next click tries again. Concurrent reads share one batch, so a double click cannot multiply the
43
- * requests. At most {@link MAX_PLUGINS} catalogue packages are read, {@link CONCURRENCY} at a time, and this
44
- * center counts as one of them; the whole batch is bounded by {@link BATCH_BUDGET_MS}.
45
- */
46
-
47
- /** This center. It is NOT a catalogue entry: the center cannot replace itself while it runs. */
48
- export const SELF_NAME = '@vibedev-si/dsh-ecosystem'
49
-
50
- /**
51
- * The packages this center may read from npm, each with the repository its metadata must name. Fixed here on
52
- * purpose: the page cannot name a package, and the catalogue cannot add one.
53
- */
54
- export const ALLOWLIST = {
55
- plugins: [
56
- { name: '@vibedev-si/dsh-vibedev', repo: 'https://github.com/VibeDev-Si/dsh-vibedev' },
57
- { name: 'dsh-film', repo: 'https://github.com/VibeDev-Si/dsh-film' },
58
- { name: '@vibedev-si/dsh-media-viewer', repo: 'https://github.com/VibeDev-Si/dsh-media-viewer' },
59
- ],
60
- self: { name: SELF_NAME, repo: 'https://github.com/VibeDev-Si/dsh-ecosystem' },
61
- }
62
-
63
- /** The two registries, in the order they are trusted: the official one first, the mirror only as a fallback. */
64
- export const REGISTRIES = ['https://registry.npmjs.org/', 'https://registry.npmmirror.com/']
65
-
66
- /** How many catalogue packages one read may cover, and how many of them may be in flight at once. */
67
- export const MAX_PLUGINS = 40
68
- export const CONCURRENCY = 4
69
-
70
- /**
71
- * The whole metadata batch has to finish inside this, however long the queue is: with forty packages four at a
72
- * time on a slow network the tail would otherwise keep the screen waiting for minutes. Once it is spent, no new
73
- * packument is requested, whatever is still in flight is aborted, and the rows that never answered are reported
74
- * as failures — never as current versions.
75
- */
76
- export const BATCH_BUDGET_MS = 20_000
77
-
78
- /** A stable release only: no prerelease, no build metadata, no range. */
79
- const STABLE = /^\d+\.\d+\.\d+$/
80
- /** npm's sha512 integrity shape. */
81
- const INTEGRITY = /^sha512-[A-Za-z0-9+/]+={0,2}$/
82
- const TIMEOUT_MS = 8000
83
- const CACHE_MS = 60_000
84
- const MAX_ERROR = 120
85
-
86
- /**
87
- * One `repository` field (a string or `{url}`) normalised for comparison: the transport prefix dropped and
88
- * the trailing `.git`/slashes removed, so `git+https://github.com/x/y.git` and `https://github.com/x/y`
89
- * compare equal. Only an https GitHub URL can ever equal an expected repository, which is what makes the
90
- * comparison a check rather than a formality.
91
- * @param value - the packument's repository field.
92
- * @returns the normalised URL, or undefined when there is nothing usable.
93
- */
94
- export function normalizeRepo(value) {
95
- const raw = typeof value === 'string' ? value : (value && typeof value.url === 'string' ? value.url : undefined)
96
- if (typeof raw !== 'string') return undefined
97
- return raw.trim()
98
- .replace(/^git\+/, '')
99
- .replace(/^git:\/\//, 'https://')
100
- .replace(/^ssh:\/\/git@/, 'https://')
101
- .replace(/\/+$/, '')
102
- .replace(/\.git$/, '')
103
- .replace(/\/+$/, '')
104
- }
105
-
106
- /** The error text one failed read carries, bounded like the host's own diagnostics. */
107
- const text = (value) => String(value ?? '').slice(0, MAX_ERROR)
108
-
109
- /**
110
- * Verify one packument answer against one allow-listed entry.
111
- * @param entry - the allow-listed package and its expected repository.
112
- * @param json - the parsed packument.
113
- * @returns the accepted facts, or the reason the answer was refused.
114
- */
115
- export function verifyPackument(entry, json) {
116
- if (!json || typeof json !== 'object') return { error: 'answer is not an object' }
117
- if (json.name !== entry.name) return { error: `answer names ${text(json.name) || 'nothing'}` }
118
- const latest = json['dist-tags']?.latest
119
- if (typeof latest !== 'string' || !STABLE.test(latest)) return { error: `latest ${text(latest) || 'is missing'} is not a stable version` }
120
- const version = json.versions?.[latest]
121
- if (!version || typeof version !== 'object') return { error: `versions has no ${latest}` }
122
- if (version.name !== entry.name || version.version !== latest) return { error: `versions.${latest} names ${text(version.name)}@${text(version.version)}` }
123
- const patch = version.dsh?.bundle?.patch
124
- if (typeof patch !== 'string' || patch.trim() === '') return { error: `${latest} carries no dsh.bundle.patch` }
125
- const repo = normalizeRepo(version.repository ?? json.repository)
126
- if (repo !== entry.repo) return { error: `${latest} names repository ${text(repo) || 'nothing'}` }
127
- const integrity = version.dist?.integrity
128
- if (typeof integrity !== 'string' || !INTEGRITY.test(integrity)) return { error: `${latest} carries no sha512 integrity` }
129
- const at = json.time?.[latest]
130
- if (typeof at !== 'string' || Number.isNaN(Date.parse(at))) return { error: `${latest} has no readable publish time` }
131
- const bytes = version.dist?.unpackedSize
132
- const sizeKB = Number.isFinite(bytes) && bytes > 0 ? Math.round(bytes / 1024) : undefined
133
- return { version: latest, publishedAt: new Date(at).toISOString(), integrity, sizeKB }
134
- }
135
-
136
- /**
137
- * Read one registry for one entry. Never throws; the state decides what the caller may do next:
138
- * `ok` (verified), `refused` (metadata arrived and failed a check — nobody else may answer instead) or
139
- * `unavailable` (the transport failed, so the next registry may be asked).
140
- * @param base - registry base URL, without the package name.
141
- * @param entry - the package to read.
142
- * @param doFetch - the fetch to use.
143
- * @param signal - the batch's signal: when the budget is spent, an in-flight request is cut off with it.
144
- * @returns one source record for the answer's `sources`.
145
- */
146
- async function readSource(base, entry, doFetch, signal) {
147
- const t0 = Date.now()
148
- const done = (o) => ({ registry: base, ms: Date.now() - t0, ...o })
149
- try {
150
- const r = await doFetch(base + entry.name.replace('/', '%2F'), {
151
- headers: { accept: 'application/json' },
152
- // Both bounds apply: this request's own timeout, and the batch's remaining budget.
153
- signal: signal === undefined ? AbortSignal.timeout(TIMEOUT_MS) : AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), signal]),
154
- redirect: 'error',
155
- })
156
- if (!r.ok) return done({ state: 'unavailable', error: `HTTP ${r.status}` })
157
- let json
158
- try { json = await r.json() } catch { return done({ state: 'unavailable', error: 'answer is not JSON' }) }
159
- const verdict = verifyPackument(entry, json)
160
- return verdict.error === undefined ? done({ state: 'ok', ...verdict }) : done({ state: 'refused', error: verdict.error })
161
- } catch (e) {
162
- return done({ state: 'unavailable', error: text(e?.name === 'TimeoutError' || e?.name === 'AbortError' ? 'timeout' : e?.cause?.code ?? e?.message ?? e) })
163
- }
164
- }
165
-
166
- /** Every source record without the state, which is internal to this module. */
167
- const publicSource = ({ state: _state, ...rest }) => rest
168
-
169
- /**
170
- * Read one package once, official first.
171
- * @param entry - the package to read.
172
- * @param doFetch - the fetch to use.
173
- * @param now - the clock, injected so tests can move time.
174
- * @param signal - the batch's signal.
175
- * @returns one package answer in the shape the route publishes.
176
- */
177
- async function readPackage(entry, doFetch, now, signal) {
178
- const sources = []
179
- const first = await readSource(REGISTRIES[0], entry, doFetch, signal)
180
- sources.push(first)
181
- let answer = first
182
- let degraded = false
183
- if (first.state === 'unavailable') {
184
- // Only a transport failure falls back: metadata that failed a check is this package's answer.
185
- const second = await readSource(REGISTRIES[1], entry, doFetch, signal)
186
- sources.push(second)
187
- answer = second
188
- degraded = second.state === 'ok'
189
- }
190
- const checkedAt = new Date(now()).toISOString()
191
- const base = { name: entry.name, ok: answer.state === 'ok', checkedAt, sources: sources.map(publicSource) }
192
- if (answer.state !== 'ok') return { ...base, registry: answer.registry, error: answer.error }
193
- return {
194
- ...base,
195
- version: answer.version,
196
- publishedAt: answer.publishedAt,
197
- integrity: answer.integrity,
198
- ...(answer.sizeKB === undefined ? {} : { sizeKB: answer.sizeKB }),
199
- registry: answer.registry,
200
- ...(degraded ? { degraded: true } : {}),
201
- }
202
- }
203
-
204
- /**
205
- * Build one reader: it owns the cache and the in-flight batch, so every call for a fresh answer goes through
206
- * the same two gates.
207
- * @param doFetch - the fetch to use; the host passes its own (with a test hook in front of the real one).
208
- * @param now - the clock in milliseconds; defaults to `Date.now`.
209
- * @param catalogReader - optional `{ read(): Promise<{catalog, source, checkedAt, error?, stale?}> }`, the
210
- * validated online catalogue. Without it the fixed {@link ALLOWLIST} is read; with it, the catalogue decides
211
- * which packages are read (this center always is), and the answer carries the catalogue it was read against.
212
- * @param options - `{ budgetMs }`: the whole batch's bound. Tests lower it; the host never sets it.
213
- * @returns the reader, whose `read()` answers the whole batch.
214
- */
215
- export function createUpdatesReader(doFetch, now = Date.now, catalogReader, options = {}) {
216
- let cache // {signature, at, body}: a fully successful answer, kept for a minute
217
- let inflight // {signature, task}: the batch a concurrent caller is already waiting for
218
- const budgetMs = options.budgetMs ?? BATCH_BUDGET_MS
219
-
220
- /**
221
- * What to read: the fixed allow-list, or the validated catalogue's official packages plus this center.
222
- * @returns the entries to read (this center last) and the catalogue fields the answer carries.
223
- */
224
- const targets = async () => {
225
- if (catalogReader === undefined) return { list: [...ALLOWLIST.plugins, ALLOWLIST.self], meta: {} }
226
- // A reader that throws or answers nonsense falls back to its own bundled catalogue: it may not take the
227
- // whole screen down, and the packages it does name are still verified here.
228
- const answer = await Promise.resolve()
229
- .then(() => catalogReader.read())
230
- .catch((error) => ({ source: 'bundled', error: error?.message ?? error }))
231
- const catalog = answer?.catalog
232
- const named = Array.isArray(catalog?.plugins) ? catalog.plugins : undefined
233
- const plugins = (named ?? [])
234
- .filter((p) => p?.origin === 'official' && typeof p?.npm === 'string' && p.npm !== SELF_NAME)
235
- .slice(0, MAX_PLUGINS)
236
- .map((p) => ({ name: p.npm, repo: normalizeRepo(p.links?.repo), version: typeof p.version === 'string' ? p.version : undefined }))
237
- return {
238
- // A reader that answered with no catalogue at all leaves the fixed allow-list in place: an unreadable
239
- // catalogue must not empty the screen, and those three packages are the ones this center ships knowing.
240
- list: [...(named === undefined ? ALLOWLIST.plugins : plugins), ALLOWLIST.self],
241
- meta: {
242
- ...(catalog && typeof catalog === 'object' ? { catalog } : {}),
243
- catalogSource: typeof answer?.source === 'string' ? answer.source : 'bundled',
244
- ...(answer?.error === undefined ? {} : { catalogError: text(answer.error) }),
245
- catalogCheckedAt: typeof answer?.checkedAt === 'string' ? answer.checkedAt : new Date(now()).toISOString(),
246
- ...(answer?.stale === true ? { catalogStale: true } : {}),
247
- },
248
- }
249
- }
250
-
251
- /** The list's identity: a different set of names or repositories is a different read, never a cache hit. */
252
- const signatureOf = (list) => JSON.stringify(list.map((e) => [e.name, e.repo ?? null, e.version ?? null]))
253
-
254
- const readAll = async (list, signature, at, meta) => {
255
- // The budget: once it is spent, no new packument is asked for, the ones in flight are aborted, and the rows
256
- // that never answered are failures. A fake transport that ignores the signal still cannot hold the batch.
257
- const batch = new AbortController()
258
- let spent = false
259
- let fireSpent
260
- const spentSignal = new Promise((resolve) => { fireSpent = resolve })
261
- const timer = setTimeout(() => { spent = true; batch.abort(); fireSpent('spent') }, budgetMs)
262
- const results = new Array(list.length)
263
- let next = 0
264
- /** A row the budget stopped: a failure, with no version claim of any kind. */
265
- const stopped = (entry) => ({ name: entry.name, ok: false, checkedAt: new Date(now()).toISOString(), error: 'timeout', sources: [] })
266
- const readOne = async (entry) => {
267
- if (spent) return stopped(entry)
268
- const raced = await Promise.race([readPackage(entry, doFetch, now, batch.signal), spentSignal])
269
- return raced === 'spent' ? stopped(entry) : raced
270
- }
271
- // A handful at a time, this center included: a catalogue that grew large may not open a connection per entry.
272
- const worker = async () => {
273
- for (;;) {
274
- const index = next++
275
- if (index >= list.length) return
276
- results[index] = await readOne(list[index])
277
- }
278
- }
279
- try {
280
- await Promise.all(Array.from({ length: Math.max(1, Math.min(CONCURRENCY, list.length)) }, worker))
281
- } finally {
282
- clearTimeout(timer)
283
- }
284
- const self = results[results.length - 1]
285
- const plugins = results.slice(0, -1)
286
- const ok = plugins.every((p) => p.ok) && self.ok
287
- const body = {
288
- ok,
289
- // Some, but not all: the screen may name what it knows and must still not claim everything is current.
290
- partial: !ok && (plugins.some((p) => p.ok) || self.ok),
291
- checkedAt: new Date(at).toISOString(),
292
- ...meta,
293
- plugins,
294
- // The center itself is reported apart, and is never a catalogue entry: it cannot replace itself.
295
- self: {
296
- ok: self.ok,
297
- checkedAt: self.checkedAt,
298
- ...(self.ok
299
- ? { latest: self.version, publishedAt: self.publishedAt, registry: self.registry, ...(self.degraded ? { degraded: true } : {}) }
300
- : { registry: self.registry, error: self.error }),
301
- sources: self.sources,
302
- },
303
- }
304
- // Only a fully successful read is cached; a failure must be retried on the next click.
305
- if (ok) cache = { signature, at, body }
306
- return body
307
- }
308
-
309
- return {
310
- async read() {
311
- const { list, meta } = await targets()
312
- const signature = signatureOf(list)
313
- const at = now()
314
- if (cache !== undefined && cache.signature === signature && at - cache.at < CACHE_MS) {
315
- return { ...cache.body, cached: true }
316
- }
317
- // A second click while the first batch is running waits for it instead of reading everything again — but
318
- // only for the same list: a catalogue that changed must not be answered from the previous batch.
319
- if (inflight === undefined || inflight.signature !== signature) {
320
- const task = readAll(list, signature, at, meta).finally(() => { if (inflight?.task === task) inflight = undefined })
321
- inflight = { signature, task }
322
- }
323
- return inflight.task
324
- },
325
- }
326
- }
@@ -1,263 +0,0 @@
1
- /**
2
- * The catalog validator, shared by everything that trusts catalog/catalog.json.
3
- *
4
- * The catalog is the install ALLOW-LIST: the ecosystem installs nothing that is not an entry here,
5
- * so every rule below protects users, not just formatting. It has two callers:
6
- *
7
- * - scripts/validate-catalog.mjs (the maintainer's offline/online check, same rules as before)
8
- * - src/remote-catalog.js (the Host's ONLINE catalog reader: an entry that arrives over
9
- * the network is validated with exactly these rules before a
10
- * single package name from it is trusted)
11
- *
12
- * Pure and dependency-free: no file reads, no network, no globals. `validateCatalog` never throws.
13
- *
14
- * The catalog source is FIXED (the repository's own catalog/catalog.json on the default branch) and
15
- * the names an entry may use are validated here — the reader does not accept a caller-supplied URL
16
- * or an unbounded set of trusted package names. It is deliberately NOT a "these four plugins only"
17
- * list: a new @vibedev-si/* plugin committed to the catalog is picked up without shipping a new
18
- * client, which is the whole point of the online catalog.
19
- */
20
-
21
- /** Hard bounds: a payload over these is refused whole rather than rendered. */
22
- export const CATALOG_LIMITS = {
23
- plugins: 40,
24
- suites: 20,
25
- sizeKB: 1048576, // 1 GB: the catalog only DESCRIBES size, so a large legitimate plugin is not blocked
26
- capabilities: 12,
27
- doesLines: 8,
28
- textLength: 600,
29
- taglineLength: 200,
30
- itemsPerSuite: 40,
31
- }
32
-
33
- /** The catalog format this build understands: `catalog.schema` must be one of these. */
34
- export const CATALOG_SCHEMA = 1
35
- export const CATALOG_SCHEMAS = [1]
36
-
37
- /** Names the catalog may claim. Everything else is refused, so the trusted install surface is fixed. */
38
- export const CATALOG_KNOWN = {
39
- /** VibeDev's own packages are scoped; dsh-film is grandfathered from before the scope existed. */
40
- officialScopes: ['@vibedev-si/'],
41
- officialGrandfathered: ['dsh-film'],
42
- /** Community entries are the packages already shipped this way; the list does not grow by remote edit. */
43
- community: ['dshmarket'],
44
- /** Never VibeDev's own: a DSH-scoped name claiming "official" is impersonation. */
45
- forbiddenScopes: ['@deepseek-ai/'],
46
- officialRepo: /^https:\/\/github\.com\/VibeDev-Si\/[A-Za-z0-9._-]+$/,
47
- npmPage: /^https:\/\/www\.npmjs\.com\/package\/[@a-z0-9._~/-]+$/i,
48
- }
49
-
50
- /** The ecosystem itself, which is never a catalog entry. */
51
- export const CATALOG_SELF = ['@vibedev-si/dsh-ecosystem']
52
-
53
- const ORIGINS = new Set(['official', 'community'])
54
- const ROLES = new Set(['official', 'dependency', 'companion', 'featured'])
55
- const UPDATES = new Set(['center', 'self'])
56
- const COMPAT = new Set(['verified', 'likely', 'unknown', 'incompatible'])
57
- const TAGS = new Set(['official', 'community', 'needsAccount', 'paid', 'needsHost02', 'dependency', 'companion', 'tested'])
58
- const CAPS = new Set(['network', 'writeFiles', 'readFiles', 'credentials', 'cost', 'agentTools', 'localRoute', 'pageScripts', 'community', 'fileAccess', 'writeConfig'])
59
- /** A plain package name: no urls, no git specs, no paths, no versions, no dist-tags. */
60
- const SPEC = /^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/
61
- /** An exact released version. No range, no tag, no prerelease suffix. */
62
- const STABLE = /^\d+\.\d+\.\d+$/
63
- const ISO_UTC = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?Z$/
64
- const EARLIEST = Date.parse('2020-01-01T00:00:00Z')
65
- /** Two CSS hex colours, and nothing else: `url(...)`, `var(...)` or a named colour would let a remote
66
- * payload make the page fetch something or read a theme value it should not touch. */
67
- const HEX = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/
68
- const PROFILE = '[A-Za-z0-9._-]{1,64}'
69
- /** The one shape a `cmd` may have. Nothing from a payload is ever executed or echoed as a shell line:
70
- * the reader regenerates the command from the entry's own npm name and exact version. */
71
- const canonicalCmd = (npm, version) => new RegExp(`^dsh plugin(?: --profile ${PROFILE})? add ${escapeRe(npm)}(?:@${escapeRe(version)})?$`)
72
-
73
- /** Escape a package name or version so it can only match itself inside a pattern. */
74
- function escapeRe(value) {
75
- return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
76
- }
77
-
78
- /**
79
- * The canonical install command for an entry, built from fields this validator has already checked.
80
- * @param npm - the entry's package name.
81
- * @param version - the entry's exact version.
82
- * @param profile - an optional dsh profile name.
83
- * @returns the command the UI may show and the user may copy.
84
- */
85
- export function catalogCommand(npm, version, profile) {
86
- return `dsh plugin${profile ? ` --profile ${profile}` : ''} add ${npm}@${version}`
87
- }
88
-
89
- /**
90
- * A copy of the catalog whose commands are regenerated rather than trusted.
91
- * @param catalog - a catalog that passed validateCatalog.
92
- * @param options - { profile }: the dsh profile the Host installs into, when it knows one.
93
- * @returns a new catalog object; the input is never modified.
94
- */
95
- export function normalizeCatalog(catalog, options = {}) {
96
- const profile = options.profile
97
- if (profile !== undefined && !new RegExp(`^${PROFILE}$`).test(String(profile))) throw new Error('invalid profile name')
98
- const plugins = (catalog?.plugins ?? []).map((p) => ({ ...p, cmd: catalogCommand(p.npm, p.version, profile) }))
99
- const suites = (catalog?.suites ?? []).map((s) => ({ ...s }))
100
- return { ...catalog, plugins, suites }
101
- }
102
-
103
- /** https, and a plain path: no credentials in the authority, no query, no fragment. */
104
- const plainHttps = (value) => typeof value === 'string' && /^https:\/\//.test(value)
105
- && !/^https:\/\/[^/]*@/.test(value) && !/[?#]/.test(value)
106
-
107
- /**
108
- * Validate one catalog.
109
- * @param catalog - the parsed catalog (or anything at all).
110
- * @param options - { now, limits, known } overrides, for tests and for a stricter caller.
111
- * @returns { ok, errors, counts }: the errors are messages, safe to log and to show.
112
- */
113
- export function validateCatalog(catalog, options = {}) {
114
- const limits = { ...CATALOG_LIMITS, ...(options.limits ?? {}) }
115
- const known = { ...CATALOG_KNOWN, ...(options.known ?? {}) }
116
- const now = typeof options.now === 'function' ? options.now() : (options.now ?? Date.now())
117
- const errors = []
118
- const err = (m) => errors.push(m)
119
- const entry = (v) => v !== null && typeof v === 'object'
120
- const text = (v) => typeof v === 'string' && v.trim().length > 0
121
- const bi = (v, where) => {
122
- if (!entry(v) || !text(v.zh) || !text(v.en)) return err(`${where}: needs non-empty zh and en`)
123
- if (v.zh.length > limits.textLength || v.en.length > limits.textLength) err(`${where}: text is longer than ${limits.textLength} characters`)
124
- }
125
- const biList = (v, where, min = 1, max = limits.doesLines) => {
126
- if (!entry(v) || !Array.isArray(v.zh) || !Array.isArray(v.en) || v.zh.length === 0) return err(`${where}: needs zh[] and en[]`)
127
- if (v.zh.length !== v.en.length) err(`${where}: zh and en must have the same number of lines (${v.zh.length} vs ${v.en.length})`)
128
- if (v.zh.length > max) err(`${where}: more than ${max} lines`)
129
- for (const line of [...v.zh, ...v.en]) if (!text(line)) err(`${where}: every line must be non-empty`)
130
- }
131
-
132
- if (!entry(catalog)) return { ok: false, errors: ['catalog: not an object'], counts: { plugins: 0, suites: 0 } }
133
- const schemas = options.schemas ?? CATALOG_SCHEMAS
134
- if (!schemas.includes(catalog.schema)) err(`schema must be one of ${schemas.join(', ')} (got ${JSON.stringify(catalog.schema)})`)
135
- if (!Array.isArray(catalog.plugins) || catalog.plugins.length === 0) err('plugins[] is required')
136
- const plugins = Array.isArray(catalog.plugins) ? catalog.plugins : []
137
- const suites = Array.isArray(catalog.suites) ? catalog.suites : []
138
- if (plugins.length > limits.plugins) err(`plugins[] has ${plugins.length} entries, more than the ${limits.plugins} this reader accepts`)
139
- if (suites.length > limits.suites) err(`suites[] has ${suites.length} entries, more than the ${limits.suites} this reader accepts`)
140
-
141
- const ids = new Set()
142
- const npmNames = new Set()
143
- for (const p of plugins) {
144
- const w = `plugin ${entry(p) ? p.id ?? '?' : '?'}`
145
- if (!entry(p)) { err(`${w}: not an object`); continue }
146
- if (!text(p.id) || ids.has(p.id)) err(`${w}: id missing or duplicated`)
147
- if (typeof p.id === 'string') ids.add(p.id)
148
- if (p.id !== p.npm) err(`${w}: id must equal npm name`)
149
- if (!text(p.npm) || !SPEC.test(p.npm)) err(`${w}: npm is not a plain package name (no urls, git specs, paths, versions or tags)`)
150
- if (npmNames.has(p.npm)) err(`${w}: duplicate npm name`)
151
- if (typeof p.npm === 'string') npmNames.add(p.npm)
152
- if (!STABLE.test(p.version ?? '')) err(`${w}: version must be an exact released x.y.z (no range, tag or prerelease)`)
153
- // When this exact version reached npm. The update screens use it to warn about pnpm's one-day cooldown honestly.
154
- const published = typeof p.publishedAt === 'string' && ISO_UTC.test(p.publishedAt) ? Date.parse(p.publishedAt) : NaN
155
- if (Number.isNaN(published)) err(`${w}: publishedAt must be an ISO UTC time such as 2026-10-05T14:40:00.000Z`)
156
- else if (published < EARLIEST) err(`${w}: publishedAt is before 2020`)
157
- else if (published > now + 24 * 3600 * 1000) err(`${w}: publishedAt is in the future`)
158
- if (!ORIGINS.has(p.origin)) err(`${w}: origin`)
159
- if (!ROLES.has(p.role)) err(`${w}: role`)
160
- if (!UPDATES.has(p.updates)) err(`${w}: updates`)
161
- // What a name may claim. A DSH-scoped package is never VibeDev's own, whatever the entry says.
162
- const scope = typeof p.npm === 'string' ? p.npm.slice(0, p.npm.indexOf('/') + 1) : ''
163
- // The center itself is listed as a manual row and updated from the Plugins page: it must never
164
- // appear here, or a click could unload the very panel reading this catalog.
165
- if ((options.self ?? CATALOG_SELF).includes(p.npm) || (options.self ?? CATALOG_SELF).includes(p.id)) {
166
- err(`${w}: the ecosystem is not a catalog entry (it is updated from the Plugins page, never installed from here)`)
167
- }
168
- if (known.forbiddenScopes.includes(scope)) err(`${w}: ${scope} is not a VibeDev package name`)
169
- if (p.origin === 'official' && !(known.officialScopes.some((s) => (p.npm ?? '').startsWith(s)) || known.officialGrandfathered.includes(p.npm))) {
170
- err(`${w}: an "official" entry must be @vibedev-si/* or one of the grandfathered unscoped names`)
171
- }
172
- if (p.origin === 'community') {
173
- if (p.role === 'official') err(`${w}: community entry cannot have role official`)
174
- if (!p.author) err(`${w}: community entry needs author`)
175
- if (!known.community.includes(p.npm)) err(`${w}: community entries are limited to the packages this catalog already ships`)
176
- if (!(p.capabilities ?? []).some((c) => entry(c) && c.key === 'community')) err(`${w}: community entry must carry the "community" capability disclaimer`)
177
- }
178
- bi(p.name, `${w}.name`)
179
- bi(p.tagline, `${w}.tagline`)
180
- if (entry(p.tagline) && text(p.tagline.zh) && p.tagline.zh.length > limits.taglineLength) err(`${w}.tagline: longer than ${limits.taglineLength} characters`)
181
- biList(p.does, `${w}.does`)
182
- // Rendered when present (the card shows this instead of the computed size), so it must be a
183
- // bilingual string pair like every other rendered field: a payload must not be able to put an
184
- // object — or a line that disagrees with the real size — there.
185
- if (p.sizeNote != null) bi(p.sizeNote, `${w}.sizeNote`)
186
- for (const t of p.tags ?? []) if (!TAGS.has(t)) err(`${w}: unknown tag ${t}`)
187
- const caps = Array.isArray(p.capabilities) ? p.capabilities : []
188
- if (caps.length > limits.capabilities) err(`${w}: more than ${limits.capabilities} capabilities`)
189
- for (const c of caps) {
190
- if (!entry(c) || !CAPS.has(c.key)) err(`${w}: unknown capability ${entry(c) ? c.key : '?'}`)
191
- bi(c?.text, `${w}.capabilities.${c?.key}`)
192
- }
193
- if (!caps.length) err(`${w}: capabilities must list at least one entry`)
194
- if (!Number.isFinite(p.sizeKB) || p.sizeKB <= 0) err(`${w}: sizeKB`)
195
- else if (p.sizeKB > limits.sizeKB) err(`${w}: sizeKB ${p.sizeKB} is larger than the ${limits.sizeKB} KB this reader accepts`)
196
- if (!p.icon?.glyph?.zh || !p.icon?.glyph?.en || p.icon.grad?.length !== 2) err(`${w}: icon.glyph{zh,en} and icon.grad[2]`)
197
- if (p.icon?.glyph?.en && /[^\x00-\x7f]/.test(p.icon.glyph.en)) err(`${w}: icon.glyph.en must be plain ASCII (it is shown in the English UI)`)
198
- for (const c of p.icon?.grad ?? []) if (!HEX.test(String(c))) err(`${w}: icon.grad must be two CSS hex colours (got ${String(c).slice(0, 40)})`)
199
- // The command is a fixed shape built from the name and version above: a payload cannot smuggle a
200
- // shell line in, and the reader regenerates it anyway (see normalizeCatalog).
201
- if (!canonicalCmd(p.npm ?? '', p.version ?? '').test(p.cmd ?? '')) {
202
- err(`${w}: cmd must be "dsh plugin [--profile <name>] add ${p.npm ?? '?'}[@${p.version ?? '?'}]" and nothing else`)
203
- }
204
- // Links: https, no credentials, no query or fragment — and the shapes this catalog actually uses.
205
- for (const k of ['repo', 'npm']) if (!plainHttps(p.links?.[k])) err(`${w}: links.${k} must be a plain https url`)
206
- if (plainHttps(p.links?.repo) && p.origin === 'official' && !known.officialRepo.test(p.links.repo)) err(`${w}: links.repo must be a VibeDev repository (${p.links.repo})`)
207
- if (plainHttps(p.links?.npm) && !known.npmPage.test(p.links.npm)) err(`${w}: links.npm must be the npm package page`)
208
- if (p.compat != null) {
209
- if (!COMPAT.has(p.compat.s)) err(`${w}: compat.s`)
210
- bi(p.compat.why, `${w}.compat.why`)
211
- }
212
- if (p.reviewed != null && !(p.reviewed.date && Array.isArray(p.reviewed.tested) && p.reviewed.tested.length)) err(`${w}: reviewed needs date and tested[]`)
213
- }
214
- for (const p of plugins) {
215
- if (!entry(p)) continue
216
- for (const k of ['requires', 'partners']) {
217
- if (p[k] !== undefined && !Array.isArray(p[k])) { err(`plugin ${p.id}: ${k} must be an array`); continue }
218
- for (const d of p[k] ?? []) if (!ids.has(d)) err(`plugin ${p.id}: ${k} points at unknown id ${d}`)
219
- }
220
- if (p.legacyNames !== undefined && !Array.isArray(p.legacyNames)) err(`plugin ${p.id}: legacyNames must be an array`)
221
- else {
222
- // Legacy aliases are the plain package names this plugin used to be published under (dsh-media):
223
- // useful for the migration banner, and never a url, a git spec or a path.
224
- for (const name of p.legacyNames ?? []) {
225
- if (typeof name !== 'string' || !SPEC.test(name)) err(`plugin ${p.id}: legacyNames must be plain package names (got ${String(name).slice(0, 40)})`)
226
- }
227
- }
228
- if ((p.requires ?? []).includes(p.id)) err(`plugin ${p.id}: requires itself`)
229
- }
230
- // dependency cycles
231
- const visit = (id, path) => {
232
- if (path.includes(id)) return err(`dependency cycle: ${[...path, id].join(' -> ')}`)
233
- const p = plugins.find((x) => entry(x) && x.id === id)
234
- for (const d of p?.requires ?? []) visit(d, [...path, id])
235
- }
236
- for (const p of plugins) if (entry(p) && text(p.id)) visit(p.id, [])
237
- const suiteIds = new Set()
238
- for (const s of suites) {
239
- if (!entry(s)) { err('suite: not an object'); continue }
240
- if (!text(s.id)) err('suite: id is required')
241
- else if (suiteIds.has(s.id)) err(`suite ${s.id}: id is duplicated`)
242
- else suiteIds.add(s.id)
243
- bi(s.name, `suite ${s.id}.name`)
244
- bi(s.tagline, `suite ${s.id}.tagline`)
245
- if (!Array.isArray(s.items)) err(`suite ${s.id}: items[] is required`)
246
- else {
247
- if (s.items.length > limits.itemsPerSuite) err(`suite ${s.id}: more than ${limits.itemsPerSuite} items`)
248
- for (const i of s.items) if (!ids.has(i)) err(`suite ${s.id}: unknown item ${i}`)
249
- }
250
- }
251
-
252
- return { ok: errors.length === 0, errors, counts: { plugins: plugins.length, suites: suites.length } }
253
- }
254
-
255
- /**
256
- * The error list alone, for a caller that only wants to know why a catalog is refused.
257
- * @param catalog - the parsed catalog.
258
- * @param options - as validateCatalog.
259
- * @returns the error messages, empty when the catalog is fine.
260
- */
261
- export function catalogErrors(catalog, options) {
262
- return validateCatalog(catalog, options).errors
263
- }