dshmarket 1.2.2 → 1.2.4

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/install.ts ADDED
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Install orchestration: collection-repo retargeting, post-install
3
+ * validation that keeps broken pieces from bricking the next boot, and
4
+ * update staleness detection. Every function takes the plugin runner as a
5
+ * parameter so tests can substitute a recording fake.
6
+ */
7
+
8
+ import { existsSync } from 'node:fs'
9
+ import { join } from 'node:path'
10
+ import type { InstallResult, PluginRunner } from './dsh-cli.ts'
11
+ import { classifyPnpmFailure } from './pnpm-compat.ts'
12
+ import { entryArtifactExists, hasDshManifest, pluginSubdirs, profileDir, readInstalled } from './profile.ts'
13
+ import { logEvent } from './log.ts'
14
+
15
+ /**
16
+ * Run one plugin command with automatic recovery from the pnpm-major drift
17
+ * failure (#20 bug 2): when the modules directory was built by a different
18
+ * pnpm major, pnpm's documented remedy is one `install` to recreate it —
19
+ * do that silently and retry the original command once. Any recognized
20
+ * failure that survives gets its bilingual explanation appended to stderr
21
+ * so the UI shows an actionable message instead of a wall of text (#20 bug 3).
22
+ */
23
+ export async function withHoistRecovery(run: PluginRunner, profile: string, pluginArgs: string[]): Promise<InstallResult> {
24
+ let result = await run(profile, pluginArgs)
25
+ const ok = (r: InstallResult): boolean => r.exitCode === 0 && !r.timedOut && !r.cancelled
26
+ if (!ok(result) && classifyPnpmFailure(`${result.stderr}\n${result.stdout}`)?.code === 'hoist-pattern-diff') {
27
+ logEvent('warn', 'install', `modules dir was built by a different pnpm major — rebuilding (pnpm install) and retrying once`)
28
+ // --no-frozen-lockfile: the market runs pnpm with CI=true (TTY hangs),
29
+ // where a lockfile written by the old major would otherwise be refused.
30
+ const rebuild = await run(profile, ['install', '--no-frozen-lockfile'])
31
+ if (ok(rebuild)) result = await run(profile, pluginArgs)
32
+ }
33
+ if (!ok(result) && !result.cancelled) {
34
+ const failure = classifyPnpmFailure(`${result.stderr}\n${result.stdout}`)
35
+ if (failure !== null) result = { ...result, stderr: `${result.stderr}\n\n${failure.message}` }
36
+ }
37
+ return result
38
+ }
39
+
40
+ /**
41
+ * Some registry entries point at collection repos whose actual plugin lives
42
+ * in a subdirectory — the root has no package.json (or a workspace root with
43
+ * no dsh surface), and pnpm installs the bare fileset with exit 0. Detect
44
+ * that junk install, drop it, and re-add each plugin subdirectory through
45
+ * pnpm's `#path:` selector (#18).
46
+ * @returns overall success (true when nothing needed retargeting).
47
+ */
48
+ export async function retargetCollections(
49
+ run: PluginRunner, profile: string, before: Set<string>, target: string,
50
+ ): Promise<boolean> {
51
+ if (!target.startsWith('github:')) return true
52
+ const junk = Object.keys(readInstalled(profile)).filter((name) => {
53
+ if (before.has(name)) return false
54
+ const root = join(profileDir(profile), 'node_modules', name)
55
+ if (!existsSync(join(root, 'package.json'))) return true
56
+ return !hasDshManifest(root)
57
+ })
58
+ let allOk = true
59
+ for (const name of junk) {
60
+ const root = join(profileDir(profile), 'node_modules', name)
61
+ const candidates = pluginSubdirs(root)
62
+ logEvent('info', 'install', `${name}: collection repo (root declares no dsh manifest); plugins inside: ${candidates.join(', ') || 'none'}`)
63
+ await run(profile, ['remove', name])
64
+ if (candidates.length === 0) {
65
+ allOk = false
66
+ continue
67
+ }
68
+ for (const sub of candidates) {
69
+ const result = await run(profile, ['add', `${target}#path:/${sub}`])
70
+ if (result.exitCode !== 0 || result.timedOut) {
71
+ allOk = false
72
+ logEvent('error', 'install',
73
+ `${target}#path:/${sub}: exit=${String(result.exitCode)}${result.timedOut ? ' TIMEOUT' : ''} — ${(result.stderr || result.stdout).slice(-220)}`)
74
+ }
75
+ }
76
+ }
77
+ return allOk
78
+ }
79
+
80
+ /**
81
+ * Fake-success guard (#18): validate every package the install added. A
82
+ * piece without a dsh manifest or without its declared entry artifact
83
+ * (source-only checkout, build blocked by pnpm allowBuilds) would brick the
84
+ * next boot, so it is removed on the spot.
85
+ * @returns names kept and names removed as broken.
86
+ */
87
+ export async function validateAddedPlugins(
88
+ run: PluginRunner, profile: string, before: Set<string>,
89
+ ): Promise<{ keep: string[]; removedBroken: string[] }> {
90
+ const addedNow = Object.keys(readInstalled(profile)).filter(n => !before.has(n))
91
+ const keep: string[] = []
92
+ const removedBroken: string[] = []
93
+ for (const n of addedNow) {
94
+ const dir = join(profileDir(profile), 'node_modules', n)
95
+ if (hasDshManifest(dir) && entryArtifactExists(dir)) {
96
+ keep.push(n)
97
+ } else {
98
+ removedBroken.push(n)
99
+ await run(profile, ['remove', n])
100
+ }
101
+ }
102
+ return { keep, removedBroken }
103
+ }
104
+
105
+ /**
106
+ * Whether a clean-exit update actually changed nothing — pnpm's
107
+ * minimumReleaseAge silently keeps the old version and exits 0 when the new
108
+ * release is "too young" (#13, #22), so a clean exit alone does not mean the
109
+ * update happened.
110
+ */
111
+ export function isStaleUpdate(check: {
112
+ isGit: boolean
113
+ beforeVersion: string | null
114
+ afterVersion: string | null
115
+ beforeCommit: string | null
116
+ afterCommit: string | null
117
+ }): boolean {
118
+ return check.isGit
119
+ ? check.beforeCommit !== null && check.afterCommit === check.beforeCommit
120
+ : check.beforeVersion !== null && check.afterVersion === check.beforeVersion
121
+ }
122
+
123
+ /**
124
+ * Package names pnpm reported as having their build scripts ignored
125
+ * ("Ignored build scripts: esbuild, koffi."). Empty when none.
126
+ * (#6 by @qichuang321.)
127
+ */
128
+ export function parseIgnoredBuilds(stdout: string, stderr: string): string[] {
129
+ const m = /Ignored build scripts:?\s*([^\n]+)/i.exec(`${stdout}\n${stderr}`)
130
+ if (m === null) return []
131
+ const found: string[] = []
132
+ for (const chunk of m[1].split(',')) {
133
+ // Entries may carry a version suffix and the sentence's final period.
134
+ const trimmed = chunk.trim().replace(/\.$/, '')
135
+ if (trimmed === '') continue
136
+ const at = trimmed.lastIndexOf('@')
137
+ const name = at > 0 ? trimmed.slice(0, at) : trimmed
138
+ if (name !== '' && !found.includes(name)) found.push(name)
139
+ }
140
+ return found
141
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * pnpm compatibility layer — everything the market needs to know about how
3
+ * different pnpm majors behave inside a dsh profile directory, kept pure and
4
+ * separately testable (test/unit + test/integration exercise this module
5
+ * against real pnpm 9/10/11).
6
+ *
7
+ * Verified behavior matrix (2026-08, pnpm 9.15.9 / 10.28.2 / 11.21.0):
8
+ * - workspace root, `add` without -w: pnpm 9 fails ERR_PNPM_ADDING_TO_ROOT;
9
+ * pnpm 10/11 succeed.
10
+ * - `add -w` where NO pnpm-workspace.yaml exists: ALL majors fail with
11
+ * "--workspace-root may only be used inside a workspace".
12
+ * - modules dir built by pnpm 9, then pnpm 10/11 mutate it:
13
+ * ERR_PNPM_PUBLIC_HOIST_PATTERN_DIFF (defaults drifted between majors).
14
+ */
15
+
16
+ import { existsSync } from 'node:fs'
17
+ import { join } from 'node:path'
18
+
19
+
20
+ /**
21
+ * Decide the argv for a `dsh plugin <add|remove> …` call in the given profile.
22
+ *
23
+ * pnpm 9 refuses to add at a workspace root without -w (#17, #20); every
24
+ * pnpm major refuses -w when the directory is NOT a workspace. So the flag
25
+ * is injected exactly when the profile has a pnpm-workspace.yaml.
26
+ * @param profileDir - resolved profile directory (owns pnpm-workspace.yaml, or not).
27
+ * @param pluginArgs - the raw args, e.g. ['add', 'dshmarket@latest'].
28
+ * @returns args with -w injected when — and only when — the profile is a workspace root.
29
+ */
30
+ export function pluginArgsFor(profileDir: string, pluginArgs: string[]): string[] {
31
+ if (pluginArgs[0] !== 'add' && pluginArgs[0] !== 'remove') return pluginArgs
32
+ if (!existsSync(join(profileDir, 'pnpm-workspace.yaml'))) return pluginArgs
33
+ return [pluginArgs[0], '-w', ...pluginArgs.slice(1)]
34
+ }
35
+
36
+ /** One recognized pnpm failure, with a bilingual explanation for the UI. */
37
+ export interface PnpmFailure {
38
+ code: 'adding-to-root' | 'not-a-workspace' | 'hoist-pattern-diff' | 'pnpm-missing'
39
+ /** Bilingual, actionable message shown to the user instead of the raw wall of text. */
40
+ message: string
41
+ /** True when re-running `pnpm install` in the profile is the documented recovery. */
42
+ recoverable: boolean
43
+ }
44
+
45
+ /**
46
+ * Map a failed pnpm run's combined output to a known failure mode.
47
+ *
48
+ * dsh's own wrapper line ("dsh: pnpm failed in profile directory …") names no
49
+ * cause, so the market must recognize pnpm's real diagnostics itself (#20).
50
+ * @param output - stdout+stderr of the failed run.
51
+ * @returns the classified failure, or null when unrecognized (raw output is then shown as-is).
52
+ */
53
+ export function classifyPnpmFailure(output: string): PnpmFailure | null {
54
+ if (output.includes('ERR_PNPM_PUBLIC_HOIST_PATTERN_DIFF')) {
55
+ return {
56
+ code: 'hoist-pattern-diff',
57
+ recoverable: true,
58
+ message: 'profile 的 node_modules 是旧版 pnpm 创建的,与当前 pnpm 的默认配置不兼容,需要重建后重试 / this profile\'s node_modules was created by a different pnpm major; it must be rebuilt (pnpm install) before changes can be applied',
59
+ }
60
+ }
61
+ if (output.includes('ERR_PNPM_ADDING_TO_ROOT')) {
62
+ return {
63
+ code: 'adding-to-root',
64
+ recoverable: false,
65
+ message: 'pnpm 拒绝在 workspace 根目录安装(缺少 -w)。这是市场的 bug,请升级 dshmarket 到最新版 / pnpm refused to add at a workspace root (missing -w); this is a market bug — please update dshmarket',
66
+ }
67
+ }
68
+ if (/--workspace-root may only be used inside a workspace/i.test(output)) {
69
+ return {
70
+ code: 'not-a-workspace',
71
+ recoverable: false,
72
+ message: 'profile 目录不是 pnpm workspace,却传入了 -w。这是市场的 bug,请升级 dshmarket 到最新版 / -w was passed but the profile is not a pnpm workspace; this is a market bug — please update dshmarket',
73
+ }
74
+ }
75
+ if (output.includes('pnpm not found on PATH')) {
76
+ return {
77
+ code: 'pnpm-missing',
78
+ recoverable: false,
79
+ message: '找不到 pnpm,请先在市场页顶部一键安装组件 / pnpm is not on PATH — use the one-click setup at the top of the market page',
80
+ }
81
+ }
82
+ return null
83
+ }
package/src/profile.ts ADDED
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Profile filesystem reads — everything the market learns from a dsh
3
+ * profile directory (manifest, lockfile, installed package trees). Pure
4
+ * functions of the directory contents; no processes, no network.
5
+ */
6
+
7
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
8
+ import { homedir } from 'node:os'
9
+ import { join } from 'node:path'
10
+
11
+ /** Resolve a profile name to its directory under DSH_HOME (default ~/.dsh). */
12
+ export function profileDir(profile: string): string {
13
+ const home = process.env.DSH_HOME ?? join(homedir(), '.dsh')
14
+ return join(home, 'profiles', profile)
15
+ }
16
+
17
+ /**
18
+ * The in-box bundles dsh's profile templates install themselves — the ONLY
19
+ * names the market hides from the installed list. Community plugins may
20
+ * legitimately publish under the official scope (#28), so a whole-scope
21
+ * filter would make them invisible and fail install validation.
22
+ * (Diagnosis and fix proposed in #28 by @Lograthmic.)
23
+ */
24
+ const INBOX_BUNDLES = new Set([
25
+ '@deepseek-ai/dsh-base',
26
+ '@deepseek-ai/dsh-web-app',
27
+ '@deepseek-ai/dsh-headless',
28
+ ])
29
+
30
+ /** Community dependencies of the profile (in-box bundles filtered out). */
31
+ export function readInstalled(profile: string): Record<string, string> {
32
+ try {
33
+ const manifest = JSON.parse(readFileSync(join(profileDir(profile), 'package.json'), 'utf8')) as {
34
+ dependencies?: Record<string, string>
35
+ }
36
+ const installed: Record<string, string> = {}
37
+ for (const [name, spec] of Object.entries(manifest.dependencies ?? {})) {
38
+ if (!INBOX_BUNDLES.has(name)) installed[name] = spec
39
+ }
40
+ return installed
41
+ } catch {
42
+ return {}
43
+ }
44
+ }
45
+
46
+ /** The version actually present in the profile's node_modules, or null. */
47
+ export function readInstalledVersion(profile: string, name: string): string | null {
48
+ try {
49
+ const manifest = JSON.parse(
50
+ readFileSync(join(profileDir(profile), 'node_modules', name, 'package.json'), 'utf8'),
51
+ ) as { version?: string }
52
+ return manifest.version ?? null
53
+ } catch {
54
+ return null
55
+ }
56
+ }
57
+
58
+ /** Pinned commit per `owner/repo` from the profile lockfile's codeload tarball URLs. */
59
+ export function readLockCommits(profile: string): Map<string, string> {
60
+ const commits = new Map<string, string>()
61
+ try {
62
+ const lock = readFileSync(join(profileDir(profile), 'pnpm-lock.yaml'), 'utf8')
63
+ for (const m of lock.matchAll(/codeload\.github\.com\/([^/\s]+\/[^/\s]+)\/tar\.gz\/([0-9a-f]{40})/g)) {
64
+ commits.set(m[1].toLowerCase(), m[2])
65
+ }
66
+ } catch { /* no lockfile — no git installs to report */ }
67
+ return commits
68
+ }
69
+
70
+ /** True when the installed package's manifest declares a dsh plugin surface. */
71
+ export function hasDshManifest(dir: string): boolean {
72
+ try {
73
+ const manifest = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as { dsh?: unknown }
74
+ return manifest.dsh !== undefined
75
+ } catch {
76
+ return false
77
+ }
78
+ }
79
+
80
+ /**
81
+ * True when the package's declared entry artifact actually exists — github
82
+ * source checkouts of build-required plugins ship no lib/, and promoting one
83
+ * into the bundle layer bricks the next boot (ERR_MODULE_NOT_FOUND kills the
84
+ * whole profile, #18).
85
+ */
86
+ export function entryArtifactExists(dir: string): boolean {
87
+ try {
88
+ const manifest = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as {
89
+ main?: string
90
+ exports?: Record<string, unknown> | string
91
+ }
92
+ const candidates: string[] = []
93
+ if (typeof manifest.main === 'string') candidates.push(manifest.main)
94
+ const rootExport = typeof manifest.exports === 'string'
95
+ ? manifest.exports
96
+ : (manifest.exports as Record<string, unknown> | undefined)?.['.']
97
+ if (typeof rootExport === 'string') candidates.push(rootExport)
98
+ else if (rootExport !== null && typeof rootExport === 'object') {
99
+ for (const value of Object.values(rootExport)) if (typeof value === 'string') candidates.push(value)
100
+ }
101
+ if (candidates.length === 0) candidates.push('index.js')
102
+ return candidates.some(rel => existsSync(join(dir, rel)))
103
+ } catch {
104
+ return false
105
+ }
106
+ }
107
+
108
+ /** Plugin subdirectories (depth 2) of a collection checkout, as relative paths. */
109
+ export function pluginSubdirs(root: string): string[] {
110
+ const found: string[] = []
111
+ let level1: string[] = []
112
+ try {
113
+ level1 = readdirSync(root, { withFileTypes: true })
114
+ .filter(dirent => dirent.isDirectory() && /^[A-Za-z0-9_.-]+$/.test(dirent.name) && dirent.name !== 'node_modules')
115
+ .map(dirent => dirent.name)
116
+ } catch {
117
+ return found
118
+ }
119
+ for (const sub of level1) {
120
+ if (hasDshManifest(join(root, sub))) {
121
+ found.push(sub)
122
+ continue
123
+ }
124
+ try {
125
+ for (const inner of readdirSync(join(root, sub), { withFileTypes: true })) {
126
+ if (!inner.isDirectory() || !/^[A-Za-z0-9_.-]+$/.test(inner.name) || inner.name === 'node_modules') continue
127
+ if (hasDshManifest(join(root, sub, inner.name))) found.push(`${sub}/${inner.name}`)
128
+ }
129
+ } catch { /* unreadable level — skip */ }
130
+ if (found.length >= 8) break
131
+ }
132
+ return found.slice(0, 8)
133
+ }
134
+
135
+ /**
136
+ * Allow the given packages' build scripts in the profile's
137
+ * pnpm-workspace.yaml `allowBuilds` block (the key dsh profiles use),
138
+ * merging with existing entries and leaving the rest of the yaml intact.
139
+ * (#6 by @qichuang321.)
140
+ * @returns every package now allowed.
141
+ */
142
+ export function setAllowBuilds(profile: string, packages: string[]): string[] {
143
+ const file = join(profileDir(profile), 'pnpm-workspace.yaml')
144
+ let yaml = ''
145
+ try { yaml = readFileSync(file, 'utf8') } catch { /* created below */ }
146
+ const blockRe = /allowBuilds:\n((?:[ \t]+[^\n]*\n?)*)/
147
+ const map: Record<string, string> = {}
148
+ const blockMatch = blockRe.exec(yaml)
149
+ if (blockMatch !== null) {
150
+ for (const line of blockMatch[1].split('\n')) {
151
+ const m = /^[ \t]+([^:\s]+(?:\/[^:\s]+)?)\s*:\s*(\S.*)?$/.exec(line)
152
+ if (m !== null) map[m[1]] = m[2] ?? 'true'
153
+ }
154
+ }
155
+ for (const pkg of packages) {
156
+ if (/^[A-Za-z0-9@/_.-]+$/.test(pkg)) map[pkg] = 'true'
157
+ }
158
+ const block = Object.entries(map).map(([k, v]) => ` ${k}: ${v}`).join('\n')
159
+ const blockText = `allowBuilds:\n${block}\n`
160
+ writeFileSync(file, blockMatch !== null ? yaml.replace(blockRe, blockText) : `${yaml.replace(/\n?$/, '\n')}${blockText}`)
161
+ return Object.keys(map)
162
+ }