@apexhub/apex-ui-skill 0.0.0-stage → 1.2.0

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.
@@ -0,0 +1,159 @@
1
+ import { cpSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import { dirname, join } from 'node:path'
3
+ import { getSkillDestPath } from './targets.mjs'
4
+
5
+ const PAYLOAD_ENTRIES = ['SKILL.md', 'references', 'scripts']
6
+
7
+ /** Heading every apex-ui rule block starts with; used to recognise blocks written by older versions. */
8
+ const RULE_HEADING = '## UI 组件规范(Apex UI)'
9
+
10
+ /**
11
+ * @typedef {object} RuleConfig
12
+ * @property {string} file rule text inside the skill, e.g. `rules/agents.md`
13
+ * @property {string} marker start marker
14
+ * @property {string} [endMarker] end marker; when set, re-installing replaces the block
15
+ * @property {string} [legacyMarker] marker written by older installers (no end marker)
16
+ * @property {string[]} [legacyFiles] files older installers appended to; their old block is removed
17
+ * @property {string} appendTo project-relative target file, e.g. `AGENTS.md`
18
+ * @property {string} [header] written above the block only when the file is new or empty, e.g. the
19
+ * front matter a tool needs to load a rule file on every request
20
+ */
21
+
22
+ /**
23
+ * @param {string} cwd
24
+ * @param {string} appendTo relative path, e.g. `AGENTS.md`
25
+ */
26
+ export function resolveRuleTargetPath(cwd, appendTo) {
27
+ return join(cwd, appendTo)
28
+ }
29
+
30
+ /**
31
+ * @param {string} skillDir
32
+ * @param {string} destDir
33
+ */
34
+ export function copySkillPayload(skillDir, destDir) {
35
+ mkdirSync(destDir, { recursive: true })
36
+
37
+ for (const entry of PAYLOAD_ENTRIES) {
38
+ const src = join(skillDir, entry)
39
+ if (!existsSync(src)) continue
40
+ cpSync(src, join(destDir, entry), { recursive: true })
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Removes a block written by an older installer: the legacy marker line, then the rule up to the
46
+ * next top-level heading, HTML comment or end of file. Only touches blocks that start with the
47
+ * apex-ui rule heading, so user text is never removed.
48
+ * @param {string} text
49
+ * @param {string} legacyMarker
50
+ * @returns {string | null} the text without the block, or null when there is no such block
51
+ */
52
+ export function removeLegacyBlock(text, legacyMarker) {
53
+ const lines = text.split('\n')
54
+ const start = lines.findIndex((line) => line.trim() === legacyMarker)
55
+ if (start === -1 || lines[start + 1]?.trim() !== RULE_HEADING) return null
56
+ let end = start + 2
57
+ while (end < lines.length && !/^(#{1,2} |<!--)/.test(lines[end])) end++
58
+ const before = lines.slice(0, start)
59
+ while (before.length && before[before.length - 1].trim() === '') before.pop()
60
+ const after = lines.slice(end)
61
+ const joined = [...before, ...(before.length && after.length ? [''] : []), ...after].join('\n')
62
+ return joined.trim() ? `${joined.replace(/\n*$/, '')}\n` : ''
63
+ }
64
+
65
+ /**
66
+ * Writes the rule block into the target file. Returns what happened:
67
+ * `created` | `appended` | `updated` | `unchanged` | `skipped` (legacy block kept, see `note`).
68
+ * @param {string} cwd
69
+ * @param {string} skillDir
70
+ * @param {RuleConfig} ruleConfig
71
+ */
72
+ export function applyRule(cwd, skillDir, ruleConfig) {
73
+ const rulePath = join(skillDir, ruleConfig.file)
74
+ if (!existsSync(rulePath)) return { applied: false, skipped: true, action: 'skipped' }
75
+
76
+ const targetFile = resolveRuleTargetPath(cwd, ruleConfig.appendTo)
77
+ const rule = readFileSync(rulePath, 'utf8').trimEnd()
78
+ const { marker, endMarker, legacyMarker } = ruleConfig
79
+ const block = endMarker ? `${marker}\n${rule}\n${endMarker}\n` : `${marker}\n${rule}\n`
80
+
81
+ const removedLegacy = []
82
+ if (legacyMarker) {
83
+ for (const rel of ruleConfig.legacyFiles ?? []) {
84
+ const legacyPath = resolveRuleTargetPath(cwd, rel)
85
+ if (!existsSync(legacyPath)) continue
86
+ const cleaned = removeLegacyBlock(readFileSync(legacyPath, 'utf8'), legacyMarker)
87
+ if (cleaned === null) continue
88
+ writeFileSync(legacyPath, cleaned)
89
+ removedLegacy.push(legacyPath)
90
+ }
91
+ }
92
+
93
+ let existing = existsSync(targetFile) ? readFileSync(targetFile, 'utf8') : ''
94
+ const start = existing.indexOf(marker)
95
+ const end = endMarker && start !== -1 ? existing.indexOf(endMarker, start) : -1
96
+
97
+ if (start !== -1 && end !== -1) {
98
+ const current = existing.slice(start, end + endMarker.length)
99
+ if (`${current}\n` === block) {
100
+ return { applied: false, action: 'unchanged', file: targetFile, removedLegacy }
101
+ }
102
+ writeFileSync(
103
+ targetFile,
104
+ existing.slice(0, start) + block.trimEnd() + existing.slice(end + endMarker.length),
105
+ )
106
+ return { applied: true, action: 'updated', file: targetFile, removedLegacy }
107
+ }
108
+
109
+ if (start !== -1) {
110
+ // Marker without an end marker: a block we cannot delimit safely. Keep it untouched.
111
+ return { applied: false, skipped: true, action: 'skipped', file: targetFile, removedLegacy }
112
+ }
113
+
114
+ if (legacyMarker && existing.includes(legacyMarker)) {
115
+ const cleaned = removeLegacyBlock(existing, legacyMarker)
116
+ if (cleaned !== null) {
117
+ existing = cleaned
118
+ removedLegacy.push(targetFile)
119
+ }
120
+ }
121
+
122
+ mkdirSync(dirname(targetFile), { recursive: true })
123
+ if (existing.trim()) {
124
+ writeFileSync(targetFile, `${existing.replace(/\n*$/, '')}\n\n${block}`)
125
+ return {
126
+ applied: true,
127
+ action: removedLegacy.includes(targetFile) ? 'updated' : 'appended',
128
+ file: targetFile,
129
+ removedLegacy,
130
+ }
131
+ }
132
+ const header = ruleConfig.header ? `${ruleConfig.header.replace(/\n*$/, '')}\n\n` : ''
133
+ writeFileSync(targetFile, header + block)
134
+ return { applied: true, action: 'created', file: targetFile, removedLegacy }
135
+ }
136
+
137
+ /**
138
+ * Applies the target-specific rule (if any) and the `*` rule that every target gets.
139
+ * @param {object} options
140
+ * @param {string} options.cwd
141
+ * @param {string} options.skillDir
142
+ * @param {string} options.skillName
143
+ * @param {string} options.targetId
144
+ * @param {Record<string, RuleConfig>} [options.rules]
145
+ */
146
+ export function installSkillToTarget({ cwd, skillDir, skillName, targetId, rules }) {
147
+ const relDest = getSkillDestPath(targetId, skillName)
148
+ const destDir = join(cwd, relDest)
149
+
150
+ copySkillPayload(skillDir, destDir)
151
+
152
+ const ruleResults = []
153
+ for (const key of [targetId, '*']) {
154
+ const ruleConfig = rules?.[key]
155
+ if (ruleConfig) ruleResults.push(applyRule(cwd, skillDir, ruleConfig))
156
+ }
157
+
158
+ return { targetId, destDir, relDest, ruleResult: ruleResults[0] ?? null, ruleResults }
159
+ }
@@ -0,0 +1,33 @@
1
+ // 自动生成:块字 logo「APEX UI」(cfonts "block")。█=亮面,描边=暗灰(3D)。
2
+ // 三档按终端宽度自适应:HUGE(2x) / BLOCK(1x) / COMPACT。
3
+ export const LOGO_HUGE = [
4
+ ' ██████████╗╗ ████████████╗╗ ██████████████╗╗ ████╗╗ ████╗╗ ████╗╗ ████╗╗ ████╗╗',
5
+ ' ██████████╗╗ ████████████╗╗ ██████████████╗╗ ████╗╗ ████╗╗ ████╗╗ ████╗╗ ████╗╗',
6
+ ' ████╔╔════████╗╗ ████╔╔════████╗╗ ████╔╔════════╝╝ ╚╚████╗╗████╔╔╝╝ ████║║ ████║║ ████║║',
7
+ ' ████╔╔════████╗╗ ████╔╔════████╗╗ ████╔╔════════╝╝ ╚╚████╗╗████╔╔╝╝ ████║║ ████║║ ████║║',
8
+ ' ██████████████║║ ████████████╔╔╝╝ ██████████╗╗ ╚╚██████╔╔╝╝ ████║║ ████║║ ████║║',
9
+ ' ██████████████║║ ████████████╔╔╝╝ ██████████╗╗ ╚╚██████╔╔╝╝ ████║║ ████║║ ████║║',
10
+ ' ████╔╔════████║║ ████╔╔══════╝╝ ████╔╔════╝╝ ████╔╔████╗╗ ████║║ ████║║ ████║║',
11
+ ' ████╔╔════████║║ ████╔╔══════╝╝ ████╔╔════╝╝ ████╔╔████╗╗ ████║║ ████║║ ████║║',
12
+ ' ████║║ ████║║ ████║║ ██████████████╗╗ ████╔╔╝╝ ████╗╗ ╚╚████████████╔╔╝╝ ████║║',
13
+ ' ████║║ ████║║ ████║║ ██████████████╗╗ ████╔╔╝╝ ████╗╗ ╚╚████████████╔╔╝╝ ████║║',
14
+ ' ╚╚══╝╝ ╚╚══╝╝ ╚╚══╝╝ ╚╚════════════╝╝ ╚╚══╝╝ ╚╚══╝╝ ╚╚══════════╝╝ ╚╚══╝╝',
15
+ ' ╚╚══╝╝ ╚╚══╝╝ ╚╚══╝╝ ╚╚════════════╝╝ ╚╚══╝╝ ╚╚══╝╝ ╚╚══════════╝╝ ╚╚══╝╝',
16
+ ]
17
+
18
+ export const LOGO_BLOCK = [
19
+ ' █████╗ ██████╗ ███████╗ ██╗ ██╗ ██╗ ██╗ ██╗',
20
+ ' ██╔══██╗ ██╔══██╗ ██╔════╝ ╚██╗██╔╝ ██║ ██║ ██║',
21
+ ' ███████║ ██████╔╝ █████╗ ╚███╔╝ ██║ ██║ ██║',
22
+ ' ██╔══██║ ██╔═══╝ ██╔══╝ ██╔██╗ ██║ ██║ ██║',
23
+ ' ██║ ██║ ██║ ███████╗ ██╔╝ ██╗ ╚██████╔╝ ██║',
24
+ ' ╚═╝ ╚═╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝',
25
+ ]
26
+
27
+ export const LOGO_COMPACT = [
28
+ '█████ █████ █████ █ █ █ █ █████',
29
+ '█ █ █ █ █ █ █ █ █ █ ',
30
+ '█████ █████ ████ █ █ █ █ ',
31
+ '█ █ █ █ █ █ █ █ █ ',
32
+ '█ █ █ █████ █ █ █████ █████',
33
+ ]
@@ -0,0 +1,56 @@
1
+ import { TARGETS } from './targets.mjs'
2
+
3
+ /**
4
+ * @param {string[]} argv
5
+ */
6
+ export function parseArgs(argv) {
7
+ const args = {
8
+ help: false,
9
+ list: false,
10
+ listTargets: false,
11
+ plain: false,
12
+ all: false,
13
+ defaultOnly: false,
14
+ skills: /** @type {string[] | null} */ (null),
15
+ targets: /** @type {string[] | null} */ (null),
16
+ }
17
+
18
+ for (let i = 0; i < argv.length; i += 1) {
19
+ const arg = argv[i]
20
+ if (arg === '-h' || arg === '--help') args.help = true
21
+ else if (arg === '--list') args.list = true
22
+ else if (arg === '--list-targets') args.listTargets = true
23
+ else if (arg === '--plain') args.plain = true
24
+ else if (arg === '--all') args.all = true
25
+ else if (arg === '--default') args.defaultOnly = true
26
+ else if (arg === '--skills') {
27
+ const value = argv[i + 1]
28
+ if (!value) throw new Error('--skills 需要参数,例如 apex-ui')
29
+ args.skills = value
30
+ .split(',')
31
+ .map((s) => s.trim())
32
+ .filter(Boolean)
33
+ i += 1
34
+ } else if (arg === '--target') {
35
+ const value = argv[i + 1]
36
+ if (!value) throw new Error('--target 需要参数,例如 claude,cursor')
37
+ args.targets = value
38
+ .split(',')
39
+ .map((s) => s.trim())
40
+ .filter(Boolean)
41
+ i += 1
42
+ } else if (arg.startsWith('-')) {
43
+ throw new Error(`未知参数:${arg}`)
44
+ }
45
+ }
46
+
47
+ return args
48
+ }
49
+
50
+ /** @param {string[]} ids */
51
+ export function validateTargetIds(ids) {
52
+ const valid = new Set([...TARGETS.map((t) => t.id), 'auto'])
53
+ for (const id of ids) {
54
+ if (!valid.has(id)) throw new Error(`未知 target:${id}(可用 --list-targets 查看)`)
55
+ }
56
+ }
@@ -0,0 +1,158 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { dirname, join } from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
4
+ import { DEFAULT_TARGET_IDS, TARGETS } from './targets.mjs'
5
+ import { paint, renderHeader } from './ui.mjs'
6
+
7
+ /**
8
+ * @typedef {{ id: string, label: string, pathTemplate: string, group: string, hint?: string }} TargetItem
9
+ */
10
+
11
+ /**
12
+ * @param {{ color: boolean, width: number, title: string, subtitle: string, groups: { title: string, items: TargetItem[] }[], initialChecked: boolean[] }} options
13
+ * @returns {Promise<boolean[]>}
14
+ */
15
+ export function promptCheckboxList(options) {
16
+ const { color, title, subtitle, groups } = options
17
+ const flatItems = groups.flatMap((g) => g.items)
18
+ let checked = [...options.initialChecked]
19
+ let index = 0
20
+
21
+ const render = () => {
22
+ const lines = []
23
+ lines.push('')
24
+ lines.push(paint(color, title, 'bold'))
25
+ lines.push(paint(color, subtitle, 'dim'))
26
+ lines.push('')
27
+
28
+ let offset = 0
29
+ for (const group of groups) {
30
+ lines.push(paint(color, ` ${group.title}`, 'dim'))
31
+ for (const item of group.items) {
32
+ const i = offset
33
+ offset += 1
34
+ const box = checked[i] ? '[✓]' : '[ ]'
35
+ const pointer = i === index ? paint(color, '› ', 'brand') : ' '
36
+ const label = i === index ? paint(color, item.label, 'bold') : item.label
37
+ const path = item.pathTemplate.replace('{name}', 'apex-ui')
38
+ lines.push(`${pointer}${box} ${label.padEnd(18)} → ${path}`)
39
+ if (item.hint) lines.push(` ${paint(color, item.hint, 'dim')}`)
40
+ }
41
+ lines.push('')
42
+ }
43
+
44
+ lines.push(paint(color, ' Space 勾选 · ↑↓ 移动 · Enter 安装 · Ctrl+C 退出', 'dim'))
45
+ if (!groups.some((g) => g.title === '提示')) {
46
+ lines.push(paint(color, ' 提示:Gemini 与 Agents 目录一般二选一即可', 'dim'))
47
+ }
48
+ return lines.join('\n')
49
+ }
50
+
51
+ return new Promise((resolve, reject) => {
52
+ const stdin = process.stdin
53
+ const stdout = process.stdout
54
+
55
+ stdin.setRawMode(true)
56
+ stdin.resume()
57
+ stdin.setEncoding('utf8')
58
+
59
+ const refresh = () => {
60
+ stdout.write('\x1b[?25l')
61
+ stdout.write('\x1b[H\x1b[J')
62
+ // 每帧先重绘大 logo 头部,保证向导过程中 logo 不消失
63
+ stdout.write(renderHeader(color, { subtitle: false }))
64
+ stdout.write(render())
65
+ }
66
+
67
+ refresh()
68
+
69
+ const cleanup = () => {
70
+ stdin.setRawMode(false)
71
+ stdin.pause()
72
+ stdin.removeListener('data', onData)
73
+ stdout.write('\x1b[?25h')
74
+ }
75
+
76
+ /** @param {string} data */
77
+ const onData = (data) => {
78
+ if (data === '\u0003') {
79
+ cleanup()
80
+ stdout.write('\n')
81
+ reject(new Error('已取消'))
82
+ return
83
+ }
84
+
85
+ if (data === '\r' || data === '\n') {
86
+ if (!checked.some(Boolean)) {
87
+ stdout.write('\n')
88
+ stdout.write(paint(color, ' 请至少选择一个 AI 工具\n', 'brand'))
89
+ refresh()
90
+ return
91
+ }
92
+ cleanup()
93
+ stdout.write('\n')
94
+ resolve(checked)
95
+ return
96
+ }
97
+
98
+ if (data === ' ') {
99
+ checked = checked.map((v, i) => (i === index ? !v : v))
100
+ refresh()
101
+ return
102
+ }
103
+
104
+ if (data === '\u001b[A') {
105
+ index = (index - 1 + flatItems.length) % flatItems.length
106
+ refresh()
107
+ return
108
+ }
109
+
110
+ if (data === '\u001b[B') {
111
+ index = (index + 1) % flatItems.length
112
+ refresh()
113
+ return
114
+ }
115
+ }
116
+
117
+ stdin.on('data', onData)
118
+ })
119
+ }
120
+
121
+ /**
122
+ * @param {{ color: boolean, width: number, skills: Array<{ name: string, description?: string, default?: boolean }>, preselect?: string[] }} ctx
123
+ * `preselect`: target ids ticked at start (defaults plus the AI tools detected in this project)
124
+ */
125
+ export async function runWizard(ctx) {
126
+ const { color, skills } = ctx
127
+
128
+ let selectedSkills = skills.filter((s) => s.default !== false)
129
+ if (selectedSkills.length === 0) selectedSkills = skills
130
+
131
+ if (skills.length === 1) {
132
+ const skill = skills[0]
133
+ console.log(paint(color, '将安装 skill:', 'dim'))
134
+ console.log(paint(color, ` [✓] ${skill.name} — ${skill.description || ''}`.trim(), 'brand'))
135
+ console.log('')
136
+ }
137
+
138
+ const common = TARGETS.filter((t) => t.group === 'common')
139
+ const other = TARGETS.filter((t) => t.group === 'other')
140
+ const allItems = [...common, ...other]
141
+ const preselect = ctx.preselect ?? DEFAULT_TARGET_IDS
142
+ const initialChecked = allItems.map((t) => preselect.includes(t.id))
143
+
144
+ const checked = await promptCheckboxList({
145
+ color: ctx.color,
146
+ width: ctx.width,
147
+ title: 'Apex UI Skills 安装向导',
148
+ subtitle: '安装到哪些 AI 工具?(Space 勾选/取消,Enter 开始安装)',
149
+ groups: [
150
+ { title: '常用', items: common },
151
+ { title: '其他主流', items: other },
152
+ ],
153
+ initialChecked,
154
+ })
155
+
156
+ const targetIds = allItems.filter((_, i) => checked[i]).map((t) => t.id)
157
+ return { skillNames: selectedSkills.map((s) => s.name), targetIds }
158
+ }
@@ -0,0 +1,78 @@
1
+ /** @typedef {{ id: string, label: string, pathTemplate: string, group: 'common' | 'other', default?: boolean, hint?: string }} Target */
2
+
3
+ /** @type {Target[]} */
4
+ export const TARGETS = [
5
+ {
6
+ id: 'agents',
7
+ label: 'Agents 通用',
8
+ pathTemplate: '.agents/skills/{name}/',
9
+ group: 'common',
10
+ default: true,
11
+ hint: 'Gemini CLI 互操作别名',
12
+ },
13
+ {
14
+ id: 'claude',
15
+ label: 'Claude Code',
16
+ pathTemplate: '.claude/skills/{name}/',
17
+ group: 'common',
18
+ default: true,
19
+ },
20
+ {
21
+ id: 'cursor',
22
+ label: 'Cursor',
23
+ pathTemplate: '.cursor/skills/{name}/',
24
+ group: 'common',
25
+ default: true,
26
+ },
27
+ {
28
+ id: 'codex',
29
+ label: 'OpenAI Codex',
30
+ pathTemplate: '.codex/skills/{name}/',
31
+ group: 'common',
32
+ },
33
+ {
34
+ id: 'opencode',
35
+ label: 'OpenCode',
36
+ pathTemplate: '.opencode/skills/{name}/',
37
+ group: 'common',
38
+ },
39
+ {
40
+ id: 'copilot',
41
+ label: 'GitHub Copilot',
42
+ pathTemplate: '.github/skills/{name}/',
43
+ group: 'other',
44
+ },
45
+ {
46
+ id: 'windsurf',
47
+ label: 'Windsurf',
48
+ pathTemplate: '.windsurf/skills/{name}/',
49
+ group: 'other',
50
+ },
51
+ {
52
+ id: 'gemini',
53
+ label: 'Gemini CLI',
54
+ pathTemplate: '.gemini/skills/{name}/',
55
+ group: 'other',
56
+ hint: '工作区 skill 需在 Gemini 内执行 /trust',
57
+ },
58
+ {
59
+ id: 'antigravity',
60
+ label: 'Google Antigravity',
61
+ pathTemplate: '.agent/skills/{name}/',
62
+ group: 'other',
63
+ },
64
+ ]
65
+
66
+ export const DEFAULT_TARGET_IDS = TARGETS.filter((t) => t.default).map((t) => t.id)
67
+
68
+ /** @param {string} id */
69
+ export function getTarget(id) {
70
+ const target = TARGETS.find((t) => t.id === id)
71
+ if (!target) throw new Error(`未知 target:${id}`)
72
+ return target
73
+ }
74
+
75
+ /** @param {string} id @param {string} skillName */
76
+ export function getSkillDestPath(id, skillName) {
77
+ return getTarget(id).pathTemplate.replace('{name}', skillName)
78
+ }