@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.
- package/README.md +29 -7
- package/THIRD-PARTY-NOTICES.txt +1 -1
- package/client/client.account-center.js +6 -9
- package/client/client.js +2700 -2989
- package/cordis.patch.yml +0 -5
- package/lib/fetch/wiring.d.ts +2 -0
- package/lib/index.js +4 -0
- package/lib/search/provider.d.ts +2 -0
- package/package.json +1 -7
- package/node_modules/@vibedev-si/dsh-ecosystem/LICENSE +0 -22
- package/node_modules/@vibedev-si/dsh-ecosystem/README.md +0 -154
- package/node_modules/@vibedev-si/dsh-ecosystem/catalog/catalog.json +0 -167
- package/node_modules/@vibedev-si/dsh-ecosystem/catalog-updates.js +0 -326
- package/node_modules/@vibedev-si/dsh-ecosystem/catalog-validator.js +0 -263
- package/node_modules/@vibedev-si/dsh-ecosystem/client.js +0 -2816
- package/node_modules/@vibedev-si/dsh-ecosystem/cordis.patch.yml +0 -5
- package/node_modules/@vibedev-si/dsh-ecosystem/icon.svg +0 -5
- package/node_modules/@vibedev-si/dsh-ecosystem/index.js +0 -169
- package/node_modules/@vibedev-si/dsh-ecosystem/locale/en.json +0 -6
- package/node_modules/@vibedev-si/dsh-ecosystem/locale/zh.json +0 -6
- package/node_modules/@vibedev-si/dsh-ecosystem/package.json +0 -75
- package/node_modules/@vibedev-si/dsh-ecosystem/remote-catalog.js +0 -212
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
|
|
2
|
-
<defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#4D6BFE"/><stop offset="1" stop-color="#8F6BFF"/></linearGradient></defs>
|
|
3
|
-
<rect width="64" height="64" rx="14" fill="url(#g)"/>
|
|
4
|
-
<path fill="none" stroke="#fff" stroke-width="4" stroke-linecap="round" stroke-linejoin="round" d="M26 14h-9a3 3 0 0 0-3 3v10a3 3 0 0 0 3 3h2a4 4 0 1 1 0 8h-2a3 3 0 0 0-3 3v7a3 3 0 0 0 3 3h10v-3a4 4 0 1 1 8 0v3h10a3 3 0 0 0 3-3V37h-3a4 4 0 1 1 0-8h3V17a3 3 0 0 0-3-3H36v3a4 4 0 1 1-8 0z"/>
|
|
5
|
-
</svg>
|
|
@@ -1,169 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @vibedev-si/dsh-ecosystem: host half.
|
|
3
|
-
*
|
|
4
|
-
* The center talks to the host's `pluginManager` from the browser (via ctx.remote), so this half stays small. It exists
|
|
5
|
-
* because the loader mounts a package through its host entry, for a developer-only self-check channel that is OFF unless
|
|
6
|
-
* a marker file exists, and for the TWO user-facing outbound reads: this package's own latest version, and the fixed
|
|
7
|
-
* allow-list of official plugins plus this center (`catalog-updates.js`).
|
|
8
|
-
*
|
|
9
|
-
* GET /vdc/ping -> {ok:true}
|
|
10
|
-
* GET /vdc/config -> {selfcheck, mount, official}: does <profile>/.vdc/enable-selfcheck exist, and does
|
|
11
|
-
* enable-selfcheck-mount (the second, separate opt-in that lets the check switch panels, which
|
|
12
|
-
* the user can SEE); and whether this is an app's built-in copy (row config `official: true`)
|
|
13
|
-
* POST /vdc/selfcheck -> writes the client's report to <profile>/.vdc/selfcheck.json (only when enabled)
|
|
14
|
-
* GET /vdc/latest -> the newest version of THIS package on npm. Called only when the user clicks "check for
|
|
15
|
-
* updates"; never on load, never on a timer.
|
|
16
|
-
* GET /vdc/updates -> the newest version of each allow-listed package (three official plugins and this center),
|
|
17
|
-
* every one of them verified against its package identity, bundle manifest, repository and
|
|
18
|
-
* integrity. Never on load, never on a timer: the panel asks when it opens and when the
|
|
19
|
-
* user clicks.
|
|
20
|
-
*
|
|
21
|
-
* Every route is loopback-only (same Host/Origin fence as the other routes). The ONLY outbound network use is those two
|
|
22
|
-
* reads: a plain GET of one packument per package, from fixed registries (the official one first, a mirror only when the
|
|
23
|
-
* official read fails at the transport level). Neither takes input from the page (no query, no body), so there is nothing
|
|
24
|
-
* to redirect elsewhere; they send no data about the user or the machine.
|
|
25
|
-
*/
|
|
26
|
-
import { access, mkdir, writeFile } from 'node:fs/promises'
|
|
27
|
-
import { join } from 'node:path'
|
|
28
|
-
import { createUpdatesReader } from './catalog-updates.js'
|
|
29
|
-
import { createCatalogReader } from './remote-catalog.js'
|
|
30
|
-
import { readFileSync } from 'node:fs'
|
|
31
|
-
const BUNDLED_CATALOG = JSON.parse(readFileSync(new URL('./catalog/catalog.json', import.meta.url), 'utf8'))
|
|
32
|
-
|
|
33
|
-
export const name = '@vibedev-si/dsh-ecosystem'
|
|
34
|
-
// Only the web server is required. The extra trusted hosts come from `webStartup` (DSH 0.2.1-alpha.2 and later) or
|
|
35
|
-
// `webRuntime` (earlier releases), read when present: requiring either one left the plugin pending on the other release.
|
|
36
|
-
export const inject = ['webServer']
|
|
37
|
-
|
|
38
|
-
/** The deployment's extra trusted hosts (loopback is always trusted), from whichever startup service this host has. */
|
|
39
|
-
export function trustedHostsOf(ctx) {
|
|
40
|
-
for (const service of ['webStartup', 'webRuntime']) {
|
|
41
|
-
try {
|
|
42
|
-
const value = typeof ctx.get === 'function' ? ctx.get(service) : ctx[service]
|
|
43
|
-
if (Array.isArray(value?.trustedHosts)) return value.trustedHosts
|
|
44
|
-
} catch { /* not provided by this host */ }
|
|
45
|
-
}
|
|
46
|
-
return []
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
const header = (h, k) => (typeof h[k] === 'string' ? h[k] : undefined)
|
|
50
|
-
const parseAuthority = (a) => { try { return new URL(`http://${a}`) } catch { return undefined } }
|
|
51
|
-
const loopback = (hn) => hn === 'localhost' || hn === '[::1]' || /^127(\.\d{1,3}){3}$/.test(hn)
|
|
52
|
-
|
|
53
|
-
export function trusted(req, trustedHosts) {
|
|
54
|
-
const host = header(req.headers, 'host')
|
|
55
|
-
const u = host && parseAuthority(host)
|
|
56
|
-
if (!u) return false
|
|
57
|
-
if (!loopback(u.hostname) && !trustedHosts.some((e) => { const x = parseAuthority(e); return x && (x.port === '' ? x.hostname === u.hostname : x.host === u.host) })) return false
|
|
58
|
-
if (header(req.headers, 'sec-fetch-site') === 'cross-site') return false
|
|
59
|
-
const origin = header(req.headers, 'origin')
|
|
60
|
-
if (origin === undefined) return true
|
|
61
|
-
try { return new URL(origin).hostname === u.hostname } catch { return false }
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
const MAX_BODY = 64 * 1024
|
|
65
|
-
const profileDir = () => process.env.DSH_PROFILE_DIR ?? process.cwd()
|
|
66
|
-
const markerPath = () => join(profileDir(), '.vdc', 'enable-selfcheck')
|
|
67
|
-
const mountMarkerPath = () => join(profileDir(), '.vdc', 'enable-selfcheck-mount')
|
|
68
|
-
const exists = async (p) => { try { await access(p); return true } catch { return false } }
|
|
69
|
-
|
|
70
|
-
// ── latest version of this package ────────────────────────────────────────────────────────────────────────────────
|
|
71
|
-
// Fixed on purpose: the package name and the two registries are constants, never taken from the request.
|
|
72
|
-
const PACKAGE = '@vibedev-si/dsh-ecosystem'
|
|
73
|
-
const REGISTRIES = ['https://registry.npmjs.org/', 'https://registry.npmmirror.com/']
|
|
74
|
-
const SEMVER = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/
|
|
75
|
-
const TIMEOUT_MS = 8000
|
|
76
|
-
const CACHE_MS = 60_000
|
|
77
|
-
|
|
78
|
-
export function compareVersions(a, b) {
|
|
79
|
-
const pa = a.split('-')[0].split('.').map(Number)
|
|
80
|
-
const pb = b.split('-')[0].split('.').map(Number)
|
|
81
|
-
for (let i = 0; i < 3; i++) if (pa[i] !== pb[i]) return pa[i] < pb[i] ? -1 : 1
|
|
82
|
-
return 0
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/** Read one registry. Never throws; always answers {registry, ms, version?, publishedAt?, error?}. */
|
|
86
|
-
export async function readRegistry(base, doFetch) {
|
|
87
|
-
const t0 = Date.now()
|
|
88
|
-
const done = (o) => ({ registry: base, ms: Date.now() - t0, ...o })
|
|
89
|
-
try {
|
|
90
|
-
const r = await doFetch(base + PACKAGE.replace('/', '%2F'), { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(TIMEOUT_MS), redirect: 'error' })
|
|
91
|
-
if (!r.ok) return done({ error: `HTTP ${r.status}` })
|
|
92
|
-
const j = await r.json()
|
|
93
|
-
const latest = j?.['dist-tags']?.latest
|
|
94
|
-
if (j?.name !== PACKAGE || typeof latest !== 'string' || !SEMVER.test(latest)) return done({ error: 'unexpected answer' })
|
|
95
|
-
const at = j?.time?.[latest]
|
|
96
|
-
const publishedAt = typeof at === 'string' && !Number.isNaN(Date.parse(at)) ? new Date(at).toISOString() : undefined
|
|
97
|
-
return done({ version: latest, ...(publishedAt ? { publishedAt } : {}) })
|
|
98
|
-
} catch (e) {
|
|
99
|
-
return done({ error: e?.name === 'TimeoutError' || e?.name === 'AbortError' ? 'timeout' : String(e?.cause?.code ?? e?.message ?? e).slice(0, 120) })
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/** Ask both registries at once and keep the highest version any of them reports (a mirror can lag behind npm). */
|
|
104
|
-
export async function latestVersion(doFetch) {
|
|
105
|
-
const sources = await Promise.all(REGISTRIES.map((b) => readRegistry(b, doFetch)))
|
|
106
|
-
const ok = sources.filter((s) => s.version)
|
|
107
|
-
if (!ok.length) return { ok: false, name: PACKAGE, sources }
|
|
108
|
-
const best = ok.reduce((a, b) => (compareVersions(b.version, a.version) > 0 ? b : a))
|
|
109
|
-
return { ok: true, name: PACKAGE, latest: best.version, publishedAt: best.publishedAt, from: best.registry, sources }
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
/** Page global telling the client half it is the app's built-in, official copy (see {@link apply}). */
|
|
113
|
-
export const OFFICIAL_GLOBAL = '__VDC_OFFICIAL__'
|
|
114
|
-
|
|
115
|
-
/**
|
|
116
|
-
* @param ctx - the host context.
|
|
117
|
-
* @param config - `official: true` only in an app that ships this center built in (VibeDev Next's web defaults set it on
|
|
118
|
-
* their own insert row). Then the client half lists the center in the Official group of the Plugins page and reports
|
|
119
|
-
* that it updates with the app. A user's own install (DeepSeek Harness, `Add plugin`) passes no config: nothing changes.
|
|
120
|
-
*/
|
|
121
|
-
export function apply(ctx, config) {
|
|
122
|
-
const official = config?.official === true
|
|
123
|
-
if (official) ctx.on('webserver/index-inject', (table) => { table.push({ kind: 'global', name: OFFICIAL_GLOBAL, value: { official: true } }) })
|
|
124
|
-
// `ctx.__vdcFetch` is a test hook; the real host never sets it, so production uses the global fetch.
|
|
125
|
-
const doFetch = (...a) => (ctx.__vdcFetch ?? globalThis.fetch)(...a)
|
|
126
|
-
let cache // {at, body}: a user mashing the button must not hammer the registry
|
|
127
|
-
// The allow-listed live reader owns its own 60-second cache and its own in-flight batch.
|
|
128
|
-
const now = typeof ctx.__vdcNow === 'function' ? ctx.__vdcNow : Date.now
|
|
129
|
-
const catalogs = ctx.__vdcCatalogReader ?? createCatalogReader(doFetch, now, BUNDLED_CATALOG)
|
|
130
|
-
const updates = createUpdatesReader(doFetch, now, catalogs)
|
|
131
|
-
ctx.effect(() => ctx.webServer.register({
|
|
132
|
-
kind: 'prefix',
|
|
133
|
-
path: '/vdc',
|
|
134
|
-
handler: async (req, res) => {
|
|
135
|
-
const json = (status, body) => { const b = Buffer.from(JSON.stringify(body)); res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'content-length': String(b.length), 'cache-control': 'no-store' }); res.end(b) }
|
|
136
|
-
try {
|
|
137
|
-
if (!trusted(req, trustedHostsOf(ctx))) return json(403, { ok: false })
|
|
138
|
-
const url = new URL(req.url ?? '/', 'http://x')
|
|
139
|
-
if (url.pathname === '/vdc/ping' && req.method === 'GET') return json(200, { ok: true, name })
|
|
140
|
-
if (url.pathname === '/vdc/config' && req.method === 'GET') {
|
|
141
|
-
const on = await exists(markerPath())
|
|
142
|
-
// The visible part only ever applies when the whole self-check is on.
|
|
143
|
-
return json(200, { ok: true, selfcheck: on, mount: on && (await exists(mountMarkerPath())), official })
|
|
144
|
-
}
|
|
145
|
-
if (url.pathname === '/vdc/latest' && req.method === 'GET') {
|
|
146
|
-
if (cache && Date.now() - cache.at < CACHE_MS) return json(200, { ...cache.body, cached: true })
|
|
147
|
-
const body = await latestVersion(doFetch)
|
|
148
|
-
if (body.ok) cache = { at: Date.now(), body } // a failure is never cached: the next click tries again
|
|
149
|
-
return json(200, body)
|
|
150
|
-
}
|
|
151
|
-
if (url.pathname === '/vdc/updates' && req.method === 'GET') return json(200, await updates.read())
|
|
152
|
-
if (url.pathname === '/vdc/selfcheck' && req.method === 'POST') {
|
|
153
|
-
if (!(await exists(markerPath()))) return json(403, { ok: false, error: 'self-check is not enabled' })
|
|
154
|
-
const chunks = []; let size = 0
|
|
155
|
-
for await (const c of req) { size += c.length; if (size > MAX_BODY) return json(413, { ok: false }); chunks.push(c) }
|
|
156
|
-
let body
|
|
157
|
-
try { body = JSON.parse(Buffer.concat(chunks).toString('utf8')) } catch { return json(400, { ok: false }) }
|
|
158
|
-
const dir = join(profileDir(), '.vdc')
|
|
159
|
-
await mkdir(dir, { recursive: true })
|
|
160
|
-
await writeFile(join(dir, 'selfcheck.json'), JSON.stringify({ at: new Date().toISOString(), ...body }, null, 2))
|
|
161
|
-
return json(200, { ok: true })
|
|
162
|
-
}
|
|
163
|
-
return json(404, { ok: false })
|
|
164
|
-
} catch (e) {
|
|
165
|
-
return json(500, { ok: false, error: String(e?.message ?? e) })
|
|
166
|
-
}
|
|
167
|
-
},
|
|
168
|
-
}), '@vibedev-si/dsh-ecosystem: /vdc routes')
|
|
169
|
-
}
|
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@vibedev-si/dsh-ecosystem",
|
|
3
|
-
"version": "0.2.0",
|
|
4
|
-
"description": "VibeDev 生态:发现、安装和管理 VibeDev 出品的插件,实时核对正式版本更新 · VibeDev Ecosystem: discover, install and manage plugins made by VibeDev, and verify stable release updates",
|
|
5
|
-
"type": "module",
|
|
6
|
-
"main": "index.js",
|
|
7
|
-
"icon": "./icon.svg",
|
|
8
|
-
"files": [
|
|
9
|
-
"index.js",
|
|
10
|
-
"catalog-updates.js",
|
|
11
|
-
"catalog-validator.js",
|
|
12
|
-
"remote-catalog.js",
|
|
13
|
-
"catalog/catalog.json",
|
|
14
|
-
"client.js",
|
|
15
|
-
"icon.svg",
|
|
16
|
-
"locale",
|
|
17
|
-
"cordis.patch.yml",
|
|
18
|
-
"README.md",
|
|
19
|
-
"LICENSE"
|
|
20
|
-
],
|
|
21
|
-
"exports": {
|
|
22
|
-
".": "./index.js",
|
|
23
|
-
"./client": {
|
|
24
|
-
"default": "./client.js"
|
|
25
|
-
},
|
|
26
|
-
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
27
|
-
"./locale/*.json": "./locale/*.json",
|
|
28
|
-
"./package.json": "./package.json"
|
|
29
|
-
},
|
|
30
|
-
"keywords": [
|
|
31
|
-
"dsh",
|
|
32
|
-
"dsh-plugin",
|
|
33
|
-
"deepseek-harness",
|
|
34
|
-
"vibedev",
|
|
35
|
-
"plugin-center",
|
|
36
|
-
"installer",
|
|
37
|
-
"suite"
|
|
38
|
-
],
|
|
39
|
-
"author": "VibeDev",
|
|
40
|
-
"license": "MIT",
|
|
41
|
-
"homepage": "https://github.com/VibeDev-Si/dsh-ecosystem#readme",
|
|
42
|
-
"repository": {
|
|
43
|
-
"type": "git",
|
|
44
|
-
"url": "git+https://github.com/VibeDev-Si/dsh-ecosystem.git"
|
|
45
|
-
},
|
|
46
|
-
"bugs": {
|
|
47
|
-
"url": "https://github.com/VibeDev-Si/dsh-ecosystem/issues"
|
|
48
|
-
},
|
|
49
|
-
"engines": {
|
|
50
|
-
"node": ">=20"
|
|
51
|
-
},
|
|
52
|
-
"publishConfig": {
|
|
53
|
-
"access": "public",
|
|
54
|
-
"registry": "https://registry.npmjs.org/"
|
|
55
|
-
},
|
|
56
|
-
"scripts": {
|
|
57
|
-
"build": "node scripts/build.mjs",
|
|
58
|
-
"validate": "node scripts/validate-catalog.mjs",
|
|
59
|
-
"validate:online": "node scripts/validate-catalog.mjs --online",
|
|
60
|
-
"test": "node scripts/build.mjs && node scripts/validate-catalog.mjs && node test/catalog.test.mjs && node test/engine.test.mjs && node test/host.test.mjs && node test/latest.test.mjs && node test/updates.test.mjs && node test/remote-catalog.test.mjs && node test/unified.test.mjs && node test/selfcheck.test.mjs",
|
|
61
|
-
"test:browser": "node scripts/build.mjs && node test/browser.test.mjs && node test/theme.browser.test.mjs && node test/updates.browser.test.mjs && node test/online-catalog.browser.test.mjs && node test/unified.browser.test.mjs",
|
|
62
|
-
"prepack": "node scripts/build.mjs"
|
|
63
|
-
},
|
|
64
|
-
"dsh": {
|
|
65
|
-
"bundle": {
|
|
66
|
-
"patch": "./cordis.patch.yml"
|
|
67
|
-
},
|
|
68
|
-
"client": {
|
|
69
|
-
"platform": "web",
|
|
70
|
-
"inject": [
|
|
71
|
-
"@deepseek-ai/dsh-client-locale"
|
|
72
|
-
]
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
}
|
|
@@ -1,212 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The online catalog reader: new VibeDev plugins are picked up without shipping a new client.
|
|
3
|
-
*
|
|
4
|
-
* The source is FIXED — the repository's own catalog/catalog.json on the default branch, maintained
|
|
5
|
-
* by committing to main, with no release or tag needed:
|
|
6
|
-
*
|
|
7
|
-
* https://raw.githubusercontent.com/VibeDev-Si/dsh-ecosystem/main/catalog/catalog.json
|
|
8
|
-
*
|
|
9
|
-
* Nothing a page or a user supplies reaches the request: no url, no package name, no header, no
|
|
10
|
-
* body, no credentials. The reader sends a plain GET, refuses to follow a redirect, stops after 8
|
|
11
|
-
* seconds IN TOTAL — the response body included, and the deadline is enforced with Promise.race as
|
|
12
|
-
* well as the abort signal, so a transport that ignores the signal still cannot hang the panel — and
|
|
13
|
-
* caps the body at 256 KB WHILE it is being read, cancelling the stream the moment it goes over.
|
|
14
|
-
*
|
|
15
|
-
* Whatever arrives is validated with the same rules the bundled catalog obeys (catalog-validator.js)
|
|
16
|
-
* and then REPLACED where it must not be trusted: every entry's install command is regenerated from
|
|
17
|
-
* its own npm name and exact version, so a payload can never smuggle a shell line into the UI. One
|
|
18
|
-
* bad field refuses the WHOLE payload, and a refused payload is never cached: the reader answers
|
|
19
|
-
* with the last good catalog it saw (marked stale) or with the catalog shipped in the package.
|
|
20
|
-
*
|
|
21
|
-
* const reader = createCatalogReader(doFetch, Date.now, bundledCatalog)
|
|
22
|
-
* const { catalog, source, checkedAt, error, stale } = await reader.read()
|
|
23
|
-
*
|
|
24
|
-
* `source` is 'online' (fetched now), 'cached' (a fetch from the last 5 minutes, or the last good
|
|
25
|
-
* catalog when the fresh check failed — then `stale` is true) or 'bundled' (the shipped copy).
|
|
26
|
-
* `error` is set whenever a fetch was attempted and did not produce a usable catalog. Nothing is
|
|
27
|
-
* thrown, nothing is installed and nothing outside this module is written.
|
|
28
|
-
*/
|
|
29
|
-
|
|
30
|
-
import { validateCatalog, normalizeCatalog } from './catalog-validator.js'
|
|
31
|
-
|
|
32
|
-
/** The one source. Committing to catalog/catalog.json on main is the whole publish step. */
|
|
33
|
-
export const CATALOG_URL = 'https://raw.githubusercontent.com/VibeDev-Si/dsh-ecosystem/main/catalog/catalog.json'
|
|
34
|
-
/** A slow mirror must not hold the panel: after this the whole read — body included — is over. */
|
|
35
|
-
export const CATALOG_TIMEOUT_MS = 8000
|
|
36
|
-
/** Bigger than the real catalog (about 10 KB) by two orders of magnitude, and still bounded. */
|
|
37
|
-
export const CATALOG_MAX_BYTES = 256 * 1024
|
|
38
|
-
/** A successful read is reused for this long, so opening the panel repeatedly is not a request storm. */
|
|
39
|
-
export const CATALOG_CACHE_MS = 5 * 60 * 1000
|
|
40
|
-
|
|
41
|
-
const iso = (ms) => new Date(ms).toISOString()
|
|
42
|
-
const bytesOf = (text) => (typeof TextEncoder === 'function'
|
|
43
|
-
? new TextEncoder().encode(text).length
|
|
44
|
-
: (globalThis.Buffer?.byteLength?.(text) ?? text.length)) // no import, no bare global: feature-detected
|
|
45
|
-
|
|
46
|
-
/** Bytes to text, without assuming TextDecoder or Buffer exist. */
|
|
47
|
-
function decodeBody(all) {
|
|
48
|
-
if (typeof TextDecoder === 'function') return new TextDecoder().decode(all)
|
|
49
|
-
if (globalThis.Buffer?.from) return globalThis.Buffer.from(all).toString('utf8')
|
|
50
|
-
let out = ''
|
|
51
|
-
for (let i = 0; i < all.length; i += 4096) out += String.fromCharCode(...all.subarray(i, i + 4096))
|
|
52
|
-
return out
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/** A bundled catalog passed as the third argument, or inside the options. */
|
|
56
|
-
function bundledOf(options) {
|
|
57
|
-
if (options === null || typeof options !== 'object') return undefined
|
|
58
|
-
if (Array.isArray(options.plugins)) return options
|
|
59
|
-
return options.bundled
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
/**
|
|
63
|
-
* Build a reader over one fixed source.
|
|
64
|
-
* @param doFetch - the transport: (url, init) => Promise<Response>. Absent means "bundled only".
|
|
65
|
-
* @param now - () => epoch ms, or a number. Injectable so a test can move the clock.
|
|
66
|
-
* @param options - { bundled, profile, url, timeoutMs, maxBytes, cacheMs, validate, validateOptions }.
|
|
67
|
-
* The third argument may also BE the bundled catalog. `url` exists so a test double
|
|
68
|
-
* can stand in for the fixed source; it is not a page-facing setting, and the HTTP
|
|
69
|
-
* request can never be steered by the caller of read().
|
|
70
|
-
* @returns { read, peek, source }: read() never throws; peek() is the last known state, no request.
|
|
71
|
-
*/
|
|
72
|
-
export function createCatalogReader(doFetch, now = Date.now, options = {}) {
|
|
73
|
-
const url = options.url ?? CATALOG_URL
|
|
74
|
-
const timeoutMs = options.timeoutMs ?? CATALOG_TIMEOUT_MS
|
|
75
|
-
const maxBytes = options.maxBytes ?? CATALOG_MAX_BYTES
|
|
76
|
-
const cacheMs = options.cacheMs ?? CATALOG_CACHE_MS
|
|
77
|
-
const validate = options.validate ?? validateCatalog
|
|
78
|
-
const profile = options.profile
|
|
79
|
-
const clock = () => (typeof now === 'function' ? now() : Date.now())
|
|
80
|
-
/** Every catalog handed out carries regenerated commands; the caller's object is never modified. */
|
|
81
|
-
const out = (catalog) => (catalog ? normalizeCatalog(catalog, { profile }) : catalog)
|
|
82
|
-
const bundled = out(bundledOf(options))
|
|
83
|
-
/** The last catalog this reader accepted from the network. */
|
|
84
|
-
let good = null
|
|
85
|
-
/** The request in flight, so two callers share one. */
|
|
86
|
-
let inflight = null
|
|
87
|
-
|
|
88
|
-
const bundledRead = (error) => ({
|
|
89
|
-
catalog: bundled,
|
|
90
|
-
source: 'bundled',
|
|
91
|
-
checkedAt: iso(clock()),
|
|
92
|
-
...(error ? { error } : {}),
|
|
93
|
-
})
|
|
94
|
-
|
|
95
|
-
/** A deadline that fails even when the transport ignores the abort signal. */
|
|
96
|
-
const deadline = (ms, onExpire) => {
|
|
97
|
-
let timer = null
|
|
98
|
-
const promise = new Promise((_, reject) => {
|
|
99
|
-
timer = setTimeout(() => { try { onExpire?.() } catch { /* aborting is best effort */ } reject(new Error(`timed out after ${ms} ms`)) }, ms)
|
|
100
|
-
})
|
|
101
|
-
promise.catch(() => {}) // the race below may already be over: never an unhandled rejection
|
|
102
|
-
return { promise, done: () => { if (timer) clearTimeout(timer) } }
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
/** The body, capped WHILE it is read: over the limit the rest is never downloaded. */
|
|
106
|
-
const readBody = async (answer, message) => {
|
|
107
|
-
const declared = Number(answer?.headers?.get?.('content-length'))
|
|
108
|
-
if (Number.isFinite(declared) && declared > maxBytes) throw new Error(`${message}: ${declared} bytes declared, over the ${maxBytes} byte limit`)
|
|
109
|
-
const stream = answer?.body?.getReader?.()
|
|
110
|
-
if (!stream) {
|
|
111
|
-
// No stream (a test double, or an old transport): the cap still applies, at the end.
|
|
112
|
-
const text = await answer.text()
|
|
113
|
-
if (bytesOf(text) > maxBytes) throw new Error(`${message}: over the ${maxBytes} byte limit`)
|
|
114
|
-
return text
|
|
115
|
-
}
|
|
116
|
-
const chunks = []
|
|
117
|
-
let total = 0
|
|
118
|
-
for (;;) {
|
|
119
|
-
const { done, value } = await stream.read()
|
|
120
|
-
if (done) break
|
|
121
|
-
total += value?.byteLength ?? value?.length ?? 0
|
|
122
|
-
if (total > maxBytes) {
|
|
123
|
-
try { await stream.cancel() } catch { /* already closed */ }
|
|
124
|
-
throw new Error(`${message}: over the ${maxBytes} byte limit while reading`)
|
|
125
|
-
}
|
|
126
|
-
chunks.push(value)
|
|
127
|
-
}
|
|
128
|
-
const all = new Uint8Array(total)
|
|
129
|
-
let at = 0
|
|
130
|
-
for (const chunk of chunks) { all.set(chunk, at); at += chunk.byteLength ?? chunk.length }
|
|
131
|
-
return decodeBody(all)
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
const textOf = async (message) => {
|
|
135
|
-
if (typeof doFetch !== 'function') throw new Error('no transport')
|
|
136
|
-
const controller = typeof AbortController === 'function' ? new AbortController() : null
|
|
137
|
-
// One deadline for the request AND its body: the limit is the whole read, not just the handshake.
|
|
138
|
-
const clockOut = deadline(timeoutMs, () => controller?.abort())
|
|
139
|
-
try {
|
|
140
|
-
const answer = await Promise.race([
|
|
141
|
-
doFetch(url, {
|
|
142
|
-
method: 'GET',
|
|
143
|
-
redirect: 'error', // a redirect is how a catalog source gets swapped underneath us
|
|
144
|
-
credentials: 'omit',
|
|
145
|
-
headers: { accept: 'application/json' }, // never an Authorization header
|
|
146
|
-
...(controller ? { signal: controller.signal } : {}),
|
|
147
|
-
}),
|
|
148
|
-
clockOut.promise,
|
|
149
|
-
])
|
|
150
|
-
if (!answer || answer.ok !== true) throw new Error(`${message}: the source answered ${answer?.status ?? 'nothing'}`)
|
|
151
|
-
return await Promise.race([readBody(answer, message), clockOut.promise])
|
|
152
|
-
} finally {
|
|
153
|
-
clockOut.done()
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
const fetchOnce = async () => {
|
|
158
|
-
const text = await textOf('could not read the online catalog')
|
|
159
|
-
let parsed
|
|
160
|
-
try {
|
|
161
|
-
parsed = JSON.parse(text)
|
|
162
|
-
} catch (error) {
|
|
163
|
-
throw new Error(`the online catalog is not JSON: ${error instanceof Error ? error.message : String(error)}`)
|
|
164
|
-
}
|
|
165
|
-
const verdict = validate(parsed, options.validateOptions)
|
|
166
|
-
if (!verdict || verdict.ok !== true) {
|
|
167
|
-
const first = (verdict?.errors ?? ['the validator refused it']).slice(0, 3).join('; ')
|
|
168
|
-
throw new Error(`the online catalog was refused: ${first}`)
|
|
169
|
-
}
|
|
170
|
-
return parsed
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
const failure = (error) => {
|
|
174
|
-
const message = error instanceof Error ? error.message : String(error)
|
|
175
|
-
// A failed check is never cached: the last good catalog stands, marked stale, and the next read
|
|
176
|
-
// tries again. When there is none, the shipped catalog answers.
|
|
177
|
-
if (good) return { catalog: good.catalog, source: 'cached', checkedAt: iso(good.at), error: message, stale: true }
|
|
178
|
-
if (bundled) return bundledRead(message)
|
|
179
|
-
return { catalog: undefined, source: 'bundled', checkedAt: iso(clock()), error: message }
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
return {
|
|
183
|
-
source: url,
|
|
184
|
-
/**
|
|
185
|
-
* Read the catalog. Takes no arguments by design: no caller can point it anywhere.
|
|
186
|
-
* @returns { catalog, source, checkedAt, error?, stale? } — never rejects.
|
|
187
|
-
*/
|
|
188
|
-
async read() {
|
|
189
|
-
const at = clock()
|
|
190
|
-
if (good && at - good.at < cacheMs) return { catalog: good.catalog, source: 'cached', checkedAt: iso(good.at) }
|
|
191
|
-
if (typeof doFetch !== 'function') return bundledRead(undefined)
|
|
192
|
-
if (inflight) return inflight
|
|
193
|
-
inflight = (async () => {
|
|
194
|
-
try {
|
|
195
|
-
const parsed = await fetchOnce()
|
|
196
|
-
good = { catalog: out(parsed), at: clock() }
|
|
197
|
-
return { catalog: good.catalog, source: 'online', checkedAt: iso(good.at) }
|
|
198
|
-
} catch (error) {
|
|
199
|
-
return failure(error)
|
|
200
|
-
} finally {
|
|
201
|
-
inflight = null
|
|
202
|
-
}
|
|
203
|
-
})()
|
|
204
|
-
return inflight
|
|
205
|
-
},
|
|
206
|
-
/** The last known state without touching the network. */
|
|
207
|
-
peek() {
|
|
208
|
-
if (good) return { catalog: good.catalog, source: 'cached', checkedAt: iso(good.at) }
|
|
209
|
-
return bundled ? { catalog: bundled, source: 'bundled', checkedAt: iso(clock()) } : undefined
|
|
210
|
-
},
|
|
211
|
-
}
|
|
212
|
-
}
|