XiaoDaiGua-Ray 403fdd589a feat!: rebuild Ray Template as a monorepo
Share workspace packages between Ray Admin and the interactive docs.

BREAKING CHANGE: v6 is a new major line. v5 stays on legacy/v5.
2026-11-04 14:01:28 +08:00

75 lines
2.5 KiB
JavaScript

import {
existsSync,
readdirSync,
readFileSync,
realpathSync,
writeFileSync,
} from 'node:fs'
import { dirname, relative, resolve, sep } from 'node:path'
import { fileURLToPath } from 'node:url'
import { format, resolveConfig } from 'prettier'
export const iconsRoot = resolve(
dirname(fileURLToPath(import.meta.url)),
'../src',
)
const manifest = resolve(iconsRoot, 'manifest.ts')
export function iconNameFromPath(filePath, root = iconsRoot) {
const name = relative(root, filePath)
.split(sep)
.join('/')
.replace(/\.svg$/, '')
if (!/^[a-z][a-z0-9_-]*(\/[a-z][a-z0-9_-]*)+$/.test(name)) {
throw new Error(`SVG must use a package/name path: ${name}`)
}
return name
}
export function scanIcons(root = iconsRoot) {
const names = []
const walk = (directory) => {
for (const entry of readdirSync(directory, { withFileTypes: true })) {
const path = resolve(directory, entry.name)
if (entry.isDirectory()) walk(path)
else if (entry.name.endsWith('.svg'))
names.push(iconNameFromPath(path, root))
}
}
walk(root)
return names.sort()
}
export async function generateIcons(check = false) {
const names = scanIcons()
const packages = [...new Set(names.map((name) => name.split('/')[0]))]
const list = (values) =>
`[\n${values.map((value) => ` '${value}',`).join('\n')}\n]`
const formatted = `// Generated by scripts/icons.mjs. Do not edit.\nexport const iconNames = ${list(names)} as const\n\nexport type IconName = (typeof iconNames)[number]\n\nexport const iconPackages = ${list(packages)} as const\n\nexport type IconPackage = (typeof iconPackages)[number]\n\nexport const iconSprites = {\n${packages.map((name) => ` ${JSON.stringify(name)}: '/__spritemap-${name}',`).join('\n')}\n} as const\n\nconst names: ReadonlySet<string> = new Set(iconNames)\n\nexport const isIconName = (value: unknown): value is IconName =>\n typeof value === 'string' && names.has(value)\n`
const source = await format(formatted, {
...(await resolveConfig(manifest)),
filepath: manifest,
})
const previous = existsSync(manifest) ? readFileSync(manifest, 'utf8') : ''
if (previous === source) return
if (check) throw new Error('Icon manifest is stale. Run pnpm icons:generate.')
writeFileSync(manifest, source)
}
if (
process.argv[1] &&
existsSync(process.argv[1]) &&
realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))
) {
await generateIcons(process.argv.includes('--check'))
}