plugin.spec.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. /**
  2. * `dsh plugin add` and `remove` through the shared installer: a temporary
  3. * harness home, a fake pnpm that stages packages and edits the manifest the
  4. * way the real one does, and a fake probe. Nothing boots.
  5. */
  6. import { EventEmitter } from 'node:events'
  7. import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
  8. import { tmpdir } from 'node:os'
  9. import { join } from 'node:path'
  10. import { PassThrough } from 'node:stream'
  11. import type { ChildProcess } from 'node:child_process'
  12. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  13. import { readProfileManifest, resolveProfileDir, type probePackage } from '@deepseek-ai/dsh-app-boot'
  14. import type { SpawnLike } from '@deepseek-ai/dsh-plugin-manager'
  15. import { runPlugin } from '../src/plugin.ts'
  16. let home: string
  17. let previousHome: string | undefined
  18. let stderr: string
  19. let stdout: string
  20. /** The FORCE_COLOR each fake pnpm run was spawned with. */
  21. let spawnEnvs: (string | undefined)[] = []
  22. beforeEach(() => {
  23. home = mkdtempSync(join(tmpdir(), 'dsh-plugin-command-'))
  24. previousHome = process.env.DSH_HOME
  25. process.env.DSH_HOME = home
  26. stderr = ''
  27. stdout = ''
  28. spawnEnvs = []
  29. vi.spyOn(process.stderr, 'write').mockImplementation((chunk) => { stderr += String(chunk); return true })
  30. vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => { stdout += String(chunk); return true })
  31. })
  32. afterEach(() => {
  33. vi.restoreAllMocks()
  34. if (previousHome === undefined) delete process.env.DSH_HOME
  35. else process.env.DSH_HOME = previousHome
  36. rmSync(home, { recursive: true, force: true })
  37. })
  38. /** Stage one package under the profile's node_modules and record it as a dependency, as `pnpm add` does. */
  39. function install(profileDir: string, name: string, bundle: boolean): void {
  40. const dir = join(profileDir, 'node_modules', name)
  41. mkdirSync(dir, { recursive: true })
  42. writeFileSync(join(dir, 'package.json'), JSON.stringify({
  43. name, version: '1.0.0', type: 'module',
  44. ...bundle ? { dsh: { bundle: { patch: './cordis.patch.yml' } } } : {},
  45. }))
  46. if (bundle) writeFileSync(join(dir, 'cordis.patch.yml'), '- insert:\n - id: hello\n name: cordis:good\n')
  47. const path = join(profileDir, 'package.json')
  48. const manifest = JSON.parse(readFileSync(path, 'utf8')) as { dependencies?: Record<string, string> }
  49. writeFileSync(path, JSON.stringify({ ...manifest, dependencies: { ...manifest.dependencies, [name]: '1.0.0' } }, null, 2))
  50. }
  51. /** Forget one package, as `pnpm remove` does. */
  52. function uninstall(profileDir: string, name: string): void {
  53. const path = join(profileDir, 'package.json')
  54. const manifest = JSON.parse(readFileSync(path, 'utf8')) as { dependencies?: Record<string, string> }
  55. const { [name]: _gone, ...remaining } = manifest.dependencies ?? {}
  56. writeFileSync(path, JSON.stringify({ ...manifest, dependencies: remaining }, null, 2))
  57. rmSync(join(profileDir, 'node_modules', name), { recursive: true, force: true })
  58. }
  59. /** A pnpm that installs `ext-bundle` as a bundle and everything else as a plain library, or fails as told. */
  60. function fakePnpm(calls: string[][], failWith?: { code: number } | { error: NodeJS.ErrnoException }): SpawnLike {
  61. return (_command, args, options) => {
  62. calls.push([...args])
  63. spawnEnvs.push(options.env?.FORCE_COLOR)
  64. const child = new EventEmitter() as EventEmitter & { stdout: PassThrough; stderr: PassThrough }
  65. child.stdout = new PassThrough()
  66. child.stderr = new PassThrough()
  67. setTimeout(() => {
  68. if (failWith !== undefined && 'error' in failWith) {
  69. child.emit('error', failWith.error)
  70. return
  71. }
  72. if (failWith !== undefined) {
  73. child.stderr.write('ERR_PNPM_FETCH\n')
  74. child.emit('close', failWith.code)
  75. return
  76. }
  77. const [verb, target] = args
  78. const profileDir = options.cwd as string
  79. if (verb === 'add' && target !== undefined) install(profileDir, target, target === 'ext-bundle')
  80. if (verb === 'remove' && target !== undefined) uninstall(profileDir, target)
  81. // A coloured line, as a pnpm told to colour anyway would print one.
  82. child.stdout.write(`\u001b[32m${verb === 'add' ? '+' : '-'}\u001b[39m ${String(target)}\n`)
  83. child.emit('close', 0)
  84. }, 5)
  85. return child as unknown as ChildProcess
  86. }
  87. }
  88. /** A probe that reads the staged manifest: a package with `dsh.bundle` is a bundle, anything else a library. */
  89. const fakeProbe: typeof probePackage = (options) => {
  90. const manifest = JSON.parse(readFileSync(join(options.profileDir, 'node_modules', options.packageName, 'package.json'), 'utf8')) as { dsh?: { bundle?: unknown } }
  91. return Promise.resolve({
  92. packageName: options.packageName,
  93. kind: manifest.dsh?.bundle === undefined ? 'library' : 'bundle',
  94. ok: true,
  95. cordisSameCopy: null,
  96. rows: [],
  97. overrides: [],
  98. addable: [],
  99. checkedAt: new Date().toISOString(),
  100. })
  101. }
  102. describe('dsh plugin', () => {
  103. it('lets pnpm colour its output when stdout is a terminal', async () => {
  104. const calls: string[][] = []
  105. const descriptor = Object.getOwnPropertyDescriptor(process.stdout, 'isTTY')
  106. Object.defineProperty(process.stdout, 'isTTY', { value: true, configurable: true })
  107. try {
  108. expect(await runPlugin('web', ['add', 'ext-bundle'], { spawn: fakePnpm(calls), probe: fakeProbe })).toBe(0)
  109. } finally {
  110. if (descriptor === undefined) delete (process.stdout as { isTTY?: boolean }).isTTY
  111. else Object.defineProperty(process.stdout, 'isTTY', descriptor)
  112. }
  113. expect(spawnEnvs).toEqual(['1'])
  114. expect(stdout).toContain('\u001b[32m+\u001b[39m ext-bundle')
  115. })
  116. it('add initializes the profile, installs through the installer, enables the new bundle, and removes a plain library again', async () => {
  117. const calls: string[][] = []
  118. const code = await runPlugin('web', ['add', 'ext-bundle', 'ext-lib'], { spawn: fakePnpm(calls), probe: fakeProbe })
  119. expect(code).toBe(0)
  120. const profileDir = resolveProfileDir('web', home)
  121. expect(stderr).toContain(`dsh: initialized profile web at ${profileDir}`)
  122. expect(calls).toEqual([['add', 'ext-bundle'], ['add', 'ext-lib'], ['remove', 'ext-lib']])
  123. const manifest = readProfileManifest('dsh', profileDir)
  124. expect(Object.keys(manifest.dependencies ?? {})).toContain('ext-bundle')
  125. expect(Object.keys(manifest.dependencies ?? {})).not.toContain('ext-lib')
  126. expect(manifest.dsh?.profile?.bundles).toContain('ext-bundle')
  127. // The log reaches its readers plain: colours are off for the child and stripped from what it still prints.
  128. expect(spawnEnvs).toEqual(['0', '0', '0'])
  129. expect(stdout).toContain('+ ext-bundle')
  130. expect(stdout).not.toContain('\u001b[')
  131. expect(stderr).toContain('dsh: removed ext-lib again: declares neither a dsh bundle nor a plugin module')
  132. expect(existsSync(join(profileDir, '.dsh-plugins', 'ext-bundle.json'))).toBe(true)
  133. })
  134. it('remove goes through the installer and forgets the probe record', async () => {
  135. const calls: string[][] = []
  136. await runPlugin('web', ['add', 'ext-bundle'], { spawn: fakePnpm(calls), probe: fakeProbe })
  137. const code = await runPlugin('web', ['remove', 'ext-bundle'], { spawn: fakePnpm(calls), probe: fakeProbe })
  138. expect(code).toBe(0)
  139. expect(calls).toEqual([['add', 'ext-bundle'], ['remove', 'ext-bundle']])
  140. const profileDir = resolveProfileDir('web', home)
  141. const manifest = readProfileManifest('dsh', profileDir)
  142. expect(Object.keys(manifest.dependencies ?? {})).not.toContain('ext-bundle')
  143. expect(manifest.dsh?.profile?.bundles).not.toContain('ext-bundle')
  144. expect(existsSync(join(profileDir, '.dsh-plugins', 'ext-bundle.json'))).toBe(false)
  145. })
  146. it('reports a failed pnpm run with its exit code, the git hint, and a missing pnpm as 127', async () => {
  147. const failed = await runPlugin('web', ['add', 'github:acme/plugin'], { spawn: fakePnpm([], { code: 1 }), probe: fakeProbe })
  148. expect(failed).toBe(1)
  149. expect(stderr).toContain('dsh: pnpm failed in profile directory')
  150. expect(stderr).toContain('git-hosted plugins build on install via their prepare script')
  151. const error = Object.assign(new Error('spawn pnpm ENOENT'), { code: 'ENOENT' })
  152. const missing = await runPlugin('web', ['add', 'ext-bundle'], { spawn: fakePnpm([], { error }), probe: fakeProbe })
  153. expect(missing).toBe(127)
  154. expect(stderr).toContain('dsh: pnpm not found on PATH')
  155. })
  156. })