Personal Telegram developer console for GitHub
feat: add path-safe workspace controller
davoodmehraban89 committed
Oct 3, 2026 at 12:43 UTC
ae9a7477dcf33fa99fed88746e1ffa5ed4be7a0f
1 file changed
+144
src/plugins/github/workspace.js
new
+144
@@ -0,0 +1,144 @@
1
+import { digestText, validateEditableFile } from '../../core/workspace-policy.js';
2
+
3
+const HANDLE_10 = '[A-Za-z0-9_-]{10}';
4
+const escapeHtml = value => String(value ?? '')
5
+ .replaceAll('&', '&')
6
+ .replaceAll('<', '<')
7
+ .replaceAll('>', '>')
8
+ .replaceAll('"', '"');
9
+const short = (value, max = 70) => {
10
+ const text = String(value ?? '');
11
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
12
+};
13
+
14
+const ownerFrom = context => {
15
+ const ownerId = String(context?.ownerId ?? '');
16
+ if (!ownerId) throw new Error('Workspace owner is required');
17
+ return ownerId;
18
+};
19
+
20
+function parseCallback(data) {
21
+ const value = String(data || '');
22
+ let match = value.match(/^(?:files):(\d+)$/);
23
+ if (match) return { actionId: 'github.files.list', kind: 'root', repoId: Number(match[1]) };
24
+ match = value.match(new RegExp(`^wnav:(${HANDLE_10})$`));
25
+ if (match) return { actionId: 'github.workspace.navigate', kind: 'navigate', refId: match[1] };
26
+ match = value.match(new RegExp(`^wedit:(${HANDLE_10})$`));
27
+ if (match) return { actionId: 'github.workspace.create', kind: 'edit', refId: match[1] };
28
+ match = value.match(new RegExp(`^ws:(${HANDLE_10})$`));
29
+ if (match) return { actionId: 'github.workspace.view', kind: 'workspace', workspaceId: match[1] };
30
+ return null;
31
+}
32
+
33
+export function createWorkspaceController({ github, workspaces } = {}) {
34
+ if (!github) throw new Error('Workspace controller requires GitHub service');
35
+ if (!workspaces) throw new Error('Workspace controller requires durable workspace store');
36
+
37
+ const renderDirectory = async (repoId, path, ownerId) => {
38
+ const [repo, items] = await Promise.all([
39
+ github.getRepository(repoId),
40
+ github.listFiles(repoId, path)
41
+ ]);
42
+ const visible = items.slice(0, 30);
43
+ const handles = await workspaces.createNavigationRefs({
44
+ ownerId,
45
+ refs: visible.map(item => ({ repoId, path: item.path, type: item.type, sha: item.sha }))
46
+ });
47
+ const body = visible.length
48
+ ? visible.map(item => `${item.type === 'dir' ? '📁' : '📄'} <code>${escapeHtml(short(item.name, 100))}</code>${item.type === 'file' && item.size ? ` (${Number(item.size).toLocaleString()} B)` : ''}`).join('\n')
49
+ : '<i>این پوشه خالی است.</i>';
50
+ const rows = visible.map((item, index) => [{
51
+ text: `${item.type === 'dir' ? '📁' : '📄'} ${short(item.name, 46)}`,
52
+ callback_data: `wnav:${handles[index].refId}`
53
+ }]);
54
+ rows.push([
55
+ { text: '🔄 بروزرسانی', callback_data: path ? `files:${repoId}` : `files:${repoId}` },
56
+ { text: '📦 پروژه', callback_data: `repo:${repoId}` }
57
+ ]);
58
+ return {
59
+ text: `📂 <b>فایلهای ${escapeHtml(repo.name)}</b>\n${path ? `مسیر: <code>${escapeHtml(path)}</code>\n` : ''}➖➖➖➖➖➖➖➖➖➖\n${body}`,
60
+ reply_markup: { inline_keyboard: rows }
61
+ };
62
+ };
63
+
64
+ const getPinnedFile = async ref => {
65
+ const repo = await github.getRepository(ref.repoId);
66
+ const snapshot = await github.getBranchSnapshot(ref.repoId, repo.defaultBranch);
67
+ const file = await github.getFileAtRef(ref.repoId, ref.path, snapshot.headSha);
68
+ return { repo, snapshot, file };
69
+ };
70
+
71
+ const renderFile = async (refId, ownerId) => {
72
+ const ref = await workspaces.resolveNavigationRef({ ownerId, refId });
73
+ if (!ref || ref.type !== 'file') throw new Error('Workspace file reference is missing or expired');
74
+ const { repo, snapshot, file } = await getPinnedFile(ref);
75
+ const policy = validateEditableFile({ path: file.path, text: file.content, byteLength: file.size });
76
+ const preview = file.content.length > 2600 ? `${file.content.slice(0, 2600)}\n…` : file.content;
77
+ const reason = repo.archived
78
+ ? 'این مخزن آرشیوشده است و ویرایش فایل در آن غیرفعال است.'
79
+ : policy.reason;
80
+ const rows = [];
81
+ if (!repo.archived && policy.editable) rows.push([{ text: '✏️ Edit', callback_data: `wedit:${refId}` }]);
82
+ rows.push([{ text: '🔙 فایلها', callback_data: `files:${ref.repoId}` }, { text: '📦 پروژه', callback_data: `repo:${ref.repoId}` }]);
83
+ return {
84
+ text: `📄 <b>پیشنمایش فایل — ${escapeHtml(repo.name)}</b>\nمسیر: <code>${escapeHtml(file.path)}</code>\nRef: <code>${escapeHtml(snapshot.headSha.slice(0, 10))}</code>\n${reason ? `⚠️ ${escapeHtml(reason)}\n` : ''}➖➖➖➖➖➖➖➖➖➖\n<pre>${escapeHtml(preview)}</pre>`,
85
+ reply_markup: { inline_keyboard: rows }
86
+ };
87
+ };
88
+
89
+ const createDraft = async (refId, ownerId) => {
90
+ const ref = await workspaces.resolveNavigationRef({ ownerId, refId });
91
+ if (!ref || ref.type !== 'file') throw new Error('Workspace file reference is missing or expired');
92
+ const { repo, snapshot, file } = await getPinnedFile(ref);
93
+ if (repo.archived) throw new Error('Archived repository is not editable');
94
+ const policy = validateEditableFile({ path: file.path, text: file.content, byteLength: file.size });
95
+ if (!policy.editable) throw new Error(policy.reason || 'File is not editable');
96
+ const originalDigest = await digestText(file.content);
97
+ const workspace = await workspaces.createWorkspace({
98
+ ownerId,
99
+ repoId: Number(ref.repoId),
100
+ repoFullName: repo.fullName,
101
+ baseBranch: repo.defaultBranch,
102
+ baseHeadSha: snapshot.headSha,
103
+ baseTreeSha: snapshot.treeSha,
104
+ path: file.path,
105
+ blobSha: file.sha,
106
+ originalText: file.content,
107
+ originalDigest
108
+ });
109
+ return {
110
+ text: `📝 <b>Draft ساخته شد</b>\nمخزن: <code>${escapeHtml(repo.fullName)}</code>\nفایل: <code>${escapeHtml(file.path)}</code>\nBase: <code>${escapeHtml(snapshot.headSha.slice(0, 10))}</code>\n\nهنوز هیچ تغییری در GitHub انجام نشده است.`,
111
+ reply_markup: { inline_keyboard: [[{ text: '📝 باز کردن Draft', callback_data: `ws:${workspace.id}` }], [{ text: '🔙 فایلها', callback_data: `files:${ref.repoId}` }]] }
112
+ };
113
+ };
114
+
115
+ const renderWorkspace = async (workspaceId, ownerId) => {
116
+ const workspace = await workspaces.getWorkspace({ ownerId, workspaceId });
117
+ if (!workspace) throw new Error('Workspace not found or expired');
118
+ return {
119
+ text: `📝 <b>Repository Workspace</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\nوضعیت: <b>${escapeHtml(workspace.state || 'DRAFT')}</b>\nBase: <code>${escapeHtml(String(workspace.baseHeadSha || '').slice(0, 10))}</code>`,
120
+ reply_markup: { inline_keyboard: [[{ text: '🔙 فایلها', callback_data: `files:${workspace.repoId}` }]] }
121
+ };
122
+ };
123
+
124
+ return {
125
+ resolveCallback(data, context = {}) {
126
+ const parsed = parseCallback(data);
127
+ if (!parsed) return null;
128
+ return {
129
+ actionId: parsed.actionId,
130
+ execute: async () => {
131
+ const ownerId = ownerFrom(context);
132
+ if (parsed.kind === 'root') return renderDirectory(parsed.repoId, '', ownerId);
133
+ if (parsed.kind === 'workspace') return renderWorkspace(parsed.workspaceId, ownerId);
134
+ if (parsed.kind === 'edit') return createDraft(parsed.refId, ownerId);
135
+ const ref = await workspaces.resolveNavigationRef({ ownerId, refId: parsed.refId });
136
+ if (!ref) throw new Error('Workspace navigation reference is missing or expired');
137
+ return ref.type === 'dir'
138
+ ? renderDirectory(ref.repoId, ref.path, ownerId)
139
+ : renderFile(parsed.refId, ownerId);
140
+ }
141
+ };
142
+ }
143
+ };
144
+}