Personal Telegram developer console for GitHub

design/cloudflare-ops-read
audit/commit-drilldown audit/finalize-workspace-menu-security audit/ops-actionability audit/pr-menu-consolidation audit/status-menu-consolidation audit/telegram-menu-e2e audit/telegram-menu-e2e-wave2 chore/actions-node24-runtime cleanup/remove-diag design/cloudflare-ops-read docs/control-plane-2-7-design docs/guide-v2-1-sync docs/menu-audit-final-sync docs/phase2-acceptance-closeout docs/phase2-multifile-design feat/bootstrap-worker feat/cloudflare-ops-read feat/cp2-multifile-final feat/cp2-multifile-workspace feat/cp3-github-write-final feat/cp4-cloudflare-ops-final feat/cp5-cicd-control-plane feat/cp6-incident-manager feat/cp7-automation-engine feat/deep-file-browser feat/final-delivery-16-20 feat/github-advanced-read feat/in-app-guide-v2 feat/navigation-recovery-ux-v2 feat/ops-console-v2-1 feat/persistent-menu-code-input feat/phase2-multifile-workspace feat/phase2-multifile-workspace-v2 feat/plugin-foundation-v1 feat/safe-github-ops feat/self-register-webhook feat/studio-g0-foundation feat/telegram-main-inline-menu feat/telegram-pr-merge feat/ux-platform-8-12 feat/v3a-readonly-copilot feat/workspace-file-upload feature/mobile-repo-browser feature/multi-file-change-set fix/approval-expiry-feedback fix/callback-resilience-and-docs fix/ci-actions-pagination fix/cloudflare-fetch-binding fix/editor-request-body-cap fix/editor-safe-file-options fix/issues-permission-release-empty-ux fix/main-menu-callback-fallback fix/phase2-file-editor-selection fix/phase2-final-ux fix/phase2-workspace-ref-persistence fix/production-auto-deploy fix/provider-write-error-feedback fix/repository-id-navigation-fallback fix/repository-pr-navigation fix/telegram-callback-updates fix/telegram-runtime-diagnostics fix/workspace-editor-flow-v2 fix/workspace-recovery-validation hardening/ci-zero-test-telegram-token hardening/pr1-destructive-totp hardening/pr2-kill-switch main multifile-workspace nexa/edit-BwJEIIY3PW nexa/edit-IPHT8irO7b nexa/edit-b4Od3BIMYd p2-multifile phase2-20261005 phase2-20261005-a phase2-20261005-b phase2-20261005-c phase2-20261005-d phase2-20261005-e phase2-20261005-f phase2-20261005-g phase2-20261005-h phase2-20261005-i phase2-20261005-j phase2-20261005-k phase2-20261005-l phase2-20261005-m phase2-20261005-n phase2-20261005-o phase2-20261005-p phase2-20261005-q phase2-20261005-r phase2-20261005-s phase2-20261005-t phase2-20261005-u phase2-20261005-v phase2-20261005-w phase2-20261005-x phase2-20261005-y phase2-20261005-z phase2-acceptance-closeout phase2-add-file-hotfix phase2-change-set phase2-design-20261005 phase2-design-final phase2-implementation phase2-multifile-implementation phase2-multifile-spec phase2-spec-final phase2-workspace phase2/multifile-workspace plan/nexa-studio-v2-reviewed security/remove-telegram-setup spec/repository-workspace-editor v3a/multifile work/multifile
js 463 lines 24.5 KB
Raw
1 import { githubPluginManifest } from './manifest.js';
2 import { createWorkspaceController } from './workspace.js';
3
4 const CALLBACK_ACTIONS = Object.freeze([
5 ['files:', 'github.files.list'],
6 ['tree:', 'github.tree.read'],
7 ['blob:', 'github.blob.read'],
8 ['pr:', 'github.pr.list'],
9 ['commits:', 'github.commits.list'],
10 ['status:', 'github.status.read']
11 ]);
12
13 const escapeHtml = value => String(value ?? '')
14 .replaceAll('&', '&')
15 .replaceAll('<', '&lt;')
16 .replaceAll('>', '&gt;')
17 .replaceAll('"', '&quot;');
18
19 const short = (value, max = 80) => {
20 const text = String(value ?? '');
21 return text.length > max ? `${text.slice(0, max - 1)}…` : text;
22 };
23
24 const numericPair = (value, prefix) => {
25 const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+):(\\d+)$`));
26 if (!match) return null;
27 return { repoId: Number(match[1]), runId: Number(match[2]) };
28 };
29
30 const numericTriple = (value, prefix) => {
31 const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+):(\\d+):(\\d+)$`));
32 if (!match) return null;
33 return {
34 repoId: Number(match[1]),
35 itemId: Number(match[2]),
36 page: Math.max(1, Math.min(100, Number(match[3]) || 1))
37 };
38 };
39
40 const pagedPair = (value, prefix) => {
41 const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+):(\\d+)(?::(\\d+))?$`));
42 if (!match) return null;
43 return {
44 repoId: Number(match[1]),
45 itemId: Number(match[2]),
46 page: Math.max(1, Math.min(100, Number(match[3]) || 1))
47 };
48 };
49
50 const numericSingle = (value, prefix) => {
51 const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+)$`));
52 return match ? Number(match[1]) : null;
53 };
54
55 const pagedSingle = (value, prefix) => {
56 const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+)(?::(\\d+))?$`));
57 if (!match) return null;
58 return {
59 repoId: Number(match[1]),
60 page: Math.max(1, Math.min(100, Number(match[2]) || 1))
61 };
62 };
63
64 const compareRef = value => {
65 const match = String(value || '').match(/^compare:(\d+):([a-f0-9]{40})$/i);
66 if (!match) return null;
67 return { repoId: Number(match[1]), sha: match[2] };
68 };
69
70 const workflowRunsPage = value => pagedSingle(value, 'runs');
71
72 const runIcon = run => {
73 if (run.conclusion === 'success') return '✅';
74 if (run.conclusion === 'failure') return '❌';
75 if (run.conclusion === 'cancelled') return '⏹';
76 return run.status === 'in_progress' ? '🟡' : '⏳';
77 };
78
79 const stateIcon = value => {
80 if (value === 'success' || value === 'completed') return '✅';
81 if (value === 'failure') return '❌';
82 if (value === 'cancelled') return '⏹';
83 if (value === 'open') return '🟢';
84 if (value === 'closed') return '⚫';
85 return '•';
86 };
87
88 const addRepoAdvancedButtons = (view, repoId) => {
89 const rows = [...(view?.reply_markup?.inline_keyboard || [])];
90 const insertAt = Math.max(0, rows.length - 1);
91 rows.splice(insertAt, 0,
92 [{ text: '🧪 CI / Actions', callback_data: `runs:${repoId}` }],
93 [
94 { text: '🌿 Branches', callback_data: `branches:${repoId}` },
95 { text: '🔎 PRها', callback_data: `prs:${repoId}` }
96 ],
97 [
98 { text: '🐛 Issues', callback_data: `issues:${repoId}` },
99 { text: '🏷 Releases', callback_data: `releases:${repoId}` }
100 ]
101 );
102 return {
103 ...view,
104 reply_markup: { ...(view?.reply_markup || {}), inline_keyboard: rows }
105 };
106 };
107
108 function listPagination(prefix, repoId, page, count, pageSize) {
109 const row = [];
110 if (page > 1) row.push({ text: '⬅️ جدیدتر', callback_data: `${prefix}:${repoId}:${page - 1}` });
111 if (count === pageSize && page < 100) row.push({ text: 'قدیمی‌تر ➡️', callback_data: `${prefix}:${repoId}:${page + 1}` });
112 return row.length ? [row] : [];
113 }
114
115 function explicitPagination(prefix, repoId, page, hasMore) {
116 const row = [];
117 if (page > 1) row.push({ text: '⬅️ جدیدتر', callback_data: `${prefix}:${repoId}:${page - 1}` });
118 if (hasMore && page < 100) row.push({ text: 'قدیمی‌تر ➡️', callback_data: `${prefix}:${repoId}:${page + 1}` });
119 return row.length ? [row] : [];
120 }
121
122 function pairPagination(prefix, repoId, itemId, page, count, pageSize) {
123 const row = [];
124 if (page > 1) row.push({ text: '⬅️ جدیدتر', callback_data: `${prefix}:${repoId}:${itemId}:${page - 1}` });
125 if (count === pageSize && page < 100) row.push({ text: 'قدیمی‌تر ➡️', callback_data: `${prefix}:${repoId}:${itemId}:${page + 1}` });
126 return row.length ? [row] : [];
127 }
128
129 async function workflowRunsView(github, repoId, page = 1) {
130 const [repo, runs] = await Promise.all([
131 github.getRepository(repoId),
132 github.listWorkflowRuns(repoId, { perPage: 10, page })
133 ]);
134 const body = runs.length
135 ? runs.slice(0, 10).map(run => `${runIcon(run)} <b>${escapeHtml(run.name)}</b> #${run.runNumber ?? '-'}\n └ ${escapeHtml(run.branch || '-')} · <code>${escapeHtml(run.sha || '-')}</code> · ${escapeHtml(run.conclusion || run.status || 'unknown')}`).join('\n\n')
136 : '<i>Workflow runی یافت نشد.</i>';
137 const refreshCallback = page === 1 ? `runs:${repoId}` : `runs:${repoId}:${page}`;
138 return {
139 text: `🧪 <b>CI / Actions — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
140 reply_markup: {
141 inline_keyboard: [
142 ...runs.slice(0, 10).map(run => [{
143 text: `${runIcon(run)} ${short(run.name, 32)} #${run.runNumber ?? run.id}`,
144 callback_data: `run:${repoId}:${run.id}`
145 }]),
146 ...listPagination('runs', repoId, page, runs.length, 10),
147 [
148 { text: '🔄 بروزرسانی', callback_data: refreshCallback },
149 { text: '🔙 پروژه', callback_data: `repo:${repoId}` }
150 ]
151 ]
152 }
153 };
154 }
155
156 async function workflowRunView(github, repoId, runId) {
157 const [repo, run] = await Promise.all([
158 github.getRepository(repoId),
159 github.getWorkflowRun(repoId, runId)
160 ]);
161 const rows = [
162 [
163 { text: '👷 Jobها', callback_data: `jobs:${repoId}:${runId}` },
164 { text: '📦 Artifacts', callback_data: `artifacts:${repoId}:${runId}` }
165 ]
166 ];
167 if (run.conclusion === 'failure') rows.push([{ text: '🔁 اجرای مجدد jobهای ناموفق', callback_data: `rerun:${repoId}:${runId}` }]);
168 if (run.status === 'in_progress' || run.status === 'queued') rows.push([{ text: '⏹ لغو Workflow', callback_data: `cancelrun:${repoId}:${runId}` }]);
169 rows.push([
170 { text: '🔄 بروزرسانی', callback_data: `run:${repoId}:${runId}` },
171 { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }
172 ]);
173 return {
174 text: `🧪 <b>${escapeHtml(run.name)} — ${escapeHtml(repo.name)}</b>\n➖➖➖➖➖➖➖➖➖➖\nوضعیت: ${runIcon(run)} <b>${escapeHtml(run.conclusion || run.status || 'unknown')}</b>\nRun: <code>#${escapeHtml(run.runNumber ?? run.id)}</code>\nBranch: <code>${escapeHtml(run.branch || '-')}</code>\nSHA: <code>${escapeHtml(run.sha || '-')}</code>\nTrigger: <code>${escapeHtml(run.event || '-')}</code>`,
175 reply_markup: { inline_keyboard: rows }
176 };
177 }
178
179 async function workflowJobsView(github, repoId, runId) {
180 const [repo, run, jobs] = await Promise.all([
181 github.getRepository(repoId),
182 github.getWorkflowRun(repoId, runId),
183 github.listWorkflowJobs(repoId, runId)
184 ]);
185 const body = jobs.length
186 ? jobs.slice(0, 20).map(job => {
187 const jobState = job.conclusion || job.status || 'unknown';
188 const steps = (job.steps || []).slice(0, 30)
189 .map(step => ` ${stateIcon(step.conclusion || step.status)} ${escapeHtml(step.name)} — ${escapeHtml(step.conclusion || step.status || 'unknown')}`)
190 .join('\n');
191 return `<b>${escapeHtml(job.name)}</b> — ${escapeHtml(jobState)}${steps ? `\n${steps}` : ''}`;
192 }).join('\n\n')
193 : '<i>Jobی در این Run یافت نشد.</i>';
194 return {
195 text: `👷 <b>Jobهای ${escapeHtml(run.name)} — ${escapeHtml(repo.name)}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
196 reply_markup: {
197 inline_keyboard: [
198 ...jobs.slice(0, 20).map(job => [{ text: `${stateIcon(job.conclusion || job.status)} ${short(job.name, 40)}`, callback_data: `job:${repoId}:${job.id}` }]),
199 [{ text: '🔄 بروزرسانی', callback_data: `jobs:${repoId}:${runId}` }, { text: '🔙 Run', callback_data: `run:${repoId}:${runId}` }]
200 ]
201 }
202 };
203 }
204
205 async function workflowJobView(github, repoId, jobId) {
206 const [repo, job] = await Promise.all([github.getRepository(repoId), github.getWorkflowJob(repoId, jobId)]);
207 const status = job.conclusion || job.status || 'unknown';
208 const steps = (job.steps || []).slice(0, 30).map(step => `${stateIcon(step.conclusion || step.status)} ${escapeHtml(step.name)} — ${escapeHtml(step.conclusion || step.status || 'unknown')}`).join('\n');
209 const rows = [];
210 if (job.conclusion === 'failure') rows.push([{ text: '📜 مشاهده log ناموفق', callback_data: `joblog:${repoId}:${jobId}` }]);
211 rows.push([{ text: '🔄 بروزرسانی', callback_data: `job:${repoId}:${jobId}` }, { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }]);
212 return {
213 text: `👷 <b>${escapeHtml(job.name)} — ${escapeHtml(repo.name)}</b>\nوضعیت: ${stateIcon(status)} <b>${escapeHtml(status)}</b>\n➖➖➖➖➖➖➖➖➖➖\n${steps || '<i>Stepی ثبت نشده.</i>'}`,
214 reply_markup: { inline_keyboard: rows }
215 };
216 }
217
218 async function workflowJobLogView(github, repoId, jobId) {
219 const [job, log] = await Promise.all([
220 github.getWorkflowJob(repoId, jobId),
221 github.getWorkflowJobLog(repoId, jobId, { maxChars: 1800 })
222 ]);
223 const escaped = escapeHtml(log.text).slice(-3200);
224 const note = log.truncated ? '⚠️ فقط بخش پایانی log نمایش داده شده است.\n\n' : '';
225 return {
226 text: `📜 <b>Log — ${escapeHtml(job.name)}</b>\n${note}<pre>${escaped || '(empty log)'}</pre>`,
227 reply_markup: { inline_keyboard: [[{ text: '🔙 Job', callback_data: `job:${repoId}:${jobId}` }]] }
228 };
229 }
230
231 async function workflowArtifactsView(github, repoId, runId, page = 1) {
232 const [repo, artifacts] = await Promise.all([
233 github.getRepository(repoId),
234 github.listWorkflowArtifacts(repoId, runId, { perPage: 10, page })
235 ]);
236 const body = artifacts.length
237 ? artifacts.slice(0, 10).map(item => `📦 <b>${escapeHtml(item.name)}</b>\n ${item.expired ? 'منقضی شده' : 'فعال'} · ${Number(item.size || 0).toLocaleString()} bytes\n expires: ${escapeHtml(item.expiresAt || '-')}`).join('\n\n')
238 : '<i>Artifactی برای این Run یافت نشد.</i>';
239 const refreshCallback = page === 1 ? `artifacts:${repoId}:${runId}` : `artifacts:${repoId}:${runId}:${page}`;
240 return {
241 text: `📦 <b>Artifacts — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
242 reply_markup: { inline_keyboard: [...pairPagination('artifacts', repoId, runId, page, artifacts.length, 10), [{ text: '🔄 بروزرسانی', callback_data: refreshCallback }, { text: '🔙 Run', callback_data: `run:${repoId}:${runId}` }]] }
243 };
244 }
245
246 async function branchesView(github, repoId, page = 1) {
247 const [repo, branches] = await Promise.all([github.getRepository(repoId), github.listBranches(repoId, { perPage: 20, page })]);
248 const body = branches.length
249 ? branches.slice(0, 20).map(branch => `🌿 <b>${escapeHtml(short(branch.name, 70))}</b>\n <code>${escapeHtml(String(branch.sha).slice(0, 10))}</code>${branch.protected ? ' · 🛡 protected' : ''}`).join('\n\n')
250 : '<i>Branchی یافت نشد.</i>';
251 return {
252 text: `🌿 <b>Branches — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
253 reply_markup: { inline_keyboard: [
254 ...branches.slice(0, 20).filter(branch => /^[a-f0-9]{40}$/i.test(String(branch.sha))).map(branch => [{ text: `↔️ ${short(branch.name, 42)}`, callback_data: `compare:${repoId}:${branch.sha}` }]),
255 ...listPagination('branches', repoId, page, branches.length, 20),
256 [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
257 ] }
258 };
259 }
260
261 async function compareView(github, repoId, sha) {
262 const [repo, compare] = await Promise.all([github.getRepository(repoId), github.compareWithDefault(repoId, sha)]);
263 const files = (compare.files || []).slice(0, 12).map(file => `${stateIcon(file.status)} <code>${escapeHtml(short(file.filename, 90))}</code> · +${file.additions}/-${file.deletions}`).join('\n');
264 return {
265 text: `↔️ <b>Compare — ${escapeHtml(repo.name)}</b>\n<code>${escapeHtml(compare.base)}</code> ← <code>${escapeHtml(String(compare.head).slice(0, 10))}</code>\nوضعیت: <b>${escapeHtml(compare.status || '-')}</b>\nAhead: <b>${compare.aheadBy ?? 0}</b> · Behind: <b>${compare.behindBy ?? 0}</b> · Commits: <b>${compare.totalCommits ?? 0}</b>\n➖➖➖➖➖➖➖➖➖➖\n${files || '<i>فایل تغییریافته‌ای نیست.</i>'}`,
266 reply_markup: { inline_keyboard: [[{ text: '🔙 Branches', callback_data: `branches:${repoId}` }]] }
267 };
268 }
269
270 async function pullRequestsView(github, repoId, page = 1) {
271 const [repo, prs] = await Promise.all([github.getRepository(repoId), github.listPullRequests(repoId, { perPage: 10, page })]);
272 const body = prs.length
273 ? prs.slice(0, 10).map(pr => `${pr.merged ? '🟣' : stateIcon(pr.state)} <b>#${pr.number} ${escapeHtml(short(pr.title, 100))}</b>\n ${escapeHtml(pr.author)} · ${escapeHtml(pr.merged ? 'merged' : pr.state)}`).join('\n\n')
274 : '<i>Pull Requestی یافت نشد.</i>';
275 return {
276 text: `🔎 <b>Pull Requests — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
277 reply_markup: { inline_keyboard: [
278 ...prs.slice(0, 10).map(pr => [{ text: `#${pr.number} ${short(pr.title, 42)}`, callback_data: `prdetail:${repoId}:${pr.number}` }]),
279 ...listPagination('prs', repoId, page, prs.length, 10),
280 [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
281 ] }
282 };
283 }
284
285 async function pullRequestDetailView(github, repoId, prNumber) {
286 const [repo, pr] = await Promise.all([github.getRepository(repoId), github.getPullRequest(repoId, prNumber)]);
287 const body = escapeHtml(short(pr.body || '', 600));
288 return {
289 text: `🔎 <b>PR #${pr.number} — ${escapeHtml(repo.name)}</b>\n<b>${escapeHtml(pr.title)}</b>\n${pr.merged ? '🟣 merged' : `${stateIcon(pr.state)} ${escapeHtml(pr.state)}`} · ${escapeHtml(pr.author)}\n<code>${escapeHtml(pr.head || '-')}</code> → <code>${escapeHtml(pr.base || '-')}</code>\n+${pr.additions}/-${pr.deletions} · ${pr.changedFiles} files\n➖➖➖➖➖➖➖➖➖➖\n${body || '<i>بدون توضیح.</i>'}`,
290 reply_markup: { inline_keyboard: [[{ text: '🧩 فایل‌ها / Diff', callback_data: `prfiles:${repoId}:${prNumber}:1` }, { text: '✅ Checks', callback_data: `prchecks:${repoId}:${prNumber}:1` }], [{ text: '🔙 PRها', callback_data: `prs:${repoId}` }]] }
291 };
292 }
293
294 async function pullRequestFilesView(github, repoId, prNumber, page = 1) {
295 const files = await github.listPullRequestFiles(repoId, prNumber, { perPage: 8, page });
296 const body = files.length ? files.slice(0, 8).map(file => {
297 const patch = escapeHtml(short(file.patch || '', 220));
298 return `🧩 <code>${escapeHtml(short(file.filename, 100))}</code> · ${escapeHtml(file.status)} · +${file.additions}/-${file.deletions}${patch ? `\n<pre>${patch}</pre>` : ''}`;
299 }).join('\n\n') : '<i>فایل تغییریافته‌ای یافت نشد.</i>';
300 return {
301 text: `🧩 <b>PR #${prNumber} Files / Diff</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
302 reply_markup: { inline_keyboard: [...pairPagination('prfiles', repoId, prNumber, page, files.length, 8), [{ text: '🔙 PR', callback_data: `prdetail:${repoId}:${prNumber}` }]] }
303 };
304 }
305
306 async function pullRequestChecksView(github, repoId, prNumber, page = 1) {
307 const pr = await github.getPullRequest(repoId, prNumber);
308 const checks = await github.listCommitChecks(repoId, pr.headSha, { perPage: 20, page });
309 const body = checks.length
310 ? checks.slice(0, 20).map(check => `${stateIcon(check.conclusion || check.status)} <b>${escapeHtml(check.name)}</b> — ${escapeHtml(check.conclusion || check.status || 'unknown')}`).join('\n')
311 : '<i>Checkی یافت نشد.</i>';
312 return {
313 text: `✅ <b>PR #${prNumber} Checks</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
314 reply_markup: { inline_keyboard: [...pairPagination('prchecks', repoId, prNumber, page, checks.length, 20), [{ text: '🔙 PR', callback_data: `prdetail:${repoId}:${prNumber}` }]] }
315 };
316 }
317
318 async function issuesView(github, repoId, page = 1) {
319 const [repo, issuePage] = await Promise.all([github.getRepository(repoId), github.listIssuesPage(repoId, { page })]);
320 const issues = issuePage.items || [];
321 const body = issues.length
322 ? issues.slice(0, 20).map(issue => `${stateIcon(issue.state)} <b>#${issue.number} ${escapeHtml(short(issue.title, 110))}</b>\n ${escapeHtml(issue.author)} · ${issue.comments} comments`).join('\n\n')
323 : '<i>Issueی یافت نشد.</i>';
324 return {
325 text: `🐛 <b>Issues — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
326 reply_markup: { inline_keyboard: [...explicitPagination('issues', repoId, page, !!issuePage.hasMore), [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]] }
327 };
328 }
329
330 async function releasesView(github, repoId, page = 1) {
331 const [repo, releases] = await Promise.all([github.getRepository(repoId), github.listReleases(repoId, { perPage: 10, page })]);
332 const body = releases.length
333 ? releases.slice(0, 10).map(release => `🏷 <b>${escapeHtml(release.tag || release.name)}</b>${release.prerelease ? ' · pre-release' : ''}${release.draft ? ' · draft' : ''}\n ${escapeHtml(short(release.name, 110))}\n ${escapeHtml(release.publishedAt || '-')}`).join('\n\n')
334 : '<i>هیچ Release منتشرشده‌ای برای این مخزن در GitHub وجود ندارد.</i>';
335 return {
336 text: `🏷 <b>Releases — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
337 reply_markup: { inline_keyboard: [...listPagination('releases', repoId, page, releases.length, 10), [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]] }
338 };
339 }
340
341 function workflowActionResultView(repoId, runId, action) {
342 const rerun = action === 'rerun_failed';
343 return {
344 text: rerun ? '✅ درخواست اجرای مجدد jobهای ناموفق برای GitHub ارسال شد.' : '✅ درخواست لغو Workflow برای GitHub ارسال شد.',
345 reply_markup: { inline_keyboard: [[{ text: '🧪 مشاهده Run', callback_data: `run:${repoId}:${runId}` }, { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }]] }
346 };
347 }
348
349 function resolveReadCallback(data) {
350 const value = String(data || '');
351 if (value === 'menu:repos') return { actionId: 'github.repos.list', kind: 'legacy' };
352 const repoId = numericSingle(value, 'repo');
353 if (repoId !== null) return { actionId: 'github.repo.detail', kind: 'repo', repoId };
354 const runs = workflowRunsPage(value);
355 if (runs) return { actionId: 'github.workflow.runs.list', kind: 'runs', ...runs };
356 const run = numericPair(value, 'run');
357 if (run) return { actionId: 'github.workflow.run.detail', kind: 'run', ...run };
358 const jobs = numericPair(value, 'jobs');
359 if (jobs) return { actionId: 'github.workflow.jobs.list', kind: 'jobs', ...jobs };
360 const job = numericPair(value, 'job');
361 if (job) return { actionId: 'github.workflow.job.detail', kind: 'job', repoId: job.repoId, jobId: job.runId };
362 const joblog = numericPair(value, 'joblog');
363 if (joblog) return { actionId: 'github.workflow.job.log', kind: 'joblog', repoId: joblog.repoId, jobId: joblog.runId };
364 const artifacts = pagedPair(value, 'artifacts');
365 if (artifacts) return { actionId: 'github.workflow.artifacts.list', kind: 'artifacts', repoId: artifacts.repoId, runId: artifacts.itemId, page: artifacts.page };
366 const branches = pagedSingle(value, 'branches');
367 if (branches) return { actionId: 'github.branches.list', kind: 'branches', ...branches };
368 const compare = compareRef(value);
369 if (compare) return { actionId: 'github.compare.read', kind: 'compare', ...compare };
370 const prs = pagedSingle(value, 'prs');
371 if (prs) return { actionId: 'github.pr.advanced.list', kind: 'prs', ...prs };
372 const prdetail = numericPair(value, 'prdetail');
373 if (prdetail) return { actionId: 'github.pr.detail', kind: 'prdetail', repoId: prdetail.repoId, prNumber: prdetail.runId };
374 const prfiles = numericTriple(value, 'prfiles');
375 if (prfiles) return { actionId: 'github.pr.files.list', kind: 'prfiles', repoId: prfiles.repoId, prNumber: prfiles.itemId, page: prfiles.page };
376 const prchecks = numericTriple(value, 'prchecks');
377 if (prchecks) return { actionId: 'github.pr.checks.list', kind: 'prchecks', repoId: prchecks.repoId, prNumber: prchecks.itemId, page: prchecks.page };
378 const issues = pagedSingle(value, 'issues');
379 if (issues) return { actionId: 'github.issues.list', kind: 'issues', ...issues };
380 const releases = pagedSingle(value, 'releases');
381 if (releases) return { actionId: 'github.releases.list', kind: 'releases', ...releases };
382 for (const [prefix, actionId] of CALLBACK_ACTIONS) {
383 if (value.startsWith(prefix)) return { actionId, kind: 'legacy' };
384 }
385 return null;
386 }
387
388 function resolveWriteCallback(data) {
389 const rerun = numericPair(data, 'rerun');
390 if (rerun) {
391 return {
392 actionId: 'github.workflow.run.rerun_failed',
393 approval: { input: rerun, label: 'اجرای مجدد jobهای ناموفق' },
394 execute: async github => {
395 await github.rerunFailedWorkflowRun(rerun.repoId, rerun.runId);
396 return workflowActionResultView(rerun.repoId, rerun.runId, 'rerun_failed');
397 }
398 };
399 }
400 const cancel = numericPair(data, 'cancelrun');
401 if (cancel) {
402 return {
403 actionId: 'github.workflow.run.cancel',
404 approval: { input: cancel, label: 'لغو Workflow در حال اجرا' },
405 execute: async github => {
406 await github.cancelWorkflowRun(cancel.repoId, cancel.runId);
407 return workflowActionResultView(cancel.repoId, cancel.runId, 'cancel');
408 }
409 };
410 }
411 return null;
412 }
413
414 export function createGitHubPlugin({ github, menu, workspaces } = {}) {
415 if (!github) throw new Error('GitHub plugin requires github service');
416 if (!menu) throw new Error('GitHub plugin requires menu manager');
417 const workspaceController = workspaces ? createWorkspaceController({ github, workspaces }) : null;
418
419 return {
420 manifest: githubPluginManifest,
421
422 resolveCommand(command) {
423 if (command !== '/repos') return null;
424 return { actionId: 'github.repos.list', execute: () => menu.getReposListView() };
425 },
426
427 resolveMessage(payload, context = {}) {
428 return workspaceController?.resolveMessage(payload, context) || null;
429 },
430
431 resolveCallback(data, context = {}) {
432 const write = resolveWriteCallback(data);
433 if (write) return { actionId: write.actionId, approval: write.approval, execute: () => write.execute(github) };
434
435 const workspaceRoute = workspaceController?.resolveCallback(data, context);
436 if (workspaceRoute) return workspaceRoute;
437
438 const read = resolveReadCallback(data);
439 if (!read) return null;
440 return {
441 actionId: read.actionId,
442 execute: async () => {
443 if (read.kind === 'repo') return addRepoAdvancedButtons(await menu.renderByCallback(data), read.repoId);
444 if (read.kind === 'runs') return workflowRunsView(github, read.repoId, read.page);
445 if (read.kind === 'run') return workflowRunView(github, read.repoId, read.runId);
446 if (read.kind === 'jobs') return workflowJobsView(github, read.repoId, read.runId);
447 if (read.kind === 'job') return workflowJobView(github, read.repoId, read.jobId);
448 if (read.kind === 'joblog') return workflowJobLogView(github, read.repoId, read.jobId);
449 if (read.kind === 'artifacts') return workflowArtifactsView(github, read.repoId, read.runId, read.page);
450 if (read.kind === 'branches') return branchesView(github, read.repoId, read.page);
451 if (read.kind === 'compare') return compareView(github, read.repoId, read.sha);
452 if (read.kind === 'prs') return pullRequestsView(github, read.repoId, read.page);
453 if (read.kind === 'prdetail') return pullRequestDetailView(github, read.repoId, read.prNumber);
454 if (read.kind === 'prfiles') return pullRequestFilesView(github, read.repoId, read.prNumber, read.page);
455 if (read.kind === 'prchecks') return pullRequestChecksView(github, read.repoId, read.prNumber, read.page);
456 if (read.kind === 'issues') return issuesView(github, read.repoId, read.page);
457 if (read.kind === 'releases') return releasesView(github, read.repoId, read.page);
458 return menu.renderByCallback(data);
459 }
460 };
461 }
462 };
463 }