|
| 1 | +import { describe, expect, it } from 'vitest' |
| 2 | +import type { JsDelivrFileNode, PackageFileTree } from '../../shared/types' |
| 3 | +import { convertToFileTree } from '../../server/utils/file-tree' |
| 4 | + |
| 5 | +const getChildren = (node?: PackageFileTree): PackageFileTree[] => node?.children ?? [] |
| 6 | + |
| 7 | +describe('convertToFileTree', () => { |
| 8 | + it('converts jsDelivr nodes to a sorted tree with directories first', () => { |
| 9 | + const input: JsDelivrFileNode[] = [ |
| 10 | + { type: 'file', name: 'zeta.txt', size: 120 }, |
| 11 | + { |
| 12 | + type: 'directory', |
| 13 | + name: 'src', |
| 14 | + files: [ |
| 15 | + { type: 'file', name: 'b.ts', size: 5 }, |
| 16 | + { type: 'file', name: 'a.ts', size: 3 }, |
| 17 | + ], |
| 18 | + }, |
| 19 | + { type: 'file', name: 'alpha.txt', size: 10 }, |
| 20 | + { |
| 21 | + type: 'directory', |
| 22 | + name: 'assets', |
| 23 | + files: [{ type: 'file', name: 'logo.svg', size: 42 }], |
| 24 | + }, |
| 25 | + ] |
| 26 | + |
| 27 | + const tree = convertToFileTree(input) |
| 28 | + |
| 29 | + const names = tree.map(node => node.name) |
| 30 | + expect(names).toEqual(['assets', 'src', 'alpha.txt', 'zeta.txt']) |
| 31 | + |
| 32 | + const srcNode = tree.find(node => node.name === 'src') |
| 33 | + expect(srcNode?.type).toBe('directory') |
| 34 | + expect(getChildren(srcNode).map(child => child.name)).toEqual(['a.ts', 'b.ts']) |
| 35 | + }) |
| 36 | + |
| 37 | + it('builds correct paths and preserves file sizes', () => { |
| 38 | + const input: JsDelivrFileNode[] = [ |
| 39 | + { |
| 40 | + type: 'directory', |
| 41 | + name: 'src', |
| 42 | + files: [ |
| 43 | + { type: 'file', name: 'index.ts', size: 100 }, |
| 44 | + { |
| 45 | + type: 'directory', |
| 46 | + name: 'utils', |
| 47 | + files: [{ type: 'file', name: 'format.ts', size: 22 }], |
| 48 | + }, |
| 49 | + ], |
| 50 | + }, |
| 51 | + ] |
| 52 | + |
| 53 | + const tree = convertToFileTree(input) |
| 54 | + |
| 55 | + const src = tree[0] |
| 56 | + expect(src?.path).toBe('src') |
| 57 | + |
| 58 | + const indexFile = getChildren(src).find(child => child.name === 'index.ts') |
| 59 | + expect(indexFile?.path).toBe('src/index.ts') |
| 60 | + expect(indexFile?.size).toBe(100) |
| 61 | + |
| 62 | + const utilsDir = getChildren(src).find(child => child.name === 'utils') |
| 63 | + expect(utilsDir?.type).toBe('directory') |
| 64 | + |
| 65 | + const formatFile = getChildren(utilsDir).find(child => child.name === 'format.ts') |
| 66 | + expect(formatFile?.path).toBe('src/utils/format.ts') |
| 67 | + expect(formatFile?.size).toBe(22) |
| 68 | + }) |
| 69 | + |
| 70 | + it('returns an empty tree for empty input', () => { |
| 71 | + const tree = convertToFileTree([]) |
| 72 | + const empty: PackageFileTree[] = [] |
| 73 | + expect(tree).toEqual(empty) |
| 74 | + }) |
| 75 | +}) |
0 commit comments