// oxlint-disable vitest/no-hooks -- the temporary workspace roots are cleaned up once per test file import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import path from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import { discoverPackages, runSyncNpmmirror, syncPackage, } from '../npmmirror.js' import type { SyncRequest } from '../npmmirror.js' const ROOT = path.resolve(import.meta.dirname, '../..') const SYNC_API = 'https://registry-direct.npmmirror.com/-/package' const roots: string[] = [] const createWorkspace = async ( files: Record, ): Promise => { const root = await mkdtemp(path.join(tmpdir(), 'npmmirror-')) roots.push(root) await Promise.all( Object.entries(files).map(async ([file, content]) => { const filePath = path.join(root, file) await mkdir(path.dirname(filePath), { recursive: true }) await writeFile(filePath, content, 'utf8') }), ) return root } const manifest = (name: string): string => JSON.stringify({ name }, null, 2) const okRequest = (): SyncRequest => () => Promise.resolve(new Response(null, { status: 200 })) // Return the given failure for a matching package and a success otherwise. const createRequest = ( failures: Record, ): SyncRequest => { const entries = Object.entries(failures) return (url) => { const failure = entries.find(([name]) => url.includes(name)) return Promise.resolve( failure ? new Response(null, failure[1]) : new Response(null, { status: 200 }), ) } } // Capture everything the runner writes, so tests can assert on the messages. const captureOutput = (): (() => string) => { const log = vi.spyOn(console, 'log').mockImplementation(() => {}) const error = vi.spyOn(console, 'error').mockImplementation(() => {}) return () => [...log.mock.calls, ...error.mock.calls].flat().join('\n') } describe('npmmirror sync', () => { afterEach(async () => { vi.restoreAllMocks() await Promise.all( roots.splice(0).map((root) => rm(root, { force: true, recursive: true })), ) }) describe('discoverPackages()', () => { it('discovers the packages of plugins, themes and tools', async () => { const root = await createWorkspace({ 'plugins/features/plugin-a/package.json': manifest('@vuepress/plugin-a'), 'plugins/markdown/plugin-b/package.json': manifest('@vuepress/plugin-b'), 'plugins/.hidden/plugin-c/package.json': manifest('@vuepress/plugin-c'), 'themes/theme-a/package.json': manifest('@vuepress/theme-a'), 'tools/tool-a/package.json': manifest('create-a'), }) const names = await discoverPackages(root) // `readdir` does not guarantee an order, so compare the sorted names. expect(names.sort()).toStrictEqual( [ '@vuepress/plugin-a', '@vuepress/plugin-b', '@vuepress/theme-a', 'create-a', ].sort(), ) }) it('discovers the packages of this repository', async () => { const names = await discoverPackages(ROOT) expect(names).toContain('@vuepress/plugin-shiki') expect(names).toContain('@vuepress/theme-default') expect(names.length).toBeGreaterThan(60) }) }) describe('syncPackage()', () => { it('sends an empty PUT request to the sync endpoint', async () => { const request = vi.fn(okRequest()) await expect( syncPackage('@vuepress/plugin-a', { request }), ).resolves.toBeUndefined() expect(request).toHaveBeenCalledTimes(1) const [[url, init]] = request.mock.calls expect(url).toBe(`${SYNC_API}/@vuepress/plugin-a/syncs`) expect(init.method).toBe('PUT') expect(init.headers).toStrictEqual({ 'Content-Length': '0' }) expect(init.body).toBeUndefined() expect(init.signal).toBeInstanceOf(AbortSignal) }) it('rejects a non-2xx response with the package name and status', async () => { const request: SyncRequest = () => Promise.resolve( new Response('rate limited', { status: 429, statusText: 'Too Many Requests', }), ) await expect( syncPackage('@vuepress/plugin-a', { request }), ).rejects.toThrow( 'Failed to sync @vuepress/plugin-a to npmmirror: HTTP 429 Too Many Requests', ) }) it('preserves the HTTP status when the response body cannot be canceled', async () => { const cancel = vi.fn<() => Promise>(() => Promise.reject(new Error('cancel failed')), ) const request: SyncRequest = () => Promise.resolve({ body: { cancel }, ok: false, status: 503, statusText: 'Service Unavailable', } as unknown as Response) await expect( syncPackage('@vuepress/plugin-a', { request }), ).rejects.toThrow( 'Failed to sync @vuepress/plugin-a to npmmirror: HTTP 503 Service Unavailable', ) expect(cancel).toHaveBeenCalledTimes(1) }) it('reports a network error with the package name', async () => { const request: SyncRequest = () => Promise.reject(new Error('connect ECONNREFUSED')) await expect( syncPackage('@vuepress/plugin-a', { request }), ).rejects.toThrow( 'Failed to sync @vuepress/plugin-a to npmmirror: connect ECONNREFUSED', ) }) it('rejects a request that exceeds the timeout', async () => { const request: SyncRequest = (_url, init) => new Promise((_resolve, reject) => { init.signal?.addEventListener( 'abort', () => reject( new DOMException( 'The operation was aborted due to timeout', 'TimeoutError', ), ), { once: true }, ) }) await expect( syncPackage('@vuepress/plugin-a', { request, timeout: 20 }), ).rejects.toThrow( 'Failed to sync @vuepress/plugin-a to npmmirror: timed out after 20 ms', ) }) }) describe('runSyncNpmmirror()', () => { it('returns 0 when every package is synced', async () => { const root = await createWorkspace({ 'plugins/features/plugin-a/package.json': manifest('@vuepress/plugin-a'), 'themes/theme-a/package.json': manifest('@vuepress/theme-a'), 'tools/tool-a/package.json': manifest('create-a'), }) const request = vi.fn(okRequest()) const output = captureOutput() await expect(runSyncNpmmirror(root, { request })).resolves.toBe(0) expect(request).toHaveBeenCalledTimes(3) expect(output()).toContain('Synced 3 package(s) to npmmirror.') }) it('returns 1 and reports every package that failed', async () => { const root = await createWorkspace({ 'plugins/features/plugin-a/package.json': manifest('@vuepress/plugin-a'), 'plugins/features/plugin-b/package.json': manifest('@vuepress/plugin-b'), 'themes/theme-a/package.json': manifest('@vuepress/theme-a'), 'tools/tool-a/package.json': manifest('create-a'), }) const request = vi.fn( createRequest({ '@vuepress/plugin-a': { status: 500, statusText: 'Internal Server Error', }, 'create-a': { status: 403, statusText: 'Forbidden' }, }), ) const output = captureOutput() await expect(runSyncNpmmirror(root, { request })).resolves.toBe(1) // A failure does not stop the remaining packages. expect(request).toHaveBeenCalledTimes(4) const text = output() expect(text).toContain( 'Failed to sync @vuepress/plugin-a to npmmirror: HTTP 500 Internal Server Error', ) expect(text).toContain( 'Failed to sync create-a to npmmirror: HTTP 403 Forbidden', ) expect(text).toContain('Failed to sync 2 of 4 package(s) to npmmirror') expect(text).toContain('@vuepress/plugin-a') expect(text).toContain('create-a') }) it('returns 1 when the packages cannot be discovered', async () => { const root = await createWorkspace({ 'README.md': '# empty' }) const output = captureOutput() await expect(runSyncNpmmirror(root)).resolves.toBe(1) expect(output()).toContain('Failed to discover the packages to sync') }) }) })