Personal Telegram developer console for GitHub

style: format existing code and enable pinned lint tooling without logic changes

Codex committed Oct 24, 2026 at 18:29 UTC 40e14f7107d3ba500c1ea65b392f30497ca83335
121 files changed +14467 -2865
.github/workflows/ci.yml
+1 -1
@@ -20,7 +20,7 @@ jobs:
20 - name: Setup Node
21 uses: actions/setup-node@v7
22 with:
23 - node-version: "22"
23 + node-version: '22'
24 package-manager-cache: false
25
26 - name: Install dependencies
.github/workflows/deploy.yml
+2 -2
@@ -2,7 +2,7 @@ name: Deploy Cloudflare Worker
2
3 on:
4 workflow_run:
5 - workflows: ["CI"]
5 + workflows: ['CI']
6 types: [completed]
7
8 permissions:
@@ -29,7 +29,7 @@ jobs:
29 - name: Setup Node
30 uses: actions/setup-node@v7
31 with:
32 - node-version: "22"
32 + node-version: '22'
33 package-manager-cache: false
34
35 - name: Verify Cloudflare deployment credentials
.prettierrc.json new
+6
@@ -0,0 +1,6 @@
1 +{
2 + "singleQuote": true,
3 + "quoteProps": "preserve",
4 + "trailingComma": "none",
5 + "embeddedLanguageFormatting": "off"
6 +}
eslint.config.js new
+24
@@ -0,0 +1,24 @@
1 +import js from '@eslint/js';
2 +import globals from 'globals';
3 +
4 +export default [
5 + { ignores: ['node_modules/**', '.wrangler/**'] },
6 + js.configs.recommended,
7 + {
8 + files: ['src/**/*.js', 'test/**/*.js', '*.config.js'],
9 + languageOptions: {
10 + ecmaVersion: 'latest',
11 + sourceType: 'module',
12 + globals: { ...globals.browser, ...globals.node }
13 + },
14 + // Adopt safety errors now; legacy cleanup stays visible without changing logic
15 + // in the formatting-only commit. Review warnings in separate behavior PRs.
16 + rules: {
17 + 'no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
18 + 'no-useless-assignment': 'warn',
19 + 'preserve-caught-error': 'warn',
20 + 'no-useless-escape': 'warn',
21 + 'no-empty': ['error', { allowEmptyCatch: true }]
22 + }
23 + }
24 +];
package-lock.json new
+2555
@@ -0,0 +1,2555 @@
1 +{
2 + "name": "nexa-dev-bot",
3 + "version": "1.1.1",
4 + "lockfileVersion": 3,
5 + "requires": true,
6 + "packages": {
7 + "": {
8 + "name": "nexa-dev-bot",
9 + "version": "1.1.1",
10 + "license": "MIT",
11 + "devDependencies": {
12 + "@eslint/js": "10.0.1",
13 + "eslint": "10.13.0",
14 + "globals": "16.5.0",
15 + "prettier": "3.6.2",
16 + "wrangler": "4.152.0"
17 + }
18 + },
19 + "node_modules/@cacheable/memory": {
20 + "version": "2.2.0",
21 + "resolved": "https://registry.npmjs.org/@cacheable/memory/-/memory-2.2.0.tgz",
22 + "integrity": "sha512-CTLKqLItRCEixEAewD3/j9DB3/o96gpTPD4eJ1v+DGOlxZRZncRQkGYqqnAGCscYd6RNeXfGeiuCphsPtqyIfQ==",
23 + "dev": true,
24 + "license": "MIT",
25 + "dependencies": {
26 + "@cacheable/utils": "^2.5.0",
27 + "@keyv/bigmap": "^1.3.1",
28 + "hookified": "^1.15.1",
29 + "keyv": "^5.6.0"
30 + }
31 + },
32 + "node_modules/@cacheable/utils": {
33 + "version": "2.5.0",
34 + "resolved": "https://registry.npmjs.org/@cacheable/utils/-/utils-2.5.0.tgz",
35 + "integrity": "sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==",
36 + "dev": true,
37 + "license": "MIT",
38 + "dependencies": {
39 + "hashery": "^1.5.1",
40 + "keyv": "^5.6.0"
41 + }
42 + },
43 + "node_modules/@cloudflare/kv-asset-handler": {
44 + "version": "0.5.0",
45 + "resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.5.0.tgz",
46 + "integrity": "sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg==",
47 + "dev": true,
48 + "license": "MIT OR Apache-2.0",
49 + "engines": {
50 + "node": ">=22.0.0"
51 + }
52 + },
53 + "node_modules/@cloudflare/unenv-preset": {
54 + "version": "2.16.2",
55 + "resolved": "https://registry.npmjs.org/@cloudflare/unenv-preset/-/unenv-preset-2.16.2.tgz",
56 + "integrity": "sha512-JBP1+Z7ZSNG/d4mRP+y8VC5dka3tZVMLEZRvS+rzQ4DGV1EoxRFQckcJTTkXbHSQiTj0DtNI01Zwb/V2fX0mvQ==",
57 + "dev": true,
58 + "license": "MIT OR Apache-2.0",
59 + "peerDependencies": {
60 + "unenv": "2.0.0-rc.24",
61 + "workerd": ">1.20260305.0 <2.0.0-0"
62 + },
63 + "peerDependenciesMeta": {
64 + "workerd": {
65 + "optional": true
66 + }
67 + }
68 + },
69 + "node_modules/@cloudflare/workerd-darwin-64": {
70 + "version": "1.20261019.1",
71 + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20261019.1.tgz",
72 + "integrity": "sha512-5ZILbAta/fBQvhmAYeCE7dKMMYIr7N9wJEX50fEGLKSIwGtvT0HzSfHNIK/O7cBQ4gHQ2WfIiPClvwcye6E0fA==",
73 + "cpu": [
74 + "x64"
75 + ],
76 + "dev": true,
77 + "license": "Apache-2.0",
78 + "optional": true,
79 + "os": [
80 + "darwin"
81 + ],
82 + "engines": {
83 + "node": ">=16"
84 + }
85 + },
86 + "node_modules/@cloudflare/workerd-darwin-arm64": {
87 + "version": "1.20261019.1",
88 + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20261019.1.tgz",
89 + "integrity": "sha512-cww2Ab6lVMxpTiEEjKmPI58p5EMo0vYTZSH+3WkqXJdQgc3ES66GuL247+U2B2YWajhhu2tqj7jySrXneU749g==",
90 + "cpu": [
91 + "arm64"
92 + ],
93 + "dev": true,
94 + "license": "Apache-2.0",
95 + "optional": true,
96 + "os": [
97 + "darwin"
98 + ],
99 + "engines": {
100 + "node": ">=16"
101 + }
102 + },
103 + "node_modules/@cloudflare/workerd-linux-64": {
104 + "version": "1.20261019.1",
105 + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20261019.1.tgz",
106 + "integrity": "sha512-4++VRi9vkQROYqrpZYOixIJuVDmujkwrT4kszsxNFlvcmsX6Mr2GumvxIN3gIixS3vJUh3Umdtkthqj5X0S3Xw==",
107 + "cpu": [
108 + "x64"
109 + ],
110 + "dev": true,
111 + "license": "Apache-2.0",
112 + "optional": true,
113 + "os": [
114 + "linux"
115 + ],
116 + "engines": {
117 + "node": ">=16"
118 + }
119 + },
120 + "node_modules/@cloudflare/workerd-linux-arm64": {
121 + "version": "1.20261019.1",
122 + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20261019.1.tgz",
123 + "integrity": "sha512-75PVtJOwfjScQ53sbLtQXI7D8yP1c21t+WEUPaYbqkzaz4ZqfR5wAd+zuWs8G5Q7kOj2SQIvEfY5Sn8Y+UVrnA==",
124 + "cpu": [
125 + "arm64"
126 + ],
127 + "dev": true,
128 + "license": "Apache-2.0",
129 + "optional": true,
130 + "os": [
131 + "linux"
132 + ],
133 + "engines": {
134 + "node": ">=16"
135 + }
136 + },
137 + "node_modules/@cloudflare/workerd-windows-64": {
138 + "version": "1.20261019.1",
139 + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20261019.1.tgz",
140 + "integrity": "sha512-z49fvKTETMCnG6wnMcQwxx9CpryFceiKz04FRjq26EkhCyzRNJ6c3UXhyZz3r5f1CXnnBZc5DcU8ZouPkUJCqw==",
141 + "cpu": [
142 + "x64"
143 + ],
144 + "dev": true,
145 + "license": "Apache-2.0",
146 + "optional": true,
147 + "os": [
148 + "win32"
149 + ],
150 + "engines": {
151 + "node": ">=16"
152 + }
153 + },
154 + "node_modules/@cspotcode/source-map-support": {
155 + "version": "0.8.1",
156 + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",
157 + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==",
158 + "dev": true,
159 + "license": "MIT",
160 + "dependencies": {
161 + "@jridgewell/trace-mapping": "0.3.9"
162 + },
163 + "engines": {
164 + "node": ">=12"
165 + }
166 + },
167 + "node_modules/@emnapi/runtime": {
168 + "version": "1.11.3",
169 + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",
170 + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",
171 + "dev": true,
172 + "license": "MIT",
173 + "optional": true,
174 + "dependencies": {
175 + "tslib": "^2.4.0"
176 + }
177 + },
178 + "node_modules/@esbuild/aix-ppc64": {
179 + "version": "0.28.2",
180 + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
181 + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==",
182 + "cpu": [
183 + "ppc64"
184 + ],
185 + "dev": true,
186 + "license": "MIT",
187 + "optional": true,
188 + "os": [
189 + "aix"
190 + ],
191 + "engines": {
192 + "node": ">=18"
193 + }
194 + },
195 + "node_modules/@esbuild/android-arm": {
196 + "version": "0.28.2",
197 + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz",
198 + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==",
199 + "cpu": [
200 + "arm"
201 + ],
202 + "dev": true,
203 + "license": "MIT",
204 + "optional": true,
205 + "os": [
206 + "android"
207 + ],
208 + "engines": {
209 + "node": ">=18"
210 + }
211 + },
212 + "node_modules/@esbuild/android-arm64": {
213 + "version": "0.28.2",
214 + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz",
215 + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==",
216 + "cpu": [
217 + "arm64"
218 + ],
219 + "dev": true,
220 + "license": "MIT",
221 + "optional": true,
222 + "os": [
223 + "android"
224 + ],
225 + "engines": {
226 + "node": ">=18"
227 + }
228 + },
229 + "node_modules/@esbuild/android-x64": {
230 + "version": "0.28.2",
231 + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz",
232 + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==",
233 + "cpu": [
234 + "x64"
235 + ],
236 + "dev": true,
237 + "license": "MIT",
238 + "optional": true,
239 + "os": [
240 + "android"
241 + ],
242 + "engines": {
243 + "node": ">=18"
244 + }
245 + },
246 + "node_modules/@esbuild/darwin-arm64": {
247 + "version": "0.28.2",
248 + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz",
249 + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==",
250 + "cpu": [
251 + "arm64"
252 + ],
253 + "dev": true,
254 + "license": "MIT",
255 + "optional": true,
256 + "os": [
257 + "darwin"
258 + ],
259 + "engines": {
260 + "node": ">=18"
261 + }
262 + },
263 + "node_modules/@esbuild/darwin-x64": {
264 + "version": "0.28.2",
265 + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz",
266 + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==",
267 + "cpu": [
268 + "x64"
269 + ],
270 + "dev": true,
271 + "license": "MIT",
272 + "optional": true,
273 + "os": [
274 + "darwin"
275 + ],
276 + "engines": {
277 + "node": ">=18"
278 + }
279 + },
280 + "node_modules/@esbuild/freebsd-arm64": {
281 + "version": "0.28.2",
282 + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz",
283 + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==",
284 + "cpu": [
285 + "arm64"
286 + ],
287 + "dev": true,
288 + "license": "MIT",
289 + "optional": true,
290 + "os": [
291 + "freebsd"
292 + ],
293 + "engines": {
294 + "node": ">=18"
295 + }
296 + },
297 + "node_modules/@esbuild/freebsd-x64": {
298 + "version": "0.28.2",
299 + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz",
300 + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==",
301 + "cpu": [
302 + "x64"
303 + ],
304 + "dev": true,
305 + "license": "MIT",
306 + "optional": true,
307 + "os": [
308 + "freebsd"
309 + ],
310 + "engines": {
311 + "node": ">=18"
312 + }
313 + },
314 + "node_modules/@esbuild/linux-arm": {
315 + "version": "0.28.2",
316 + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz",
317 + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==",
318 + "cpu": [
319 + "arm"
320 + ],
321 + "dev": true,
322 + "license": "MIT",
323 + "optional": true,
324 + "os": [
325 + "linux"
326 + ],
327 + "engines": {
328 + "node": ">=18"
329 + }
330 + },
331 + "node_modules/@esbuild/linux-arm64": {
332 + "version": "0.28.2",
333 + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz",
334 + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==",
335 + "cpu": [
336 + "arm64"
337 + ],
338 + "dev": true,
339 + "license": "MIT",
340 + "optional": true,
341 + "os": [
342 + "linux"
343 + ],
344 + "engines": {
345 + "node": ">=18"
346 + }
347 + },
348 + "node_modules/@esbuild/linux-ia32": {
349 + "version": "0.28.2",
350 + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz",
351 + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==",
352 + "cpu": [
353 + "ia32"
354 + ],
355 + "dev": true,
356 + "license": "MIT",
357 + "optional": true,
358 + "os": [
359 + "linux"
360 + ],
361 + "engines": {
362 + "node": ">=18"
363 + }
364 + },
365 + "node_modules/@esbuild/linux-loong64": {
366 + "version": "0.28.2",
367 + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz",
368 + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==",
369 + "cpu": [
370 + "loong64"
371 + ],
372 + "dev": true,
373 + "license": "MIT",
374 + "optional": true,
375 + "os": [
376 + "linux"
377 + ],
378 + "engines": {
379 + "node": ">=18"
380 + }
381 + },
382 + "node_modules/@esbuild/linux-mips64el": {
383 + "version": "0.28.2",
384 + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz",
385 + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==",
386 + "cpu": [
387 + "mips64el"
388 + ],
389 + "dev": true,
390 + "license": "MIT",
391 + "optional": true,
392 + "os": [
393 + "linux"
394 + ],
395 + "engines": {
396 + "node": ">=18"
397 + }
398 + },
399 + "node_modules/@esbuild/linux-ppc64": {
400 + "version": "0.28.2",
401 + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz",
402 + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==",
403 + "cpu": [
404 + "ppc64"
405 + ],
406 + "dev": true,
407 + "license": "MIT",
408 + "optional": true,
409 + "os": [
410 + "linux"
411 + ],
412 + "engines": {
413 + "node": ">=18"
414 + }
415 + },
416 + "node_modules/@esbuild/linux-riscv64": {
417 + "version": "0.28.2",
418 + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz",
419 + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==",
420 + "cpu": [
421 + "riscv64"
422 + ],
423 + "dev": true,
424 + "license": "MIT",
425 + "optional": true,
426 + "os": [
427 + "linux"
428 + ],
429 + "engines": {
430 + "node": ">=18"
431 + }
432 + },
433 + "node_modules/@esbuild/linux-s390x": {
434 + "version": "0.28.2",
435 + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz",
436 + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==",
437 + "cpu": [
438 + "s390x"
439 + ],
440 + "dev": true,
441 + "license": "MIT",
442 + "optional": true,
443 + "os": [
444 + "linux"
445 + ],
446 + "engines": {
447 + "node": ">=18"
448 + }
449 + },
450 + "node_modules/@esbuild/linux-x64": {
451 + "version": "0.28.2",
452 + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz",
453 + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==",
454 + "cpu": [
455 + "x64"
456 + ],
457 + "dev": true,
458 + "license": "MIT",
459 + "optional": true,
460 + "os": [
461 + "linux"
462 + ],
463 + "engines": {
464 + "node": ">=18"
465 + }
466 + },
467 + "node_modules/@esbuild/netbsd-arm64": {
468 + "version": "0.28.2",
469 + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz",
470 + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==",
471 + "cpu": [
472 + "arm64"
473 + ],
474 + "dev": true,
475 + "license": "MIT",
476 + "optional": true,
477 + "os": [
478 + "netbsd"
479 + ],
480 + "engines": {
481 + "node": ">=18"
482 + }
483 + },
484 + "node_modules/@esbuild/netbsd-x64": {
485 + "version": "0.28.2",
486 + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz",
487 + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==",
488 + "cpu": [
489 + "x64"
490 + ],
491 + "dev": true,
492 + "license": "MIT",
493 + "optional": true,
494 + "os": [
495 + "netbsd"
496 + ],
497 + "engines": {
498 + "node": ">=18"
499 + }
500 + },
501 + "node_modules/@esbuild/openbsd-arm64": {
502 + "version": "0.28.2",
503 + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz",
504 + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==",
505 + "cpu": [
506 + "arm64"
507 + ],
508 + "dev": true,
509 + "license": "MIT",
510 + "optional": true,
511 + "os": [
512 + "openbsd"
513 + ],
514 + "engines": {
515 + "node": ">=18"
516 + }
517 + },
518 + "node_modules/@esbuild/openbsd-x64": {
519 + "version": "0.28.2",
520 + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz",
521 + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==",
522 + "cpu": [
523 + "x64"
524 + ],
525 + "dev": true,
526 + "license": "MIT",
527 + "optional": true,
528 + "os": [
529 + "openbsd"
530 + ],
531 + "engines": {
532 + "node": ">=18"
533 + }
534 + },
535 + "node_modules/@esbuild/openharmony-arm64": {
536 + "version": "0.28.2",
537 + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz",
538 + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==",
539 + "cpu": [
540 + "arm64"
541 + ],
542 + "dev": true,
543 + "license": "MIT",
544 + "optional": true,
545 + "os": [
546 + "openharmony"
547 + ],
548 + "engines": {
549 + "node": ">=18"
550 + }
551 + },
552 + "node_modules/@esbuild/sunos-x64": {
553 + "version": "0.28.2",
554 + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz",
555 + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==",
556 + "cpu": [
557 + "x64"
558 + ],
559 + "dev": true,
560 + "license": "MIT",
561 + "optional": true,
562 + "os": [
563 + "sunos"
564 + ],
565 + "engines": {
566 + "node": ">=18"
567 + }
568 + },
569 + "node_modules/@esbuild/win32-arm64": {
570 + "version": "0.28.2",
571 + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz",
572 + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==",
573 + "cpu": [
574 + "arm64"
575 + ],
576 + "dev": true,
577 + "license": "MIT",
578 + "optional": true,
579 + "os": [
580 + "win32"
581 + ],
582 + "engines": {
583 + "node": ">=18"
584 + }
585 + },
586 + "node_modules/@esbuild/win32-ia32": {
587 + "version": "0.28.2",
588 + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz",
589 + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==",
590 + "cpu": [
591 + "ia32"
592 + ],
593 + "dev": true,
594 + "license": "MIT",
595 + "optional": true,
596 + "os": [
597 + "win32"
598 + ],
599 + "engines": {
600 + "node": ">=18"
601 + }
602 + },
603 + "node_modules/@esbuild/win32-x64": {
604 + "version": "0.28.2",
605 + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz",
606 + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==",
607 + "cpu": [
608 + "x64"
609 + ],
610 + "dev": true,
611 + "license": "MIT",
612 + "optional": true,
613 + "os": [
614 + "win32"
615 + ],
616 + "engines": {
617 + "node": ">=18"
618 + }
619 + },
620 + "node_modules/@eslint-community/eslint-utils": {
621 + "version": "4.10.1",
622 + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz",
623 + "integrity": "sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==",
624 + "dev": true,
625 + "license": "MIT",
626 + "dependencies": {
627 + "eslint-visitor-keys": "^3.4.3"
628 + },
629 + "engines": {
630 + "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
631 + },
632 + "funding": {
633 + "url": "https://opencollective.com/eslint"
634 + },
635 + "peerDependencies": {
636 + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0"
637 + }
638 + },
639 + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": {
640 + "version": "3.4.3",
641 + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz",
642 + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==",
643 + "dev": true,
644 + "license": "Apache-2.0",
645 + "engines": {
646 + "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
647 + },
648 + "funding": {
649 + "url": "https://opencollective.com/eslint"
650 + }
651 + },
652 + "node_modules/@eslint-community/regexpp": {
653 + "version": "4.12.2",
654 + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz",
655 + "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==",
656 + "dev": true,
657 + "license": "MIT",
658 + "engines": {
659 + "node": "^12.0.0 || ^14.0.0 || >=16.0.0"
660 + }
661 + },
662 + "node_modules/@eslint/config-array": {
663 + "version": "0.23.5",
664 + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.5.tgz",
665 + "integrity": "sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==",
666 + "dev": true,
667 + "license": "Apache-2.0",
668 + "dependencies": {
669 + "@eslint/object-schema": "^3.0.5",
670 + "debug": "^4.3.1",
671 + "minimatch": "^10.2.4"
672 + },
673 + "engines": {
674 + "node": "^20.19.0 || ^22.13.0 || >=24"
675 + }
676 + },
677 + "node_modules/@eslint/config-helpers": {
678 + "version": "0.7.0",
679 + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.7.0.tgz",
680 + "integrity": "sha512-DObd/KKUsU+FaFv4PLxSRenpXfQWmPXXP3pPZ6/K1PCrMu2vQpMDMuQe/BqYeoLcz8ro0bVDF1RxOJgfVEdhUw==",
681 + "dev": true,
682 + "license": "Apache-2.0",
683 + "dependencies": {
684 + "@eslint/core": "^1.2.1"
685 + },
686 + "engines": {
687 + "node": "^20.19.0 || ^22.13.0 || >=24"
688 + }
689 + },
690 + "node_modules/@eslint/core": {
691 + "version": "1.2.1",
692 + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-1.2.1.tgz",
693 + "integrity": "sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==",
694 + "dev": true,
695 + "license": "Apache-2.0",
696 + "dependencies": {
697 + "@types/json-schema": "^7.0.15"
698 + },
699 + "engines": {
700 + "node": "^20.19.0 || ^22.13.0 || >=24"
701 + }
702 + },
703 + "node_modules/@eslint/js": {
704 + "version": "10.0.1",
705 + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-10.0.1.tgz",
706 + "integrity": "sha512-zeR9k5pd4gxjZ0abRoIaxdc7I3nDktoXZk2qOv9gCNWx3mVwEn32VRhyLaRsDiJjTs0xq/T8mfPtyuXu7GWBcA==",
707 + "dev": true,
708 + "license": "MIT",
709 + "engines": {
710 + "node": "^20.19.0 || ^22.13.0 || >=24"
711 + },
712 + "funding": {
713 + "url": "https://eslint.org/donate"
714 + },
715 + "peerDependencies": {
716 + "eslint": "^10.0.0"
717 + },
718 + "peerDependenciesMeta": {
719 + "eslint": {
720 + "optional": true
721 + }
722 + }
723 + },
724 + "node_modules/@eslint/object-schema": {
725 + "version": "3.0.5",
726 + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-3.0.5.tgz",
727 + "integrity": "sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==",
728 + "dev": true,
729 + "license": "Apache-2.0",
730 + "engines": {
731 + "node": "^20.19.0 || ^22.13.0 || >=24"
732 + }
733 + },
734 + "node_modules/@eslint/plugin-kit": {
735 + "version": "0.7.3",
736 + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.7.3.tgz",
737 + "integrity": "sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q==",
738 + "dev": true,
739 + "license": "Apache-2.0",
740 + "dependencies": {
741 + "@eslint/core": "^1.2.1",
742 + "levn": "^0.4.1"
743 + },
744 + "engines": {
745 + "node": "^20.19.0 || ^22.13.0 || >=24"
746 + }
747 + },
748 + "node_modules/@humanfs/core": {
749 + "version": "0.19.2",
750 + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz",
751 + "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==",
752 + "dev": true,
753 + "license": "Apache-2.0",
754 + "dependencies": {
755 + "@humanfs/types": "^0.15.0"
756 + },
757 + "engines": {
758 + "node": ">=18.18.0"
759 + }
760 + },
761 + "node_modules/@humanfs/node": {
762 + "version": "0.16.8",
763 + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz",
764 + "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==",
765 + "dev": true,
766 + "license": "Apache-2.0",
767 + "dependencies": {
768 + "@humanfs/core": "^0.19.2",
769 + "@humanfs/types": "^0.15.0",
770 + "@humanwhocodes/retry": "^0.4.0"
771 + },
772 + "engines": {
773 + "node": ">=18.18.0"
774 + }
775 + },
776 + "node_modules/@humanfs/types": {
777 + "version": "0.15.0",
778 + "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz",
779 + "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==",
780 + "dev": true,
781 + "license": "Apache-2.0",
782 + "engines": {
783 + "node": ">=18.18.0"
784 + }
785 + },
786 + "node_modules/@humanwhocodes/module-importer": {
787 + "version": "1.0.1",
788 + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz",
789 + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==",
790 + "dev": true,
791 + "license": "Apache-2.0",
792 + "engines": {
793 + "node": ">=12.22"
794 + },
795 + "funding": {
796 + "type": "github",
797 + "url": "https://github.com/sponsors/nzakas"
798 + }
799 + },
800 + "node_modules/@humanwhocodes/retry": {
801 + "version": "0.4.3",
802 + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz",
803 + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==",
804 + "dev": true,
805 + "license": "Apache-2.0",
806 + "engines": {
807 + "node": ">=18.18"
808 + },
809 + "funding": {
810 + "type": "github",
811 + "url": "https://github.com/sponsors/nzakas"
812 + }
813 + },
814 + "node_modules/@img/colour": {
815 + "version": "1.1.0",
816 + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
817 + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",
818 + "dev": true,
819 + "license": "MIT",
820 + "engines": {
821 + "node": ">=18"
822 + }
823 + },
824 + "node_modules/@img/sharp-darwin-arm64": {
825 + "version": "0.35.5",
826 + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz",
827 + "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==",
828 + "cpu": [
829 + "arm64"
830 + ],
831 + "dev": true,
832 + "license": "Apache-2.0",
833 + "optional": true,
834 + "os": [
835 + "darwin"
836 + ],
837 + "engines": {
838 + "node": ">=20.9.0"
839 + },
840 + "funding": {
841 + "url": "https://opencollective.com/libvips"
842 + },
843 + "optionalDependencies": {
844 + "@img/sharp-libvips-darwin-arm64": "1.3.4"
845 + }
846 + },
847 + "node_modules/@img/sharp-darwin-x64": {
848 + "version": "0.35.5",
849 + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz",
850 + "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==",
851 + "cpu": [
852 + "x64"
853 + ],
854 + "dev": true,
855 + "license": "Apache-2.0",
856 + "optional": true,
857 + "os": [
858 + "darwin"
859 + ],
860 + "engines": {
861 + "node": ">=20.9.0"
862 + },
863 + "funding": {
864 + "url": "https://opencollective.com/libvips"
865 + },
866 + "optionalDependencies": {
867 + "@img/sharp-libvips-darwin-x64": "1.3.4"
868 + }
869 + },
870 + "node_modules/@img/sharp-freebsd-wasm32": {
871 + "version": "0.35.5",
872 + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz",
873 + "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==",
874 + "dev": true,
875 + "license": "Apache-2.0",
876 + "optional": true,
877 + "os": [
878 + "freebsd"
879 + ],
880 + "dependencies": {
881 + "@img/sharp-wasm32": "0.35.5"
882 + },
883 + "engines": {
884 + "node": ">=20.9.0"
885 + },
886 + "funding": {
887 + "url": "https://opencollective.com/libvips"
888 + }
889 + },
890 + "node_modules/@img/sharp-libvips-darwin-arm64": {
891 + "version": "1.3.4",
892 + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz",
893 + "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==",
894 + "cpu": [
895 + "arm64"
896 + ],
897 + "dev": true,
898 + "license": "LGPL-3.0-or-later",
899 + "optional": true,
900 + "os": [
901 + "darwin"
902 + ],
903 + "funding": {
904 + "url": "https://opencollective.com/libvips"
905 + }
906 + },
907 + "node_modules/@img/sharp-libvips-darwin-x64": {
908 + "version": "1.3.4",
909 + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz",
910 + "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==",
911 + "cpu": [
912 + "x64"
913 + ],
914 + "dev": true,
915 + "license": "LGPL-3.0-or-later",
916 + "optional": true,
917 + "os": [
918 + "darwin"
919 + ],
920 + "funding": {
921 + "url": "https://opencollective.com/libvips"
922 + }
923 + },
924 + "node_modules/@img/sharp-libvips-linux-arm": {
925 + "version": "1.3.4",
926 + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz",
927 + "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==",
928 + "cpu": [
929 + "arm"
930 + ],
931 + "dev": true,
932 + "license": "LGPL-3.0-or-later",
933 + "optional": true,
934 + "os": [
935 + "linux"
936 + ],
937 + "funding": {
938 + "url": "https://opencollective.com/libvips"
939 + }
940 + },
941 + "node_modules/@img/sharp-libvips-linux-arm64": {
942 + "version": "1.3.4",
943 + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz",
944 + "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==",
945 + "cpu": [
946 + "arm64"
947 + ],
948 + "dev": true,
949 + "license": "LGPL-3.0-or-later",
950 + "optional": true,
951 + "os": [
952 + "linux"
953 + ],
954 + "funding": {
955 + "url": "https://opencollective.com/libvips"
956 + }
957 + },
958 + "node_modules/@img/sharp-libvips-linux-ppc64": {
959 + "version": "1.3.4",
960 + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz",
961 + "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==",
962 + "cpu": [
963 + "ppc64"
964 + ],
965 + "dev": true,
966 + "license": "LGPL-3.0-or-later",
967 + "optional": true,
968 + "os": [
969 + "linux"
970 + ],
971 + "funding": {
972 + "url": "https://opencollective.com/libvips"
973 + }
974 + },
975 + "node_modules/@img/sharp-libvips-linux-riscv64": {
976 + "version": "1.3.4",
977 + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz",
978 + "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==",
979 + "cpu": [
980 + "riscv64"
981 + ],
982 + "dev": true,
983 + "license": "LGPL-3.0-or-later",
984 + "optional": true,
985 + "os": [
986 + "linux"
987 + ],
988 + "funding": {
989 + "url": "https://opencollective.com/libvips"
990 + }
991 + },
992 + "node_modules/@img/sharp-libvips-linux-s390x": {
993 + "version": "1.3.4",
994 + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz",
995 + "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==",
996 + "cpu": [
997 + "s390x"
998 + ],
999 + "dev": true,
1000 + "license": "LGPL-3.0-or-later",
1001 + "optional": true,
1002 + "os": [
1003 + "linux"
1004 + ],
1005 + "funding": {
1006 + "url": "https://opencollective.com/libvips"
1007 + }
1008 + },
1009 + "node_modules/@img/sharp-libvips-linux-x64": {
1010 + "version": "1.3.4",
1011 + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz",
1012 + "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==",
1013 + "cpu": [
1014 + "x64"
1015 + ],
1016 + "dev": true,
1017 + "license": "LGPL-3.0-or-later",
1018 + "optional": true,
1019 + "os": [
1020 + "linux"
1021 + ],
1022 + "funding": {
1023 + "url": "https://opencollective.com/libvips"
1024 + }
1025 + },
1026 + "node_modules/@img/sharp-libvips-linuxmusl-arm64": {
1027 + "version": "1.3.4",
1028 + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz",
1029 + "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==",
1030 + "cpu": [
1031 + "arm64"
1032 + ],
1033 + "dev": true,
1034 + "license": "LGPL-3.0-or-later",
1035 + "optional": true,
1036 + "os": [
1037 + "linux"
1038 + ],
1039 + "funding": {
1040 + "url": "https://opencollective.com/libvips"
1041 + }
1042 + },
1043 + "node_modules/@img/sharp-libvips-linuxmusl-x64": {
1044 + "version": "1.3.4",
1045 + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz",
1046 + "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==",
1047 + "cpu": [
1048 + "x64"
1049 + ],
1050 + "dev": true,
1051 + "license": "LGPL-3.0-or-later",
1052 + "optional": true,
1053 + "os": [
1054 + "linux"
1055 + ],
1056 + "funding": {
1057 + "url": "https://opencollective.com/libvips"
1058 + }
1059 + },
1060 + "node_modules/@img/sharp-linux-arm": {
1061 + "version": "0.35.5",
1062 + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz",
1063 + "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==",
1064 + "cpu": [
1065 + "arm"
1066 + ],
1067 + "dev": true,
1068 + "license": "Apache-2.0",
1069 + "optional": true,
1070 + "os": [
1071 + "linux"
1072 + ],
1073 + "engines": {
1074 + "node": ">=20.9.0"
1075 + },
1076 + "funding": {
1077 + "url": "https://opencollective.com/libvips"
1078 + },
1079 + "optionalDependencies": {
1080 + "@img/sharp-libvips-linux-arm": "1.3.4"
1081 + }
1082 + },
1083 + "node_modules/@img/sharp-linux-arm64": {
1084 + "version": "0.35.5",
1085 + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz",
1086 + "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==",
1087 + "cpu": [
1088 + "arm64"
1089 + ],
1090 + "dev": true,
1091 + "license": "Apache-2.0",
1092 + "optional": true,
1093 + "os": [
1094 + "linux"
1095 + ],
1096 + "engines": {
1097 + "node": ">=20.9.0"
1098 + },
1099 + "funding": {
1100 + "url": "https://opencollective.com/libvips"
1101 + },
1102 + "optionalDependencies": {
1103 + "@img/sharp-libvips-linux-arm64": "1.3.4"
1104 + }
1105 + },
1106 + "node_modules/@img/sharp-linux-ppc64": {
1107 + "version": "0.35.5",
1108 + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz",
1109 + "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==",
1110 + "cpu": [
1111 + "ppc64"
1112 + ],
1113 + "dev": true,
1114 + "license": "Apache-2.0",
1115 + "optional": true,
1116 + "os": [
1117 + "linux"
1118 + ],
1119 + "engines": {
1120 + "node": ">=20.9.0"
1121 + },
1122 + "funding": {
1123 + "url": "https://opencollective.com/libvips"
1124 + },
1125 + "optionalDependencies": {
1126 + "@img/sharp-libvips-linux-ppc64": "1.3.4"
1127 + }
1128 + },
1129 + "node_modules/@img/sharp-linux-riscv64": {
1130 + "version": "0.35.5",
1131 + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz",
1132 + "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==",
1133 + "cpu": [
1134 + "riscv64"
1135 + ],
1136 + "dev": true,
1137 + "license": "Apache-2.0",
1138 + "optional": true,
1139 + "os": [
1140 + "linux"
1141 + ],
1142 + "engines": {
1143 + "node": ">=20.9.0"
1144 + },
1145 + "funding": {
1146 + "url": "https://opencollective.com/libvips"
1147 + },
1148 + "optionalDependencies": {
1149 + "@img/sharp-libvips-linux-riscv64": "1.3.4"
1150 + }
1151 + },
1152 + "node_modules/@img/sharp-linux-s390x": {
1153 + "version": "0.35.5",
1154 + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz",
1155 + "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==",
1156 + "cpu": [
1157 + "s390x"
1158 + ],
1159 + "dev": true,
1160 + "license": "Apache-2.0",
1161 + "optional": true,
1162 + "os": [
1163 + "linux"
1164 + ],
1165 + "engines": {
1166 + "node": ">=20.9.0"
1167 + },
1168 + "funding": {
1169 + "url": "https://opencollective.com/libvips"
1170 + },
1171 + "optionalDependencies": {
1172 + "@img/sharp-libvips-linux-s390x": "1.3.4"
1173 + }
1174 + },
1175 + "node_modules/@img/sharp-linux-x64": {
1176 + "version": "0.35.5",
1177 + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz",
1178 + "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==",
1179 + "cpu": [
1180 + "x64"
1181 + ],
1182 + "dev": true,
1183 + "license": "Apache-2.0",
1184 + "optional": true,
1185 + "os": [
1186 + "linux"
1187 + ],
1188 + "engines": {
1189 + "node": ">=20.9.0"
1190 + },
1191 + "funding": {
1192 + "url": "https://opencollective.com/libvips"
1193 + },
1194 + "optionalDependencies": {
1195 + "@img/sharp-libvips-linux-x64": "1.3.4"
1196 + }
1197 + },
1198 + "node_modules/@img/sharp-linuxmusl-arm64": {
1199 + "version": "0.35.5",
1200 + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz",
1201 + "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==",
1202 + "cpu": [
1203 + "arm64"
1204 + ],
1205 + "dev": true,
1206 + "license": "Apache-2.0",
1207 + "optional": true,
1208 + "os": [
1209 + "linux"
1210 + ],
1211 + "engines": {
1212 + "node": ">=20.9.0"
1213 + },
1214 + "funding": {
1215 + "url": "https://opencollective.com/libvips"
1216 + },
1217 + "optionalDependencies": {
1218 + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4"
1219 + }
1220 + },
1221 + "node_modules/@img/sharp-linuxmusl-x64": {
1222 + "version": "0.35.5",
1223 + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz",
1224 + "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==",
1225 + "cpu": [
1226 + "x64"
1227 + ],
1228 + "dev": true,
1229 + "license": "Apache-2.0",
1230 + "optional": true,
1231 + "os": [
1232 + "linux"
1233 + ],
1234 + "engines": {
1235 + "node": ">=20.9.0"
1236 + },
1237 + "funding": {
1238 + "url": "https://opencollective.com/libvips"
1239 + },
1240 + "optionalDependencies": {
1241 + "@img/sharp-libvips-linuxmusl-x64": "1.3.4"
1242 + }
1243 + },
1244 + "node_modules/@img/sharp-wasm32": {
1245 + "version": "0.35.5",
1246 + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz",
1247 + "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==",
1248 + "dev": true,
1249 + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
1250 + "optional": true,
1251 + "dependencies": {
1252 + "@emnapi/runtime": "^1.11.3"
1253 + },
1254 + "engines": {
1255 + "node": ">=20.9.0"
1256 + },
1257 + "funding": {
1258 + "url": "https://opencollective.com/libvips"
1259 + }
1260 + },
1261 + "node_modules/@img/sharp-webcontainers-wasm32": {
1262 + "version": "0.35.5",
1263 + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz",
1264 + "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==",
1265 + "cpu": [
1266 + "wasm32"
1267 + ],
1268 + "dev": true,
1269 + "license": "Apache-2.0",
1270 + "optional": true,
1271 + "dependencies": {
1272 + "@img/sharp-wasm32": "0.35.5"
1273 + },
1274 + "engines": {
1275 + "node": ">=20.9.0"
1276 + },
1277 + "funding": {
1278 + "url": "https://opencollective.com/libvips"
1279 + }
1280 + },
1281 + "node_modules/@img/sharp-win32-arm64": {
1282 + "version": "0.35.5",
1283 + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz",
1284 + "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==",
1285 + "cpu": [
1286 + "arm64"
1287 + ],
1288 + "dev": true,
1289 + "license": "Apache-2.0 AND LGPL-3.0-or-later",
1290 + "optional": true,
1291 + "os": [
1292 + "win32"
1293 + ],
1294 + "engines": {
1295 + "node": ">=20.9.0"
1296 + },
1297 + "funding": {
1298 + "url": "https://opencollective.com/libvips"
1299 + }
1300 + },
1301 + "node_modules/@img/sharp-win32-ia32": {
1302 + "version": "0.35.5",
1303 + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz",
1304 + "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==",
1305 + "cpu": [
1306 + "ia32"
1307 + ],
1308 + "dev": true,
1309 + "license": "Apache-2.0 AND LGPL-3.0-or-later",
1310 + "optional": true,
1311 + "os": [
1312 + "win32"
1313 + ],
1314 + "engines": {
1315 + "node": "^20.9.0"
1316 + },
1317 + "funding": {
1318 + "url": "https://opencollective.com/libvips"
1319 + }
1320 + },
1321 + "node_modules/@img/sharp-win32-x64": {
1322 + "version": "0.35.5",
1323 + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz",
1324 + "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==",
1325 + "cpu": [
1326 + "x64"
1327 + ],
1328 + "dev": true,
1329 + "license": "Apache-2.0 AND LGPL-3.0-or-later",
1330 + "optional": true,
1331 + "os": [
1332 + "win32"
1333 + ],
1334 + "engines": {
1335 + "node": ">=20.9.0"
1336 + },
1337 + "funding": {
1338 + "url": "https://opencollective.com/libvips"
1339 + }
1340 + },
1341 + "node_modules/@jridgewell/resolve-uri": {
1342 + "version": "3.1.2",
1343 + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
1344 + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
1345 + "dev": true,
1346 + "license": "MIT",
1347 + "engines": {
1348 + "node": ">=6.0.0"
1349 + }
1350 + },
1351 + "node_modules/@jridgewell/sourcemap-codec": {
1352 + "version": "1.6.0",
1353 + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
1354 + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
1355 + "dev": true,
1356 + "license": "MIT"
1357 + },
1358 + "node_modules/@jridgewell/trace-mapping": {
1359 + "version": "0.3.9",
1360 + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz",
1361 + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==",
1362 + "dev": true,
1363 + "license": "MIT",
1364 + "dependencies": {
1365 + "@jridgewell/resolve-uri": "^3.0.3",
1366 + "@jridgewell/sourcemap-codec": "^1.4.10"
1367 + }
1368 + },
1369 + "node_modules/@keyv/bigmap": {
1370 + "version": "1.3.1",
1371 + "resolved": "https://registry.npmjs.org/@keyv/bigmap/-/bigmap-1.3.1.tgz",
1372 + "integrity": "sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ==",
1373 + "dev": true,
1374 + "license": "MIT",
1375 + "dependencies": {
1376 + "hashery": "^1.4.0",
1377 + "hookified": "^1.15.0"
1378 + },
1379 + "engines": {
1380 + "node": ">= 18"
1381 + },
1382 + "peerDependencies": {
1383 + "keyv": "^5.6.0"
1384 + }
1385 + },
1386 + "node_modules/@keyv/serialize": {
1387 + "version": "1.1.1",
1388 + "resolved": "https://registry.npmjs.org/@keyv/serialize/-/serialize-1.1.1.tgz",
1389 + "integrity": "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==",
1390 + "dev": true,
1391 + "license": "MIT"
1392 + },
1393 + "node_modules/@poppinss/colors": {
1394 + "version": "4.1.6",
1395 + "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz",
1396 + "integrity": "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==",
1397 + "dev": true,
1398 + "license": "MIT",
1399 + "dependencies": {
1400 + "kleur": "^4.1.5"
1401 + }
1402 + },
1403 + "node_modules/@poppinss/dumper": {
1404 + "version": "0.6.5",
1405 + "resolved": "https://registry.npmjs.org/@poppinss/dumper/-/dumper-0.6.5.tgz",
1406 + "integrity": "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==",
1407 + "dev": true,
1408 + "license": "MIT",
1409 + "dependencies": {
1410 + "@poppinss/colors": "^4.1.5",
1411 + "@sindresorhus/is": "^7.0.2",
1412 + "supports-color": "^10.0.0"
1413 + }
1414 + },
1415 + "node_modules/@poppinss/dumper/node_modules/supports-color": {
1416 + "version": "10.2.2",
1417 + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz",
1418 + "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==",
1419 + "dev": true,
1420 + "license": "MIT",
1421 + "engines": {
1422 + "node": ">=18"
1423 + },
1424 + "funding": {
1425 + "url": "https://github.com/chalk/supports-color?sponsor=1"
1426 + }
1427 + },
1428 + "node_modules/@poppinss/exception": {
1429 + "version": "1.2.3",
1430 + "resolved": "https://registry.npmjs.org/@poppinss/exception/-/exception-1.2.3.tgz",
1431 + "integrity": "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==",
1432 + "dev": true,
1433 + "license": "MIT"
1434 + },
1435 + "node_modules/@sindresorhus/is": {
1436 + "version": "7.2.0",
1437 + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz",
1438 + "integrity": "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==",
1439 + "dev": true,
1440 + "license": "MIT",
1441 + "engines": {
1442 + "node": ">=18"
1443 + },
1444 + "funding": {
1445 + "url": "https://github.com/sindresorhus/is?sponsor=1"
1446 + }
1447 + },
1448 + "node_modules/@speed-highlight/core": {
1449 + "version": "1.2.24",
1450 + "resolved": "https://registry.npmjs.org/@speed-highlight/core/-/core-1.2.24.tgz",
1451 + "integrity": "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==",
1452 + "dev": true,
1453 + "license": "CC0-1.0"
1454 + },
1455 + "node_modules/@types/esrecurse": {
1456 + "version": "4.3.1",
1457 + "resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz",
1458 + "integrity": "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==",
1459 + "dev": true,
1460 + "license": "MIT"
1461 + },
1462 + "node_modules/@types/estree": {
1463 + "version": "1.0.9",
1464 + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
1465 + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
1466 + "dev": true,
1467 + "license": "MIT"
1468 + },
1469 + "node_modules/@types/json-schema": {
1470 + "version": "7.0.15",
1471 + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
1472 + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",
1473 + "dev": true,
1474 + "license": "MIT"
1475 + },
1476 + "node_modules/acorn": {
1477 + "version": "8.19.0",
1478 + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz",
1479 + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==",
1480 + "dev": true,
1481 + "license": "MIT",
1482 + "bin": {
1483 + "acorn": "bin/acorn"
1484 + },
1485 + "engines": {
1486 + "node": ">=0.4.0"
1487 + }
1488 + },
1489 + "node_modules/acorn-jsx": {
1490 + "version": "5.3.2",
1491 + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz",
1492 + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==",
1493 + "dev": true,
1494 + "license": "MIT",
1495 + "peerDependencies": {
1496 + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
1497 + }
1498 + },
1499 + "node_modules/ajv": {
1500 + "version": "6.15.0",
1501 + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz",
1502 + "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==",
1503 + "dev": true,
1504 + "license": "MIT",
1505 + "dependencies": {
1506 + "fast-deep-equal": "^3.1.1",
1507 + "fast-json-stable-stringify": "^2.0.0",
1508 + "json-schema-traverse": "^0.4.1",
1509 + "uri-js": "^4.2.2"
1510 + },
1511 + "funding": {
1512 + "type": "github",
1513 + "url": "https://github.com/sponsors/epoberezkin"
1514 + }
1515 + },
1516 + "node_modules/balanced-match": {
1517 + "version": "4.0.4",
1518 + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
1519 + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
1520 + "dev": true,
1521 + "license": "MIT",
1522 + "engines": {
1523 + "node": "18 || 20 || >=22"
1524 + }
1525 + },
1526 + "node_modules/blake3-wasm": {
1527 + "version": "2.1.5",
1528 + "resolved": "https://registry.npmjs.org/blake3-wasm/-/blake3-wasm-2.1.5.tgz",
1529 + "integrity": "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==",
1530 + "dev": true,
1531 + "license": "MIT"
1532 + },
1533 + "node_modules/brace-expansion": {
1534 + "version": "5.0.12",
1535 + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz",
1536 + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==",
1537 + "dev": true,
1538 + "license": "MIT",
1539 + "dependencies": {
1540 + "balanced-match": "^4.0.2"
1541 + },
1542 + "engines": {
1543 + "node": "20 || >=22"
1544 + }
1545 + },
1546 + "node_modules/cacheable": {
1547 + "version": "2.5.0",
1548 + "resolved": "https://registry.npmjs.org/cacheable/-/cacheable-2.5.0.tgz",
1549 + "integrity": "sha512-60cyAOytib/OzBw1JNSoSV/boK1AtHryDIjvVBk7XbN4ugfkM3+Sry7fEjNgPMGgOjuaZPAp8ruZ0Cxafwyq9g==",
1550 + "dev": true,
1551 + "license": "MIT",
1552 + "dependencies": {
1553 + "@cacheable/memory": "^2.2.0",
1554 + "@cacheable/utils": "^2.5.0",
1555 + "hookified": "^1.15.0",
1556 + "keyv": "^5.6.0",
1557 + "qified": "^0.10.1"
1558 + }
1559 + },
1560 + "node_modules/cookie": {
1561 + "version": "1.1.1",
1562 + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",
1563 + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",
1564 + "dev": true,
1565 + "license": "MIT",
1566 + "engines": {
1567 + "node": ">=18"
1568 + },
1569 + "funding": {
1570 + "type": "opencollective",
1571 + "url": "https://opencollective.com/express"
1572 + }
1573 + },
1574 + "node_modules/cross-spawn": {
1575 + "version": "7.0.6",
1576 + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
1577 + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
1578 + "dev": true,
1579 + "license": "MIT",
1580 + "dependencies": {
1581 + "path-key": "^3.1.0",
1582 + "shebang-command": "^2.0.0",
1583 + "which": "^2.0.1"
1584 + },
1585 + "engines": {
1586 + "node": ">= 8"
1587 + }
1588 + },
1589 + "node_modules/debug": {
1590 + "version": "4.4.3",
1591 + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
1592 + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
1593 + "dev": true,
1594 + "license": "MIT",
1595 + "dependencies": {
1596 + "ms": "^2.1.3"
1597 + },
1598 + "engines": {
1599 + "node": ">=6.0"
1600 + },
1601 + "peerDependenciesMeta": {
1602 + "supports-color": {
1603 + "optional": true
1604 + }
1605 + }
1606 + },
1607 + "node_modules/deep-is": {
1608 + "version": "0.1.4",
1609 + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",
1610 + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==",
1611 + "dev": true,
1612 + "license": "MIT"
1613 + },
1614 + "node_modules/detect-libc": {
1615 + "version": "2.1.2",
1616 + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
1617 + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
1618 + "dev": true,
1619 + "license": "Apache-2.0",
1620 + "engines": {
1621 + "node": ">=8"
1622 + }
1623 + },
1624 + "node_modules/error-stack-parser-es": {
1625 + "version": "1.0.5",
1626 + "resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz",
1627 + "integrity": "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==",
1628 + "dev": true,
1629 + "license": "MIT",
1630 + "funding": {
1631 + "url": "https://github.com/sponsors/antfu"
1632 + }
1633 + },
1634 + "node_modules/esbuild": {
1635 + "version": "0.28.2",
1636 + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",
1637 + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",
1638 + "dev": true,
1639 + "hasInstallScript": true,
1640 + "license": "MIT",
1641 + "bin": {
1642 + "esbuild": "bin/esbuild"
1643 + },
1644 + "engines": {
1645 + "node": ">=18"
1646 + },
1647 + "optionalDependencies": {
1648 + "@esbuild/aix-ppc64": "0.28.2",
1649 + "@esbuild/android-arm": "0.28.2",
1650 + "@esbuild/android-arm64": "0.28.2",
1651 + "@esbuild/android-x64": "0.28.2",
1652 + "@esbuild/darwin-arm64": "0.28.2",
1653 + "@esbuild/darwin-x64": "0.28.2",
1654 + "@esbuild/freebsd-arm64": "0.28.2",
1655 + "@esbuild/freebsd-x64": "0.28.2",
1656 + "@esbuild/linux-arm": "0.28.2",
1657 + "@esbuild/linux-arm64": "0.28.2",
1658 + "@esbuild/linux-ia32": "0.28.2",
1659 + "@esbuild/linux-loong64": "0.28.2",
1660 + "@esbuild/linux-mips64el": "0.28.2",
1661 + "@esbuild/linux-ppc64": "0.28.2",
1662 + "@esbuild/linux-riscv64": "0.28.2",
1663 + "@esbuild/linux-s390x": "0.28.2",
1664 + "@esbuild/linux-x64": "0.28.2",
1665 + "@esbuild/netbsd-arm64": "0.28.2",
1666 + "@esbuild/netbsd-x64": "0.28.2",
1667 + "@esbuild/openbsd-arm64": "0.28.2",
1668 + "@esbuild/openbsd-x64": "0.28.2",
1669 + "@esbuild/openharmony-arm64": "0.28.2",
1670 + "@esbuild/sunos-x64": "0.28.2",
1671 + "@esbuild/win32-arm64": "0.28.2",
1672 + "@esbuild/win32-ia32": "0.28.2",
1673 + "@esbuild/win32-x64": "0.28.2"
1674 + }
1675 + },
1676 + "node_modules/escape-string-regexp": {
1677 + "version": "4.0.0",
1678 + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",
1679 + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",
1680 + "dev": true,
1681 + "license": "MIT",
1682 + "engines": {
1683 + "node": ">=10"
1684 + },
1685 + "funding": {
1686 + "url": "https://github.com/sponsors/sindresorhus"
1687 + }
1688 + },
1689 + "node_modules/eslint": {
1690 + "version": "10.13.0",
1691 + "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.13.0.tgz",
1692 + "integrity": "sha512-UohDjD4zSzEwhf58M3O7vc/ycc8O1I7dNlhtD0WxE8Px8EHNJKtUwzBqrzeGhisRuv2ag4sAYswszCJRgKXYUg==",
1693 + "dev": true,
1694 + "license": "MIT",
1695 + "workspaces": [
1696 + "packages/*"
1697 + ],
1698 + "dependencies": {
1699 + "@eslint-community/eslint-utils": "^4.8.0",
1700 + "@eslint-community/regexpp": "^4.12.2",
1701 + "@eslint/config-array": "^0.23.5",
1702 + "@eslint/config-helpers": "^0.7.0",
1703 + "@eslint/core": "^1.2.1",
1704 + "@eslint/plugin-kit": "^0.7.3",
1705 + "@humanfs/node": "^0.16.6",
1706 + "@humanwhocodes/module-importer": "^1.0.1",
1707 + "@humanwhocodes/retry": "^0.4.2",
1708 + "@types/estree": "^1.0.6",
1709 + "ajv": "^6.14.0",
1710 + "cross-spawn": "^7.0.6",
1711 + "debug": "^4.3.2",
1712 + "escape-string-regexp": "^4.0.0",
1713 + "eslint-scope": "^9.1.2",
1714 + "eslint-visitor-keys": "^5.0.1",
1715 + "espree": "^11.2.0",
1716 + "esquery": "^1.7.0",
1717 + "esutils": "^2.0.2",
1718 + "fast-deep-equal": "^3.1.3",
1719 + "file-entry-cache": "11.1.5 || >11.1.6 <12",
1720 + "find-up": "^5.0.0",
1721 + "glob-parent": "^6.0.2",
1722 + "ignore": "^5.2.0",
1723 + "imurmurhash": "^0.1.4",
1724 + "is-glob": "^4.0.0",
1725 + "json-stable-stringify-without-jsonify": "^1.0.1",
1726 + "minimatch": "^10.2.5",
1727 + "natural-compare": "^1.4.0",
1728 + "optionator": "^0.9.3"
1729 + },
1730 + "bin": {
1731 + "eslint": "bin/eslint.js"
1732 + },
1733 + "engines": {
1734 + "node": "^20.19.0 || ^22.13.0 || >=24"
1735 + },
1736 + "funding": {
1737 + "url": "https://eslint.org/donate"
1738 + },
1739 + "peerDependencies": {
1740 + "jiti": "*"
1741 + },
1742 + "peerDependenciesMeta": {
1743 + "jiti": {
1744 + "optional": true
1745 + }
1746 + }
1747 + },
1748 + "node_modules/eslint-scope": {
1749 + "version": "9.1.2",
1750 + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-9.1.2.tgz",
1751 + "integrity": "sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ==",
1752 + "dev": true,
1753 + "license": "BSD-2-Clause",
1754 + "dependencies": {
1755 + "@types/esrecurse": "^4.3.1",
1756 + "@types/estree": "^1.0.8",
1757 + "esrecurse": "^4.3.0",
1758 + "estraverse": "^5.2.0"
1759 + },
1760 + "engines": {
1761 + "node": "^20.19.0 || ^22.13.0 || >=24"
1762 + },
1763 + "funding": {
1764 + "url": "https://opencollective.com/eslint"
1765 + }
1766 + },
1767 + "node_modules/eslint-visitor-keys": {
1768 + "version": "5.0.1",
1769 + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz",
1770 + "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==",
1771 + "dev": true,
1772 + "license": "Apache-2.0",
1773 + "engines": {
1774 + "node": "^20.19.0 || ^22.13.0 || >=24"
1775 + },
1776 + "funding": {
1777 + "url": "https://opencollective.com/eslint"
1778 + }
1779 + },
1780 + "node_modules/espree": {
1781 + "version": "11.2.0",
1782 + "resolved": "https://registry.npmjs.org/espree/-/espree-11.2.0.tgz",
1783 + "integrity": "sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw==",
1784 + "dev": true,
1785 + "license": "BSD-2-Clause",
1786 + "dependencies": {
1787 + "acorn": "^8.16.0",
1788 + "acorn-jsx": "^5.3.2",
1789 + "eslint-visitor-keys": "^5.0.1"
1790 + },
1791 + "engines": {
1792 + "node": "^20.19.0 || ^22.13.0 || >=24"
1793 + },
1794 + "funding": {
1795 + "url": "https://opencollective.com/eslint"
1796 + }
1797 + },
1798 + "node_modules/esquery": {
1799 + "version": "1.7.0",
1800 + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz",
1801 + "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==",
1802 + "dev": true,
1803 + "license": "BSD-3-Clause",
1804 + "dependencies": {
1805 + "estraverse": "^5.1.0"
1806 + },
1807 + "engines": {
1808 + "node": ">=0.10"
1809 + }
1810 + },
1811 + "node_modules/esrecurse": {
1812 + "version": "4.3.0",
1813 + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz",
1814 + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==",
1815 + "dev": true,
1816 + "license": "BSD-2-Clause",
1817 + "dependencies": {
1818 + "estraverse": "^5.2.0"
1819 + },
1820 + "engines": {
1821 + "node": ">=4.0"
1822 + }
1823 + },
1824 + "node_modules/estraverse": {
1825 + "version": "5.3.0",
1826 + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",
1827 + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",
1828 + "dev": true,
1829 + "license": "BSD-2-Clause",
1830 + "engines": {
1831 + "node": ">=4.0"
1832 + }
1833 + },
1834 + "node_modules/esutils": {
1835 + "version": "2.0.3",
1836 + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",
1837 + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==",
1838 + "dev": true,
1839 + "license": "BSD-2-Clause",
1840 + "engines": {
1841 + "node": ">=0.10.0"
1842 + }
1843 + },
1844 + "node_modules/fast-deep-equal": {
1845 + "version": "3.1.3",
1846 + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
1847 + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
1848 + "dev": true,
1849 + "license": "MIT"
1850 + },
1851 + "node_modules/fast-json-stable-stringify": {
1852 + "version": "2.1.0",
1853 + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
1854 + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==",
1855 + "dev": true,
1856 + "license": "MIT"
1857 + },
1858 + "node_modules/fast-levenshtein": {
1859 + "version": "2.0.6",
1860 + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz",
1861 + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==",
1862 + "dev": true,
1863 + "license": "MIT"
1864 + },
1865 + "node_modules/file-entry-cache": {
1866 + "version": "11.1.5",
1867 + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-11.1.5.tgz",
1868 + "integrity": "sha512-+PFTHITI08JIGhnNpGNI8T8inUpgZfk3GNEqfT9R2zZV2iFXg3CvqzSl/uEhs7TSGujYRELEANyDvS8Fj7+S7Q==",
1869 + "dev": true,
1870 + "license": "MIT",
1871 + "dependencies": {
1872 + "flat-cache": "^6.1.23"
1873 + }
1874 + },
1875 + "node_modules/find-up": {
1876 + "version": "5.0.0",
1877 + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz",
1878 + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==",
1879 + "dev": true,
1880 + "license": "MIT",
1881 + "dependencies": {
1882 + "locate-path": "^6.0.0",
1883 + "path-exists": "^4.0.0"
1884 + },
1885 + "engines": {
1886 + "node": ">=10"
1887 + },
1888 + "funding": {
1889 + "url": "https://github.com/sponsors/sindresorhus"
1890 + }
1891 + },
1892 + "node_modules/flat-cache": {
1893 + "version": "6.1.23",
1894 + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-6.1.23.tgz",
1895 + "integrity": "sha512-f++BY9pTk+983xK1FLzlLpmM0i0z+jHmx3QESGkURMXujQZz1k5wzwX6hjnQ8goaD0B+sYnDK1yZ6MTyZfUaqA==",
1896 + "dev": true,
1897 + "license": "MIT",
1898 + "dependencies": {
1899 + "cacheable": "^2.5.0",
1900 + "flatted": "^3.4.2",
1901 + "hookified": "^1.15.0"
1902 + }
1903 + },
1904 + "node_modules/flatted": {
1905 + "version": "3.4.4",
1906 + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz",
1907 + "integrity": "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==",
1908 + "dev": true,
1909 + "license": "ISC"
1910 + },
1911 + "node_modules/fsevents": {
1912 + "version": "2.3.3",
1913 + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
1914 + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
1915 + "dev": true,
1916 + "hasInstallScript": true,
1917 + "license": "MIT",
1918 + "optional": true,
1919 + "os": [
1920 + "darwin"
1921 + ],
1922 + "engines": {
1923 + "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
1924 + }
1925 + },
1926 + "node_modules/glob-parent": {
1927 + "version": "6.0.2",
1928 + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz",
1929 + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==",
1930 + "dev": true,
1931 + "license": "ISC",
1932 + "dependencies": {
1933 + "is-glob": "^4.0.3"
1934 + },
1935 + "engines": {
1936 + "node": ">=10.13.0"
1937 + }
1938 + },
1939 + "node_modules/globals": {
1940 + "version": "16.5.0",
1941 + "resolved": "https://registry.npmjs.org/globals/-/globals-16.5.0.tgz",
1942 + "integrity": "sha512-c/c15i26VrJ4IRt5Z89DnIzCGDn9EcebibhAOjw5ibqEHsE1wLUgkPn9RDmNcUKyU87GeaL633nyJ+pplFR2ZQ==",
1943 + "dev": true,
1944 + "license": "MIT",
1945 + "engines": {
1946 + "node": ">=18"
1947 + },
1948 + "funding": {
1949 + "url": "https://github.com/sponsors/sindresorhus"
1950 + }
1951 + },
1952 + "node_modules/hashery": {
1953 + "version": "1.5.1",
1954 + "resolved": "https://registry.npmjs.org/hashery/-/hashery-1.5.1.tgz",
1955 + "integrity": "sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ==",
1956 + "dev": true,
1957 + "license": "MIT",
1958 + "dependencies": {
1959 + "hookified": "^1.15.0"
1960 + },
1961 + "engines": {
1962 + "node": ">=20"
1963 + }
1964 + },
1965 + "node_modules/hookified": {
1966 + "version": "1.15.1",
1967 + "resolved": "https://registry.npmjs.org/hookified/-/hookified-1.15.1.tgz",
1968 + "integrity": "sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg==",
1969 + "dev": true,
1970 + "license": "MIT"
1971 + },
1972 + "node_modules/ignore": {
1973 + "version": "5.3.2",
1974 + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
1975 + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
1976 + "dev": true,
1977 + "license": "MIT",
1978 + "engines": {
1979 + "node": ">= 4"
1980 + }
1981 + },
1982 + "node_modules/imurmurhash": {
1983 + "version": "0.1.4",
1984 + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",
1985 + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==",
1986 + "dev": true,
1987 + "license": "MIT",
1988 + "engines": {
1989 + "node": ">=0.8.19"
1990 + }
1991 + },
1992 + "node_modules/is-extglob": {
1993 + "version": "2.1.1",
1994 + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
1995 + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
1996 + "dev": true,
1997 + "license": "MIT",
1998 + "engines": {
1999 + "node": ">=0.10.0"
2000 + }
2001 + },
2002 + "node_modules/is-glob": {
2003 + "version": "4.0.3",
2004 + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
2005 + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
2006 + "dev": true,
2007 + "license": "MIT",
2008 + "dependencies": {
2009 + "is-extglob": "^2.1.1"
2010 + },
2011 + "engines": {
2012 + "node": ">=0.10.0"
2013 + }
2014 + },
2015 + "node_modules/isexe": {
2016 + "version": "2.0.0",
2017 + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
2018 + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
2019 + "dev": true,
2020 + "license": "ISC"
2021 + },
2022 + "node_modules/json-schema-traverse": {
2023 + "version": "0.4.1",
2024 + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
2025 + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",
2026 + "dev": true,
2027 + "license": "MIT"
2028 + },
2029 + "node_modules/json-stable-stringify-without-jsonify": {
2030 + "version": "1.0.1",
2031 + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz",
2032 + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==",
2033 + "dev": true,
2034 + "license": "MIT"
2035 + },
2036 + "node_modules/keyv": {
2037 + "version": "5.6.0",
2038 + "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz",
2039 + "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==",
2040 + "dev": true,
2041 + "license": "MIT",
2042 + "dependencies": {
2043 + "@keyv/serialize": "^1.1.1"
2044 + }
2045 + },
2046 + "node_modules/kleur": {
2047 + "version": "4.1.5",
2048 + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz",
2049 + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==",
2050 + "dev": true,
2051 + "license": "MIT",
2052 + "engines": {
2053 + "node": ">=6"
2054 + }
2055 + },
2056 + "node_modules/levn": {
2057 + "version": "0.4.1",
2058 + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz",
2059 + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==",
2060 + "dev": true,
2061 + "license": "MIT",
2062 + "dependencies": {
2063 + "prelude-ls": "^1.2.1",
2064 + "type-check": "~0.4.0"
2065 + },
2066 + "engines": {
2067 + "node": ">= 0.8.0"
2068 + }
2069 + },
2070 + "node_modules/locate-path": {
2071 + "version": "6.0.0",
2072 + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",
2073 + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==",
2074 + "dev": true,
2075 + "license": "MIT",
2076 + "dependencies": {
2077 + "p-locate": "^5.0.0"
2078 + },
2079 + "engines": {
2080 + "node": ">=10"
2081 + },
2082 + "funding": {
2083 + "url": "https://github.com/sponsors/sindresorhus"
2084 + }
2085 + },
2086 + "node_modules/miniflare": {
2087 + "version": "5.20261019.2-beta",
2088 + "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261019.2-beta.tgz",
2089 + "integrity": "sha512-QNgCA/axizZ7kv7RV3nwbRoz+w4watBlwIsyXjwgYHw4eSw5BrR1F2152s3Kz+Bzy/YxjKFHrZl3LzBRbPgYoQ==",
2090 + "dev": true,
2091 + "license": "MIT",
2092 + "dependencies": {
2093 + "@cspotcode/source-map-support": "0.8.1",
2094 + "sharp": "0.35.5",
2095 + "undici": "7.29.1",
2096 + "workerd": "1.20261019.1",
2097 + "ws": "8.21.0",
2098 + "youch": "4.1.0-beta.10"
2099 + },
2100 + "engines": {
2101 + "node": ">=22.0.0"
2102 + }
2103 + },
2104 + "node_modules/minimatch": {
2105 + "version": "10.2.6",
2106 + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz",
2107 + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==",
2108 + "dev": true,
2109 + "license": "BlueOak-1.0.0",
2110 + "dependencies": {
2111 + "brace-expansion": "^5.0.8"
2112 + },
2113 + "engines": {
2114 + "node": "18 || 20 || >=22"
2115 + },
2116 + "funding": {
2117 + "url": "https://github.com/sponsors/isaacs"
2118 + }
2119 + },
2120 + "node_modules/ms": {
2121 + "version": "2.1.3",
2122 + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
2123 + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
2124 + "dev": true,
2125 + "license": "MIT"
2126 + },
2127 + "node_modules/natural-compare": {
2128 + "version": "1.4.0",
2129 + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",
2130 + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==",
2131 + "dev": true,
2132 + "license": "MIT"
2133 + },
2134 + "node_modules/optionator": {
2135 + "version": "0.9.4",
2136 + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
2137 + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==",
2138 + "dev": true,
2139 + "license": "MIT",
2140 + "dependencies": {
2141 + "deep-is": "^0.1.3",
2142 + "fast-levenshtein": "^2.0.6",
2143 + "levn": "^0.4.1",
2144 + "prelude-ls": "^1.2.1",
2145 + "type-check": "^0.4.0",
2146 + "word-wrap": "^1.2.5"
2147 + },
2148 + "engines": {
2149 + "node": ">= 0.8.0"
2150 + }
2151 + },
2152 + "node_modules/p-limit": {
2153 + "version": "3.1.0",
2154 + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",
2155 + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",
2156 + "dev": true,
2157 + "license": "MIT",
2158 + "dependencies": {
2159 + "yocto-queue": "^0.1.0"
2160 + },
2161 + "engines": {
2162 + "node": ">=10"
2163 + },
2164 + "funding": {
2165 + "url": "https://github.com/sponsors/sindresorhus"
2166 + }
2167 + },
2168 + "node_modules/p-locate": {
2169 + "version": "5.0.0",
2170 + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz",
2171 + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==",
2172 + "dev": true,
2173 + "license": "MIT",
2174 + "dependencies": {
2175 + "p-limit": "^3.0.2"
2176 + },
2177 + "engines": {
2178 + "node": ">=10"
2179 + },
2180 + "funding": {
2181 + "url": "https://github.com/sponsors/sindresorhus"
2182 + }
2183 + },
2184 + "node_modules/path-exists": {
2185 + "version": "4.0.0",
2186 + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
2187 + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
2188 + "dev": true,
2189 + "license": "MIT",
2190 + "engines": {
2191 + "node": ">=8"
2192 + }
2193 + },
2194 + "node_modules/path-key": {
2195 + "version": "3.1.1",
2196 + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
2197 + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
2198 + "dev": true,
2199 + "license": "MIT",
2200 + "engines": {
2201 + "node": ">=8"
2202 + }
2203 + },
2204 + "node_modules/path-to-regexp": {
2205 + "version": "6.3.0",
2206 + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.3.0.tgz",
2207 + "integrity": "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==",
2208 + "dev": true,
2209 + "license": "MIT"
2210 + },
2211 + "node_modules/pathe": {
2212 + "version": "2.0.3",
2213 + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
2214 + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
2215 + "dev": true,
2216 + "license": "MIT"
2217 + },
2218 + "node_modules/prelude-ls": {
2219 + "version": "1.2.1",
2220 + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
2221 + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==",
2222 + "dev": true,
2223 + "license": "MIT",
2224 + "engines": {
2225 + "node": ">= 0.8.0"
2226 + }
2227 + },
2228 + "node_modules/prettier": {
2229 + "version": "3.6.2",
2230 + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.6.2.tgz",
2231 + "integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==",
2232 + "dev": true,
2233 + "license": "MIT",
2234 + "bin": {
2235 + "prettier": "bin/prettier.cjs"
2236 + },
2237 + "engines": {
2238 + "node": ">=14"
2239 + },
2240 + "funding": {
2241 + "url": "https://github.com/prettier/prettier?sponsor=1"
2242 + }
2243 + },
2244 + "node_modules/punycode": {
2245 + "version": "2.3.1",
2246 + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
2247 + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
2248 + "dev": true,
2249 + "license": "MIT",
2250 + "engines": {
2251 + "node": ">=6"
2252 + }
2253 + },
2254 + "node_modules/qified": {
2255 + "version": "0.10.1",
2256 + "resolved": "https://registry.npmjs.org/qified/-/qified-0.10.1.tgz",
2257 + "integrity": "sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA==",
2258 + "dev": true,
2259 + "license": "MIT",
2260 + "dependencies": {
2261 + "hookified": "^2.1.1"
2262 + },
2263 + "engines": {
2264 + "node": ">=20"
2265 + }
2266 + },
2267 + "node_modules/qified/node_modules/hookified": {
2268 + "version": "2.2.0",
2269 + "resolved": "https://registry.npmjs.org/hookified/-/hookified-2.2.0.tgz",
2270 + "integrity": "sha512-p/LgFzRN5FeoD3DLS6bkUapeye6E4SI6yJs6KetENd18S+FBthqYq2amJUWpt5z0EQwwHemidjY5OqJGEKm5uA==",
2271 + "dev": true,
2272 + "license": "MIT"
2273 + },
2274 + "node_modules/semver": {
2275 + "version": "7.8.5",
2276 + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
2277 + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
2278 + "dev": true,
2279 + "license": "ISC",
2280 + "bin": {
2281 + "semver": "bin/semver.js"
2282 + },
2283 + "engines": {
2284 + "node": ">=10"
2285 + }
2286 + },
2287 + "node_modules/sharp": {
2288 + "version": "0.35.5",
2289 + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz",
2290 + "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==",
2291 + "dev": true,
2292 + "license": "Apache-2.0",
2293 + "dependencies": {
2294 + "@img/colour": "^1.1.0",
2295 + "detect-libc": "^2.1.2",
2296 + "semver": "^7.8.5"
2297 + },
2298 + "engines": {
2299 + "node": ">=20.9.0"
2300 + },
2301 + "funding": {
2302 + "url": "https://opencollective.com/libvips"
2303 + },
2304 + "optionalDependencies": {
2305 + "@img/sharp-darwin-arm64": "0.35.5",
2306 + "@img/sharp-darwin-x64": "0.35.5",
2307 + "@img/sharp-freebsd-wasm32": "0.35.5",
2308 + "@img/sharp-libvips-darwin-arm64": "1.3.4",
2309 + "@img/sharp-libvips-darwin-x64": "1.3.4",
2310 + "@img/sharp-libvips-linux-arm": "1.3.4",
2311 + "@img/sharp-libvips-linux-arm64": "1.3.4",
2312 + "@img/sharp-libvips-linux-ppc64": "1.3.4",
2313 + "@img/sharp-libvips-linux-riscv64": "1.3.4",
2314 + "@img/sharp-libvips-linux-s390x": "1.3.4",
2315 + "@img/sharp-libvips-linux-x64": "1.3.4",
2316 + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4",
2317 + "@img/sharp-libvips-linuxmusl-x64": "1.3.4",
2318 + "@img/sharp-linux-arm": "0.35.5",
2319 + "@img/sharp-linux-arm64": "0.35.5",
2320 + "@img/sharp-linux-ppc64": "0.35.5",
2321 + "@img/sharp-linux-riscv64": "0.35.5",
2322 + "@img/sharp-linux-s390x": "0.35.5",
2323 + "@img/sharp-linux-x64": "0.35.5",
2324 + "@img/sharp-linuxmusl-arm64": "0.35.5",
2325 + "@img/sharp-linuxmusl-x64": "0.35.5",
2326 + "@img/sharp-webcontainers-wasm32": "0.35.5",
2327 + "@img/sharp-win32-arm64": "0.35.5",
2328 + "@img/sharp-win32-ia32": "0.35.5",
2329 + "@img/sharp-win32-x64": "0.35.5"
2330 + },
2331 + "peerDependenciesMeta": {
2332 + "@types/node": {
2333 + "optional": true
2334 + }
2335 + }
2336 + },
2337 + "node_modules/shebang-command": {
2338 + "version": "2.0.0",
2339 + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
2340 + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
2341 + "dev": true,
2342 + "license": "MIT",
2343 + "dependencies": {
2344 + "shebang-regex": "^3.0.0"
2345 + },
2346 + "engines": {
2347 + "node": ">=8"
2348 + }
2349 + },
2350 + "node_modules/shebang-regex": {
2351 + "version": "3.0.0",
2352 + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
2353 + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
2354 + "dev": true,
2355 + "license": "MIT",
2356 + "engines": {
2357 + "node": ">=8"
2358 + }
2359 + },
2360 + "node_modules/tslib": {
2361 + "version": "2.8.1",
2362 + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
2363 + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
2364 + "dev": true,
2365 + "license": "0BSD",
2366 + "optional": true
2367 + },
2368 + "node_modules/type-check": {
2369 + "version": "0.4.0",
2370 + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
2371 + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==",
2372 + "dev": true,
2373 + "license": "MIT",
2374 + "dependencies": {
2375 + "prelude-ls": "^1.2.1"
2376 + },
2377 + "engines": {
2378 + "node": ">= 0.8.0"
2379 + }
2380 + },
2381 + "node_modules/undici": {
2382 + "version": "7.29.1",
2383 + "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.1.tgz",
2384 + "integrity": "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q==",
2385 + "dev": true,
2386 + "license": "MIT",
2387 + "engines": {
2388 + "node": ">=20.18.1"
2389 + }
2390 + },
2391 + "node_modules/unenv": {
2392 + "version": "2.0.0-rc.24",
2393 + "resolved": "https://registry.npmjs.org/unenv/-/unenv-2.0.0-rc.24.tgz",
2394 + "integrity": "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==",
2395 + "dev": true,
2396 + "license": "MIT",
2397 + "dependencies": {
2398 + "pathe": "^2.0.3"
2399 + }
2400 + },
2401 + "node_modules/uri-js": {
2402 + "version": "4.4.1",
2403 + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
2404 + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
2405 + "dev": true,
2406 + "license": "BSD-2-Clause",
2407 + "dependencies": {
2408 + "punycode": "^2.1.0"
2409 + }
2410 + },
2411 + "node_modules/which": {
2412 + "version": "2.0.2",
2413 + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
2414 + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
2415 + "dev": true,
2416 + "license": "ISC",
2417 + "dependencies": {
2418 + "isexe": "^2.0.0"
2419 + },
2420 + "bin": {
2421 + "node-which": "bin/node-which"
2422 + },
2423 + "engines": {
2424 + "node": ">= 8"
2425 + }
2426 + },
2427 + "node_modules/word-wrap": {
2428 + "version": "1.2.5",
2429 + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",
2430 + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==",
2431 + "dev": true,
2432 + "license": "MIT",
2433 + "engines": {
2434 + "node": ">=0.10.0"
2435 + }
2436 + },
2437 + "node_modules/workerd": {
2438 + "version": "1.20261019.1",
2439 + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20261019.1.tgz",
2440 + "integrity": "sha512-UUYRUq/7DmeCl11YriNbcVbjUZVLtt8uuCXFu+nz77hGFf8d4DEVXoCYtnA+MlBatE4+wxoj47DVqzK3xGBAiw==",
2441 + "dev": true,
2442 + "hasInstallScript": true,
2443 + "license": "Apache-2.0",
2444 + "bin": {
2445 + "workerd": "bin/workerd"
2446 + },
2447 + "engines": {
2448 + "node": ">=16"
2449 + },
2450 + "optionalDependencies": {
2451 + "@cloudflare/workerd-darwin-64": "1.20261019.1",
2452 + "@cloudflare/workerd-darwin-arm64": "1.20261019.1",
2453 + "@cloudflare/workerd-linux-64": "1.20261019.1",
2454 + "@cloudflare/workerd-linux-arm64": "1.20261019.1",
2455 + "@cloudflare/workerd-windows-64": "1.20261019.1"
2456 + }
2457 + },
2458 + "node_modules/wrangler": {
2459 + "version": "4.152.0",
2460 + "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.152.0.tgz",
2461 + "integrity": "sha512-lmXTF1sCDEqBaEMpreGczvg/x3AIh1d/qxc4BN7utQ4jEDwdA4YG0L6kr3ev0TtVLHRb6QLySNAOAunwn+dHeA==",
2462 + "dev": true,
2463 + "license": "MIT OR Apache-2.0",
2464 + "dependencies": {
2465 + "@cloudflare/kv-asset-handler": "0.5.0",
2466 + "@cloudflare/unenv-preset": "2.16.2",
2467 + "blake3-wasm": "2.1.5",
2468 + "esbuild": "0.28.2",
2469 + "miniflare": "5.20261019.2-beta",
2470 + "path-to-regexp": "6.3.0",
2471 + "unenv": "2.0.0-rc.24",
2472 + "workerd": "1.20261019.1"
2473 + },
2474 + "bin": {
2475 + "cf-wrangler": "bin/cf-wrangler.js",
2476 + "wrangler": "bin/wrangler.js",
2477 + "wrangler2": "bin/wrangler.js"
2478 + },
2479 + "engines": {
2480 + "node": ">=22.0.0"
2481 + },
2482 + "optionalDependencies": {
2483 + "fsevents": "2.3.3"
2484 + },
2485 + "peerDependencies": {
2486 + "@cloudflare/workers-types": "^5.20261019.1"
2487 + },
2488 + "peerDependenciesMeta": {
2489 + "@cloudflare/workers-types": {
2490 + "optional": true
2491 + }
2492 + }
2493 + },
2494 + "node_modules/ws": {
2495 + "version": "8.21.0",
2496 + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
2497 + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
2498 + "dev": true,
2499 + "license": "MIT",
2500 + "engines": {
2501 + "node": ">=10.0.0"
2502 + },
2503 + "peerDependencies": {
2504 + "bufferutil": "^4.0.1",
2505 + "utf-8-validate": ">=5.0.2"
2506 + },
2507 + "peerDependenciesMeta": {
2508 + "bufferutil": {
2509 + "optional": true
2510 + },
2511 + "utf-8-validate": {
2512 + "optional": true
2513 + }
2514 + }
2515 + },
2516 + "node_modules/yocto-queue": {
2517 + "version": "0.1.0",
2518 + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
2519 + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",
2520 + "dev": true,
2521 + "license": "MIT",
2522 + "engines": {
2523 + "node": ">=10"
2524 + },
2525 + "funding": {
2526 + "url": "https://github.com/sponsors/sindresorhus"
2527 + }
2528 + },
2529 + "node_modules/youch": {
2530 + "version": "4.1.0-beta.10",
2531 + "resolved": "https://registry.npmjs.org/youch/-/youch-4.1.0-beta.10.tgz",
2532 + "integrity": "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==",
2533 + "dev": true,
2534 + "license": "MIT",
2535 + "dependencies": {
2536 + "@poppinss/colors": "^4.1.5",
2537 + "@poppinss/dumper": "^0.6.4",
2538 + "@speed-highlight/core": "^1.2.7",
2539 + "cookie": "^1.0.2",
2540 + "youch-core": "^0.3.3"
2541 + }
2542 + },
2543 + "node_modules/youch-core": {
2544 + "version": "0.3.3",
2545 + "resolved": "https://registry.npmjs.org/youch-core/-/youch-core-0.3.3.tgz",
2546 + "integrity": "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==",
2547 + "dev": true,
2548 + "license": "MIT",
2549 + "dependencies": {
2550 + "@poppinss/exception": "^1.2.2",
2551 + "error-stack-parser-es": "^1.0.5"
2552 + }
2553 + }
2554 + }
2555 +}
package.json
+13 -2
@@ -6,7 +6,11 @@
6 "type": "module",
7 "scripts": {
8 "test": "node --test test/*.test.js",
9 - "start": "npx wrangler dev"
9 + "start": "npx wrangler dev",
10 + "lint": "eslint src test eslint.config.js",
11 + "format": "prettier --write \"src/**/*.js\" \"test/**/*.js\" \"*.config.js\" \"package*.json\" \"wrangler.jsonc\" \".github/workflows/*.yml\" \".prettierrc.json\"",
12 + "format:check": "prettier --check \"src/**/*.js\" \"test/**/*.js\" \"*.config.js\" \"package*.json\" \"wrangler.jsonc\" \".github/workflows/*.yml\" \".prettierrc.json\"",
13 + "build:check": "wrangler deploy --dry-run --outdir .wrangler/build-check"
14 },
15 "keywords": [
16 "telegram-bot",
@@ -15,5 +19,12 @@
19 "devops"
20 ],
21 "author": "Davood Mehraban",
18 - "license": "MIT"
22 + "license": "MIT",
23 + "devDependencies": {
24 + "@eslint/js": "10.0.1",
25 + "eslint": "10.13.0",
26 + "globals": "16.5.0",
27 + "prettier": "3.6.2",
28 + "wrangler": "4.152.0"
29 + }
30 }
src/bot-legacy.js
+394 -95
@@ -9,7 +9,10 @@ import { DurableWorkspaceStoreClient } from './core/workspace-store.js';
9 import { WORKSPACE_EDITOR_LIMITS } from './core/workspace-policy.js';
10 import { AuditLogger } from './core/audit.js';
11 import { PluginRouter } from './core/router.js';
12 -import { buildApprovedActionFailedView, buildCallbackFailureView } from './core/callback-failure-view.js';
12 +import {
13 + buildApprovedActionFailedView,
14 + buildCallbackFailureView
15 +} from './core/callback-failure-view.js';
16 import { createGitHubPlugin } from './plugins/github/plugin.js';
17 import { CloudflareService } from './plugins/cloudflare/service.js';
18 import { createCloudflarePlugin } from './plugins/cloudflare/plugin.js';
@@ -22,11 +25,12 @@ const QUICK_MENU = Object.freeze({
25 '🔧 ابزارها': 'tools',
26 '🔐 امنیت': 'security'
27 });
25 -const escapeHtml = value => String(value ?? '')
26 - .replaceAll('&', '&amp;')
27 - .replaceAll('<', '&lt;')
28 - .replaceAll('>', '&gt;')
29 - .replaceAll('"', '&quot;');
28 +const escapeHtml = (value) =>
29 + String(value ?? '')
30 + .replaceAll('&', '&amp;')
31 + .replaceAll('<', '&lt;')
32 + .replaceAll('>', '&gt;')
33 + .replaceAll('"', '&quot;');
34
35 function persistentQuickMenuMarkup() {
36 return {
@@ -51,27 +55,33 @@ function focusedCodeInputMarkup() {
55
56 function approvalSourceCallback(payload = {}) {
57 const repoId = payload.input?.repoId;
54 - if (!Number.isSafeInteger(Number(repoId))) throw new Error('Approval input is invalid');
58 + if (!Number.isSafeInteger(Number(repoId)))
59 + throw new Error('Approval input is invalid');
60
61 if (payload.actionId === 'github.workspace.commit_branch') {
62 const intentId = String(payload.input?.intentId || '');
58 - if (!INTENT_ID_PATTERN.test(intentId)) throw new Error('Approval input is invalid');
63 + if (!INTENT_ID_PATTERN.test(intentId))
64 + throw new Error('Approval input is invalid');
65 return `wscommit:${repoId}:${intentId}`;
66 }
67
68 const runId = payload.input?.runId;
63 - if (!Number.isSafeInteger(Number(runId))) throw new Error('Approval input is invalid');
64 - if (payload.actionId === 'github.workflow.dispatch') return `dispatchwf:${repoId}:${runId}`;
65 - if (payload.actionId === 'github.workflow.job.rerun') return `rerunjob:${repoId}:${runId}`;
66 - if (payload.actionId === 'github.workflow.run.rerun_failed') return `rerun:${repoId}:${runId}`;
67 - if (payload.actionId === 'github.workflow.run.cancel') return `cancelrun:${repoId}:${runId}`;
69 + if (!Number.isSafeInteger(Number(runId)))
70 + throw new Error('Approval input is invalid');
71 + if (payload.actionId === 'github.workflow.dispatch')
72 + return `dispatchwf:${repoId}:${runId}`;
73 + if (payload.actionId === 'github.workflow.job.rerun')
74 + return `rerunjob:${repoId}:${runId}`;
75 + if (payload.actionId === 'github.workflow.run.rerun_failed')
76 + return `rerun:${repoId}:${runId}`;
77 + if (payload.actionId === 'github.workflow.run.cancel')
78 + return `cancelrun:${repoId}:${runId}`;
79 throw new Error('Approval action is not supported');
80 }
81
82 function approvalView({ label, token, cancelCallback = 'menu:main' }) {
83 return {
73 - text:
74 -`⚠️ <b>تأیید عملیات لازم است</b>
84 + text: `⚠️ <b>تأیید عملیات لازم است</b>
85 ➖➖➖➖➖➖➖➖➖➖
86 عملیات: <b>${label}</b>
87 این عملیات روی GitHub تغییر ایجاد می‌کند و فقط پس از تأیید شما اجرا می‌شود.
@@ -90,24 +100,29 @@ function approvalRejectedView(message, error) {
100 const reason = String(error?.message || 'Approval rejected');
101 const expired = /expired/i.test(reason);
102 const used = /already used|replay/i.test(reason);
93 - const fallback = message?.reply_markup?.inline_keyboard
94 - ?.flat()
95 - .map(button => String(button?.callback_data || ''))
96 - .find(callback => callback && !callback.startsWith('approve:')) || 'menu:main';
103 + const fallback =
104 + message?.reply_markup?.inline_keyboard
105 + ?.flat()
106 + .map((button) => String(button?.callback_data || ''))
107 + .find((callback) => callback && !callback.startsWith('approve:')) ||
108 + 'menu:main';
109
110 let detail = 'این تأیید معتبر نیست و هیچ تغییری اجرا نشد.';
111 if (expired) detail = 'مهلت این تأیید تمام شده است و هیچ تغییری اجرا نشد.';
112 if (used) detail = 'این تأیید قبلاً استفاده شده است و دوباره اجرا نمی‌شود.';
101 - const backText = fallback.startsWith('run:') ? '↩️ بازگشت به Run' : '↩️ بازگشت';
113 + const backText = fallback.startsWith('run:')
114 + ? '↩️ بازگشت به Run'
115 + : '↩️ بازگشت';
116
117 return {
104 - text:
105 -`⚠️ <b>عملیات اجرا نشد</b>
118 + text: `⚠️ <b>عملیات اجرا نشد</b>
119 ➖➖➖➖➖➖➖➖➖➖
120 ${detail}
121
122 برای ادامه برگردید و در صورت نیاز یک تأیید تازه ایجاد کنید.`,
110 - reply_markup: { inline_keyboard: [[{ text: backText, callback_data: fallback }]] }
123 + reply_markup: {
124 + inline_keyboard: [[{ text: backText, callback_data: fallback }]]
125 + }
126 };
127 }
128
@@ -115,10 +130,17 @@ export class NexaDevBot {
130 constructor(env = {}) {
131 this.env = env;
132 this.telegram = new TelegramClient(env.TELEGRAM_BOT_TOKEN || '');
118 - this.github = new GitHubService(env.GITHUB_TOKEN || '', env.GITHUB_OWNER || 'davoodmehraban89');
133 + this.github = new GitHubService(
134 + env.GITHUB_TOKEN || '',
135 + env.GITHUB_OWNER || 'davoodmehraban89'
136 + );
137 this.menu = new MenuManager(this.github);
120 - this.replayStore = new DurableApprovalReplayStore({ namespace: env.APPROVAL_REPLAY_GUARD });
121 - this.workspaceStore = new DurableWorkspaceStoreClient({ namespace: env.WORKSPACE_STORE });
138 + this.replayStore = new DurableApprovalReplayStore({
139 + namespace: env.APPROVAL_REPLAY_GUARD
140 + });
141 + this.workspaceStore = new DurableWorkspaceStoreClient({
142 + namespace: env.WORKSPACE_STORE
143 + });
144 this.approvals = new ApprovalService({
145 secret: env.APPROVAL_SIGNING_SECRET || env.TELEGRAM_WEBHOOK_SECRET || '',
146 replayStore: this.replayStore
@@ -126,25 +148,45 @@ export class NexaDevBot {
148 this.githubPlugin = createGitHubPlugin({
149 github: this.github,
150 menu: this.menu,
129 - workspaces: this.workspaceStore.isConfigured() ? this.workspaceStore : null
151 + workspaces: this.workspaceStore.isConfigured()
152 + ? this.workspaceStore
153 + : null
154 });
155 this.cloudflare = new CloudflareService({
156 token: env.CLOUDFLARE_API_TOKEN || '',
157 accountId: env.CLOUDFLARE_ACCOUNT_ID || '',
158 workerName: env.CLOUDFLARE_WORKER_NAME || 'nexa-dev-bot'
159 });
136 - this.cloudflarePlugin = createCloudflarePlugin({ cloudflare: this.cloudflare, github: this.github });
137 - this.registry = new PluginRegistry([this.githubPlugin, this.cloudflarePlugin]);
160 + this.cloudflarePlugin = createCloudflarePlugin({
161 + cloudflare: this.cloudflare,
162 + github: this.github
163 + });
164 + this.registry = new PluginRegistry([
165 + this.githubPlugin,
166 + this.cloudflarePlugin
167 + ]);
168 this.policy = new ActionPolicy();
169 this.audit = new AuditLogger({
140 - secrets: [env.TELEGRAM_BOT_TOKEN, env.TELEGRAM_WEBHOOK_SECRET, env.GITHUB_TOKEN, env.CLOUDFLARE_API_TOKEN, env.APPROVAL_SIGNING_SECRET, env.DESTRUCTIVE_TOTP_SECRET]
170 + secrets: [
171 + env.TELEGRAM_BOT_TOKEN,
172 + env.TELEGRAM_WEBHOOK_SECRET,
173 + env.GITHUB_TOKEN,
174 + env.CLOUDFLARE_API_TOKEN,
175 + env.APPROVAL_SIGNING_SECRET,
176 + env.DESTRUCTIVE_TOTP_SECRET
177 + ]
178 + });
179 + this.router = new PluginRouter({
180 + registry: this.registry,
181 + policy: this.policy,
182 + audit: this.audit
183 });
142 - this.router = new PluginRouter({ registry: this.registry, policy: this.policy, audit: this.audit });
184 }
185
186 async handleUpdate(update) {
187 if (!update) return { ok: false, error: 'Empty update' };
147 - if (update.callback_query) return this.handleCallbackQuery(update.callback_query);
188 + if (update.callback_query)
189 + return this.handleCallbackQuery(update.callback_query);
190 if (update.message) return this.handleMessage(update.message);
191 return { ok: true, ignored: true };
192 }
@@ -158,24 +200,62 @@ export class NexaDevBot {
200 const ownerId = query.from?.id;
201
202 let callbackAnswered = true;
161 - try { await this.telegram.answerCallbackQuery(callbackId); } catch { callbackAnswered = false; }
162 - if (!chatId || !messageId) return { ok: false, error: 'Missing message context for callback', callbackAnswered };
203 + try {
204 + await this.telegram.answerCallbackQuery(callbackId);
205 + } catch {
206 + callbackAnswered = false;
207 + }
208 + if (!chatId || !messageId)
209 + return {
210 + ok: false,
211 + error: 'Missing message context for callback',
212 + callbackAnswered
213 + };
214
215 try {
216 if (data.startsWith('approve:')) {
166 - if (ownerId === undefined || ownerId === null) throw new Error('Approval owner is required');
217 + if (ownerId === undefined || ownerId === null)
218 + throw new Error('Approval owner is required');
219 const token = data.slice('approve:'.length);
220 let payload;
221 try {
170 - payload = await this.approvals.consume(token, { ownerId: String(ownerId), pluginId: 'github', risk: 'WRITE' });
222 + payload = await this.approvals.consume(token, {
223 + ownerId: String(ownerId),
224 + pluginId: 'github',
225 + risk: 'WRITE'
226 + });
227 } catch (error) {
172 - this.audit.log({ event: 'approval_rejected', pluginId: 'github', risk: 'WRITE', outcome: 'rejected', error: error?.message || 'Approval rejected' });
228 + this.audit.log({
229 + event: 'approval_rejected',
230 + pluginId: 'github',
231 + risk: 'WRITE',
232 + outcome: 'rejected',
233 + error: error?.message || 'Approval rejected'
234 + });
235 const view = approvalRejectedView(message, error);
174 - const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
175 - return { ok: false, approvalRejected: true, error: error?.message || 'Approval rejected', callbackAnswered, edited: true, res };
236 + const res = await this.telegram.editMessageText(
237 + chatId,
238 + messageId,
239 + view.text,
240 + view.reply_markup
241 + );
242 + return {
243 + ok: false,
244 + approvalRejected: true,
245 + error: error?.message || 'Approval rejected',
246 + callbackAnswered,
247 + edited: true,
248 + res
249 + };
250 }
251
178 - this.audit.log({ event: 'approval_verified', pluginId: payload.pluginId, actionId: payload.actionId, risk: payload.risk, outcome: 'verified' });
252 + this.audit.log({
253 + event: 'approval_verified',
254 + pluginId: payload.pluginId,
255 + actionId: payload.actionId,
256 + risk: payload.risk,
257 + outcome: 'verified'
258 + });
259 const sourceCallback = approvalSourceCallback(payload);
260 let routed;
261 try {
@@ -184,7 +264,8 @@ export class NexaDevBot {
264 ownerId: String(ownerId),
265 approved: true
266 });
187 - if (!routed || routed.requiresApproval || routed.denied) throw new Error('Approved action could not be dispatched');
267 + if (!routed || routed.requiresApproval || routed.denied)
268 + throw new Error('Approved action could not be dispatched');
269 } catch (error) {
270 const view = await buildApprovedActionFailedView({
271 payload,
@@ -192,37 +273,76 @@ export class NexaDevBot {
273 ownerId,
274 workspaces: this.workspaceStore
275 });
195 - const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
196 - return { ok: false, approved: true, providerError: true, actionId: payload.actionId, error: error?.message || 'GitHub operation failed', callbackAnswered, edited: true, res };
276 + const res = await this.telegram.editMessageText(
277 + chatId,
278 + messageId,
279 + view.text,
280 + view.reply_markup
281 + );
282 + return {
283 + ok: false,
284 + approved: true,
285 + providerError: true,
286 + actionId: payload.actionId,
287 + error: error?.message || 'GitHub operation failed',
288 + callbackAnswered,
289 + edited: true,
290 + res
291 + };
292 }
293
199 - const res = await this.telegram.editMessageText(chatId, messageId, routed.text, routed.reply_markup);
200 - return { ok: true, approved: true, actionId: payload.actionId, callbackAnswered, edited: true, res };
294 + const res = await this.telegram.editMessageText(
295 + chatId,
296 + messageId,
297 + routed.text,
298 + routed.reply_markup
299 + );
300 + return {
301 + ok: true,
302 + approved: true,
303 + actionId: payload.actionId,
304 + callbackAnswered,
305 + edited: true,
306 + res
307 + };
308 }
309
310 const routed = await this.router.dispatchCallback(data, {
311 isOwner: true,
205 - ownerId: ownerId === undefined || ownerId === null ? '' : String(ownerId)
312 + ownerId:
313 + ownerId === undefined || ownerId === null ? '' : String(ownerId)
314 });
315 if (!routed) {
316 const view = await this.menu.renderByCallback(data);
209 - const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
317 + const res = await this.telegram.editMessageText(
318 + chatId,
319 + messageId,
320 + view.text,
321 + view.reply_markup
322 + );
323 return { ok: true, edited: true, callbackAnswered, res };
324 }
325 if (routed?.requiresApproval) {
326 const approval = routed.approval;
327 const repoId = approval?.input?.repoId;
215 - if (!approval || !Number.isSafeInteger(Number(repoId))) throw new Error('Approval metadata is missing');
216 - const workspaceApproval = routed.actionId === 'github.workspace.commit_branch';
328 + if (!approval || !Number.isSafeInteger(Number(repoId)))
329 + throw new Error('Approval metadata is missing');
330 + const workspaceApproval =
331 + routed.actionId === 'github.workspace.commit_branch';
332 const runId = approval?.input?.runId;
333 const intentId = String(approval?.input?.intentId || '');
334 if (workspaceApproval) {
220 - if (!INTENT_ID_PATTERN.test(intentId)) throw new Error('Approval metadata is missing');
335 + if (!INTENT_ID_PATTERN.test(intentId))
336 + throw new Error('Approval metadata is missing');
337 } else if (!Number.isSafeInteger(Number(runId))) {
338 throw new Error('Approval metadata is missing');
339 }
224 - if (ownerId === undefined || ownerId === null) throw new Error('Approval owner is required');
225 - if (!this.approvals.isReplayProtected()) throw new Error('Durable approval replay protection is not configured');
340 + if (ownerId === undefined || ownerId === null)
341 + throw new Error('Approval owner is required');
342 + if (!this.approvals.isReplayProtected())
343 + throw new Error(
344 + 'Durable approval replay protection is not configured'
345 + );
346
347 const token = await this.approvals.issue({
348 pluginId: routed.pluginId,
@@ -231,27 +351,87 @@ export class NexaDevBot {
351 ownerId: String(ownerId),
352 input: approval.input
353 });
234 - this.audit.log({ event: 'approval_issued', pluginId: routed.pluginId, actionId: routed.actionId, risk: routed.risk, outcome: 'pending' });
235 - const cancelCallback = approval.cancelCallback || (Number.isSafeInteger(Number(runId)) ? `run:${repoId}:${runId}` : `repo:${repoId}`);
236 - const view = approvalView({ label: approval.label || routed.actionId, token, cancelCallback });
237 - const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
238 - return { ok: true, approvalRequired: true, actionId: routed.actionId, risk: routed.risk, callbackAnswered, edited: true, res };
354 + this.audit.log({
355 + event: 'approval_issued',
356 + pluginId: routed.pluginId,
357 + actionId: routed.actionId,
358 + risk: routed.risk,
359 + outcome: 'pending'
360 + });
361 + const cancelCallback =
362 + approval.cancelCallback ||
363 + (Number.isSafeInteger(Number(runId))
364 + ? `run:${repoId}:${runId}`
365 + : `repo:${repoId}`);
366 + const view = approvalView({
367 + label: approval.label || routed.actionId,
368 + token,
369 + cancelCallback
370 + });
371 + const res = await this.telegram.editMessageText(
372 + chatId,
373 + messageId,
374 + view.text,
375 + view.reply_markup
376 + );
377 + return {
378 + ok: true,
379 + approvalRequired: true,
380 + actionId: routed.actionId,
381 + risk: routed.risk,
382 + callbackAnswered,
383 + edited: true,
384 + res
385 + };
386 }
240 - if (routed?.denied) return { ok: false, denied: true, actionId: routed.actionId, reason: routed.reason, callbackAnswered };
387 + if (routed?.denied)
388 + return {
389 + ok: false,
390 + denied: true,
391 + actionId: routed.actionId,
392 + reason: routed.reason,
393 + callbackAnswered
394 + };
395
242 - const view = routed || await this.menu.renderByCallback(data);
396 + const view = routed || (await this.menu.renderByCallback(data));
397 if (data.startsWith('wtext:') && routed) {
244 - const res = await this.telegram.sendMessage(chatId, view.text, focusedCodeInputMarkup());
245 - return { ok: true, inputPrompt: true, callbackAnswered, sent: true, res };
398 + const res = await this.telegram.sendMessage(
399 + chatId,
400 + view.text,
401 + focusedCodeInputMarkup()
402 + );
403 + return {
404 + ok: true,
405 + inputPrompt: true,
406 + callbackAnswered,
407 + sent: true,
408 + res
409 + };
410 }
247 - const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
411 + const res = await this.telegram.editMessageText(
412 + chatId,
413 + messageId,
414 + view.text,
415 + view.reply_markup
416 + );
417 return { ok: true, edited: true, callbackAnswered, res };
418 } catch (err) {
250 - if (err.message && err.message.includes('message is not modified')) return { ok: true, unmodified: true, callbackAnswered };
419 + if (err.message && err.message.includes('message is not modified'))
420 + return { ok: true, unmodified: true, callbackAnswered };
421 if (!data.startsWith('approve:')) {
422 try {
253 - const view = await buildCallbackFailureView({ data, error: err, ownerId, workspaces: this.workspaceStore });
254 - const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
423 + const view = await buildCallbackFailureView({
424 + data,
425 + error: err,
426 + ownerId,
427 + workspaces: this.workspaceStore
428 + });
429 + const res = await this.telegram.editMessageText(
430 + chatId,
431 + messageId,
432 + view.text,
433 + view.reply_markup
434 + );
435 return {
436 ok: false,
437 error: err.message,
@@ -282,8 +462,18 @@ export class NexaDevBot {
462 persistentQuickMenuMarkup()
463 );
464 const view = this.menu.getMainMenuView();
285 - const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
286 - return { ok: true, command: 'start', persistentMenu: true, quickMenuRes, res };
465 + const res = await this.telegram.sendMessage(
466 + chatId,
467 + view.text,
468 + view.reply_markup
469 + );
470 + return {
471 + ok: true,
472 + command: 'start',
473 + persistentMenu: true,
474 + quickMenuRes,
475 + res
476 + };
477 }
478
479 const quickMenu = QUICK_MENU[text];
@@ -292,9 +482,15 @@ export class NexaDevBot {
482 if (quickMenu === 'main') {
483 view = this.menu.getMainMenuView();
484 } else if (quickMenu === 'repos') {
295 - const routed = await this.router.dispatchCommand('/repos', { isOwner: true });
485 + const routed = await this.router.dispatchCommand('/repos', {
486 + isOwner: true
487 + });
488 if (routed?.requiresApproval || routed?.denied || !routed) {
297 - return { ok: false, quickMenu, error: routed?.reason || 'GitHub repository route unavailable' };
489 + return {
490 + ok: false,
491 + quickMenu,
492 + error: routed?.reason || 'GitHub repository route unavailable'
493 + };
494 }
495 view = routed;
496 } else if (quickMenu === 'status') {
@@ -304,28 +500,50 @@ export class NexaDevBot {
500 } else {
501 view = this.menu.getSecurityView();
502 }
307 - const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
503 + const res = await this.telegram.sendMessage(
504 + chatId,
505 + view.text,
506 + view.reply_markup
507 + );
508 return { ok: true, quickMenu, res };
509 }
510
511 if (text === '/repos') {
512 const routed = await this.router.dispatchCommand(text, { isOwner: true });
513 if (routed?.requiresApproval || routed?.denied || !routed) {
314 - return { ok: false, command: 'repos', error: routed?.reason || 'GitHub repository route unavailable' };
514 + return {
515 + ok: false,
516 + command: 'repos',
517 + error: routed?.reason || 'GitHub repository route unavailable'
518 + };
519 }
316 - const res = await this.telegram.sendMessage(chatId, routed.text, routed.reply_markup);
520 + const res = await this.telegram.sendMessage(
521 + chatId,
522 + routed.text,
523 + routed.reply_markup
524 + );
525 return { ok: true, command: 'repos', res };
526 }
527
528 if (text === '/status') {
529 const view = this.menu.getServiceStatusView();
322 - const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
530 + const res = await this.telegram.sendMessage(
531 + chatId,
532 + view.text,
533 + view.reply_markup
534 + );
535 return { ok: true, command: 'status', res };
536 }
537
538 const ownerId = message.from?.id;
327 - if (ownerId !== undefined && ownerId !== null && this.workspaceStore.isConfigured()) {
328 - const pending = await this.workspaceStore.getPendingInput({ ownerId: String(ownerId) });
539 + if (
540 + ownerId !== undefined &&
541 + ownerId !== null &&
542 + this.workspaceStore.isConfigured()
543 + ) {
544 + const pending = await this.workspaceStore.getPendingInput({
545 + ownerId: String(ownerId)
546 + });
547 if (pending) {
548 let payload = { pending, text: rawText };
549 if (pending.mode === 'draft_file') {
@@ -334,29 +552,91 @@ export class NexaDevBot {
552 if (!document?.file_id) {
553 const view = {
554 text: `📎 <b>یک فایل متنی ارسال کنید</b>\nاین Workspace در حالت بارگذاری فایل است. فایل باید UTF-8 معتبر و حداکثر ${maxUploadBytes.toLocaleString('en-US')} بایت باشد.`,
337 - reply_markup: { inline_keyboard: [[{ text: '↩️ بازگشت به Draft', callback_data: `ws:${pending.workspaceId}` }]] }
555 + reply_markup: {
556 + inline_keyboard: [
557 + [
558 + {
559 + text: '↩️ بازگشت به Draft',
560 + callback_data: `ws:${pending.workspaceId}`
561 + }
562 + ]
563 + ]
564 + }
565 + };
566 + const res = await this.telegram.sendMessage(
567 + chatId,
568 + view.text,
569 + view.reply_markup
570 + );
571 + return {
572 + ok: true,
573 + workspaceInput: true,
574 + inputRequired: 'document',
575 + res
576 };
339 - const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
340 - return { ok: true, workspaceInput: true, inputRequired: 'document', res };
577 }
342 - if (Number.isFinite(Number(document.file_size)) && Number(document.file_size) > maxUploadBytes) {
578 + if (
579 + Number.isFinite(Number(document.file_size)) &&
580 + Number(document.file_size) > maxUploadBytes
581 + ) {
582 const view = {
583 text: `⚠️ <b>فایل پذیرفته نشد</b>\nحجم فایل بیشتر از سقف ${maxUploadBytes.toLocaleString('en-US')} بایت است. Draft تغییر نکرد؛ یک فایل کوچک‌تر ارسال کنید.`,
345 - reply_markup: { inline_keyboard: [[{ text: '↩️ بازگشت به Draft', callback_data: `ws:${pending.workspaceId}` }]] }
584 + reply_markup: {
585 + inline_keyboard: [
586 + [
587 + {
588 + text: '↩️ بازگشت به Draft',
589 + callback_data: `ws:${pending.workspaceId}`
590 + }
591 + ]
592 + ]
593 + }
594 + };
595 + const res = await this.telegram.sendMessage(
596 + chatId,
597 + view.text,
598 + view.reply_markup
599 + );
600 + return {
601 + ok: false,
602 + workspaceInput: true,
603 + inputRejected: true,
604 + error: `Telegram file exceeds ${maxUploadBytes} byte size limit`,
605 + res
606 };
347 - const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
348 - return { ok: false, workspaceInput: true, inputRejected: true, error: `Telegram file exceeds ${maxUploadBytes} byte size limit`, res };
607 }
608 let downloaded;
609 try {
352 - downloaded = await this.telegram.downloadTextFile(document.file_id, { maxBytes: maxUploadBytes });
610 + downloaded = await this.telegram.downloadTextFile(
611 + document.file_id,
612 + { maxBytes: maxUploadBytes }
613 + );
614 } catch (error) {
615 const view = {
616 text: `⚠️ <b>فایل پذیرفته نشد</b>\n${escapeHtml(error?.message || 'Telegram file download failed')}\n\nDraft تغییر نکرد و می‌توانید فایل دیگری ارسال کنید.`,
356 - reply_markup: { inline_keyboard: [[{ text: '↩️ بازگشت به Draft', callback_data: `ws:${pending.workspaceId}` }]] }
617 + reply_markup: {
618 + inline_keyboard: [
619 + [
620 + {
621 + text: '↩️ بازگشت به Draft',
622 + callback_data: `ws:${pending.workspaceId}`
623 + }
624 + ]
625 + ]
626 + }
627 + };
628 + const res = await this.telegram.sendMessage(
629 + chatId,
630 + view.text,
631 + view.reply_markup
632 + );
633 + return {
634 + ok: false,
635 + workspaceInput: true,
636 + inputRejected: true,
637 + error: error?.message || 'Telegram file download failed',
638 + res
639 };
358 - const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
359 - return { ok: false, workspaceInput: true, inputRejected: true, error: error?.message || 'Telegram file download failed', res };
640 }
641 payload = {
642 pending,
@@ -368,26 +648,45 @@ export class NexaDevBot {
648 };
649 }
650
371 - const routed = await this.router.dispatchMessage(
372 - payload,
373 - { isOwner: true, ownerId: String(ownerId) }
374 - );
651 + const routed = await this.router.dispatchMessage(payload, {
652 + isOwner: true,
653 + ownerId: String(ownerId)
654 + });
655 if (routed?.requiresApproval || routed?.denied || !routed) {
376 - return { ok: false, error: routed?.reason || 'Workspace input route unavailable' };
656 + return {
657 + ok: false,
658 + error: routed?.reason || 'Workspace input route unavailable'
659 + };
660 }
378 - const res = await this.telegram.sendMessage(chatId, routed.text, routed.reply_markup);
661 + const res = await this.telegram.sendMessage(
662 + chatId,
663 + routed.text,
664 + routed.reply_markup
665 + );
666 return { ok: true, workspaceInput: true, res };
667 }
668 }
669
383 - const defaultText = '💡 برای دسترسی به منوهای پروژه‌ها و ابزارهای Nexa Dev، دکمه زیر را لمس کنید:';
670 + const defaultText =
671 + '💡 برای دسترسی به منوهای پروژه‌ها و ابزارهای Nexa Dev، دکمه زیر را لمس کنید:';
672 const view = {
673 text: defaultText,
674 reply_markup: {
387 - inline_keyboard: [[{ text: '⚡ باز کردن منوی اصلی Nexa Dev', callback_data: 'menu:main' }]]
675 + inline_keyboard: [
676 + [
677 + {
678 + text: '⚡ باز کردن منوی اصلی Nexa Dev',
679 + callback_data: 'menu:main'
680 + }
681 + ]
682 + ]
683 }
684 };
390 - const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
685 + const res = await this.telegram.sendMessage(
686 + chatId,
687 + view.text,
688 + view.reply_markup
689 + );
690 return { ok: true, default: true, res };
691 }
692 }
src/bot.js
+330 -66
@@ -1,10 +1,11 @@
1 import { NexaDevBot as LegacyNexaDevBot } from './bot-legacy.js';
2 import { TotpVerifier } from './core/totp.js';
3
4 -const escapeHtml = value => String(value ?? '')
5 - .replaceAll('&', '&amp;')
6 - .replaceAll('<', '&lt;')
7 - .replaceAll('>', '&gt;');
4 +const escapeHtml = (value) =>
5 + String(value ?? '')
6 + .replaceAll('&', '&amp;')
7 + .replaceAll('<', '&lt;')
8 + .replaceAll('>', '&gt;');
9
10 function destructiveSourceCallback(payload = {}) {
11 if (payload.actionId === 'cloudflare.worker.deploy_version') {
@@ -16,7 +17,11 @@ function destructiveSourceCallback(payload = {}) {
17 const repoId = Number(payload.input?.repoId);
18 const prNumber = Number(payload.input?.prNumber);
19 const headSha = String(payload.input?.headSha || '');
19 - if (!Number.isSafeInteger(repoId) || !Number.isSafeInteger(prNumber) || !/^[a-f0-9]{40}$/i.test(headSha)) {
20 + if (
21 + !Number.isSafeInteger(repoId) ||
22 + !Number.isSafeInteger(prNumber) ||
23 + !/^[a-f0-9]{40}$/i.test(headSha)
24 + ) {
25 throw new Error('Destructive approval target is invalid');
26 }
27 return `mergepr:${repoId.toString(36)}:${prNumber.toString(36)}:${headSha}`;
@@ -26,15 +31,21 @@ function destructiveSourceCallback(payload = {}) {
31
32 function secondFactorFailureMarkup(payload = {}) {
33 if (payload.actionId === 'cloudflare.worker.deploy_version') {
29 - return { inline_keyboard: [[{ text: '↩️ نسخه‌ها', callback_data: 'cf:versions' }]] };
34 + return {
35 + inline_keyboard: [[{ text: '↩️ نسخه‌ها', callback_data: 'cf:versions' }]]
36 + };
37 }
31 - return { inline_keyboard: [[{ text: '↩️ پروژه‌ها', callback_data: 'menu:repos' }]] };
38 + return {
39 + inline_keyboard: [[{ text: '↩️ پروژه‌ها', callback_data: 'menu:repos' }]]
40 + };
41 }
42
43 export class NexaDevBot extends LegacyNexaDevBot {
44 constructor(env = {}) {
45 super(env);
37 - this.destructiveTotp = new TotpVerifier({ secret: env.DESTRUCTIVE_TOTP_SECRET || '' });
46 + this.destructiveTotp = new TotpVerifier({
47 + secret: env.DESTRUCTIVE_TOTP_SECRET || ''
48 + });
49 }
50
51 async handleCallbackQuery(query) {
@@ -43,25 +54,51 @@ export class NexaDevBot extends LegacyNexaDevBot {
54 const chatId = query?.message?.chat?.id;
55 const messageId = query?.message?.message_id;
56
46 - if (data.startsWith('approve:') && ownerId !== undefined && ownerId !== null) {
57 + if (
58 + data.startsWith('approve:') &&
59 + ownerId !== undefined &&
60 + ownerId !== null
61 + ) {
62 const token = data.slice(8);
63 let preview = null;
49 - try { preview = await this.approvals.verify(token, { ownerId: String(ownerId) }); } catch {}
64 + try {
65 + preview = await this.approvals.verify(token, {
66 + ownerId: String(ownerId)
67 + });
68 + } catch {}
69
70 if (preview?.risk === 'DESTRUCTIVE') {
71 let callbackAnswered = true;
53 - try { await this.telegram.answerCallbackQuery(query.id); } catch { callbackAnswered = false; }
72 + try {
73 + await this.telegram.answerCallbackQuery(query.id);
74 + } catch {
75 + callbackAnswered = false;
76 + }
77
78 if (!this.destructiveTotp.isConfigured()) {
79 const error = 'Destructive second factor (TOTP) is not configured';
57 - this.audit.log({ event: 'second_factor_unavailable', pluginId: preview.pluginId, actionId: preview.actionId, risk: 'DESTRUCTIVE', outcome: 'rejected' });
80 + this.audit.log({
81 + event: 'second_factor_unavailable',
82 + pluginId: preview.pluginId,
83 + actionId: preview.actionId,
84 + risk: 'DESTRUCTIVE',
85 + outcome: 'rejected'
86 + });
87 const res = await this.telegram.editMessageText(
88 chatId,
89 messageId,
90 `⚠️ <b>عملیات متوقف شد</b>\nعامل دوم TOTP برای عملیات DESTRUCTIVE پیکربندی نشده است.\nهیچ تغییری اجرا نشد.`,
91 secondFactorFailureMarkup(preview)
92 );
64 - return { ok: false, secondFactorRequired: true, approvalRejected: true, error, callbackAnswered, edited: true, res };
93 + return {
94 + ok: false,
95 + secondFactorRequired: true,
96 + approvalRejected: true,
97 + error,
98 + callbackAnswered,
99 + edited: true,
100 + res
101 + };
102 }
103
104 try {
@@ -71,14 +108,28 @@ export class NexaDevBot extends LegacyNexaDevBot {
108 expiresAt: preview.expiresAt,
109 attempts: 0
110 });
74 - this.audit.log({ event: 'second_factor_required', pluginId: preview.pluginId, actionId: preview.actionId, risk: 'DESTRUCTIVE', outcome: 'pending' });
111 + this.audit.log({
112 + event: 'second_factor_required',
113 + pluginId: preview.pluginId,
114 + actionId: preview.actionId,
115 + risk: 'DESTRUCTIVE',
116 + outcome: 'pending'
117 + });
118 const res = await this.telegram.editMessageText(
119 chatId,
120 messageId,
121 '🔐 <b>عامل دوم لازم است</b>\nApproval تلگرام معتبر است، اما عملیات هنوز اجرا نشده.\n\nکد ۶ رقمی برنامه Authenticator را به شکل زیر ارسال کنید:\n<code>/totp 123456</code>\n\nکد یا Secret در Audit ذخیره نمی‌شود.',
122 secondFactorFailureMarkup(preview)
123 );
81 - return { ok: true, secondFactorRequired: true, actionId: preview.actionId, risk: preview.risk, callbackAnswered, edited: true, res };
124 + return {
125 + ok: true,
126 + secondFactorRequired: true,
127 + actionId: preview.actionId,
128 + risk: preview.risk,
129 + callbackAnswered,
130 + edited: true,
131 + res
132 + };
133 } catch (error) {
134 const res = await this.telegram.editMessageText(
135 chatId,
@@ -86,46 +137,174 @@ export class NexaDevBot extends LegacyNexaDevBot {
137 `⚠️ <b>عامل دوم آماده نشد</b>\nهیچ تغییر DESTRUCTIVE اجرا نشد.\n\n${escapeHtml(error?.message || 'Second factor unavailable')}`,
138 secondFactorFailureMarkup(preview)
139 );
89 - return { ok: false, secondFactorRequired: true, approvalRejected: true, error: error?.message, callbackAnswered, edited: true, res };
140 + return {
141 + ok: false,
142 + secondFactorRequired: true,
143 + approvalRejected: true,
144 + error: error?.message,
145 + callbackAnswered,
146 + edited: true,
147 + res
148 + };
149 }
150 }
151 }
152
153 if (data.startsWith('cfdeploy:')) {
95 - let callbackAnswered = true; try { await this.telegram.answerCallbackQuery(query.id); } catch { callbackAnswered = false; }
154 + let callbackAnswered = true;
155 try {
97 - const routed = await this.router.dispatchCallback(data, { isOwner: true, ownerId: String(ownerId ?? '') });
98 - if (!routed?.requiresApproval || routed.actionId !== 'cloudflare.worker.deploy_version') throw new Error(routed?.reason || 'Cloudflare approval route unavailable');
99 - if (ownerId === undefined || ownerId === null) throw new Error('Approval owner is required');
100 - const token = await this.approvals.issue({ pluginId: routed.pluginId, actionId: routed.actionId, risk: routed.risk, ownerId: String(ownerId), input: routed.approval.input });
101 - const callback = `approve:${token}`; if (callback.length > 64) throw new Error('Approval callback exceeds Telegram limit');
156 + await this.telegram.answerCallbackQuery(query.id);
157 + } catch {
158 + callbackAnswered = false;
159 + }
160 + try {
161 + const routed = await this.router.dispatchCallback(data, {
162 + isOwner: true,
163 + ownerId: String(ownerId ?? '')
164 + });
165 + if (
166 + !routed?.requiresApproval ||
167 + routed.actionId !== 'cloudflare.worker.deploy_version'
168 + )
169 + throw new Error(
170 + routed?.reason || 'Cloudflare approval route unavailable'
171 + );
172 + if (ownerId === undefined || ownerId === null)
173 + throw new Error('Approval owner is required');
174 + const token = await this.approvals.issue({
175 + pluginId: routed.pluginId,
176 + actionId: routed.actionId,
177 + risk: routed.risk,
178 + ownerId: String(ownerId),
179 + input: routed.approval.input
180 + });
181 + const callback = `approve:${token}`;
182 + if (callback.length > 64)
183 + throw new Error('Approval callback exceeds Telegram limit');
184 const text = `⚠️ <b>تأیید نهایی Cloudflare لازم است</b>\nVersion: <code>${routed.approval.input.versionId}</code>\n\nTraffic این Worker روی نسخه انتخاب‌شده قرار می‌گیرد. پس از این تأیید، عامل دوم TOTP نیز لازم است.`;
103 - const markup = { inline_keyboard: [[{ text: '✅ ادامه تأیید Deploy / Rollback', callback_data: callback }],[{ text: '↩️ انصراف', callback_data: 'cf:versions' }]] };
104 - const res = await this.telegram.editMessageText(chatId, messageId, text, markup);
105 - return { ok: true, approvalRequired: true, actionId: routed.actionId, risk: routed.risk, callbackAnswered, edited: true, res };
185 + const markup = {
186 + inline_keyboard: [
187 + [
188 + {
189 + text: '✅ ادامه تأیید Deploy / Rollback',
190 + callback_data: callback
191 + }
192 + ],
193 + [{ text: '↩️ انصراف', callback_data: 'cf:versions' }]
194 + ]
195 + };
196 + const res = await this.telegram.editMessageText(
197 + chatId,
198 + messageId,
199 + text,
200 + markup
201 + );
202 + return {
203 + ok: true,
204 + approvalRequired: true,
205 + actionId: routed.actionId,
206 + risk: routed.risk,
207 + callbackAnswered,
208 + edited: true,
209 + res
210 + };
211 } catch (error) {
212 const text = `⚠️ <b>Cloudflare Deploy آماده نشد</b>\n${escapeHtml(error?.message || 'Unavailable')}`;
108 - const res = await this.telegram.editMessageText(chatId, messageId, text, { inline_keyboard: [[{ text: '↩️ نسخه‌ها', callback_data: 'cf:versions' }]] });
109 - return { ok: false, error: error?.message, callbackAnswered, edited: true, res };
213 + const res = await this.telegram.editMessageText(
214 + chatId,
215 + messageId,
216 + text,
217 + {
218 + inline_keyboard: [
219 + [{ text: '↩️ نسخه‌ها', callback_data: 'cf:versions' }]
220 + ]
221 + }
222 + );
223 + return {
224 + ok: false,
225 + error: error?.message,
226 + callbackAnswered,
227 + edited: true,
228 + res
229 + };
230 }
231 }
232
233 if (data.startsWith('mergepr:')) {
114 - let callbackAnswered = true; try { await this.telegram.answerCallbackQuery(query.id); } catch { callbackAnswered = false; }
234 + let callbackAnswered = true;
235 + try {
236 + await this.telegram.answerCallbackQuery(query.id);
237 + } catch {
238 + callbackAnswered = false;
239 + }
240 try {
116 - const routed = await this.router.dispatchCallback(data, { isOwner: true, ownerId: String(ownerId ?? '') });
117 - if (!routed?.requiresApproval || routed.actionId !== 'github.pull_request.merge') throw new Error(routed?.reason || 'Merge approval route unavailable');
118 - if (ownerId === undefined || ownerId === null) throw new Error('Approval owner is required');
119 - const token = await this.approvals.issue({ pluginId: routed.pluginId, actionId: routed.actionId, risk: routed.risk, ownerId: String(ownerId), input: routed.approval.input });
120 - const callback = `approve:${token}`; if (callback.length > 64) throw new Error('Approval callback exceeds Telegram limit');
121 - const text = `⚠️ <b>تأیید نهایی Merge لازم است</b>\nPR #${routed.approval.input.prNumber}\nHead: <code>${routed.approval.input.headSha.slice(0,12)}</code>\n\nMerge فقط برای همین Head و فقط یک‌بار قابل اجراست. پس از این تأیید، عامل دوم TOTP نیز لازم است.`;
122 - const markup = { inline_keyboard: [[{ text: '✅ ادامه تأیید Merge', callback_data: callback }],[{ text: '↩️ انصراف', callback_data: routed.approval.cancelCallback }]] };
123 - const res = await this.telegram.editMessageText(chatId, messageId, text, markup);
124 - return { ok: true, approvalRequired: true, actionId: routed.actionId, risk: routed.risk, callbackAnswered, edited: true, res };
241 + const routed = await this.router.dispatchCallback(data, {
242 + isOwner: true,
243 + ownerId: String(ownerId ?? '')
244 + });
245 + if (
246 + !routed?.requiresApproval ||
247 + routed.actionId !== 'github.pull_request.merge'
248 + )
249 + throw new Error(routed?.reason || 'Merge approval route unavailable');
250 + if (ownerId === undefined || ownerId === null)
251 + throw new Error('Approval owner is required');
252 + const token = await this.approvals.issue({
253 + pluginId: routed.pluginId,
254 + actionId: routed.actionId,
255 + risk: routed.risk,
256 + ownerId: String(ownerId),
257 + input: routed.approval.input
258 + });
259 + const callback = `approve:${token}`;
260 + if (callback.length > 64)
261 + throw new Error('Approval callback exceeds Telegram limit');
262 + const text = `⚠️ <b>تأیید نهایی Merge لازم است</b>\nPR #${routed.approval.input.prNumber}\nHead: <code>${routed.approval.input.headSha.slice(0, 12)}</code>\n\nMerge فقط برای همین Head و فقط یک‌بار قابل اجراست. پس از این تأیید، عامل دوم TOTP نیز لازم است.`;
263 + const markup = {
264 + inline_keyboard: [
265 + [{ text: '✅ ادامه تأیید Merge', callback_data: callback }],
266 + [
267 + {
268 + text: '↩️ انصراف',
269 + callback_data: routed.approval.cancelCallback
270 + }
271 + ]
272 + ]
273 + };
274 + const res = await this.telegram.editMessageText(
275 + chatId,
276 + messageId,
277 + text,
278 + markup
279 + );
280 + return {
281 + ok: true,
282 + approvalRequired: true,
283 + actionId: routed.actionId,
284 + risk: routed.risk,
285 + callbackAnswered,
286 + edited: true,
287 + res
288 + };
289 } catch (error) {
290 const text = `⚠️ <b>Merge آماده نشد</b>\n${escapeHtml(error?.message || 'Merge unavailable')}`;
127 - const res = await this.telegram.editMessageText(chatId, messageId, text, { inline_keyboard: [[{ text: '↩️ پروژه‌ها', callback_data: 'menu:repos' }]] });
128 - return { ok: false, error: error?.message, callbackAnswered, edited: true, res };
291 + const res = await this.telegram.editMessageText(
292 + chatId,
293 + messageId,
294 + text,
295 + {
296 + inline_keyboard: [
297 + [{ text: '↩️ پروژه‌ها', callback_data: 'menu:repos' }]
298 + ]
299 + }
300 + );
301 + return {
302 + ok: false,
303 + error: error?.message,
304 + callbackAnswered,
305 + edited: true,
306 + res
307 + };
308 }
309 }
310
@@ -133,87 +312,172 @@ export class NexaDevBot extends LegacyNexaDevBot {
312 }
313
314 async handleMessage(message) {
136 - const rawText = typeof message?.text === 'string' ? message.text.trim() : '';
315 + const rawText =
316 + typeof message?.text === 'string' ? message.text.trim() : '';
317 if (!rawText.startsWith('/totp')) return super.handleMessage(message);
318
319 const chatId = message?.chat?.id;
320 const ownerId = message?.from?.id;
321 if (!chatId || ownerId === undefined || ownerId === null) {
142 - return { ok: false, secondFactorRejected: true, error: 'Second-factor owner context is missing' };
322 + return {
323 + ok: false,
324 + secondFactorRejected: true,
325 + error: 'Second-factor owner context is missing'
326 + };
327 }
328
329 if (!this.destructiveTotp.isConfigured()) {
330 const error = 'Destructive second factor (TOTP) is not configured';
147 - const res = await this.telegram.sendMessage(chatId, '⚠️ <b>عامل دوم پیکربندی نشده است</b>\nهیچ عملیات DESTRUCTIVE اجرا نشد.');
331 + const res = await this.telegram.sendMessage(
332 + chatId,
333 + '⚠️ <b>عامل دوم پیکربندی نشده است</b>\nهیچ عملیات DESTRUCTIVE اجرا نشد.'
334 + );
335 return { ok: false, secondFactorRejected: true, error, res };
336 }
337
338 const match = rawText.match(/^\/totp\s+(\d{6})$/);
339 if (!match) {
153 - const res = await this.telegram.sendMessage(chatId, '⚠️ فرمت کد درست نیست. فقط به شکل <code>/totp 123456</code> ارسال کنید.');
154 - return { ok: false, secondFactorRejected: true, error: 'Invalid TOTP format', res };
340 + const res = await this.telegram.sendMessage(
341 + chatId,
342 + '⚠️ فرمت کد درست نیست. فقط به شکل <code>/totp 123456</code> ارسال کنید.'
343 + );
344 + return {
345 + ok: false,
346 + secondFactorRejected: true,
347 + error: 'Invalid TOTP format',
348 + res
349 + };
350 }
351
352 let pending;
353 try {
159 - pending = await this.replayStore.getSecondFactorPending({ ownerId: String(ownerId) });
354 + pending = await this.replayStore.getSecondFactorPending({
355 + ownerId: String(ownerId)
356 + });
357 } catch (error) {
161 - const res = await this.telegram.sendMessage(chatId, '⚠️ وضعیت عامل دوم در دسترس نیست؛ عملیات متوقف شد.');
162 - return { ok: false, secondFactorRejected: true, error: error?.message || 'Second-factor state unavailable', res };
358 + const res = await this.telegram.sendMessage(
359 + chatId,
360 + '⚠️ وضعیت عامل دوم در دسترس نیست؛ عملیات متوقف شد.'
361 + );
362 + return {
363 + ok: false,
364 + secondFactorRejected: true,
365 + error: error?.message || 'Second-factor state unavailable',
366 + res
367 + };
368 }
369
370 if (!pending) {
166 - const res = await this.telegram.sendMessage(chatId, '⚠️ درخواست DESTRUCTIVE منتظر عامل دوم پیدا نشد. از ابتدا یک Approval تازه ایجاد کنید.');
167 - return { ok: false, secondFactorRejected: true, error: 'Second-factor challenge is unavailable', res };
371 + const res = await this.telegram.sendMessage(
372 + chatId,
373 + '⚠️ درخواست DESTRUCTIVE منتظر عامل دوم پیدا نشد. از ابتدا یک Approval تازه ایجاد کنید.'
374 + );
375 + return {
376 + ok: false,
377 + secondFactorRejected: true,
378 + error: 'Second-factor challenge is unavailable',
379 + res
380 + };
381 }
382
383 const validCode = await this.destructiveTotp.verify(match[1]);
384 if (!validCode) {
385 const attempts = Number(pending.attempts || 0) + 1;
386 if (attempts >= 5) {
174 - await this.replayStore.clearSecondFactorPending({ ownerId: String(ownerId) });
387 + await this.replayStore.clearSecondFactorPending({
388 + ownerId: String(ownerId)
389 + });
390 } else {
176 - await this.replayStore.setSecondFactorPending({ ownerId: String(ownerId), token: pending.token, expiresAt: pending.expiresAt, attempts });
391 + await this.replayStore.setSecondFactorPending({
392 + ownerId: String(ownerId),
393 + token: pending.token,
394 + expiresAt: pending.expiresAt,
395 + attempts
396 + });
397 }
178 - this.audit.log({ event: 'second_factor_rejected', risk: 'DESTRUCTIVE', outcome: 'rejected', reason: attempts >= 5 ? 'attempt_limit' : 'invalid_code' });
398 + this.audit.log({
399 + event: 'second_factor_rejected',
400 + risk: 'DESTRUCTIVE',
401 + outcome: 'rejected',
402 + reason: attempts >= 5 ? 'attempt_limit' : 'invalid_code'
403 + });
404 const res = await this.telegram.sendMessage(
405 chatId,
406 attempts >= 5
407 ? '⚠️ <b>عامل دوم رد شد</b>\nتعداد تلاش مجاز تمام شد. برای ادامه Approval تازه بسازید.'
408 : '⚠️ <b>کد TOTP معتبر نیست</b>\nهیچ تغییری اجرا نشد.'
409 );
185 - return { ok: false, secondFactorRejected: true, error: 'Invalid TOTP code', res };
410 + return {
411 + ok: false,
412 + secondFactorRejected: true,
413 + error: 'Invalid TOTP code',
414 + res
415 + };
416 }
417
418 let payload;
419 try {
190 - const preview = await this.approvals.verify(pending.token, { ownerId: String(ownerId), risk: 'DESTRUCTIVE' });
420 + const preview = await this.approvals.verify(pending.token, {
421 + ownerId: String(ownerId),
422 + risk: 'DESTRUCTIVE'
423 + });
424 payload = await this.approvals.consume(pending.token, {
425 ownerId: String(ownerId),
426 pluginId: preview.pluginId,
427 actionId: preview.actionId,
428 risk: 'DESTRUCTIVE'
429 });
197 - await this.replayStore.clearSecondFactorPending({ ownerId: String(ownerId) });
198 - this.audit.log({ event: 'second_factor_verified', pluginId: payload.pluginId, actionId: payload.actionId, risk: 'DESTRUCTIVE', outcome: 'verified' });
199 -
200 - const routed = await this.router.dispatchCallback(destructiveSourceCallback(payload), {
201 - isOwner: true,
202 - ownerId: String(ownerId),
203 - approved: true
430 + await this.replayStore.clearSecondFactorPending({
431 + ownerId: String(ownerId)
432 + });
433 + this.audit.log({
434 + event: 'second_factor_verified',
435 + pluginId: payload.pluginId,
436 + actionId: payload.actionId,
437 + risk: 'DESTRUCTIVE',
438 + outcome: 'verified'
439 });
205 - if (!routed || routed.requiresApproval || routed.denied) throw new Error('Approved destructive action could not be dispatched');
440
207 - const res = await this.telegram.sendMessage(chatId, routed.text, routed.reply_markup);
208 - return { ok: true, approved: true, secondFactorVerified: true, actionId: payload.actionId, res };
441 + const routed = await this.router.dispatchCallback(
442 + destructiveSourceCallback(payload),
443 + {
444 + isOwner: true,
445 + ownerId: String(ownerId),
446 + approved: true
447 + }
448 + );
449 + if (!routed || routed.requiresApproval || routed.denied)
450 + throw new Error('Approved destructive action could not be dispatched');
451 +
452 + const res = await this.telegram.sendMessage(
453 + chatId,
454 + routed.text,
455 + routed.reply_markup
456 + );
457 + return {
458 + ok: true,
459 + approved: true,
460 + secondFactorVerified: true,
461 + actionId: payload.actionId,
462 + res
463 + };
464 } catch (error) {
210 - try { await this.replayStore.clearSecondFactorPending({ ownerId: String(ownerId) }); } catch {}
465 + try {
466 + await this.replayStore.clearSecondFactorPending({
467 + ownerId: String(ownerId)
468 + });
469 + } catch {}
470 const res = await this.telegram.sendMessage(
471 chatId,
472 `⚠️ <b>عملیات DESTRUCTIVE اجرا نشد</b>\nهیچ Success ساختگی ثبت نمی‌شود.\n\n${escapeHtml(error?.message || 'Approval rejected')}`,
473 secondFactorFailureMarkup(payload || {})
474 );
216 - return { ok: false, secondFactorRejected: true, error: error?.message || 'Destructive approval rejected', res };
475 + return {
476 + ok: false,
477 + secondFactorRejected: true,
478 + error: error?.message || 'Destructive approval rejected',
479 + res
480 + };
481 }
482 }
483 }
src/cloudflare-menu.js
+3 -1
@@ -5,7 +5,9 @@ export class CloudflareMenuManager extends OpsMenuManager {
5 const view = super.getToolsView();
6 const rows = [...(view.reply_markup?.inline_keyboard || [])];
7 const insertAt = Math.min(2, rows.length);
8 - rows.splice(insertAt, 0, [{ text: '☁️ Cloudflare status', callback_data: 'cf:status' }]);
8 + rows.splice(insertAt, 0, [
9 + { text: '☁️ Cloudflare status', callback_data: 'cf:status' }
10 + ]);
11 return {
12 ...view,
13 reply_markup: { ...(view.reply_markup || {}), inline_keyboard: rows }
src/config.js
+2 -1
@@ -1,6 +1,7 @@
1 export const DEFAULT_CONFIG = {
2 defaultOwner: 'davoodmehraban89',
3 - workspaceEditorUrl: 'https://nexa-dev-bot.davoodmehraban89.workers.dev/workspace/editor',
3 + workspaceEditorUrl:
4 + 'https://nexa-dev-bot.davoodmehraban89.workers.dev/workspace/editor',
5 devTools: [
6 {
7 id: 'ping',
src/core/action-policy.js
+4 -1
@@ -36,7 +36,10 @@ export class ActionPolicy {
36 allowed: true,
37 requiresApproval: false,
38 risk,
39 - reason: risk === 'WRITE' ? 'owner_write_approved' : 'owner_destructive_approved'
39 + reason:
40 + risk === 'WRITE'
41 + ? 'owner_write_approved'
42 + : 'owner_destructive_approved'
43 };
44 }
45
src/core/approval.js
+292 -40
@@ -4,66 +4,318 @@ const INTENT_ID_PATTERN = /^[A-Za-z0-9_-]{8}$/;
4 const FULL_SHA_PATTERN = /^[a-f0-9]{40}$/i;
5 const VERSION_ID_PATTERN = /^[0-9a-f-]{36}$/i;
6 const DEFAULT_CODECS = new Map([
7 - ['github.workflow.run.rerun_failed', { code: 'r', pluginId: 'github', risk: 'WRITE', target: 'run' }],
8 - ['github.workflow.run.cancel', { code: 'c', pluginId: 'github', risk: 'WRITE', target: 'run' }],
9 - ['github.workspace.commit_branch', { code: 'e', pluginId: 'github', risk: 'WRITE', target: 'intent' }]
7 + [
8 + 'github.workflow.run.rerun_failed',
9 + { code: 'r', pluginId: 'github', risk: 'WRITE', target: 'run' }
10 + ],
11 + [
12 + 'github.workflow.run.cancel',
13 + { code: 'c', pluginId: 'github', risk: 'WRITE', target: 'run' }
14 + ],
15 + [
16 + 'github.workspace.commit_branch',
17 + { code: 'e', pluginId: 'github', risk: 'WRITE', target: 'intent' }
18 + ]
19 ]);
11 -const bytesToBase64Url = bytes => { let binary = ''; for (const byte of bytes) binary += String.fromCharCode(byte); return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, ''); };
12 -const base64UrlToBytes = value => { const normalized = value.replace(/-/g, '+').replace(/_/g, '/'); const padding = '='.repeat((4 - (normalized.length % 4)) % 4); const binary = atob(normalized + padding); return Uint8Array.from(binary, char => char.charCodeAt(0)); };
13 -const textToBase64Url = value => bytesToBase64Url(encoder.encode(value));
14 -const base64UrlToText = value => new TextDecoder().decode(base64UrlToBytes(value));
15 -const toBase36Int = value => { const number = Number(value); if (!Number.isSafeInteger(number) || number < 0) throw new Error('Invalid approval numeric input'); return number.toString(36); };
16 -const fromBase36Int = value => { if (!/^[0-9a-z]+$/i.test(value)) throw new Error('Invalid approval numeric input'); const number = Number.parseInt(value, 36); if (!Number.isSafeInteger(number) || number < 0) throw new Error('Invalid approval numeric input'); return number; };
17 -const constantTimeEqual = (left, right) => { if (left.length !== right.length) return false; let mismatch = 0; for (let i = 0; i < left.length; i += 1) mismatch |= left[i] ^ right[i]; return mismatch === 0; };
18 -const compactCodecFor = actionId => DEFAULT_CODECS.get(actionId) || null;
19 -const compactCodecByCode = code => { for (const [actionId, codec] of DEFAULT_CODECS.entries()) if (codec.code === code) return { actionId, ...codec }; return null; };
20 +const bytesToBase64Url = (bytes) => {
21 + let binary = '';
22 + for (const byte of bytes) binary += String.fromCharCode(byte);
23 + return btoa(binary)
24 + .replace(/\+/g, '-')
25 + .replace(/\//g, '_')
26 + .replace(/=+$/g, '');
27 +};
28 +const base64UrlToBytes = (value) => {
29 + const normalized = value.replace(/-/g, '+').replace(/_/g, '/');
30 + const padding = '='.repeat((4 - (normalized.length % 4)) % 4);
31 + const binary = atob(normalized + padding);
32 + return Uint8Array.from(binary, (char) => char.charCodeAt(0));
33 +};
34 +const textToBase64Url = (value) => bytesToBase64Url(encoder.encode(value));
35 +const base64UrlToText = (value) =>
36 + new TextDecoder().decode(base64UrlToBytes(value));
37 +const toBase36Int = (value) => {
38 + const number = Number(value);
39 + if (!Number.isSafeInteger(number) || number < 0)
40 + throw new Error('Invalid approval numeric input');
41 + return number.toString(36);
42 +};
43 +const fromBase36Int = (value) => {
44 + if (!/^[0-9a-z]+$/i.test(value))
45 + throw new Error('Invalid approval numeric input');
46 + const number = Number.parseInt(value, 36);
47 + if (!Number.isSafeInteger(number) || number < 0)
48 + throw new Error('Invalid approval numeric input');
49 + return number;
50 +};
51 +const constantTimeEqual = (left, right) => {
52 + if (left.length !== right.length) return false;
53 + let mismatch = 0;
54 + for (let i = 0; i < left.length; i += 1) mismatch |= left[i] ^ right[i];
55 + return mismatch === 0;
56 +};
57 +const compactCodecFor = (actionId) => DEFAULT_CODECS.get(actionId) || null;
58 +const compactCodecByCode = (code) => {
59 + for (const [actionId, codec] of DEFAULT_CODECS.entries())
60 + if (codec.code === code) return { actionId, ...codec };
61 + return null;
62 +};
63
64 export class ApprovalService {
22 - constructor({ secret = '', now = () => Date.now(), ttlMs = 120_000, maxTokenLength = 56, signatureBytes = 12, replayStore = null } = {}) { this.secret = String(secret || ''); this.now = now; this.ttlMs = ttlMs; this.maxTokenLength = maxTokenLength; this.signatureBytes = signatureBytes; if (replayStore && typeof replayStore.consume !== 'function') throw new Error('Approval replay store is invalid'); this.replayStore = replayStore; this.keyPromise = null; }
23 - isReplayProtected() { return Boolean(this.replayStore && typeof this.replayStore.consume === 'function'); }
65 + constructor({
66 + secret = '',
67 + now = () => Date.now(),
68 + ttlMs = 120_000,
69 + maxTokenLength = 56,
70 + signatureBytes = 12,
71 + replayStore = null
72 + } = {}) {
73 + this.secret = String(secret || '');
74 + this.now = now;
75 + this.ttlMs = ttlMs;
76 + this.maxTokenLength = maxTokenLength;
77 + this.signatureBytes = signatureBytes;
78 + if (replayStore && typeof replayStore.consume !== 'function')
79 + throw new Error('Approval replay store is invalid');
80 + this.replayStore = replayStore;
81 + this.keyPromise = null;
82 + }
83 + isReplayProtected() {
84 + return Boolean(
85 + this.replayStore && typeof this.replayStore.consume === 'function'
86 + );
87 + }
88 async issue(payload = {}) {
25 - this.#assertSecret(); const issuedAt = this.now(); const expiresAt = issuedAt + this.ttlMs; const nonce = this.#nonce();
26 - const normalized = { v: 1, pluginId: payload.pluginId, actionId: payload.actionId, risk: payload.risk, ownerId: String(payload.ownerId ?? ''), input: payload.input ?? {}, issuedAt, expiresAt, nonce };
89 + this.#assertSecret();
90 + const issuedAt = this.now();
91 + const expiresAt = issuedAt + this.ttlMs;
92 + const nonce = this.#nonce();
93 + const normalized = {
94 + v: 1,
95 + pluginId: payload.pluginId,
96 + actionId: payload.actionId,
97 + risk: payload.risk,
98 + ownerId: String(payload.ownerId ?? ''),
99 + input: payload.input ?? {},
100 + issuedAt,
101 + expiresAt,
102 + nonce
103 + };
104 if (!normalized.ownerId) throw new Error('Approval owner is required');
105 let body;
29 - if (normalized.actionId === 'github.pull_request.merge' || normalized.actionId === 'cloudflare.worker.deploy_version') {
106 + if (
107 + normalized.actionId === 'github.pull_request.merge' ||
108 + normalized.actionId === 'cloudflare.worker.deploy_version'
109 + ) {
110 let code = '';
111 if (normalized.actionId === 'github.pull_request.merge') {
112 const { repoId, prNumber, headSha } = normalized.input || {};
33 - if (normalized.pluginId !== 'github' || normalized.risk !== 'DESTRUCTIVE' || !Number.isSafeInteger(Number(repoId)) || !Number.isSafeInteger(Number(prNumber)) || !FULL_SHA_PATTERN.test(String(headSha || ''))) throw new Error('Invalid pull request approval target');
113 + if (
114 + normalized.pluginId !== 'github' ||
115 + normalized.risk !== 'DESTRUCTIVE' ||
116 + !Number.isSafeInteger(Number(repoId)) ||
117 + !Number.isSafeInteger(Number(prNumber)) ||
118 + !FULL_SHA_PATTERN.test(String(headSha || ''))
119 + )
120 + throw new Error('Invalid pull request approval target');
121 code = 'm';
122 } else {
123 const { versionId } = normalized.input || {};
37 - if (normalized.pluginId !== 'cloudflare' || normalized.risk !== 'DESTRUCTIVE' || !VERSION_ID_PATTERN.test(String(versionId || ''))) throw new Error('Invalid Cloudflare approval target');
124 + if (
125 + normalized.pluginId !== 'cloudflare' ||
126 + normalized.risk !== 'DESTRUCTIVE' ||
127 + !VERSION_ID_PATTERN.test(String(versionId || ''))
128 + )
129 + throw new Error('Invalid Cloudflare approval target');
130 code = 'c';
131 }
40 - if (!this.replayStore || typeof this.replayStore.put !== 'function' || typeof this.replayStore.peek !== 'function') throw new Error('Durable approval context storage is not configured');
41 - await this.replayStore.put({ ownerId: normalized.ownerId, nonce, expiresAt, payload: normalized });
132 + if (
133 + !this.replayStore ||
134 + typeof this.replayStore.put !== 'function' ||
135 + typeof this.replayStore.peek !== 'function'
136 + )
137 + throw new Error('Durable approval context storage is not configured');
138 + await this.replayStore.put({
139 + ownerId: normalized.ownerId,
140 + nonce,
141 + expiresAt,
142 + payload: normalized
143 + });
144 body = `s.${code}.${toBase36Int(expiresAt)}.${nonce}`;
145 } else body = this.#encodeBody(normalized);
44 - const signature = await this.#sign(normalized.ownerId, body); const token = `${body}.${bytesToBase64Url(signature.slice(0, this.signatureBytes))}`;
45 - if (token.length > this.maxTokenLength) throw new Error('Approval token too large for callback data'); return token;
146 + const signature = await this.#sign(normalized.ownerId, body);
147 + const token = `${body}.${bytesToBase64Url(signature.slice(0, this.signatureBytes))}`;
148 + if (token.length > this.maxTokenLength)
149 + throw new Error('Approval token too large for callback data');
150 + return token;
151 }
152 async verify(token, expectations = {}) {
48 - this.#assertSecret(); if (!token || typeof token !== 'string') throw new Error('Invalid approval token'); const ownerId = String(expectations.ownerId ?? ''); if (!ownerId) throw new Error('Approval owner is required');
49 - const parts = token.split('.'); if (parts.length < 3) throw new Error('Invalid approval token'); const signaturePart = parts.pop(); const body = parts.join('.'); let suppliedSignature;
50 - try { suppliedSignature = base64UrlToBytes(signaturePart); } catch { throw new Error('Invalid approval signature'); }
51 - const expectedSignature = (await this.#sign(ownerId, body)).slice(0, this.signatureBytes); if (!constantTimeEqual(suppliedSignature, expectedSignature)) throw new Error('Invalid approval signature or owner mismatch');
153 + this.#assertSecret();
154 + if (!token || typeof token !== 'string')
155 + throw new Error('Invalid approval token');
156 + const ownerId = String(expectations.ownerId ?? '');
157 + if (!ownerId) throw new Error('Approval owner is required');
158 + const parts = token.split('.');
159 + if (parts.length < 3) throw new Error('Invalid approval token');
160 + const signaturePart = parts.pop();
161 + const body = parts.join('.');
162 + let suppliedSignature;
163 + try {
164 + suppliedSignature = base64UrlToBytes(signaturePart);
165 + } catch {
166 + throw new Error('Invalid approval signature');
167 + }
168 + const expectedSignature = (await this.#sign(ownerId, body)).slice(
169 + 0,
170 + this.signatureBytes
171 + );
172 + if (!constantTimeEqual(suppliedSignature, expectedSignature))
173 + throw new Error('Invalid approval signature or owner mismatch');
174 let payload;
175 if (body.startsWith('s.m.') || body.startsWith('s.c.')) {
54 - const state = body.split('.'); if (state.length !== 4) throw new Error('Invalid approval payload'); const code = state[1]; const expiresAt = fromBase36Int(state[2]); const nonce = state[3]; if (expiresAt < this.now()) throw new Error('Approval token expired');
55 - if (!this.replayStore || typeof this.replayStore.peek !== 'function') throw new Error('Durable approval context storage is not configured');
56 - payload = await this.replayStore.peek({ ownerId, nonce }); if (!payload) throw new Error('Approval context is unavailable');
57 - const expectedAction = code === 'm' ? 'github.pull_request.merge' : code === 'c' ? 'cloudflare.worker.deploy_version' : '';
58 - if (!expectedAction || payload.expiresAt !== expiresAt || payload.nonce !== nonce || payload.ownerId !== ownerId || payload.actionId !== expectedAction) throw new Error('Approval context mismatch');
176 + const state = body.split('.');
177 + if (state.length !== 4) throw new Error('Invalid approval payload');
178 + const code = state[1];
179 + const expiresAt = fromBase36Int(state[2]);
180 + const nonce = state[3];
181 + if (expiresAt < this.now()) throw new Error('Approval token expired');
182 + if (!this.replayStore || typeof this.replayStore.peek !== 'function')
183 + throw new Error('Durable approval context storage is not configured');
184 + payload = await this.replayStore.peek({ ownerId, nonce });
185 + if (!payload) throw new Error('Approval context is unavailable');
186 + const expectedAction =
187 + code === 'm'
188 + ? 'github.pull_request.merge'
189 + : code === 'c'
190 + ? 'cloudflare.worker.deploy_version'
191 + : '';
192 + if (
193 + !expectedAction ||
194 + payload.expiresAt !== expiresAt ||
195 + payload.nonce !== nonce ||
196 + payload.ownerId !== ownerId ||
197 + payload.actionId !== expectedAction
198 + )
199 + throw new Error('Approval context mismatch');
200 } else payload = this.#decodeBody(body, ownerId);
60 - if (payload.expiresAt < this.now()) throw new Error('Approval token expired'); if (expectations.pluginId && payload.pluginId !== expectations.pluginId) throw new Error('Approval plugin mismatch'); if (expectations.actionId && payload.actionId !== expectations.actionId) throw new Error('Approval action mismatch'); if (expectations.risk && payload.risk !== expectations.risk) throw new Error('Approval risk mismatch'); return payload;
201 + if (payload.expiresAt < this.now())
202 + throw new Error('Approval token expired');
203 + if (expectations.pluginId && payload.pluginId !== expectations.pluginId)
204 + throw new Error('Approval plugin mismatch');
205 + if (expectations.actionId && payload.actionId !== expectations.actionId)
206 + throw new Error('Approval action mismatch');
207 + if (expectations.risk && payload.risk !== expectations.risk)
208 + throw new Error('Approval risk mismatch');
209 + return payload;
210 + }
211 + async consume(token, expectations = {}) {
212 + const payload = await this.verify(token, expectations);
213 + if (!this.isReplayProtected())
214 + throw new Error('Durable approval replay protection is not configured');
215 + const accepted = await this.replayStore.consume({
216 + ownerId: payload.ownerId,
217 + nonce: payload.nonce,
218 + expiresAt: payload.expiresAt
219 + });
220 + if (!accepted) throw new Error('Approval token already used');
221 + return payload;
222 + }
223 + #encodeBody(payload) {
224 + const codec = compactCodecFor(payload.actionId);
225 + const repoId = payload.input?.repoId;
226 + if (
227 + codec &&
228 + codec.pluginId === payload.pluginId &&
229 + codec.risk === payload.risk &&
230 + Number.isSafeInteger(Number(repoId))
231 + ) {
232 + let target;
233 + if (codec.target === 'run') {
234 + const runId = payload.input?.runId;
235 + if (!Number.isSafeInteger(Number(runId)))
236 + return `j.${textToBase64Url(JSON.stringify(payload))}`;
237 + target = toBase36Int(runId);
238 + } else if (codec.target === 'intent') {
239 + const intentId = String(payload.input?.intentId || '');
240 + if (!INTENT_ID_PATTERN.test(intentId))
241 + throw new Error('Invalid approval intent ID');
242 + target = intentId;
243 + } else return `j.${textToBase64Url(JSON.stringify(payload))}`;
244 + return [
245 + '1',
246 + codec.code,
247 + toBase36Int(repoId),
248 + target,
249 + toBase36Int(payload.expiresAt),
250 + payload.nonce
251 + ].join('.');
252 + }
253 + return `j.${textToBase64Url(JSON.stringify(payload))}`;
254 + }
255 + #decodeBody(body, ownerId) {
256 + if (body.startsWith('j.')) {
257 + let payload;
258 + try {
259 + payload = JSON.parse(base64UrlToText(body.slice(2)));
260 + } catch {
261 + throw new Error('Invalid approval payload');
262 + }
263 + if (String(payload.ownerId ?? '') !== ownerId)
264 + throw new Error('Approval owner mismatch');
265 + return payload;
266 + }
267 + const parts = body.split('.');
268 + if (parts.length !== 6 || parts[0] !== '1')
269 + throw new Error('Invalid approval payload');
270 + const [, code, repoPart, targetPart, expiryPart, nonce] = parts;
271 + const codec = compactCodecByCode(code);
272 + if (!codec) throw new Error('Invalid approval action');
273 + const expiresAt = fromBase36Int(expiryPart);
274 + const input = { repoId: fromBase36Int(repoPart) };
275 + if (codec.target === 'run') input.runId = fromBase36Int(targetPart);
276 + else if (codec.target === 'intent') {
277 + if (!INTENT_ID_PATTERN.test(targetPart))
278 + throw new Error('Invalid approval intent ID');
279 + input.intentId = targetPart;
280 + }
281 + return {
282 + v: 1,
283 + pluginId: codec.pluginId,
284 + actionId: codec.actionId,
285 + risk: codec.risk,
286 + ownerId,
287 + input,
288 + issuedAt: expiresAt - this.ttlMs,
289 + expiresAt,
290 + nonce
291 + };
292 + }
293 + async #sign(ownerId, body) {
294 + const key = await this.#key();
295 + const signature = await crypto.subtle.sign(
296 + 'HMAC',
297 + key,
298 + encoder.encode(`${SIGNING_DOMAIN}|${ownerId}|${body}`)
299 + );
300 + return new Uint8Array(signature);
301 + }
302 + async #key() {
303 + if (!this.keyPromise)
304 + this.keyPromise = crypto.subtle.importKey(
305 + 'raw',
306 + encoder.encode(this.secret),
307 + { name: 'HMAC', hash: 'SHA-256' },
308 + false,
309 + ['sign']
310 + );
311 + return this.keyPromise;
312 + }
313 + #nonce() {
314 + const bytes = new Uint8Array(6);
315 + crypto.getRandomValues(bytes);
316 + return bytesToBase64Url(bytes);
317 + }
318 + #assertSecret() {
319 + if (!this.secret) throw new Error('Approval signing secret is required');
320 }
62 - async consume(token, expectations = {}) { const payload = await this.verify(token, expectations); if (!this.isReplayProtected()) throw new Error('Durable approval replay protection is not configured'); const accepted = await this.replayStore.consume({ ownerId: payload.ownerId, nonce: payload.nonce, expiresAt: payload.expiresAt }); if (!accepted) throw new Error('Approval token already used'); return payload; }
63 - #encodeBody(payload) { const codec = compactCodecFor(payload.actionId); const repoId = payload.input?.repoId; if (codec && codec.pluginId === payload.pluginId && codec.risk === payload.risk && Number.isSafeInteger(Number(repoId))) { let target; if (codec.target === 'run') { const runId = payload.input?.runId; if (!Number.isSafeInteger(Number(runId))) return `j.${textToBase64Url(JSON.stringify(payload))}`; target = toBase36Int(runId); } else if (codec.target === 'intent') { const intentId = String(payload.input?.intentId || ''); if (!INTENT_ID_PATTERN.test(intentId)) throw new Error('Invalid approval intent ID'); target = intentId; } else return `j.${textToBase64Url(JSON.stringify(payload))}`; return ['1', codec.code, toBase36Int(repoId), target, toBase36Int(payload.expiresAt), payload.nonce].join('.'); } return `j.${textToBase64Url(JSON.stringify(payload))}`; }
64 - #decodeBody(body, ownerId) { if (body.startsWith('j.')) { let payload; try { payload = JSON.parse(base64UrlToText(body.slice(2))); } catch { throw new Error('Invalid approval payload'); } if (String(payload.ownerId ?? '') !== ownerId) throw new Error('Approval owner mismatch'); return payload; } const parts = body.split('.'); if (parts.length !== 6 || parts[0] !== '1') throw new Error('Invalid approval payload'); const [, code, repoPart, targetPart, expiryPart, nonce] = parts; const codec = compactCodecByCode(code); if (!codec) throw new Error('Invalid approval action'); const expiresAt = fromBase36Int(expiryPart); const input = { repoId: fromBase36Int(repoPart) }; if (codec.target === 'run') input.runId = fromBase36Int(targetPart); else if (codec.target === 'intent') { if (!INTENT_ID_PATTERN.test(targetPart)) throw new Error('Invalid approval intent ID'); input.intentId = targetPart; } return { v: 1, pluginId: codec.pluginId, actionId: codec.actionId, risk: codec.risk, ownerId, input, issuedAt: expiresAt - this.ttlMs, expiresAt, nonce }; }
65 - async #sign(ownerId, body) { const key = await this.#key(); const signature = await crypto.subtle.sign('HMAC', key, encoder.encode(`${SIGNING_DOMAIN}|${ownerId}|${body}`)); return new Uint8Array(signature); }
66 - async #key() { if (!this.keyPromise) this.keyPromise = crypto.subtle.importKey('raw', encoder.encode(this.secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']); return this.keyPromise; }
67 - #nonce() { const bytes = new Uint8Array(6); crypto.getRandomValues(bytes); return bytesToBase64Url(bytes); }
68 - #assertSecret() { if (!this.secret) throw new Error('Approval signing secret is required'); }
321 }
src/core/audit.js
+8 -4
@@ -8,10 +8,13 @@ function redactString(value, secrets) {
8
9 function sanitize(value, secrets) {
10 if (typeof value === 'string') return redactString(value, secrets);
11 - if (Array.isArray(value)) return value.map(item => sanitize(item, secrets));
11 + if (Array.isArray(value)) return value.map((item) => sanitize(item, secrets));
12 if (value && typeof value === 'object') {
13 return Object.fromEntries(
14 - Object.entries(value).map(([key, nested]) => [key, sanitize(nested, secrets)])
14 + Object.entries(value).map(([key, nested]) => [
15 + key,
16 + sanitize(nested, secrets)
17 + ])
18 );
19 }
20 return value;
@@ -19,8 +22,9 @@ function sanitize(value, secrets) {
22
23 export class AuditLogger {
24 constructor({ secrets = [], sink } = {}) {
22 - this.secrets = secrets.map(value => String(value || '')).filter(Boolean);
23 - this.sink = sink || (event => console.log('nexa_audit', JSON.stringify(event)));
25 + this.secrets = secrets.map((value) => String(value || '')).filter(Boolean);
26 + this.sink =
27 + sink || ((event) => console.log('nexa_audit', JSON.stringify(event)));
28 }
29
30 log(event) {
src/core/automation-runner.js
+65 -7
@@ -1,9 +1,67 @@
1 -import {transitionAutomation} from './automation.js';
2 -export class AutomationRunner{
3 - constructor({router,store,killSwitch=null}){this.router=router;this.store=store;this.killSwitch=killSwitch;}
4 - async advance(state){
5 - if(this.killSwitch&&await this.killSwitch.automationBlocked()){const next={...structuredClone(state),status:'paused_kill_switch',updatedAt:Date.now()};await this.store.put(next);return next;}
6 - const step=state.steps[state.cursor];if(!step)return state;const routed=await this.router.dispatchCallback(step.callback,{isOwner:true,ownerId:state.ownerId});if(!routed)throw new Error('Automation action unavailable');if(routed.killSwitchLocked){const next={...structuredClone(state),status:'paused_kill_switch',updatedAt:Date.now()};await this.store.put(next);return next;}if(routed.requiresApproval){const next=transitionAutomation(state,{type:'pause',intent:{pluginId:routed.pluginId,actionId:routed.actionId,risk:routed.risk,input:routed.approval?.input,callback:step.callback,key:step.key}});await this.store.put(next);return next;}const checkpoint=await this.store.put(state);const result=routed.execute?await routed.execute():routed;const next=transitionAutomation(checkpoint,{type:'complete_step',key:step.key});await this.store.put(next);return {...next,lastResult:result};
1 +import { transitionAutomation } from './automation.js';
2 +export class AutomationRunner {
3 + constructor({ router, store, killSwitch = null }) {
4 + this.router = router;
5 + this.store = store;
6 + this.killSwitch = killSwitch;
7 + }
8 + async advance(state) {
9 + if (this.killSwitch && (await this.killSwitch.automationBlocked())) {
10 + const next = {
11 + ...structuredClone(state),
12 + status: 'paused_kill_switch',
13 + updatedAt: Date.now()
14 + };
15 + await this.store.put(next);
16 + return next;
17 + }
18 + const step = state.steps[state.cursor];
19 + if (!step) return state;
20 + const routed = await this.router.dispatchCallback(step.callback, {
21 + isOwner: true,
22 + ownerId: state.ownerId
23 + });
24 + if (!routed) throw new Error('Automation action unavailable');
25 + if (routed.killSwitchLocked) {
26 + const next = {
27 + ...structuredClone(state),
28 + status: 'paused_kill_switch',
29 + updatedAt: Date.now()
30 + };
31 + await this.store.put(next);
32 + return next;
33 + }
34 + if (routed.requiresApproval) {
35 + const next = transitionAutomation(state, {
36 + type: 'pause',
37 + intent: {
38 + pluginId: routed.pluginId,
39 + actionId: routed.actionId,
40 + risk: routed.risk,
41 + input: routed.approval?.input,
42 + callback: step.callback,
43 + key: step.key
44 + }
45 + });
46 + await this.store.put(next);
47 + return next;
48 + }
49 + const checkpoint = await this.store.put(state);
50 + const result = routed.execute ? await routed.execute() : routed;
51 + const next = transitionAutomation(checkpoint, {
52 + type: 'complete_step',
53 + key: step.key
54 + });
55 + await this.store.put(next);
56 + return { ...next, lastResult: result };
57 + }
58 + async resume(state, { approval, key }) {
59 + if (this.killSwitch && (await this.killSwitch.automationBlocked()))
60 + throw new Error('Automation blocked by emergency kill switch');
61 + if (!approval || state.approvalIntent?.key !== key)
62 + throw new Error('Matching approval required');
63 + const resumed = transitionAutomation(state, { type: 'resume', key });
64 + await this.store.put(resumed);
65 + return resumed;
66 }
8 - async resume(state,{approval,key}){if(this.killSwitch&&await this.killSwitch.automationBlocked())throw new Error('Automation blocked by emergency kill switch');if(!approval||state.approvalIntent?.key!==key)throw new Error('Matching approval required');const resumed=transitionAutomation(state,{type:'resume',key});await this.store.put(resumed);return resumed;}
67 }
src/core/automation-store.js
+33 -1
@@ -1 +1,33 @@
1 -export class DurableAutomationStoreClient{constructor({namespace,ownerId}){this.namespace=namespace;this.ownerId=String(ownerId||'');}stub(id){if(!this.namespace||!this.ownerId)throw new Error('Automation store is not configured');return this.namespace.get(this.namespace.idFromName(`owner:${this.ownerId}:automation:${id}`));}async get(id){const r=await this.stub(id).fetch(`https://automation.local/?owner=${encodeURIComponent(this.ownerId)}&id=${encodeURIComponent(id)}`);if(r.status===404)return null;if(!r.ok)throw new Error('Automation read failed');return r.json();}async put(state){const r=await this.stub(state.id).fetch(`https://automation.local/?owner=${encodeURIComponent(this.ownerId)}&id=${encodeURIComponent(state.id)}`,{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(state)});if(!r.ok)throw new Error('Automation write failed');return r.json();}}
1 +export class DurableAutomationStoreClient {
2 + constructor({ namespace, ownerId }) {
3 + this.namespace = namespace;
4 + this.ownerId = String(ownerId || '');
5 + }
6 + stub(id) {
7 + if (!this.namespace || !this.ownerId)
8 + throw new Error('Automation store is not configured');
9 + return this.namespace.get(
10 + this.namespace.idFromName(`owner:${this.ownerId}:automation:${id}`)
11 + );
12 + }
13 + async get(id) {
14 + const r = await this.stub(id).fetch(
15 + `https://automation.local/?owner=${encodeURIComponent(this.ownerId)}&id=${encodeURIComponent(id)}`
16 + );
17 + if (r.status === 404) return null;
18 + if (!r.ok) throw new Error('Automation read failed');
19 + return r.json();
20 + }
21 + async put(state) {
22 + const r = await this.stub(state.id).fetch(
23 + `https://automation.local/?owner=${encodeURIComponent(this.ownerId)}&id=${encodeURIComponent(state.id)}`,
24 + {
25 + method: 'PUT',
26 + headers: { 'content-type': 'application/json' },
27 + body: JSON.stringify(state)
28 + }
29 + );
30 + if (!r.ok) throw new Error('Automation write failed');
31 + return r.json();
32 + }
33 +}
src/core/automation.js
+40 -2
@@ -1,2 +1,40 @@
1 -export const createAutomation=({id,ownerId,recipe,steps=[]})=>({version:1,id,ownerId:String(ownerId),recipe,status:'ready',cursor:0,steps,completedKeys:[],updatedAt:Date.now()});
2 -export function transitionAutomation(state,event={}){if(event.type==='inspect')return structuredClone(state);const s=structuredClone(state);if(['completed','cancelled','failed'].includes(s.status))throw new Error('Automation is terminal');if(event.type==='cancel'){s.status='cancelled';}else if(event.type==='fail'){s.status='failed';s.error=String(event.error||'failed');}else if(event.type==='pause'){s.status='awaiting_approval';s.approvalIntent=event.intent;}else if(event.type==='resume'){if(s.status!=='awaiting_approval')throw new Error('Automation is not awaiting approval');if(event.key&&s.completedKeys.includes(event.key))throw new Error('Automation step already executed');s.status='ready';delete s.approvalIntent;}else if(event.type==='complete_step'){if(event.key&&s.completedKeys.includes(event.key))return s;if(event.key)s.completedKeys.push(event.key);s.cursor++;s.status=s.cursor>=s.steps.length?'completed':'ready';}else throw new Error('Unsupported automation transition');s.updatedAt=Date.now();return s;}
1 +export const createAutomation = ({ id, ownerId, recipe, steps = [] }) => ({
2 + version: 1,
3 + id,
4 + ownerId: String(ownerId),
5 + recipe,
6 + status: 'ready',
7 + cursor: 0,
8 + steps,
9 + completedKeys: [],
10 + updatedAt: Date.now()
11 +});
12 +export function transitionAutomation(state, event = {}) {
13 + if (event.type === 'inspect') return structuredClone(state);
14 + const s = structuredClone(state);
15 + if (['completed', 'cancelled', 'failed'].includes(s.status))
16 + throw new Error('Automation is terminal');
17 + if (event.type === 'cancel') {
18 + s.status = 'cancelled';
19 + } else if (event.type === 'fail') {
20 + s.status = 'failed';
21 + s.error = String(event.error || 'failed');
22 + } else if (event.type === 'pause') {
23 + s.status = 'awaiting_approval';
24 + s.approvalIntent = event.intent;
25 + } else if (event.type === 'resume') {
26 + if (s.status !== 'awaiting_approval')
27 + throw new Error('Automation is not awaiting approval');
28 + if (event.key && s.completedKeys.includes(event.key))
29 + throw new Error('Automation step already executed');
30 + s.status = 'ready';
31 + delete s.approvalIntent;
32 + } else if (event.type === 'complete_step') {
33 + if (event.key && s.completedKeys.includes(event.key)) return s;
34 + if (event.key) s.completedKeys.push(event.key);
35 + s.cursor++;
36 + s.status = s.cursor >= s.steps.length ? 'completed' : 'ready';
37 + } else throw new Error('Unsupported automation transition');
38 + s.updatedAt = Date.now();
39 + return s;
40 +}
src/core/bounded-json.js
+19 -7
@@ -1,10 +1,15 @@
1 export async function readBoundedJson(request, maxBytes) {
2 - if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new RangeError('Invalid request body limit');
2 + if (!Number.isSafeInteger(maxBytes) || maxBytes < 1)
3 + throw new RangeError('Invalid request body limit');
4 const header = request.headers.get('content-length');
4 - if (header !== null && (!/^(0|[1-9][0-9]*)$/.test(header) || Number(header) > maxBytes)) {
5 + if (
6 + header !== null &&
7 + (!/^(0|[1-9][0-9]*)$/.test(header) || Number(header) > maxBytes)
8 + ) {
9 throw new RangeError('Editor request body is too large');
10 }
7 - if (!request.body) throw new SyntaxError('Editor request body must be valid JSON');
11 + if (!request.body)
12 + throw new SyntaxError('Editor request body must be valid JSON');
13 const reader = request.body.getReader();
14 const chunks = [];
15 let total = 0;
@@ -13,7 +18,8 @@ export async function readBoundedJson(request, maxBytes) {
18 const { done, value } = await reader.read();
19 if (done) break;
20 total += value.byteLength;
16 - if (total > maxBytes) throw new RangeError('Editor request body is too large');
21 + if (total > maxBytes)
22 + throw new RangeError('Editor request body is too large');
23 chunks.push(value);
24 }
25 } catch (error) {
@@ -24,7 +30,13 @@ export async function readBoundedJson(request, maxBytes) {
30 }
31 const bytes = new Uint8Array(total);
32 let offset = 0;
27 - for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
28 - try { return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); }
29 - catch { throw new SyntaxError('Editor request body must be valid JSON'); }
33 + for (const chunk of chunks) {
34 + bytes.set(chunk, offset);
35 + offset += chunk.byteLength;
36 + }
37 + try {
38 + return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
39 + } catch {
40 + throw new SyntaxError('Editor request body must be valid JSON');
41 + }
42 }
src/core/callback-failure-view.js
+82 -30
@@ -1,16 +1,19 @@
1 -const WORKSPACE_CALLBACK = /^(?:ws|wfile|wtext|wmsg|wdiff|wready|wcancel):([A-Za-z0-9_-]{10})$/;
1 +const WORKSPACE_CALLBACK =
2 + /^(?:ws|wfile|wtext|wmsg|wdiff|wready|wcancel):([A-Za-z0-9_-]{10})$/;
3 const WORKSPACE_ID = /^[A-Za-z0-9_-]{10}$/;
4 const INTENT_ID = /^[A-Za-z0-9_-]{8}$/;
5
5 -const escapeHtml = value => String(value ?? '')
6 - .replaceAll('&', '&amp;')
7 - .replaceAll('<', '&lt;')
8 - .replaceAll('>', '&gt;')
9 - .replaceAll('"', '&quot;');
6 +const escapeHtml = (value) =>
7 + String(value ?? '')
8 + .replaceAll('&', '&amp;')
9 + .replaceAll('<', '&lt;')
10 + .replaceAll('>', '&gt;')
11 + .replaceAll('"', '&quot;');
12
13 function legacyFailureView(data, error) {
14 const reason = String(error?.message || 'Provider read failed');
13 - const permissionDenied = /403|resource not accessible by personal access token/i.test(reason);
15 + const permissionDenied =
16 + /403|resource not accessible by personal access token/i.test(reason);
17 const repoMatch = String(data || '').match(/^[^:]+:(\d+)/);
18 const fallback = repoMatch ? `repo:${repoMatch[1]}` : 'menu:main';
19 const isIssues = String(data || '').startsWith('issues:');
@@ -21,18 +24,31 @@ function legacyFailureView(data, error) {
24 : 'دریافت اطلاعات از سرویس با خطا مواجه شد. هیچ تغییری انجام نشد.';
25
26 return {
24 - text:
25 -`⚠️ <b>دریافت اطلاعات با خطا مواجه شد</b>
27 + text: `⚠️ <b>دریافت اطلاعات با خطا مواجه شد</b>
28 ➖➖➖➖➖➖➖➖➖➖
29 ${detail}
30
31 این خطا هیچ عملیات تغییردهنده‌ای اجرا نکرد.`,
30 - reply_markup: { inline_keyboard: [[{ text: repoMatch ? '↩️ بازگشت به پروژه' : '↩️ منوی اصلی', callback_data: fallback }]] },
32 + reply_markup: {
33 + inline_keyboard: [
34 + [
35 + {
36 + text: repoMatch ? '↩️ بازگشت به پروژه' : '↩️ منوی اصلی',
37 + callback_data: fallback
38 + }
39 + ]
40 + ]
41 + },
42 validationError: false
43 };
44 }
45
35 -export async function buildCallbackFailureView({ data, error, ownerId, workspaces } = {}) {
46 +export async function buildCallbackFailureView({
47 + data,
48 + error,
49 + ownerId,
50 + workspaces
51 +} = {}) {
52 const callback = String(data || '');
53 const reason = String(error?.message || 'Provider read failed');
54 const match = callback.match(WORKSPACE_CALLBACK);
@@ -40,9 +56,16 @@ export async function buildCallbackFailureView({ data, error, ownerId, workspace
56
57 const workspaceId = match[1];
58 let workspace = null;
43 - if (ownerId !== undefined && ownerId !== null && typeof workspaces?.getWorkspace === 'function') {
59 + if (
60 + ownerId !== undefined &&
61 + ownerId !== null &&
62 + typeof workspaces?.getWorkspace === 'function'
63 + ) {
64 try {
45 - workspace = await workspaces.getWorkspace({ ownerId: String(ownerId), workspaceId });
65 + workspace = await workspaces.getWorkspace({
66 + ownerId: String(ownerId),
67 + workspaceId
68 + });
69 } catch {
70 // Recovery remains available even when durable context lookup itself fails.
71 }
@@ -51,9 +74,11 @@ export async function buildCallbackFailureView({ data, error, ownerId, workspace
74 const repoId = Number(workspace?.repoId);
75 const hasRepo = Number.isSafeInteger(repoId);
76 const missingCommitMessage = /^Commit message is required$/i.test(reason);
54 - const longCommitMessage = /^Commit message must be 120 characters or fewer$/i.test(reason);
77 + const longCommitMessage =
78 + /^Commit message must be 120 characters or fewer$/i.test(reason);
79 const noDraftChange = /^No draft change to commit$/i.test(reason);
56 - const validationError = missingCommitMessage || longCommitMessage || noDraftChange;
80 + const validationError =
81 + missingCommitMessage || longCommitMessage || noDraftChange;
82
83 let title = '⚠️ <b>عملیات Workspace متوقف شد</b>';
84 let detail = workspace
@@ -61,22 +86,30 @@ export async function buildCallbackFailureView({ data, error, ownerId, workspace
86 : 'عملیات متوقف شد. برای بازیابی وضعیت، دوباره تلاش کنید یا به منوی اصلی برگردید.';
87 if (missingCommitMessage) {
88 title = '✍️ <b>پیام Commit لازم است</b>';
64 - detail = 'قبل از «آماده Commit»، یک پیام Commit ثبت کنید. هیچ تغییری در GitHub انجام نشده است.';
89 + detail =
90 + 'قبل از «آماده Commit»، یک پیام Commit ثبت کنید. هیچ تغییری در GitHub انجام نشده است.';
91 } else if (longCommitMessage) {
92 title = '✍️ <b>پیام Commit بیش از حد طولانی است</b>';
67 - detail = 'پیام Commit باید حداکثر 120 کاراکتر باشد. هیچ تغییری در GitHub انجام نشده است.';
93 + detail =
94 + 'پیام Commit باید حداکثر 120 کاراکتر باشد. هیچ تغییری در GitHub انجام نشده است.';
95 } else if (noDraftChange) {
96 title = '📝 <b>تغییری برای Commit وجود ندارد</b>';
70 - detail = 'محتوای Draft با نسخهٔ اصلی یکسان است. ابتدا Draft را تغییر دهید؛ هیچ تغییری در GitHub انجام نشده است.';
97 + detail =
98 + 'محتوای Draft با نسخهٔ اصلی یکسان است. ابتدا Draft را تغییر دهید؛ هیچ تغییری در GitHub انجام نشده است.';
99 }
100
101 const rows = [];
102 if (missingCommitMessage || longCommitMessage) {
75 - rows.push([{ text: '✍️ ثبت پیام Commit', callback_data: `wmsg:${workspaceId}` }]);
103 + rows.push([
104 + { text: '✍️ ثبت پیام Commit', callback_data: `wmsg:${workspaceId}` }
105 + ]);
106 }
107 rows.push([{ text: '🔄 تلاش مجدد', callback_data: callback }]);
108 rows.push([{ text: '📝 ادامه Draft', callback_data: `ws:${workspaceId}` }]);
79 - if (hasRepo) rows.push([{ text: '📦 بازگشت به پروژه', callback_data: `repo:${repoId}` }]);
109 + if (hasRepo)
110 + rows.push([
111 + { text: '📦 بازگشت به پروژه', callback_data: `repo:${repoId}` }
112 + ]);
113 rows.push([{ text: '🏠 منوی اصلی', callback_data: 'menu:main' }]);
114
115 return {
@@ -86,12 +119,19 @@ export async function buildCallbackFailureView({ data, error, ownerId, workspace
119 };
120 }
121
89 -export async function buildApprovedActionFailedView({ payload, error, ownerId, workspaces } = {}) {
122 +export async function buildApprovedActionFailedView({
123 + payload,
124 + error,
125 + ownerId,
126 + workspaces
127 +} = {}) {
128 const reason = String(error?.message || 'GitHub operation failed');
91 - const permissionDenied = /403|resource not accessible by personal access token/i.test(reason);
129 + const permissionDenied =
130 + /403|resource not accessible by personal access token/i.test(reason);
131 const repoId = Number(payload?.input?.repoId);
132 const runId = Number(payload?.input?.runId);
94 - const workspaceAction = payload?.actionId === 'github.workspace.commit_branch';
133 + const workspaceAction =
134 + payload?.actionId === 'github.workspace.commit_branch';
135 const intentId = String(payload?.input?.intentId || '');
136
137 let workspaceId = '';
@@ -103,7 +143,10 @@ export async function buildApprovedActionFailedView({ payload, error, ownerId, w
143 typeof workspaces?.getIntent === 'function'
144 ) {
145 try {
106 - const intent = await workspaces.getIntent({ ownerId: String(ownerId), intentId });
146 + const intent = await workspaces.getIntent({
147 + ownerId: String(ownerId),
148 + intentId
149 + });
150 const candidate = String(intent?.workspaceId || '');
151 if (WORKSPACE_ID.test(candidate)) workspaceId = candidate;
152 } catch {
@@ -121,19 +164,28 @@ export async function buildApprovedActionFailedView({ payload, error, ownerId, w
164
165 const rows = [];
166 if (workspaceAction && workspaceId) {
124 - rows.push([{ text: '🔄 درخواست تأیید تازه', callback_data: `wready:${workspaceId}` }]);
167 + rows.push([
168 + { text: '🔄 درخواست تأیید تازه', callback_data: `wready:${workspaceId}` }
169 + ]);
170 rows.push([{ text: '📝 ادامه Draft', callback_data: `ws:${workspaceId}` }]);
126 - } else if (!workspaceAction && Number.isSafeInteger(repoId) && Number.isSafeInteger(runId)) {
127 - rows.push([{ text: '↩️ بازگشت به Run', callback_data: `run:${repoId}:${runId}` }]);
171 + } else if (
172 + !workspaceAction &&
173 + Number.isSafeInteger(repoId) &&
174 + Number.isSafeInteger(runId)
175 + ) {
176 + rows.push([
177 + { text: '↩️ بازگشت به Run', callback_data: `run:${repoId}:${runId}` }
178 + ]);
179 }
180 if (Number.isSafeInteger(repoId)) {
130 - rows.push([{ text: '📦 بازگشت به پروژه', callback_data: `repo:${repoId}` }]);
181 + rows.push([
182 + { text: '📦 بازگشت به پروژه', callback_data: `repo:${repoId}` }
183 + ]);
184 }
185 rows.push([{ text: '🏠 منوی اصلی', callback_data: 'menu:main' }]);
186
187 return {
135 - text:
136 -`⚠️ <b>اجرای عملیات در GitHub ناموفق بود</b>
188 + text: `⚠️ <b>اجرای عملیات در GitHub ناموفق بود</b>
189 ➖➖➖➖➖➖➖➖➖➖
190 ${detail}
191
src/core/cicd-control-plane.js
+30 -7
@@ -1,8 +1,17 @@
1 -const fullSha = value => /^[a-f0-9]{40}$/i.test(String(value || '')) ? String(value).toLowerCase() : '';
1 +const fullSha = (value) =>
2 + /^[a-f0-9]{40}$/i.test(String(value || ''))
3 + ? String(value).toLowerCase()
4 + : '';
5
3 -export function correlateDeliveryState({ targetSha, ci, deploy, runtime } = {}) {
6 +export function correlateDeliveryState({
7 + targetSha,
8 + ci,
9 + deploy,
10 + runtime
11 +} = {}) {
12 const target = fullSha(targetSha);
5 - if (!target || !ci || !deploy) return { state: 'unknown', reason: 'Delivery evidence is incomplete' };
13 + if (!target || !ci || !deploy)
14 + return { state: 'unknown', reason: 'Delivery evidence is incomplete' };
15
16 const ciSha = fullSha(ci.sha);
17 const deploySha = fullSha(deploy.sha);
@@ -12,8 +21,14 @@ export function correlateDeliveryState({ targetSha, ci, deploy, runtime } = {})
21
22 const ciState = String(ci.conclusion || ci.status || '');
23 const deployState = String(deploy.conclusion || deploy.status || '');
15 - if (['failure', 'cancelled', 'timed_out', 'action_required'].includes(ciState) ||
16 - ['failure', 'cancelled', 'timed_out', 'action_required'].includes(deployState)) {
24 + if (
25 + ['failure', 'cancelled', 'timed_out', 'action_required'].includes(
26 + ciState
27 + ) ||
28 + ['failure', 'cancelled', 'timed_out', 'action_required'].includes(
29 + deployState
30 + )
31 + ) {
32 return { state: 'failed', reason: 'CI or deploy failed' };
33 }
34 if (ci.status !== 'completed' || deploy.status !== 'completed') {
@@ -24,8 +39,16 @@ export function correlateDeliveryState({ targetSha, ci, deploy, runtime } = {})
39 }
40
41 const versions = runtime?.deployment?.versions;
27 - if (!Array.isArray(versions) || versions.length !== 1 || Number(versions[0]?.percentage) !== 100 || !versions[0]?.versionId) {
28 - return { state: 'mismatch', reason: 'Runtime traffic is not pinned to one verified version' };
42 + if (
43 + !Array.isArray(versions) ||
44 + versions.length !== 1 ||
45 + Number(versions[0]?.percentage) !== 100 ||
46 + !versions[0]?.versionId
47 + ) {
48 + return {
49 + state: 'mismatch',
50 + reason: 'Runtime traffic is not pinned to one verified version'
51 + };
52 }
53
54 return {
src/core/durable-replay-store.js
+97 -26
@@ -1,60 +1,131 @@
1 export class DurableApprovalReplayStore {
2 - constructor({ namespace } = {}) { this.namespace = namespace || null; }
3 - isConfigured() { return Boolean(this.namespace && typeof this.namespace.idFromName === 'function' && typeof this.namespace.get === 'function'); }
2 + constructor({ namespace } = {}) {
3 + this.namespace = namespace || null;
4 + }
5 + isConfigured() {
6 + return Boolean(
7 + this.namespace &&
8 + typeof this.namespace.idFromName === 'function' &&
9 + typeof this.namespace.get === 'function'
10 + );
11 + }
12 #stub(ownerId, nonce) {
5 - if (!this.isConfigured()) throw new Error('Durable approval replay protection is not configured');
6 - const owner = String(ownerId ?? ''); const nonceValue = String(nonce ?? '');
7 - if (!owner || !nonceValue) throw new Error('Invalid durable approval replay input');
8 - return this.namespace.get(this.namespace.idFromName(`${owner}:${nonceValue}`));
13 + if (!this.isConfigured())
14 + throw new Error('Durable approval replay protection is not configured');
15 + const owner = String(ownerId ?? '');
16 + const nonceValue = String(nonce ?? '');
17 + if (!owner || !nonceValue)
18 + throw new Error('Invalid durable approval replay input');
19 + return this.namespace.get(
20 + this.namespace.idFromName(`${owner}:${nonceValue}`)
21 + );
22 }
23 #secondFactorStub(ownerId) {
24 return this.#stub(ownerId, 'second-factor');
25 }
26 async put({ ownerId, nonce, expiresAt, payload } = {}) {
14 - const expiry = Number(expiresAt); if (!Number.isFinite(expiry) || !payload) throw new Error('Invalid durable approval replay input');
15 - const response = await this.#stub(ownerId, nonce).fetch(new Request('https://approval-replay/prepare', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ expiresAt: expiry, payload }) }));
16 - if (!response.ok) throw new Error(`Durable approval preparation failed (${response.status})`);
27 + const expiry = Number(expiresAt);
28 + if (!Number.isFinite(expiry) || !payload)
29 + throw new Error('Invalid durable approval replay input');
30 + const response = await this.#stub(ownerId, nonce).fetch(
31 + new Request('https://approval-replay/prepare', {
32 + method: 'POST',
33 + headers: { 'content-type': 'application/json' },
34 + body: JSON.stringify({ expiresAt: expiry, payload })
35 + })
36 + );
37 + if (!response.ok)
38 + throw new Error(
39 + `Durable approval preparation failed (${response.status})`
40 + );
41 return true;
42 }
43 async peek({ ownerId, nonce } = {}) {
20 - const response = await this.#stub(ownerId, nonce).fetch(new Request('https://approval-replay/peek'));
44 + const response = await this.#stub(ownerId, nonce).fetch(
45 + new Request('https://approval-replay/peek')
46 + );
47 if (!response.ok) return null;
22 - const body = await response.json().catch(() => null); return body?.payload || null;
48 + const body = await response.json().catch(() => null);
49 + return body?.payload || null;
50 }
51 async consume({ ownerId, nonce, expiresAt } = {}) {
25 - const expiry = Number(expiresAt); if (!Number.isFinite(expiry)) throw new Error('Invalid durable approval replay input');
26 - const response = await this.#stub(ownerId, nonce).fetch(new Request('https://approval-replay/consume', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ expiresAt: expiry }) }));
52 + const expiry = Number(expiresAt);
53 + if (!Number.isFinite(expiry))
54 + throw new Error('Invalid durable approval replay input');
55 + const response = await this.#stub(ownerId, nonce).fetch(
56 + new Request('https://approval-replay/consume', {
57 + method: 'POST',
58 + headers: { 'content-type': 'application/json' },
59 + body: JSON.stringify({ expiresAt: expiry })
60 + })
61 + );
62 const body = await response.json().catch(() => null);
63 if (response.status === 409 || response.status === 410) return false;
29 - if (!response.ok || body?.accepted !== true) throw new Error(`Durable approval replay protection failed (${response.status})`);
64 + if (!response.ok || body?.accepted !== true)
65 + throw new Error(
66 + `Durable approval replay protection failed (${response.status})`
67 + );
68 return true;
69 }
32 - async setSecondFactorPending({ ownerId, token, expiresAt, attempts = 0 } = {}) {
70 + async setSecondFactorPending({
71 + ownerId,
72 + token,
73 + expiresAt,
74 + attempts = 0
75 + } = {}) {
76 const expiry = Number(expiresAt);
77 const attemptCount = Number(attempts);
35 - if (!String(ownerId ?? '') || !String(token || '') || !Number.isFinite(expiry) || expiry < Date.now() || !Number.isSafeInteger(attemptCount) || attemptCount < 0) {
78 + if (
79 + !String(ownerId ?? '') ||
80 + !String(token || '') ||
81 + !Number.isFinite(expiry) ||
82 + expiry < Date.now() ||
83 + !Number.isSafeInteger(attemptCount) ||
84 + attemptCount < 0
85 + ) {
86 throw new Error('Invalid second-factor pending state');
87 }
38 - const response = await this.#secondFactorStub(ownerId).fetch(new Request('https://approval-replay/second-factor/put', {
39 - method: 'POST',
40 - headers: { 'content-type': 'application/json' },
41 - body: JSON.stringify({ token: String(token), expiresAt: expiry, attempts: attemptCount })
42 - }));
43 - if (!response.ok) throw new Error(`Durable second-factor state failed (${response.status})`);
88 + const response = await this.#secondFactorStub(ownerId).fetch(
89 + new Request('https://approval-replay/second-factor/put', {
90 + method: 'POST',
91 + headers: { 'content-type': 'application/json' },
92 + body: JSON.stringify({
93 + token: String(token),
94 + expiresAt: expiry,
95 + attempts: attemptCount
96 + })
97 + })
98 + );
99 + if (!response.ok)
100 + throw new Error(
101 + `Durable second-factor state failed (${response.status})`
102 + );
103 return true;
104 }
105 async getSecondFactorPending({ ownerId } = {}) {
106 if (!String(ownerId ?? '')) throw new Error('Invalid second-factor owner');
48 - const response = await this.#secondFactorStub(ownerId).fetch(new Request('https://approval-replay/second-factor/get'));
107 + const response = await this.#secondFactorStub(ownerId).fetch(
108 + new Request('https://approval-replay/second-factor/get')
109 + );
110 if (response.status === 404 || response.status === 410) return null;
50 - if (!response.ok) throw new Error(`Durable second-factor state failed (${response.status})`);
111 + if (!response.ok)
112 + throw new Error(
113 + `Durable second-factor state failed (${response.status})`
114 + );
115 const body = await response.json().catch(() => null);
116 return body?.pending || null;
117 }
118 async clearSecondFactorPending({ ownerId } = {}) {
119 if (!String(ownerId ?? '')) throw new Error('Invalid second-factor owner');
56 - const response = await this.#secondFactorStub(ownerId).fetch(new Request('https://approval-replay/second-factor/clear', { method: 'POST' }));
57 - if (!response.ok) throw new Error(`Durable second-factor clear failed (${response.status})`);
120 + const response = await this.#secondFactorStub(ownerId).fetch(
121 + new Request('https://approval-replay/second-factor/clear', {
122 + method: 'POST'
123 + })
124 + );
125 + if (!response.ok)
126 + throw new Error(
127 + `Durable second-factor clear failed (${response.status})`
128 + );
129 return true;
130 }
131 }
src/core/final-delivery.js
+66 -12
@@ -1,25 +1,79 @@
1 const DELIVERY_ROWS = Object.freeze([
2 - { id: 16, key: 'release', title: 'Release integrity', required: ['mainSha', 'ciSuccess', 'deploySuccess'] },
3 - { id: 17, key: 'runtime', title: 'Runtime verification', required: ['deployedShaMatchesMain', 'runtimeHealthy'] },
4 - { id: 18, key: 'rollback', title: 'Rollback readiness', required: ['knownGoodVersion', 'rollbackDocumented'] },
5 - { id: 19, key: 'operations', title: 'Operations handoff', required: ['runbookPresent', 'securityInvariantsPresent', 'monitoringPathPresent'] },
6 - { id: 20, key: 'acceptance', title: 'Final acceptance', required: ['allTestsGreen', 'noOpenCriticalBlocker', 'evidenceRecorded'] }
2 + {
3 + id: 16,
4 + key: 'release',
5 + title: 'Release integrity',
6 + required: ['mainSha', 'ciSuccess', 'deploySuccess']
7 + },
8 + {
9 + id: 17,
10 + key: 'runtime',
11 + title: 'Runtime verification',
12 + required: ['deployedShaMatchesMain', 'runtimeHealthy']
13 + },
14 + {
15 + id: 18,
16 + key: 'rollback',
17 + title: 'Rollback readiness',
18 + required: ['knownGoodVersion', 'rollbackDocumented']
19 + },
20 + {
21 + id: 19,
22 + key: 'operations',
23 + title: 'Operations handoff',
24 + required: [
25 + 'runbookPresent',
26 + 'securityInvariantsPresent',
27 + 'monitoringPathPresent'
28 + ]
29 + },
30 + {
31 + id: 20,
32 + key: 'acceptance',
33 + title: 'Final acceptance',
34 + required: ['allTestsGreen', 'noOpenCriticalBlocker', 'evidenceRecorded']
35 + }
36 ]);
37
38 export function getFinalDeliveryRows() {
10 - return DELIVERY_ROWS.map(row => ({ ...row, required: [...row.required] }));
39 + return DELIVERY_ROWS.map((row) => ({ ...row, required: [...row.required] }));
40 }
41
42 export function evaluateFinalDelivery(evidence = {}) {
14 - const rows = DELIVERY_ROWS.map(row => {
15 - const missing = row.required.filter(key => evidence[key] !== true && !(key === 'mainSha' && typeof evidence[key] === 'string' && evidence[key].length >= 7) && !(key === 'knownGoodVersion' && typeof evidence[key] === 'string' && evidence[key].length > 0));
16 - return { id: row.id, key: row.key, title: row.title, complete: missing.length === 0, missing };
43 + const rows = DELIVERY_ROWS.map((row) => {
44 + const missing = row.required.filter(
45 + (key) =>
46 + evidence[key] !== true &&
47 + !(
48 + key === 'mainSha' &&
49 + typeof evidence[key] === 'string' &&
50 + evidence[key].length >= 7
51 + ) &&
52 + !(
53 + key === 'knownGoodVersion' &&
54 + typeof evidence[key] === 'string' &&
55 + evidence[key].length > 0
56 + )
57 + );
58 + return {
59 + id: row.id,
60 + key: row.key,
61 + title: row.title,
62 + complete: missing.length === 0,
63 + missing
64 + };
65 });
18 - return { complete: rows.every(row => row.complete), rows };
66 + return { complete: rows.every((row) => row.complete), rows };
67 }
68
69 export function renderFinalDeliverySummary(evidence = {}) {
70 const report = evaluateFinalDelivery(evidence);
23 - const lines = report.rows.map(row => `${row.complete ? '✅' : '⛔'} ${row.id}. ${row.title}${row.complete ? '' : ` — missing: ${row.missing.join(', ')}`}`);
24 - return [`Final delivery: ${report.complete ? 'ACCEPTED' : 'BLOCKED'}`, ...lines].join('\n');
71 + const lines = report.rows.map(
72 + (row) =>
73 + `${row.complete ? '✅' : '⛔'} ${row.id}. ${row.title}${row.complete ? '' : ` — missing: ${row.missing.join(', ')}`}`
74 + );
75 + return [
76 + `Final delivery: ${report.complete ? 'ACCEPTED' : 'BLOCKED'}`,
77 + ...lines
78 + ].join('\n');
79 }
src/core/incident-store.js
+37 -1
@@ -1 +1,37 @@
1 -export class DurableIncidentStoreClient { constructor({namespace,ownerId}){this.namespace=namespace;this.ownerId=String(ownerId||'');} stub(){if(!this.namespace||!this.ownerId)throw new Error('Incident store is not configured');return this.namespace.get(this.namespace.idFromName('owner:'+this.ownerId));} async request(path,body){const r=await this.stub().fetch('https://incident.local'+path+'?owner='+encodeURIComponent(this.ownerId),{method:body?'POST':'GET',headers:{'content-type':'application/json'},body:body?JSON.stringify(body):undefined});if(!r.ok)throw new Error('Incident store request failed');return r.json();} list(){return this.request('/');} upsert(e){return this.request('/upsert',e);} resolve(id){return this.request('/resolve',{id});} }
1 +export class DurableIncidentStoreClient {
2 + constructor({ namespace, ownerId }) {
3 + this.namespace = namespace;
4 + this.ownerId = String(ownerId || '');
5 + }
6 + stub() {
7 + if (!this.namespace || !this.ownerId)
8 + throw new Error('Incident store is not configured');
9 + return this.namespace.get(
10 + this.namespace.idFromName('owner:' + this.ownerId)
11 + );
12 + }
13 + async request(path, body) {
14 + const r = await this.stub().fetch(
15 + 'https://incident.local' +
16 + path +
17 + '?owner=' +
18 + encodeURIComponent(this.ownerId),
19 + {
20 + method: body ? 'POST' : 'GET',
21 + headers: { 'content-type': 'application/json' },
22 + body: body ? JSON.stringify(body) : undefined
23 + }
24 + );
25 + if (!r.ok) throw new Error('Incident store request failed');
26 + return r.json();
27 + }
28 + list() {
29 + return this.request('/');
30 + }
31 + upsert(e) {
32 + return this.request('/upsert', e);
33 + }
34 + resolve(id) {
35 + return this.request('/resolve', { id });
36 + }
37 +}
src/core/incidents.js
+40 -4
@@ -1,5 +1,41 @@
1 const SECRET = /(token|secret|password|authorization|api[_-]?key)=?[^\s&]*/gi;
2 -export const redactIncidentText = value => String(value ?? '').replace(SECRET, '$1=[REDACTED]').replace(/https?:\/\/[^\s?]+\?[^\s]*/gi, m => m.split('?')[0] + '?[REDACTED]');
3 -export const incidentFingerprint = ({ provider='', repo='', sha='', kind='' }={}) => [provider,repo,sha,kind].map(v=>String(v).trim().toLowerCase()).join('|');
4 -export const incidentSeverity = evidence => evidence?.runtimeMismatch || evidence?.deployFailure ? 'critical' : evidence?.ciFailure ? 'high' : 'medium';
5 -export function normalizeIncident(input={}) { const fingerprint=incidentFingerprint(input); if(!fingerprint.replaceAll('|','')) throw new Error('Incident evidence is required'); return { fingerprint, provider:String(input.provider||''), repo:String(input.repo||''), sha:String(input.sha||''), kind:String(input.kind||''), severity:incidentSeverity(input), summary:redactIncidentText(input.summary||input.kind||'Operational incident'), evidenceRef:redactIncidentText(input.evidenceRef||''), status:'open' }; }
2 +export const redactIncidentText = (value) =>
3 + String(value ?? '')
4 + .replace(SECRET, '$1=[REDACTED]')
5 + .replace(
6 + /https?:\/\/[^\s?]+\?[^\s]*/gi,
7 + (m) => m.split('?')[0] + '?[REDACTED]'
8 + );
9 +export const incidentFingerprint = ({
10 + provider = '',
11 + repo = '',
12 + sha = '',
13 + kind = ''
14 +} = {}) =>
15 + [provider, repo, sha, kind]
16 + .map((v) => String(v).trim().toLowerCase())
17 + .join('|');
18 +export const incidentSeverity = (evidence) =>
19 + evidence?.runtimeMismatch || evidence?.deployFailure
20 + ? 'critical'
21 + : evidence?.ciFailure
22 + ? 'high'
23 + : 'medium';
24 +export function normalizeIncident(input = {}) {
25 + const fingerprint = incidentFingerprint(input);
26 + if (!fingerprint.replaceAll('|', ''))
27 + throw new Error('Incident evidence is required');
28 + return {
29 + fingerprint,
30 + provider: String(input.provider || ''),
31 + repo: String(input.repo || ''),
32 + sha: String(input.sha || ''),
33 + kind: String(input.kind || ''),
34 + severity: incidentSeverity(input),
35 + summary: redactIncidentText(
36 + input.summary || input.kind || 'Operational incident'
37 + ),
38 + evidenceRef: redactIncidentText(input.evidenceRef || ''),
39 + status: 'open'
40 + };
41 +}
src/core/kill-switch-store.js
+30 -8
@@ -1,18 +1,40 @@
1 export class DurableKillSwitchStoreClient {
2 - constructor({ namespace } = {}) { this.namespace = namespace || null; }
3 - isConfigured() { return Boolean(this.namespace && typeof this.namespace.idFromName === 'function' && typeof this.namespace.get === 'function'); }
2 + constructor({ namespace } = {}) {
3 + this.namespace = namespace || null;
4 + }
5 + isConfigured() {
6 + return Boolean(
7 + this.namespace &&
8 + typeof this.namespace.idFromName === 'function' &&
9 + typeof this.namespace.get === 'function'
10 + );
11 + }
12 #stub() {
5 - if (!this.isConfigured()) throw new Error('Kill switch durable store is not configured');
6 - return this.namespace.get(this.namespace.idFromName('global-emergency-kill-switch'));
13 + if (!this.isConfigured())
14 + throw new Error('Kill switch durable store is not configured');
15 + return this.namespace.get(
16 + this.namespace.idFromName('global-emergency-kill-switch')
17 + );
18 }
19 async get() {
9 - const response = await this.#stub().fetch('https://kill-switch.local/state');
10 - if (!response.ok) throw new Error(`Kill switch read failed (${response.status})`);
20 + const response = await this.#stub().fetch(
21 + 'https://kill-switch.local/state'
22 + );
23 + if (!response.ok)
24 + throw new Error(`Kill switch read failed (${response.status})`);
25 return response.json();
26 }
27 async set(state) {
14 - const response = await this.#stub().fetch('https://kill-switch.local/state', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(state) });
15 - if (!response.ok) throw new Error(`Kill switch write failed (${response.status})`);
28 + const response = await this.#stub().fetch(
29 + 'https://kill-switch.local/state',
30 + {
31 + method: 'PUT',
32 + headers: { 'content-type': 'application/json' },
33 + body: JSON.stringify(state)
34 + }
35 + );
36 + if (!response.ok)
37 + throw new Error(`Kill switch write failed (${response.status})`);
38 return response.json();
39 }
40 }
src/core/kill-switch.js
+41 -7
@@ -1,12 +1,46 @@
1 export class KillSwitch {
2 constructor({ store } = {}) {
3 - if (!store || typeof store.get !== 'function') throw new Error('Kill switch store is required');
3 + if (!store || typeof store.get !== 'function')
4 + throw new Error('Kill switch store is required');
5 this.store = store;
6 }
6 - async status(){const state=await this.store.get();if(!state||!['NORMAL','LOCKED'].includes(state.mode))throw new Error('Kill switch state is unavailable');return state;}
7 - async blocks(risk){if(!['WRITE','DESTRUCTIVE'].includes(String(risk||'')))return false;try{return(await this.status()).mode!=='NORMAL';}catch{return true;}}
8 - async automationBlocked(){try{return(await this.status()).mode!=='NORMAL';}catch{return true;}}
9 - async lock(context={}){this.#assertControl(context);if(typeof this.store.set!=='function')throw new Error('Kill switch store is not writable');return this.store.set({mode:'LOCKED',changedAt:Date.now()});}
10 - async unlock(context={}){this.#assertControl(context);if(typeof this.store.set!=='function')throw new Error('Kill switch store is not writable');return this.store.set({mode:'NORMAL',changedAt:Date.now()});}
11 - #assertControl(context){if(context.isOwner!==true)throw new Error('Kill switch control requires owner');if(context.approved!==true)throw new Error('Kill switch control requires approval');}
7 + async status() {
8 + const state = await this.store.get();
9 + if (!state || !['NORMAL', 'LOCKED'].includes(state.mode))
10 + throw new Error('Kill switch state is unavailable');
11 + return state;
12 + }
13 + async blocks(risk) {
14 + if (!['WRITE', 'DESTRUCTIVE'].includes(String(risk || ''))) return false;
15 + try {
16 + return (await this.status()).mode !== 'NORMAL';
17 + } catch {
18 + return true;
19 + }
20 + }
21 + async automationBlocked() {
22 + try {
23 + return (await this.status()).mode !== 'NORMAL';
24 + } catch {
25 + return true;
26 + }
27 + }
28 + async lock(context = {}) {
29 + this.#assertControl(context);
30 + if (typeof this.store.set !== 'function')
31 + throw new Error('Kill switch store is not writable');
32 + return this.store.set({ mode: 'LOCKED', changedAt: Date.now() });
33 + }
34 + async unlock(context = {}) {
35 + this.#assertControl(context);
36 + if (typeof this.store.set !== 'function')
37 + throw new Error('Kill switch store is not writable');
38 + return this.store.set({ mode: 'NORMAL', changedAt: Date.now() });
39 + }
40 + #assertControl(context) {
41 + if (context.isOwner !== true)
42 + throw new Error('Kill switch control requires owner');
43 + if (context.approved !== true)
44 + throw new Error('Kill switch control requires approval');
45 + }
46 }
src/core/platform-experience.js
+98 -12
@@ -1,13 +1,99 @@
1 -const clean=v=>String(v??'').replace(/(token|secret|password|authorization|api[_-]?key)\s*[:=]\s*\S+/gi,'$1=[REDACTED]');
2 -export const UX_CAPABILITIES=Object.freeze([
3 - {id:8,key:'copilot',title:'Developer Copilot',mode:'READ_ASSIST'},
4 - {id:9,key:'browser_qa',title:'Browser QA',mode:'EVIDENCE_ONLY'},
5 - {id:10,key:'plugin_catalog',title:'Plugin Catalog',mode:'POLICY_BOUND'},
6 - {id:11,key:'portfolio',title:'Multi-project Portfolio',mode:'OWNER_SCOPED'},
7 - {id:12,key:'command_center',title:'Unified Command Center',mode:'NAVIGATION'}
1 +const clean = (v) =>
2 + String(v ?? '').replace(
3 + /(token|secret|password|authorization|api[_-]?key)\s*[:=]\s*\S+/gi,
4 + '$1=[REDACTED]'
5 + );
6 +export const UX_CAPABILITIES = Object.freeze([
7 + { id: 8, key: 'copilot', title: 'Developer Copilot', mode: 'READ_ASSIST' },
8 + { id: 9, key: 'browser_qa', title: 'Browser QA', mode: 'EVIDENCE_ONLY' },
9 + {
10 + id: 10,
11 + key: 'plugin_catalog',
12 + title: 'Plugin Catalog',
13 + mode: 'POLICY_BOUND'
14 + },
15 + {
16 + id: 11,
17 + key: 'portfolio',
18 + title: 'Multi-project Portfolio',
19 + mode: 'OWNER_SCOPED'
20 + },
21 + {
22 + id: 12,
23 + key: 'command_center',
24 + title: 'Unified Command Center',
25 + mode: 'NAVIGATION'
26 + }
27 ]);
9 -export function buildCopilotBrief({goal='',evidence=[]}={}){const safe=evidence.slice(0,12).map(x=>clean(x)).filter(Boolean);return{goal:clean(goal).slice(0,500),evidence:safe,recommendations:safe.length?['Review source-backed evidence','Choose a policy-declared action','Use Safe Approval for mutation']:['Collect source-backed evidence before recommending mutation'],canMutate:false};}
10 -export function evaluateBrowserQa(checks=[]){const normalized=checks.slice(0,50).map((c,i)=>({id:String(c.id??i),label:clean(c.label||`check ${i+1}`),status:['pass','fail','blocked'].includes(c.status)?c.status:'blocked',evidence:clean(c.evidence||'').slice(0,500)}));return{status:normalized.some(x=>x.status==='fail')?'failed':normalized.some(x=>x.status==='blocked')?'blocked':'passed',checks:normalized,sourceBacked:normalized.every(x=>x.status==='blocked'||Boolean(x.evidence))};}
11 -export function buildPluginCatalog(manifests=[]){return manifests.map(m=>({id:String(m.id),name:clean(m.name||m.id),actions:(m.actions||[]).map(a=>({id:String(a.id),risk:String(a.risk||'READ')}))})).sort((a,b)=>a.id.localeCompare(b.id));}
12 -export function buildPortfolio(projects=[]){return projects.slice(0,50).map(p=>({id:String(p.id),name:clean(p.name),provider:clean(p.provider||'github'),status:['healthy','attention','unknown'].includes(p.status)?p.status:'unknown'}));}
13 -export function searchCommandCenter(query,items=[]){const q=String(query||'').trim().toLocaleLowerCase();if(!q)return items.slice(0,12);return items.filter(x=>`${x.title||''} ${x.keywords||''}`.toLocaleLowerCase().includes(q)).slice(0,12);}
28 +export function buildCopilotBrief({ goal = '', evidence = [] } = {}) {
29 + const safe = evidence
30 + .slice(0, 12)
31 + .map((x) => clean(x))
32 + .filter(Boolean);
33 + return {
34 + goal: clean(goal).slice(0, 500),
35 + evidence: safe,
36 + recommendations: safe.length
37 + ? [
38 + 'Review source-backed evidence',
39 + 'Choose a policy-declared action',
40 + 'Use Safe Approval for mutation'
41 + ]
42 + : ['Collect source-backed evidence before recommending mutation'],
43 + canMutate: false
44 + };
45 +}
46 +export function evaluateBrowserQa(checks = []) {
47 + const normalized = checks.slice(0, 50).map((c, i) => ({
48 + id: String(c.id ?? i),
49 + label: clean(c.label || `check ${i + 1}`),
50 + status: ['pass', 'fail', 'blocked'].includes(c.status)
51 + ? c.status
52 + : 'blocked',
53 + evidence: clean(c.evidence || '').slice(0, 500)
54 + }));
55 + return {
56 + status: normalized.some((x) => x.status === 'fail')
57 + ? 'failed'
58 + : normalized.some((x) => x.status === 'blocked')
59 + ? 'blocked'
60 + : 'passed',
61 + checks: normalized,
62 + sourceBacked: normalized.every(
63 + (x) => x.status === 'blocked' || Boolean(x.evidence)
64 + )
65 + };
66 +}
67 +export function buildPluginCatalog(manifests = []) {
68 + return manifests
69 + .map((m) => ({
70 + id: String(m.id),
71 + name: clean(m.name || m.id),
72 + actions: (m.actions || []).map((a) => ({
73 + id: String(a.id),
74 + risk: String(a.risk || 'READ')
75 + }))
76 + }))
77 + .sort((a, b) => a.id.localeCompare(b.id));
78 +}
79 +export function buildPortfolio(projects = []) {
80 + return projects.slice(0, 50).map((p) => ({
81 + id: String(p.id),
82 + name: clean(p.name),
83 + provider: clean(p.provider || 'github'),
84 + status: ['healthy', 'attention', 'unknown'].includes(p.status)
85 + ? p.status
86 + : 'unknown'
87 + }));
88 +}
89 +export function searchCommandCenter(query, items = []) {
90 + const q = String(query || '')
91 + .trim()
92 + .toLocaleLowerCase();
93 + if (!q) return items.slice(0, 12);
94 + return items
95 + .filter((x) =>
96 + `${x.title || ''} ${x.keywords || ''}`.toLocaleLowerCase().includes(q)
97 + )
98 + .slice(0, 12);
99 +}
src/core/plugin-registry.js
+10 -5
@@ -26,7 +26,9 @@ export class PluginRegistry {
26 throw new Error(`Duplicate action id: ${actionId}`);
27 }
28 if (!ALLOWED_RISKS.has(descriptor?.risk)) {
29 - throw new Error(`Invalid action risk for ${actionId}: ${descriptor?.risk}`);
29 + throw new Error(
30 + `Invalid action risk for ${actionId}: ${descriptor?.risk}`
31 + );
32 }
33 }
34
@@ -34,11 +36,14 @@ export class PluginRegistry {
36 this.pluginsById.set(pluginId, plugin);
37
38 for (const [actionId, descriptor] of Object.entries(actions)) {
37 - this.actionsById.set(actionId, Object.freeze({
38 - pluginId,
39 + this.actionsById.set(
40 actionId,
40 - risk: descriptor.risk
41 - }));
41 + Object.freeze({
42 + pluginId,
43 + actionId,
44 + risk: descriptor.risk
45 + })
46 + );
47 }
48 }
49
src/core/router.js
+154 -4
@@ -1,4 +1,154 @@
1 -const AUDIT_METADATA_KEYS=Object.freeze(new Set(['repoId','workspaceId','intentId','path','contentDigest','commitMessageDigest','baseHeadSha','targetBranch','commitSha','branch','idempotent']));
2 -function sanitizeAuditMetadata(value){if(!value||typeof value!=='object'||Array.isArray(value))return{};const safe={};for(const[key,raw]of Object.entries(value)){if(!AUDIT_METADATA_KEYS.has(key))continue;if(typeof raw==='number'&&Number.isSafeInteger(raw)){safe[key]=raw;continue;}if(typeof raw==='boolean'){safe[key]=raw;continue;}if(typeof raw==='string')safe[key]=raw.slice(0,240);}return safe;}
3 -function withoutAuditMetadata(result){if(!result||typeof result!=='object'||Array.isArray(result)||!Object.hasOwn(result,'audit'))return result;const{audit,...publicResult}=result;return publicResult;}
4 -export class PluginRouter{constructor({registry,policy,audit,killSwitch=null}={}){if(!registry)throw new Error('PluginRouter registry is required');if(!policy)throw new Error('PluginRouter policy is required');if(!audit)throw new Error('PluginRouter audit logger is required');this.registry=registry;this.policy=policy;this.audit=audit;this.killSwitch=killSwitch;}async dispatchCommand(command,context={}){return this.#dispatch('resolveCommand',command,context);}async dispatchCallback(data,context={}){return this.#dispatch('resolveCallback',data,context);}async dispatchMessage(payload,context={}){return this.#dispatch('resolveMessage',payload,context);}async #dispatch(resolverName,input,context){for(const plugin of this.registry.getPlugins()){const resolver=plugin?.[resolverName];if(typeof resolver!=='function')continue;const route=await resolver.call(plugin,input,context);if(!route)continue;const pluginId=plugin.manifest.id;const actionId=route.actionId;const registeredAction=this.registry.getAction(actionId);const action=registeredAction?.pluginId===pluginId?registeredAction:null;const decision=this.policy.evaluate({action,isOwner:context.isOwner===true,approved:context.approved===true});const routeAudit=sanitizeAuditMetadata(route.audit);this.audit.log({event:'action_attempt',pluginId,actionId,risk:decision.risk,outcome:decision.allowed?'allowed':(decision.requiresApproval?'approval_required':'denied'),reason:decision.reason,...routeAudit});if(!decision.allowed)return{ok:false,pluginId,actionId,risk:decision.risk,requiresApproval:decision.requiresApproval,denied:!decision.requiresApproval,reason:decision.reason,approval:route.approval||null};if(this.killSwitch&&await this.killSwitch.blocks(decision.risk)){this.audit.log({event:'kill_switch_block',pluginId,actionId,risk:decision.risk,outcome:'denied'});return{ok:false,pluginId,actionId,risk:decision.risk,requiresApproval:false,denied:true,killSwitchLocked:true,reason:'Emergency kill switch is locked'};}if(typeof route.execute!=='function')throw new Error(`Plugin route execute function is required for ${actionId}`);try{const result=await route.execute();this.audit.log({event:'action_result',pluginId,actionId,risk:decision.risk,outcome:'success',...routeAudit,...sanitizeAuditMetadata(result?.audit)});return withoutAuditMetadata(result);}catch(error){this.audit.log({event:'action_result',pluginId,actionId,risk:decision.risk,outcome:'error',error:error?.message||'Unknown plugin error',...routeAudit});throw error;}}return null;}}
1 +const AUDIT_METADATA_KEYS = Object.freeze(
2 + new Set([
3 + 'repoId',
4 + 'workspaceId',
5 + 'intentId',
6 + 'path',
7 + 'contentDigest',
8 + 'commitMessageDigest',
9 + 'baseHeadSha',
10 + 'targetBranch',
11 + 'commitSha',
12 + 'branch',
13 + 'idempotent'
14 + ])
15 +);
16 +function sanitizeAuditMetadata(value) {
17 + if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
18 + const safe = {};
19 + for (const [key, raw] of Object.entries(value)) {
20 + if (!AUDIT_METADATA_KEYS.has(key)) continue;
21 + if (typeof raw === 'number' && Number.isSafeInteger(raw)) {
22 + safe[key] = raw;
23 + continue;
24 + }
25 + if (typeof raw === 'boolean') {
26 + safe[key] = raw;
27 + continue;
28 + }
29 + if (typeof raw === 'string') safe[key] = raw.slice(0, 240);
30 + }
31 + return safe;
32 +}
33 +function withoutAuditMetadata(result) {
34 + if (
35 + !result ||
36 + typeof result !== 'object' ||
37 + Array.isArray(result) ||
38 + !Object.hasOwn(result, 'audit')
39 + )
40 + return result;
41 + const { audit, ...publicResult } = result;
42 + return publicResult;
43 +}
44 +export class PluginRouter {
45 + constructor({ registry, policy, audit, killSwitch = null } = {}) {
46 + if (!registry) throw new Error('PluginRouter registry is required');
47 + if (!policy) throw new Error('PluginRouter policy is required');
48 + if (!audit) throw new Error('PluginRouter audit logger is required');
49 + this.registry = registry;
50 + this.policy = policy;
51 + this.audit = audit;
52 + this.killSwitch = killSwitch;
53 + }
54 + async dispatchCommand(command, context = {}) {
55 + return this.#dispatch('resolveCommand', command, context);
56 + }
57 + async dispatchCallback(data, context = {}) {
58 + return this.#dispatch('resolveCallback', data, context);
59 + }
60 + async dispatchMessage(payload, context = {}) {
61 + return this.#dispatch('resolveMessage', payload, context);
62 + }
63 + async #dispatch(resolverName, input, context) {
64 + for (const plugin of this.registry.getPlugins()) {
65 + const resolver = plugin?.[resolverName];
66 + if (typeof resolver !== 'function') continue;
67 + const route = await resolver.call(plugin, input, context);
68 + if (!route) continue;
69 + const pluginId = plugin.manifest.id;
70 + const actionId = route.actionId;
71 + const registeredAction = this.registry.getAction(actionId);
72 + const action =
73 + registeredAction?.pluginId === pluginId ? registeredAction : null;
74 + const decision = this.policy.evaluate({
75 + action,
76 + isOwner: context.isOwner === true,
77 + approved: context.approved === true
78 + });
79 + const routeAudit = sanitizeAuditMetadata(route.audit);
80 + this.audit.log({
81 + event: 'action_attempt',
82 + pluginId,
83 + actionId,
84 + risk: decision.risk,
85 + outcome: decision.allowed
86 + ? 'allowed'
87 + : decision.requiresApproval
88 + ? 'approval_required'
89 + : 'denied',
90 + reason: decision.reason,
91 + ...routeAudit
92 + });
93 + if (!decision.allowed)
94 + return {
95 + ok: false,
96 + pluginId,
97 + actionId,
98 + risk: decision.risk,
99 + requiresApproval: decision.requiresApproval,
100 + denied: !decision.requiresApproval,
101 + reason: decision.reason,
102 + approval: route.approval || null
103 + };
104 + if (this.killSwitch && (await this.killSwitch.blocks(decision.risk))) {
105 + this.audit.log({
106 + event: 'kill_switch_block',
107 + pluginId,
108 + actionId,
109 + risk: decision.risk,
110 + outcome: 'denied'
111 + });
112 + return {
113 + ok: false,
114 + pluginId,
115 + actionId,
116 + risk: decision.risk,
117 + requiresApproval: false,
118 + denied: true,
119 + killSwitchLocked: true,
120 + reason: 'Emergency kill switch is locked'
121 + };
122 + }
123 + if (typeof route.execute !== 'function')
124 + throw new Error(
125 + `Plugin route execute function is required for ${actionId}`
126 + );
127 + try {
128 + const result = await route.execute();
129 + this.audit.log({
130 + event: 'action_result',
131 + pluginId,
132 + actionId,
133 + risk: decision.risk,
134 + outcome: 'success',
135 + ...routeAudit,
136 + ...sanitizeAuditMetadata(result?.audit)
137 + });
138 + return withoutAuditMetadata(result);
139 + } catch (error) {
140 + this.audit.log({
141 + event: 'action_result',
142 + pluginId,
143 + actionId,
144 + risk: decision.risk,
145 + outcome: 'error',
146 + error: error?.message || 'Unknown plugin error',
147 + ...routeAudit
148 + });
149 + throw error;
150 + }
151 + }
152 + return null;
153 + }
154 +}
src/core/runtime-diagnostics.js
+68 -18
@@ -1,4 +1,4 @@
1 -const configured = value => Boolean(String(value || '').trim());
1 +const configured = (value) => Boolean(String(value || '').trim());
2
3 function safeConfigured(checkable) {
4 try {
@@ -17,7 +17,7 @@ function pluginStats(registry) {
17 }
18
19 let actionCount = 0;
20 - const summary = plugins.map(plugin => {
20 + const summary = plugins.map((plugin) => {
21 const manifest = plugin?.manifest || {};
22 const actions = Object.entries(manifest.actions || {});
23 actionCount += actions.length;
@@ -37,7 +37,14 @@ function pluginStats(registry) {
37 }
38
39 export class RuntimeDiagnostics {
40 - constructor({ env = {}, github = null, registry = null, replayStore = null, workspaceStore = null, approvals = null } = {}) {
40 + constructor({
41 + env = {},
42 + github = null,
43 + registry = null,
44 + replayStore = null,
45 + workspaceStore = null,
46 + approvals = null
47 + } = {}) {
48 this.env = env || {};
49 this.github = github;
50 this.registry = registry;
@@ -53,7 +60,9 @@ export class RuntimeDiagnostics {
60 this.env.TELEGRAM_WEBHOOK_SECRET,
61 this.env.GITHUB_TOKEN,
62 this.env.APPROVAL_SIGNING_SECRET
56 - ].map(secret => String(secret || '')).filter(Boolean);
63 + ]
64 + .map((secret) => String(secret || ''))
65 + .filter(Boolean);
66 for (const secret of secrets) text = text.split(secret).join('[REDACTED]');
67 return text;
68 }
@@ -73,15 +82,22 @@ export class RuntimeDiagnostics {
82
83 return {
84 runtime: 'Cloudflare Worker',
76 - githubOwner: String(this.env.GITHUB_OWNER || this.github?.owner || 'davoodmehraban89'),
85 + githubOwner: String(
86 + this.env.GITHUB_OWNER || this.github?.owner || 'davoodmehraban89'
87 + ),
88 telegramConfigured: configured(this.env.TELEGRAM_BOT_TOKEN),
89 webhookSecretConfigured: configured(this.env.TELEGRAM_WEBHOOK_SECRET),
90 ownerConfigured: configured(this.env.OWNER_TELEGRAM_ID),
91 githubConfigured: configured(this.env.GITHUB_TOKEN),
81 - replayGuardConfigured: safeConfigured(this.replayStore) || replayProtected,
92 + replayGuardConfigured:
93 + safeConfigured(this.replayStore) || replayProtected,
94 workspaceStoreConfigured: safeConfigured(this.workspaceStore),
83 - approvalSignerConfigured: configured(this.env.APPROVAL_SIGNING_SECRET) || configured(this.env.TELEGRAM_WEBHOOK_SECRET),
84 - dedicatedApprovalSignerConfigured: configured(this.env.APPROVAL_SIGNING_SECRET),
95 + approvalSignerConfigured:
96 + configured(this.env.APPROVAL_SIGNING_SECRET) ||
97 + configured(this.env.TELEGRAM_WEBHOOK_SECRET),
98 + dedicatedApprovalSignerConfigured: configured(
99 + this.env.APPROVAL_SIGNING_SECRET
100 + ),
101 pluginCount: plugins.pluginCount,
102 actionCount: plugins.actionCount
103 };
@@ -89,10 +105,18 @@ export class RuntimeDiagnostics {
105
106 async probeGitHub() {
107 if (!configured(this.env.GITHUB_TOKEN)) {
92 - return { ok: false, owner: String(this.github?.owner || this.env.GITHUB_OWNER || ''), error: 'GitHub token is not configured' };
108 + return {
109 + ok: false,
110 + owner: String(this.github?.owner || this.env.GITHUB_OWNER || ''),
111 + error: 'GitHub token is not configured'
112 + };
113 }
114 if (!this.github || typeof this.github.listRepositories !== 'function') {
95 - return { ok: false, owner: String(this.github?.owner || this.env.GITHUB_OWNER || ''), error: 'GitHub provider is unavailable' };
115 + return {
116 + ok: false,
117 + owner: String(this.github?.owner || this.env.GITHUB_OWNER || ''),
118 + error: 'GitHub provider is unavailable'
119 + };
120 }
121
122 try {
@@ -115,23 +139,49 @@ export class RuntimeDiagnostics {
139 const snapshot = this.getSnapshot();
140 const githubLive = await this.probeGitHub();
141 const checks = [
118 - { id: 'telegram', label: 'Telegram Bot token', ok: snapshot.telegramConfigured },
119 - { id: 'webhook', label: 'Telegram Webhook secret', ok: snapshot.webhookSecretConfigured },
142 + {
143 + id: 'telegram',
144 + label: 'Telegram Bot token',
145 + ok: snapshot.telegramConfigured
146 + },
147 + {
148 + id: 'webhook',
149 + label: 'Telegram Webhook secret',
150 + ok: snapshot.webhookSecretConfigured
151 + },
152 { id: 'owner', label: 'Owner lock', ok: snapshot.ownerConfigured },
121 - { id: 'github-token', label: 'GitHub credential', ok: snapshot.githubConfigured },
122 - { id: 'replay-guard', label: 'Approval replay guard', ok: snapshot.replayGuardConfigured },
123 - { id: 'workspace-store', label: 'Workspace store', ok: snapshot.workspaceStoreConfigured },
124 - { id: 'approval-signer', label: 'Approval signer', ok: snapshot.approvalSignerConfigured },
153 + {
154 + id: 'github-token',
155 + label: 'GitHub credential',
156 + ok: snapshot.githubConfigured
157 + },
158 + {
159 + id: 'replay-guard',
160 + label: 'Approval replay guard',
161 + ok: snapshot.replayGuardConfigured
162 + },
163 + {
164 + id: 'workspace-store',
165 + label: 'Workspace store',
166 + ok: snapshot.workspaceStoreConfigured
167 + },
168 + {
169 + id: 'approval-signer',
170 + label: 'Approval signer',
171 + ok: snapshot.approvalSignerConfigured
172 + },
173 {
174 id: 'github-live',
175 label: 'GitHub live READ',
176 ok: githubLive.ok,
129 - detail: githubLive.ok ? `${githubLive.repositoryCount} repositories visible` : githubLive.error
177 + detail: githubLive.ok
178 + ? `${githubLive.repositoryCount} repositories visible`
179 + : githubLive.error
180 }
181 ];
182
183 return {
134 - ok: checks.every(check => check.ok),
184 + ok: checks.every((check) => check.ok),
185 checks,
186 snapshot,
187 github: githubLive
src/core/telegram-webapp-auth.js
+16 -11
@@ -8,26 +8,28 @@ async function hmacSha256(keyBytes, value) {
8 false,
9 ['sign']
10 );
11 - return new Uint8Array(await crypto.subtle.sign('HMAC', key, encoder.encode(String(value))));
11 + return new Uint8Array(
12 + await crypto.subtle.sign('HMAC', key, encoder.encode(String(value)))
13 + );
14 }
15
14 -const hex = bytes => Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');
16 +const hex = (bytes) =>
17 + Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
18
19 function timingSafeHexEqual(left, right) {
20 const a = String(left || '').toLowerCase();
21 const b = String(right || '').toLowerCase();
22 if (!/^[a-f0-9]{64}$/.test(a) || !/^[a-f0-9]{64}$/.test(b)) return false;
23 let mismatch = 0;
21 - for (let i = 0; i < a.length; i += 1) mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);
24 + for (let i = 0; i < a.length; i += 1)
25 + mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);
26 return mismatch === 0;
27 }
28
25 -export async function validateTelegramWebAppInitData(initData, {
26 - botToken,
27 - ownerId,
28 - now = () => Date.now(),
29 - maxAgeSeconds = 3600
30 -} = {}) {
29 +export async function validateTelegramWebAppInitData(
30 + initData,
31 + { botToken, ownerId, now = () => Date.now(), maxAgeSeconds = 3600 } = {}
32 +) {
33 const token = String(botToken || '');
34 const owner = String(ownerId || '');
35 if (!token) throw new Error('Mini App bot token is not configured');
@@ -40,7 +42,9 @@ export async function validateTelegramWebAppInitData(initData, {
42 const pairs = [...params.entries()]
43 .filter(([key]) => key !== 'hash')
44 .sort(([a], [b]) => a.localeCompare(b));
43 - const dataCheckString = pairs.map(([key, value]) => `${key}=${value}`).join('\n');
45 + const dataCheckString = pairs
46 + .map(([key, value]) => `${key}=${value}`)
47 + .join('\n');
48
49 // Telegram Mini Apps validation: HMAC_SHA256(key="WebAppData", data=bot_token),
50 // then HMAC_SHA256(key=secret_key, data=data_check_string).
@@ -51,7 +55,8 @@ export async function validateTelegramWebAppInitData(initData, {
55 }
56
57 const authDate = Number(params.get('auth_date'));
54 - if (!Number.isSafeInteger(authDate) || authDate <= 0) throw new Error('Mini App auth_date is invalid');
58 + if (!Number.isSafeInteger(authDate) || authDate <= 0)
59 + throw new Error('Mini App auth_date is invalid');
60 const currentSeconds = Math.floor(Number(now()) / 1000);
61 const age = currentSeconds - authDate;
62 if (!Number.isFinite(age) || age < -60 || age > Number(maxAgeSeconds)) {
src/core/totp.js
+31 -11
@@ -1,7 +1,10 @@
1 const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
2
3 function decodeBase32(secret) {
4 - const normalized = String(secret || '').replace(/\s+/g, '').replace(/=+$/g, '').toUpperCase();
4 + const normalized = String(secret || '')
5 + .replace(/\s+/g, '')
6 + .replace(/=+$/g, '')
7 + .toUpperCase();
8 if (!normalized) throw new Error('TOTP secret is not configured');
9 let bits = '';
10 for (const char of normalized) {
@@ -30,12 +33,19 @@ function constantTimeCodeEqual(left, right) {
33 const b = String(right || '');
34 if (a.length !== b.length) return false;
35 let mismatch = 0;
33 - for (let index = 0; index < a.length; index += 1) mismatch |= a.charCodeAt(index) ^ b.charCodeAt(index);
36 + for (let index = 0; index < a.length; index += 1)
37 + mismatch |= a.charCodeAt(index) ^ b.charCodeAt(index);
38 return mismatch === 0;
39 }
40
41 export class TotpVerifier {
38 - constructor({ secret = '', now = () => Date.now(), periodMs = 30_000, digits = 6, window = 1 } = {}) {
42 + constructor({
43 + secret = '',
44 + now = () => Date.now(),
45 + periodMs = 30_000,
46 + digits = 6,
47 + window = 1
48 + } = {}) {
49 this.secret = String(secret || '');
50 this.now = now;
51 this.periodMs = periodMs;
@@ -49,12 +59,19 @@ export class TotpVerifier {
59 }
60
61 async verify(code) {
52 - if (!this.isConfigured()) throw new Error('Destructive second factor is not configured');
62 + if (!this.isConfigured())
63 + throw new Error('Destructive second factor is not configured');
64 const supplied = String(code || '').trim();
65 if (!new RegExp(`^\\d{${this.digits}}$`).test(supplied)) return false;
66 const currentCounter = Math.floor(this.now() / this.periodMs);
67 for (let delta = -this.window; delta <= this.window; delta += 1) {
57 - if (constantTimeCodeEqual(supplied, await this.#generate(currentCounter + delta))) return true;
68 + if (
69 + constantTimeCodeEqual(
70 + supplied,
71 + await this.#generate(currentCounter + delta)
72 + )
73 + )
74 + return true;
75 }
76 return false;
77 }
@@ -62,13 +79,16 @@ export class TotpVerifier {
79 async #generate(counter) {
80 if (!Number.isSafeInteger(counter) || counter < 0) return '';
81 const key = await this.#key();
65 - const digest = new Uint8Array(await crypto.subtle.sign('HMAC', key, counterBytes(counter)));
82 + const digest = new Uint8Array(
83 + await crypto.subtle.sign('HMAC', key, counterBytes(counter))
84 + );
85 const offset = digest[digest.length - 1] & 0x0f;
67 - const binary = ((digest[offset] & 0x7f) << 24)
68 - | (digest[offset + 1] << 16)
69 - | (digest[offset + 2] << 8)
70 - | digest[offset + 3];
71 - return String(binary % (10 ** this.digits)).padStart(this.digits, '0');
86 + const binary =
87 + ((digest[offset] & 0x7f) << 24) |
88 + (digest[offset + 1] << 16) |
89 + (digest[offset + 2] << 8) |
90 + digest[offset + 3];
91 + return String(binary % 10 ** this.digits).padStart(this.digits, '0');
92 }
93
94 async #key() {
src/core/workspace-policy.js
+98 -35
@@ -14,8 +14,10 @@ export const WORKSPACE_EDITOR_LIMITS = Object.freeze({
14
15 const encoder = new TextEncoder();
16
17 -const sensitivePath = value => {
18 - const path = String(value || '').replaceAll('\\', '/').toLowerCase();
17 +const sensitivePath = (value) => {
18 + const path = String(value || '')
19 + .replaceAll('\\', '/')
20 + .toLowerCase();
21 const name = path.split('/').pop() || '';
22 if (name === '.env' || name.startsWith('.env.')) return true;
23 if (name === 'id_rsa' || name === 'id_ed25519') return true;
@@ -25,23 +27,30 @@ const sensitivePath = value => {
27 return false;
28 };
29
28 -const codePointLength = value => Array.from(value).length;
30 +const codePointLength = (value) => Array.from(value).length;
31
32 export function validateEditableFile({ path, text, byteLength } = {}) {
33 const source = String(text ?? '');
34 const charLength = codePointLength(source);
35 const computedBytes = encoder.encode(source).byteLength;
36 const providerBytes = Number(byteLength);
35 - const effectiveBytes = Number.isFinite(providerBytes) && providerBytes >= 0
36 - ? Math.max(computedBytes, providerBytes)
37 - : computedBytes;
37 + const effectiveBytes =
38 + Number.isFinite(providerBytes) && providerBytes >= 0
39 + ? Math.max(computedBytes, providerBytes)
40 + : computedBytes;
41
42 let reason = '';
43 if (sensitivePath(path)) reason = 'Sensitive file path is not editable.';
41 - else if (source.includes('\0')) reason = 'Binary-like content is not editable.';
42 - else if (/^version https:\/\/git-lfs\.github\.com\/spec\/v1(?:\r?\n|$)/.test(source)) reason = 'Git LFS pointer files are not editable.';
43 - else if (charLength > MAX_CHARS) reason = 'Editable text is limited to 20,000 Unicode characters.';
44 - else if (effectiveBytes > MAX_BYTES) reason = 'Editable text is limited to 65,536 UTF-8 bytes.';
44 + else if (source.includes('\0'))
45 + reason = 'Binary-like content is not editable.';
46 + else if (
47 + /^version https:\/\/git-lfs\.github\.com\/spec\/v1(?:\r?\n|$)/.test(source)
48 + )
49 + reason = 'Git LFS pointer files are not editable.';
50 + else if (charLength > MAX_CHARS)
51 + reason = 'Editable text is limited to 20,000 Unicode characters.';
52 + else if (effectiveBytes > MAX_BYTES)
53 + reason = 'Editable text is limited to 65,536 UTF-8 bytes.';
54
55 return {
56 editable: reason === '',
@@ -53,7 +62,9 @@ export function validateEditableFile({ path, text, byteLength } = {}) {
62 }
63
64 export function normalizeCommitMessage(value) {
56 - const normalized = String(value ?? '').trim().replace(/\s+/g, ' ');
65 + const normalized = String(value ?? '')
66 + .trim()
67 + .replace(/\s+/g, ' ');
68 if (!normalized) throw new Error('Commit message is required');
69 if (codePointLength(normalized) > MAX_COMMIT_MESSAGE) {
70 throw new Error('Commit message must be 120 characters or fewer');
@@ -63,13 +74,19 @@ export function normalizeCommitMessage(value) {
74
75 export function makeTargetBranch(workspaceId) {
76 const id = String(workspaceId ?? '');
66 - if (!SAFE_HANDLE.test(id)) throw new Error('Workspace ID must be a 10-character URL-safe handle');
77 + if (!SAFE_HANDLE.test(id))
78 + throw new Error('Workspace ID must be a 10-character URL-safe handle');
79 return `nexa/edit-${id}`;
80 }
81
82 export async function digestText(value) {
71 - const digest = await crypto.subtle.digest('SHA-256', encoder.encode(String(value ?? '')));
72 - return Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('');
83 + const digest = await crypto.subtle.digest(
84 + 'SHA-256',
85 + encoder.encode(String(value ?? ''))
86 + );
87 + return Array.from(new Uint8Array(digest), (byte) =>
88 + byte.toString(16).padStart(2, '0')
89 + ).join('');
90 }
91
92 function linesOf(value) {
@@ -84,9 +101,10 @@ function diffOperations(beforeLines, afterLines) {
101
102 for (let i = beforeLines.length - 1; i >= 0; i -= 1) {
103 for (let j = afterLines.length - 1; j >= 0; j -= 1) {
87 - table[at(i, j)] = beforeLines[i] === afterLines[j]
88 - ? table[at(i + 1, j + 1)] + 1
89 - : Math.max(table[at(i + 1, j)], table[at(i, j + 1)]);
104 + table[at(i, j)] =
105 + beforeLines[i] === afterLines[j]
106 + ? table[at(i + 1, j + 1)] + 1
107 + : Math.max(table[at(i + 1, j)], table[at(i, j + 1)]);
108 }
109 }
110
@@ -94,13 +112,20 @@ function diffOperations(beforeLines, afterLines) {
112 let i = 0;
113 let j = 0;
114 while (i < beforeLines.length || j < afterLines.length) {
97 - if (i < beforeLines.length && j < afterLines.length && beforeLines[i] === afterLines[j]) {
115 + if (
116 + i < beforeLines.length &&
117 + j < afterLines.length &&
118 + beforeLines[i] === afterLines[j]
119 + ) {
120 operations.push({ kind: ' ', line: beforeLines[i] });
121 i += 1;
122 j += 1;
123 continue;
124 }
103 - if (j < afterLines.length && (i >= beforeLines.length || table[at(i, j + 1)] >= table[at(i + 1, j)])) {
125 + if (
126 + j < afterLines.length &&
127 + (i >= beforeLines.length || table[at(i, j + 1)] >= table[at(i + 1, j)])
128 + ) {
129 operations.push({ kind: '+', line: afterLines[j] });
130 j += 1;
131 continue;
@@ -111,16 +136,27 @@ function diffOperations(beforeLines, afterLines) {
136 return operations;
137 }
138
114 -export function buildUnifiedDiff({ path, before, after, maxChars = 2600 } = {}) {
139 +export function buildUnifiedDiff({
140 + path,
141 + before,
142 + after,
143 + maxChars = 2600
144 +} = {}) {
145 const safePath = String(path || 'file').replace(/[\r\n]/g, '');
146 const operations = diffOperations(linesOf(before), linesOf(after));
117 - const additions = operations.reduce((count, op) => count + (op.kind === '+' ? 1 : 0), 0);
118 - const deletions = operations.reduce((count, op) => count + (op.kind === '-' ? 1 : 0), 0);
147 + const additions = operations.reduce(
148 + (count, op) => count + (op.kind === '+' ? 1 : 0),
149 + 0
150 + );
151 + const deletions = operations.reduce(
152 + (count, op) => count + (op.kind === '-' ? 1 : 0),
153 + 0
154 + );
155 const raw = [
156 `--- a/${safePath}`,
157 `+++ b/${safePath}`,
158 '@@',
123 - ...operations.map(op => `${op.kind}${op.line}`)
159 + ...operations.map((op) => `${op.kind}${op.line}`)
160 ].join('\n');
161
162 const limit = Math.max(32, Math.min(10000, Number(maxChars) || 2600));
@@ -136,26 +172,40 @@ export function buildUnifiedDiff({ path, before, after, maxChars = 2600 } = {})
172 };
173 }
174
139 -
175 export function validateWorkspaceFiles(files = []) {
141 - if (!Array.isArray(files) || files.length === 0) throw new Error('Workspace files are required');
142 - if (files.length > MAX_WORKSPACE_FILES) throw new Error(`Workspace is limited to ${MAX_WORKSPACE_FILES} files`);
176 + if (!Array.isArray(files) || files.length === 0)
177 + throw new Error('Workspace files are required');
178 + if (files.length > MAX_WORKSPACE_FILES)
179 + throw new Error(`Workspace is limited to ${MAX_WORKSPACE_FILES} files`);
180 const seen = new Set();
181 let totalBytes = 0;
145 - const normalized = files.map(source => {
182 + const normalized = files.map((source) => {
183 const path = String(source?.path || '').replaceAll('\\', '/');
184 if (!path) throw new Error('Workspace file path is required');
185 if (seen.has(path)) throw new Error(`Duplicate workspace path: ${path}`);
186 seen.add(path);
150 - const original = validateEditableFile({ path, text: source?.originalText ?? '' });
187 + const original = validateEditableFile({
188 + path,
189 + text: source?.originalText ?? ''
190 + });
191 if (!original.editable) throw new Error(original.reason);
152 - const draft = validateEditableFile({ path, text: source?.draftText ?? source?.originalText ?? '' });
192 + const draft = validateEditableFile({
193 + path,
194 + text: source?.draftText ?? source?.originalText ?? ''
195 + });
196 if (!draft.editable) throw new Error(draft.reason);
197 totalBytes += Math.max(original.byteLength, draft.byteLength);
155 - return { ...source, path, originalText: original.text, draftText: draft.text };
198 + return {
199 + ...source,
200 + path,
201 + originalText: original.text,
202 + draftText: draft.text
203 + };
204 });
205 if (totalBytes > MAX_WORKSPACE_BYTES) {
158 - throw new Error('Workspace aggregate text is limited to 131,072 UTF-8 bytes');
206 + throw new Error(
207 + 'Workspace aggregate text is limited to 131,072 UTF-8 bytes'
208 + );
209 }
210 return { valid: true, files: normalized, totalBytes };
211 }
@@ -167,7 +217,12 @@ export function buildWorkspaceDiff({ files = [], maxChars = 3000 } = {}) {
217 let deletions = 0;
218 for (const file of validated.files) {
219 if (file.originalText === file.draftText) continue;
170 - const diff = buildUnifiedDiff({ path: file.path, before: file.originalText, after: file.draftText, maxChars: 10000 });
220 + const diff = buildUnifiedDiff({
221 + path: file.path,
222 + before: file.originalText,
223 + after: file.draftText,
224 + maxChars: 10000
225 + });
226 additions += diff.additions;
227 deletions += diff.deletions;
228 changed.push(diff.text);
@@ -176,14 +231,22 @@ export function buildWorkspaceDiff({ files = [], maxChars = 3000 } = {}) {
231 const limit = Math.max(32, Math.min(10000, Number(maxChars) || 3000));
232 const marker = '\n…';
233 const truncated = raw.length > limit;
179 - const text = truncated ? `${raw.slice(0, Math.max(0, limit - marker.length))}${marker}` : raw;
180 - return { text, additions, deletions, filesChanged: changed.length, truncated };
234 + const text = truncated
235 + ? `${raw.slice(0, Math.max(0, limit - marker.length))}${marker}`
236 + : raw;
237 + return {
238 + text,
239 + additions,
240 + deletions,
241 + filesChanged: changed.length,
242 + truncated
243 + };
244 }
245
246 export async function digestWorkspaceFiles(files = []) {
247 const validated = validateWorkspaceFiles(files);
248 const canonical = validated.files
186 - .map(file => ({
249 + .map((file) => ({
250 path: file.path,
251 blobSha: String(file.blobSha || ''),
252 originalDigest: String(file.originalDigest || ''),
src/core/workspace-store.js
+102 -29
@@ -1,8 +1,9 @@
1 -const jsonRequest = (url, body) => new Request(url, {
2 - method: 'POST',
3 - headers: { 'content-type': 'application/json' },
4 - body: JSON.stringify(body)
5 -});
1 +const jsonRequest = (url, body) =>
2 + new Request(url, {
3 + method: 'POST',
4 + headers: { 'content-type': 'application/json' },
5 + body: JSON.stringify(body)
6 + });
7
8 export class DurableWorkspaceStoreClient {
9 constructor({ namespace = null, now = () => Date.now() } = {}) {
@@ -11,39 +12,111 @@ export class DurableWorkspaceStoreClient {
12 }
13
14 isConfigured() {
14 - return Boolean(this.namespace && typeof this.namespace.idFromName === 'function' && typeof this.namespace.get === 'function');
15 + return Boolean(
16 + this.namespace &&
17 + typeof this.namespace.idFromName === 'function' &&
18 + typeof this.namespace.get === 'function'
19 + );
20 }
21
22 async #call(ownerId, operation, payload = {}) {
18 - if (!this.isConfigured()) throw new Error('Durable workspace store is not configured');
23 + if (!this.isConfigured())
24 + throw new Error('Durable workspace store is not configured');
25 const owner = String(ownerId ?? '');
26 if (!owner) throw new Error('Workspace owner is required');
27 const id = this.namespace.idFromName(owner);
28 const stub = this.namespace.get(id);
23 - const response = await stub.fetch(jsonRequest(`https://workspace-store/${operation}`, { ...payload, now: Number(this.now()) }));
29 + const response = await stub.fetch(
30 + jsonRequest(`https://workspace-store/${operation}`, {
31 + ...payload,
32 + now: Number(this.now())
33 + })
34 + );
35 let body = null;
25 - try { body = await response.json(); } catch { body = null; }
26 - if (!response.ok) throw new Error(body?.error || `Durable workspace store failed (${response.status})`);
36 + try {
37 + body = await response.json();
38 + } catch {
39 + body = null;
40 + }
41 + if (!response.ok)
42 + throw new Error(
43 + body?.error || `Durable workspace store failed (${response.status})`
44 + );
45 return body?.result ?? null;
46 }
47
30 - createNavigationRefs({ ownerId, refs, ttlMs = 900_000 } = {}) { return this.#call(ownerId, 'refs/create', { refs, ttlMs }); }
31 - resolveNavigationRef({ ownerId, refId } = {}) { return this.#call(ownerId, 'refs/get', { refId }); }
32 - createWorkspace({ ownerId, ...workspace } = {}) { return this.#call(ownerId, 'workspace/create', workspace); }
33 - getWorkspace({ ownerId, workspaceId } = {}) { return this.#call(ownerId, 'workspace/get', { workspaceId }); }
34 - updateDraft({ ownerId, workspaceId, text, digest } = {}) { return this.#call(ownerId, 'workspace/draft', { workspaceId, text, digest }); }
35 - upsertWorkspaceFile({ ownerId, workspaceId, file } = {}) { return this.#call(ownerId, 'workspace/file/upsert', { workspaceId, file }); }
36 - updateWorkspaceFileDraft({ ownerId, workspaceId, path, text, digest } = {}) { return this.#call(ownerId, 'workspace/file/draft', { workspaceId, path, text, digest }); }
37 - removeWorkspaceFile({ ownerId, workspaceId, path } = {}) { return this.#call(ownerId, 'workspace/file/remove', { workspaceId, path }); }
38 - setPendingInput({ ownerId, workspaceId, mode } = {}) { return this.#call(ownerId, 'pending/set', { workspaceId, mode }); }
39 - getPendingInput({ ownerId } = {}) { return this.#call(ownerId, 'pending/get'); }
40 - consumePendingInput({ ownerId, workspaceId, mode } = {}) { return this.#call(ownerId, 'pending/consume', { workspaceId, mode }); }
41 - setCommitMessage({ ownerId, workspaceId, message, digest } = {}) { return this.#call(ownerId, 'workspace/message', { workspaceId, message, digest }); }
42 - sealIntent({ ownerId, workspaceId, intent } = {}) { return this.#call(ownerId, 'intent/seal', { workspaceId, intent }); }
43 - getIntent({ ownerId, intentId } = {}) { return this.#call(ownerId, 'intent/get', { intentId }); }
44 - beginCommit({ ownerId, intentId } = {}) { return this.#call(ownerId, 'intent/begin', { intentId }); }
45 - setCandidateCommit({ ownerId, intentId, commitSha } = {}) { return this.#call(ownerId, 'intent/candidate', { intentId, commitSha }); }
46 - completeCommit({ ownerId, intentId, commitSha, branch } = {}) { return this.#call(ownerId, 'intent/complete', { intentId, commitSha, branch }); }
47 - markStale({ ownerId, intentId, reason } = {}) { return this.#call(ownerId, 'intent/stale', { intentId, reason }); }
48 - cancelWorkspace({ ownerId, workspaceId } = {}) { return this.#call(ownerId, 'workspace/cancel', { workspaceId }); }
48 + createNavigationRefs({ ownerId, refs, ttlMs = 900_000 } = {}) {
49 + return this.#call(ownerId, 'refs/create', { refs, ttlMs });
50 + }
51 + resolveNavigationRef({ ownerId, refId } = {}) {
52 + return this.#call(ownerId, 'refs/get', { refId });
53 + }
54 + createWorkspace({ ownerId, ...workspace } = {}) {
55 + return this.#call(ownerId, 'workspace/create', workspace);
56 + }
57 + getWorkspace({ ownerId, workspaceId } = {}) {
58 + return this.#call(ownerId, 'workspace/get', { workspaceId });
59 + }
60 + updateDraft({ ownerId, workspaceId, text, digest } = {}) {
61 + return this.#call(ownerId, 'workspace/draft', {
62 + workspaceId,
63 + text,
64 + digest
65 + });
66 + }
67 + upsertWorkspaceFile({ ownerId, workspaceId, file } = {}) {
68 + return this.#call(ownerId, 'workspace/file/upsert', { workspaceId, file });
69 + }
70 + updateWorkspaceFileDraft({ ownerId, workspaceId, path, text, digest } = {}) {
71 + return this.#call(ownerId, 'workspace/file/draft', {
72 + workspaceId,
73 + path,
74 + text,
75 + digest
76 + });
77 + }
78 + removeWorkspaceFile({ ownerId, workspaceId, path } = {}) {
79 + return this.#call(ownerId, 'workspace/file/remove', { workspaceId, path });
80 + }
81 + setPendingInput({ ownerId, workspaceId, mode } = {}) {
82 + return this.#call(ownerId, 'pending/set', { workspaceId, mode });
83 + }
84 + getPendingInput({ ownerId } = {}) {
85 + return this.#call(ownerId, 'pending/get');
86 + }
87 + consumePendingInput({ ownerId, workspaceId, mode } = {}) {
88 + return this.#call(ownerId, 'pending/consume', { workspaceId, mode });
89 + }
90 + setCommitMessage({ ownerId, workspaceId, message, digest } = {}) {
91 + return this.#call(ownerId, 'workspace/message', {
92 + workspaceId,
93 + message,
94 + digest
95 + });
96 + }
97 + sealIntent({ ownerId, workspaceId, intent } = {}) {
98 + return this.#call(ownerId, 'intent/seal', { workspaceId, intent });
99 + }
100 + getIntent({ ownerId, intentId } = {}) {
101 + return this.#call(ownerId, 'intent/get', { intentId });
102 + }
103 + beginCommit({ ownerId, intentId } = {}) {
104 + return this.#call(ownerId, 'intent/begin', { intentId });
105 + }
106 + setCandidateCommit({ ownerId, intentId, commitSha } = {}) {
107 + return this.#call(ownerId, 'intent/candidate', { intentId, commitSha });
108 + }
109 + completeCommit({ ownerId, intentId, commitSha, branch } = {}) {
110 + return this.#call(ownerId, 'intent/complete', {
111 + intentId,
112 + commitSha,
113 + branch
114 + });
115 + }
116 + markStale({ ownerId, intentId, reason } = {}) {
117 + return this.#call(ownerId, 'intent/stale', { intentId, reason });
118 + }
119 + cancelWorkspace({ ownerId, workspaceId } = {}) {
120 + return this.#call(ownerId, 'workspace/cancel', { workspaceId });
121 + }
122 }
src/durable/approval-replay-guard.js
+70 -23
@@ -1,7 +1,9 @@
1 const json = (payload, status = 200) => Response.json(payload, { status });
2
3 export class ApprovalReplayGuard {
4 - constructor(state) { this.state = state; }
4 + constructor(state) {
5 + this.state = state;
6 + }
7 async fetch(request) {
8 const url = new URL(request.url);
9
@@ -10,10 +12,16 @@ export class ApprovalReplayGuard {
12 const token = String(payload?.token || '');
13 const expiresAt = Number(payload?.expiresAt);
14 const attempts = Number(payload?.attempts || 0);
13 - if (!token || !Number.isFinite(expiresAt) || expiresAt < Date.now() || !Number.isSafeInteger(attempts) || attempts < 0) {
15 + if (
16 + !token ||
17 + !Number.isFinite(expiresAt) ||
18 + expiresAt < Date.now() ||
19 + !Number.isSafeInteger(attempts) ||
20 + attempts < 0
21 + ) {
22 return json({ stored: false }, 400);
23 }
16 - await this.state.storage.transaction(async txn => {
24 + await this.state.storage.transaction(async (txn) => {
25 await txn.put('secondFactorPending', { token, expiresAt, attempts });
26 });
27 await this.state.storage.setAlarm(expiresAt);
@@ -21,44 +29,83 @@ export class ApprovalReplayGuard {
29 }
30
31 if (request.method === 'GET' && url.pathname === '/second-factor/get') {
24 - const pending = await this.state.storage.transaction(async txn => txn.get('secondFactorPending'));
32 + const pending = await this.state.storage.transaction(async (txn) =>
33 + txn.get('secondFactorPending')
34 + );
35 if (!pending) return json({ pending: null }, 404);
26 - if (!Number.isFinite(Number(pending.expiresAt)) || Number(pending.expiresAt) < Date.now()) {
27 - await this.state.storage.transaction(async txn => txn.delete('secondFactorPending'));
36 + if (
37 + !Number.isFinite(Number(pending.expiresAt)) ||
38 + Number(pending.expiresAt) < Date.now()
39 + ) {
40 + await this.state.storage.transaction(async (txn) =>
41 + txn.delete('secondFactorPending')
42 + );
43 return json({ pending: null }, 410);
44 }
45 return json({ pending });
46 }
47
48 if (request.method === 'POST' && url.pathname === '/second-factor/clear') {
34 - await this.state.storage.transaction(async txn => txn.delete('secondFactorPending'));
49 + await this.state.storage.transaction(async (txn) =>
50 + txn.delete('secondFactorPending')
51 + );
52 return json({ cleared: true });
53 }
54
55 if (request.method === 'POST' && url.pathname === '/prepare') {
39 - const payload = await request.json().catch(() => null); const expiresAt = Number(payload?.expiresAt);
40 - if (!Number.isFinite(expiresAt) || expiresAt < Date.now() || !payload?.payload) return json({ prepared: false }, 400);
41 - const prepared = await this.state.storage.transaction(async txn => {
56 + const payload = await request.json().catch(() => null);
57 + const expiresAt = Number(payload?.expiresAt);
58 + if (
59 + !Number.isFinite(expiresAt) ||
60 + expiresAt < Date.now() ||
61 + !payload?.payload
62 + )
63 + return json({ prepared: false }, 400);
64 + const prepared = await this.state.storage.transaction(async (txn) => {
65 if (await txn.get('used')) return false;
66 const existing = await txn.get('payload');
44 - if (existing) return JSON.stringify(existing) === JSON.stringify(payload.payload);
45 - await txn.put('payload', payload.payload); await txn.put('expiresAt', expiresAt); return true;
67 + if (existing)
68 + return JSON.stringify(existing) === JSON.stringify(payload.payload);
69 + await txn.put('payload', payload.payload);
70 + await txn.put('expiresAt', expiresAt);
71 + return true;
72 });
73 if (!prepared) return json({ prepared: false }, 409);
48 - await this.state.storage.setAlarm(expiresAt); return json({ prepared: true });
74 + await this.state.storage.setAlarm(expiresAt);
75 + return json({ prepared: true });
76 }
77 if (request.method === 'GET' && url.pathname === '/peek') {
78 const expiresAt = Number(await this.state.storage.get('expiresAt'));
52 - if (!Number.isFinite(expiresAt) || expiresAt < Date.now() || await this.state.storage.get('used')) return json({ payload: null }, 404);
53 - return json({ payload: await this.state.storage.get('payload') || null });
79 + if (
80 + !Number.isFinite(expiresAt) ||
81 + expiresAt < Date.now() ||
82 + (await this.state.storage.get('used'))
83 + )
84 + return json({ payload: null }, 404);
85 + return json({
86 + payload: (await this.state.storage.get('payload')) || null
87 + });
88 }
55 - if (request.method !== 'POST' || url.pathname !== '/consume') return new Response('Not Found', { status: 404 });
56 - const payload = await request.json().catch(() => null); const expiresAt = Number(payload?.expiresAt);
57 - if (!Number.isFinite(expiresAt)) return json({ accepted: false, reason: 'invalid_expiry' }, 400);
58 - if (expiresAt < Date.now()) return json({ accepted: false, reason: 'expired' }, 410);
59 - const accepted = await this.state.storage.transaction(async txn => { const usedUntil = await txn.get('used'); if (usedUntil) return false; await txn.put('used', expiresAt); return true; });
60 - if (!accepted) return json({ accepted: false, reason: 'already_used' }, 409);
61 - await this.state.storage.setAlarm(expiresAt); return json({ accepted: true });
89 + if (request.method !== 'POST' || url.pathname !== '/consume')
90 + return new Response('Not Found', { status: 404 });
91 + const payload = await request.json().catch(() => null);
92 + const expiresAt = Number(payload?.expiresAt);
93 + if (!Number.isFinite(expiresAt))
94 + return json({ accepted: false, reason: 'invalid_expiry' }, 400);
95 + if (expiresAt < Date.now())
96 + return json({ accepted: false, reason: 'expired' }, 410);
97 + const accepted = await this.state.storage.transaction(async (txn) => {
98 + const usedUntil = await txn.get('used');
99 + if (usedUntil) return false;
100 + await txn.put('used', expiresAt);
101 + return true;
102 + });
103 + if (!accepted)
104 + return json({ accepted: false, reason: 'already_used' }, 409);
105 + await this.state.storage.setAlarm(expiresAt);
106 + return json({ accepted: true });
107 + }
108 + async alarm() {
109 + await this.state.storage.deleteAll();
110 }
63 - async alarm() { await this.state.storage.deleteAll(); }
111 }
src/durable/automation-store.js
+33 -1
@@ -1 +1,33 @@
1 -const json=(x,s=200)=>new Response(JSON.stringify(x),{status:s,headers:{'content-type':'application/json'}});export class AutomationStore{constructor(state){this.storage=state.storage;}async fetch(req){const u=new URL(req.url),owner=u.searchParams.get('owner')||'',id=u.searchParams.get('id')||'';if(!owner||!id)return json({error:'owner/id required'},400);const key=`automation:${owner}:${id}`;if(req.method==='GET'){const v=await this.storage.get(key);return v?json(v):json({error:'not found'},404);}if(req.method==='PUT'){const body=await req.json();if(String(body.ownerId)!==owner||body.id!==id||body.version!==1)return json({error:'invalid state'},400);await this.storage.put(key,body);return json(body);}return json({error:'not found'},404);}}
1 +const json = (x, s = 200) =>
2 + new Response(JSON.stringify(x), {
3 + status: s,
4 + headers: { 'content-type': 'application/json' }
5 + });
6 +export class AutomationStore {
7 + constructor(state) {
8 + this.storage = state.storage;
9 + }
10 + async fetch(req) {
11 + const u = new URL(req.url),
12 + owner = u.searchParams.get('owner') || '',
13 + id = u.searchParams.get('id') || '';
14 + if (!owner || !id) return json({ error: 'owner/id required' }, 400);
15 + const key = `automation:${owner}:${id}`;
16 + if (req.method === 'GET') {
17 + const v = await this.storage.get(key);
18 + return v ? json(v) : json({ error: 'not found' }, 404);
19 + }
20 + if (req.method === 'PUT') {
21 + const body = await req.json();
22 + if (
23 + String(body.ownerId) !== owner ||
24 + body.id !== id ||
25 + body.version !== 1
26 + )
27 + return json({ error: 'invalid state' }, 400);
28 + await this.storage.put(key, body);
29 + return json(body);
30 + }
31 + return json({ error: 'not found' }, 404);
32 + }
33 +}
src/durable/incident-store.js
+53 -8
@@ -1,12 +1,57 @@
1 import { normalizeIncident } from '../core/incidents.js';
2 -const json=(data,status=200)=>new Response(JSON.stringify(data),{status,headers:{'content-type':'application/json'}});
2 +const json = (data, status = 200) =>
3 + new Response(JSON.stringify(data), {
4 + status,
5 + headers: { 'content-type': 'application/json' }
6 + });
7 export class IncidentStore {
4 - constructor(state){this.state=state;this.storage=state.storage;}
5 - async fetch(request){const url=new URL(request.url); const owner=url.searchParams.get('owner')||''; if(!owner)return json({error:'owner required'},400); const key='incidents:'+owner; const items=(await this.storage.get(key))||[];
6 - if(request.method==='GET') return json({version:1,items});
7 - const body=await request.json().catch(()=>({}));
8 - if(request.method==='POST'&&url.pathname.endsWith('/upsert')){const next=normalizeIncident(body); const i=items.findIndex(x=>x.fingerprint===next.fingerprint); const now=Date.now(); if(i>=0){items[i]={...items[i],...next,status:'open',count:(items[i].count||1)+1,updatedAt:now};}else items.unshift({...next,id:crypto.randomUUID(),count:1,createdAt:now,updatedAt:now}); await this.storage.put(key,items.slice(0,100)); return json(i>=0?items[i]:items[0]);}
9 - if(request.method==='POST'&&url.pathname.endsWith('/resolve')){const i=items.findIndex(x=>x.id===body.id); if(i<0)return json({error:'not found'},404); items[i]={...items[i],status:'resolved',resolvedAt:Date.now(),updatedAt:Date.now()}; await this.storage.put(key,items); return json(items[i]);}
10 - return json({error:'not found'},404);
8 + constructor(state) {
9 + this.state = state;
10 + this.storage = state.storage;
11 + }
12 + async fetch(request) {
13 + const url = new URL(request.url);
14 + const owner = url.searchParams.get('owner') || '';
15 + if (!owner) return json({ error: 'owner required' }, 400);
16 + const key = 'incidents:' + owner;
17 + const items = (await this.storage.get(key)) || [];
18 + if (request.method === 'GET') return json({ version: 1, items });
19 + const body = await request.json().catch(() => ({}));
20 + if (request.method === 'POST' && url.pathname.endsWith('/upsert')) {
21 + const next = normalizeIncident(body);
22 + const i = items.findIndex((x) => x.fingerprint === next.fingerprint);
23 + const now = Date.now();
24 + if (i >= 0) {
25 + items[i] = {
26 + ...items[i],
27 + ...next,
28 + status: 'open',
29 + count: (items[i].count || 1) + 1,
30 + updatedAt: now
31 + };
32 + } else
33 + items.unshift({
34 + ...next,
35 + id: crypto.randomUUID(),
36 + count: 1,
37 + createdAt: now,
38 + updatedAt: now
39 + });
40 + await this.storage.put(key, items.slice(0, 100));
41 + return json(i >= 0 ? items[i] : items[0]);
42 + }
43 + if (request.method === 'POST' && url.pathname.endsWith('/resolve')) {
44 + const i = items.findIndex((x) => x.id === body.id);
45 + if (i < 0) return json({ error: 'not found' }, 404);
46 + items[i] = {
47 + ...items[i],
48 + status: 'resolved',
49 + resolvedAt: Date.now(),
50 + updatedAt: Date.now()
51 + };
52 + await this.storage.put(key, items);
53 + return json(items[i]);
54 + }
55 + return json({ error: 'not found' }, 404);
56 }
57 }
src/durable/kill-switch-store.js
+22 -11
@@ -1,16 +1,27 @@
1 -const json=(payload,status=200)=>Response.json(payload,{status});
1 +const json = (payload, status = 200) => Response.json(payload, { status });
2 export class KillSwitchStore {
3 - constructor(state){this.state=state;}
4 - async fetch(request){
5 - const url=new URL(request.url);if(url.pathname!=='/state')return new Response('Not Found',{status:404});
6 - if(request.method==='GET'){
7 - const state=await this.state.storage.get('state');
8 - return json(state||{mode:'NORMAL',changedAt:0});
3 + constructor(state) {
4 + this.state = state;
5 + }
6 + async fetch(request) {
7 + const url = new URL(request.url);
8 + if (url.pathname !== '/state')
9 + return new Response('Not Found', { status: 404 });
10 + if (request.method === 'GET') {
11 + const state = await this.state.storage.get('state');
12 + return json(state || { mode: 'NORMAL', changedAt: 0 });
13 }
10 - if(request.method==='PUT'){
11 - const body=await request.json().catch(()=>null);if(!body||!['NORMAL','LOCKED'].includes(body.mode))return json({ok:false},400);
12 - const next={mode:body.mode,changedAt:Number(body.changedAt)||Date.now()};await this.state.storage.put('state',next);return json(next);
14 + if (request.method === 'PUT') {
15 + const body = await request.json().catch(() => null);
16 + if (!body || !['NORMAL', 'LOCKED'].includes(body.mode))
17 + return json({ ok: false }, 400);
18 + const next = {
19 + mode: body.mode,
20 + changedAt: Number(body.changedAt) || Date.now()
21 + };
22 + await this.state.storage.put('state', next);
23 + return json(next);
24 }
14 - return new Response('Method Not Allowed',{status:405});
25 + return new Response('Method Not Allowed', { status: 405 });
26 }
27 }
src/durable/workspace-store.js
+544 -41
@@ -1,43 +1,546 @@
1 -const json=(payload,status=200)=>Response.json(payload,{status});
2 -const HANDLE_ALPHABET='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-';
3 -const WORKSPACE_TTL_MS=30*60_000, REF_TTL_MS=15*60_000, COMMITTED_RETENTION_MS=24*60*60_000;
4 -const MAX_WORKSPACE_BYTES=262144;
5 -function randomHandle(length){const bytes=new Uint8Array(length);crypto.getRandomValues(bytes);let out='';for(const byte of bytes)out+=HANDLE_ALPHABET[byte&63];return out}
6 -function finiteNow(v){const n=Number(v);return Number.isFinite(n)?n:Date.now()}
7 -function positiveTtl(v,f){const n=Number(v);return Number.isFinite(n)&&n>0?n:f}
8 -function expired(r,now){return Boolean(r&&Number.isFinite(Number(r.expiresAt))&&Number(r.expiresAt)<now)}
9 -function normalizePath(value){const path=String(value||'').replace(/\\/g,'/').replace(/^\.\//,'');if(!path||path.startsWith('/')||path.split('/').some(p=>!p||p==='.'||p==='..'))throw new Error('Workspace file path is invalid');return path}
10 -function legacyFile(payload){return {path:normalizePath(payload.path),blobSha:String(payload.blobSha||''),originalText:String(payload.originalText??''),originalDigest:String(payload.originalDigest||''),draftText:String(payload.originalText??''),draftDigest:String(payload.originalDigest||'')}}
11 -function migrate(ws){if(!ws)return ws;if(Array.isArray(ws.files))return ws;return {...ws,schemaVersion:2,files:[{path:String(ws.path||''),blobSha:String(ws.blobSha||''),originalText:String(ws.originalText??''),originalDigest:String(ws.originalDigest||''),draftText:String(ws.draftText??ws.originalText??''),draftDigest:String(ws.draftDigest||ws.originalDigest||'')}]} }
12 -function bytes(files){return files.reduce((n,f)=>n+new TextEncoder().encode(String(f.originalText??'')).length+new TextEncoder().encode(String(f.draftText??'')).length,0)}
13 -function validateFiles(files){if(!Array.isArray(files)||!files.length)throw new Error('Workspace must contain at least one file');const seen=new Set();for(const f of files){const p=normalizePath(f.path);if(seen.has(p))throw new Error('Workspace file path already exists');seen.add(p)}if(bytes(files)>MAX_WORKSPACE_BYTES)throw new Error('Workspace aggregate size is too large')}
1 +const json = (payload, status = 200) => Response.json(payload, { status });
2 +const HANDLE_ALPHABET =
3 + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-';
4 +const WORKSPACE_TTL_MS = 30 * 60_000,
5 + REF_TTL_MS = 15 * 60_000,
6 + COMMITTED_RETENTION_MS = 24 * 60 * 60_000;
7 +const MAX_WORKSPACE_BYTES = 262144;
8 +function randomHandle(length) {
9 + const bytes = new Uint8Array(length);
10 + crypto.getRandomValues(bytes);
11 + let out = '';
12 + for (const byte of bytes) out += HANDLE_ALPHABET[byte & 63];
13 + return out;
14 +}
15 +function finiteNow(v) {
16 + const n = Number(v);
17 + return Number.isFinite(n) ? n : Date.now();
18 +}
19 +function positiveTtl(v, f) {
20 + const n = Number(v);
21 + return Number.isFinite(n) && n > 0 ? n : f;
22 +}
23 +function expired(r, now) {
24 + return Boolean(
25 + r && Number.isFinite(Number(r.expiresAt)) && Number(r.expiresAt) < now
26 + );
27 +}
28 +function normalizePath(value) {
29 + const path = String(value || '')
30 + .replace(/\\/g, '/')
31 + .replace(/^\.\//, '');
32 + if (
33 + !path ||
34 + path.startsWith('/') ||
35 + path.split('/').some((p) => !p || p === '.' || p === '..')
36 + )
37 + throw new Error('Workspace file path is invalid');
38 + return path;
39 +}
40 +function legacyFile(payload) {
41 + return {
42 + path: normalizePath(payload.path),
43 + blobSha: String(payload.blobSha || ''),
44 + originalText: String(payload.originalText ?? ''),
45 + originalDigest: String(payload.originalDigest || ''),
46 + draftText: String(payload.originalText ?? ''),
47 + draftDigest: String(payload.originalDigest || '')
48 + };
49 +}
50 +function migrate(ws) {
51 + if (!ws) return ws;
52 + if (Array.isArray(ws.files)) return ws;
53 + return {
54 + ...ws,
55 + schemaVersion: 2,
56 + files: [
57 + {
58 + path: String(ws.path || ''),
59 + blobSha: String(ws.blobSha || ''),
60 + originalText: String(ws.originalText ?? ''),
61 + originalDigest: String(ws.originalDigest || ''),
62 + draftText: String(ws.draftText ?? ws.originalText ?? ''),
63 + draftDigest: String(ws.draftDigest || ws.originalDigest || '')
64 + }
65 + ]
66 + };
67 +}
68 +function bytes(files) {
69 + return files.reduce(
70 + (n, f) =>
71 + n +
72 + new TextEncoder().encode(String(f.originalText ?? '')).length +
73 + new TextEncoder().encode(String(f.draftText ?? '')).length,
74 + 0
75 + );
76 +}
77 +function validateFiles(files) {
78 + if (!Array.isArray(files) || !files.length)
79 + throw new Error('Workspace must contain at least one file');
80 + const seen = new Set();
81 + for (const f of files) {
82 + const p = normalizePath(f.path);
83 + if (seen.has(p)) throw new Error('Workspace file path already exists');
84 + seen.add(p);
85 + }
86 + if (bytes(files) > MAX_WORKSPACE_BYTES)
87 + throw new Error('Workspace aggregate size is too large');
88 +}
89
15 -export class WorkspaceStore{
16 - constructor(state){this.state=state}
17 - async fetch(request){const url=new URL(request.url);if(request.method!=='POST')return new Response('Not Found',{status:404});let payload;try{payload=await request.json()}catch{return json({error:'Invalid workspace payload'},400)}const now=finiteNow(payload?.now);try{switch(url.pathname){
18 - case'/refs/create':return json({result:await this.#createRefs(payload,now)});case'/refs/get':return json({result:await this.#getExpiring(`ref:${String(payload.refId||'')}`,now)});
19 - case'/workspace/create':return json({result:await this.#createWorkspace(payload,now)});case'/workspace/get':return json({result:migrate(await this.#getExpiring(`ws:${String(payload.workspaceId||'')}`,now))});case'/workspace/draft':return json({result:await this.#updateDraft(payload,now)});
20 - case'/workspace/file/upsert':return json({result:await this.#upsertFile(payload,now)});case'/workspace/file/draft':return json({result:await this.#updateFileDraft(payload,now)});case'/workspace/file/remove':return json({result:await this.#removeFile(payload,now)});
21 - case'/workspace/message':return json({result:await this.#setCommitMessage(payload,now)});case'/workspace/cancel':return json({result:await this.#cancelWorkspace(payload)});case'/pending/set':return json({result:await this.#setPending(payload,now)});case'/pending/get':return json({result:await this.#getPending(now)});case'/pending/consume':return json({result:await this.#consumePending(payload,now)});case'/intent/seal':return json({result:await this.#sealIntent(payload,now)});case'/intent/get':return json({result:await this.#getExpiring(`intent:${String(payload.intentId||'')}`,now)});case'/intent/begin':return json({result:await this.#beginCommit(payload,now)});case'/intent/candidate':return json({result:await this.#setCandidate(payload,now)});case'/intent/complete':return json({result:await this.#completeCommit(payload,now)});case'/intent/stale':return json({result:await this.#markStale(payload,now)});default:return new Response('Not Found',{status:404})}}catch(error){return json({error:String(error?.message||'Workspace store operation failed')},400)}}
22 - async #schedule(expiresAt){const expiry=Number(expiresAt);if(!Number.isFinite(expiry))return;const current=Number(await this.state.storage.get('__next_alarm'));if(!Number.isFinite(current)||expiry<current){await this.state.storage.put('__next_alarm',expiry);await this.state.storage.setAlarm(expiry)}}
23 - async #getExpiring(key,now){if(!key||key.endsWith(':'))return null;const record=await this.state.storage.get(key);if(!record)return null;if(expired(record,now)){await this.state.storage.delete(key);return null}return record}
24 - async #createRefs(payload,now){if(!Array.isArray(payload.refs))throw new Error('Navigation refs are required');const expiresAt=now+positiveTtl(payload.ttlMs,REF_TTL_MS),output=[];for(const source of payload.refs){const refId=randomHandle(10),type=['dir','file','workspace-add','workspace-file'].includes(source?.type)?source.type:'file',workspaceId=String(source?.workspaceId||'');if(type.startsWith('workspace-')&&!/^[A-Za-z0-9_-]{10}$/.test(workspaceId))throw new Error('Workspace navigation ref is invalid');const record={repoId:source?.repoId,path:String(source?.path||''),type,sha:String(source?.sha||''),...(type.startsWith('workspace-')?{workspaceId}:{}),expiresAt};await this.state.storage.put(`ref:${refId}`,record);output.push({refId})}await this.#schedule(expiresAt);return output}
25 - async #createWorkspace(payload,now){const id=randomHandle(10),expiresAt=Number.isFinite(Number(payload.expiresAt))?Number(payload.expiresAt):now+WORKSPACE_TTL_MS;if(expiresAt<=now)throw new Error('Workspace expiry must be in the future');const first=legacyFile(payload);validateFiles([first]);const workspace={id,schemaVersion:2,repoId:payload.repoId,repoFullName:String(payload.repoFullName||''),baseBranch:String(payload.baseBranch||''),baseHeadSha:String(payload.baseHeadSha||''),baseTreeSha:String(payload.baseTreeSha||''),path:first.path,blobSha:first.blobSha,originalText:first.originalText,originalDigest:first.originalDigest,draftText:first.draftText,draftDigest:first.draftDigest,files:[first],commitMessage:'',commitMessageDigest:'',currentIntentId:null,state:'DRAFT',createdAt:now,updatedAt:now,expiresAt};await this.state.storage.put(`ws:${id}`,workspace);await this.#schedule(expiresAt);return workspace}
26 - async #requireWorkspace(id,now){const ws=migrate(await this.#getExpiring(`ws:${String(id||'')}`,now));if(!ws)throw new Error('Workspace not found or expired');return ws}
27 - async #saveMaterial(ws,files,now){validateFiles(files);const primary=files[0];const updated={...ws,schemaVersion:2,files,path:primary.path,blobSha:primary.blobSha,originalText:primary.originalText,originalDigest:primary.originalDigest,draftText:primary.draftText,draftDigest:primary.draftDigest,currentIntentId:null,state:'DRAFT',updatedAt:now};await this.state.storage.put(`ws:${ws.id}`,updated);return updated}
28 - async #upsertFile(payload,now){const ws=await this.#requireWorkspace(payload.workspaceId,now),source=payload.file||{},path=normalizePath(source.path);if(ws.files.some(f=>normalizePath(f.path)===path))throw new Error('Workspace file path already exists');const file={path,blobSha:String(source.blobSha||''),originalText:String(source.originalText??''),originalDigest:String(source.originalDigest||''),draftText:String(source.draftText??source.originalText??''),draftDigest:String(source.draftDigest||source.originalDigest||'')};return this.#saveMaterial(ws,[...ws.files,file],now)}
29 - async #updateFileDraft(payload,now){const ws=await this.#requireWorkspace(payload.workspaceId,now),path=normalizePath(payload.path),digest=String(payload.digest||'');if(!digest)throw new Error('Draft digest is required');let found=false;const files=ws.files.map(f=>normalizePath(f.path)===path?(found=true,{...f,draftText:String(payload.text??''),draftDigest:digest}):f);if(!found)throw new Error('Workspace file not found');if(ws.files.find(f=>normalizePath(f.path)===path)?.draftDigest===digest)return ws;return this.#saveMaterial(ws,files,now)}
30 - async #removeFile(payload,now){const ws=await this.#requireWorkspace(payload.workspaceId,now),path=normalizePath(payload.path),files=ws.files.filter(f=>normalizePath(f.path)!==path);if(files.length===ws.files.length)throw new Error('Workspace file not found');return this.#saveMaterial(ws,files,now)}
31 - async #updateDraft(payload,now){const ws=await this.#requireWorkspace(payload.workspaceId,now),digest=String(payload.digest||'');if(!digest)throw new Error('Draft digest is required');if(digest===ws.draftDigest)return ws;const files=ws.files.map((f,i)=>i?f:{...f,draftText:String(payload.text??''),draftDigest:digest});return this.#saveMaterial(ws,files,now)}
32 - async #setCommitMessage(payload,now){const ws=await this.#requireWorkspace(payload.workspaceId,now),digest=String(payload.digest||'');if(!digest)throw new Error('Commit message digest is required');const changed=digest!==ws.commitMessageDigest,updated={...ws,commitMessage:String(payload.message||''),commitMessageDigest:digest,updatedAt:now,...(changed?{currentIntentId:null,state:'DRAFT'}:{})};await this.state.storage.put(`ws:${ws.id}`,updated);return updated}
33 - async #setPending(payload,now){const ws=await this.#requireWorkspace(payload.workspaceId,now),mode=String(payload.mode||'');if(!['draft','draft_file','commit_message'].includes(mode))throw new Error('Pending input mode is invalid');const pending={workspaceId:ws.id,mode,expiresAt:ws.expiresAt};await this.state.storage.put('pending',pending);await this.#schedule(pending.expiresAt);return pending}
34 - async #getPending(now){const p=await this.state.storage.get('pending');if(!p)return null;if(expired(p,now)){await this.state.storage.delete('pending');return null}const ws=await this.#getExpiring(`ws:${p.workspaceId}`,now);if(!ws){await this.state.storage.delete('pending');return null}return{workspaceId:p.workspaceId,mode:p.mode}}
35 - async #consumePending(payload,now){return this.state.storage.transaction(async txn=>{const p=await txn.get('pending');if(!p||expired(p,now)){if(p)await txn.delete('pending');return false}if(p.workspaceId!==String(payload.workspaceId||'')||p.mode!==String(payload.mode||''))return false;await txn.delete('pending');return true})}
36 - async #sealIntent(payload,now){const ws=await this.#requireWorkspace(payload.workspaceId,now),proposed=payload.intent&&typeof payload.intent==='object'?payload.intent:null;if(!proposed?.intentDigest)throw new Error('Commit intent digest is required');if(ws.currentIntentId){const existing=await this.#getExpiring(`intent:${ws.currentIntentId}`,now);if(existing?.intentDigest===proposed.intentDigest)return existing}const id=randomHandle(8),intent={...proposed,id,workspaceId:ws.id,state:'READY',candidateCommitSha:null,commitSha:null,branch:null,createdAt:now,updatedAt:now,expiresAt:ws.expiresAt};await this.state.storage.put(`intent:${id}`,intent);await this.state.storage.put(`ws:${ws.id}`,{...ws,currentIntentId:id,state:'READY',updatedAt:now});await this.#schedule(intent.expiresAt);return intent}
37 - async #beginCommit(payload,now){const key=`intent:${String(payload.intentId||'')}`;return this.state.storage.transaction(async txn=>{const intent=await txn.get(key);if(!intent||expired(intent,now))throw new Error('Commit intent not found or expired');if(intent.state==='COMMITTED')return{disposition:'committed',intent};if(intent.state==='COMMITTING')return{disposition:'resume',intent};if(intent.state!=='READY')throw new Error(`Commit intent is ${intent.state||'invalid'}`);const updated={...intent,state:'COMMITTING',updatedAt:now};await txn.put(key,updated);return{disposition:'start',intent:updated}})}
38 - async #setCandidate(payload,now){const key=`intent:${String(payload.intentId||'')}`;return this.state.storage.transaction(async txn=>{const intent=await txn.get(key);if(!intent||expired(intent,now))throw new Error('Commit intent not found or expired');if(intent.state==='COMMITTED')return intent;if(intent.state!=='COMMITTING')throw new Error('Commit intent is not committing');const updated={...intent,candidateCommitSha:String(payload.commitSha||''),updatedAt:now};await txn.put(key,updated);return updated})}
39 - async #completeCommit(payload,now){const key=`intent:${String(payload.intentId||'')}`,retainedUntil=now+COMMITTED_RETENTION_MS;const completed=await this.state.storage.transaction(async txn=>{const intent=await txn.get(key);if(!intent)throw new Error('Commit intent not found');if(intent.state==='COMMITTED')return intent;if(intent.state!=='COMMITTING')throw new Error('Commit intent is not committing');const updated={...intent,state:'COMMITTED',commitSha:String(payload.commitSha||''),branch:String(payload.branch||''),updatedAt:now,expiresAt:retainedUntil};await txn.put(key,updated);const wk=`ws:${intent.workspaceId}`,ws=await txn.get(wk);if(ws)await txn.put(wk,{...ws,state:'COMMITTED',currentIntentId:intent.id,commitSha:updated.commitSha,branch:updated.branch,updatedAt:now,expiresAt:retainedUntil});return updated});await this.#schedule(retainedUntil);return completed}
40 - async #markStale(payload,now){const key=`intent:${String(payload.intentId||'')}`;return this.state.storage.transaction(async txn=>{const intent=await txn.get(key);if(!intent)throw new Error('Commit intent not found');if(intent.state==='COMMITTED')return intent;const updated={...intent,state:'STALE',staleReason:String(payload.reason||'stale'),updatedAt:now};await txn.put(key,updated);return updated})}
41 - async #cancelWorkspace(payload){const id=String(payload.workspaceId||'');if(!id)throw new Error('Workspace ID is required');await this.state.storage.transaction(async txn=>{await txn.delete(`ws:${id}`);const p=await txn.get('pending');if(p?.workspaceId===id)await txn.delete('pending')});return{cancelled:true}}
42 - async alarm(){const now=Date.now(),entries=await this.state.storage.list();let next=Infinity;for(const[key,value]of entries){if(key==='__next_alarm')continue;const expiry=Number(value?.expiresAt);if(!Number.isFinite(expiry))continue;if(expiry<=now)await this.state.storage.delete(key);else next=Math.min(next,expiry)}await this.state.storage.delete('__next_alarm');if(Number.isFinite(next)){await this.state.storage.put('__next_alarm',next);await this.state.storage.setAlarm(next)}}
90 +export class WorkspaceStore {
91 + constructor(state) {
92 + this.state = state;
93 + }
94 + async fetch(request) {
95 + const url = new URL(request.url);
96 + if (request.method !== 'POST')
97 + return new Response('Not Found', { status: 404 });
98 + let payload;
99 + try {
100 + payload = await request.json();
101 + } catch {
102 + return json({ error: 'Invalid workspace payload' }, 400);
103 + }
104 + const now = finiteNow(payload?.now);
105 + try {
106 + switch (url.pathname) {
107 + case '/refs/create':
108 + return json({ result: await this.#createRefs(payload, now) });
109 + case '/refs/get':
110 + return json({
111 + result: await this.#getExpiring(
112 + `ref:${String(payload.refId || '')}`,
113 + now
114 + )
115 + });
116 + case '/workspace/create':
117 + return json({ result: await this.#createWorkspace(payload, now) });
118 + case '/workspace/get':
119 + return json({
120 + result: migrate(
121 + await this.#getExpiring(
122 + `ws:${String(payload.workspaceId || '')}`,
123 + now
124 + )
125 + )
126 + });
127 + case '/workspace/draft':
128 + return json({ result: await this.#updateDraft(payload, now) });
129 + case '/workspace/file/upsert':
130 + return json({ result: await this.#upsertFile(payload, now) });
131 + case '/workspace/file/draft':
132 + return json({ result: await this.#updateFileDraft(payload, now) });
133 + case '/workspace/file/remove':
134 + return json({ result: await this.#removeFile(payload, now) });
135 + case '/workspace/message':
136 + return json({ result: await this.#setCommitMessage(payload, now) });
137 + case '/workspace/cancel':
138 + return json({ result: await this.#cancelWorkspace(payload) });
139 + case '/pending/set':
140 + return json({ result: await this.#setPending(payload, now) });
141 + case '/pending/get':
142 + return json({ result: await this.#getPending(now) });
143 + case '/pending/consume':
144 + return json({ result: await this.#consumePending(payload, now) });
145 + case '/intent/seal':
146 + return json({ result: await this.#sealIntent(payload, now) });
147 + case '/intent/get':
148 + return json({
149 + result: await this.#getExpiring(
150 + `intent:${String(payload.intentId || '')}`,
151 + now
152 + )
153 + });
154 + case '/intent/begin':
155 + return json({ result: await this.#beginCommit(payload, now) });
156 + case '/intent/candidate':
157 + return json({ result: await this.#setCandidate(payload, now) });
158 + case '/intent/complete':
159 + return json({ result: await this.#completeCommit(payload, now) });
160 + case '/intent/stale':
161 + return json({ result: await this.#markStale(payload, now) });
162 + default:
163 + return new Response('Not Found', { status: 404 });
164 + }
165 + } catch (error) {
166 + return json(
167 + { error: String(error?.message || 'Workspace store operation failed') },
168 + 400
169 + );
170 + }
171 + }
172 + async #schedule(expiresAt) {
173 + const expiry = Number(expiresAt);
174 + if (!Number.isFinite(expiry)) return;
175 + const current = Number(await this.state.storage.get('__next_alarm'));
176 + if (!Number.isFinite(current) || expiry < current) {
177 + await this.state.storage.put('__next_alarm', expiry);
178 + await this.state.storage.setAlarm(expiry);
179 + }
180 + }
181 + async #getExpiring(key, now) {
182 + if (!key || key.endsWith(':')) return null;
183 + const record = await this.state.storage.get(key);
184 + if (!record) return null;
185 + if (expired(record, now)) {
186 + await this.state.storage.delete(key);
187 + return null;
188 + }
189 + return record;
190 + }
191 + async #createRefs(payload, now) {
192 + if (!Array.isArray(payload.refs))
193 + throw new Error('Navigation refs are required');
194 + const expiresAt = now + positiveTtl(payload.ttlMs, REF_TTL_MS),
195 + output = [];
196 + for (const source of payload.refs) {
197 + const refId = randomHandle(10),
198 + type = ['dir', 'file', 'workspace-add', 'workspace-file'].includes(
199 + source?.type
200 + )
201 + ? source.type
202 + : 'file',
203 + workspaceId = String(source?.workspaceId || '');
204 + if (
205 + type.startsWith('workspace-') &&
206 + !/^[A-Za-z0-9_-]{10}$/.test(workspaceId)
207 + )
208 + throw new Error('Workspace navigation ref is invalid');
209 + const record = {
210 + repoId: source?.repoId,
211 + path: String(source?.path || ''),
212 + type,
213 + sha: String(source?.sha || ''),
214 + ...(type.startsWith('workspace-') ? { workspaceId } : {}),
215 + expiresAt
216 + };
217 + await this.state.storage.put(`ref:${refId}`, record);
218 + output.push({ refId });
219 + }
220 + await this.#schedule(expiresAt);
221 + return output;
222 + }
223 + async #createWorkspace(payload, now) {
224 + const id = randomHandle(10),
225 + expiresAt = Number.isFinite(Number(payload.expiresAt))
226 + ? Number(payload.expiresAt)
227 + : now + WORKSPACE_TTL_MS;
228 + if (expiresAt <= now)
229 + throw new Error('Workspace expiry must be in the future');
230 + const first = legacyFile(payload);
231 + validateFiles([first]);
232 + const workspace = {
233 + id,
234 + schemaVersion: 2,
235 + repoId: payload.repoId,
236 + repoFullName: String(payload.repoFullName || ''),
237 + baseBranch: String(payload.baseBranch || ''),
238 + baseHeadSha: String(payload.baseHeadSha || ''),
239 + baseTreeSha: String(payload.baseTreeSha || ''),
240 + path: first.path,
241 + blobSha: first.blobSha,
242 + originalText: first.originalText,
243 + originalDigest: first.originalDigest,
244 + draftText: first.draftText,
245 + draftDigest: first.draftDigest,
246 + files: [first],
247 + commitMessage: '',
248 + commitMessageDigest: '',
249 + currentIntentId: null,
250 + state: 'DRAFT',
251 + createdAt: now,
252 + updatedAt: now,
253 + expiresAt
254 + };
255 + await this.state.storage.put(`ws:${id}`, workspace);
256 + await this.#schedule(expiresAt);
257 + return workspace;
258 + }
259 + async #requireWorkspace(id, now) {
260 + const ws = migrate(await this.#getExpiring(`ws:${String(id || '')}`, now));
261 + if (!ws) throw new Error('Workspace not found or expired');
262 + return ws;
263 + }
264 + async #saveMaterial(ws, files, now) {
265 + validateFiles(files);
266 + const primary = files[0];
267 + const updated = {
268 + ...ws,
269 + schemaVersion: 2,
270 + files,
271 + path: primary.path,
272 + blobSha: primary.blobSha,
273 + originalText: primary.originalText,
274 + originalDigest: primary.originalDigest,
275 + draftText: primary.draftText,
276 + draftDigest: primary.draftDigest,
277 + currentIntentId: null,
278 + state: 'DRAFT',
279 + updatedAt: now
280 + };
281 + await this.state.storage.put(`ws:${ws.id}`, updated);
282 + return updated;
283 + }
284 + async #upsertFile(payload, now) {
285 + const ws = await this.#requireWorkspace(payload.workspaceId, now),
286 + source = payload.file || {},
287 + path = normalizePath(source.path);
288 + if (ws.files.some((f) => normalizePath(f.path) === path))
289 + throw new Error('Workspace file path already exists');
290 + const file = {
291 + path,
292 + blobSha: String(source.blobSha || ''),
293 + originalText: String(source.originalText ?? ''),
294 + originalDigest: String(source.originalDigest || ''),
295 + draftText: String(source.draftText ?? source.originalText ?? ''),
296 + draftDigest: String(source.draftDigest || source.originalDigest || '')
297 + };
298 + return this.#saveMaterial(ws, [...ws.files, file], now);
299 + }
300 + async #updateFileDraft(payload, now) {
301 + const ws = await this.#requireWorkspace(payload.workspaceId, now),
302 + path = normalizePath(payload.path),
303 + digest = String(payload.digest || '');
304 + if (!digest) throw new Error('Draft digest is required');
305 + let found = false;
306 + const files = ws.files.map((f) =>
307 + normalizePath(f.path) === path
308 + ? ((found = true),
309 + { ...f, draftText: String(payload.text ?? ''), draftDigest: digest })
310 + : f
311 + );
312 + if (!found) throw new Error('Workspace file not found');
313 + if (
314 + ws.files.find((f) => normalizePath(f.path) === path)?.draftDigest ===
315 + digest
316 + )
317 + return ws;
318 + return this.#saveMaterial(ws, files, now);
319 + }
320 + async #removeFile(payload, now) {
321 + const ws = await this.#requireWorkspace(payload.workspaceId, now),
322 + path = normalizePath(payload.path),
323 + files = ws.files.filter((f) => normalizePath(f.path) !== path);
324 + if (files.length === ws.files.length)
325 + throw new Error('Workspace file not found');
326 + return this.#saveMaterial(ws, files, now);
327 + }
328 + async #updateDraft(payload, now) {
329 + const ws = await this.#requireWorkspace(payload.workspaceId, now),
330 + digest = String(payload.digest || '');
331 + if (!digest) throw new Error('Draft digest is required');
332 + if (digest === ws.draftDigest) return ws;
333 + const files = ws.files.map((f, i) =>
334 + i
335 + ? f
336 + : { ...f, draftText: String(payload.text ?? ''), draftDigest: digest }
337 + );
338 + return this.#saveMaterial(ws, files, now);
339 + }
340 + async #setCommitMessage(payload, now) {
341 + const ws = await this.#requireWorkspace(payload.workspaceId, now),
342 + digest = String(payload.digest || '');
343 + if (!digest) throw new Error('Commit message digest is required');
344 + const changed = digest !== ws.commitMessageDigest,
345 + updated = {
346 + ...ws,
347 + commitMessage: String(payload.message || ''),
348 + commitMessageDigest: digest,
349 + updatedAt: now,
350 + ...(changed ? { currentIntentId: null, state: 'DRAFT' } : {})
351 + };
352 + await this.state.storage.put(`ws:${ws.id}`, updated);
353 + return updated;
354 + }
355 + async #setPending(payload, now) {
356 + const ws = await this.#requireWorkspace(payload.workspaceId, now),
357 + mode = String(payload.mode || '');
358 + if (!['draft', 'draft_file', 'commit_message'].includes(mode))
359 + throw new Error('Pending input mode is invalid');
360 + const pending = { workspaceId: ws.id, mode, expiresAt: ws.expiresAt };
361 + await this.state.storage.put('pending', pending);
362 + await this.#schedule(pending.expiresAt);
363 + return pending;
364 + }
365 + async #getPending(now) {
366 + const p = await this.state.storage.get('pending');
367 + if (!p) return null;
368 + if (expired(p, now)) {
369 + await this.state.storage.delete('pending');
370 + return null;
371 + }
372 + const ws = await this.#getExpiring(`ws:${p.workspaceId}`, now);
373 + if (!ws) {
374 + await this.state.storage.delete('pending');
375 + return null;
376 + }
377 + return { workspaceId: p.workspaceId, mode: p.mode };
378 + }
379 + async #consumePending(payload, now) {
380 + return this.state.storage.transaction(async (txn) => {
381 + const p = await txn.get('pending');
382 + if (!p || expired(p, now)) {
383 + if (p) await txn.delete('pending');
384 + return false;
385 + }
386 + if (
387 + p.workspaceId !== String(payload.workspaceId || '') ||
388 + p.mode !== String(payload.mode || '')
389 + )
390 + return false;
391 + await txn.delete('pending');
392 + return true;
393 + });
394 + }
395 + async #sealIntent(payload, now) {
396 + const ws = await this.#requireWorkspace(payload.workspaceId, now),
397 + proposed =
398 + payload.intent && typeof payload.intent === 'object'
399 + ? payload.intent
400 + : null;
401 + if (!proposed?.intentDigest)
402 + throw new Error('Commit intent digest is required');
403 + if (ws.currentIntentId) {
404 + const existing = await this.#getExpiring(
405 + `intent:${ws.currentIntentId}`,
406 + now
407 + );
408 + if (existing?.intentDigest === proposed.intentDigest) return existing;
409 + }
410 + const id = randomHandle(8),
411 + intent = {
412 + ...proposed,
413 + id,
414 + workspaceId: ws.id,
415 + state: 'READY',
416 + candidateCommitSha: null,
417 + commitSha: null,
418 + branch: null,
419 + createdAt: now,
420 + updatedAt: now,
421 + expiresAt: ws.expiresAt
422 + };
423 + await this.state.storage.put(`intent:${id}`, intent);
424 + await this.state.storage.put(`ws:${ws.id}`, {
425 + ...ws,
426 + currentIntentId: id,
427 + state: 'READY',
428 + updatedAt: now
429 + });
430 + await this.#schedule(intent.expiresAt);
431 + return intent;
432 + }
433 + async #beginCommit(payload, now) {
434 + const key = `intent:${String(payload.intentId || '')}`;
435 + return this.state.storage.transaction(async (txn) => {
436 + const intent = await txn.get(key);
437 + if (!intent || expired(intent, now))
438 + throw new Error('Commit intent not found or expired');
439 + if (intent.state === 'COMMITTED')
440 + return { disposition: 'committed', intent };
441 + if (intent.state === 'COMMITTING')
442 + return { disposition: 'resume', intent };
443 + if (intent.state !== 'READY')
444 + throw new Error(`Commit intent is ${intent.state || 'invalid'}`);
445 + const updated = { ...intent, state: 'COMMITTING', updatedAt: now };
446 + await txn.put(key, updated);
447 + return { disposition: 'start', intent: updated };
448 + });
449 + }
450 + async #setCandidate(payload, now) {
451 + const key = `intent:${String(payload.intentId || '')}`;
452 + return this.state.storage.transaction(async (txn) => {
453 + const intent = await txn.get(key);
454 + if (!intent || expired(intent, now))
455 + throw new Error('Commit intent not found or expired');
456 + if (intent.state === 'COMMITTED') return intent;
457 + if (intent.state !== 'COMMITTING')
458 + throw new Error('Commit intent is not committing');
459 + const updated = {
460 + ...intent,
461 + candidateCommitSha: String(payload.commitSha || ''),
462 + updatedAt: now
463 + };
464 + await txn.put(key, updated);
465 + return updated;
466 + });
467 + }
468 + async #completeCommit(payload, now) {
469 + const key = `intent:${String(payload.intentId || '')}`,
470 + retainedUntil = now + COMMITTED_RETENTION_MS;
471 + const completed = await this.state.storage.transaction(async (txn) => {
472 + const intent = await txn.get(key);
473 + if (!intent) throw new Error('Commit intent not found');
474 + if (intent.state === 'COMMITTED') return intent;
475 + if (intent.state !== 'COMMITTING')
476 + throw new Error('Commit intent is not committing');
477 + const updated = {
478 + ...intent,
479 + state: 'COMMITTED',
480 + commitSha: String(payload.commitSha || ''),
481 + branch: String(payload.branch || ''),
482 + updatedAt: now,
483 + expiresAt: retainedUntil
484 + };
485 + await txn.put(key, updated);
486 + const wk = `ws:${intent.workspaceId}`,
487 + ws = await txn.get(wk);
488 + if (ws)
489 + await txn.put(wk, {
490 + ...ws,
491 + state: 'COMMITTED',
492 + currentIntentId: intent.id,
493 + commitSha: updated.commitSha,
494 + branch: updated.branch,
495 + updatedAt: now,
496 + expiresAt: retainedUntil
497 + });
498 + return updated;
499 + });
500 + await this.#schedule(retainedUntil);
501 + return completed;
502 + }
503 + async #markStale(payload, now) {
504 + const key = `intent:${String(payload.intentId || '')}`;
505 + return this.state.storage.transaction(async (txn) => {
506 + const intent = await txn.get(key);
507 + if (!intent) throw new Error('Commit intent not found');
508 + if (intent.state === 'COMMITTED') return intent;
509 + const updated = {
510 + ...intent,
511 + state: 'STALE',
512 + staleReason: String(payload.reason || 'stale'),
513 + updatedAt: now
514 + };
515 + await txn.put(key, updated);
516 + return updated;
517 + });
518 + }
519 + async #cancelWorkspace(payload) {
520 + const id = String(payload.workspaceId || '');
521 + if (!id) throw new Error('Workspace ID is required');
522 + await this.state.storage.transaction(async (txn) => {
523 + await txn.delete(`ws:${id}`);
524 + const p = await txn.get('pending');
525 + if (p?.workspaceId === id) await txn.delete('pending');
526 + });
527 + return { cancelled: true };
528 + }
529 + async alarm() {
530 + const now = Date.now(),
531 + entries = await this.state.storage.list();
532 + let next = Infinity;
533 + for (const [key, value] of entries) {
534 + if (key === '__next_alarm') continue;
535 + const expiry = Number(value?.expiresAt);
536 + if (!Number.isFinite(expiry)) continue;
537 + if (expiry <= now) await this.state.storage.delete(key);
538 + else next = Math.min(next, expiry);
539 + }
540 + await this.state.storage.delete('__next_alarm');
541 + if (Number.isFinite(next)) {
542 + await this.state.storage.put('__next_alarm', next);
543 + await this.state.storage.setAlarm(next);
544 + }
545 + }
546 }
src/github.js
+814 -60
@@ -1,65 +1,819 @@
1 import { DEFAULT_CONFIG } from './config.js';
2
3 -const clampPage = value => Math.max(1, Math.min(100, Number(value) || 1));
4 -const clampPerPage = (value, fallback = 10) => Math.max(1, Math.min(20, Number(value) || fallback));
5 -const boundedPatch = value => String(value || '').slice(0, 1200);
6 -const numericId = (value, label) => { const text = String(value ?? ''); if (!/^\d+$/.test(text)) throw new Error(`Invalid ${label} ID`); return text; };
7 -const fullSha = (value, label = 'Git commit') => { const text = String(value || ''); if (!/^[a-f0-9]{40}$/i.test(text)) throw new Error(`Invalid ${label} SHA`); return text; };
8 -const gitBranch = value => { const branch = String(value || ''); if (!branch || branch.includes('..') || branch.startsWith('/') || branch.endsWith('/') || branch.includes('\0')) throw new Error('Invalid Git branch'); return branch; };
9 -const encodedBranch = value => gitBranch(value).split('/').map(encodeURIComponent).join('/');
10 -const encodedPath = value => String(value || '').split('/').filter(Boolean).map(encodeURIComponent).join('/');
11 -const decodeBase64Utf8 = value => { let binary; try { binary = atob(String(value || '').replace(/\s/g, '')); } catch { throw new Error('GitHub file content is not valid base64'); } const bytes = Uint8Array.from(binary, char => char.charCodeAt(0)); try { return new TextDecoder('utf-8', { fatal: true }).decode(bytes); } catch { throw new Error('GitHub file content is not valid UTF-8 text'); } };
3 +const clampPage = (value) => Math.max(1, Math.min(100, Number(value) || 1));
4 +const clampPerPage = (value, fallback = 10) =>
5 + Math.max(1, Math.min(20, Number(value) || fallback));
6 +const boundedPatch = (value) => String(value || '').slice(0, 1200);
7 +const numericId = (value, label) => {
8 + const text = String(value ?? '');
9 + if (!/^\d+$/.test(text)) throw new Error(`Invalid ${label} ID`);
10 + return text;
11 +};
12 +const fullSha = (value, label = 'Git commit') => {
13 + const text = String(value || '');
14 + if (!/^[a-f0-9]{40}$/i.test(text)) throw new Error(`Invalid ${label} SHA`);
15 + return text;
16 +};
17 +const gitBranch = (value) => {
18 + const branch = String(value || '');
19 + if (
20 + !branch ||
21 + branch.includes('..') ||
22 + branch.startsWith('/') ||
23 + branch.endsWith('/') ||
24 + branch.includes('\0')
25 + )
26 + throw new Error('Invalid Git branch');
27 + return branch;
28 +};
29 +const encodedBranch = (value) =>
30 + gitBranch(value).split('/').map(encodeURIComponent).join('/');
31 +const encodedPath = (value) =>
32 + String(value || '')
33 + .split('/')
34 + .filter(Boolean)
35 + .map(encodeURIComponent)
36 + .join('/');
37 +const decodeBase64Utf8 = (value) => {
38 + let binary;
39 + try {
40 + binary = atob(String(value || '').replace(/\s/g, ''));
41 + } catch {
42 + throw new Error('GitHub file content is not valid base64');
43 + }
44 + const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
45 + try {
46 + return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
47 + } catch {
48 + throw new Error('GitHub file content is not valid UTF-8 text');
49 + }
50 +};
51
52 export class GitHubService {
14 - constructor(token = '', owner = DEFAULT_CONFIG.defaultOwner) { this.token = token; this.owner = owner; this.baseUrl = 'https://api.github.com'; }
15 - requireToken() { if (!this.token) throw new Error('GITHUB_TOKEN is not configured'); }
16 - getHeaders() { this.requireToken(); return { 'User-Agent': 'Nexa-Dev-Bot-v1.1', 'Accept': 'application/vnd.github+json', 'Authorization': `Bearer ${this.token}`, 'X-GitHub-Api-Version': '2022-11-28' }; }
17 - async requestJson(url, label, { method = 'GET', body, allowEmpty = false, allowNotFound = false } = {}) { const headers = this.getHeaders(); const options = { method, headers }; if (body !== undefined) { options.body = JSON.stringify(body); options.headers = { ...headers, 'Content-Type': 'application/json' }; } const res = await fetch(url, options); const raw = await res.text(); let parsed = null; if (raw) { try { parsed = JSON.parse(raw); } catch { parsed = null; } } if (!res.ok) { if (allowNotFound && res.status === 404) return null; const providerMessage = parsed?.message || raw.slice(0, 240); const detail = providerMessage ? ` ${providerMessage}` : ''; const error = new Error(`${label} failed: ${res.status}${detail}`); error.status = res.status; throw error; } if (allowEmpty) return { accepted: true, status: res.status }; if (!raw) return null; if (parsed === null) throw new Error(`${label} failed: invalid JSON response`); return parsed; }
18 - async requestText(url, label, { maxChars = 12000 } = {}) { const res = await fetch(url, { method: 'GET', headers: this.getHeaders() }); const raw = await res.text(); if (!res.ok) { const detail = raw ? ` ${raw.slice(0, 240)}` : ''; throw new Error(`${label} failed: ${res.status}${detail}`); } const limit = Math.max(1, Math.min(20000, Number(maxChars) || 12000)); return { text: raw.length > limit ? raw.slice(-limit) : raw, truncated: raw.length > limit }; }
19 - repoUrl(repo, suffix = '') { return `${this.baseUrl}/repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(repo)}${suffix}`; }
20 - repositoryLookupUrl(repoRef) { const value = String(repoRef || ''); return /^\d+$/.test(value) ? `${this.baseUrl}/repositories/${value}` : this.repoUrl(value); }
21 - repositoryApiBase(fullName) { const parts = String(fullName || '').split('/').filter(Boolean); if (parts.length !== 2) throw new Error('GitHub repository full_name is invalid'); return `${this.baseUrl}/repos/${parts.map(encodeURIComponent).join('/')}`; }
22 - async getRepositoryContext(repoRef) { const value = String(repoRef || ''); try { const raw = await this.requestJson(this.repositoryLookupUrl(value), 'GitHub repository'); return { raw, apiBase: this.repositoryApiBase(raw.full_name) }; } catch (error) { if (!/^\d+$/.test(value) || error?.status !== 404) throw error; const repositories = await this.listRepositories(); const match = repositories.find(repo => repo.id === value); if (!match?.fullName) throw error; const apiBase = this.repositoryApiBase(match.fullName); const raw = await this.requestJson(apiBase, 'GitHub repository'); return { raw, apiBase: this.repositoryApiBase(raw.full_name) }; } }
23 - mapRepository(r) { return { id: String(r.id ?? r.name), name: r.name, fullName: r.full_name, private: !!r.private, description: r.description || '', defaultBranch: r.default_branch || 'main', archived: !!r.archived, htmlUrl: r.html_url || '', stars: r.stargazers_count ?? 0, forks: r.forks_count ?? 0 }; }
24 - mapWorkflowRun(run = {}) { const headSha = String(run.head_sha || ''); const mapped = { id: run.id, name: run.name || 'Workflow', status: run.status || '', conclusion: run.conclusion || null, event: run.event || '', branch: run.head_branch || '', sha: headSha.slice(0, 7), runNumber: run.run_number ?? null, url: run.html_url || '', createdAt: run.created_at || '', updatedAt: run.updated_at || '' }; if (/^[a-f0-9]{40}$/i.test(headSha)) mapped.fullSha = headSha.toLowerCase(); if (Number.isSafeInteger(Number(run.workflow_id))) mapped.workflowId = Number(run.workflow_id); return mapped; }
25 - mapWorkflowJob(job = {}) { return { id: job.id, name: job.name || 'Job', status: job.status || '', conclusion: job.conclusion || null, startedAt: job.started_at || '', completedAt: job.completed_at || '', url: job.html_url || '', steps: (job.steps || []).slice(0, 30).map(step => ({ number: step.number, name: step.name || 'Step', status: step.status || '', conclusion: step.conclusion || null })) }; }
26 - mapPullRequestFile(file = {}) { return { filename: file.filename || '', status: file.status || '', additions: file.additions ?? 0, deletions: file.deletions ?? 0, changes: file.changes ?? 0, patch: boundedPatch(file.patch) }; }
27 - mapIssue(issue = {}) { return { number: issue.number, title: issue.title || '', state: issue.state || '', author: issue.user?.login || 'unknown', comments: issue.comments ?? 0, url: issue.html_url || '' }; }
28 - async listRepositories() { const data = await this.requestJson(`${this.baseUrl}/user/repos?sort=updated&per_page=20&affiliation=owner,collaborator,organization_member`, 'GitHub repositories'); return data.map(r => { const repo = this.mapRepository(r); return { ...repo, title: `${repo.name} ${repo.private ? '🔒' : '🌐'}` }; }); }
29 - async getRepository(repoRef) { const { raw } = await this.getRepositoryContext(repoRef); return this.mapRepository(raw); }
30 - async listPullRequests(repoRef, { perPage = 10, page = 1 } = {}) { const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const pageQuery = pageNumber > 1 ? `&page=${pageNumber}` : ''; const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/pulls?state=all&per_page=${count}${pageQuery}`, 'GitHub pull requests'); return data.map(pr => ({ number: pr.number, title: pr.title, author: pr.user?.login || 'unknown', state: pr.state, merged: !!pr.merged_at, createdAt: pr.created_at, url: pr.html_url })); }
31 - async getPullRequest(repoRef, prNumber) { const number = numericId(prNumber, 'pull request'); const { apiBase } = await this.getRepositoryContext(repoRef); const pr = await this.requestJson(`${apiBase}/pulls/${number}`, 'GitHub pull request'); return { number: pr.number, title: pr.title || '', author: pr.user?.login || 'unknown', state: pr.state || '', merged: !!(pr.merged ?? pr.merged_at), body: pr.body || '', url: pr.html_url || '', head: pr.head?.ref || '', headSha: pr.head?.sha || '', base: pr.base?.ref || '', additions: pr.additions ?? 0, deletions: pr.deletions ?? 0, changedFiles: pr.changed_files ?? 0 }; }
32 - async listPullRequestFiles(repoRef, prNumber, { perPage = 20, page = 1 } = {}) { const number = numericId(prNumber, 'pull request'); const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/pulls/${number}/files?per_page=${count}&page=${pageNumber}`, 'GitHub pull request files'); return data.map(file => this.mapPullRequestFile(file)); }
33 - async listCommits(repoRef) { const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/commits?per_page=5`, 'GitHub commits'); return data.map(c => ({ sha: String(c.sha || '').slice(0, 7), fullSha: String(c.sha || ''), message: String(c.commit?.message || '').split('\n')[0], author: c.author?.login || c.commit?.author?.name || 'Unknown', date: c.commit?.author?.date ? c.commit.author.date.slice(0, 10) : '' })); }
34 - async getCommit(repoRef, sha) { const commitSha = fullSha(sha); const { apiBase } = await this.getRepositoryContext(repoRef); const c = await this.requestJson(`${apiBase}/commits/${commitSha}`, 'GitHub commit'); const files = (c.files || []).slice(0, 20).map(file => ({ filename: file.filename || '', status: file.status || '', additions: file.additions ?? 0, deletions: file.deletions ?? 0, changes: file.changes ?? 0 })); return { sha: commitSha, shortSha: commitSha.slice(0, 7), message: String(c.commit?.message || ''), author: c.author?.login || c.commit?.author?.name || 'Unknown', date: c.commit?.author?.date || '', additions: c.stats?.additions ?? 0, deletions: c.stats?.deletions ?? 0, changedFiles: files.length, files }; }
35 - async listCommitChecks(repoRef, sha, { perPage = 20, page = 1 } = {}) { const commitSha = fullSha(sha); const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/commits/${commitSha}/check-runs?per_page=${count}&page=${pageNumber}`, 'GitHub check runs'); return (data.check_runs || []).map(check => ({ id: check.id, name: check.name || 'Check', status: check.status || '', conclusion: check.conclusion || null, url: check.html_url || '' })); }
36 - async listFiles(repoRef, path = '', { ref } = {}) { const { apiBase } = await this.getRepositoryContext(repoRef); const suffix = path ? `/contents/${encodedPath(path)}` : '/contents'; const query = ref ? `?ref=${encodeURIComponent(String(ref))}` : ''; const data = await this.requestJson(`${apiBase}${suffix}${query}`, 'GitHub contents'); if (!Array.isArray(data)) throw new Error('GitHub contents response is not a directory listing'); return data.map(item => ({ name: item.name, path: item.path, type: item.type === 'dir' ? 'dir' : 'file', size: item.size ?? 0, sha: item.sha || '' })); }
37 - async getGitRef(repoRef, branch, { allowMissing = false } = {}) { const branchName = gitBranch(branch); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/ref/heads/${encodedBranch(branchName)}`, 'GitHub branch ref', { allowNotFound: allowMissing }); if (data === null) return null; return { branch: branchName, sha: fullSha(data?.object?.sha, 'Git branch head') }; }
38 - async getBranchSnapshot(repoRef, branch) { const branchName = gitBranch(branch); const { apiBase } = await this.getRepositoryContext(repoRef); const ref = await this.requestJson(`${apiBase}/git/ref/heads/${encodedBranch(branchName)}`, 'GitHub branch ref'); const headSha = fullSha(ref?.object?.sha, 'Git branch head'); const commit = await this.requestJson(`${apiBase}/git/commits/${headSha}`, 'GitHub branch commit'); const treeSha = fullSha(commit?.tree?.sha, 'Git tree'); return { branch: branchName, headSha, treeSha }; }
39 - async getFileAtRef(repoRef, path, ref) { const filePath = String(path || ''); if (!filePath || filePath.startsWith('/') || filePath.includes('\0')) throw new Error('Invalid GitHub file path'); const commitRef = fullSha(ref); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/contents/${encodedPath(filePath)}?ref=${commitRef}`, 'GitHub file'); if (!data || Array.isArray(data) || data.type !== 'file') throw new Error('GitHub contents response is not a file'); if (data.encoding !== 'base64') throw new Error('GitHub file encoding is not supported'); const content = decodeBase64Utf8(data.content || ''); return { path: data.path || filePath, sha: String(data.sha || ''), size: Number(data.size) || 0, encoding: 'utf-8', content }; }
40 - async createGitBlob(repoRef, text) { const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/blobs`, 'GitHub create blob', { method: 'POST', body: { content: String(text ?? ''), encoding: 'utf-8' } }); return { sha: fullSha(data?.sha, 'Git blob') }; }
41 - async createGitTree(repoRef, { baseTreeSha, entries } = {}) { const base = fullSha(baseTreeSha, 'Git base tree'); if (!Array.isArray(entries)) throw new Error('Git tree entries are required'); const tree = entries.map(entry => { const path = String(entry?.path || ''); if (!path || path.startsWith('/') || path.includes('\0')) throw new Error('Invalid Git tree path'); if (entry?.mode !== '100644' || entry?.type !== 'blob') throw new Error('Unsupported Git tree entry'); return { path, mode: '100644', type: 'blob', sha: fullSha(entry.sha, 'Git blob') }; }); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/trees`, 'GitHub create tree', { method: 'POST', body: { base_tree: base, tree } }); return { sha: fullSha(data?.sha, 'Git tree') }; }
42 - async createGitCommit(repoRef, { message, treeSha, parentSha, timestamp } = {}) { const commitMessage = String(message || ''); if (!commitMessage) throw new Error('Git commit message is required'); const tree = fullSha(treeSha, 'Git tree'); const parent = fullSha(parentSha, 'Git parent commit'); const date = new Date(String(timestamp || '')); if (Number.isNaN(date.getTime()) || date.toISOString() !== String(timestamp)) throw new Error('Invalid Git commit timestamp'); const identity = { name: 'Nexa Dev Bot', email: 'nexa-dev-bot@users.noreply.github.com', date: String(timestamp) }; const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/commits`, 'GitHub create commit', { method: 'POST', body: { message: commitMessage, tree, parents: [parent], author: identity, committer: identity } }); return { sha: fullSha(data?.sha, 'Git commit') }; }
43 - async createGitBranchRef(repoRef, { branch, sha } = {}) { const branchName = gitBranch(branch); const commitSha = fullSha(sha, 'Git commit'); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/refs`, 'GitHub create branch ref', { method: 'POST', body: { ref: `refs/heads/${branchName}`, sha: commitSha } }); return { ref: String(data?.ref || `refs/heads/${branchName}`), sha: fullSha(data?.object?.sha || commitSha, 'Git commit') }; }
44 - async listTree(repoRef, sha) { if (!/^[a-f0-9]{40}$/i.test(String(sha || ''))) throw new Error('Invalid Git tree SHA'); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/trees/${encodeURIComponent(sha)}`, 'GitHub tree'); return (data.tree || []).filter(item => item.type === 'tree' || item.type === 'blob').map(item => ({ name: item.path, path: item.path, type: item.type === 'tree' ? 'dir' : 'file', size: item.size ?? 0, sha: item.sha || '' })); }
45 - async getBlob(repoRef, sha) { if (!/^[a-f0-9]{40}$/i.test(String(sha || ''))) throw new Error('Invalid Git blob SHA'); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/blobs/${encodeURIComponent(sha)}`, 'GitHub blob'); return { encoding: data.encoding || '', size: data.size ?? 0, content: data.content || '' }; }
46 - async getRepoStatus(repoRef) { const { raw, apiBase } = await this.getRepositoryContext(repoRef); const runsData = await this.requestJson(`${apiBase}/actions/runs?per_page=3`, 'GitHub Actions runs'); const runs = runsData.workflow_runs || []; return { repo: String(repoRef), repoName: raw.name, defaultBranch: raw.default_branch || 'main', lastRuns: runs.map(r => ({ name: r.name, status: r.status, conclusion: r.conclusion, commit: r.head_commit?.message?.slice(0, 80) || '', url: r.html_url || '' })) }; }
47 - async listWorkflowRuns(repoRef, { perPage = 10, page = 1 } = {}) { const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const pageQuery = pageNumber > 1 ? `&page=${pageNumber}` : ''; const data = await this.requestJson(`${apiBase}/actions/runs?per_page=${count}${pageQuery}`, 'GitHub workflow runs'); return (data.workflow_runs || []).map(run => this.mapWorkflowRun(run)); }
48 - async getWorkflowRun(repoRef, runId) { const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef); return this.mapWorkflowRun(await this.requestJson(`${apiBase}/actions/runs/${id}`, 'GitHub workflow run')); }
49 - async listWorkflowJobs(repoRef, runId) { const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/actions/runs/${id}/jobs?per_page=20`, 'GitHub workflow jobs'); return (data.jobs || []).map(job => this.mapWorkflowJob(job)); }
50 - async getWorkflowJob(repoRef, jobId) { const id = numericId(jobId, 'workflow job'); const { apiBase } = await this.getRepositoryContext(repoRef); return this.mapWorkflowJob(await this.requestJson(`${apiBase}/actions/jobs/${id}`, 'GitHub workflow job')); }
51 - async getWorkflowJobLog(repoRef, jobId, { maxChars = 12000 } = {}) { const id = numericId(jobId, 'workflow job'); const { apiBase } = await this.getRepositoryContext(repoRef); return this.requestText(`${apiBase}/actions/jobs/${id}/logs`, 'GitHub workflow job log', { maxChars }); }
52 - async listWorkflowArtifacts(repoRef, runId, { perPage = 20, page = 1 } = {}) { const id = numericId(runId, 'workflow run'); const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/actions/runs/${id}/artifacts?per_page=${count}&page=${pageNumber}`, 'GitHub workflow artifacts'); return (data.artifacts || []).map(artifact => ({ id: artifact.id, name: artifact.name || 'Artifact', size: artifact.size_in_bytes ?? 0, expired: !!artifact.expired, createdAt: artifact.created_at || '', expiresAt: artifact.expires_at || '', downloadUrl: artifact.archive_download_url || '' })); }
53 - async listBranches(repoRef, { perPage = 20, page = 1 } = {}) { const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/branches?per_page=${count}&page=${pageNumber}`, 'GitHub branches'); return data.map(branch => ({ name: branch.name || '', sha: branch.commit?.sha || '', protected: !!branch.protected })); }
54 - async compareWithDefault(repoRef, headSha) { const head = fullSha(headSha); const { raw, apiBase } = await this.getRepositoryContext(repoRef); const base = raw.default_branch || 'main'; const data = await this.requestJson(`${apiBase}/compare/${encodeURIComponent(base)}...${head}`, 'GitHub compare'); return { base, head, status: data.status || '', aheadBy: data.ahead_by ?? 0, behindBy: data.behind_by ?? 0, totalCommits: data.total_commits ?? 0, baseSha: data.base_commit?.sha || '', mergeBaseSha: data.merge_base_commit?.sha || '', files: (data.files || []).slice(0, 20).map(file => this.mapPullRequestFile(file)) }; }
55 - async listIssues(repoRef, { perPage = 10, page = 1 } = {}) { const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/issues?state=all&per_page=${count}&page=${pageNumber}`, 'GitHub issues'); return data.filter(issue => !issue.pull_request).map(issue => this.mapIssue(issue)); }
56 - async listIssuesPage(repoRef, { page = 1 } = {}) { const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/issues?state=all&per_page=20&page=${pageNumber}`, 'GitHub issues'); return { items: data.filter(issue => !issue.pull_request).map(issue => this.mapIssue(issue)), hasMore: data.length === 20 }; }
57 - async getIssue(repoRef, issueNumber) { const number = numericId(issueNumber, 'issue'); const { apiBase } = await this.getRepositoryContext(repoRef); const issue = await this.requestJson(apiBase + '/issues/' + number, 'GitHub issue'); return { ...this.mapIssue(issue), body: issue.body || '', labels: (issue.labels || []).map(label => typeof label === 'string' ? label : label.name).filter(Boolean), assignees: (issue.assignees || []).map(user => user.login).filter(Boolean), createdAt: issue.created_at || '', updatedAt: issue.updated_at || '' }; }
58 - async listReleases(repoRef, { perPage = 10, page = 1 } = {}) { const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/releases?per_page=${count}&page=${pageNumber}`, 'GitHub releases'); return data.map(release => ({ id: release.id, tag: release.tag_name || '', name: release.name || release.tag_name || 'Release', draft: !!release.draft, prerelease: !!release.prerelease, publishedAt: release.published_at || release.created_at || '', url: release.html_url || '' })); }
59 - async getRelease(repoRef, releaseId) { const id = numericId(releaseId, 'release'); const { apiBase } = await this.getRepositoryContext(repoRef); const release = await this.requestJson(apiBase + '/releases/' + id, 'GitHub release'); return { id: release.id, tag: release.tag_name || '', name: release.name || release.tag_name || 'Release', body: release.body || '', draft: !!release.draft, prerelease: !!release.prerelease, publishedAt: release.published_at || release.created_at || '', author: release.author?.login || 'unknown', target: release.target_commitish || '', url: release.html_url || '' }; }
60 - async mergePullRequest(repoRef, prNumber, { expectedHeadSha, mergeMethod = 'squash' } = {}) { const number = numericId(prNumber, 'pull request'); const method = String(mergeMethod || 'squash'); if (!['merge', 'squash', 'rebase'].includes(method)) throw new Error('Unsupported merge method'); const expected = fullSha(expectedHeadSha, 'expected pull request head'); const { apiBase } = await this.getRepositoryContext(repoRef); const result = await this.requestJson(`${apiBase}/pulls/${number}/merge`, 'GitHub pull request merge', { method: 'PUT', body: { sha: expected, merge_method: method } }); if (!result?.merged) throw new Error(`GitHub pull request merge failed: ${String(result?.message || 'not merged').slice(0, 240)}`); return { merged: true, sha: String(result.sha || ''), message: String(result.message || '') }; }
61 - async dispatchWorkflow(repoRef, workflowId, { ref, inputs = {} } = {}) { const id = numericId(workflowId, 'workflow'); const targetRef = String(ref || ''); if (!targetRef || targetRef.includes('\0')) throw new Error('Workflow dispatch ref is required'); if (!inputs || typeof inputs !== 'object' || Array.isArray(inputs)) throw new Error('Workflow dispatch inputs must be an object'); const { apiBase } = await this.getRepositoryContext(repoRef); return this.requestJson(`${apiBase}/actions/workflows/${id}/dispatches`, 'GitHub workflow dispatch', { method: 'POST', body: { ref: targetRef, inputs }, allowEmpty: true }); }
62 - async rerunJob(repoRef, jobId) { const id = numericId(jobId, 'workflow job'); const { apiBase } = await this.getRepositoryContext(repoRef); return this.requestJson(`${apiBase}/actions/jobs/${id}/rerun`, 'GitHub rerun workflow job', { method: 'POST', allowEmpty: true }); }
63 - async rerunFailedWorkflowRun(repoRef, runId) { const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef); return this.requestJson(`${apiBase}/actions/runs/${id}/rerun-failed-jobs`, 'GitHub rerun failed jobs', { method: 'POST', allowEmpty: true }); }
64 - async cancelWorkflowRun(repoRef, runId) { const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef); return this.requestJson(`${apiBase}/actions/runs/${id}/cancel`, 'GitHub cancel workflow run', { method: 'POST', allowEmpty: true }); }
53 + constructor(token = '', owner = DEFAULT_CONFIG.defaultOwner) {
54 + this.token = token;
55 + this.owner = owner;
56 + this.baseUrl = 'https://api.github.com';
57 + }
58 + requireToken() {
59 + if (!this.token) throw new Error('GITHUB_TOKEN is not configured');
60 + }
61 + getHeaders() {
62 + this.requireToken();
63 + return {
64 + 'User-Agent': 'Nexa-Dev-Bot-v1.1',
65 + 'Accept': 'application/vnd.github+json',
66 + 'Authorization': `Bearer ${this.token}`,
67 + 'X-GitHub-Api-Version': '2022-11-28'
68 + };
69 + }
70 + async requestJson(
71 + url,
72 + label,
73 + { method = 'GET', body, allowEmpty = false, allowNotFound = false } = {}
74 + ) {
75 + const headers = this.getHeaders();
76 + const options = { method, headers };
77 + if (body !== undefined) {
78 + options.body = JSON.stringify(body);
79 + options.headers = { ...headers, 'Content-Type': 'application/json' };
80 + }
81 + const res = await fetch(url, options);
82 + const raw = await res.text();
83 + let parsed = null;
84 + if (raw) {
85 + try {
86 + parsed = JSON.parse(raw);
87 + } catch {
88 + parsed = null;
89 + }
90 + }
91 + if (!res.ok) {
92 + if (allowNotFound && res.status === 404) return null;
93 + const providerMessage = parsed?.message || raw.slice(0, 240);
94 + const detail = providerMessage ? ` ${providerMessage}` : '';
95 + const error = new Error(`${label} failed: ${res.status}${detail}`);
96 + error.status = res.status;
97 + throw error;
98 + }
99 + if (allowEmpty) return { accepted: true, status: res.status };
100 + if (!raw) return null;
101 + if (parsed === null)
102 + throw new Error(`${label} failed: invalid JSON response`);
103 + return parsed;
104 + }
105 + async requestText(url, label, { maxChars = 12000 } = {}) {
106 + const res = await fetch(url, { method: 'GET', headers: this.getHeaders() });
107 + const raw = await res.text();
108 + if (!res.ok) {
109 + const detail = raw ? ` ${raw.slice(0, 240)}` : '';
110 + throw new Error(`${label} failed: ${res.status}${detail}`);
111 + }
112 + const limit = Math.max(1, Math.min(20000, Number(maxChars) || 12000));
113 + return {
114 + text: raw.length > limit ? raw.slice(-limit) : raw,
115 + truncated: raw.length > limit
116 + };
117 + }
118 + repoUrl(repo, suffix = '') {
119 + return `${this.baseUrl}/repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(repo)}${suffix}`;
120 + }
121 + repositoryLookupUrl(repoRef) {
122 + const value = String(repoRef || '');
123 + return /^\d+$/.test(value)
124 + ? `${this.baseUrl}/repositories/${value}`
125 + : this.repoUrl(value);
126 + }
127 + repositoryApiBase(fullName) {
128 + const parts = String(fullName || '')
129 + .split('/')
130 + .filter(Boolean);
131 + if (parts.length !== 2)
132 + throw new Error('GitHub repository full_name is invalid');
133 + return `${this.baseUrl}/repos/${parts.map(encodeURIComponent).join('/')}`;
134 + }
135 + async getRepositoryContext(repoRef) {
136 + const value = String(repoRef || '');
137 + try {
138 + const raw = await this.requestJson(
139 + this.repositoryLookupUrl(value),
140 + 'GitHub repository'
141 + );
142 + return { raw, apiBase: this.repositoryApiBase(raw.full_name) };
143 + } catch (error) {
144 + if (!/^\d+$/.test(value) || error?.status !== 404) throw error;
145 + const repositories = await this.listRepositories();
146 + const match = repositories.find((repo) => repo.id === value);
147 + if (!match?.fullName) throw error;
148 + const apiBase = this.repositoryApiBase(match.fullName);
149 + const raw = await this.requestJson(apiBase, 'GitHub repository');
150 + return { raw, apiBase: this.repositoryApiBase(raw.full_name) };
151 + }
152 + }
153 + mapRepository(r) {
154 + return {
155 + id: String(r.id ?? r.name),
156 + name: r.name,
157 + fullName: r.full_name,
158 + private: !!r.private,
159 + description: r.description || '',
160 + defaultBranch: r.default_branch || 'main',
161 + archived: !!r.archived,
162 + htmlUrl: r.html_url || '',
163 + stars: r.stargazers_count ?? 0,
164 + forks: r.forks_count ?? 0
165 + };
166 + }
167 + mapWorkflowRun(run = {}) {
168 + const headSha = String(run.head_sha || '');
169 + const mapped = {
170 + id: run.id,
171 + name: run.name || 'Workflow',
172 + status: run.status || '',
173 + conclusion: run.conclusion || null,
174 + event: run.event || '',
175 + branch: run.head_branch || '',
176 + sha: headSha.slice(0, 7),
177 + runNumber: run.run_number ?? null,
178 + url: run.html_url || '',
179 + createdAt: run.created_at || '',
180 + updatedAt: run.updated_at || ''
181 + };
182 + if (/^[a-f0-9]{40}$/i.test(headSha)) mapped.fullSha = headSha.toLowerCase();
183 + if (Number.isSafeInteger(Number(run.workflow_id)))
184 + mapped.workflowId = Number(run.workflow_id);
185 + return mapped;
186 + }
187 + mapWorkflowJob(job = {}) {
188 + return {
189 + id: job.id,
190 + name: job.name || 'Job',
191 + status: job.status || '',
192 + conclusion: job.conclusion || null,
193 + startedAt: job.started_at || '',
194 + completedAt: job.completed_at || '',
195 + url: job.html_url || '',
196 + steps: (job.steps || []).slice(0, 30).map((step) => ({
197 + number: step.number,
198 + name: step.name || 'Step',
199 + status: step.status || '',
200 + conclusion: step.conclusion || null
201 + }))
202 + };
203 + }
204 + mapPullRequestFile(file = {}) {
205 + return {
206 + filename: file.filename || '',
207 + status: file.status || '',
208 + additions: file.additions ?? 0,
209 + deletions: file.deletions ?? 0,
210 + changes: file.changes ?? 0,
211 + patch: boundedPatch(file.patch)
212 + };
213 + }
214 + mapIssue(issue = {}) {
215 + return {
216 + number: issue.number,
217 + title: issue.title || '',
218 + state: issue.state || '',
219 + author: issue.user?.login || 'unknown',
220 + comments: issue.comments ?? 0,
221 + url: issue.html_url || ''
222 + };
223 + }
224 + async listRepositories() {
225 + const data = await this.requestJson(
226 + `${this.baseUrl}/user/repos?sort=updated&per_page=20&affiliation=owner,collaborator,organization_member`,
227 + 'GitHub repositories'
228 + );
229 + return data.map((r) => {
230 + const repo = this.mapRepository(r);
231 + return { ...repo, title: `${repo.name} ${repo.private ? '🔒' : '🌐'}` };
232 + });
233 + }
234 + async getRepository(repoRef) {
235 + const { raw } = await this.getRepositoryContext(repoRef);
236 + return this.mapRepository(raw);
237 + }
238 + async listPullRequests(repoRef, { perPage = 10, page = 1 } = {}) {
239 + const count = clampPerPage(perPage, 10);
240 + const pageNumber = clampPage(page);
241 + const pageQuery = pageNumber > 1 ? `&page=${pageNumber}` : '';
242 + const { apiBase } = await this.getRepositoryContext(repoRef);
243 + const data = await this.requestJson(
244 + `${apiBase}/pulls?state=all&per_page=${count}${pageQuery}`,
245 + 'GitHub pull requests'
246 + );
247 + return data.map((pr) => ({
248 + number: pr.number,
249 + title: pr.title,
250 + author: pr.user?.login || 'unknown',
251 + state: pr.state,
252 + merged: !!pr.merged_at,
253 + createdAt: pr.created_at,
254 + url: pr.html_url
255 + }));
256 + }
257 + async getPullRequest(repoRef, prNumber) {
258 + const number = numericId(prNumber, 'pull request');
259 + const { apiBase } = await this.getRepositoryContext(repoRef);
260 + const pr = await this.requestJson(
261 + `${apiBase}/pulls/${number}`,
262 + 'GitHub pull request'
263 + );
264 + return {
265 + number: pr.number,
266 + title: pr.title || '',
267 + author: pr.user?.login || 'unknown',
268 + state: pr.state || '',
269 + merged: !!(pr.merged ?? pr.merged_at),
270 + body: pr.body || '',
271 + url: pr.html_url || '',
272 + head: pr.head?.ref || '',
273 + headSha: pr.head?.sha || '',
274 + base: pr.base?.ref || '',
275 + additions: pr.additions ?? 0,
276 + deletions: pr.deletions ?? 0,
277 + changedFiles: pr.changed_files ?? 0
278 + };
279 + }
280 + async listPullRequestFiles(
281 + repoRef,
282 + prNumber,
283 + { perPage = 20, page = 1 } = {}
284 + ) {
285 + const number = numericId(prNumber, 'pull request');
286 + const count = clampPerPage(perPage, 20);
287 + const pageNumber = clampPage(page);
288 + const { apiBase } = await this.getRepositoryContext(repoRef);
289 + const data = await this.requestJson(
290 + `${apiBase}/pulls/${number}/files?per_page=${count}&page=${pageNumber}`,
291 + 'GitHub pull request files'
292 + );
293 + return data.map((file) => this.mapPullRequestFile(file));
294 + }
295 + async listCommits(repoRef) {
296 + const { apiBase } = await this.getRepositoryContext(repoRef);
297 + const data = await this.requestJson(
298 + `${apiBase}/commits?per_page=5`,
299 + 'GitHub commits'
300 + );
301 + return data.map((c) => ({
302 + sha: String(c.sha || '').slice(0, 7),
303 + fullSha: String(c.sha || ''),
304 + message: String(c.commit?.message || '').split('\n')[0],
305 + author: c.author?.login || c.commit?.author?.name || 'Unknown',
306 + date: c.commit?.author?.date ? c.commit.author.date.slice(0, 10) : ''
307 + }));
308 + }
309 + async getCommit(repoRef, sha) {
310 + const commitSha = fullSha(sha);
311 + const { apiBase } = await this.getRepositoryContext(repoRef);
312 + const c = await this.requestJson(
313 + `${apiBase}/commits/${commitSha}`,
314 + 'GitHub commit'
315 + );
316 + const files = (c.files || []).slice(0, 20).map((file) => ({
317 + filename: file.filename || '',
318 + status: file.status || '',
319 + additions: file.additions ?? 0,
320 + deletions: file.deletions ?? 0,
321 + changes: file.changes ?? 0
322 + }));
323 + return {
324 + sha: commitSha,
325 + shortSha: commitSha.slice(0, 7),
326 + message: String(c.commit?.message || ''),
327 + author: c.author?.login || c.commit?.author?.name || 'Unknown',
328 + date: c.commit?.author?.date || '',
329 + additions: c.stats?.additions ?? 0,
330 + deletions: c.stats?.deletions ?? 0,
331 + changedFiles: files.length,
332 + files
333 + };
334 + }
335 + async listCommitChecks(repoRef, sha, { perPage = 20, page = 1 } = {}) {
336 + const commitSha = fullSha(sha);
337 + const count = clampPerPage(perPage, 20);
338 + const pageNumber = clampPage(page);
339 + const { apiBase } = await this.getRepositoryContext(repoRef);
340 + const data = await this.requestJson(
341 + `${apiBase}/commits/${commitSha}/check-runs?per_page=${count}&page=${pageNumber}`,
342 + 'GitHub check runs'
343 + );
344 + return (data.check_runs || []).map((check) => ({
345 + id: check.id,
346 + name: check.name || 'Check',
347 + status: check.status || '',
348 + conclusion: check.conclusion || null,
349 + url: check.html_url || ''
350 + }));
351 + }
352 + async listFiles(repoRef, path = '', { ref } = {}) {
353 + const { apiBase } = await this.getRepositoryContext(repoRef);
354 + const suffix = path ? `/contents/${encodedPath(path)}` : '/contents';
355 + const query = ref ? `?ref=${encodeURIComponent(String(ref))}` : '';
356 + const data = await this.requestJson(
357 + `${apiBase}${suffix}${query}`,
358 + 'GitHub contents'
359 + );
360 + if (!Array.isArray(data))
361 + throw new Error('GitHub contents response is not a directory listing');
362 + return data.map((item) => ({
363 + name: item.name,
364 + path: item.path,
365 + type: item.type === 'dir' ? 'dir' : 'file',
366 + size: item.size ?? 0,
367 + sha: item.sha || ''
368 + }));
369 + }
370 + async getGitRef(repoRef, branch, { allowMissing = false } = {}) {
371 + const branchName = gitBranch(branch);
372 + const { apiBase } = await this.getRepositoryContext(repoRef);
373 + const data = await this.requestJson(
374 + `${apiBase}/git/ref/heads/${encodedBranch(branchName)}`,
375 + 'GitHub branch ref',
376 + { allowNotFound: allowMissing }
377 + );
378 + if (data === null) return null;
379 + return {
380 + branch: branchName,
381 + sha: fullSha(data?.object?.sha, 'Git branch head')
382 + };
383 + }
384 + async getBranchSnapshot(repoRef, branch) {
385 + const branchName = gitBranch(branch);
386 + const { apiBase } = await this.getRepositoryContext(repoRef);
387 + const ref = await this.requestJson(
388 + `${apiBase}/git/ref/heads/${encodedBranch(branchName)}`,
389 + 'GitHub branch ref'
390 + );
391 + const headSha = fullSha(ref?.object?.sha, 'Git branch head');
392 + const commit = await this.requestJson(
393 + `${apiBase}/git/commits/${headSha}`,
394 + 'GitHub branch commit'
395 + );
396 + const treeSha = fullSha(commit?.tree?.sha, 'Git tree');
397 + return { branch: branchName, headSha, treeSha };
398 + }
399 + async getFileAtRef(repoRef, path, ref) {
400 + const filePath = String(path || '');
401 + if (!filePath || filePath.startsWith('/') || filePath.includes('\0'))
402 + throw new Error('Invalid GitHub file path');
403 + const commitRef = fullSha(ref);
404 + const { apiBase } = await this.getRepositoryContext(repoRef);
405 + const data = await this.requestJson(
406 + `${apiBase}/contents/${encodedPath(filePath)}?ref=${commitRef}`,
407 + 'GitHub file'
408 + );
409 + if (!data || Array.isArray(data) || data.type !== 'file')
410 + throw new Error('GitHub contents response is not a file');
411 + if (data.encoding !== 'base64')
412 + throw new Error('GitHub file encoding is not supported');
413 + const content = decodeBase64Utf8(data.content || '');
414 + return {
415 + path: data.path || filePath,
416 + sha: String(data.sha || ''),
417 + size: Number(data.size) || 0,
418 + encoding: 'utf-8',
419 + content
420 + };
421 + }
422 + async createGitBlob(repoRef, text) {
423 + const { apiBase } = await this.getRepositoryContext(repoRef);
424 + const data = await this.requestJson(
425 + `${apiBase}/git/blobs`,
426 + 'GitHub create blob',
427 + {
428 + method: 'POST',
429 + body: { content: String(text ?? ''), encoding: 'utf-8' }
430 + }
431 + );
432 + return { sha: fullSha(data?.sha, 'Git blob') };
433 + }
434 + async createGitTree(repoRef, { baseTreeSha, entries } = {}) {
435 + const base = fullSha(baseTreeSha, 'Git base tree');
436 + if (!Array.isArray(entries))
437 + throw new Error('Git tree entries are required');
438 + const tree = entries.map((entry) => {
439 + const path = String(entry?.path || '');
440 + if (!path || path.startsWith('/') || path.includes('\0'))
441 + throw new Error('Invalid Git tree path');
442 + if (entry?.mode !== '100644' || entry?.type !== 'blob')
443 + throw new Error('Unsupported Git tree entry');
444 + return {
445 + path,
446 + mode: '100644',
447 + type: 'blob',
448 + sha: fullSha(entry.sha, 'Git blob')
449 + };
450 + });
451 + const { apiBase } = await this.getRepositoryContext(repoRef);
452 + const data = await this.requestJson(
453 + `${apiBase}/git/trees`,
454 + 'GitHub create tree',
455 + { method: 'POST', body: { base_tree: base, tree } }
456 + );
457 + return { sha: fullSha(data?.sha, 'Git tree') };
458 + }
459 + async createGitCommit(
460 + repoRef,
461 + { message, treeSha, parentSha, timestamp } = {}
462 + ) {
463 + const commitMessage = String(message || '');
464 + if (!commitMessage) throw new Error('Git commit message is required');
465 + const tree = fullSha(treeSha, 'Git tree');
466 + const parent = fullSha(parentSha, 'Git parent commit');
467 + const date = new Date(String(timestamp || ''));
468 + if (
469 + Number.isNaN(date.getTime()) ||
470 + date.toISOString() !== String(timestamp)
471 + )
472 + throw new Error('Invalid Git commit timestamp');
473 + const identity = {
474 + name: 'Nexa Dev Bot',
475 + email: 'nexa-dev-bot@users.noreply.github.com',
476 + date: String(timestamp)
477 + };
478 + const { apiBase } = await this.getRepositoryContext(repoRef);
479 + const data = await this.requestJson(
480 + `${apiBase}/git/commits`,
481 + 'GitHub create commit',
482 + {
483 + method: 'POST',
484 + body: {
485 + message: commitMessage,
486 + tree,
487 + parents: [parent],
488 + author: identity,
489 + committer: identity
490 + }
491 + }
492 + );
493 + return { sha: fullSha(data?.sha, 'Git commit') };
494 + }
495 + async createGitBranchRef(repoRef, { branch, sha } = {}) {
496 + const branchName = gitBranch(branch);
497 + const commitSha = fullSha(sha, 'Git commit');
498 + const { apiBase } = await this.getRepositoryContext(repoRef);
499 + const data = await this.requestJson(
500 + `${apiBase}/git/refs`,
501 + 'GitHub create branch ref',
502 + {
503 + method: 'POST',
504 + body: { ref: `refs/heads/${branchName}`, sha: commitSha }
505 + }
506 + );
507 + return {
508 + ref: String(data?.ref || `refs/heads/${branchName}`),
509 + sha: fullSha(data?.object?.sha || commitSha, 'Git commit')
510 + };
511 + }
512 + async listTree(repoRef, sha) {
513 + if (!/^[a-f0-9]{40}$/i.test(String(sha || '')))
514 + throw new Error('Invalid Git tree SHA');
515 + const { apiBase } = await this.getRepositoryContext(repoRef);
516 + const data = await this.requestJson(
517 + `${apiBase}/git/trees/${encodeURIComponent(sha)}`,
518 + 'GitHub tree'
519 + );
520 + return (data.tree || [])
521 + .filter((item) => item.type === 'tree' || item.type === 'blob')
522 + .map((item) => ({
523 + name: item.path,
524 + path: item.path,
525 + type: item.type === 'tree' ? 'dir' : 'file',
526 + size: item.size ?? 0,
527 + sha: item.sha || ''
528 + }));
529 + }
530 + async getBlob(repoRef, sha) {
531 + if (!/^[a-f0-9]{40}$/i.test(String(sha || '')))
532 + throw new Error('Invalid Git blob SHA');
533 + const { apiBase } = await this.getRepositoryContext(repoRef);
534 + const data = await this.requestJson(
535 + `${apiBase}/git/blobs/${encodeURIComponent(sha)}`,
536 + 'GitHub blob'
537 + );
538 + return {
539 + encoding: data.encoding || '',
540 + size: data.size ?? 0,
541 + content: data.content || ''
542 + };
543 + }
544 + async getRepoStatus(repoRef) {
545 + const { raw, apiBase } = await this.getRepositoryContext(repoRef);
546 + const runsData = await this.requestJson(
547 + `${apiBase}/actions/runs?per_page=3`,
548 + 'GitHub Actions runs'
549 + );
550 + const runs = runsData.workflow_runs || [];
551 + return {
552 + repo: String(repoRef),
553 + repoName: raw.name,
554 + defaultBranch: raw.default_branch || 'main',
555 + lastRuns: runs.map((r) => ({
556 + name: r.name,
557 + status: r.status,
558 + conclusion: r.conclusion,
559 + commit: r.head_commit?.message?.slice(0, 80) || '',
560 + url: r.html_url || ''
561 + }))
562 + };
563 + }
564 + async listWorkflowRuns(repoRef, { perPage = 10, page = 1 } = {}) {
565 + const count = clampPerPage(perPage, 10);
566 + const pageNumber = clampPage(page);
567 + const { apiBase } = await this.getRepositoryContext(repoRef);
568 + const pageQuery = pageNumber > 1 ? `&page=${pageNumber}` : '';
569 + const data = await this.requestJson(
570 + `${apiBase}/actions/runs?per_page=${count}${pageQuery}`,
571 + 'GitHub workflow runs'
572 + );
573 + return (data.workflow_runs || []).map((run) => this.mapWorkflowRun(run));
574 + }
575 + async getWorkflowRun(repoRef, runId) {
576 + const id = numericId(runId, 'workflow run');
577 + const { apiBase } = await this.getRepositoryContext(repoRef);
578 + return this.mapWorkflowRun(
579 + await this.requestJson(
580 + `${apiBase}/actions/runs/${id}`,
581 + 'GitHub workflow run'
582 + )
583 + );
584 + }
585 + async listWorkflowJobs(repoRef, runId) {
586 + const id = numericId(runId, 'workflow run');
587 + const { apiBase } = await this.getRepositoryContext(repoRef);
588 + const data = await this.requestJson(
589 + `${apiBase}/actions/runs/${id}/jobs?per_page=20`,
590 + 'GitHub workflow jobs'
591 + );
592 + return (data.jobs || []).map((job) => this.mapWorkflowJob(job));
593 + }
594 + async getWorkflowJob(repoRef, jobId) {
595 + const id = numericId(jobId, 'workflow job');
596 + const { apiBase } = await this.getRepositoryContext(repoRef);
597 + return this.mapWorkflowJob(
598 + await this.requestJson(
599 + `${apiBase}/actions/jobs/${id}`,
600 + 'GitHub workflow job'
601 + )
602 + );
603 + }
604 + async getWorkflowJobLog(repoRef, jobId, { maxChars = 12000 } = {}) {
605 + const id = numericId(jobId, 'workflow job');
606 + const { apiBase } = await this.getRepositoryContext(repoRef);
607 + return this.requestText(
608 + `${apiBase}/actions/jobs/${id}/logs`,
609 + 'GitHub workflow job log',
610 + { maxChars }
611 + );
612 + }
613 + async listWorkflowArtifacts(repoRef, runId, { perPage = 20, page = 1 } = {}) {
614 + const id = numericId(runId, 'workflow run');
615 + const count = clampPerPage(perPage, 20);
616 + const pageNumber = clampPage(page);
617 + const { apiBase } = await this.getRepositoryContext(repoRef);
618 + const data = await this.requestJson(
619 + `${apiBase}/actions/runs/${id}/artifacts?per_page=${count}&page=${pageNumber}`,
620 + 'GitHub workflow artifacts'
621 + );
622 + return (data.artifacts || []).map((artifact) => ({
623 + id: artifact.id,
624 + name: artifact.name || 'Artifact',
625 + size: artifact.size_in_bytes ?? 0,
626 + expired: !!artifact.expired,
627 + createdAt: artifact.created_at || '',
628 + expiresAt: artifact.expires_at || '',
629 + downloadUrl: artifact.archive_download_url || ''
630 + }));
631 + }
632 + async listBranches(repoRef, { perPage = 20, page = 1 } = {}) {
633 + const count = clampPerPage(perPage, 20);
634 + const pageNumber = clampPage(page);
635 + const { apiBase } = await this.getRepositoryContext(repoRef);
636 + const data = await this.requestJson(
637 + `${apiBase}/branches?per_page=${count}&page=${pageNumber}`,
638 + 'GitHub branches'
639 + );
640 + return data.map((branch) => ({
641 + name: branch.name || '',
642 + sha: branch.commit?.sha || '',
643 + protected: !!branch.protected
644 + }));
645 + }
646 + async compareWithDefault(repoRef, headSha) {
647 + const head = fullSha(headSha);
648 + const { raw, apiBase } = await this.getRepositoryContext(repoRef);
649 + const base = raw.default_branch || 'main';
650 + const data = await this.requestJson(
651 + `${apiBase}/compare/${encodeURIComponent(base)}...${head}`,
652 + 'GitHub compare'
653 + );
654 + return {
655 + base,
656 + head,
657 + status: data.status || '',
658 + aheadBy: data.ahead_by ?? 0,
659 + behindBy: data.behind_by ?? 0,
660 + totalCommits: data.total_commits ?? 0,
661 + baseSha: data.base_commit?.sha || '',
662 + mergeBaseSha: data.merge_base_commit?.sha || '',
663 + files: (data.files || [])
664 + .slice(0, 20)
665 + .map((file) => this.mapPullRequestFile(file))
666 + };
667 + }
668 + async listIssues(repoRef, { perPage = 10, page = 1 } = {}) {
669 + const count = clampPerPage(perPage, 10);
670 + const pageNumber = clampPage(page);
671 + const { apiBase } = await this.getRepositoryContext(repoRef);
672 + const data = await this.requestJson(
673 + `${apiBase}/issues?state=all&per_page=${count}&page=${pageNumber}`,
674 + 'GitHub issues'
675 + );
676 + return data
677 + .filter((issue) => !issue.pull_request)
678 + .map((issue) => this.mapIssue(issue));
679 + }
680 + async listIssuesPage(repoRef, { page = 1 } = {}) {
681 + const pageNumber = clampPage(page);
682 + const { apiBase } = await this.getRepositoryContext(repoRef);
683 + const data = await this.requestJson(
684 + `${apiBase}/issues?state=all&per_page=20&page=${pageNumber}`,
685 + 'GitHub issues'
686 + );
687 + return {
688 + items: data
689 + .filter((issue) => !issue.pull_request)
690 + .map((issue) => this.mapIssue(issue)),
691 + hasMore: data.length === 20
692 + };
693 + }
694 + async getIssue(repoRef, issueNumber) {
695 + const number = numericId(issueNumber, 'issue');
696 + const { apiBase } = await this.getRepositoryContext(repoRef);
697 + const issue = await this.requestJson(
698 + apiBase + '/issues/' + number,
699 + 'GitHub issue'
700 + );
701 + return {
702 + ...this.mapIssue(issue),
703 + body: issue.body || '',
704 + labels: (issue.labels || [])
705 + .map((label) => (typeof label === 'string' ? label : label.name))
706 + .filter(Boolean),
707 + assignees: (issue.assignees || [])
708 + .map((user) => user.login)
709 + .filter(Boolean),
710 + createdAt: issue.created_at || '',
711 + updatedAt: issue.updated_at || ''
712 + };
713 + }
714 + async listReleases(repoRef, { perPage = 10, page = 1 } = {}) {
715 + const count = clampPerPage(perPage, 10);
716 + const pageNumber = clampPage(page);
717 + const { apiBase } = await this.getRepositoryContext(repoRef);
718 + const data = await this.requestJson(
719 + `${apiBase}/releases?per_page=${count}&page=${pageNumber}`,
720 + 'GitHub releases'
721 + );
722 + return data.map((release) => ({
723 + id: release.id,
724 + tag: release.tag_name || '',
725 + name: release.name || release.tag_name || 'Release',
726 + draft: !!release.draft,
727 + prerelease: !!release.prerelease,
728 + publishedAt: release.published_at || release.created_at || '',
729 + url: release.html_url || ''
730 + }));
731 + }
732 + async getRelease(repoRef, releaseId) {
733 + const id = numericId(releaseId, 'release');
734 + const { apiBase } = await this.getRepositoryContext(repoRef);
735 + const release = await this.requestJson(
736 + apiBase + '/releases/' + id,
737 + 'GitHub release'
738 + );
739 + return {
740 + id: release.id,
741 + tag: release.tag_name || '',
742 + name: release.name || release.tag_name || 'Release',
743 + body: release.body || '',
744 + draft: !!release.draft,
745 + prerelease: !!release.prerelease,
746 + publishedAt: release.published_at || release.created_at || '',
747 + author: release.author?.login || 'unknown',
748 + target: release.target_commitish || '',
749 + url: release.html_url || ''
750 + };
751 + }
752 + async mergePullRequest(
753 + repoRef,
754 + prNumber,
755 + { expectedHeadSha, mergeMethod = 'squash' } = {}
756 + ) {
757 + const number = numericId(prNumber, 'pull request');
758 + const method = String(mergeMethod || 'squash');
759 + if (!['merge', 'squash', 'rebase'].includes(method))
760 + throw new Error('Unsupported merge method');
761 + const expected = fullSha(expectedHeadSha, 'expected pull request head');
762 + const { apiBase } = await this.getRepositoryContext(repoRef);
763 + const result = await this.requestJson(
764 + `${apiBase}/pulls/${number}/merge`,
765 + 'GitHub pull request merge',
766 + { method: 'PUT', body: { sha: expected, merge_method: method } }
767 + );
768 + if (!result?.merged)
769 + throw new Error(
770 + `GitHub pull request merge failed: ${String(result?.message || 'not merged').slice(0, 240)}`
771 + );
772 + return {
773 + merged: true,
774 + sha: String(result.sha || ''),
775 + message: String(result.message || '')
776 + };
777 + }
778 + async dispatchWorkflow(repoRef, workflowId, { ref, inputs = {} } = {}) {
779 + const id = numericId(workflowId, 'workflow');
780 + const targetRef = String(ref || '');
781 + if (!targetRef || targetRef.includes('\0'))
782 + throw new Error('Workflow dispatch ref is required');
783 + if (!inputs || typeof inputs !== 'object' || Array.isArray(inputs))
784 + throw new Error('Workflow dispatch inputs must be an object');
785 + const { apiBase } = await this.getRepositoryContext(repoRef);
786 + return this.requestJson(
787 + `${apiBase}/actions/workflows/${id}/dispatches`,
788 + 'GitHub workflow dispatch',
789 + { method: 'POST', body: { ref: targetRef, inputs }, allowEmpty: true }
790 + );
791 + }
792 + async rerunJob(repoRef, jobId) {
793 + const id = numericId(jobId, 'workflow job');
794 + const { apiBase } = await this.getRepositoryContext(repoRef);
795 + return this.requestJson(
796 + `${apiBase}/actions/jobs/${id}/rerun`,
797 + 'GitHub rerun workflow job',
798 + { method: 'POST', allowEmpty: true }
799 + );
800 + }
801 + async rerunFailedWorkflowRun(repoRef, runId) {
802 + const id = numericId(runId, 'workflow run');
803 + const { apiBase } = await this.getRepositoryContext(repoRef);
804 + return this.requestJson(
805 + `${apiBase}/actions/runs/${id}/rerun-failed-jobs`,
806 + 'GitHub rerun failed jobs',
807 + { method: 'POST', allowEmpty: true }
808 + );
809 + }
810 + async cancelWorkflowRun(repoRef, runId) {
811 + const id = numericId(runId, 'workflow run');
812 + const { apiBase } = await this.getRepositoryContext(repoRef);
813 + return this.requestJson(
814 + `${apiBase}/actions/runs/${id}/cancel`,
815 + 'GitHub cancel workflow run',
816 + { method: 'POST', allowEmpty: true }
817 + );
818 + }
819 }
src/guide-bot.js
+94 -4
@@ -3,9 +3,99 @@ import { CloudflareMenuManager } from './cloudflare-menu.js';
3 import { RuntimeDiagnostics } from './core/runtime-diagnostics.js';
4 import { platformHomeView, platformCapabilityView } from './platform-menu.js';
5
6 -function guidedPersistentQuickMenuMarkup() { return { keyboard:[[{text:'🏠 منوی اصلی'},{text:'📁 پروژه‌ها'}],[{text:'📊 وضعیت'},{text:'🔧 ابزارها'}],[{text:'🧭 پلتفرم'},{text:'🔐 امنیت'}],[{text:'📘 راهنما'}]],resize_keyboard:true,is_persistent:true,input_field_placeholder:'Nexa Dev — یک گزینه را انتخاب کنید' }; }
6 +function guidedPersistentQuickMenuMarkup() {
7 + return {
8 + keyboard: [
9 + [{ text: '🏠 منوی اصلی' }, { text: '📁 پروژه‌ها' }],
10 + [{ text: '📊 وضعیت' }, { text: '🔧 ابزارها' }],
11 + [{ text: '🧭 پلتفرم' }, { text: '🔐 امنیت' }],
12 + [{ text: '📘 راهنما' }]
13 + ],
14 + resize_keyboard: true,
15 + is_persistent: true,
16 + input_field_placeholder: 'Nexa Dev — یک گزینه را انتخاب کنید'
17 + };
18 +}
19 export class GuidedNexaDevBot extends NexaDevBot {
8 - constructor(env={}){super(env);this.diagnostics=new RuntimeDiagnostics({env,github:this.github,registry:this.registry,replayStore:this.replayStore,workspaceStore:this.workspaceStore,approvals:this.approvals});this.menu=new CloudflareMenuManager(this.github,this.diagnostics);}
9 - async handleMessage(message){const chatId=message?.chat?.id,rawText=typeof message?.text==='string'?message.text:'',text=rawText.trim();if(!chatId)return super.handleMessage(message);if(text==='/start'||text==='/menu'||text.startsWith('/start')){const quickMenuRes=await this.telegram.sendMessage(chatId,'⌨️ <b>منوی سریع Nexa Dev فعال شد</b>\nاین منو پایین صفحه می‌ماند و «📘 راهنما» از هر بخش در دسترس است.',guidedPersistentQuickMenuMarkup());const view=this.menu.getMainMenuView();const res=await this.telegram.sendMessage(chatId,view.text,view.reply_markup);return{ok:true,command:'start',persistentMenu:true,quickMenuRes,res};}if(text==='📘 راهنما'||text==='/help'){const view=this.menu.getGuideIndexView();const res=await this.telegram.sendMessage(chatId,view.text,view.reply_markup);return{ok:true,quickMenu:'help',res};}if(text==='🧭 پلتفرم'||text==='/platform'){const view=platformHomeView();const res=await this.telegram.sendMessage(chatId,view.text,view.reply_markup);return{ok:true,quickMenu:'platform',res};}return super.handleMessage(message);}
10 - async handleCallbackQuery(query){const data=query?.data||'';if(data==='menu:platform'||data.startsWith('platform:')){const view=data==='menu:platform'?platformHomeView():platformCapabilityView(data.slice(9));if(!view)return super.handleCallbackQuery(query);let callbackAnswered=true;try{await this.telegram.answerCallbackQuery(query.id);}catch{callbackAnswered=false;}const res=await this.telegram.editMessageText(query?.message?.chat?.id,query?.message?.message_id,view.text,view.reply_markup);return{ok:true,platform:true,callbackAnswered,edited:true,res};}return super.handleCallbackQuery(query);}
20 + constructor(env = {}) {
21 + super(env);
22 + this.diagnostics = new RuntimeDiagnostics({
23 + env,
24 + github: this.github,
25 + registry: this.registry,
26 + replayStore: this.replayStore,
27 + workspaceStore: this.workspaceStore,
28 + approvals: this.approvals
29 + });
30 + this.menu = new CloudflareMenuManager(this.github, this.diagnostics);
31 + }
32 + async handleMessage(message) {
33 + const chatId = message?.chat?.id,
34 + rawText = typeof message?.text === 'string' ? message.text : '',
35 + text = rawText.trim();
36 + if (!chatId) return super.handleMessage(message);
37 + if (text === '/start' || text === '/menu' || text.startsWith('/start')) {
38 + const quickMenuRes = await this.telegram.sendMessage(
39 + chatId,
40 + '⌨️ <b>منوی سریع Nexa Dev فعال شد</b>\nاین منو پایین صفحه می‌ماند و «📘 راهنما» از هر بخش در دسترس است.',
41 + guidedPersistentQuickMenuMarkup()
42 + );
43 + const view = this.menu.getMainMenuView();
44 + const res = await this.telegram.sendMessage(
45 + chatId,
46 + view.text,
47 + view.reply_markup
48 + );
49 + return {
50 + ok: true,
51 + command: 'start',
52 + persistentMenu: true,
53 + quickMenuRes,
54 + res
55 + };
56 + }
57 + if (text === '📘 راهنما' || text === '/help') {
58 + const view = this.menu.getGuideIndexView();
59 + const res = await this.telegram.sendMessage(
60 + chatId,
61 + view.text,
62 + view.reply_markup
63 + );
64 + return { ok: true, quickMenu: 'help', res };
65 + }
66 + if (text === '🧭 پلتفرم' || text === '/platform') {
67 + const view = platformHomeView();
68 + const res = await this.telegram.sendMessage(
69 + chatId,
70 + view.text,
71 + view.reply_markup
72 + );
73 + return { ok: true, quickMenu: 'platform', res };
74 + }
75 + return super.handleMessage(message);
76 + }
77 + async handleCallbackQuery(query) {
78 + const data = query?.data || '';
79 + if (data === 'menu:platform' || data.startsWith('platform:')) {
80 + const view =
81 + data === 'menu:platform'
82 + ? platformHomeView()
83 + : platformCapabilityView(data.slice(9));
84 + if (!view) return super.handleCallbackQuery(query);
85 + let callbackAnswered = true;
86 + try {
87 + await this.telegram.answerCallbackQuery(query.id);
88 + } catch {
89 + callbackAnswered = false;
90 + }
91 + const res = await this.telegram.editMessageText(
92 + query?.message?.chat?.id,
93 + query?.message?.message_id,
94 + view.text,
95 + view.reply_markup
96 + );
97 + return { ok: true, platform: true, callbackAnswered, edited: true, res };
98 + }
99 + return super.handleCallbackQuery(query);
100 + }
101 }
src/guide-menu.js
+13 -8
@@ -16,8 +16,10 @@ function guideNav(page) {
16 const rows = [];
17 const step = Number(page);
18 const move = [];
19 - if (step > 1) move.push({ text: '⬅️ فصل قبلی', callback_data: `help:${step - 1}` });
20 - if (step < GUIDE_MAX_PAGE) move.push({ text: 'فصل بعدی ➡️', callback_data: `help:${step + 1}` });
19 + if (step > 1)
20 + move.push({ text: '⬅️ فصل قبلی', callback_data: `help:${step - 1}` });
21 + if (step < GUIDE_MAX_PAGE)
22 + move.push({ text: 'فصل بعدی ➡️', callback_data: `help:${step + 1}` });
23 if (move.length) rows.push(move);
24 rows.push([
25 { text: '📘 فهرست راهنما', callback_data: 'menu:help' },
@@ -49,16 +51,18 @@ function guidePage(page) {
51 export class GuideMenuManager extends MenuManager {
52 getMainMenuView() {
53 const view = super.getMainMenuView();
52 - const rows = view.reply_markup.inline_keyboard.map(row => [...row]);
54 + const rows = view.reply_markup.inline_keyboard.map((row) => [...row]);
55 rows.push([{ text: '📘 راهنما', callback_data: 'menu:help' }]);
56 return { ...view, reply_markup: { inline_keyboard: rows } };
57 }
58
59 getGuideIndexView() {
58 - const rows = Object.entries(GUIDE_TITLES).map(([page, title]) => ([{
59 - text: `${page}️⃣ ${title}`,
60 - callback_data: `help:${page}`
61 - }]));
60 + const rows = Object.entries(GUIDE_TITLES).map(([page, title]) => [
61 + {
62 + text: `${page}️⃣ ${title}`,
63 + callback_data: `help:${page}`
64 + }
65 + ]);
66 rows.push([{ text: '🏠 منوی اصلی', callback_data: 'menu:main' }]);
67 return {
68 text: `📘 <b>راهنمای Nexa Dev — V2.1</b>\n➖➖➖➖➖➖➖➖➖➖\nاین راهنما دکمه‌های فعلی Bot، ابزارهای عملیاتی، مسیر کامل اصلاح فایل و مرز Production را توضیح می‌دهد. یک فصل را انتخاب کنید:`,
@@ -72,7 +76,8 @@ export class GuideMenuManager extends MenuManager {
76
77 async renderByCallback(callbackData) {
78 const value = String(callbackData || '');
75 - if (value === 'menu:help' || value === 'help:index') return this.getGuideIndexView();
79 + if (value === 'menu:help' || value === 'help:index')
80 + return this.getGuideIndexView();
81 const match = value.match(/^help:([1-7])$/);
82 if (match) return this.getGuidePageView(Number(match[1]));
83 return super.renderByCallback(callbackData);
src/index.js
+92 -2
@@ -1,9 +1,99 @@
1 import { KillSwitchGuidedNexaDevBot } from './kill-switch-bot.js';
2 import { DurableWorkspaceStoreClient } from './core/workspace-store.js';
3 -import { handleWorkspaceEditorRequest, workspaceEditorPageResponse } from './workspace-editor.js';
3 +import {
4 + handleWorkspaceEditorRequest,
5 + workspaceEditorPageResponse
6 +} from './workspace-editor.js';
7 export { ApprovalReplayGuard } from './durable/approval-replay-guard.js';
8 export { WorkspaceStore } from './durable/workspace-store.js';
9 export { IncidentStore } from './durable/incident-store.js';
10 export { AutomationStore } from './durable/automation-store.js';
11 export { KillSwitchStore } from './durable/kill-switch-store.js';
9 -const jsonResponse=(p,s=200)=>new Response(JSON.stringify(p),{status:s,headers:{'Content-Type':'application/json; charset=utf-8'}});const publicHealthPayload=()=>({status:'online',bot:'Nexa Dev Bot',version:'1.1.1',mode:'Cloudflare Worker Webhook'});const senderIdFromUpdate=u=>u?.message?.from?.id??u?.callback_query?.from?.id??null;const isOwnerUpdate=(u,e)=>!!e.OWNER_TELEGRAM_ID&&senderIdFromUpdate(u)!==null&&String(senderIdFromUpdate(u))===String(e.OWNER_TELEGRAM_ID);function safeErrorMessage(error,env={}){let m=String(error?.message||'Unknown error');for(const s of[env.TELEGRAM_BOT_TOKEN,env.TELEGRAM_WEBHOOK_SECRET,env.GITHUB_TOKEN,env.CLOUDFLARE_API_TOKEN,env.APPROVAL_SIGNING_SECRET,env.DESTRUCTIVE_TOTP_SECRET]){const v=String(s||'');if(v)m=m.split(v).join('[REDACTED]');}return m;}export default{async fetch(request,env={}){const url=new URL(request.url);if(request.method==='GET'&&url.pathname==='/workspace/editor')return workspaceEditorPageResponse();if(url.pathname==='/workspace/api/editor'&&(request.method==='GET'||request.method==='PUT'))return handleWorkspaceEditorRequest(request,{workspaces:new DurableWorkspaceStoreClient({namespace:env.WORKSPACE_STORE}),botToken:env.TELEGRAM_BOT_TOKEN||'',ownerId:env.OWNER_TELEGRAM_ID||''});if(request.method==='GET'){if(['/health','/','/status'].includes(url.pathname))return jsonResponse(publicHealthPayload());return new Response('Not Found',{status:404});}if(request.method==='POST'&&url.pathname==='/telegram/webhook'){if(!env.TELEGRAM_WEBHOOK_SECRET)return new Response('Webhook secret not configured',{status:503});if(request.headers.get('X-Telegram-Bot-Api-Secret-Token')!==env.TELEGRAM_WEBHOOK_SECRET)return new Response('Forbidden',{status:403});if(!env.OWNER_TELEGRAM_ID)return new Response('Owner not configured',{status:503});if(!env.TELEGRAM_BOT_TOKEN)return new Response('Telegram bot token not configured',{status:503});try{const u=await request.json();if(!isOwnerUpdate(u,env))return jsonResponse({ok:true,ignored:true});return jsonResponse(await new KillSwitchGuidedNexaDevBot(env).handleUpdate(u));}catch(e){console.error('telegram_webhook_error',safeErrorMessage(e,env));return jsonResponse({ok:false,error:'Telegram webhook processing failed'},400);}}return new Response(request.method==='POST'?'Not Found':'Method Not Allowed',{status:request.method==='POST'?404:405});}};
12 +const jsonResponse = (p, s = 200) =>
13 + new Response(JSON.stringify(p), {
14 + status: s,
15 + headers: { 'Content-Type': 'application/json; charset=utf-8' }
16 + });
17 +const publicHealthPayload = () => ({
18 + status: 'online',
19 + bot: 'Nexa Dev Bot',
20 + version: '1.1.1',
21 + mode: 'Cloudflare Worker Webhook'
22 +});
23 +const senderIdFromUpdate = (u) =>
24 + u?.message?.from?.id ?? u?.callback_query?.from?.id ?? null;
25 +const isOwnerUpdate = (u, e) =>
26 + !!e.OWNER_TELEGRAM_ID &&
27 + senderIdFromUpdate(u) !== null &&
28 + String(senderIdFromUpdate(u)) === String(e.OWNER_TELEGRAM_ID);
29 +function safeErrorMessage(error, env = {}) {
30 + let m = String(error?.message || 'Unknown error');
31 + for (const s of [
32 + env.TELEGRAM_BOT_TOKEN,
33 + env.TELEGRAM_WEBHOOK_SECRET,
34 + env.GITHUB_TOKEN,
35 + env.CLOUDFLARE_API_TOKEN,
36 + env.APPROVAL_SIGNING_SECRET,
37 + env.DESTRUCTIVE_TOTP_SECRET
38 + ]) {
39 + const v = String(s || '');
40 + if (v) m = m.split(v).join('[REDACTED]');
41 + }
42 + return m;
43 +}
44 +export default {
45 + async fetch(request, env = {}) {
46 + const url = new URL(request.url);
47 + if (request.method === 'GET' && url.pathname === '/workspace/editor')
48 + return workspaceEditorPageResponse();
49 + if (
50 + url.pathname === '/workspace/api/editor' &&
51 + (request.method === 'GET' || request.method === 'PUT')
52 + )
53 + return handleWorkspaceEditorRequest(request, {
54 + workspaces: new DurableWorkspaceStoreClient({
55 + namespace: env.WORKSPACE_STORE
56 + }),
57 + botToken: env.TELEGRAM_BOT_TOKEN || '',
58 + ownerId: env.OWNER_TELEGRAM_ID || ''
59 + });
60 + if (request.method === 'GET') {
61 + if (['/health', '/', '/status'].includes(url.pathname))
62 + return jsonResponse(publicHealthPayload());
63 + return new Response('Not Found', { status: 404 });
64 + }
65 + if (request.method === 'POST' && url.pathname === '/telegram/webhook') {
66 + if (!env.TELEGRAM_WEBHOOK_SECRET)
67 + return new Response('Webhook secret not configured', { status: 503 });
68 + if (
69 + request.headers.get('X-Telegram-Bot-Api-Secret-Token') !==
70 + env.TELEGRAM_WEBHOOK_SECRET
71 + )
72 + return new Response('Forbidden', { status: 403 });
73 + if (!env.OWNER_TELEGRAM_ID)
74 + return new Response('Owner not configured', { status: 503 });
75 + if (!env.TELEGRAM_BOT_TOKEN)
76 + return new Response('Telegram bot token not configured', {
77 + status: 503
78 + });
79 + try {
80 + const u = await request.json();
81 + if (!isOwnerUpdate(u, env))
82 + return jsonResponse({ ok: true, ignored: true });
83 + return jsonResponse(
84 + await new KillSwitchGuidedNexaDevBot(env).handleUpdate(u)
85 + );
86 + } catch (e) {
87 + console.error('telegram_webhook_error', safeErrorMessage(e, env));
88 + return jsonResponse(
89 + { ok: false, error: 'Telegram webhook processing failed' },
90 + 400
91 + );
92 + }
93 + }
94 + return new Response(
95 + request.method === 'POST' ? 'Not Found' : 'Method Not Allowed',
96 + { status: request.method === 'POST' ? 404 : 405 }
97 + );
98 + }
99 +};
src/kill-switch-bot.js
+63 -19
@@ -2,16 +2,22 @@ import { GuidedNexaDevBot } from './guide-bot.js';
2 import { DurableKillSwitchStoreClient } from './core/kill-switch-store.js';
3 import { KillSwitch } from './core/kill-switch.js';
4
5 -const lockMarkup = mode => ({ inline_keyboard: [[
6 - mode === 'LOCKED'
7 - ? { text: '🔓 بازکردن اضطراری', callback_data: 'killswitch:unlock' }
8 - : { text: '🔒 قفل اضطراری', callback_data: 'killswitch:lock' }
9 -]] });
5 +const lockMarkup = (mode) => ({
6 + inline_keyboard: [
7 + [
8 + mode === 'LOCKED'
9 + ? { text: '🔓 بازکردن اضطراری', callback_data: 'killswitch:unlock' }
10 + : { text: '🔒 قفل اضطراری', callback_data: 'killswitch:lock' }
11 + ]
12 + ]
13 +});
14
15 export class KillSwitchGuidedNexaDevBot extends GuidedNexaDevBot {
16 constructor(env = {}) {
17 super(env);
14 - const store = new DurableKillSwitchStoreClient({ namespace: env.KILL_SWITCH_STORE });
18 + const store = new DurableKillSwitchStoreClient({
19 + namespace: env.KILL_SWITCH_STORE
20 + });
21 this.killSwitch = new KillSwitch({ store });
22 if (store.isConfigured()) this.router.killSwitch = this.killSwitch;
23 }
@@ -21,9 +27,13 @@ export class KillSwitchGuidedNexaDevBot extends GuidedNexaDevBot {
27 if (text === '/killswitch' || text === '/lockdown') {
28 const state = await this.killSwitch.status();
29 const locked = state.mode === 'LOCKED';
24 - const res = await this.telegram.sendMessage(message.chat.id,
25 - locked ? '🔒 <b>قفل اضطراری فعال است</b>\nWRITE، DESTRUCTIVE و ادامه Automation متوقف هستند؛ READ مجاز است.' : '🔓 <b>وضعیت عادی</b>\nقفل اضطراری غیرفعال است.',
26 - lockMarkup(state.mode));
30 + const res = await this.telegram.sendMessage(
31 + message.chat.id,
32 + locked
33 + ? '🔒 <b>قفل اضطراری فعال است</b>\nWRITE، DESTRUCTIVE و ادامه Automation متوقف هستند؛ READ مجاز است.'
34 + : '🔓 <b>وضعیت عادی</b>\nقفل اضطراری غیرفعال است.',
35 + lockMarkup(state.mode)
36 + );
37 return { ok: true, killSwitch: true, mode: state.mode, res };
38 }
39 return super.handleMessage(message);
@@ -31,25 +41,59 @@ export class KillSwitchGuidedNexaDevBot extends GuidedNexaDevBot {
41
42 async handleCallbackQuery(query) {
43 const data = query?.data || '';
34 - if (data !== 'killswitch:lock' && data !== 'killswitch:unlock' && data !== 'killswitch:confirm-lock' && data !== 'killswitch:confirm-unlock') return super.handleCallbackQuery(query);
44 + if (
45 + data !== 'killswitch:lock' &&
46 + data !== 'killswitch:unlock' &&
47 + data !== 'killswitch:confirm-lock' &&
48 + data !== 'killswitch:confirm-unlock'
49 + )
50 + return super.handleCallbackQuery(query);
51 const chatId = query?.message?.chat?.id;
52 const messageId = query?.message?.message_id;
37 - try { await this.telegram.answerCallbackQuery(query.id); } catch {}
53 + try {
54 + await this.telegram.answerCallbackQuery(query.id);
55 + } catch {}
56 if (data === 'killswitch:lock' || data === 'killswitch:unlock') {
57 const target = data.endsWith('lock') ? 'lock' : 'unlock';
40 - const label = target === 'lock' ? 'فعال‌کردن قفل اضطراری' : 'بازکردن قفل اضطراری';
41 - const res = await this.telegram.editMessageText(chatId, messageId,
58 + const label =
59 + target === 'lock' ? 'فعال‌کردن قفل اضطراری' : 'بازکردن قفل اضطراری';
60 + const res = await this.telegram.editMessageText(
61 + chatId,
62 + messageId,
63 `⚠️ <b>${label}</b>\nاین تغییر فقط با تأیید صریح مالک اجرا می‌شود.`,
43 - { inline_keyboard: [[{ text: '✅ تأیید', callback_data: `killswitch:confirm-${target}` }],[{ text: '↩️ انصراف', callback_data: 'menu:main' }]] });
64 + {
65 + inline_keyboard: [
66 + [
67 + {
68 + text: '✅ تأیید',
69 + callback_data: `killswitch:confirm-${target}`
70 + }
71 + ],
72 + [{ text: '↩️ انصراف', callback_data: 'menu:main' }]
73 + ]
74 + }
75 + );
76 return { ok: true, killSwitchApprovalRequired: true, res };
77 }
78 const target = data.endsWith('lock') ? 'lock' : 'unlock';
79 const context = { isOwner: true, approved: true };
48 - const state = target === 'lock' ? await this.killSwitch.lock(context) : await this.killSwitch.unlock(context);
49 - this.audit.log({ event: 'kill_switch_control', outcome: 'success', mode: state.mode });
50 - const res = await this.telegram.editMessageText(chatId, messageId,
51 - state.mode === 'LOCKED' ? '🔒 <b>قفل اضطراری فعال شد</b>\nWRITE، DESTRUCTIVE و Automation متوقف شدند.' : '🔓 <b>قفل اضطراری باز شد</b>\nاجرای عملیات طبق Policy عادی ادامه دارد.',
52 - lockMarkup(state.mode));
80 + const state =
81 + target === 'lock'
82 + ? await this.killSwitch.lock(context)
83 + : await this.killSwitch.unlock(context);
84 + this.audit.log({
85 + event: 'kill_switch_control',
86 + outcome: 'success',
87 + mode: state.mode
88 + });
89 + const res = await this.telegram.editMessageText(
90 + chatId,
91 + messageId,
92 + state.mode === 'LOCKED'
93 + ? '🔒 <b>قفل اضطراری فعال شد</b>\nWRITE، DESTRUCTIVE و Automation متوقف شدند.'
94 + : '🔓 <b>قفل اضطراری باز شد</b>\nاجرای عملیات طبق Policy عادی ادامه دارد.',
95 + lockMarkup(state.mode)
96 + );
97 return { ok: true, killSwitch: true, mode: state.mode, res };
98 }
99 }
src/menu.js
+134 -88
@@ -10,7 +10,7 @@ function escapeHtml(value = '') {
10
11 function decodeBase64Utf8(value = '') {
12 const binary = atob(String(value).replace(/\s/g, ''));
13 - const bytes = Uint8Array.from(binary, char => char.charCodeAt(0));
13 + const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
14 return new TextDecoder().decode(bytes);
15 }
16
@@ -24,10 +24,12 @@ function fileItemRows(repoId, items) {
24 const action = item.type === 'dir' ? 'tree' : 'blob';
25 const callbackData = `${action}:${repoId}:${item.sha}`;
26 if (!item.sha || !callbackFits(callbackData)) continue;
27 - rows.push([{
28 - text: `${item.type === 'dir' ? '📁' : '📄'} ${item.name}`,
29 - callback_data: callbackData
30 - }]);
27 + rows.push([
28 + {
29 + text: `${item.type === 'dir' ? '📁' : '📄'} ${item.name}`,
30 + callback_data: callbackData
31 + }
32 + ]);
33 }
34 return rows;
35 }
@@ -42,8 +44,7 @@ export class MenuManager {
44 }
45
46 getMainMenuView() {
45 - const text =
46 -`⚡ <b>Nexa Dev Bot | پنل مدیریت توسعه</b>
47 + const text = `⚡ <b>Nexa Dev Bot | پنل مدیریت توسعه</b>
48 ➖➖➖➖➖➖➖➖➖➖
49 یکی از بخش‌های زیر را انتخاب کنید.
50 اتصال GitHub هنگام باز کردن مخزن‌ها به‌صورت زنده بررسی می‌شود.`;
@@ -60,9 +61,7 @@ export class MenuManager {
61 { text: '🔧 ابزارهای توسعه', callback_data: 'menu:tools' },
62 { text: '⚙️ تنظیمات', callback_data: 'menu:settings' }
63 ],
63 - [
64 - { text: '🔐 امنیت', callback_data: 'menu:security' }
65 - ]
64 + [{ text: '🔐 امنیت', callback_data: 'menu:security' }]
65 ]
66 }
67 };
@@ -70,8 +69,7 @@ export class MenuManager {
69
70 async getReposListView() {
71 const repos = await this.github.listRepositories();
73 - const text =
74 -`📁 <b>فهرست مخزن‌ها و پروژه‌ها</b>
72 + const text = `📁 <b>فهرست مخزن‌ها و پروژه‌ها</b>
73 <code>🏠 Nexa Dev &gt; 📁 مخزن‌ها</code>
74 ➖➖➖➖➖➖➖➖➖➖
75 این فهرست از GitHub API دریافت شده است. پروژه مورد نظر را انتخاب کنید:`;
@@ -93,9 +91,13 @@ export class MenuManager {
91 }
92
93 if (!repos.length) {
96 - inlineKeyboard.push([{ text: '🔄 بررسی مجدد', callback_data: 'menu:repos' }]);
94 + inlineKeyboard.push([
95 + { text: '🔄 بررسی مجدد', callback_data: 'menu:repos' }
96 + ]);
97 }
98 - inlineKeyboard.push([{ text: '🔙 بازگشت به منوی اصلی', callback_data: 'menu:main' }]);
98 + inlineKeyboard.push([
99 + { text: '🔙 بازگشت به منوی اصلی', callback_data: 'menu:main' }
100 + ]);
101
102 return { text, reply_markup: { inline_keyboard: inlineKeyboard } };
103 }
@@ -104,9 +106,10 @@ export class MenuManager {
106 const repo = await this.github.getRepository(repoId);
107 const visibility = repo.private ? '🔒 خصوصی' : '🌐 عمومی';
108 const archived = repo.archived ? '\n⚠️ وضعیت: آرشیوشده' : '';
107 - const description = repo.description ? `\n📝 ${escapeHtml(repo.description)}` : '';
108 - const text =
109 -`📦 <b>پروژه: ${escapeHtml(repo.name)}</b>
109 + const description = repo.description
110 + ? `\n📝 ${escapeHtml(repo.description)}`
111 + : '';
112 + const text = `📦 <b>پروژه: ${escapeHtml(repo.name)}</b>
113 <code>🏠 Nexa Dev &gt; 📁 مخزن‌ها &gt; ${escapeHtml(repo.name)}</code>
114 ➖➖➖➖➖➖➖➖➖➖
115 👤 مخزن: <code>${escapeHtml(repo.fullName)}</code>
@@ -139,14 +142,19 @@ export class MenuManager {
142 this.github.listPullRequests(repoId)
143 ]);
144 const prListText = prs.length
142 - ? prs.map(pr => {
143 - const state = pr.merged ? '🟣 Merged' : (pr.state === 'open' ? '🟢 Open' : '🔴 Closed');
144 - return `• <b>#${pr.number}</b> ${escapeHtml(pr.title)}\n └ <i>${escapeHtml(pr.author)} | ${state}</i>`;
145 - }).join('\n\n')
145 + ? prs
146 + .map((pr) => {
147 + const state = pr.merged
148 + ? '🟣 Merged'
149 + : pr.state === 'open'
150 + ? '🟢 Open'
151 + : '🔴 Closed';
152 + return `• <b>#${pr.number}</b> ${escapeHtml(pr.title)}\n └ <i>${escapeHtml(pr.author)} | ${state}</i>`;
153 + })
154 + .join('\n\n')
155 : '<i>Pull Requestی در پاسخ GitHub یافت نشد.</i>';
156
148 - const text =
149 -`🔀 <b>Pull Requestهای پروژه ${escapeHtml(repo.name)}</b>
157 + const text = `🔀 <b>Pull Requestهای پروژه ${escapeHtml(repo.name)}</b>
158 <code>🏠 Nexa Dev &gt; 📁 مخزن‌ها &gt; ${escapeHtml(repo.name)} &gt; 🔀 Pull Request</code>
159 ➖➖➖➖➖➖➖➖➖➖
160 ${prListText}`;
@@ -154,10 +162,12 @@ ${prListText}`;
162 return {
163 text,
164 reply_markup: {
157 - inline_keyboard: [[
158 - { text: '🔄 بروزرسانی', callback_data: `pr:${repoId}` },
159 - { text: '🔙 بازگشت به پروژه', callback_data: `repo:${repoId}` }
160 - ]]
165 + inline_keyboard: [
166 + [
167 + { text: '🔄 بروزرسانی', callback_data: `pr:${repoId}` },
168 + { text: '🔙 بازگشت به پروژه', callback_data: `repo:${repoId}` }
169 + ]
170 + ]
171 }
172 };
173 }
@@ -168,11 +178,15 @@ ${prListText}`;
178 this.github.listCommits(repoId)
179 ]);
180 const commitListText = commits.length
171 - ? commits.map(c => `• <code>${escapeHtml(c.sha)}</code> - ${escapeHtml(c.message)}\n └ <i>${escapeHtml(c.author)}${c.date ? ` | ${escapeHtml(c.date)}` : ''}</i>`).join('\n\n')
181 + ? commits
182 + .map(
183 + (c) =>
184 + `• <code>${escapeHtml(c.sha)}</code> - ${escapeHtml(c.message)}\n └ <i>${escapeHtml(c.author)}${c.date ? ` | ${escapeHtml(c.date)}` : ''}</i>`
185 + )
186 + .join('\n\n')
187 : '<i>کامیتی در پاسخ GitHub یافت نشد.</i>';
188
174 - const text =
175 -`📝 <b>آخرین Commitهای پروژه ${escapeHtml(repo.name)}</b>
189 + const text = `📝 <b>آخرین Commitهای پروژه ${escapeHtml(repo.name)}</b>
190 <code>🏠 Nexa Dev &gt; 📁 مخزن‌ها &gt; ${escapeHtml(repo.name)} &gt; 📝 Commitها</code>
191 ➖➖➖➖➖➖➖➖➖➖
192 ${commitListText}`;
@@ -180,10 +194,12 @@ ${commitListText}`;
194 return {
195 text,
196 reply_markup: {
183 - inline_keyboard: [[
184 - { text: '🔄 بروزرسانی', callback_data: `commits:${repoId}` },
185 - { text: '🔙 بازگشت به پروژه', callback_data: `repo:${repoId}` }
186 - ]]
197 + inline_keyboard: [
198 + [
199 + { text: '🔄 بروزرسانی', callback_data: `commits:${repoId}` },
200 + { text: '🔙 بازگشت به پروژه', callback_data: `repo:${repoId}` }
201 + ]
202 + ]
203 }
204 };
205 }
@@ -195,25 +211,30 @@ ${commitListText}`;
211 ]);
212 const visibleItems = files.slice(0, 30);
213 const itemsText = visibleItems.length
198 - ? visibleItems.map(f => {
199 - const icon = f.type === 'dir' ? '📁' : '📄';
200 - const size = f.type === 'file' && f.size ? ` (${f.size} B)` : '';
201 - return `${icon} <code>${escapeHtml(f.name)}</code>${size}`;
202 - }).join('\n')
214 + ? visibleItems
215 + .map((f) => {
216 + const icon = f.type === 'dir' ? '📁' : '📄';
217 + const size = f.type === 'file' && f.size ? ` (${f.size} B)` : '';
218 + return `${icon} <code>${escapeHtml(f.name)}</code>${size}`;
219 + })
220 + .join('\n')
221 : '<i>پوشه خالی است.</i>';
204 - const omitted = files.length > visibleItems.length
205 - ? `\n\n<i>${files.length - visibleItems.length} مورد دیگر در این نما نمایش داده نشده است.</i>`
206 - : '';
222 + const omitted =
223 + files.length > visibleItems.length
224 + ? `\n\n<i>${files.length - visibleItems.length} مورد دیگر در این نما نمایش داده نشده است.</i>`
225 + : '';
226
208 - const text =
209 -`📂 <b>ساختار فایل‌های پروژه ${escapeHtml(repo.name)}</b>
227 + const text = `📂 <b>ساختار فایل‌های پروژه ${escapeHtml(repo.name)}</b>
228 <code>🏠 Nexa Dev &gt; 📁 مخزن‌ها &gt; ${escapeHtml(repo.name)} &gt; 📂 فایل‌ها${subpath ? ` &gt; ${escapeHtml(subpath)}` : ''}</code>
229 ➖➖➖➖➖➖➖➖➖➖
230 ${itemsText}${omitted}`;
231
232 const inlineKeyboard = fileItemRows(repoId, visibleItems);
233 inlineKeyboard.push([
216 - { text: '🔄 بروزرسانی', callback_data: `files:${repoId}${subpath ? `:${subpath}` : ''}` },
234 + {
235 + text: '🔄 بروزرسانی',
236 + callback_data: `files:${repoId}${subpath ? `:${subpath}` : ''}`
237 + },
238 { text: '🔙 بازگشت به پروژه', callback_data: `repo:${repoId}` }
239 ]);
240
@@ -227,18 +248,21 @@ ${itemsText}${omitted}`;
248 ]);
249 const visibleItems = items.slice(0, 30);
250 const itemsText = visibleItems.length
230 - ? visibleItems.map(item => {
231 - const icon = item.type === 'dir' ? '📁' : '📄';
232 - const size = item.type === 'file' && item.size ? ` (${item.size} B)` : '';
233 - return `${icon} <code>${escapeHtml(item.name)}</code>${size}`;
234 - }).join('\n')
251 + ? visibleItems
252 + .map((item) => {
253 + const icon = item.type === 'dir' ? '📁' : '📄';
254 + const size =
255 + item.type === 'file' && item.size ? ` (${item.size} B)` : '';
256 + return `${icon} <code>${escapeHtml(item.name)}</code>${size}`;
257 + })
258 + .join('\n')
259 : '<i>این پوشه خالی است.</i>';
236 - const omitted = items.length > visibleItems.length
237 - ? `\n\n<i>${items.length - visibleItems.length} مورد دیگر در این نما نمایش داده نشده است.</i>`
238 - : '';
260 + const omitted =
261 + items.length > visibleItems.length
262 + ? `\n\n<i>${items.length - visibleItems.length} مورد دیگر در این نما نمایش داده نشده است.</i>`
263 + : '';
264
240 - const text =
241 -`📁 <b>پوشه در ${escapeHtml(repo.name)}</b>
265 + const text = `📁 <b>پوشه در ${escapeHtml(repo.name)}</b>
266 <code>🏠 Nexa Dev &gt; 📁 مخزن‌ها &gt; ${escapeHtml(repo.name)} &gt; 📂 فایل‌ها &gt; پوشه</code>
267 ➖➖➖➖➖➖➖➖➖➖
268 ${itemsText}${omitted}`;
@@ -263,12 +287,12 @@ ${itemsText}${omitted}`;
287 body = '<i>این فایل برای نمایش مستقیم در تلگرام مناسب نیست.</i>';
288 } else {
289 const decoded = decodeBase64Utf8(blob.content);
266 - const preview = decoded.length > 2800 ? `${decoded.slice(0, 2800)}\n…` : decoded;
290 + const preview =
291 + decoded.length > 2800 ? `${decoded.slice(0, 2800)}\n…` : decoded;
292 body = `<pre>${escapeHtml(preview)}</pre>`;
293 }
294
270 - const text =
271 -`📄 <b>پیش‌نمایش فایل در ${escapeHtml(repo.name)}</b>
295 + const text = `📄 <b>پیش‌نمایش فایل در ${escapeHtml(repo.name)}</b>
296 <code>🏠 Nexa Dev &gt; 📁 مخزن‌ها &gt; ${escapeHtml(repo.name)} &gt; 📂 فایل‌ها &gt; فایل</code>
297 ➖➖➖➖➖➖➖➖➖➖
298 ${body}`;
@@ -276,10 +300,12 @@ ${body}`;
300 return {
301 text,
302 reply_markup: {
279 - inline_keyboard: [[
280 - { text: '🔙 ریشه فایل‌ها', callback_data: `files:${repoId}` },
281 - { text: '📦 پروژه', callback_data: `repo:${repoId}` }
282 - ]]
303 + inline_keyboard: [
304 + [
305 + { text: '🔙 ریشه فایل‌ها', callback_data: `files:${repoId}` },
306 + { text: '📦 پروژه', callback_data: `repo:${repoId}` }
307 + ]
308 + ]
309 }
310 };
311 }
@@ -287,15 +313,21 @@ ${body}`;
313 async getRepoStatusView(repoId) {
314 const status = await this.github.getRepoStatus(repoId);
315 const runsText = status.lastRuns.length
290 - ? status.lastRuns.map(r => {
291 - const icon = r.conclusion === 'success' ? '✅' : (r.conclusion === 'failure' ? '❌' : '⏳');
292 - return `• ${icon} <b>${escapeHtml(r.name)}</b>: ${escapeHtml(r.conclusion || r.status || 'unknown')}\n └ <i>${escapeHtml(r.commit || '')}</i>`;
293 - }).join('\n')
316 + ? status.lastRuns
317 + .map((r) => {
318 + const icon =
319 + r.conclusion === 'success'
320 + ? '✅'
321 + : r.conclusion === 'failure'
322 + ? '❌'
323 + : '⏳';
324 + return `• ${icon} <b>${escapeHtml(r.name)}</b>: ${escapeHtml(r.conclusion || r.status || 'unknown')}\n └ <i>${escapeHtml(r.commit || '')}</i>`;
325 + })
326 + .join('\n')
327 : '<i>Workflow runی در پاسخ GitHub یافت نشد.</i>';
328
329 const label = status.repoName || repoId;
297 - const text =
298 -`📊 <b>وضعیت پایپ‌لاین ${escapeHtml(label)}</b>
330 + const text = `📊 <b>وضعیت پایپ‌لاین ${escapeHtml(label)}</b>
331 <code>🏠 Nexa Dev &gt; 📁 مخزن‌ها &gt; ${escapeHtml(label)} &gt; 📊 وضعیت</code>
332 ➖➖➖➖➖➖➖➖➖➖
333 شاخه پیش‌فرض: <code>${escapeHtml(status.defaultBranch)}</code>
@@ -306,17 +338,18 @@ ${runsText}`;
338 return {
339 text,
340 reply_markup: {
309 - inline_keyboard: [[
310 - { text: '🔄 بروزرسانی', callback_data: `status:${repoId}` },
311 - { text: '🔙 بازگشت به پروژه', callback_data: `repo:${repoId}` }
312 - ]]
341 + inline_keyboard: [
342 + [
343 + { text: '🔄 بروزرسانی', callback_data: `status:${repoId}` },
344 + { text: '🔙 بازگشت به پروژه', callback_data: `repo:${repoId}` }
345 + ]
346 + ]
347 }
348 };
349 }
350
351 getServiceStatusView() {
318 - const text =
319 -`📊 <b>وضعیت سیستم و سرویس‌ها</b>
352 + const text = `📊 <b>وضعیت سیستم و سرویس‌ها</b>
353 <code>🏠 Nexa Dev &gt; 📊 وضعیت سرویس</code>
354 ➖➖➖➖➖➖➖➖➖➖
355 • <b>Cloudflare Worker:</b> این درخواست توسط Worker پاسخ داده شد.
@@ -329,18 +362,21 @@ ${runsText}`;
362 return {
363 text,
364 reply_markup: {
332 - inline_keyboard: [[
333 - { text: '🔄 بررسی مجدد', callback_data: 'menu:status' },
334 - { text: '🔙 بازگشت به منوی اصلی', callback_data: 'menu:main' }
335 - ]]
365 + inline_keyboard: [
366 + [
367 + { text: '🔄 بررسی مجدد', callback_data: 'menu:status' },
368 + { text: '🔙 بازگشت به منوی اصلی', callback_data: 'menu:main' }
369 + ]
370 + ]
371 }
372 };
373 }
374
375 getToolsView() {
341 - const tools = DEFAULT_CONFIG.devTools.map(t => `• <b>${t.title}</b>\n └ <i>${t.desc}</i>`).join('\n\n');
342 - const text =
343 -`🔧 <b>ابزارهای توسعه</b>
376 + const tools = DEFAULT_CONFIG.devTools
377 + .map((t) => `• <b>${t.title}</b>\n └ <i>${t.desc}</i>`)
378 + .join('\n\n');
379 + const text = `🔧 <b>ابزارهای توسعه</b>
380 <code>🏠 Nexa Dev &gt; 🔧 ابزارهای توسعه</code>
381 ➖➖➖➖➖➖➖➖➖➖
382 ${tools}`;
@@ -357,8 +393,7 @@ ${tools}`;
393 }
394
395 getSettingsView() {
360 - const text =
361 -`⚙️ <b>تنظیمات Nexa Dev</b>
396 + const text = `⚙️ <b>تنظیمات Nexa Dev</b>
397 <code>🏠 Nexa Dev &gt; ⚙️ تنظیمات</code>
398 ➖➖➖➖➖➖➖➖➖➖
399 • مالک GitHub پیش‌فرض: <code>${escapeHtml(DEFAULT_CONFIG.defaultOwner)}</code>
@@ -370,13 +405,16 @@ ${tools}`;
405
406 return {
407 text,
373 - reply_markup: { inline_keyboard: [[{ text: '🔙 بازگشت به منوی اصلی', callback_data: 'menu:main' }]] }
408 + reply_markup: {
409 + inline_keyboard: [
410 + [{ text: '🔙 بازگشت به منوی اصلی', callback_data: 'menu:main' }]
411 + ]
412 + }
413 };
414 }
415
416 getSecurityView() {
378 - const text =
379 -`🔐 <b>امنیت و دسترسی‌ها</b>
417 + const text = `🔐 <b>امنیت و دسترسی‌ها</b>
418 <code>🏠 Nexa Dev &gt; 🔐 امنیت</code>
419 ➖➖➖➖➖➖➖➖➖➖
420 • Webhook secret: <b>اجباری در Worker</b>
@@ -388,7 +426,11 @@ ${tools}`;
426
427 return {
428 text,
391 - reply_markup: { inline_keyboard: [[{ text: '🔙 بازگشت به منوی اصلی', callback_data: 'menu:main' }]] }
429 + reply_markup: {
430 + inline_keyboard: [
431 + [{ text: '🔙 بازگشت به منوی اصلی', callback_data: 'menu:main' }]
432 + ]
433 + }
434 };
435 }
436
@@ -421,7 +463,11 @@ ${tools}`;
463 if (target === 'ping') {
464 return {
465 text: '🏓 <b>Pong</b>\nمسیر داخلی ربات پاسخ داد. latency شبکه یا سلامت سرویس خارجی در این عملیات اندازه‌گیری نشده است.',
424 - reply_markup: { inline_keyboard: [[{ text: '🔙 بازگشت به ابزارها', callback_data: 'menu:tools' }]] }
466 + reply_markup: {
467 + inline_keyboard: [
468 + [{ text: '🔙 بازگشت به ابزارها', callback_data: 'menu:tools' }]
469 + ]
470 + }
471 };
472 }
473 return this.getToolsView();
src/ops-menu.js
+106 -59
@@ -1,14 +1,15 @@
1 import { GuideMenuManager } from './guide-menu.js';
2 import { DEFAULT_CONFIG } from './config.js';
3
4 -const escapeHtml = value => String(value ?? '')
5 - .replaceAll('&', '&amp;')
6 - .replaceAll('<', '&lt;')
7 - .replaceAll('>', '&gt;')
8 - .replaceAll('"', '&quot;');
4 +const escapeHtml = (value) =>
5 + String(value ?? '')
6 + .replaceAll('&', '&amp;')
7 + .replaceAll('<', '&lt;')
8 + .replaceAll('>', '&gt;')
9 + .replaceAll('"', '&quot;');
10
10 -const mark = ok => ok ? '✅' : '❌';
11 -const configuredText = ok => ok ? '✅ پیکربندی شده' : '❌ پیکربندی نشده';
11 +const mark = (ok) => (ok ? '✅' : '❌');
12 +const configuredText = (ok) => (ok ? '✅ پیکربندی شده' : '❌ پیکربندی نشده');
13
14 function backRow(text, callback) {
15 return [{ text, callback_data: callback }];
@@ -22,18 +23,23 @@ export class OpsMenuManager extends GuideMenuManager {
23
24 getMainMenuView() {
25 const view = super.getMainMenuView();
25 - const inlineKeyboard = (view.reply_markup?.inline_keyboard || []).map(row => row.map(button => (
26 - button.callback_data === 'menu:settings'
27 - ? { ...button, text: '⚙️ پیکربندی' }
28 - : button
29 - )));
30 - return { ...view, reply_markup: { ...view.reply_markup, inline_keyboard: inlineKeyboard } };
26 + const inlineKeyboard = (view.reply_markup?.inline_keyboard || []).map(
27 + (row) =>
28 + row.map((button) =>
29 + button.callback_data === 'menu:settings'
30 + ? { ...button, text: '⚙️ پیکربندی' }
31 + : button
32 + )
33 + );
34 + return {
35 + ...view,
36 + reply_markup: { ...view.reply_markup, inline_keyboard: inlineKeyboard }
37 + };
38 }
39
40 getToolsView() {
41 return {
35 - text:
36 -`🔧 <b>ابزارهای توسعه و عیب‌یابی</b>
42 + text: `🔧 <b>ابزارهای توسعه و عیب‌یابی</b>
43 <code>🏠 Nexa Dev &gt; 🔧 ابزارها</code>
44 ➖➖➖➖➖➖➖➖➖➖
45 این بخش Diagnostics واقعی و فقط‌خواندنی Nexa است. هیچ‌کدام از ابزارهای این صفحه GitHub WRITE انجام نمی‌دهند.
@@ -67,8 +73,7 @@ export class OpsMenuManager extends GuideMenuManager {
73 : `❌ ناموفق؛ ${escapeHtml(github.error || 'خطای نامشخص')}`;
74
75 return {
70 - text:
71 -`📊 <b>وضعیت زنده Nexa Dev</b>
76 + text: `📊 <b>وضعیت زنده Nexa Dev</b>
77 <code>🏠 Nexa Dev &gt; 📊 وضعیت</code>
78 ➖➖➖➖➖➖➖➖➖➖
79 • <b>Cloudflare Worker:</b> ✅ این درخواست داخل Worker اجرا شد.
@@ -96,8 +101,7 @@ export class OpsMenuManager extends GuideMenuManager {
101 getSecurityView() {
102 const snapshot = this.diagnostics.getSnapshot();
103 return {
99 - text:
100 -`🔐 <b>مرکز امنیت Nexa Dev</b>
104 + text: `🔐 <b>مرکز امنیت Nexa Dev</b>
105 <code>🏠 Nexa Dev &gt; 🔐 امنیت</code>
106 ➖➖➖➖➖➖➖➖➖➖
107 • <b>Owner-only boundary:</b> ${configuredText(snapshot.ownerConfigured)}
@@ -124,8 +128,7 @@ export class OpsMenuManager extends GuideMenuManager {
128 getSettingsView() {
129 const snapshot = this.diagnostics.getSnapshot();
130 return {
127 - text:
128 -`⚙️ <b>مرکز پیکربندی Nexa Dev</b>
131 + text: `⚙️ <b>مرکز پیکربندی Nexa Dev</b>
132 <code>🏠 Nexa Dev &gt; ⚙️ پیکربندی</code>
133 ➖➖➖➖➖➖➖➖➖➖
134 این بخش در V2.1 عمداً <b>فقط‌خواندنی</b> است تا Secret یا تنظیم حساس از Telegram تغییر نکند.
@@ -154,43 +157,64 @@ export class OpsMenuManager extends GuideMenuManager {
157
158 async getSelfCheckView(backCallback = 'menu:tools') {
159 const report = await this.diagnostics.runSelfCheck();
157 - const lines = report.checks.map(check => {
158 - const detail = check.detail ? ` — ${escapeHtml(check.detail)}` : '';
159 - return `• ${mark(check.ok)} <b>${escapeHtml(check.label)}</b>${detail}`;
160 - }).join('\n');
160 + const lines = report.checks
161 + .map((check) => {
162 + const detail = check.detail ? ` — ${escapeHtml(check.detail)}` : '';
163 + return `• ${mark(check.ok)} <b>${escapeHtml(check.label)}</b>${detail}`;
164 + })
165 + .join('\n');
166 return {
162 - text:
163 -`🩺 <b>Self-check Nexa Dev</b>
167 + text: `🩺 <b>Self-check Nexa Dev</b>
168 ➖➖➖➖➖➖➖➖➖➖
169 ${lines}
170
171 <b>نتیجه:</b> ${report.ok ? '✅ PASS' : '❌ ATTENTION REQUIRED'}
172 این بررسی READ-only است و هیچ Provider mutation اجرا نمی‌کند.`,
169 - reply_markup: { inline_keyboard: [
170 - [{ text: '🔄 اجرای مجدد', callback_data: backCallback === 'menu:security' ? 'security:selfcheck' : 'ops:selfcheck' }],
171 - backRow(backCallback === 'menu:security' ? '🔙 مرکز امنیت' : '🔙 ابزارها', backCallback)
172 - ] }
173 + reply_markup: {
174 + inline_keyboard: [
175 + [
176 + {
177 + text: '🔄 اجرای مجدد',
178 + callback_data:
179 + backCallback === 'menu:security'
180 + ? 'security:selfcheck'
181 + : 'ops:selfcheck'
182 + }
183 + ],
184 + backRow(
185 + backCallback === 'menu:security' ? '🔙 مرکز امنیت' : '🔙 ابزارها',
186 + backCallback
187 + )
188 + ]
189 + }
190 };
191 }
192
176 - async getGitHubProbeView(backCallback = 'menu:tools', refreshCallback = 'ops:github') {
193 + async getGitHubProbeView(
194 + backCallback = 'menu:tools',
195 + refreshCallback = 'ops:github'
196 + ) {
197 const probe = await this.diagnostics.probeGitHub();
198 return {
199 text: probe.ok
200 ? `🐙 <b>تست اتصال GitHub</b>\n➖➖➖➖➖➖➖➖➖➖\n✅ READ زنده موفق بود.\nمالک: <code>${escapeHtml(probe.owner)}</code>\nRepositoryهای قابل مشاهده: <b>${probe.repositoryCount}</b>\n\nهیچ WRITEای انجام نشد.`
201 : `🐙 <b>تست اتصال GitHub</b>\n➖➖➖➖➖➖➖➖➖➖\n❌ READ زنده ناموفق بود.\n${escapeHtml(probe.error || 'خطای نامشخص')}\n\nهیچ وضعیت موفق ساختگی نمایش داده نمی‌شود.`,
182 - reply_markup: { inline_keyboard: [
183 - [{ text: '🔄 تست دوباره', callback_data: refreshCallback }],
184 - backRow(backCallback === 'menu:settings' ? '🔙 پیکربندی' : '🔙 ابزارها', backCallback)
185 - ] }
202 + reply_markup: {
203 + inline_keyboard: [
204 + [{ text: '🔄 تست دوباره', callback_data: refreshCallback }],
205 + backRow(
206 + backCallback === 'menu:settings' ? '🔙 پیکربندی' : '🔙 ابزارها',
207 + backCallback
208 + )
209 + ]
210 + }
211 };
212 }
213
214 getRuntimeView(backCallback = 'menu:tools') {
215 const snapshot = this.diagnostics.getSnapshot();
216 return {
192 - text:
193 -`🧱 <b>Runtime / Bindings</b>
217 + text: `🧱 <b>Runtime / Bindings</b>
218 ➖➖➖➖➖➖➖➖➖➖
219 • Runtime: <b>${escapeHtml(snapshot.runtime)}</b>
220 • Telegram Bot: ${configuredText(snapshot.telegramConfigured)}
@@ -202,61 +226,80 @@ ${lines}
226 • Approval signer: ${configuredText(snapshot.approvalSignerConfigured)}
227
228 این صفحه فقط وجود پیکربندی را نشان می‌دهد و هیچ Secretی را چاپ نمی‌کند.`,
205 - reply_markup: { inline_keyboard: [backRow(backCallback === 'menu:settings' ? '🔙 پیکربندی' : '🔙 ابزارها', backCallback)] }
229 + reply_markup: {
230 + inline_keyboard: [
231 + backRow(
232 + backCallback === 'menu:settings' ? '🔙 پیکربندی' : '🔙 ابزارها',
233 + backCallback
234 + )
235 + ]
236 + }
237 };
238 }
239
240 getPluginsView(backCallback = 'menu:tools') {
241 const summary = this.diagnostics.getPluginSummary();
242 const items = summary.plugins.length
212 - ? summary.plugins.map(plugin => `• <b>${escapeHtml(plugin.id)}</b>: ${plugin.actionCount} Action — READ ${plugin.risks.READ} / WRITE ${plugin.risks.WRITE} / DESTRUCTIVE ${plugin.risks.DESTRUCTIVE}`).join('\n')
243 + ? summary.plugins
244 + .map(
245 + (plugin) =>
246 + `• <b>${escapeHtml(plugin.id)}</b>: ${plugin.actionCount} Action — READ ${plugin.risks.READ} / WRITE ${plugin.risks.WRITE} / DESTRUCTIVE ${plugin.risks.DESTRUCTIVE}`
247 + )
248 + .join('\n')
249 : '<i>Plugin ثبت‌شده‌ای یافت نشد.</i>';
250 return {
215 - text:
216 -`🧩 <b>Plugin Registry</b>
251 + text: `🧩 <b>Plugin Registry</b>
252 ➖➖➖➖➖➖➖➖➖➖
253 Pluginها: <b>${summary.pluginCount}</b>
254 Actionها: <b>${summary.actionCount}</b>
255
256 ${items}`,
222 - reply_markup: { inline_keyboard: [backRow(backCallback === 'menu:settings' ? '🔙 پیکربندی' : '🔙 ابزارها', backCallback)] }
257 + reply_markup: {
258 + inline_keyboard: [
259 + backRow(
260 + backCallback === 'menu:settings' ? '🔙 پیکربندی' : '🔙 ابزارها',
261 + backCallback
262 + )
263 + ]
264 + }
265 };
266 }
267
268 getSecurityPolicyView() {
269 return {
228 - text:
229 -`📜 <b>سیاست عملیات Nexa Dev</b>
270 + text: `📜 <b>سیاست عملیات Nexa Dev</b>
271 ➖➖➖➖➖➖➖➖➖➖
272 • <b>READ:</b> فقط برای Owner مجاز است و بدون Safe Approval قابل اجراست.
273 • <b>WRITE:</b> قبل از Provider mutation به Safe Approval معتبر و Owner-bound نیاز دارد.
274 • <b>DESTRUCTIVE:</b> باید پشت همان Policy مرکزی و تأیید صریح باقی بماند؛ این مرکز امنیت هیچ مسیر دورزدنی ایجاد نمی‌کند.
275 • Approval token به Owner / Action / Risk / Target / Expiry متصل و یک‌بارمصرف است.
276 • Source، Draft، Secret و Signed token نباید وارد Audit log شوند.`,
236 - reply_markup: { inline_keyboard: [backRow('🔙 مرکز امنیت', 'menu:security')] }
277 + reply_markup: {
278 + inline_keyboard: [backRow('🔙 مرکز امنیت', 'menu:security')]
279 + }
280 };
281 }
282
283 getApprovalStatusView() {
284 const snapshot = this.diagnostics.getSnapshot();
285 return {
243 - text:
244 -`✅ <b>وضعیت Safe Approval</b>
286 + text: `✅ <b>وضعیت Safe Approval</b>
287 ➖➖➖➖➖➖➖➖➖➖
288 • Signer: ${configuredText(snapshot.approvalSignerConfigured)}
289 • Durable replay guard: ${configuredText(snapshot.replayGuardConfigured)}
290 • Owner lock: ${configuredText(snapshot.ownerConfigured)}
291
292 WRITE فقط بعد از تأیید معتبر اجرا می‌شود و Approval مصرف‌شده دوباره قابل استفاده نیست.`,
251 - reply_markup: { inline_keyboard: [backRow('🔙 مرکز امنیت', 'menu:security')] }
293 + reply_markup: {
294 + inline_keyboard: [backRow('🔙 مرکز امنیت', 'menu:security')]
295 + }
296 };
297 }
298
299 getProvidersView() {
300 const snapshot = this.diagnostics.getSnapshot();
301 return {
258 - text:
259 -`🔗 <b>Providerها و اتصال‌ها</b>
302 + text: `🔗 <b>Providerها و اتصال‌ها</b>
303 ➖➖➖➖➖➖➖➖➖➖
304 • GitHub owner: <code>${escapeHtml(snapshot.githubOwner)}</code>
305 • GitHub credential: ${configuredText(snapshot.githubConfigured)}
@@ -264,24 +307,27 @@ WRITE فقط بعد از تأیید معتبر اجرا می‌شود و Approva
307 • Telegram Webhook secret: ${configuredText(snapshot.webhookSecretConfigured)}
308
309 مقادیر Credential نمایش داده نمی‌شوند. برای اعتبارسنجی Provider، تست READ زنده GitHub را مستقیماً اجرا کنید.`,
267 - reply_markup: { inline_keyboard: [
268 - [{ text: '🐙 تست زنده GitHub', callback_data: 'config:github' }],
269 - backRow('🔙 پیکربندی', 'menu:settings')
270 - ] }
310 + reply_markup: {
311 + inline_keyboard: [
312 + [{ text: '🐙 تست زنده GitHub', callback_data: 'config:github' }],
313 + backRow('🔙 پیکربندی', 'menu:settings')
314 + ]
315 + }
316 };
317 }
318
319 getEditorConfigView() {
320 return {
276 - text:
277 -`🧑‍💻 <b>پیکربندی Workspace Editor</b>
321 + text: `🧑‍💻 <b>پیکربندی Workspace Editor</b>
322 ➖➖➖➖➖➖➖➖➖➖
323 • نوع: <b>Telegram Mini App</b>
324 • URL: <code>${escapeHtml(DEFAULT_CONFIG.workspaceEditorUrl)}</code>
325 • ذخیره: <b>Durable Draft در WORKSPACE_STORE</b>
326 • GitHub WRITE مستقیم از Editor: <b>ندارد</b>
327 • Commit نهایی: <b>Branch-only + Safe Approval</b>`,
284 - reply_markup: { inline_keyboard: [backRow('🔙 پیکربندی', 'menu:settings')] }
328 + reply_markup: {
329 + inline_keyboard: [backRow('🔙 پیکربندی', 'menu:settings')]
330 + }
331 };
332 }
333
@@ -311,7 +357,8 @@ WRITE فقط بعد از تأیید معتبر اجرا می‌شود و Approva
357 if (action === 'config') {
358 if (target === 'runtime') return this.getRuntimeView('menu:settings');
359 if (target === 'providers') return this.getProvidersView();
314 - if (target === 'github') return this.getGitHubProbeView('menu:settings', 'config:github');
360 + if (target === 'github')
361 + return this.getGitHubProbeView('menu:settings', 'config:github');
362 if (target === 'editor') return this.getEditorConfigView();
363 if (target === 'plugins') return this.getPluginsView('menu:settings');
364 }
src/platform-menu.js
+29 -4
@@ -1,4 +1,29 @@
1 -import {UX_CAPABILITIES} from './core/platform-experience.js';
2 -const esc=v=>String(v??'').replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;');
3 -export function platformHomeView(){const rows=UX_CAPABILITIES.map(c=>[{text:`${c.id}. ${c.title}`,callback_data:`platform:${c.key}`}]);rows.push([{text:'🔙 منوی اصلی',callback_data:'menu:main'}]);return{text:`🧭 <b>مرکز تجربه و توسعه پلتفرم</b>\n➖➖➖➖➖➖➖➖➖➖\nردیف‌های ۸ تا ۱۲ در یک سطح واحد: کمک توسعه، QA مبتنی بر شواهد، کاتالوگ Plugin، نمای چندپروژه‌ای و Command Center.\n\nهیچ‌یک از این مسیرها Policy مرکزی یا Safe Approval را دور نمی‌زند.`,reply_markup:{inline_keyboard:rows}};}
4 -export function platformCapabilityView(key){const c=UX_CAPABILITIES.find(x=>x.key===key);if(!c)return null;return{text:`🧩 <b>${esc(c.title)}</b>\nردیف <b>${c.id}</b> — <code>${esc(c.mode)}</code>\n➖➖➖➖➖➖➖➖➖➖\nاین قابلیت روی مرز Owner-only و Policy مرکزی اجرا می‌شود. دادهٔ ساختگی جایگزین Evidence نمی‌شود و mutation فقط از Actionهای ثبت‌شده و Safe Approval عبور می‌کند.`,reply_markup:{inline_keyboard:[[{text:'🔙 مرکز پلتفرم',callback_data:'menu:platform'}],[{text:'🏠 منوی اصلی',callback_data:'menu:main'}]]}};}
1 +import { UX_CAPABILITIES } from './core/platform-experience.js';
2 +const esc = (v) =>
3 + String(v ?? '')
4 + .replaceAll('&', '&amp;')
5 + .replaceAll('<', '&lt;')
6 + .replaceAll('>', '&gt;');
7 +export function platformHomeView() {
8 + const rows = UX_CAPABILITIES.map((c) => [
9 + { text: `${c.id}. ${c.title}`, callback_data: `platform:${c.key}` }
10 + ]);
11 + rows.push([{ text: '🔙 منوی اصلی', callback_data: 'menu:main' }]);
12 + return {
13 + text: `🧭 <b>مرکز تجربه و توسعه پلتفرم</b>\n➖➖➖➖➖➖➖➖➖➖\nردیف‌های ۸ تا ۱۲ در یک سطح واحد: کمک توسعه، QA مبتنی بر شواهد، کاتالوگ Plugin، نمای چندپروژه‌ای و Command Center.\n\nهیچ‌یک از این مسیرها Policy مرکزی یا Safe Approval را دور نمی‌زند.`,
14 + reply_markup: { inline_keyboard: rows }
15 + };
16 +}
17 +export function platformCapabilityView(key) {
18 + const c = UX_CAPABILITIES.find((x) => x.key === key);
19 + if (!c) return null;
20 + return {
21 + text: `🧩 <b>${esc(c.title)}</b>\nردیف <b>${c.id}</b> — <code>${esc(c.mode)}</code>\n➖➖➖➖➖➖➖➖➖➖\nاین قابلیت روی مرز Owner-only و Policy مرکزی اجرا می‌شود. دادهٔ ساختگی جایگزین Evidence نمی‌شود و mutation فقط از Actionهای ثبت‌شده و Safe Approval عبور می‌کند.`,
22 + reply_markup: {
23 + inline_keyboard: [
24 + [{ text: '🔙 مرکز پلتفرم', callback_data: 'menu:platform' }],
25 + [{ text: '🏠 منوی اصلی', callback_data: 'menu:main' }]
26 + ]
27 + }
28 + };
29 +}
src/plugins/cloudflare/plugin.js
+171 -48
@@ -1,33 +1,59 @@
1 import { correlateDeliveryState } from '../../core/cicd-control-plane.js';
2 import { cloudflarePluginManifest } from './manifest.js';
3
4 -const escapeHtml = value => String(value ?? '')
5 - .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;');
6 -const mark = value => value ? '✅' : '❌';
4 +const escapeHtml = (value) =>
5 + String(value ?? '')
6 + .replaceAll('&', '&amp;')
7 + .replaceAll('<', '&lt;')
8 + .replaceAll('>', '&gt;')
9 + .replaceAll('"', '&quot;');
10 +const mark = (value) => (value ? '✅' : '❌');
11 const VERSION_ID = /^[0-9a-f-]{36}$/i;
12
13 function unavailableView() {
14 return {
15 text: '☁️ <b>Cloudflare Worker</b>\n❌ Provider Cloudflare پیکربندی نشده است.\nهیچ وضعیت موفق ساختگی نمایش داده نمی‌شود.',
12 - reply_markup: { inline_keyboard: [[{ text: '🔄 بررسی مجدد', callback_data: 'cf:status' }],[{ text: '🔙 ابزارها', callback_data: 'menu:tools' }]] }
16 + reply_markup: {
17 + inline_keyboard: [
18 + [{ text: '🔄 بررسی مجدد', callback_data: 'cf:status' }],
19 + [{ text: '🔙 ابزارها', callback_data: 'menu:tools' }]
20 + ]
21 + }
22 };
23 }
24
25 function snapshotView(snapshot) {
17 - const deployment=snapshot.deployment, version=snapshot.version, obs=snapshot.observability||{};
18 - const traffic=deployment?.versions?.length ? deployment.versions.map(i=>`${escapeHtml(i.versionId||'-')} — ${Number(i.percentage||0)}%`).join('\n') : 'استقرار فعالی گزارش نشده است.';
19 - const bindings=snapshot.bindings?.length ? snapshot.bindings.slice(0,20).map(i=>`• <code>${escapeHtml(i.name||'-')}</code> — ${escapeHtml(i.type||'-')}`).join('\n') : '<i>Bindingی گزارش نشده است.</i>';
26 + const deployment = snapshot.deployment,
27 + version = snapshot.version,
28 + obs = snapshot.observability || {};
29 + const traffic = deployment?.versions?.length
30 + ? deployment.versions
31 + .map(
32 + (i) =>
33 + `${escapeHtml(i.versionId || '-')} — ${Number(i.percentage || 0)}%`
34 + )
35 + .join('\n')
36 + : 'استقرار فعالی گزارش نشده است.';
37 + const bindings = snapshot.bindings?.length
38 + ? snapshot.bindings
39 + .slice(0, 20)
40 + .map(
41 + (i) =>
42 + `• <code>${escapeHtml(i.name || '-')}</code> — ${escapeHtml(i.type || '-')}`
43 + )
44 + .join('\n')
45 + : '<i>Bindingی گزارش نشده است.</i>';
46 return {
21 - text:`☁️ <b>Cloudflare Worker — ${escapeHtml(snapshot.workerName||'-')}</b>
47 + text: `☁️ <b>Cloudflare Worker — ${escapeHtml(snapshot.workerName || '-')}</b>
48 ➖➖➖➖➖➖➖➖➖➖
49 <b>Deployment</b>
24 -ID: <code>${escapeHtml(deployment?.id||'-')}</code>
25 -Created: <code>${escapeHtml(deployment?.createdOn||'-')}</code>
50 +ID: <code>${escapeHtml(deployment?.id || '-')}</code>
51 +Created: <code>${escapeHtml(deployment?.createdOn || '-')}</code>
52 Traffic:
53 ${traffic}
54
55 <b>Version</b>
30 -ID: <code>${escapeHtml(version?.id||'-')}</code>
56 +ID: <code>${escapeHtml(version?.id || '-')}</code>
57
58 <b>Bindings</b>
59 ${bindings}
@@ -39,25 +65,47 @@ ${bindings}
65 • Traces: ${mark(obs.tracesEnabled)}
66
67 Secret values نمایش داده نمی‌شوند.`,
42 - reply_markup:{inline_keyboard:[
43 - [{text:'🚦 CI/CD Control Plane',callback_data:'cf:delivery'}],
44 - [{text:'📚 نسخه‌ها / Rollback',callback_data:'cf:versions'}],
45 - [{text:'🔄 بروزرسانی',callback_data:'cf:status'}],
46 - [{text:'🔙 ابزارها',callback_data:'menu:tools'}]
47 - ]}
68 + reply_markup: {
69 + inline_keyboard: [
70 + [{ text: '🚦 CI/CD Control Plane', callback_data: 'cf:delivery' }],
71 + [{ text: '📚 نسخه‌ها / Rollback', callback_data: 'cf:versions' }],
72 + [{ text: '🔄 بروزرسانی', callback_data: 'cf:status' }],
73 + [{ text: '🔙 ابزارها', callback_data: 'menu:tools' }]
74 + ]
75 + }
76 };
77 }
78
51 -function versionsView(versions=[]) {
52 - const rows=versions.slice(0,10).filter(v=>VERSION_ID.test(v.id)).map(v=>[
53 - {text:`🚀 ${v.id.slice(0,8)} · ${String(v.createdOn||'').slice(0,10)}`,callback_data:`cfdeploy:${v.id}`}
54 - ]);
79 +function versionsView(versions = []) {
80 + const rows = versions
81 + .slice(0, 10)
82 + .filter((v) => VERSION_ID.test(v.id))
83 + .map((v) => [
84 + {
85 + text: `🚀 ${v.id.slice(0, 8)} · ${String(v.createdOn || '').slice(0, 10)}`,
86 + callback_data: `cfdeploy:${v.id}`
87 + }
88 + ]);
89 return {
56 - text:`☁️ <b>Cloudflare Versions</b>
90 + text: `☁️ <b>Cloudflare Versions</b>
91 هر Deploy/Rollback یک عملیات DESTRUCTIVE با Safe Approval است.
92 ➖➖➖➖➖➖➖➖➖➖
59 -${versions.slice(0,10).map(v=>`• <code>${escapeHtml(v.id)}</code>\n ${escapeHtml(v.createdOn||'-')} · ${escapeHtml(v.triggeredBy||'-')}`).join('\n\n')||'<i>نسخه‌ای گزارش نشده است.</i>'}`,
60 - reply_markup:{inline_keyboard:[...rows,[{text:'🔄 بروزرسانی',callback_data:'cf:versions'}],[{text:'🔙 Cloudflare',callback_data:'cf:status'}]]}
93 +${
94 + versions
95 + .slice(0, 10)
96 + .map(
97 + (v) =>
98 + `• <code>${escapeHtml(v.id)}</code>\n ${escapeHtml(v.createdOn || '-')} · ${escapeHtml(v.triggeredBy || '-')}`
99 + )
100 + .join('\n\n') || '<i>نسخه‌ای گزارش نشده است.</i>'
101 +}`,
102 + reply_markup: {
103 + inline_keyboard: [
104 + ...rows,
105 + [{ text: '🔄 بروزرسانی', callback_data: 'cf:versions' }],
106 + [{ text: '🔙 Cloudflare', callback_data: 'cf:status' }]
107 + ]
108 + }
109 };
110 }
111
@@ -65,31 +113,106 @@ export function createCloudflarePlugin({ cloudflare, github } = {}) {
113 return {
114 manifest: cloudflarePluginManifest,
115 resolveCallback(data) {
68 - const value=String(data||'');
69 - if(value==='cf:status') return {actionId:'cloudflare.worker.status',kind:'worker-status',async execute(){if(!cloudflare?.isConfigured?.())return unavailableView();return snapshotView(await cloudflare.getWorkerSnapshot());}};
70 - if(value==='cf:versions') return {actionId:'cloudflare.worker.versions',kind:'versions',async execute(){if(!cloudflare?.isConfigured?.())return unavailableView();return versionsView(await cloudflare.listVersions());}};
71 - if(value==='cf:delivery') return {actionId:'cloudflare.delivery.status',kind:'delivery-status',async execute(){
72 - if(!cloudflare?.isConfigured?.() || !github) return {text:'🚦 <b>Delivery Control Plane</b>\n❌ Provider evidence is not configured.',reply_markup:{inline_keyboard:[[{text:'🔙 Cloudflare',callback_data:'cf:status'}]]}};
73 - const repos=await github.listRepositories();
74 - const repo=repos.find(item=>item.name===cloudflare.workerName) || repos[0];
75 - if(!repo) throw new Error('GitHub repository evidence is unavailable');
76 - const [commits,runs,runtime]=await Promise.all([github.listCommits(repo.id),github.listWorkflowRuns(repo.id,{perPage:20,page:1}),cloudflare.getWorkerSnapshot()]);
77 - const targetSha=String(commits[0]?.fullSha||'');
78 - const ci=runs.find(run=>run.name==='CI' && run.branch===(repo.defaultBranch||'main') && run.fullSha===targetSha) || null;
79 - const deploy=runs.find(run=>/Deploy Cloudflare Worker/i.test(run.name) && run.branch===(repo.defaultBranch||'main') && run.fullSha===targetSha) || null;
80 - const state=correlateDeliveryState({targetSha,ci,deploy,runtime});
81 - const label=state.state==='success'?'SUCCESS / موفق':state.state.toUpperCase();
82 - return {text:`🚦 <b>CI/CD Control Plane</b>\nState: <b>${label}</b>\nSHA: <code>${escapeHtml(targetSha.slice(0,12)||'-')}</code>\nCI: <b>${escapeHtml(ci?.conclusion||ci?.status||'unknown')}</b>\nDeploy: <b>${escapeHtml(deploy?.conclusion||deploy?.status||'unknown')}</b>\nRuntime: <code>${escapeHtml(state.versionId||runtime?.deployment?.versions?.[0]?.versionId||'-')}</code>\n\n${escapeHtml(state.reason)}</b>`,reply_markup:{inline_keyboard:[[{text:'🔄 بروزرسانی',callback_data:'cf:delivery'}],[{text:'🔙 Cloudflare',callback_data:'cf:status'}]]}};
83 - }};
84 - const m=value.match(/^cfdeploy:([0-9a-f-]{36})$/i);
85 - if(m) {
86 - const versionId=m[1];
116 + const value = String(data || '');
117 + if (value === 'cf:status')
118 + return {
119 + actionId: 'cloudflare.worker.status',
120 + kind: 'worker-status',
121 + async execute() {
122 + if (!cloudflare?.isConfigured?.()) return unavailableView();
123 + return snapshotView(await cloudflare.getWorkerSnapshot());
124 + }
125 + };
126 + if (value === 'cf:versions')
127 + return {
128 + actionId: 'cloudflare.worker.versions',
129 + kind: 'versions',
130 + async execute() {
131 + if (!cloudflare?.isConfigured?.()) return unavailableView();
132 + return versionsView(await cloudflare.listVersions());
133 + }
134 + };
135 + if (value === 'cf:delivery')
136 + return {
137 + actionId: 'cloudflare.delivery.status',
138 + kind: 'delivery-status',
139 + async execute() {
140 + if (!cloudflare?.isConfigured?.() || !github)
141 + return {
142 + text: '🚦 <b>Delivery Control Plane</b>\n❌ Provider evidence is not configured.',
143 + reply_markup: {
144 + inline_keyboard: [
145 + [{ text: '🔙 Cloudflare', callback_data: 'cf:status' }]
146 + ]
147 + }
148 + };
149 + const repos = await github.listRepositories();
150 + const repo =
151 + repos.find((item) => item.name === cloudflare.workerName) ||
152 + repos[0];
153 + if (!repo)
154 + throw new Error('GitHub repository evidence is unavailable');
155 + const [commits, runs, runtime] = await Promise.all([
156 + github.listCommits(repo.id),
157 + github.listWorkflowRuns(repo.id, { perPage: 20, page: 1 }),
158 + cloudflare.getWorkerSnapshot()
159 + ]);
160 + const targetSha = String(commits[0]?.fullSha || '');
161 + const ci =
162 + runs.find(
163 + (run) =>
164 + run.name === 'CI' &&
165 + run.branch === (repo.defaultBranch || 'main') &&
166 + run.fullSha === targetSha
167 + ) || null;
168 + const deploy =
169 + runs.find(
170 + (run) =>
171 + /Deploy Cloudflare Worker/i.test(run.name) &&
172 + run.branch === (repo.defaultBranch || 'main') &&
173 + run.fullSha === targetSha
174 + ) || null;
175 + const state = correlateDeliveryState({
176 + targetSha,
177 + ci,
178 + deploy,
179 + runtime
180 + });
181 + const label =
182 + state.state === 'success'
183 + ? 'SUCCESS / موفق'
184 + : state.state.toUpperCase();
185 + return {
186 + text: `🚦 <b>CI/CD Control Plane</b>\nState: <b>${label}</b>\nSHA: <code>${escapeHtml(targetSha.slice(0, 12) || '-')}</code>\nCI: <b>${escapeHtml(ci?.conclusion || ci?.status || 'unknown')}</b>\nDeploy: <b>${escapeHtml(deploy?.conclusion || deploy?.status || 'unknown')}</b>\nRuntime: <code>${escapeHtml(state.versionId || runtime?.deployment?.versions?.[0]?.versionId || '-')}</code>\n\n${escapeHtml(state.reason)}</b>`,
187 + reply_markup: {
188 + inline_keyboard: [
189 + [{ text: '🔄 بروزرسانی', callback_data: 'cf:delivery' }],
190 + [{ text: '🔙 Cloudflare', callback_data: 'cf:status' }]
191 + ]
192 + }
193 + };
194 + }
195 + };
196 + const m = value.match(/^cfdeploy:([0-9a-f-]{36})$/i);
197 + if (m) {
198 + const versionId = m[1];
199 return {
88 - actionId:'cloudflare.worker.deploy_version',
89 - approval:{input:{versionId},label:`Deploy/Rollback Cloudflare ${versionId.slice(0,8)}`,cancelCallback:'cf:versions'},
90 - async execute(){
91 - const result=await cloudflare.deployVersion(versionId);
92 - return {text:`✅ Cloudflare version <code>${escapeHtml(result.versionId)}</code> با 100% traffic تأیید شد.`,reply_markup:{inline_keyboard:[[{text:'☁️ وضعیت',callback_data:'cf:status'}]]}};
200 + actionId: 'cloudflare.worker.deploy_version',
201 + approval: {
202 + input: { versionId },
203 + label: `Deploy/Rollback Cloudflare ${versionId.slice(0, 8)}`,
204 + cancelCallback: 'cf:versions'
205 + },
206 + async execute() {
207 + const result = await cloudflare.deployVersion(versionId);
208 + return {
209 + text: `✅ Cloudflare version <code>${escapeHtml(result.versionId)}</code> با 100% traffic تأیید شد.`,
210 + reply_markup: {
211 + inline_keyboard: [
212 + [{ text: '☁️ وضعیت', callback_data: 'cf:status' }]
213 + ]
214 + }
215 + };
216 }
217 };
218 }
src/plugins/cloudflare/service.js
+125 -51
@@ -1,7 +1,7 @@
1 const API_BASE = 'https://api.cloudflare.com/client/v4';
2
3 -const clean = value => String(value ?? '').trim();
4 -const safe = value => encodeURIComponent(clean(value));
3 +const clean = (value) => String(value ?? '').trim();
4 +const safe = (value) => encodeURIComponent(clean(value));
5
6 function redact(message, token) {
7 const text = String(message || 'Cloudflare request failed');
@@ -10,11 +10,19 @@ function redact(message, token) {
10
11 function firstError(payload) {
12 const errors = Array.isArray(payload?.errors) ? payload.errors : [];
13 - return errors.map(item => item?.message).filter(Boolean).join('; ');
13 + return errors
14 + .map((item) => item?.message)
15 + .filter(Boolean)
16 + .join('; ');
17 }
18
19 export class CloudflareService {
17 - constructor({ token = '', accountId = '', workerName = '', fetchImpl = globalThis.fetch } = {}) {
20 + constructor({
21 + token = '',
22 + accountId = '',
23 + workerName = '',
24 + fetchImpl = globalThis.fetch
25 + } = {}) {
26 this.token = clean(token);
27 this.accountId = clean(accountId);
28 this.workerName = clean(workerName);
@@ -22,11 +30,17 @@ export class CloudflareService {
30 }
31
32 isConfigured() {
25 - return Boolean(this.token && this.accountId && this.workerName && typeof this.fetchImpl === 'function');
33 + return Boolean(
34 + this.token &&
35 + this.accountId &&
36 + this.workerName &&
37 + typeof this.fetchImpl === 'function'
38 + );
39 }
40
41 requireConfigured() {
29 - if (!this.isConfigured()) throw new Error('Cloudflare provider is not configured');
42 + if (!this.isConfigured())
43 + throw new Error('Cloudflare provider is not configured');
44 }
45
46 get headers() {
@@ -48,7 +62,9 @@ export class CloudflareService {
62 if (body !== undefined) options.body = JSON.stringify(body);
63 response = await this.fetchImpl(this.endpoint(suffix), options);
64 } catch (error) {
51 - throw new Error(redact(`${label} failed: ${error?.message || error}`, this.token));
65 + throw new Error(
66 + redact(`${label} failed: ${error?.message || error}`, this.token)
67 + );
68 }
69
70 let raw = '';
@@ -60,97 +76,155 @@ export class CloudflareService {
76
77 let payload = null;
78 if (raw) {
63 - try { payload = JSON.parse(raw); } catch { payload = null; }
79 + try {
80 + payload = JSON.parse(raw);
81 + } catch {
82 + payload = null;
83 + }
84 }
85
86 if (!response.ok || payload?.success === false) {
67 - const detail = firstError(payload) || raw.slice(0, 240) || 'request failed';
68 - throw new Error(redact(`${label} failed: ${response.status} ${detail}`, this.token));
87 + const detail =
88 + firstError(payload) || raw.slice(0, 240) || 'request failed';
89 + throw new Error(
90 + redact(`${label} failed: ${response.status} ${detail}`, this.token)
91 + );
92 }
93
71 - if (payload === null) throw new Error(`${label} failed: invalid JSON response`);
94 + if (payload === null)
95 + throw new Error(`${label} failed: invalid JSON response`);
96 return payload?.result ?? payload;
97 }
98
99 async listVersions() {
100 const result = await this.requestJson('/versions', 'Cloudflare versions');
77 - const items = Array.isArray(result?.items) ? result.items : Array.isArray(result) ? result : [];
78 - return items.slice(0, 20).map(item => ({
79 - id: clean(item?.id),
80 - createdOn: clean(item?.created_on),
81 - triggeredBy: clean(item?.annotations?.['workers/triggered_by'])
82 - })).filter(item => item.id);
101 + const items = Array.isArray(result?.items)
102 + ? result.items
103 + : Array.isArray(result)
104 + ? result
105 + : [];
106 + return items
107 + .slice(0, 20)
108 + .map((item) => ({
109 + id: clean(item?.id),
110 + createdOn: clean(item?.created_on),
111 + triggeredBy: clean(item?.annotations?.['workers/triggered_by'])
112 + }))
113 + .filter((item) => item.id);
114 }
115
116 async listDeployments() {
86 - const result = await this.requestJson('/deployments', 'Cloudflare deployments');
87 - const items = Array.isArray(result?.deployments) ? result.deployments : Array.isArray(result) ? result : [];
88 - return items.slice(0, 20).map(item => ({
117 + const result = await this.requestJson(
118 + '/deployments',
119 + 'Cloudflare deployments'
120 + );
121 + const items = Array.isArray(result?.deployments)
122 + ? result.deployments
123 + : Array.isArray(result)
124 + ? result
125 + : [];
126 + return items.slice(0, 20).map((item) => ({
127 id: clean(item?.id),
128 createdOn: clean(item?.created_on),
91 - versions: (Array.isArray(item?.versions) ? item.versions : []).map(version => ({
92 - versionId: clean(version?.version_id),
93 - percentage: Number.isFinite(Number(version?.percentage)) ? Number(version.percentage) : 0
94 - }))
129 + versions: (Array.isArray(item?.versions) ? item.versions : []).map(
130 + (version) => ({
131 + versionId: clean(version?.version_id),
132 + percentage: Number.isFinite(Number(version?.percentage))
133 + ? Number(version.percentage)
134 + : 0
135 + })
136 + )
137 }));
138 }
139
140 async deployVersion(versionId) {
141 const target = clean(versionId);
100 - if (!/^[0-9a-f-]{36}$/i.test(target)) throw new Error('Cloudflare version ID is invalid');
142 + if (!/^[0-9a-f-]{36}$/i.test(target))
143 + throw new Error('Cloudflare version ID is invalid');
144 const versions = await this.listVersions();
102 - if (!versions.some(version => version.id === target)) throw new Error('Cloudflare version is not known');
145 + if (!versions.some((version) => version.id === target))
146 + throw new Error('Cloudflare version is not known');
147 await this.requestJson('/deployments', 'Cloudflare deploy version', {
148 method: 'POST',
105 - body: { strategy: 'percentage', versions: [{ percentage: 100, version_id: target }] }
149 + body: {
150 + strategy: 'percentage',
151 + versions: [{ percentage: 100, version_id: target }]
152 + }
153 });
154 const snapshot = await this.getWorkerSnapshot();
155 const active = snapshot.deployment?.versions || [];
109 - if (active.length !== 1 || active[0].versionId !== target || Number(active[0].percentage) !== 100) {
156 + if (
157 + active.length !== 1 ||
158 + active[0].versionId !== target ||
159 + Number(active[0].percentage) !== 100
160 + ) {
161 throw new Error('Cloudflare deployment verification failed');
162 }
112 - return { versionId: target, deploymentId: snapshot.deployment?.id || '', verified: true };
163 + return {
164 + versionId: target,
165 + deploymentId: snapshot.deployment?.id || '',
166 + verified: true
167 + };
168 }
169
170 async getWorkerSnapshot() {
171 this.requireConfigured();
117 - const [deploymentsResult, versionsResult, settingsResult] = await Promise.all([
118 - this.requestJson('/deployments', 'Cloudflare deployments'),
119 - this.requestJson('/versions', 'Cloudflare versions'),
120 - this.requestJson('/settings', 'Cloudflare settings')
121 - ]);
172 + const [deploymentsResult, versionsResult, settingsResult] =
173 + await Promise.all([
174 + this.requestJson('/deployments', 'Cloudflare deployments'),
175 + this.requestJson('/versions', 'Cloudflare versions'),
176 + this.requestJson('/settings', 'Cloudflare settings')
177 + ]);
178
179 const deployments = Array.isArray(deploymentsResult?.deployments)
180 ? deploymentsResult.deployments
125 - : Array.isArray(deploymentsResult) ? deploymentsResult : [];
181 + : Array.isArray(deploymentsResult)
182 + ? deploymentsResult
183 + : [];
184 const versions = Array.isArray(versionsResult?.items)
185 ? versionsResult.items
128 - : Array.isArray(versionsResult) ? versionsResult : [];
186 + : Array.isArray(versionsResult)
187 + ? versionsResult
188 + : [];
189
190 const latestDeployment = deployments[0] || null;
191 const latestVersion = versions[0] || null;
192 const bindings = Array.isArray(settingsResult?.bindings)
193 ? settingsResult.bindings
134 - .map(binding => ({ name: clean(binding?.name), type: clean(binding?.type) }))
135 - .filter(binding => binding.name || binding.type)
194 + .map((binding) => ({
195 + name: clean(binding?.name),
196 + type: clean(binding?.type)
197 + }))
198 + .filter((binding) => binding.name || binding.type)
199 : [];
200 const observability = settingsResult?.observability || {};
201
202 return {
203 workerName: this.workerName,
141 - deployment: latestDeployment ? {
142 - id: clean(latestDeployment.id),
143 - createdOn: clean(latestDeployment.created_on),
144 - versions: (Array.isArray(latestDeployment.versions) ? latestDeployment.versions : []).map(item => ({
145 - versionId: clean(item?.version_id),
146 - percentage: Number.isFinite(Number(item?.percentage)) ? Number(item.percentage) : 0
147 - }))
148 - } : null,
149 - version: latestVersion ? {
150 - id: clean(latestVersion.id),
151 - createdOn: clean(latestVersion.created_on),
152 - triggeredBy: clean(latestVersion.annotations?.['workers/triggered_by'])
153 - } : null,
204 + deployment: latestDeployment
205 + ? {
206 + id: clean(latestDeployment.id),
207 + createdOn: clean(latestDeployment.created_on),
208 + versions: (Array.isArray(latestDeployment.versions)
209 + ? latestDeployment.versions
210 + : []
211 + ).map((item) => ({
212 + versionId: clean(item?.version_id),
213 + percentage: Number.isFinite(Number(item?.percentage))
214 + ? Number(item.percentage)
215 + : 0
216 + }))
217 + }
218 + : null,
219 + version: latestVersion
220 + ? {
221 + id: clean(latestVersion.id),
222 + createdOn: clean(latestVersion.created_on),
223 + triggeredBy: clean(
224 + latestVersion.annotations?.['workers/triggered_by']
225 + )
226 + }
227 + : null,
228 bindings,
229 observability: {
230 enabled: observability.enabled === true,
src/plugins/github/plugin-legacy.js
+634 -163
@@ -10,11 +10,12 @@ const CALLBACK_ACTIONS = Object.freeze([
10 ['status:', 'github.status.read']
11 ]);
12
13 -const escapeHtml = value => String(value ?? '')
14 - .replaceAll('&', '&amp;')
15 - .replaceAll('<', '&lt;')
16 - .replaceAll('>', '&gt;')
17 - .replaceAll('"', '&quot;');
13 +const escapeHtml = (value) =>
14 + String(value ?? '')
15 + .replaceAll('&', '&amp;')
16 + .replaceAll('<', '&lt;')
17 + .replaceAll('>', '&gt;')
18 + .replaceAll('"', '&quot;');
19
20 const short = (value, max = 80) => {
21 const text = String(value ?? '');
@@ -22,13 +23,17 @@ const short = (value, max = 80) => {
23 };
24
25 const numericPair = (value, prefix) => {
25 - const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+):(\\d+)$`));
26 + const match = String(value || '').match(
27 + new RegExp(`^${prefix}:(\\d+):(\\d+)$`)
28 + );
29 if (!match) return null;
30 return { repoId: Number(match[1]), runId: Number(match[2]) };
31 };
32
33 const numericTriple = (value, prefix) => {
31 - const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+):(\\d+):(\\d+)$`));
34 + const match = String(value || '').match(
35 + new RegExp(`^${prefix}:(\\d+):(\\d+):(\\d+)$`)
36 + );
37 if (!match) return null;
38 return {
39 repoId: Number(match[1]),
@@ -38,7 +43,9 @@ const numericTriple = (value, prefix) => {
43 };
44
45 const pagedPair = (value, prefix) => {
41 - const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+):(\\d+)(?::(\\d+))?$`));
46 + const match = String(value || '').match(
47 + new RegExp(`^${prefix}:(\\d+):(\\d+)(?::(\\d+))?$`)
48 + );
49 if (!match) return null;
50 return {
51 repoId: Number(match[1]),
@@ -53,7 +60,9 @@ const numericSingle = (value, prefix) => {
60 };
61
62 const pagedSingle = (value, prefix) => {
56 - const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+)(?::(\\d+))?$`));
63 + const match = String(value || '').match(
64 + new RegExp(`^${prefix}:(\\d+)(?::(\\d+))?$`)
65 + );
66 if (!match) return null;
67 return {
68 repoId: Number(match[1]),
@@ -61,28 +70,30 @@ const pagedSingle = (value, prefix) => {
70 };
71 };
72
64 -const compareRef = value => {
73 +const compareRef = (value) => {
74 const match = String(value || '').match(/^compare:(\d+):([a-f0-9]{40})$/i);
75 if (!match) return null;
76 return { repoId: Number(match[1]), sha: match[2] };
77 };
78
70 -const commitDetailRef = value => {
71 - const match = String(value || '').match(/^commitdetail:(\d+):([a-f0-9]{40})$/i);
79 +const commitDetailRef = (value) => {
80 + const match = String(value || '').match(
81 + /^commitdetail:(\d+):([a-f0-9]{40})$/i
82 + );
83 if (!match) return null;
84 return { repoId: Number(match[1]), sha: match[2] };
85 };
86
76 -const workflowRunsPage = value => pagedSingle(value, 'runs');
87 +const workflowRunsPage = (value) => pagedSingle(value, 'runs');
88
78 -const runIcon = run => {
89 +const runIcon = (run) => {
90 if (run.conclusion === 'success') return '✅';
91 if (run.conclusion === 'failure') return '❌';
92 if (run.conclusion === 'cancelled') return '⏹';
93 return run.status === 'in_progress' ? '🟡' : '⏳';
94 };
95
85 -const stateIcon = value => {
96 +const stateIcon = (value) => {
97 if (value === 'success' || value === 'completed') return '✅';
98 if (value === 'failure') return '❌';
99 if (value === 'cancelled') return '⏹';
@@ -94,7 +105,9 @@ const stateIcon = value => {
105 const addRepoAdvancedButtons = (view, repoId) => {
106 const rows = [...(view?.reply_markup?.inline_keyboard || [])];
107 const insertAt = Math.max(0, rows.length - 1);
97 - rows.splice(insertAt, 0,
108 + rows.splice(
109 + insertAt,
110 + 0,
111 [{ text: '🌿 Branches', callback_data: `branches:${repoId}` }],
112 [
113 { text: '🐛 Issues', callback_data: `issues:${repoId}` },
@@ -109,53 +122,117 @@ const addRepoAdvancedButtons = (view, repoId) => {
122
123 function listPagination(prefix, repoId, page, count, pageSize) {
124 const row = [];
112 - if (page > 1) row.push({ text: '⬅️ جدیدتر', callback_data: `${prefix}:${repoId}:${page - 1}` });
113 - if (count === pageSize && page < 100) row.push({ text: 'قدیمی‌تر ➡️', callback_data: `${prefix}:${repoId}:${page + 1}` });
125 + if (page > 1)
126 + row.push({
127 + text: '⬅️ جدیدتر',
128 + callback_data: `${prefix}:${repoId}:${page - 1}`
129 + });
130 + if (count === pageSize && page < 100)
131 + row.push({
132 + text: 'قدیمی‌تر ➡️',
133 + callback_data: `${prefix}:${repoId}:${page + 1}`
134 + });
135 return row.length ? [row] : [];
136 }
137
138 function explicitPagination(prefix, repoId, page, hasMore) {
139 const row = [];
119 - if (page > 1) row.push({ text: '⬅️ جدیدتر', callback_data: `${prefix}:${repoId}:${page - 1}` });
120 - if (hasMore && page < 100) row.push({ text: 'قدیمی‌تر ➡️', callback_data: `${prefix}:${repoId}:${page + 1}` });
140 + if (page > 1)
141 + row.push({
142 + text: '⬅️ جدیدتر',
143 + callback_data: `${prefix}:${repoId}:${page - 1}`
144 + });
145 + if (hasMore && page < 100)
146 + row.push({
147 + text: 'قدیمی‌تر ➡️',
148 + callback_data: `${prefix}:${repoId}:${page + 1}`
149 + });
150 return row.length ? [row] : [];
151 }
152
153 function pairPagination(prefix, repoId, itemId, page, count, pageSize) {
154 const row = [];
126 - if (page > 1) row.push({ text: '⬅️ جدیدتر', callback_data: `${prefix}:${repoId}:${itemId}:${page - 1}` });
127 - if (count === pageSize && page < 100) row.push({ text: 'قدیمی‌تر ➡️', callback_data: `${prefix}:${repoId}:${itemId}:${page + 1}` });
155 + if (page > 1)
156 + row.push({
157 + text: '⬅️ جدیدتر',
158 + callback_data: `${prefix}:${repoId}:${itemId}:${page - 1}`
159 + });
160 + if (count === pageSize && page < 100)
161 + row.push({
162 + text: 'قدیمی‌تر ➡️',
163 + callback_data: `${prefix}:${repoId}:${itemId}:${page + 1}`
164 + });
165 return row.length ? [row] : [];
166 }
167
168 async function commitsView(github, repoId) {
132 - const [repo, commits] = await Promise.all([github.getRepository(repoId), github.listCommits(repoId)]);
169 + const [repo, commits] = await Promise.all([
170 + github.getRepository(repoId),
171 + github.listCommits(repoId)
172 + ]);
173 const body = commits.length
134 - ? commits.slice(0, 10).map(commit => `• <code>${escapeHtml(commit.shortSha || commit.sha)}</code> — ${escapeHtml(short(commit.message, 110))}\n ${escapeHtml(commit.author || 'Unknown')}${commit.date ? ` · ${escapeHtml(commit.date)}` : ''}`).join('\n\n')
174 + ? commits
175 + .slice(0, 10)
176 + .map(
177 + (commit) =>
178 + `• <code>${escapeHtml(commit.shortSha || commit.sha)}</code> — ${escapeHtml(short(commit.message, 110))}\n ${escapeHtml(commit.author || 'Unknown')}${commit.date ? ` · ${escapeHtml(commit.date)}` : ''}`
179 + )
180 + .join('\n\n')
181 : '<i>کامیتی در پاسخ GitHub یافت نشد.</i>';
136 - const detailRows = commits.slice(0, 10).map(commit => {
137 - const sha = String(commit.fullSha || commit.sha || '');
138 - return /^[a-f0-9]{40}$/i.test(sha)
139 - ? [{ text: `📝 ${short(commit.message || sha.slice(0, 7), 42)}`, callback_data: `commitdetail:${repoId}:${sha}` }]
140 - : null;
141 - }).filter(Boolean);
182 + const detailRows = commits
183 + .slice(0, 10)
184 + .map((commit) => {
185 + const sha = String(commit.fullSha || commit.sha || '');
186 + return /^[a-f0-9]{40}$/i.test(sha)
187 + ? [
188 + {
189 + text: `📝 ${short(commit.message || sha.slice(0, 7), 42)}`,
190 + callback_data: `commitdetail:${repoId}:${sha}`
191 + }
192 + ]
193 + : null;
194 + })
195 + .filter(Boolean);
196 return {
197 text: `📝 <b>آخرین Commitهای ${escapeHtml(repo.name)}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
144 - reply_markup: { inline_keyboard: [
145 - ...detailRows,
146 - [{ text: '🔄 بروزرسانی', callback_data: `commits:${repoId}` }, { text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
147 - ] }
198 + reply_markup: {
199 + inline_keyboard: [
200 + ...detailRows,
201 + [
202 + { text: '🔄 بروزرسانی', callback_data: `commits:${repoId}` },
203 + { text: '🔙 پروژه', callback_data: `repo:${repoId}` }
204 + ]
205 + ]
206 + }
207 };
208 }
209
210 async function commitDetailView(github, repoId, sha) {
152 - const [repo, commit] = await Promise.all([github.getRepository(repoId), github.getCommit(repoId, sha)]);
153 - const files = (commit.files || []).slice(0, 12)
154 - .map(file => `• <code>${escapeHtml(short(file.filename, 90))}</code> · ${escapeHtml(file.status || 'changed')} · +${file.additions ?? 0}/-${file.deletions ?? 0}`)
211 + const [repo, commit] = await Promise.all([
212 + github.getRepository(repoId),
213 + github.getCommit(repoId, sha)
214 + ]);
215 + const files = (commit.files || [])
216 + .slice(0, 12)
217 + .map(
218 + (file) =>
219 + `• <code>${escapeHtml(short(file.filename, 90))}</code> · ${escapeHtml(file.status || 'changed')} · +${file.additions ?? 0}/-${file.deletions ?? 0}`
220 + )
221 .join('\n');
222 return {
223 text: `📝 <b>Commit — ${escapeHtml(repo.name)}</b>\n<code>${escapeHtml(commit.shortSha || String(commit.sha).slice(0, 7))}</code> · ${escapeHtml(commit.author || 'Unknown')}\n${escapeHtml(commit.date || '-')}\n+${commit.additions ?? 0}/-${commit.deletions ?? 0} · ${commit.changedFiles ?? (commit.files || []).length} files\n➖➖➖➖➖➖➖➖➖➖\n${escapeHtml(short(commit.message || '', 1200)) || '<i>بدون پیام.</i>'}\n\n<b>فایل‌های تغییرکرده</b>\n${files || '<i>فایلی گزارش نشده است.</i>'}`,
158 - reply_markup: { inline_keyboard: [[{ text: '🔄 بروزرسانی', callback_data: `commitdetail:${repoId}:${sha}` }, { text: '🔙 Commitها', callback_data: `commits:${repoId}` }], [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]] }
224 + reply_markup: {
225 + inline_keyboard: [
226 + [
227 + {
228 + text: '🔄 بروزرسانی',
229 + callback_data: `commitdetail:${repoId}:${sha}`
230 + },
231 + { text: '🔙 Commitها', callback_data: `commits:${repoId}` }
232 + ],
233 + [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
234 + ]
235 + }
236 };
237 }
238
@@ -165,17 +242,26 @@ async function workflowRunsView(github, repoId, page = 1) {
242 github.listWorkflowRuns(repoId, { perPage: 10, page })
243 ]);
244 const body = runs.length
168 - ? 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')
245 + ? runs
246 + .slice(0, 10)
247 + .map(
248 + (run) =>
249 + `${runIcon(run)} <b>${escapeHtml(run.name)}</b> #${run.runNumber ?? '-'}\n └ ${escapeHtml(run.branch || '-')} · <code>${escapeHtml(run.sha || '-')}</code> · ${escapeHtml(run.conclusion || run.status || 'unknown')}`
250 + )
251 + .join('\n\n')
252 : '<i>Workflow runی یافت نشد.</i>';
170 - const refreshCallback = page === 1 ? `runs:${repoId}` : `runs:${repoId}:${page}`;
253 + const refreshCallback =
254 + page === 1 ? `runs:${repoId}` : `runs:${repoId}:${page}`;
255 return {
256 text: `🧪 <b>CI / Actions — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
257 reply_markup: {
258 inline_keyboard: [
175 - ...runs.slice(0, 10).map(run => [{
176 - text: `${runIcon(run)} ${short(run.name, 32)} #${run.runNumber ?? run.id}`,
177 - callback_data: `run:${repoId}:${run.id}`
178 - }]),
259 + ...runs.slice(0, 10).map((run) => [
260 + {
261 + text: `${runIcon(run)} ${short(run.name, 32)} #${run.runNumber ?? run.id}`,
262 + callback_data: `run:${repoId}:${run.id}`
263 + }
264 + ]),
265 ...listPagination('runs', repoId, page, runs.length, 10),
266 [
267 { text: '🔄 بروزرسانی', callback_data: refreshCallback },
@@ -197,8 +283,17 @@ async function workflowRunView(github, repoId, runId) {
283 { text: '📦 Artifacts', callback_data: `artifacts:${repoId}:${runId}` }
284 ]
285 ];
200 - if (run.conclusion === 'failure') rows.push([{ text: '🔁 اجرای مجدد jobهای ناموفق', callback_data: `rerun:${repoId}:${runId}` }]);
201 - if (run.status === 'in_progress' || run.status === 'queued') rows.push([{ text: '⏹ لغو Workflow', callback_data: `cancelrun:${repoId}:${runId}` }]);
286 + if (run.conclusion === 'failure')
287 + rows.push([
288 + {
289 + text: '🔁 اجرای مجدد jobهای ناموفق',
290 + callback_data: `rerun:${repoId}:${runId}`
291 + }
292 + ]);
293 + if (run.status === 'in_progress' || run.status === 'queued')
294 + rows.push([
295 + { text: '⏹ لغو Workflow', callback_data: `cancelrun:${repoId}:${runId}` }
296 + ]);
297 rows.push([
298 { text: '🔄 بروزرسانی', callback_data: `run:${repoId}:${runId}` },
299 { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }
@@ -216,32 +311,65 @@ async function workflowJobsView(github, repoId, runId) {
311 github.listWorkflowJobs(repoId, runId)
312 ]);
313 const body = jobs.length
219 - ? jobs.slice(0, 20).map(job => {
220 - const jobState = job.conclusion || job.status || 'unknown';
221 - const steps = (job.steps || []).slice(0, 30)
222 - .map(step => ` ${stateIcon(step.conclusion || step.status)} ${escapeHtml(step.name)} — ${escapeHtml(step.conclusion || step.status || 'unknown')}`)
223 - .join('\n');
224 - return `<b>${escapeHtml(job.name)}</b> — ${escapeHtml(jobState)}${steps ? `\n${steps}` : ''}`;
225 - }).join('\n\n')
314 + ? jobs
315 + .slice(0, 20)
316 + .map((job) => {
317 + const jobState = job.conclusion || job.status || 'unknown';
318 + const steps = (job.steps || [])
319 + .slice(0, 30)
320 + .map(
321 + (step) =>
322 + ` ${stateIcon(step.conclusion || step.status)} ${escapeHtml(step.name)} — ${escapeHtml(step.conclusion || step.status || 'unknown')}`
323 + )
324 + .join('\n');
325 + return `<b>${escapeHtml(job.name)}</b> — ${escapeHtml(jobState)}${steps ? `\n${steps}` : ''}`;
326 + })
327 + .join('\n\n')
328 : '<i>Jobی در این Run یافت نشد.</i>';
329 return {
330 text: `👷 <b>Jobهای ${escapeHtml(run.name)} — ${escapeHtml(repo.name)}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
331 reply_markup: {
332 inline_keyboard: [
231 - ...jobs.slice(0, 20).map(job => [{ text: `${stateIcon(job.conclusion || job.status)} ${short(job.name, 40)}`, callback_data: `job:${repoId}:${job.id}` }]),
232 - [{ text: '🔄 بروزرسانی', callback_data: `jobs:${repoId}:${runId}` }, { text: '🔙 Run', callback_data: `run:${repoId}:${runId}` }]
333 + ...jobs.slice(0, 20).map((job) => [
334 + {
335 + text: `${stateIcon(job.conclusion || job.status)} ${short(job.name, 40)}`,
336 + callback_data: `job:${repoId}:${job.id}`
337 + }
338 + ]),
339 + [
340 + { text: '🔄 بروزرسانی', callback_data: `jobs:${repoId}:${runId}` },
341 + { text: '🔙 Run', callback_data: `run:${repoId}:${runId}` }
342 + ]
343 ]
344 }
345 };
346 }
347
348 async function workflowJobView(github, repoId, jobId) {
239 - const [repo, job] = await Promise.all([github.getRepository(repoId), github.getWorkflowJob(repoId, jobId)]);
349 + const [repo, job] = await Promise.all([
350 + github.getRepository(repoId),
351 + github.getWorkflowJob(repoId, jobId)
352 + ]);
353 const status = job.conclusion || job.status || 'unknown';
241 - 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');
354 + const steps = (job.steps || [])
355 + .slice(0, 30)
356 + .map(
357 + (step) =>
358 + `${stateIcon(step.conclusion || step.status)} ${escapeHtml(step.name)} — ${escapeHtml(step.conclusion || step.status || 'unknown')}`
359 + )
360 + .join('\n');
361 const rows = [];
243 - if (job.conclusion === 'failure') rows.push([{ text: '📜 مشاهده log ناموفق', callback_data: `joblog:${repoId}:${jobId}` }]);
244 - rows.push([{ text: '🔄 بروزرسانی', callback_data: `job:${repoId}:${jobId}` }, { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }]);
362 + if (job.conclusion === 'failure')
363 + rows.push([
364 + {
365 + text: '📜 مشاهده log ناموفق',
366 + callback_data: `joblog:${repoId}:${jobId}`
367 + }
368 + ]);
369 + rows.push([
370 + { text: '🔄 بروزرسانی', callback_data: `job:${repoId}:${jobId}` },
371 + { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }
372 + ]);
373 return {
374 text: `👷 <b>${escapeHtml(job.name)} — ${escapeHtml(repo.name)}</b>\nوضعیت: ${stateIcon(status)} <b>${escapeHtml(status)}</b>\n➖➖➖➖➖➖➖➖➖➖\n${steps || '<i>Stepی ثبت نشده.</i>'}`,
375 reply_markup: { inline_keyboard: rows }
@@ -254,10 +382,16 @@ async function workflowJobLogView(github, repoId, jobId) {
382 github.getWorkflowJobLog(repoId, jobId, { maxChars: 1800 })
383 ]);
384 const escaped = escapeHtml(log.text).slice(-3200);
257 - const note = log.truncated ? '⚠️ فقط بخش پایانی log نمایش داده شده است.\n\n' : '';
385 + const note = log.truncated
386 + ? '⚠️ فقط بخش پایانی log نمایش داده شده است.\n\n'
387 + : '';
388 return {
389 text: `📜 <b>Log — ${escapeHtml(job.name)}</b>\n${note}<pre>${escaped || '(empty log)'}</pre>`,
260 - reply_markup: { inline_keyboard: [[{ text: '🔙 Job', callback_data: `job:${repoId}:${jobId}` }]] }
390 + reply_markup: {
391 + inline_keyboard: [
392 + [{ text: '🔙 Job', callback_data: `job:${repoId}:${jobId}` }]
393 + ]
394 + }
395 };
396 }
397
@@ -267,192 +401,473 @@ async function workflowArtifactsView(github, repoId, runId, page = 1) {
401 github.listWorkflowArtifacts(repoId, runId, { perPage: 10, page })
402 ]);
403 const body = artifacts.length
270 - ? 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')
404 + ? artifacts
405 + .slice(0, 10)
406 + .map(
407 + (item) =>
408 + `📦 <b>${escapeHtml(item.name)}</b>\n ${item.expired ? 'منقضی شده' : 'فعال'} · ${Number(item.size || 0).toLocaleString()} bytes\n expires: ${escapeHtml(item.expiresAt || '-')}`
409 + )
410 + .join('\n\n')
411 : '<i>Artifactی برای این Run یافت نشد.</i>';
272 - const refreshCallback = page === 1 ? `artifacts:${repoId}:${runId}` : `artifacts:${repoId}:${runId}:${page}`;
412 + const refreshCallback =
413 + page === 1
414 + ? `artifacts:${repoId}:${runId}`
415 + : `artifacts:${repoId}:${runId}:${page}`;
416 return {
417 text: `📦 <b>Artifacts — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
275 - reply_markup: { inline_keyboard: [...pairPagination('artifacts', repoId, runId, page, artifacts.length, 10), [{ text: '🔄 بروزرسانی', callback_data: refreshCallback }, { text: '🔙 Run', callback_data: `run:${repoId}:${runId}` }]] }
418 + reply_markup: {
419 + inline_keyboard: [
420 + ...pairPagination(
421 + 'artifacts',
422 + repoId,
423 + runId,
424 + page,
425 + artifacts.length,
426 + 10
427 + ),
428 + [
429 + { text: '🔄 بروزرسانی', callback_data: refreshCallback },
430 + { text: '🔙 Run', callback_data: `run:${repoId}:${runId}` }
431 + ]
432 + ]
433 + }
434 };
435 }
436
437 async function branchesView(github, repoId, page = 1) {
280 - const [repo, branches] = await Promise.all([github.getRepository(repoId), github.listBranches(repoId, { perPage: 20, page })]);
438 + const [repo, branches] = await Promise.all([
439 + github.getRepository(repoId),
440 + github.listBranches(repoId, { perPage: 20, page })
441 + ]);
442 const body = branches.length
282 - ? 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')
443 + ? branches
444 + .slice(0, 20)
445 + .map(
446 + (branch) =>
447 + `🌿 <b>${escapeHtml(short(branch.name, 70))}</b>\n <code>${escapeHtml(String(branch.sha).slice(0, 10))}</code>${branch.protected ? ' · 🛡 protected' : ''}`
448 + )
449 + .join('\n\n')
450 : '<i>Branchی یافت نشد.</i>';
451 return {
452 text: `🌿 <b>Branches — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
286 - reply_markup: { inline_keyboard: [
287 - ...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}` }]),
288 - ...listPagination('branches', repoId, page, branches.length, 20),
289 - [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
290 - ] }
453 + reply_markup: {
454 + inline_keyboard: [
455 + ...branches
456 + .slice(0, 20)
457 + .filter((branch) => /^[a-f0-9]{40}$/i.test(String(branch.sha)))
458 + .map((branch) => [
459 + {
460 + text: `↔️ ${short(branch.name, 42)}`,
461 + callback_data: `compare:${repoId}:${branch.sha}`
462 + }
463 + ]),
464 + ...listPagination('branches', repoId, page, branches.length, 20),
465 + [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
466 + ]
467 + }
468 };
469 }
470
471 async function compareView(github, repoId, sha) {
295 - const [repo, compare] = await Promise.all([github.getRepository(repoId), github.compareWithDefault(repoId, sha)]);
296 - 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');
472 + const [repo, compare] = await Promise.all([
473 + github.getRepository(repoId),
474 + github.compareWithDefault(repoId, sha)
475 + ]);
476 + const files = (compare.files || [])
477 + .slice(0, 12)
478 + .map(
479 + (file) =>
480 + `${stateIcon(file.status)} <code>${escapeHtml(short(file.filename, 90))}</code> · +${file.additions}/-${file.deletions}`
481 + )
482 + .join('\n');
483 return {
484 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>'}`,
299 - reply_markup: { inline_keyboard: [[{ text: '🔙 Branches', callback_data: `branches:${repoId}` }]] }
485 + reply_markup: {
486 + inline_keyboard: [
487 + [{ text: '🔙 Branches', callback_data: `branches:${repoId}` }]
488 + ]
489 + }
490 };
491 }
492
493 async function pullRequestsView(github, repoId, page = 1) {
304 - const [repo, prs] = await Promise.all([github.getRepository(repoId), github.listPullRequests(repoId, { perPage: 10, page })]);
494 + const [repo, prs] = await Promise.all([
495 + github.getRepository(repoId),
496 + github.listPullRequests(repoId, { perPage: 10, page })
497 + ]);
498 const body = prs.length
306 - ? 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')
499 + ? prs
500 + .slice(0, 10)
501 + .map(
502 + (pr) =>
503 + `${pr.merged ? '🟣' : stateIcon(pr.state)} <b>#${pr.number} ${escapeHtml(short(pr.title, 100))}</b>\n ${escapeHtml(pr.author)} · ${escapeHtml(pr.merged ? 'merged' : pr.state)}`
504 + )
505 + .join('\n\n')
506 : '<i>Pull Requestی یافت نشد.</i>';
507 return {
508 text: `🔎 <b>Pull Requests — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
310 - reply_markup: { inline_keyboard: [
311 - ...prs.slice(0, 10).map(pr => [{ text: `#${pr.number} ${short(pr.title, 42)}`, callback_data: `prdetail:${repoId}:${pr.number}` }]),
312 - ...listPagination('prs', repoId, page, prs.length, 10),
313 - [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
314 - ] }
509 + reply_markup: {
510 + inline_keyboard: [
511 + ...prs.slice(0, 10).map((pr) => [
512 + {
513 + text: `#${pr.number} ${short(pr.title, 42)}`,
514 + callback_data: `prdetail:${repoId}:${pr.number}`
515 + }
516 + ]),
517 + ...listPagination('prs', repoId, page, prs.length, 10),
518 + [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
519 + ]
520 + }
521 };
522 }
523
524 async function pullRequestDetailView(github, repoId, prNumber) {
319 - const [repo, pr] = await Promise.all([github.getRepository(repoId), github.getPullRequest(repoId, prNumber)]);
525 + const [repo, pr] = await Promise.all([
526 + github.getRepository(repoId),
527 + github.getPullRequest(repoId, prNumber)
528 + ]);
529 const body = escapeHtml(short(pr.body || '', 600));
530 return {
531 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>'}`,
323 - 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}` }]] }
532 + reply_markup: {
533 + inline_keyboard: [
534 + [
535 + {
536 + text: '🧩 فایل‌ها / Diff',
537 + callback_data: `prfiles:${repoId}:${prNumber}:1`
538 + },
539 + {
540 + text: '✅ Checks',
541 + callback_data: `prchecks:${repoId}:${prNumber}:1`
542 + }
543 + ],
544 + [{ text: '🔙 PRها', callback_data: `prs:${repoId}` }]
545 + ]
546 + }
547 };
548 }
549
550 async function pullRequestFilesView(github, repoId, prNumber, page = 1) {
328 - const files = await github.listPullRequestFiles(repoId, prNumber, { perPage: 8, page });
329 - const body = files.length ? files.slice(0, 8).map(file => {
330 - const patch = escapeHtml(short(file.patch || '', 220));
331 - return `🧩 <code>${escapeHtml(short(file.filename, 100))}</code> · ${escapeHtml(file.status)} · +${file.additions}/-${file.deletions}${patch ? `\n<pre>${patch}</pre>` : ''}`;
332 - }).join('\n\n') : '<i>فایل تغییریافته‌ای یافت نشد.</i>';
551 + const files = await github.listPullRequestFiles(repoId, prNumber, {
552 + perPage: 8,
553 + page
554 + });
555 + const body = files.length
556 + ? files
557 + .slice(0, 8)
558 + .map((file) => {
559 + const patch = escapeHtml(short(file.patch || '', 220));
560 + return `🧩 <code>${escapeHtml(short(file.filename, 100))}</code> · ${escapeHtml(file.status)} · +${file.additions}/-${file.deletions}${patch ? `\n<pre>${patch}</pre>` : ''}`;
561 + })
562 + .join('\n\n')
563 + : '<i>فایل تغییریافته‌ای یافت نشد.</i>';
564 return {
565 text: `🧩 <b>PR #${prNumber} Files / Diff</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
335 - reply_markup: { inline_keyboard: [...pairPagination('prfiles', repoId, prNumber, page, files.length, 8), [{ text: '🔙 PR', callback_data: `prdetail:${repoId}:${prNumber}` }]] }
566 + reply_markup: {
567 + inline_keyboard: [
568 + ...pairPagination('prfiles', repoId, prNumber, page, files.length, 8),
569 + [{ text: '🔙 PR', callback_data: `prdetail:${repoId}:${prNumber}` }]
570 + ]
571 + }
572 };
573 }
574
575 async function pullRequestChecksView(github, repoId, prNumber, page = 1) {
576 const pr = await github.getPullRequest(repoId, prNumber);
341 - const checks = await github.listCommitChecks(repoId, pr.headSha, { perPage: 20, page });
577 + const checks = await github.listCommitChecks(repoId, pr.headSha, {
578 + perPage: 20,
579 + page
580 + });
581 const body = checks.length
343 - ? checks.slice(0, 20).map(check => `${stateIcon(check.conclusion || check.status)} <b>${escapeHtml(check.name)}</b> — ${escapeHtml(check.conclusion || check.status || 'unknown')}`).join('\n')
582 + ? checks
583 + .slice(0, 20)
584 + .map(
585 + (check) =>
586 + `${stateIcon(check.conclusion || check.status)} <b>${escapeHtml(check.name)}</b> — ${escapeHtml(check.conclusion || check.status || 'unknown')}`
587 + )
588 + .join('\n')
589 : '<i>Checkی یافت نشد.</i>';
590 return {
591 text: `✅ <b>PR #${prNumber} Checks</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
347 - reply_markup: { inline_keyboard: [...pairPagination('prchecks', repoId, prNumber, page, checks.length, 20), [{ text: '🔙 PR', callback_data: `prdetail:${repoId}:${prNumber}` }]] }
592 + reply_markup: {
593 + inline_keyboard: [
594 + ...pairPagination(
595 + 'prchecks',
596 + repoId,
597 + prNumber,
598 + page,
599 + checks.length,
600 + 20
601 + ),
602 + [{ text: '🔙 PR', callback_data: `prdetail:${repoId}:${prNumber}` }]
603 + ]
604 + }
605 };
606 }
607
608 async function issuesView(github, repoId, page = 1) {
352 - const [repo, issuePage] = await Promise.all([github.getRepository(repoId), github.listIssuesPage(repoId, { page })]);
609 + const [repo, issuePage] = await Promise.all([
610 + github.getRepository(repoId),
611 + github.listIssuesPage(repoId, { page })
612 + ]);
613 const issues = issuePage.items || [];
614 const body = issues.length
355 - ? 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')
615 + ? issues
616 + .slice(0, 20)
617 + .map(
618 + (issue) =>
619 + `${stateIcon(issue.state)} <b>#${issue.number} ${escapeHtml(short(issue.title, 110))}</b>\n ${escapeHtml(issue.author)} · ${issue.comments} comments`
620 + )
621 + .join('\n\n')
622 : '<i>Issueی یافت نشد.</i>';
623 return {
624 text: `🐛 <b>Issues — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
359 - reply_markup: { inline_keyboard: [
360 - ...issues.slice(0, 20).map(issue => [{ text: `#${issue.number} ${short(issue.title, 42)}`, callback_data: `issuedetail:${repoId}:${issue.number}` }]),
361 - ...explicitPagination('issues', repoId, page, !!issuePage.hasMore),
362 - [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
363 - ] }
625 + reply_markup: {
626 + inline_keyboard: [
627 + ...issues.slice(0, 20).map((issue) => [
628 + {
629 + text: `#${issue.number} ${short(issue.title, 42)}`,
630 + callback_data: `issuedetail:${repoId}:${issue.number}`
631 + }
632 + ]),
633 + ...explicitPagination('issues', repoId, page, !!issuePage.hasMore),
634 + [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
635 + ]
636 + }
637 };
638 }
639
640 async function issueDetailView(github, repoId, issueNumber) {
368 - const [repo, issue] = await Promise.all([github.getRepository(repoId), github.getIssue(repoId, issueNumber)]);
369 - const labels = (issue.labels || []).map(label => `#${escapeHtml(label)}`).join(' ');
370 - const assignees = (issue.assignees || []).map(name => `@${escapeHtml(name)}`).join(' ');
641 + const [repo, issue] = await Promise.all([
642 + github.getRepository(repoId),
643 + github.getIssue(repoId, issueNumber)
644 + ]);
645 + const labels = (issue.labels || [])
646 + .map((label) => `#${escapeHtml(label)}`)
647 + .join(' ');
648 + const assignees = (issue.assignees || [])
649 + .map((name) => `@${escapeHtml(name)}`)
650 + .join(' ');
651 const body = escapeHtml(short(issue.body || '', 1800));
652 return {
653 text: `🐛 <b>Issue #${issue.number} — ${escapeHtml(repo.name)}</b>\n<b>${escapeHtml(issue.title)}</b>\n${stateIcon(issue.state)} ${escapeHtml(issue.state || 'unknown')} · ${escapeHtml(issue.author)} · ${issue.comments ?? 0} comments\nLabels: ${labels || '-'}\nAssignees: ${assignees || '-'}\nUpdated: ${escapeHtml(issue.updatedAt || issue.createdAt || '-')}\n➖➖➖➖➖➖➖➖➖➖\n${body || '<i>بدون توضیح.</i>'}`,
374 - reply_markup: { inline_keyboard: [[{ text: '🔄 بروزرسانی', callback_data: `issuedetail:${repoId}:${issueNumber}` }, { text: '🔙 Issues', callback_data: `issues:${repoId}` }]] }
654 + reply_markup: {
655 + inline_keyboard: [
656 + [
657 + {
658 + text: '🔄 بروزرسانی',
659 + callback_data: `issuedetail:${repoId}:${issueNumber}`
660 + },
661 + { text: '🔙 Issues', callback_data: `issues:${repoId}` }
662 + ]
663 + ]
664 + }
665 };
666 }
667
668 async function releasesView(github, repoId, page = 1) {
379 - const [repo, releases] = await Promise.all([github.getRepository(repoId), github.listReleases(repoId, { perPage: 10, page })]);
669 + const [repo, releases] = await Promise.all([
670 + github.getRepository(repoId),
671 + github.listReleases(repoId, { perPage: 10, page })
672 + ]);
673 const body = releases.length
381 - ? 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')
674 + ? releases
675 + .slice(0, 10)
676 + .map(
677 + (release) =>
678 + `🏷 <b>${escapeHtml(release.tag || release.name)}</b>${release.prerelease ? ' · pre-release' : ''}${release.draft ? ' · draft' : ''}\n ${escapeHtml(short(release.name, 110))}\n ${escapeHtml(release.publishedAt || '-')}`
679 + )
680 + .join('\n\n')
681 : '<i>هیچ Release منتشرشده‌ای برای این مخزن در GitHub وجود ندارد.</i>';
682 return {
683 text: `🏷 <b>Releases — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
385 - reply_markup: { inline_keyboard: [
386 - ...releases.slice(0, 10).map(release => [{ text: `🏷 ${short(release.tag || release.name, 42)}`, callback_data: `releasedetail:${repoId}:${release.id}` }]),
387 - ...listPagination('releases', repoId, page, releases.length, 10),
388 - [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
389 - ] }
684 + reply_markup: {
685 + inline_keyboard: [
686 + ...releases.slice(0, 10).map((release) => [
687 + {
688 + text: `🏷 ${short(release.tag || release.name, 42)}`,
689 + callback_data: `releasedetail:${repoId}:${release.id}`
690 + }
691 + ]),
692 + ...listPagination('releases', repoId, page, releases.length, 10),
693 + [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
694 + ]
695 + }
696 };
697 }
698
699 async function releaseDetailView(github, repoId, releaseId) {
394 - const [repo, release] = await Promise.all([github.getRepository(repoId), github.getRelease(repoId, releaseId)]);
700 + const [repo, release] = await Promise.all([
701 + github.getRepository(repoId),
702 + github.getRelease(repoId, releaseId)
703 + ]);
704 const body = escapeHtml(short(release.body || '', 1800));
396 - const flags = [release.draft ? 'draft' : '', release.prerelease ? 'pre-release' : ''].filter(Boolean).join(' · ');
705 + const flags = [
706 + release.draft ? 'draft' : '',
707 + release.prerelease ? 'pre-release' : ''
708 + ]
709 + .filter(Boolean)
710 + .join(' · ');
711 return {
712 text: `🏷 <b>${escapeHtml(release.name)} — ${escapeHtml(repo.name)}</b>\nTag: <code>${escapeHtml(release.tag || '-')}</code>\nTarget: <code>${escapeHtml(release.target || '-')}</code>\nAuthor: ${escapeHtml(release.author || 'unknown')}\nPublished: ${escapeHtml(release.publishedAt || '-')}${flags ? `\nState: ${escapeHtml(flags)}` : ''}\n➖➖➖➖➖➖➖➖➖➖\n${body || '<i>بدون Release notes.</i>'}`,
399 - reply_markup: { inline_keyboard: [[{ text: '🔄 بروزرسانی', callback_data: `releasedetail:${repoId}:${releaseId}` }, { text: '🔙 Releases', callback_data: `releases:${repoId}` }]] }
713 + reply_markup: {
714 + inline_keyboard: [
715 + [
716 + {
717 + text: '🔄 بروزرسانی',
718 + callback_data: `releasedetail:${repoId}:${releaseId}`
719 + },
720 + { text: '🔙 Releases', callback_data: `releases:${repoId}` }
721 + ]
722 + ]
723 + }
724 };
725 }
726
727 function workflowActionResultView(repoId, runId, action) {
728 const rerun = action === 'rerun_failed';
729 return {
406 - text: rerun ? '✅ درخواست اجرای مجدد jobهای ناموفق برای GitHub ارسال شد.' : '✅ درخواست لغو Workflow برای GitHub ارسال شد.',
407 - reply_markup: { inline_keyboard: [[{ text: '🧪 مشاهده Run', callback_data: `run:${repoId}:${runId}` }, { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }]] }
730 + text: rerun
731 + ? '✅ درخواست اجرای مجدد jobهای ناموفق برای GitHub ارسال شد.'
732 + : '✅ درخواست لغو Workflow برای GitHub ارسال شد.',
733 + reply_markup: {
734 + inline_keyboard: [
735 + [
736 + { text: '🧪 مشاهده Run', callback_data: `run:${repoId}:${runId}` },
737 + { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }
738 + ]
739 + ]
740 + }
741 };
742 }
743
744 function resolveReadCallback(data) {
745 const value = String(data || '');
413 - if (value === 'menu:repos') return { actionId: 'github.repos.list', kind: 'legacy' };
746 + if (value === 'menu:repos')
747 + return { actionId: 'github.repos.list', kind: 'legacy' };
748 const repoId = numericSingle(value, 'repo');
415 - if (repoId !== null) return { actionId: 'github.repo.detail', kind: 'repo', repoId };
749 + if (repoId !== null)
750 + return { actionId: 'github.repo.detail', kind: 'repo', repoId };
751 const commits = numericSingle(value, 'commits');
417 - if (commits !== null) return { actionId: 'github.commits.list', kind: 'commits', repoId: commits };
752 + if (commits !== null)
753 + return {
754 + actionId: 'github.commits.list',
755 + kind: 'commits',
756 + repoId: commits
757 + };
758 const commitdetail = commitDetailRef(value);
419 - if (commitdetail) return { actionId: 'github.commit.detail', kind: 'commitdetail', ...commitdetail };
759 + if (commitdetail)
760 + return {
761 + actionId: 'github.commit.detail',
762 + kind: 'commitdetail',
763 + ...commitdetail
764 + };
765 const legacyStatus = numericSingle(value, 'status');
421 - if (legacyStatus !== null) return { actionId: 'github.workflow.runs.list', kind: 'runs', repoId: legacyStatus, page: 1 };
766 + if (legacyStatus !== null)
767 + return {
768 + actionId: 'github.workflow.runs.list',
769 + kind: 'runs',
770 + repoId: legacyStatus,
771 + page: 1
772 + };
773 const runs = workflowRunsPage(value);
423 - if (runs) return { actionId: 'github.workflow.runs.list', kind: 'runs', ...runs };
774 + if (runs)
775 + return { actionId: 'github.workflow.runs.list', kind: 'runs', ...runs };
776 const run = numericPair(value, 'run');
425 - if (run) return { actionId: 'github.workflow.run.detail', kind: 'run', ...run };
777 + if (run)
778 + return { actionId: 'github.workflow.run.detail', kind: 'run', ...run };
779 const jobs = numericPair(value, 'jobs');
427 - if (jobs) return { actionId: 'github.workflow.jobs.list', kind: 'jobs', ...jobs };
780 + if (jobs)
781 + return { actionId: 'github.workflow.jobs.list', kind: 'jobs', ...jobs };
782 const job = numericPair(value, 'job');
429 - if (job) return { actionId: 'github.workflow.job.detail', kind: 'job', repoId: job.repoId, jobId: job.runId };
783 + if (job)
784 + return {
785 + actionId: 'github.workflow.job.detail',
786 + kind: 'job',
787 + repoId: job.repoId,
788 + jobId: job.runId
789 + };
790 const joblog = numericPair(value, 'joblog');
431 - if (joblog) return { actionId: 'github.workflow.job.log', kind: 'joblog', repoId: joblog.repoId, jobId: joblog.runId };
791 + if (joblog)
792 + return {
793 + actionId: 'github.workflow.job.log',
794 + kind: 'joblog',
795 + repoId: joblog.repoId,
796 + jobId: joblog.runId
797 + };
798 const artifacts = pagedPair(value, 'artifacts');
433 - if (artifacts) return { actionId: 'github.workflow.artifacts.list', kind: 'artifacts', repoId: artifacts.repoId, runId: artifacts.itemId, page: artifacts.page };
799 + if (artifacts)
800 + return {
801 + actionId: 'github.workflow.artifacts.list',
802 + kind: 'artifacts',
803 + repoId: artifacts.repoId,
804 + runId: artifacts.itemId,
805 + page: artifacts.page
806 + };
807 const branches = pagedSingle(value, 'branches');
435 - if (branches) return { actionId: 'github.branches.list', kind: 'branches', ...branches };
808 + if (branches)
809 + return { actionId: 'github.branches.list', kind: 'branches', ...branches };
810 const compare = compareRef(value);
437 - if (compare) return { actionId: 'github.compare.read', kind: 'compare', ...compare };
811 + if (compare)
812 + return { actionId: 'github.compare.read', kind: 'compare', ...compare };
813 const legacyPr = numericSingle(value, 'pr');
439 - if (legacyPr !== null) return { actionId: 'github.pr.advanced.list', kind: 'prs', repoId: legacyPr, page: 1 };
814 + if (legacyPr !== null)
815 + return {
816 + actionId: 'github.pr.advanced.list',
817 + kind: 'prs',
818 + repoId: legacyPr,
819 + page: 1
820 + };
821 const prs = pagedSingle(value, 'prs');
822 if (prs) return { actionId: 'github.pr.advanced.list', kind: 'prs', ...prs };
823 const prdetail = numericPair(value, 'prdetail');
443 - if (prdetail) return { actionId: 'github.pr.detail', kind: 'prdetail', repoId: prdetail.repoId, prNumber: prdetail.runId };
824 + if (prdetail)
825 + return {
826 + actionId: 'github.pr.detail',
827 + kind: 'prdetail',
828 + repoId: prdetail.repoId,
829 + prNumber: prdetail.runId
830 + };
831 const prfiles = numericTriple(value, 'prfiles');
445 - if (prfiles) return { actionId: 'github.pr.files.list', kind: 'prfiles', repoId: prfiles.repoId, prNumber: prfiles.itemId, page: prfiles.page };
832 + if (prfiles)
833 + return {
834 + actionId: 'github.pr.files.list',
835 + kind: 'prfiles',
836 + repoId: prfiles.repoId,
837 + prNumber: prfiles.itemId,
838 + page: prfiles.page
839 + };
840 const prchecks = numericTriple(value, 'prchecks');
447 - if (prchecks) return { actionId: 'github.pr.checks.list', kind: 'prchecks', repoId: prchecks.repoId, prNumber: prchecks.itemId, page: prchecks.page };
841 + if (prchecks)
842 + return {
843 + actionId: 'github.pr.checks.list',
844 + kind: 'prchecks',
845 + repoId: prchecks.repoId,
846 + prNumber: prchecks.itemId,
847 + page: prchecks.page
848 + };
849 const issues = pagedSingle(value, 'issues');
449 - if (issues) return { actionId: 'github.issues.list', kind: 'issues', ...issues };
850 + if (issues)
851 + return { actionId: 'github.issues.list', kind: 'issues', ...issues };
852 const issuedetail = numericPair(value, 'issuedetail');
451 - if (issuedetail) return { actionId: 'github.issue.detail', kind: 'issuedetail', repoId: issuedetail.repoId, issueNumber: issuedetail.runId };
853 + if (issuedetail)
854 + return {
855 + actionId: 'github.issue.detail',
856 + kind: 'issuedetail',
857 + repoId: issuedetail.repoId,
858 + issueNumber: issuedetail.runId
859 + };
860 const releases = pagedSingle(value, 'releases');
453 - if (releases) return { actionId: 'github.releases.list', kind: 'releases', ...releases };
861 + if (releases)
862 + return { actionId: 'github.releases.list', kind: 'releases', ...releases };
863 const releasedetail = numericPair(value, 'releasedetail');
455 - if (releasedetail) return { actionId: 'github.release.detail', kind: 'releasedetail', repoId: releasedetail.repoId, releaseId: releasedetail.runId };
864 + if (releasedetail)
865 + return {
866 + actionId: 'github.release.detail',
867 + kind: 'releasedetail',
868 + repoId: releasedetail.repoId,
869 + releaseId: releasedetail.runId
870 + };
871 for (const [prefix, actionId] of CALLBACK_ACTIONS) {
872 if (value.startsWith(prefix)) return { actionId, kind: 'legacy' };
873 }
@@ -465,9 +880,13 @@ function resolveWriteCallback(data) {
880 return {
881 actionId: 'github.workflow.run.rerun_failed',
882 approval: { input: rerun, label: 'اجرای مجدد jobهای ناموفق' },
468 - execute: async github => {
883 + execute: async (github) => {
884 await github.rerunFailedWorkflowRun(rerun.repoId, rerun.runId);
470 - return workflowActionResultView(rerun.repoId, rerun.runId, 'rerun_failed');
885 + return workflowActionResultView(
886 + rerun.repoId,
887 + rerun.runId,
888 + 'rerun_failed'
889 + );
890 }
891 };
892 }
@@ -476,7 +895,7 @@ function resolveWriteCallback(data) {
895 return {
896 actionId: 'github.workflow.run.cancel',
897 approval: { input: cancel, label: 'لغو Workflow در حال اجرا' },
479 - execute: async github => {
898 + execute: async (github) => {
899 await github.cancelWorkflowRun(cancel.repoId, cancel.runId);
900 return workflowActionResultView(cancel.repoId, cancel.runId, 'cancel');
901 }
@@ -488,14 +907,19 @@ function resolveWriteCallback(data) {
907 export function createGitHubPlugin({ github, menu, workspaces } = {}) {
908 if (!github) throw new Error('GitHub plugin requires github service');
909 if (!menu) throw new Error('GitHub plugin requires menu manager');
491 - const workspaceController = workspaces ? createWorkspaceController({ github, workspaces }) : null;
910 + const workspaceController = workspaces
911 + ? createWorkspaceController({ github, workspaces })
912 + : null;
913
914 return {
915 manifest: githubPluginManifest,
916
917 resolveCommand(command) {
918 if (command !== '/repos') return null;
498 - return { actionId: 'github.repos.list', execute: () => menu.getReposListView() };
919 + return {
920 + actionId: 'github.repos.list',
921 + execute: () => menu.getReposListView()
922 + };
923 },
924
925 resolveMessage(payload, context = {}) {
@@ -504,9 +928,17 @@ export function createGitHubPlugin({ github, menu, workspaces } = {}) {
928
929 resolveCallback(data, context = {}) {
930 const write = resolveWriteCallback(data);
507 - if (write) return { actionId: write.actionId, approval: write.approval, execute: () => write.execute(github) };
508 -
509 - const workspaceRoute = workspaceController?.resolveCallback(data, context);
931 + if (write)
932 + return {
933 + actionId: write.actionId,
934 + approval: write.approval,
935 + execute: () => write.execute(github)
936 + };
937 +
938 + const workspaceRoute = workspaceController?.resolveCallback(
939 + data,
940 + context
941 + );
942 if (workspaceRoute) return workspaceRoute;
943
944 const read = resolveReadCallback(data);
@@ -514,25 +946,64 @@ export function createGitHubPlugin({ github, menu, workspaces } = {}) {
946 return {
947 actionId: read.actionId,
948 execute: async () => {
517 - if (read.kind === 'repo') return addRepoAdvancedButtons(await menu.renderByCallback(data), read.repoId);
518 - if (read.kind === 'commits') return typeof github.listCommits === 'function' ? commitsView(github, read.repoId) : menu.renderByCallback(data);
519 - if (read.kind === 'commitdetail') return commitDetailView(github, read.repoId, read.sha);
520 - if (read.kind === 'runs') return workflowRunsView(github, read.repoId, read.page);
521 - if (read.kind === 'run') return workflowRunView(github, read.repoId, read.runId);
522 - if (read.kind === 'jobs') return workflowJobsView(github, read.repoId, read.runId);
523 - if (read.kind === 'job') return workflowJobView(github, read.repoId, read.jobId);
524 - if (read.kind === 'joblog') return workflowJobLogView(github, read.repoId, read.jobId);
525 - if (read.kind === 'artifacts') return workflowArtifactsView(github, read.repoId, read.runId, read.page);
526 - if (read.kind === 'branches') return branchesView(github, read.repoId, read.page);
527 - if (read.kind === 'compare') return compareView(github, read.repoId, read.sha);
528 - if (read.kind === 'prs') return pullRequestsView(github, read.repoId, read.page);
529 - if (read.kind === 'prdetail') return pullRequestDetailView(github, read.repoId, read.prNumber);
530 - if (read.kind === 'prfiles') return pullRequestFilesView(github, read.repoId, read.prNumber, read.page);
531 - if (read.kind === 'prchecks') return pullRequestChecksView(github, read.repoId, read.prNumber, read.page);
532 - if (read.kind === 'issues') return issuesView(github, read.repoId, read.page);
533 - if (read.kind === 'issuedetail') return issueDetailView(github, read.repoId, read.issueNumber);
534 - if (read.kind === 'releases') return releasesView(github, read.repoId, read.page);
535 - if (read.kind === 'releasedetail') return releaseDetailView(github, read.repoId, read.releaseId);
949 + if (read.kind === 'repo')
950 + return addRepoAdvancedButtons(
951 + await menu.renderByCallback(data),
952 + read.repoId
953 + );
954 + if (read.kind === 'commits')
955 + return typeof github.listCommits === 'function'
956 + ? commitsView(github, read.repoId)
957 + : menu.renderByCallback(data);
958 + if (read.kind === 'commitdetail')
959 + return commitDetailView(github, read.repoId, read.sha);
960 + if (read.kind === 'runs')
961 + return workflowRunsView(github, read.repoId, read.page);
962 + if (read.kind === 'run')
963 + return workflowRunView(github, read.repoId, read.runId);
964 + if (read.kind === 'jobs')
965 + return workflowJobsView(github, read.repoId, read.runId);
966 + if (read.kind === 'job')
967 + return workflowJobView(github, read.repoId, read.jobId);
968 + if (read.kind === 'joblog')
969 + return workflowJobLogView(github, read.repoId, read.jobId);
970 + if (read.kind === 'artifacts')
971 + return workflowArtifactsView(
972 + github,
973 + read.repoId,
974 + read.runId,
975 + read.page
976 + );
977 + if (read.kind === 'branches')
978 + return branchesView(github, read.repoId, read.page);
979 + if (read.kind === 'compare')
980 + return compareView(github, read.repoId, read.sha);
981 + if (read.kind === 'prs')
982 + return pullRequestsView(github, read.repoId, read.page);
983 + if (read.kind === 'prdetail')
984 + return pullRequestDetailView(github, read.repoId, read.prNumber);
985 + if (read.kind === 'prfiles')
986 + return pullRequestFilesView(
987 + github,
988 + read.repoId,
989 + read.prNumber,
990 + read.page
991 + );
992 + if (read.kind === 'prchecks')
993 + return pullRequestChecksView(
994 + github,
995 + read.repoId,
996 + read.prNumber,
997 + read.page
998 + );
999 + if (read.kind === 'issues')
1000 + return issuesView(github, read.repoId, read.page);
1001 + if (read.kind === 'issuedetail')
1002 + return issueDetailView(github, read.repoId, read.issueNumber);
1003 + if (read.kind === 'releases')
1004 + return releasesView(github, read.repoId, read.page);
1005 + if (read.kind === 'releasedetail')
1006 + return releaseDetailView(github, read.repoId, read.releaseId);
1007 return menu.renderByCallback(data);
1008 }
1009 };
src/plugins/github/plugin.js
+111 -29
@@ -1,26 +1,36 @@
1 import { createGitHubPlugin as createLegacyGitHubPlugin } from './plugin-legacy.js';
2
3 const FULL_SHA = /^[a-f0-9]{40}$/i;
4 -const from36 = value => /^[0-9a-z]+$/i.test(String(value || '')) ? Number.parseInt(value, 36) : NaN;
5 -const mergeRef = value => {
6 - const m = String(value || '').match(/^mergepr:([0-9a-z]+):([0-9a-z]+):([a-f0-9]{40})$/i);
4 +const from36 = (value) =>
5 + /^[0-9a-z]+$/i.test(String(value || '')) ? Number.parseInt(value, 36) : NaN;
6 +const mergeRef = (value) => {
7 + const m = String(value || '').match(
8 + /^mergepr:([0-9a-z]+):([0-9a-z]+):([a-f0-9]{40})$/i
9 + );
10 if (!m) return null;
11 const repoId = from36(m[1]);
12 const prNumber = from36(m[2]);
10 - return Number.isSafeInteger(repoId) && Number.isSafeInteger(prNumber) && prNumber > 0
13 + return Number.isSafeInteger(repoId) &&
14 + Number.isSafeInteger(prNumber) &&
15 + prNumber > 0
16 ? { repoId, prNumber, headSha: m[3].toLowerCase() }
17 : null;
18 };
19
20 const cp3Pair = (value, prefix) => {
16 - const m = String(value || '').match(new RegExp('^' + prefix + ':(\\d+):(\\d+)$'));
21 + const m = String(value || '').match(
22 + new RegExp('^' + prefix + ':(\\d+):(\\d+)$')
23 + );
24 return m ? { repoId: Number(m[1]), runId: Number(m[2]) } : null;
25 };
26
27 const appendBeforeBack = (view, row) => {
28 const rows = [...(view?.reply_markup?.inline_keyboard || [])];
29 rows.splice(Math.max(0, rows.length - 1), 0, row);
23 - return { ...view, reply_markup: { ...(view.reply_markup || {}), inline_keyboard: rows } };
30 + return {
31 + ...view,
32 + reply_markup: { ...(view.reply_markup || {}), inline_keyboard: rows }
33 + };
34 };
35
36 export function createGitHubPlugin(options = {}) {
@@ -40,15 +50,28 @@ export function createGitHubPlugin(options = {}) {
50 cancelCallback: `run:${dispatch.repoId}:${dispatch.runId}`
51 },
52 execute: async () => {
43 - const run = await github.getWorkflowRun(dispatch.repoId, dispatch.runId);
53 + const run = await github.getWorkflowRun(
54 + dispatch.repoId,
55 + dispatch.runId
56 + );
57 if (!Number.isSafeInteger(Number(run.workflowId)) || !run.branch) {
58 throw new Error('Workflow dispatch target is unavailable');
59 }
47 - await github.dispatchWorkflow(dispatch.repoId, run.workflowId, { ref: run.branch, inputs: {} });
60 + await github.dispatchWorkflow(dispatch.repoId, run.workflowId, {
61 + ref: run.branch,
62 + inputs: {}
63 + });
64 return {
65 text: '✅ درخواست اجرای Workflow برای GitHub ارسال شد.',
66 reply_markup: {
51 - inline_keyboard: [[{ text: '🧪 مشاهده Run', callback_data: `run:${dispatch.repoId}:${dispatch.runId}` }]]
67 + inline_keyboard: [
68 + [
69 + {
70 + text: '🧪 مشاهده Run',
71 + callback_data: `run:${dispatch.repoId}:${dispatch.runId}`
72 + }
73 + ]
74 + ]
75 }
76 };
77 }
@@ -60,20 +83,36 @@ export function createGitHubPlugin(options = {}) {
83 return {
84 actionId: 'github.workflow.job.rerun',
85 approval: {
63 - input: { repoId: rerunJob.repoId, runId: rerunJob.runId, jobId: rerunJob.runId },
86 + input: {
87 + repoId: rerunJob.repoId,
88 + runId: rerunJob.runId,
89 + jobId: rerunJob.runId
90 + },
91 label: 'اجرای مجدد Job',
92 cancelCallback: `job:${rerunJob.repoId}:${rerunJob.runId}`
93 },
94 execute: async () => {
68 - const job = await github.getWorkflowJob(rerunJob.repoId, rerunJob.runId);
69 - if (!['failure', 'cancelled'].includes(String(job.conclusion || ''))) {
95 + const job = await github.getWorkflowJob(
96 + rerunJob.repoId,
97 + rerunJob.runId
98 + );
99 + if (
100 + !['failure', 'cancelled'].includes(String(job.conclusion || ''))
101 + ) {
102 throw new Error('Workflow job is not eligible for rerun');
103 }
104 await github.rerunJob(rerunJob.repoId, rerunJob.runId);
105 return {
106 text: '✅ درخواست اجرای مجدد Job برای GitHub ارسال شد.',
107 reply_markup: {
76 - inline_keyboard: [[{ text: '👷 مشاهده Job', callback_data: `job:${rerunJob.repoId}:${rerunJob.runId}` }]]
108 + inline_keyboard: [
109 + [
110 + {
111 + text: '👷 مشاهده Job',
112 + callback_data: `job:${rerunJob.repoId}:${rerunJob.runId}`
113 + }
114 + ]
115 + ]
116 }
117 };
118 }
@@ -90,19 +129,39 @@ export function createGitHubPlugin(options = {}) {
129 cancelCallback: `prdetail:${merge.repoId}:${merge.prNumber}`
130 },
131 execute: async () => {
93 - const current = await github.getPullRequest(merge.repoId, merge.prNumber);
94 - if (current.merged || current.state !== 'open' || current.draft) throw new Error('Pull request is not mergeable');
95 - if (!FULL_SHA.test(String(current.headSha || '')) || String(current.headSha).toLowerCase() !== merge.headSha) {
96 - throw new Error('Pull request head changed; fresh approval is required');
132 + const current = await github.getPullRequest(
133 + merge.repoId,
134 + merge.prNumber
135 + );
136 + if (current.merged || current.state !== 'open' || current.draft)
137 + throw new Error('Pull request is not mergeable');
138 + if (
139 + !FULL_SHA.test(String(current.headSha || '')) ||
140 + String(current.headSha).toLowerCase() !== merge.headSha
141 + ) {
142 + throw new Error(
143 + 'Pull request head changed; fresh approval is required'
144 + );
145 }
98 - const result = await github.mergePullRequest(merge.repoId, merge.prNumber, {
99 - expectedHeadSha: merge.headSha,
100 - mergeMethod: 'squash'
101 - });
102 - if (!result?.merged) throw new Error(result?.message || 'GitHub did not merge the pull request');
146 + const result = await github.mergePullRequest(
147 + merge.repoId,
148 + merge.prNumber,
149 + {
150 + expectedHeadSha: merge.headSha,
151 + mergeMethod: 'squash'
152 + }
153 + );
154 + if (!result?.merged)
155 + throw new Error(
156 + result?.message || 'GitHub did not merge the pull request'
157 + );
158 return {
159 text: `✅ <b>PR #${merge.prNumber} با موفقیت Merge شد.</b>`,
105 - reply_markup: { inline_keyboard: [[{ text: '🔙 PRها', callback_data: `prs:${merge.repoId}` }]] }
160 + reply_markup: {
161 + inline_keyboard: [
162 + [{ text: '🔙 PRها', callback_data: `prs:${merge.repoId}` }]
163 + ]
164 + }
165 };
166 }
167 };
@@ -123,10 +182,18 @@ export function createGitHubPlugin(options = {}) {
182 execute: async () => {
183 const view = await route.execute();
184 const pr = await github.getPullRequest(repoId, prNumber);
126 - if (pr?.state !== 'open' || pr?.merged || pr?.draft || !FULL_SHA.test(String(pr?.headSha || ''))) return view;
185 + if (
186 + pr?.state !== 'open' ||
187 + pr?.merged ||
188 + pr?.draft ||
189 + !FULL_SHA.test(String(pr?.headSha || ''))
190 + )
191 + return view;
192 const callback = `mergepr:${repoId.toString(36)}:${prNumber.toString(36)}:${String(pr.headSha).toLowerCase()}`;
193 if (callback.length > 64) return view;
129 - return appendBeforeBack(view, [{ text: '🔀 Merge امن (Squash)', callback_data: callback }]);
194 + return appendBeforeBack(view, [
195 + { text: '🔀 Merge امن (Squash)', callback_data: callback }
196 + ]);
197 }
198 };
199 }
@@ -140,8 +207,15 @@ export function createGitHubPlugin(options = {}) {
207 const view = await route.execute();
208 const run = await github.getWorkflowRun(repoId, runId);
209 const callback = `dispatchwf:${repoId}:${runId}`;
143 - if (!Number.isSafeInteger(Number(run.workflowId)) || !run.branch || callback.length > 64) return view;
144 - return appendBeforeBack(view, [{ text: '▶️ اجرای دوباره Workflow', callback_data: callback }]);
210 + if (
211 + !Number.isSafeInteger(Number(run.workflowId)) ||
212 + !run.branch ||
213 + callback.length > 64
214 + )
215 + return view;
216 + return appendBeforeBack(view, [
217 + { text: '▶️ اجرای دوباره Workflow', callback_data: callback }
218 + ]);
219 }
220 };
221 }
@@ -155,8 +229,16 @@ export function createGitHubPlugin(options = {}) {
229 const view = await route.execute();
230 const job = await github.getWorkflowJob(repoId, jobId);
231 const callback = `rerunjob:${repoId}:${jobId}`;
158 - if (!['failure', 'cancelled'].includes(String(job.conclusion || '')) || callback.length > 64) return view;
159 - return appendBeforeBack(view, [{ text: '🔁 اجرای مجدد Job', callback_data: callback }]);
232 + if (
233 + !['failure', 'cancelled'].includes(
234 + String(job.conclusion || '')
235 + ) ||
236 + callback.length > 64
237 + )
238 + return view;
239 + return appendBeforeBack(view, [
240 + { text: '🔁 اجرای مجدد Job', callback_data: callback }
241 + ]);
242 }
243 };
244 }
src/plugins/github/workspace-commit.js
+233 -10
@@ -1,10 +1,233 @@
1 -const INTENT_ID_PATTERN=/^[A-Za-z0-9_-]{8}$/;const FULL_SHA_PATTERN=/^[a-f0-9]{40}$/i;
2 -function assertOwner(v){const x=String(v??'');if(!x)throw new Error('Workspace owner is required');return x}function assertRepoId(v){const x=Number(v);if(!Number.isSafeInteger(x)||x<1)throw new Error('Workspace repository ID is invalid');return x}function assertIntentId(v){const x=String(v||'');if(!INTENT_ID_PATTERN.test(x))throw new Error('Workspace intent ID is invalid');return x}function assertSha(v,label){const x=String(v||'');if(!FULL_SHA_PATTERN.test(x))throw new Error(`${label} SHA is invalid`);return x}
3 -function committedResult(intent,idempotent=true){return{commitSha:assertSha(intent?.commitSha,'Committed'),branch:String(intent?.branch||intent?.targetBranch||''),idempotent}}
4 -function materialMismatch(intent,ws,repoId,intentId){if(Number(intent?.repoId)!==repoId||Number(ws?.repoId)!==repoId||String(ws?.id||'')!==String(intent?.workspaceId||'')||String(ws?.currentIntentId||'')!==intentId||String(ws?.baseBranch||'')!==String(intent?.baseBranch||'')||String(ws?.baseHeadSha||'')!==String(intent?.baseHeadSha||'')||String(ws?.baseTreeSha||'')!==String(intent?.baseTreeSha||'')||String(ws?.commitMessageDigest||'')!==String(intent?.commitMessageDigest||''))return true;
5 - if(Array.isArray(intent?.files)){if(!Array.isArray(ws?.files)||intent.files.length!==ws.files.length)return true;return intent.files.some((f,i)=>String(f.path)!==String(ws.files[i]?.path)||String(f.sourceBlobSha)!==String(ws.files[i]?.blobSha)||String(f.contentDigest)!==String(ws.files[i]?.draftDigest))}
6 - return String(ws?.path||'')!==String(intent?.path||'')||String(ws?.blobSha||'')!==String(intent?.sourceBlobSha||'')||String(ws?.draftDigest||'')!==String(intent?.contentDigest||'')}
7 -async function markStaleThenThrow(workspaces,ownerId,intentId,reason){try{await workspaces.markStale({ownerId,intentId,reason})}catch{}throw new Error(reason)}
8 -async function reconcileCandidate({github,workspaces,ownerId,repoId,intent,intentId}){const candidate=assertSha(intent.candidateCommitSha,'Candidate commit'),branch=String(intent.targetBranch||''),existing=await github.getGitRef(repoId,branch,{allowMissing:true});if(existing?.sha===candidate){await workspaces.completeCommit({ownerId,intentId,commitSha:candidate,branch});return{commitSha:candidate,branch,idempotent:true}}if(existing)throw new Error('Target branch exists at an unexpected commit');const snapshot=await github.getBranchSnapshot(repoId,intent.baseBranch);if(snapshot.headSha!==intent.baseHeadSha)return markStaleThenThrow(workspaces,ownerId,intentId,'Base branch changed; commit intent is stale');try{await github.createGitBranchRef(repoId,{branch,sha:candidate})}catch(error){const observed=await github.getGitRef(repoId,branch,{allowMissing:true});if(observed?.sha!==candidate)throw new Error(`Unable to reconcile candidate branch after provider error: ${error?.message||'unknown error'}`)}await workspaces.completeCommit({ownerId,intentId,commitSha:candidate,branch});return{commitSha:candidate,branch,idempotent:true}}
9 -export async function commitWorkspaceIntent({github,workspaces,ownerId,repoId,intentId}={}){if(!github)throw new Error('Workspace commit requires GitHub service');if(!workspaces)throw new Error('Workspace commit requires durable workspace store');const owner=assertOwner(ownerId),repositoryId=assertRepoId(repoId),id=assertIntentId(intentId);let intent=await workspaces.getIntent({ownerId:owner,intentId:id});if(!intent)throw new Error('Commit intent not found or expired');if(Number(intent.repoId)!==repositoryId)throw new Error('Commit intent repository mismatch');if(intent.state==='COMMITTED')return committedResult(intent,true);const workspace=await workspaces.getWorkspace({ownerId:owner,workspaceId:intent.workspaceId});if(!workspace||materialMismatch(intent,workspace,repositoryId,id))return markStaleThenThrow(workspaces,owner,id,'Workspace material changed; commit intent is stale');const begun=await workspaces.beginCommit({ownerId:owner,intentId:id});intent=begun?.intent;if(!intent)throw new Error('Commit intent could not begin');if(begun.disposition==='committed'||intent.state==='COMMITTED')return committedResult(intent,true);if(intent.candidateCommitSha)return reconcileCandidate({github,workspaces,ownerId:owner,repoId:repositoryId,intent,intentId:id});const snapshot=await github.getBranchSnapshot(repositoryId,intent.baseBranch);if(snapshot.headSha!==intent.baseHeadSha)return markStaleThenThrow(workspaces,owner,id,'Base branch changed; commit intent is stale');const existing=await github.getGitRef(repositoryId,intent.targetBranch,{allowMissing:true});if(existing)throw new Error('Target branch already exists unexpectedly');
10 - const files=Array.isArray(intent.files)?intent.files.map((f,i)=>({intent:f,workspace:workspace.files[i]})):[{intent:{path:intent.path},workspace:{draftText:workspace.draftText}}];const entries=[];for(const item of files){const blob=await github.createGitBlob(repositoryId,item.workspace.draftText);entries.push({path:item.intent.path,mode:'100644',type:'blob',sha:blob.sha})}const tree=await github.createGitTree(repositoryId,{baseTreeSha:intent.baseTreeSha,entries});const commit=await github.createGitCommit(repositoryId,{message:workspace.commitMessage,treeSha:tree.sha,parentSha:intent.baseHeadSha,timestamp:intent.commitTimestamp});const commitSha=assertSha(commit.sha,'Candidate commit');await workspaces.setCandidateCommit({ownerId:owner,intentId:id,commitSha});let idempotent=false;try{await github.createGitBranchRef(repositoryId,{branch:intent.targetBranch,sha:commitSha})}catch(error){const observed=await github.getGitRef(repositoryId,intent.targetBranch,{allowMissing:true});if(observed?.sha!==commitSha)throw new Error(`Unable to reconcile target branch after provider error: ${error?.message||'unknown error'}`);idempotent=true}await workspaces.completeCommit({ownerId:owner,intentId:id,commitSha,branch:intent.targetBranch});return{commitSha,branch:intent.targetBranch,idempotent}}
1 +const INTENT_ID_PATTERN = /^[A-Za-z0-9_-]{8}$/;
2 +const FULL_SHA_PATTERN = /^[a-f0-9]{40}$/i;
3 +function assertOwner(v) {
4 + const x = String(v ?? '');
5 + if (!x) throw new Error('Workspace owner is required');
6 + return x;
7 +}
8 +function assertRepoId(v) {
9 + const x = Number(v);
10 + if (!Number.isSafeInteger(x) || x < 1)
11 + throw new Error('Workspace repository ID is invalid');
12 + return x;
13 +}
14 +function assertIntentId(v) {
15 + const x = String(v || '');
16 + if (!INTENT_ID_PATTERN.test(x))
17 + throw new Error('Workspace intent ID is invalid');
18 + return x;
19 +}
20 +function assertSha(v, label) {
21 + const x = String(v || '');
22 + if (!FULL_SHA_PATTERN.test(x)) throw new Error(`${label} SHA is invalid`);
23 + return x;
24 +}
25 +function committedResult(intent, idempotent = true) {
26 + return {
27 + commitSha: assertSha(intent?.commitSha, 'Committed'),
28 + branch: String(intent?.branch || intent?.targetBranch || ''),
29 + idempotent
30 + };
31 +}
32 +function materialMismatch(intent, ws, repoId, intentId) {
33 + if (
34 + Number(intent?.repoId) !== repoId ||
35 + Number(ws?.repoId) !== repoId ||
36 + String(ws?.id || '') !== String(intent?.workspaceId || '') ||
37 + String(ws?.currentIntentId || '') !== intentId ||
38 + String(ws?.baseBranch || '') !== String(intent?.baseBranch || '') ||
39 + String(ws?.baseHeadSha || '') !== String(intent?.baseHeadSha || '') ||
40 + String(ws?.baseTreeSha || '') !== String(intent?.baseTreeSha || '') ||
41 + String(ws?.commitMessageDigest || '') !==
42 + String(intent?.commitMessageDigest || '')
43 + )
44 + return true;
45 + if (Array.isArray(intent?.files)) {
46 + if (!Array.isArray(ws?.files) || intent.files.length !== ws.files.length)
47 + return true;
48 + return intent.files.some(
49 + (f, i) =>
50 + String(f.path) !== String(ws.files[i]?.path) ||
51 + String(f.sourceBlobSha) !== String(ws.files[i]?.blobSha) ||
52 + String(f.contentDigest) !== String(ws.files[i]?.draftDigest)
53 + );
54 + }
55 + return (
56 + String(ws?.path || '') !== String(intent?.path || '') ||
57 + String(ws?.blobSha || '') !== String(intent?.sourceBlobSha || '') ||
58 + String(ws?.draftDigest || '') !== String(intent?.contentDigest || '')
59 + );
60 +}
61 +async function markStaleThenThrow(workspaces, ownerId, intentId, reason) {
62 + try {
63 + await workspaces.markStale({ ownerId, intentId, reason });
64 + } catch {}
65 + throw new Error(reason);
66 +}
67 +async function reconcileCandidate({
68 + github,
69 + workspaces,
70 + ownerId,
71 + repoId,
72 + intent,
73 + intentId
74 +}) {
75 + const candidate = assertSha(intent.candidateCommitSha, 'Candidate commit'),
76 + branch = String(intent.targetBranch || ''),
77 + existing = await github.getGitRef(repoId, branch, { allowMissing: true });
78 + if (existing?.sha === candidate) {
79 + await workspaces.completeCommit({
80 + ownerId,
81 + intentId,
82 + commitSha: candidate,
83 + branch
84 + });
85 + return { commitSha: candidate, branch, idempotent: true };
86 + }
87 + if (existing) throw new Error('Target branch exists at an unexpected commit');
88 + const snapshot = await github.getBranchSnapshot(repoId, intent.baseBranch);
89 + if (snapshot.headSha !== intent.baseHeadSha)
90 + return markStaleThenThrow(
91 + workspaces,
92 + ownerId,
93 + intentId,
94 + 'Base branch changed; commit intent is stale'
95 + );
96 + try {
97 + await github.createGitBranchRef(repoId, { branch, sha: candidate });
98 + } catch (error) {
99 + const observed = await github.getGitRef(repoId, branch, {
100 + allowMissing: true
101 + });
102 + if (observed?.sha !== candidate)
103 + throw new Error(
104 + `Unable to reconcile candidate branch after provider error: ${error?.message || 'unknown error'}`
105 + );
106 + }
107 + await workspaces.completeCommit({
108 + ownerId,
109 + intentId,
110 + commitSha: candidate,
111 + branch
112 + });
113 + return { commitSha: candidate, branch, idempotent: true };
114 +}
115 +export async function commitWorkspaceIntent({
116 + github,
117 + workspaces,
118 + ownerId,
119 + repoId,
120 + intentId
121 +} = {}) {
122 + if (!github) throw new Error('Workspace commit requires GitHub service');
123 + if (!workspaces)
124 + throw new Error('Workspace commit requires durable workspace store');
125 + const owner = assertOwner(ownerId),
126 + repositoryId = assertRepoId(repoId),
127 + id = assertIntentId(intentId);
128 + let intent = await workspaces.getIntent({ ownerId: owner, intentId: id });
129 + if (!intent) throw new Error('Commit intent not found or expired');
130 + if (Number(intent.repoId) !== repositoryId)
131 + throw new Error('Commit intent repository mismatch');
132 + if (intent.state === 'COMMITTED') return committedResult(intent, true);
133 + const workspace = await workspaces.getWorkspace({
134 + ownerId: owner,
135 + workspaceId: intent.workspaceId
136 + });
137 + if (!workspace || materialMismatch(intent, workspace, repositoryId, id))
138 + return markStaleThenThrow(
139 + workspaces,
140 + owner,
141 + id,
142 + 'Workspace material changed; commit intent is stale'
143 + );
144 + const begun = await workspaces.beginCommit({ ownerId: owner, intentId: id });
145 + intent = begun?.intent;
146 + if (!intent) throw new Error('Commit intent could not begin');
147 + if (begun.disposition === 'committed' || intent.state === 'COMMITTED')
148 + return committedResult(intent, true);
149 + if (intent.candidateCommitSha)
150 + return reconcileCandidate({
151 + github,
152 + workspaces,
153 + ownerId: owner,
154 + repoId: repositoryId,
155 + intent,
156 + intentId: id
157 + });
158 + const snapshot = await github.getBranchSnapshot(
159 + repositoryId,
160 + intent.baseBranch
161 + );
162 + if (snapshot.headSha !== intent.baseHeadSha)
163 + return markStaleThenThrow(
164 + workspaces,
165 + owner,
166 + id,
167 + 'Base branch changed; commit intent is stale'
168 + );
169 + const existing = await github.getGitRef(repositoryId, intent.targetBranch, {
170 + allowMissing: true
171 + });
172 + if (existing) throw new Error('Target branch already exists unexpectedly');
173 + const files = Array.isArray(intent.files)
174 + ? intent.files.map((f, i) => ({ intent: f, workspace: workspace.files[i] }))
175 + : [
176 + {
177 + intent: { path: intent.path },
178 + workspace: { draftText: workspace.draftText }
179 + }
180 + ];
181 + const entries = [];
182 + for (const item of files) {
183 + const blob = await github.createGitBlob(
184 + repositoryId,
185 + item.workspace.draftText
186 + );
187 + entries.push({
188 + path: item.intent.path,
189 + mode: '100644',
190 + type: 'blob',
191 + sha: blob.sha
192 + });
193 + }
194 + const tree = await github.createGitTree(repositoryId, {
195 + baseTreeSha: intent.baseTreeSha,
196 + entries
197 + });
198 + const commit = await github.createGitCommit(repositoryId, {
199 + message: workspace.commitMessage,
200 + treeSha: tree.sha,
201 + parentSha: intent.baseHeadSha,
202 + timestamp: intent.commitTimestamp
203 + });
204 + const commitSha = assertSha(commit.sha, 'Candidate commit');
205 + await workspaces.setCandidateCommit({
206 + ownerId: owner,
207 + intentId: id,
208 + commitSha
209 + });
210 + let idempotent = false;
211 + try {
212 + await github.createGitBranchRef(repositoryId, {
213 + branch: intent.targetBranch,
214 + sha: commitSha
215 + });
216 + } catch (error) {
217 + const observed = await github.getGitRef(repositoryId, intent.targetBranch, {
218 + allowMissing: true
219 + });
220 + if (observed?.sha !== commitSha)
221 + throw new Error(
222 + `Unable to reconcile target branch after provider error: ${error?.message || 'unknown error'}`
223 + );
224 + idempotent = true;
225 + }
226 + await workspaces.completeCommit({
227 + ownerId: owner,
228 + intentId: id,
229 + commitSha,
230 + branch: intent.targetBranch
231 + });
232 + return { commitSha, branch: intent.targetBranch, idempotent };
233 +}
src/plugins/github/workspace.js
+556 -145
@@ -12,17 +12,18 @@ export { commitWorkspaceIntent } from './workspace-commit.js';
12
13 const HANDLE_10 = '[A-Za-z0-9_-]{10}';
14 const INTENT_8 = '[A-Za-z0-9_-]{8}';
15 -const escapeHtml = value => String(value ?? '')
16 - .replaceAll('&', '&amp;')
17 - .replaceAll('<', '&lt;')
18 - .replaceAll('>', '&gt;')
19 - .replaceAll('"', '&quot;');
15 +const escapeHtml = (value) =>
16 + String(value ?? '')
17 + .replaceAll('&', '&amp;')
18 + .replaceAll('<', '&lt;')
19 + .replaceAll('>', '&gt;')
20 + .replaceAll('"', '&quot;');
21 const short = (value, max = 70) => {
22 const text = String(value ?? '');
23 return text.length > max ? `${text.slice(0, max - 1)}…` : text;
24 };
25
25 -const ownerFrom = context => {
26 +const ownerFrom = (context) => {
27 const ownerId = String(context?.ownerId ?? '');
28 if (!ownerId) throw new Error('Workspace owner is required');
29 return ownerId;
@@ -31,38 +32,108 @@ const ownerFrom = context => {
32 function parseCallback(data) {
33 const value = String(data || '');
34 let match = value.match(/^(?:files):(\d+)$/);
34 - if (match) return { actionId: 'github.files.list', kind: 'root', repoId: Number(match[1]) };
35 + if (match)
36 + return {
37 + actionId: 'github.files.list',
38 + kind: 'root',
39 + repoId: Number(match[1])
40 + };
41 match = value.match(new RegExp(`^wnav:(${HANDLE_10})$`));
36 - if (match) return { actionId: 'github.workspace.navigate', kind: 'navigate', refId: match[1] };
42 + if (match)
43 + return {
44 + actionId: 'github.workspace.navigate',
45 + kind: 'navigate',
46 + refId: match[1]
47 + };
48 match = value.match(new RegExp(`^wedit:(${HANDLE_10})$`));
38 - if (match) return { actionId: 'github.workspace.create', kind: 'edit', refId: match[1] };
49 + if (match)
50 + return {
51 + actionId: 'github.workspace.create',
52 + kind: 'edit',
53 + refId: match[1]
54 + };
55 match = value.match(new RegExp(`^ws:(${HANDLE_10})$`));
40 - if (match) return { actionId: 'github.workspace.view', kind: 'workspace', workspaceId: match[1] };
56 + if (match)
57 + return {
58 + actionId: 'github.workspace.view',
59 + kind: 'workspace',
60 + workspaceId: match[1]
61 + };
62 match = value.match(new RegExp(`^wadd:(${HANDLE_10})$`));
42 - if (match) return { actionId: 'github.workspace.file.add', kind: 'add_file', refId: match[1] };
63 + if (match)
64 + return {
65 + actionId: 'github.workspace.file.add',
66 + kind: 'add_file',
67 + refId: match[1]
68 + };
69 match = value.match(new RegExp(`^wremove:(${HANDLE_10})$`));
44 - if (match) return { actionId: 'github.workspace.file.remove', kind: 'remove_file', refId: match[1] };
70 + if (match)
71 + return {
72 + actionId: 'github.workspace.file.remove',
73 + kind: 'remove_file',
74 + refId: match[1]
75 + };
76 match = value.match(new RegExp(`^wfiles:(${HANDLE_10}):(\\d+)$`));
46 - if (match) return { actionId: 'github.workspace.file.pick', kind: 'pick_file', workspaceId: match[1], repoId: Number(match[2]) };
77 + if (match)
78 + return {
79 + actionId: 'github.workspace.file.pick',
80 + kind: 'pick_file',
81 + workspaceId: match[1],
82 + repoId: Number(match[2])
83 + };
84 match = value.match(new RegExp(`^wfile:(${HANDLE_10})$`));
48 - if (match) return { actionId: 'github.workspace.input.prepare', kind: 'input', workspaceId: match[1], mode: 'draft_file' };
85 + if (match)
86 + return {
87 + actionId: 'github.workspace.input.prepare',
88 + kind: 'input',
89 + workspaceId: match[1],
90 + mode: 'draft_file'
91 + };
92 match = value.match(new RegExp(`^wtext:(${HANDLE_10})$`));
50 - if (match) return { actionId: 'github.workspace.input.prepare', kind: 'input', workspaceId: match[1], mode: 'draft' };
93 + if (match)
94 + return {
95 + actionId: 'github.workspace.input.prepare',
96 + kind: 'input',
97 + workspaceId: match[1],
98 + mode: 'draft'
99 + };
100 match = value.match(new RegExp(`^wmsg:(${HANDLE_10})$`));
52 - if (match) return { actionId: 'github.workspace.input.prepare', kind: 'input', workspaceId: match[1], mode: 'commit_message' };
101 + if (match)
102 + return {
103 + actionId: 'github.workspace.input.prepare',
104 + kind: 'input',
105 + workspaceId: match[1],
106 + mode: 'commit_message'
107 + };
108 match = value.match(new RegExp(`^wdiff:(${HANDLE_10})$`));
54 - if (match) return { actionId: 'github.workspace.diff', kind: 'diff', workspaceId: match[1] };
109 + if (match)
110 + return {
111 + actionId: 'github.workspace.diff',
112 + kind: 'diff',
113 + workspaceId: match[1]
114 + };
115 match = value.match(new RegExp(`^wready:(${HANDLE_10})$`));
56 - if (match) return { actionId: 'github.workspace.ready', kind: 'ready', workspaceId: match[1] };
116 + if (match)
117 + return {
118 + actionId: 'github.workspace.ready',
119 + kind: 'ready',
120 + workspaceId: match[1]
121 + };
122 match = value.match(new RegExp(`^wcancel:(${HANDLE_10})$`));
58 - if (match) return { actionId: 'github.workspace.cancel', kind: 'cancel', workspaceId: match[1] };
123 + if (match)
124 + return {
125 + actionId: 'github.workspace.cancel',
126 + kind: 'cancel',
127 + workspaceId: match[1]
128 + };
129 match = value.match(new RegExp(`^wscommit:(\\d+):(${INTENT_8})$`));
60 - if (match) return {
61 - actionId: 'github.workspace.commit_branch',
62 - kind: 'commit',
63 - repoId: Number(match[1]),
64 - intentId: match[2]
65 - };
130 + if (match)
131 + return {
132 + actionId: 'github.workspace.commit_branch',
133 + kind: 'commit',
134 + repoId: Number(match[1]),
135 + intentId: match[2]
136 + };
137 return null;
138 }
139
@@ -84,8 +155,15 @@ function workspaceButtons(workspace, editorUrl) {
155 const editor = editorUrlFor(workspace, editorUrl);
156 const firstRow = [];
157 if (editor) firstRow.push({ text: '🧑‍💻 Editor', web_app: { url: editor } });
87 - firstRow.push({ text: '📎 بارگذاری فایل', callback_data: `wfile:${workspace.id}` });
88 - if (!editor) firstRow.push({ text: '📝 Paste متن', callback_data: `wtext:${workspace.id}` });
158 + firstRow.push({
159 + text: '📎 بارگذاری فایل',
160 + callback_data: `wfile:${workspace.id}`
161 + });
162 + if (!editor)
163 + firstRow.push({
164 + text: '📝 Paste متن',
165 + callback_data: `wtext:${workspace.id}`
166 + });
167 return [
168 firstRow,
169 [{ text: '✍️ پیام Commit', callback_data: `wmsg:${workspace.id}` }],
@@ -101,11 +179,11 @@ function workspaceButtons(workspace, editorUrl) {
179 }
180
181 function workspaceCommitResultView(repoId, intent, result) {
104 - const rows = [
105 - [{ text: '🧪 CI / Actions', callback_data: `runs:${repoId}` }]
106 - ];
182 + const rows = [[{ text: '🧪 CI / Actions', callback_data: `runs:${repoId}` }]];
183 if (intent?.workspaceId) {
108 - rows.push([{ text: '📝 Workspace', callback_data: `ws:${intent.workspaceId}` }]);
184 + rows.push([
185 + { text: '📝 Workspace', callback_data: `ws:${intent.workspaceId}` }
186 + ]);
187 }
188 rows.push([{ text: '📦 پروژه', callback_data: `repo:${repoId}` }]);
189 return {
@@ -114,9 +192,14 @@ function workspaceCommitResultView(repoId, intent, result) {
192 };
193 }
194
117 -export function createWorkspaceController({ github, workspaces, editorUrl = DEFAULT_CONFIG.workspaceEditorUrl } = {}) {
195 +export function createWorkspaceController({
196 + github,
197 + workspaces,
198 + editorUrl = DEFAULT_CONFIG.workspaceEditorUrl
199 +} = {}) {
200 if (!github) throw new Error('Workspace controller requires GitHub service');
119 - if (!workspaces) throw new Error('Workspace controller requires durable workspace store');
201 + if (!workspaces)
202 + throw new Error('Workspace controller requires durable workspace store');
203
204 const requireWorkspace = async (workspaceId, ownerId) => {
205 const workspace = await workspaces.getWorkspace({ ownerId, workspaceId });
@@ -132,15 +215,27 @@ export function createWorkspaceController({ github, workspaces, editorUrl = DEFA
215 const visible = items.slice(0, 30);
216 const handles = await workspaces.createNavigationRefs({
217 ownerId,
135 - refs: visible.map(item => ({ repoId, path: item.path, type: item.type, sha: item.sha }))
218 + refs: visible.map((item) => ({
219 + repoId,
220 + path: item.path,
221 + type: item.type,
222 + sha: item.sha
223 + }))
224 });
225 const body = visible.length
138 - ? 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')
226 + ? visible
227 + .map(
228 + (item) =>
229 + `${item.type === 'dir' ? '📁' : '📄'} <code>${escapeHtml(short(item.name, 100))}</code>${item.type === 'file' && item.size ? ` (${Number(item.size).toLocaleString()} B)` : ''}`
230 + )
231 + .join('\n')
232 : '<i>این پوشه خالی است.</i>';
140 - const rows = visible.map((item, index) => [{
141 - text: `${item.type === 'dir' ? '📁' : '📄'} ${short(item.name, 46)}`,
142 - callback_data: `wnav:${handles[index].refId}`
143 - }]);
233 + const rows = visible.map((item, index) => [
234 + {
235 + text: `${item.type === 'dir' ? '📁' : '📄'} ${short(item.name, 46)}`,
236 + callback_data: `wnav:${handles[index].refId}`
237 + }
238 + ]);
239 rows.push([
240 { text: '🔄 بروزرسانی', callback_data: `files:${repoId}` },
241 { text: '📦 پروژه', callback_data: `repo:${repoId}` }
@@ -151,25 +246,44 @@ export function createWorkspaceController({ github, workspaces, editorUrl = DEFA
246 };
247 };
248
154 - const getPinnedFile = async ref => {
249 + const getPinnedFile = async (ref) => {
250 const repo = await github.getRepository(ref.repoId);
156 - const snapshot = await github.getBranchSnapshot(ref.repoId, repo.defaultBranch);
157 - const file = await github.getFileAtRef(ref.repoId, ref.path, snapshot.headSha);
251 + const snapshot = await github.getBranchSnapshot(
252 + ref.repoId,
253 + repo.defaultBranch
254 + );
255 + const file = await github.getFileAtRef(
256 + ref.repoId,
257 + ref.path,
258 + snapshot.headSha
259 + );
260 return { repo, snapshot, file };
261 };
262
263 const renderFile = async (refId, ownerId) => {
264 const ref = await workspaces.resolveNavigationRef({ ownerId, refId });
163 - if (!ref || ref.type !== 'file') throw new Error('Workspace file reference is missing or expired');
265 + if (!ref || ref.type !== 'file')
266 + throw new Error('Workspace file reference is missing or expired');
267 const { repo, snapshot, file } = await getPinnedFile(ref);
165 - const policy = validateEditableFile({ path: file.path, text: file.content, byteLength: file.size });
166 - const preview = file.content.length > 2600 ? `${file.content.slice(0, 2600)}\n…` : file.content;
268 + const policy = validateEditableFile({
269 + path: file.path,
270 + text: file.content,
271 + byteLength: file.size
272 + });
273 + const preview =
274 + file.content.length > 2600
275 + ? `${file.content.slice(0, 2600)}\n…`
276 + : file.content;
277 const reason = repo.archived
278 ? 'این مخزن آرشیوشده است و ویرایش فایل در آن غیرفعال است.'
279 : policy.reason;
280 const rows = [];
171 - if (!repo.archived && policy.editable) rows.push([{ text: '✏️ Edit', callback_data: `wedit:${refId}` }]);
172 - rows.push([{ text: '🔙 فایل‌ها', callback_data: `files:${ref.repoId}` }, { text: '📦 پروژه', callback_data: `repo:${ref.repoId}` }]);
281 + if (!repo.archived && policy.editable)
282 + rows.push([{ text: '✏️ Edit', callback_data: `wedit:${refId}` }]);
283 + rows.push([
284 + { text: '🔙 فایل‌ها', callback_data: `files:${ref.repoId}` },
285 + { text: '📦 پروژه', callback_data: `repo:${ref.repoId}` }
286 + ]);
287 return {
288 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>`,
289 reply_markup: { inline_keyboard: rows }
@@ -178,11 +292,17 @@ export function createWorkspaceController({ github, workspaces, editorUrl = DEFA
292
293 const createDraft = async (refId, ownerId) => {
294 const ref = await workspaces.resolveNavigationRef({ ownerId, refId });
181 - if (!ref || ref.type !== 'file') throw new Error('Workspace file reference is missing or expired');
295 + if (!ref || ref.type !== 'file')
296 + throw new Error('Workspace file reference is missing or expired');
297 const { repo, snapshot, file } = await getPinnedFile(ref);
298 if (repo.archived) throw new Error('Archived repository is not editable');
184 - const policy = validateEditableFile({ path: file.path, text: file.content, byteLength: file.size });
185 - if (!policy.editable) throw new Error(policy.reason || 'File is not editable');
299 + const policy = validateEditableFile({
300 + path: file.path,
301 + text: file.content,
302 + byteLength: file.size
303 + });
304 + if (!policy.editable)
305 + throw new Error(policy.reason || 'File is not editable');
306 const originalDigest = await digestText(file.content);
307 const workspace = await workspaces.createWorkspace({
308 ownerId,
@@ -198,57 +318,178 @@ export function createWorkspaceController({ github, workspaces, editorUrl = DEFA
318 });
319 return {
320 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 انجام نشده است.`,
201 - reply_markup: { inline_keyboard: [[{ text: '📝 باز کردن Draft', callback_data: `ws:${workspace.id}` }], [{ text: '🔙 فایل‌ها', callback_data: `files:${ref.repoId}` }]] }
321 + reply_markup: {
322 + inline_keyboard: [
323 + [{ text: '📝 باز کردن Draft', callback_data: `ws:${workspace.id}` }],
324 + [{ text: '🔙 فایل‌ها', callback_data: `files:${ref.repoId}` }]
325 + ]
326 + }
327 };
328 };
329
330 const renderWorkspaceObject = async (workspace, ownerId) => {
206 - const files = Array.isArray(workspace.files) && workspace.files.length ? workspace.files : [{ path: workspace.path, originalText: workspace.originalText, draftText: workspace.draftText }];
207 - const changedCount = files.filter(file => file.draftText !== file.originalText).length;
208 - const refs = await workspaces.createNavigationRefs?.({ ownerId, refs: files.map(file => ({ workspaceId: workspace.id, path: file.path, type: 'workspace-file', repoId: workspace.repoId })) }) || [];
209 - const commitMessage = workspace.commitMessage ? `<code>${escapeHtml(short(workspace.commitMessage, 120))}</code>` : '<i>ثبت نشده</i>';
210 - const list = files.map((file, i) => `${file.draftText !== file.originalText ? '●' : '○'} <code>${escapeHtml(file.path)}</code>${refs[i]?.refId && files.length > 1 ? ` — <i>قابل حذف</i>` : ''}`).join('\n');
331 + const files =
332 + Array.isArray(workspace.files) && workspace.files.length
333 + ? workspace.files
334 + : [
335 + {
336 + path: workspace.path,
337 + originalText: workspace.originalText,
338 + draftText: workspace.draftText
339 + }
340 + ];
341 + const changedCount = files.filter(
342 + (file) => file.draftText !== file.originalText
343 + ).length;
344 + const refs =
345 + (await workspaces.createNavigationRefs?.({
346 + ownerId,
347 + refs: files.map((file) => ({
348 + workspaceId: workspace.id,
349 + path: file.path,
350 + type: 'workspace-file',
351 + repoId: workspace.repoId
352 + }))
353 + })) || [];
354 + const commitMessage = workspace.commitMessage
355 + ? `<code>${escapeHtml(short(workspace.commitMessage, 120))}</code>`
356 + : '<i>ثبت نشده</i>';
357 + const list = files
358 + .map(
359 + (file, i) =>
360 + `${file.draftText !== file.originalText ? '●' : '○'} <code>${escapeHtml(file.path)}</code>${refs[i]?.refId && files.length > 1 ? ` — <i>قابل حذف</i>` : ''}`
361 + )
362 + .join('\n');
363 const buttons = workspaceButtons(workspace, editorUrl);
364 if (editorUrl && files.length > 1) {
213 - const fileEditors = files.map(file => [{ text: 'Edit ' + short(file.path, 34), web_app: { url: editorUrlFor(workspace, editorUrl, file.path) } }]);
365 + const fileEditors = files.map((file) => [
366 + {
367 + text: 'Edit ' + short(file.path, 34),
368 + web_app: { url: editorUrlFor(workspace, editorUrl, file.path) }
369 + }
370 + ]);
371 buttons.unshift(...fileEditors);
372 const genericEditorUrl = editorUrlFor(workspace, editorUrl);
216 - const genericEditorIndex = buttons.findIndex(row => row.some(button => button.web_app?.url === genericEditorUrl));
217 - if (genericEditorIndex >= 0) buttons[genericEditorIndex] = buttons[genericEditorIndex].filter(button => !button.web_app);
373 + const genericEditorIndex = buttons.findIndex((row) =>
374 + row.some((button) => button.web_app?.url === genericEditorUrl)
375 + );
376 + if (genericEditorIndex >= 0)
377 + buttons[genericEditorIndex] = buttons[genericEditorIndex].filter(
378 + (button) => !button.web_app
379 + );
380 }
219 - buttons.unshift([{ text: '➕ افزودن فایل', callback_data: `wfiles:${workspace.id}:${workspace.repoId}` }]);
220 - if (files.length > 1 && refs[1]?.refId) buttons.unshift([{ text: `➖ حذف ${short(files[1].path, 28)}`, callback_data: `wremove:${refs[1].refId}` }]);
221 - return { text: `📝 <b>Repository Workspace</b>\nChange Set: <b>${files.length} فایل</b> · تغییرکرده: <b>${changedCount}</b>\n${list}\nوضعیت: <b>${escapeHtml(workspace.state || 'DRAFT')}</b>\nBase: <code>${escapeHtml(String(workspace.baseHeadSha || '').slice(0, 10))}</code>\nپیام Commit: ${commitMessage}\n\nذخیره فقط Draft محلی را تغییر می‌دهد؛ GitHub فقط بعد از Diff، Ready و Safe Approval تغییر می‌کند.`, reply_markup:{inline_keyboard:buttons} };
381 + buttons.unshift([
382 + {
383 + text: '➕ افزودن فایل',
384 + callback_data: `wfiles:${workspace.id}:${workspace.repoId}`
385 + }
386 + ]);
387 + if (files.length > 1 && refs[1]?.refId)
388 + buttons.unshift([
389 + {
390 + text: `➖ حذف ${short(files[1].path, 28)}`,
391 + callback_data: `wremove:${refs[1].refId}`
392 + }
393 + ]);
394 + return {
395 + text: `📝 <b>Repository Workspace</b>\nChange Set: <b>${files.length} فایل</b> · تغییرکرده: <b>${changedCount}</b>\n${list}\nوضعیت: <b>${escapeHtml(workspace.state || 'DRAFT')}</b>\nBase: <code>${escapeHtml(String(workspace.baseHeadSha || '').slice(0, 10))}</code>\nپیام Commit: ${commitMessage}\n\nذخیره فقط Draft محلی را تغییر می‌دهد؛ GitHub فقط بعد از Diff، Ready و Safe Approval تغییر می‌کند.`,
396 + reply_markup: { inline_keyboard: buttons }
397 + };
398 };
399
224 - const renderWorkspace = async (workspaceId, ownerId) => renderWorkspaceObject(await requireWorkspace(workspaceId, ownerId), ownerId);
400 + const renderWorkspace = async (workspaceId, ownerId) =>
401 + renderWorkspaceObject(
402 + await requireWorkspace(workspaceId, ownerId),
403 + ownerId
404 + );
405
406 const pickWorkspaceFile = async (workspaceId, repoId, ownerId) => {
407 const workspace = await requireWorkspace(workspaceId, ownerId);
228 - if (Number(workspace.repoId) !== Number(repoId)) throw new Error('Workspace repository mismatch');
229 - const existingPaths = new Set((Array.isArray(workspace.files) && workspace.files.length ? workspace.files : [{ path: workspace.path }]).map(file => file.path));
230 - const items = (await github.listFiles(repoId, '', { ref: workspace.baseHeadSha })).filter(item => item.type === 'file' && !existingPaths.has(item.path)).slice(0, 20);
231 - const refs = await workspaces.createNavigationRefs({ ownerId, refs: items.map(item => ({ repoId, workspaceId, path:item.path, type:'workspace-add', sha:item.sha })) });
232 - return { text:`➕ <b>افزودن فایل به Change Set</b>\n${items.length ? 'یک فایل را انتخاب کنید.' : 'فایل قابل افزودن دیگری در این نما نیست.'}`, reply_markup:{inline_keyboard:items.map((item,i)=>[{text:`📄 ${short(item.path,42)}`,callback_data:`wadd:${refs[i].refId}`}]).concat([[{text:'↩️ Workspace',callback_data:`ws:${workspaceId}`} ]])} };
408 + if (Number(workspace.repoId) !== Number(repoId))
409 + throw new Error('Workspace repository mismatch');
410 + const existingPaths = new Set(
411 + (Array.isArray(workspace.files) && workspace.files.length
412 + ? workspace.files
413 + : [{ path: workspace.path }]
414 + ).map((file) => file.path)
415 + );
416 + const items = (
417 + await github.listFiles(repoId, '', { ref: workspace.baseHeadSha })
418 + )
419 + .filter((item) => item.type === 'file' && !existingPaths.has(item.path))
420 + .slice(0, 20);
421 + const refs = await workspaces.createNavigationRefs({
422 + ownerId,
423 + refs: items.map((item) => ({
424 + repoId,
425 + workspaceId,
426 + path: item.path,
427 + type: 'workspace-add',
428 + sha: item.sha
429 + }))
430 + });
431 + return {
432 + text: `➕ <b>افزودن فایل به Change Set</b>\n${items.length ? 'یک فایل را انتخاب کنید.' : 'فایل قابل افزودن دیگری در این نما نیست.'}`,
433 + reply_markup: {
434 + inline_keyboard: items
435 + .map((item, i) => [
436 + {
437 + text: `📄 ${short(item.path, 42)}`,
438 + callback_data: `wadd:${refs[i].refId}`
439 + }
440 + ])
441 + .concat([
442 + [{ text: '↩️ Workspace', callback_data: `ws:${workspaceId}` }]
443 + ])
444 + }
445 + };
446 };
447
448 const addWorkspaceFile = async (refId, ownerId) => {
236 - const ref = await workspaces.resolveNavigationRef({ownerId,refId});
237 - if (!ref || ref.type !== 'workspace-add') throw new Error('Workspace add-file reference is missing or expired');
449 + const ref = await workspaces.resolveNavigationRef({ ownerId, refId });
450 + if (!ref || ref.type !== 'workspace-add')
451 + throw new Error('Workspace add-file reference is missing or expired');
452 const workspace = await requireWorkspace(ref.workspaceId, ownerId);
239 - const file = await github.getFileAtRef(ref.repoId, ref.path, workspace.baseHeadSha);
240 - const policy = validateEditableFile({path:file.path,text:file.content,byteLength:file.size});
241 - if (!policy.editable) throw new Error(policy.reason || 'File is not editable');
453 + const file = await github.getFileAtRef(
454 + ref.repoId,
455 + ref.path,
456 + workspace.baseHeadSha
457 + );
458 + const policy = validateEditableFile({
459 + path: file.path,
460 + text: file.content,
461 + byteLength: file.size
462 + });
463 + if (!policy.editable)
464 + throw new Error(policy.reason || 'File is not editable');
465 const digest = await digestText(file.content);
243 - const updated = await workspaces.upsertWorkspaceFile({ownerId,workspaceId:workspace.id,file:{path:file.path,blobSha:file.sha,originalText:file.content,originalDigest:digest,draftText:file.content,draftDigest:digest}});
244 - const view = await renderWorkspaceObject(updated, ownerId); view.text = `✅ فایل <code>${escapeHtml(file.path)}</code> اضافه شد.\n\n${view.text}`; return view;
466 + const updated = await workspaces.upsertWorkspaceFile({
467 + ownerId,
468 + workspaceId: workspace.id,
469 + file: {
470 + path: file.path,
471 + blobSha: file.sha,
472 + originalText: file.content,
473 + originalDigest: digest,
474 + draftText: file.content,
475 + draftDigest: digest
476 + }
477 + });
478 + const view = await renderWorkspaceObject(updated, ownerId);
479 + view.text = `✅ فایل <code>${escapeHtml(file.path)}</code> اضافه شد.\n\n${view.text}`;
480 + return view;
481 };
482
483 const removeWorkspaceFile = async (refId, ownerId) => {
248 - const ref=await workspaces.resolveNavigationRef({ownerId,refId});
249 - if(!ref || ref.type!=='workspace-file') throw new Error('Workspace file reference is missing or expired');
250 - const updated=await workspaces.removeWorkspaceFile({ownerId,workspaceId:ref.workspaceId,path:ref.path});
251 - return renderWorkspaceObject(updated,ownerId);
484 + const ref = await workspaces.resolveNavigationRef({ ownerId, refId });
485 + if (!ref || ref.type !== 'workspace-file')
486 + throw new Error('Workspace file reference is missing or expired');
487 + const updated = await workspaces.removeWorkspaceFile({
488 + ownerId,
489 + workspaceId: ref.workspaceId,
490 + path: ref.path
491 + });
492 + return renderWorkspaceObject(updated, ownerId);
493 };
494
495 const prepareInput = async (workspaceId, mode, ownerId) => {
@@ -262,40 +503,76 @@ export function createWorkspaceController({ github, workspaces, editorUrl = DEFA
503 : draftMode
504 ? `📝 <b>ورودی متنی قدیمی Workspace</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n\nاین مسیر فقط برای سازگاری پیام‌های قدیمی باقی مانده است. Editor جدید مسیر اصلی است. سقف: 20,000 کاراکتر Unicode و 65,536 بایت UTF-8.`
505 : `✍️ <b>پیام Commit را ارسال کنید</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n\nپیام باید غیرخالی و حداکثر 120 کاراکتر باشد. پیام بعدی فقط یک‌بار مصرف می‌شود.`,
265 - reply_markup: { inline_keyboard: [[{ text: '↩️ بازگشت به Draft', callback_data: `ws:${workspace.id}` }]] }
506 + reply_markup: {
507 + inline_keyboard: [
508 + [{ text: '↩️ بازگشت به Draft', callback_data: `ws:${workspace.id}` }]
509 + ]
510 + }
511 };
512 };
513
514 const applyPendingInput = async ({ pending, text, file }, ownerId) => {
515 const workspaceId = String(pending?.workspaceId || '');
516 const mode = String(pending?.mode || '');
272 - if (!new RegExp(`^${HANDLE_10}$`).test(workspaceId) || !['draft', 'draft_file', 'commit_message'].includes(mode)) {
517 + if (
518 + !new RegExp(`^${HANDLE_10}$`).test(workspaceId) ||
519 + !['draft', 'draft_file', 'commit_message'].includes(mode)
520 + ) {
521 throw new Error('Pending workspace input is invalid');
522 }
523
524 if (mode === 'draft_file' && (!file || typeof file.text !== 'string')) {
277 - throw new Error('A UTF-8 Telegram document is required for this workspace input');
525 + throw new Error(
526 + 'A UTF-8 Telegram document is required for this workspace input'
527 + );
528 }
529
280 - const consumed = await workspaces.consumePendingInput({ ownerId, workspaceId, mode });
281 - if (!consumed) throw new Error('Pending workspace input was already consumed or expired');
530 + const consumed = await workspaces.consumePendingInput({
531 + ownerId,
532 + workspaceId,
533 + mode
534 + });
535 + if (!consumed)
536 + throw new Error(
537 + 'Pending workspace input was already consumed or expired'
538 + );
539 const workspace = await requireWorkspace(workspaceId, ownerId);
540
541 if (mode === 'draft' || mode === 'draft_file') {
542 const inputText = mode === 'draft_file' ? file.text : text;
286 - const inputBytes = mode === 'draft_file' ? Number(file.byteLength) : undefined;
287 - const policy = validateEditableFile({ path: workspace.path, text: inputText, byteLength: inputBytes });
543 + const inputBytes =
544 + mode === 'draft_file' ? Number(file.byteLength) : undefined;
545 + const policy = validateEditableFile({
546 + path: workspace.path,
547 + text: inputText,
548 + byteLength: inputBytes
549 + });
550 if (!policy.editable) {
551 return {
552 text: `⚠️ <b>Draft تغییر نکرد</b>\n${escapeHtml(policy.reason || 'محتوای ارسال‌شده مجاز نیست.')}\n\nاین ورودی مصرف شد؛ برای تلاش دوباره ${mode === 'draft_file' ? '«بارگذاری فایل»' : 'Editor'} را باز کنید.`,
291 - reply_markup: { inline_keyboard: [[{ text: '📝 بازگشت به Draft', callback_data: `ws:${workspace.id}` }]] }
553 + reply_markup: {
554 + inline_keyboard: [
555 + [
556 + {
557 + text: '📝 بازگشت به Draft',
558 + callback_data: `ws:${workspace.id}`
559 + }
560 + ]
561 + ]
562 + }
563 };
564 }
565 const digest = await digestText(policy.text);
295 - const updated = await workspaces.updateDraft({ ownerId, workspaceId, text: policy.text, digest });
296 - const source = mode === 'draft_file'
297 - ? `\nفایل ورودی: <code>${escapeHtml(short(file.name || 'uploaded file', 100))}</code>`
298 - : '';
566 + const updated = await workspaces.updateDraft({
567 + ownerId,
568 + workspaceId,
569 + text: policy.text,
570 + digest
571 + });
572 + const source =
573 + mode === 'draft_file'
574 + ? `\nفایل ورودی: <code>${escapeHtml(short(file.name || 'uploaded file', 100))}</code>`
575 + : '';
576 return {
577 text: `✅ <b>Draft محلی ذخیره شد</b>\nفایل مقصد: <code>${escapeHtml(updated.path)}</code>${source}\nکاراکتر: <b>${policy.charLength}</b> · بایت UTF-8: <b>${policy.byteLength}</b>\n\nهنوز هیچ تغییری در GitHub انجام نشده است.`,
578 reply_markup: { inline_keyboard: workspaceButtons(updated, editorUrl) }
@@ -308,11 +585,25 @@ export function createWorkspaceController({ github, workspaces, editorUrl = DEFA
585 } catch (error) {
586 return {
587 text: `⚠️ <b>پیام Commit ذخیره نشد</b>\n${escapeHtml(error?.message || 'Commit message is invalid')}\n\nاین ورودی مصرف شد؛ برای تلاش دوباره «پیام Commit» را بزنید.`,
311 - reply_markup: { inline_keyboard: [[{ text: '📝 بازگشت به Draft', callback_data: `ws:${workspace.id}` }]] }
588 + reply_markup: {
589 + inline_keyboard: [
590 + [
591 + {
592 + text: '📝 بازگشت به Draft',
593 + callback_data: `ws:${workspace.id}`
594 + }
595 + ]
596 + ]
597 + }
598 };
599 }
600 const digest = await digestText(message);
315 - const updated = await workspaces.setCommitMessage({ ownerId, workspaceId, message, digest });
601 + const updated = await workspaces.setCommitMessage({
602 + ownerId,
603 + workspaceId,
604 + message,
605 + digest
606 + });
607 return {
608 text: `✅ <b>پیام Commit ذخیره شد</b>\n<code>${escapeHtml(message)}</code>\n\nهنوز هیچ تغییری در GitHub انجام نشده است.`,
609 reply_markup: { inline_keyboard: workspaceButtons(updated, editorUrl) }
@@ -321,54 +612,130 @@ export function createWorkspaceController({ github, workspaces, editorUrl = DEFA
612
613 const renderDiff = async (workspaceId, ownerId) => {
614 const workspace = await requireWorkspace(workspaceId, ownerId);
324 - const files = Array.isArray(workspace.files) && workspace.files.length ? workspace.files : [{path:workspace.path,originalText:workspace.originalText,draftText:workspace.draftText}];
325 - const changed = files.filter(file => file.draftText !== file.originalText);
326 - const diffs = changed.map(file => ({file,diff:buildUnifiedDiff({path:file.path,before:file.originalText,after:file.draftText,maxChars:Math.max(500,Math.floor(2200/Math.max(1,changed.length)))})}));
327 - const additions=diffs.reduce((n,x)=>n+x.diff.additions,0), deletions=diffs.reduce((n,x)=>n+x.diff.deletions,0);
328 - const body=diffs.length ? diffs.map(({file,diff})=>`<b>${escapeHtml(file.path)}</b> · +${diff.additions}/-${diff.deletions}${diff.truncated?' ⚠️':''}\n<pre>${escapeHtml(diff.text)}</pre>`).join('\n') : '<i>هیچ تغییر محلی وجود ندارد.</i>';
329 - return { text:`🔍 <b>Diff تجمیعی Change Set</b>\n${changed.length} فایل تغییرکرده · +${additions} / -${deletions}\n➖➖➖➖➖➖➖➖➖➖\n${body}`, reply_markup:{inline_keyboard:[[{text:'📝 Draft',callback_data:`ws:${workspace.id}`},{text:'✅ آماده Commit',callback_data:`wready:${workspace.id}`}]]} };
615 + const files =
616 + Array.isArray(workspace.files) && workspace.files.length
617 + ? workspace.files
618 + : [
619 + {
620 + path: workspace.path,
621 + originalText: workspace.originalText,
622 + draftText: workspace.draftText
623 + }
624 + ];
625 + const changed = files.filter(
626 + (file) => file.draftText !== file.originalText
627 + );
628 + const diffs = changed.map((file) => ({
629 + file,
630 + diff: buildUnifiedDiff({
631 + path: file.path,
632 + before: file.originalText,
633 + after: file.draftText,
634 + maxChars: Math.max(500, Math.floor(2200 / Math.max(1, changed.length)))
635 + })
636 + }));
637 + const additions = diffs.reduce((n, x) => n + x.diff.additions, 0),
638 + deletions = diffs.reduce((n, x) => n + x.diff.deletions, 0);
639 + const body = diffs.length
640 + ? diffs
641 + .map(
642 + ({ file, diff }) =>
643 + `<b>${escapeHtml(file.path)}</b> · +${diff.additions}/-${diff.deletions}${diff.truncated ? ' ⚠️' : ''}\n<pre>${escapeHtml(diff.text)}</pre>`
644 + )
645 + .join('\n')
646 + : '<i>هیچ تغییر محلی وجود ندارد.</i>';
647 + return {
648 + text: `🔍 <b>Diff تجمیعی Change Set</b>\n${changed.length} فایل تغییرکرده · +${additions} / -${deletions}\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
649 + reply_markup: {
650 + inline_keyboard: [
651 + [
652 + { text: '📝 Draft', callback_data: `ws:${workspace.id}` },
653 + { text: '✅ آماده Commit', callback_data: `wready:${workspace.id}` }
654 + ]
655 + ]
656 + }
657 + };
658 };
659
660 const sealReadyIntent = async (workspaceId, ownerId) => {
661 const workspace = await requireWorkspace(workspaceId, ownerId);
334 - const workspaceFiles = Array.isArray(workspace.files) && workspace.files.length ? workspace.files : null;
335 - const changedFiles = workspaceFiles ? workspaceFiles.filter(file => file.draftText !== file.originalText) : null;
336 - if (workspaceFiles ? changedFiles.length === 0 : workspace.draftText === workspace.originalText) throw new Error('No draft change to commit');
662 + const workspaceFiles =
663 + Array.isArray(workspace.files) && workspace.files.length
664 + ? workspace.files
665 + : null;
666 + const changedFiles = workspaceFiles
667 + ? workspaceFiles.filter((file) => file.draftText !== file.originalText)
668 + : null;
669 + if (
670 + workspaceFiles
671 + ? changedFiles.length === 0
672 + : workspace.draftText === workspace.originalText
673 + )
674 + throw new Error('No draft change to commit');
675 const commitMessage = normalizeCommitMessage(workspace.commitMessage);
676 const commitMessageDigest = await digestText(commitMessage);
677 const targetBranch = makeTargetBranch(workspace.id);
678 const createdAt = Number(workspace.createdAt);
341 - const commitTimestamp = new Date(Number.isFinite(createdAt) ? createdAt : 0).toISOString();
342 - const fileDescriptors = workspaceFiles ? await Promise.all(workspaceFiles.map(async file => ({ path:file.path, sourceBlobSha:file.blobSha, contentDigest:file.draftDigest || await digestText(file.draftText) }))) : null;
343 - const material = workspaceFiles ? {
344 - repoId:Number(workspace.repoId), workspaceId:workspace.id, baseBranch:workspace.baseBranch, baseHeadSha:workspace.baseHeadSha, baseTreeSha:workspace.baseTreeSha,
345 - files:fileDescriptors, commitMessageDigest, targetBranch, commitTimestamp
346 - } : {
347 - repoId: Number(workspace.repoId),
348 - workspaceId: workspace.id,
349 - baseBranch: workspace.baseBranch,
350 - baseHeadSha: workspace.baseHeadSha,
351 - baseTreeSha: workspace.baseTreeSha,
352 - path: workspace.path,
353 - sourceBlobSha: workspace.blobSha,
354 - contentDigest: await digestText(workspace.draftText),
355 - commitMessageDigest,
356 - targetBranch,
357 - commitTimestamp
358 - };
679 + const commitTimestamp = new Date(
680 + Number.isFinite(createdAt) ? createdAt : 0
681 + ).toISOString();
682 + const fileDescriptors = workspaceFiles
683 + ? await Promise.all(
684 + workspaceFiles.map(async (file) => ({
685 + path: file.path,
686 + sourceBlobSha: file.blobSha,
687 + contentDigest:
688 + file.draftDigest || (await digestText(file.draftText))
689 + }))
690 + )
691 + : null;
692 + const material = workspaceFiles
693 + ? {
694 + repoId: Number(workspace.repoId),
695 + workspaceId: workspace.id,
696 + baseBranch: workspace.baseBranch,
697 + baseHeadSha: workspace.baseHeadSha,
698 + baseTreeSha: workspace.baseTreeSha,
699 + files: fileDescriptors,
700 + commitMessageDigest,
701 + targetBranch,
702 + commitTimestamp
703 + }
704 + : {
705 + repoId: Number(workspace.repoId),
706 + workspaceId: workspace.id,
707 + baseBranch: workspace.baseBranch,
708 + baseHeadSha: workspace.baseHeadSha,
709 + baseTreeSha: workspace.baseTreeSha,
710 + path: workspace.path,
711 + sourceBlobSha: workspace.blobSha,
712 + contentDigest: await digestText(workspace.draftText),
713 + commitMessageDigest,
714 + targetBranch,
715 + commitTimestamp
716 + };
717 const intentDigest = await digestText(JSON.stringify(material));
718 const intent = await workspaces.sealIntent({
719 ownerId,
720 workspaceId,
721 intent: { ...material, intentDigest }
722 });
365 - if (!intent?.id || !/^[A-Za-z0-9_-]{8}$/.test(intent.id)) throw new Error('Commit intent ID is invalid');
723 + if (!intent?.id || !/^[A-Za-z0-9_-]{8}$/.test(intent.id))
724 + throw new Error('Commit intent ID is invalid');
725 return {
367 - text: `✅ <b>آمادهٔ تأیید Commit</b>\n${workspaceFiles ? `Change Set: <b>${changedFiles.length} فایل تغییرکرده</b>\n${changedFiles.map(file => `• <code>${escapeHtml(file.path)}</code>`).join('\n')}` : `فایل: <code>${escapeHtml(workspace.path)}</code>`}\nBranch: <code>${escapeHtml(targetBranch)}</code>\nBase: <code>${escapeHtml(String(workspace.baseHeadSha).slice(0, 10))}</code>\n\nمرحلهٔ بعد فقط درخواست تأیید امن را می‌سازد؛ تا تأیید معتبر مصرف نشود GitHub WRITE اجرا نمی‌شود.`,
726 + text: `✅ <b>آمادهٔ تأیید Commit</b>\n${workspaceFiles ? `Change Set: <b>${changedFiles.length} فایل تغییرکرده</b>\n${changedFiles.map((file) => `• <code>${escapeHtml(file.path)}</code>`).join('\n')}` : `فایل: <code>${escapeHtml(workspace.path)}</code>`}\nBranch: <code>${escapeHtml(targetBranch)}</code>\nBase: <code>${escapeHtml(String(workspace.baseHeadSha).slice(0, 10))}</code>\n\nمرحلهٔ بعد فقط درخواست تأیید امن را می‌سازد؛ تا تأیید معتبر مصرف نشود GitHub WRITE اجرا نمی‌شود.`,
727 reply_markup: {
728 inline_keyboard: [
370 - [{ text: '✅ تأیید و Commit', callback_data: `wscommit:${workspace.repoId}:${intent.id}` }],
371 - [{ text: '🔍 Diff', callback_data: `wdiff:${workspace.id}` }, { text: '📝 Draft', callback_data: `ws:${workspace.id}` }]
729 + [
730 + {
731 + text: '✅ تأیید و Commit',
732 + callback_data: `wscommit:${workspace.repoId}:${intent.id}`
733 + }
734 + ],
735 + [
736 + { text: '🔍 Diff', callback_data: `wdiff:${workspace.id}` },
737 + { text: '📝 Draft', callback_data: `ws:${workspace.id}` }
738 + ]
739 ]
740 }
741 };
@@ -379,7 +746,11 @@ export function createWorkspaceController({ github, workspaces, editorUrl = DEFA
746 await workspaces.cancelWorkspace({ ownerId, workspaceId });
747 return {
748 text: `🗑 <b>Draft لغو شد</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\nهیچ تغییری در GitHub انجام نشد.`,
382 - reply_markup: { inline_keyboard: [[{ text: '🔙 فایل‌ها', callback_data: `files:${workspace.repoId}` }]] }
749 + reply_markup: {
750 + inline_keyboard: [
751 + [{ text: '🔙 فایل‌ها', callback_data: `files:${workspace.repoId}` }]
752 + ]
753 + }
754 };
755 };
756
@@ -406,8 +777,15 @@ export function createWorkspaceController({ github, workspaces, editorUrl = DEFA
777 repoId: parsed.repoId,
778 intentId: parsed.intentId
779 });
409 - const intent = await workspaces.getIntent({ ownerId, intentId: parsed.intentId });
410 - const view = workspaceCommitResultView(parsed.repoId, intent, result);
780 + const intent = await workspaces.getIntent({
781 + ownerId,
782 + intentId: parsed.intentId
783 + });
784 + const view = workspaceCommitResultView(
785 + parsed.repoId,
786 + intent,
787 + result
788 + );
789 return {
790 ...view,
791 audit: {
@@ -432,18 +810,37 @@ export function createWorkspaceController({ github, workspaces, editorUrl = DEFA
810 actionId: parsed.actionId,
811 execute: async () => {
812 const ownerId = ownerFrom(context);
435 - if (parsed.kind === 'root') return renderDirectory(parsed.repoId, '', ownerId);
436 - if (parsed.kind === 'workspace') return renderWorkspace(parsed.workspaceId, ownerId);
437 - if (parsed.kind === 'pick_file') return pickWorkspaceFile(parsed.workspaceId, parsed.repoId, ownerId);
438 - if (parsed.kind === 'add_file') return addWorkspaceFile(parsed.refId, ownerId);
439 - if (parsed.kind === 'remove_file') return removeWorkspaceFile(parsed.refId, ownerId);
813 + if (parsed.kind === 'root')
814 + return renderDirectory(parsed.repoId, '', ownerId);
815 + if (parsed.kind === 'workspace')
816 + return renderWorkspace(parsed.workspaceId, ownerId);
817 + if (parsed.kind === 'pick_file')
818 + return pickWorkspaceFile(
819 + parsed.workspaceId,
820 + parsed.repoId,
821 + ownerId
822 + );
823 + if (parsed.kind === 'add_file')
824 + return addWorkspaceFile(parsed.refId, ownerId);
825 + if (parsed.kind === 'remove_file')
826 + return removeWorkspaceFile(parsed.refId, ownerId);
827 if (parsed.kind === 'edit') return createDraft(parsed.refId, ownerId);
441 - if (parsed.kind === 'input') return prepareInput(parsed.workspaceId, parsed.mode, ownerId);
442 - if (parsed.kind === 'diff') return renderDiff(parsed.workspaceId, ownerId);
443 - if (parsed.kind === 'ready') return sealReadyIntent(parsed.workspaceId, ownerId);
444 - if (parsed.kind === 'cancel') return cancelDraft(parsed.workspaceId, ownerId);
445 - const ref = await workspaces.resolveNavigationRef({ ownerId, refId: parsed.refId });
446 - if (!ref) throw new Error('Workspace navigation reference is missing or expired');
828 + if (parsed.kind === 'input')
829 + return prepareInput(parsed.workspaceId, parsed.mode, ownerId);
830 + if (parsed.kind === 'diff')
831 + return renderDiff(parsed.workspaceId, ownerId);
832 + if (parsed.kind === 'ready')
833 + return sealReadyIntent(parsed.workspaceId, ownerId);
834 + if (parsed.kind === 'cancel')
835 + return cancelDraft(parsed.workspaceId, ownerId);
836 + const ref = await workspaces.resolveNavigationRef({
837 + ownerId,
838 + refId: parsed.refId
839 + });
840 + if (!ref)
841 + throw new Error(
842 + 'Workspace navigation reference is missing or expired'
843 + );
844 return ref.type === 'dir'
845 ? renderDirectory(ref.repoId, ref.path, ownerId)
846 : renderFile(parsed.refId, ownerId);
@@ -453,15 +850,29 @@ export function createWorkspaceController({ github, workspaces, editorUrl = DEFA
850
851 resolveMessage(payload, context = {}) {
852 const pending = payload?.pending;
456 - if (!pending || !['draft', 'draft_file', 'commit_message'].includes(String(pending.mode || ''))) return null;
457 - if (!new RegExp(`^${HANDLE_10}$`).test(String(pending.workspaceId || ''))) return null;
853 + if (
854 + !pending ||
855 + !['draft', 'draft_file', 'commit_message'].includes(
856 + String(pending.mode || '')
857 + )
858 + )
859 + return null;
860 + if (!new RegExp(`^${HANDLE_10}$`).test(String(pending.workspaceId || '')))
861 + return null;
862 return {
863 actionId: 'github.workspace.input.apply',
460 - execute: async () => applyPendingInput({
461 - pending,
462 - text: String(payload?.text ?? ''),
463 - file: payload?.file && typeof payload.file === 'object' ? payload.file : null
464 - }, ownerFrom(context))
864 + execute: async () =>
865 + applyPendingInput(
866 + {
867 + pending,
868 + text: String(payload?.text ?? ''),
869 + file:
870 + payload?.file && typeof payload.file === 'object'
871 + ? payload.file
872 + : null
873 + },
874 + ownerFrom(context)
875 + )
876 };
877 }
878 };
src/telegram.js
+26 -9
@@ -2,7 +2,8 @@ export class TelegramClient {
2 constructor(botToken, options = {}) {
3 this.botToken = botToken;
4 this.baseUrl = options.baseUrl || `https://api.telegram.org/bot${botToken}`;
5 - this.fileBaseUrl = options.fileBaseUrl || `https://api.telegram.org/file/bot${botToken}`;
5 + this.fileBaseUrl =
6 + options.fileBaseUrl || `https://api.telegram.org/file/bot${botToken}`;
7 this.fetchFn = options.fetch || ((...args) => fetch(...args));
8 }
9
@@ -31,7 +32,9 @@ export class TelegramClient {
32
33 if (!response.ok) {
34 const detail = body?.description ? ` ${body.description}` : '';
34 - throw new Error(`Telegram API ${method} failed: ${response.status}${detail}`);
35 + throw new Error(
36 + `Telegram API ${method} failed: ${response.status}${detail}`
37 + );
38 }
39
40 if (!body || body.ok !== true) {
@@ -47,7 +50,8 @@ export class TelegramClient {
50 const id = String(fileId || '');
51 if (!id) throw new Error('Telegram file_id is required');
52 const limit = Number(maxBytes);
50 - if (!Number.isFinite(limit) || limit <= 0) throw new Error('Telegram file size limit is invalid');
53 + if (!Number.isFinite(limit) || limit <= 0)
54 + throw new Error('Telegram file size limit is invalid');
55
56 const metadata = await this.callApi('getFile', { file_id: id });
57 const filePath = String(metadata?.result?.file_path || '');
@@ -57,17 +61,24 @@ export class TelegramClient {
61 throw new Error(`Telegram file exceeds ${limit} byte size limit`);
62 }
63
60 - const safePath = filePath.split('/').map(segment => encodeURIComponent(segment)).join('/');
64 + const safePath = filePath
65 + .split('/')
66 + .map((segment) => encodeURIComponent(segment))
67 + .join('/');
68 let response;
69 try {
63 - response = await this.fetchFn(`${this.fileBaseUrl}/${safePath}`, { method: 'GET' });
70 + response = await this.fetchFn(`${this.fileBaseUrl}/${safePath}`, {
71 + method: 'GET'
72 + });
73 } catch (err) {
74 throw new Error(`Telegram file download network failure: ${err.message}`);
75 }
67 - if (!response.ok) throw new Error(`Telegram file download failed: ${response.status}`);
76 + if (!response.ok)
77 + throw new Error(`Telegram file download failed: ${response.status}`);
78
79 const bytes = await response.arrayBuffer();
70 - if (bytes.byteLength > limit) throw new Error(`Telegram file exceeds ${limit} byte size limit`);
80 + if (bytes.byteLength > limit)
81 + throw new Error(`Telegram file exceeds ${limit} byte size limit`);
82
83 let text;
84 try {
@@ -88,7 +99,13 @@ export class TelegramClient {
99 return this.callApi('sendMessage', payload);
100 }
101
91 - async editMessageText(chatId, messageId, text, replyMarkup = null, parseMode = 'HTML') {
102 + async editMessageText(
103 + chatId,
104 + messageId,
105 + text,
106 + replyMarkup = null,
107 + parseMode = 'HTML'
108 + ) {
109 const payload = {
110 chat_id: chatId,
111 message_id: messageId,
@@ -105,4 +122,4 @@ export class TelegramClient {
122 if (showAlert) payload.show_alert = showAlert;
123 return this.callApi('answerCallbackQuery', payload);
124 }
108 -}
\ No newline at end of file
125 +}
src/workspace-editor.js
+92 -36
@@ -8,13 +8,14 @@ import { readBoundedJson } from './core/bounded-json.js';
8
9 const WORKSPACE_ID = /^[A-Za-z0-9_-]{10}$/;
10
11 -const jsonResponse = (payload, status = 200) => new Response(JSON.stringify(payload), {
12 - status,
13 - headers: {
14 - 'content-type': 'application/json; charset=utf-8',
15 - 'cache-control': 'no-store'
16 - }
17 -});
11 +const jsonResponse = (payload, status = 200) =>
12 + new Response(JSON.stringify(payload), {
13 + status,
14 + headers: {
15 + 'content-type': 'application/json; charset=utf-8',
16 + 'cache-control': 'no-store'
17 + }
18 + });
19
20 function safeWorkspaceId(value) {
21 const id = String(value || '');
@@ -27,18 +28,18 @@ function statusForError(error) {
28 if (/signature|hash|auth_date|owner|initData|user/i.test(message)) return 403;
29 if (/not found|expired/i.test(message)) return 404;
30 if (/limited|not editable|binary|LFS|sensitive/i.test(message)) return 422;
30 - if (/invalid|required|JSON|body|path|member|Change Set/i.test(message)) return 400;
31 + if (/invalid|required|JSON|body|path|member|Change Set/i.test(message))
32 + return 400;
33 return 500;
34 }
35
34 -export async function handleWorkspaceEditorRequest(request, {
35 - workspaces,
36 - botToken,
37 - ownerId,
38 - now = () => Date.now()
39 -} = {}) {
36 +export async function handleWorkspaceEditorRequest(
37 + request,
38 + { workspaces, botToken, ownerId, now = () => Date.now() } = {}
39 +) {
40 try {
41 - if (!workspaces) throw new Error('Durable workspace store is not configured');
41 + if (!workspaces)
42 + throw new Error('Durable workspace store is not configured');
43 const initData = request.headers.get('x-telegram-init-data') || '';
44 const identity = await validateTelegramWebAppInitData(initData, {
45 botToken,
@@ -51,17 +52,26 @@ export async function handleWorkspaceEditorRequest(request, {
52
53 if (request.method === 'GET') {
54 const workspaceId = safeWorkspaceId(url.searchParams.get('workspaceId'));
54 - const workspace = await workspaces.getWorkspace({ ownerId: owner, workspaceId });
55 + const workspace = await workspaces.getWorkspace({
56 + ownerId: owner,
57 + workspaceId
58 + });
59 if (!workspace) throw new Error('Workspace not found or expired');
56 - const files = Array.isArray(workspace.files) && workspace.files.length ? workspace.files : [{ path: workspace.path, draftText: workspace.draftText }];
57 - const requestedPath = String(url.searchParams.get('path') || workspace.path || files[0].path);
58 - const selected = files.find(file => file.path === requestedPath);
59 - if (!selected) throw new Error('Editor path is not a member of this Change Set');
60 + const files =
61 + Array.isArray(workspace.files) && workspace.files.length
62 + ? workspace.files
63 + : [{ path: workspace.path, draftText: workspace.draftText }];
64 + const requestedPath = String(
65 + url.searchParams.get('path') || workspace.path || files[0].path
66 + );
67 + const selected = files.find((file) => file.path === requestedPath);
68 + if (!selected)
69 + throw new Error('Editor path is not a member of this Change Set');
70 return jsonResponse({
71 workspace: {
72 id: workspace.id,
73 path: selected.path,
64 - files: files.map(file => ({ path: file.path })),
74 + files: files.map((file) => ({ path: file.path })),
75 state: workspace.state || 'DRAFT',
76 baseHeadSha: String(workspace.baseHeadSha || '').slice(0, 10),
77 draftText: String(selected.draftText ?? '')
@@ -73,25 +83,61 @@ export async function handleWorkspaceEditorRequest(request, {
83 if (request.method === 'PUT') {
84 let body;
85 try {
76 - body = await readBoundedJson(request, WORKSPACE_EDITOR_LIMITS.maxBytes + 4096);
86 + body = await readBoundedJson(
87 + request,
88 + WORKSPACE_EDITOR_LIMITS.maxBytes + 4096
89 + );
90 } catch (error) {
78 - if (error instanceof RangeError) return jsonResponse({ ok: false, error: 'Editor request body is too large' }, 413);
79 - if (error instanceof SyntaxError) return jsonResponse({ ok: false, error: 'Editor request body must be valid JSON' }, 400);
91 + if (error instanceof RangeError)
92 + return jsonResponse(
93 + { ok: false, error: 'Editor request body is too large' },
94 + 413
95 + );
96 + if (error instanceof SyntaxError)
97 + return jsonResponse(
98 + { ok: false, error: 'Editor request body must be valid JSON' },
99 + 400
100 + );
101 throw error;
102 }
103 const workspaceId = safeWorkspaceId(body?.workspaceId);
83 - const workspace = await workspaces.getWorkspace({ ownerId: owner, workspaceId });
104 + const workspace = await workspaces.getWorkspace({
105 + ownerId: owner,
106 + workspaceId
107 + });
108 if (!workspace) throw new Error('Workspace not found or expired');
85 - const files = Array.isArray(workspace.files) && workspace.files.length ? workspace.files : [{ path: workspace.path, draftText: workspace.draftText }];
86 - const requestedPath = String(body?.path || workspace.path || files[0].path);
87 - const selected = files.find(file => file.path === requestedPath);
88 - if (!selected) throw new Error('Editor path is not a member of this Change Set');
89 - const policy = validateEditableFile({ path: selected.path, text: body?.text });
90 - if (!policy.editable) return jsonResponse({ ok: false, error: policy.reason }, 422);
109 + const files =
110 + Array.isArray(workspace.files) && workspace.files.length
111 + ? workspace.files
112 + : [{ path: workspace.path, draftText: workspace.draftText }];
113 + const requestedPath = String(
114 + body?.path || workspace.path || files[0].path
115 + );
116 + const selected = files.find((file) => file.path === requestedPath);
117 + if (!selected)
118 + throw new Error('Editor path is not a member of this Change Set');
119 + const policy = validateEditableFile({
120 + path: selected.path,
121 + text: body?.text
122 + });
123 + if (!policy.editable)
124 + return jsonResponse({ ok: false, error: policy.reason }, 422);
125 const digest = await digestText(policy.text);
92 - const updated = typeof workspaces.updateWorkspaceFileDraft === 'function'
93 - ? await workspaces.updateWorkspaceFileDraft({ ownerId: owner, workspaceId, path: selected.path, text: policy.text, digest })
94 - : await workspaces.updateDraft({ ownerId: owner, workspaceId, text: policy.text, digest });
126 + const updated =
127 + typeof workspaces.updateWorkspaceFileDraft === 'function'
128 + ? await workspaces.updateWorkspaceFileDraft({
129 + ownerId: owner,
130 + workspaceId,
131 + path: selected.path,
132 + text: policy.text,
133 + digest
134 + })
135 + : await workspaces.updateDraft({
136 + ownerId: owner,
137 + workspaceId,
138 + text: policy.text,
139 + digest
140 + });
141 return jsonResponse({
142 ok: true,
143 workspace: {
@@ -107,7 +153,16 @@ export async function handleWorkspaceEditorRequest(request, {
153 return jsonResponse({ ok: false, error: 'Method not allowed' }, 405);
154 } catch (error) {
155 const status = statusForError(error);
110 - return jsonResponse({ ok: false, error: status === 500 ? 'Workspace editor request failed' : String(error?.message || 'Workspace editor request failed') }, status);
156 + return jsonResponse(
157 + {
158 + ok: false,
159 + error:
160 + status === 500
161 + ? 'Workspace editor request failed'
162 + : String(error?.message || 'Workspace editor request failed')
163 + },
164 + status
165 + );
166 }
167 }
168
@@ -219,7 +274,8 @@ export function workspaceEditorPageResponse() {
274 'cache-control': 'no-store',
275 'x-content-type-options': 'nosniff',
276 'referrer-policy': 'no-referrer',
222 - 'content-security-policy': "default-src 'none'; script-src 'unsafe-inline' https://telegram.org; style-src 'unsafe-inline'; connect-src 'self'; img-src data:; base-uri 'none'; form-action 'none'"
277 + 'content-security-policy':
278 + "default-src 'none'; script-src 'unsafe-inline' https://telegram.org; style-src 'unsafe-inline'; connect-src 'self'; img-src data:; base-uri 'none'; form-action 'none'"
279 }
280 });
281 }
test/action-policy.test.js
+57 -27
@@ -2,7 +2,11 @@ import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import { ActionPolicy } from '../src/core/action-policy.js';
4
5 -const action = risk => ({ pluginId: 'x', actionId: `x.${risk.toLowerCase()}`, risk });
5 +const action = (risk) => ({
6 + pluginId: 'x',
7 + actionId: `x.${risk.toLowerCase()}`,
8 + risk
9 +});
10
11 test('ActionPolicy allows owner READ without approval', () => {
12 const policy = new ActionPolicy();
@@ -21,45 +25,71 @@ test('ActionPolicy requires approval for WRITE and DESTRUCTIVE actions', () => {
25 allowed: false,
26 requiresApproval: true,
27 risk,
24 - reason: risk === 'WRITE' ? 'owner_write_requires_approval' : 'owner_destructive_requires_approval'
28 + reason:
29 + risk === 'WRITE'
30 + ? 'owner_write_requires_approval'
31 + : 'owner_destructive_requires_approval'
32 });
33 }
34 });
35
36 test('ActionPolicy allows verified owner approval for WRITE and DESTRUCTIVE actions', () => {
37 const policy = new ActionPolicy();
31 - assert.deepEqual(policy.evaluate({ action: action('WRITE'), isOwner: true, approved: true }), {
32 - allowed: true,
33 - requiresApproval: false,
34 - risk: 'WRITE',
35 - reason: 'owner_write_approved'
36 - });
37 - assert.deepEqual(policy.evaluate({ action: action('DESTRUCTIVE'), isOwner: true, approved: true }), {
38 - allowed: true,
39 - requiresApproval: false,
40 - risk: 'DESTRUCTIVE',
41 - reason: 'owner_destructive_approved'
42 - });
38 + assert.deepEqual(
39 + policy.evaluate({ action: action('WRITE'), isOwner: true, approved: true }),
40 + {
41 + allowed: true,
42 + requiresApproval: false,
43 + risk: 'WRITE',
44 + reason: 'owner_write_approved'
45 + }
46 + );
47 + assert.deepEqual(
48 + policy.evaluate({
49 + action: action('DESTRUCTIVE'),
50 + isOwner: true,
51 + approved: true
52 + }),
53 + {
54 + allowed: true,
55 + requiresApproval: false,
56 + risk: 'DESTRUCTIVE',
57 + reason: 'owner_destructive_approved'
58 + }
59 + );
60 });
61
62 test('ActionPolicy denies non-owner even when approved flag is present', () => {
63 const policy = new ActionPolicy();
47 - assert.deepEqual(policy.evaluate({ action: action('WRITE'), isOwner: false, approved: true }), {
48 - allowed: false,
49 - requiresApproval: false,
50 - risk: 'WRITE',
51 - reason: 'owner_required'
52 - });
64 + assert.deepEqual(
65 + policy.evaluate({
66 + action: action('WRITE'),
67 + isOwner: false,
68 + approved: true
69 + }),
70 + {
71 + allowed: false,
72 + requiresApproval: false,
73 + risk: 'WRITE',
74 + reason: 'owner_required'
75 + }
76 + );
77 });
78
79 test('ActionPolicy denies non-owner, missing and unknown actions', () => {
80 const policy = new ActionPolicy();
57 - assert.deepEqual(policy.evaluate({ action: action('READ'), isOwner: false }), {
58 - allowed: false,
59 - requiresApproval: false,
60 - risk: 'READ',
61 - reason: 'owner_required'
62 - });
81 + assert.deepEqual(
82 + policy.evaluate({ action: action('READ'), isOwner: false }),
83 + {
84 + allowed: false,
85 + requiresApproval: false,
86 + risk: 'READ',
87 + reason: 'owner_required'
88 + }
89 + );
90 assert.equal(policy.evaluate({ action: null, isOwner: true }).allowed, false);
64 - assert.equal(policy.evaluate({ action: { risk: 'UNKNOWN' }, isOwner: true }).allowed, false);
91 + assert.equal(
92 + policy.evaluate({ action: { risk: 'UNKNOWN' }, isOwner: true }).allowed,
93 + false
94 + );
95 });
test/approval-expiry-ui.test.js
+45 -14
@@ -14,14 +14,23 @@ function makeReplayNamespace() {
14 const body = await request.json();
15 const expiresAt = Number(body?.expiresAt);
16 if (!Number.isFinite(expiresAt)) {
17 - return Response.json({ accepted: false, reason: 'invalid_expiry' }, { status: 400 });
17 + return Response.json(
18 + { accepted: false, reason: 'invalid_expiry' },
19 + { status: 400 }
20 + );
21 }
22 if (expiresAt < Date.now()) {
20 - return Response.json({ accepted: false, reason: 'expired' }, { status: 410 });
23 + return Response.json(
24 + { accepted: false, reason: 'expired' },
25 + { status: 410 }
26 + );
27 }
28 const key = String(id);
29 if (used.has(key)) {
24 - return Response.json({ accepted: false, reason: 'already_used' }, { status: 409 });
30 + return Response.json(
31 + { accepted: false, reason: 'already_used' },
32 + { status: 409 }
33 + );
34 }
35 used.add(key);
36 return Response.json({ accepted: true });
@@ -70,13 +79,23 @@ function installMock() {
79 const method = value.split('/').at(-1);
80 const body = options.body ? JSON.parse(options.body) : {};
81 telegramCalls.push({ method, body });
73 - return json({ ok: true, result: { message_id: body.message_id || 700, ...body } });
82 + return json({
83 + ok: true,
84 + result: { message_id: body.message_id || 700, ...body }
85 + });
86 }
87 if (value === 'https://api.github.com/repositories/1001') {
88 githubCalls.push({ url: value, method: options.method || 'GET' });
77 - return json({ id: 1001, name: 'demo', full_name: 'davoodmehraban89/demo' });
89 + return json({
90 + id: 1001,
91 + name: 'demo',
92 + full_name: 'davoodmehraban89/demo'
93 + });
94 }
79 - if (value === 'https://api.github.com/repos/davoodmehraban89/demo/actions/runs/55/rerun-failed-jobs') {
95 + if (
96 + value ===
97 + 'https://api.github.com/repos/davoodmehraban89/demo/actions/runs/55/rerun-failed-jobs'
98 + ) {
99 githubCalls.push({ url: value, method: options.method || 'GET' });
100 return new Response('', { status: 201 });
101 }
@@ -117,15 +136,18 @@ test('expired approval gives visible Telegram feedback and no GitHub write', asy
136 assert.equal(issued.approvalRequired, true);
137
138 const approvalEdit = mock.telegramCalls
120 - .filter(call => call.method === 'editMessageText')
139 + .filter((call) => call.method === 'editMessageText')
140 .at(-1);
141 const approveButton = approvalEdit.body.reply_markup.inline_keyboard
142 .flat()
124 - .find(button => String(button.callback_data || '').startsWith('approve:'));
143 + .find((button) =>
144 + String(button.callback_data || '').startsWith('approve:')
145 + );
146 assert.ok(approveButton);
147
127 - const editCountBeforeExpiryClick = mock.telegramCalls
128 - .filter(call => call.method === 'editMessageText').length;
148 + const editCountBeforeExpiryClick = mock.telegramCalls.filter(
149 + (call) => call.method === 'editMessageText'
150 + ).length;
151
152 now += 121_000;
153 const expired = await sendUpdate({
@@ -142,16 +164,25 @@ test('expired approval gives visible Telegram feedback and no GitHub write', asy
164 });
165
166 assert.equal(expired.ok, false);
145 - assert.equal(mock.githubCalls.filter(call => call.method === 'POST').length, 0);
167 + assert.equal(
168 + mock.githubCalls.filter((call) => call.method === 'POST').length,
169 + 0
170 + );
171
147 - const edits = mock.telegramCalls.filter(call => call.method === 'editMessageText');
148 - assert.equal(edits.length, editCountBeforeExpiryClick + 1, 'expired approval must visibly update the Telegram message');
172 + const edits = mock.telegramCalls.filter(
173 + (call) => call.method === 'editMessageText'
174 + );
175 + assert.equal(
176 + edits.length,
177 + editCountBeforeExpiryClick + 1,
178 + 'expired approval must visibly update the Telegram message'
179 + );
180 const feedback = edits.at(-1);
181 assert.match(feedback.body.text, /منقضی|اعتبار|اجرا نشد/);
182 assert.ok(
183 feedback.body.reply_markup.inline_keyboard
184 .flat()
154 - .some(button => button.callback_data === 'run:1001:55'),
185 + .some((button) => button.callback_data === 'run:1001:55'),
186 'feedback must provide a safe route back to the workflow run'
187 );
188 } finally {
test/approval-flow.test.js
+85 -30
@@ -14,14 +14,23 @@ function makeReplayNamespace() {
14 const body = await request.json();
15 const expiresAt = Number(body?.expiresAt);
16 if (!Number.isFinite(expiresAt)) {
17 - return Response.json({ accepted: false, reason: 'invalid_expiry' }, { status: 400 });
17 + return Response.json(
18 + { accepted: false, reason: 'invalid_expiry' },
19 + { status: 400 }
20 + );
21 }
22 if (expiresAt < Date.now()) {
20 - return Response.json({ accepted: false, reason: 'expired' }, { status: 410 });
23 + return Response.json(
24 + { accepted: false, reason: 'expired' },
25 + { status: 410 }
26 + );
27 }
28 const key = String(id);
29 if (used.has(key)) {
24 - return Response.json({ accepted: false, reason: 'already_used' }, { status: 409 });
30 + return Response.json(
31 + { accepted: false, reason: 'already_used' },
32 + { status: 409 }
33 + );
34 }
35 used.add(key);
36 return Response.json({ accepted: true });
@@ -71,7 +80,10 @@ function installMock() {
80 const method = value.split('/').at(-1);
81 const body = options.body ? JSON.parse(options.body) : {};
82 telegramCalls.push({ method, body });
74 - return json({ ok: true, result: { message_id: body.message_id || 700, ...body } });
83 + return json({
84 + ok: true,
85 + result: { message_id: body.message_id || 700, ...body }
86 + });
87 }
88
89 if (value === 'https://api.github.com/repositories/1001') {
@@ -87,7 +99,10 @@ function installMock() {
99 });
100 }
101
90 - if (value === 'https://api.github.com/repos/davoodmehraban89/demo/actions/runs/55/rerun-failed-jobs') {
102 + if (
103 + value ===
104 + 'https://api.github.com/repos/davoodmehraban89/demo/actions/runs/55/rerun-failed-jobs'
105 + ) {
106 githubCalls.push({ url: value, method: options.method || 'GET' });
107 return new Response('', { status: 201 });
108 }
@@ -125,17 +140,27 @@ test('WRITE callback renders owner-bound approval and performs no GitHub write b
140
141 assert.equal(result.ok, true);
142 assert.equal(result.approvalRequired, true);
128 - assert.equal(mock.githubCalls.length, 0, 'GitHub write must not execute before approval');
143 + assert.equal(
144 + mock.githubCalls.length,
145 + 0,
146 + 'GitHub write must not execute before approval'
147 + );
148
130 - const edit = mock.telegramCalls.find(call => call.method === 'editMessageText');
149 + const edit = mock.telegramCalls.find(
150 + (call) => call.method === 'editMessageText'
151 + );
152 assert.ok(edit, 'approval request must edit the existing Telegram message');
153 assert.match(edit.body.text, /تأیید|اجرا/);
154
155 const approveButton = edit.body.reply_markup.inline_keyboard
156 .flat()
136 - .find(button => String(button.callback_data || '').startsWith('approve:'));
157 + .find((button) =>
158 + String(button.callback_data || '').startsWith('approve:')
159 + );
160 assert.ok(approveButton, 'approval button must be present');
138 - assert.ok(new TextEncoder().encode(approveButton.callback_data).length <= 64);
161 + assert.ok(
162 + new TextEncoder().encode(approveButton.callback_data).length <= 64
163 + );
164 } finally {
165 mock.restore();
166 }
@@ -156,11 +181,13 @@ test('approve callback executes exactly once and replay is rejected', async () =
181 });
182
183 const approvalEdit = mock.telegramCalls
159 - .filter(call => call.method === 'editMessageText')
184 + .filter((call) => call.method === 'editMessageText')
185 .at(-1);
186 const approveButton = approvalEdit.body.reply_markup.inline_keyboard
187 .flat()
163 - .find(button => String(button.callback_data || '').startsWith('approve:'));
188 + .find((button) =>
189 + String(button.callback_data || '').startsWith('approve:')
190 + );
191 assert.ok(approveButton);
192
193 const first = await sendUpdate({
@@ -173,7 +200,9 @@ test('approve callback executes exactly once and replay is rejected', async () =
200 });
201 assert.equal(first.ok, true);
202
176 - const writesAfterFirst = mock.githubCalls.filter(call => call.method === 'POST');
203 + const writesAfterFirst = mock.githubCalls.filter(
204 + (call) => call.method === 'POST'
205 + );
206 assert.equal(writesAfterFirst.length, 1);
207 assert.match(writesAfterFirst[0].url, /rerun-failed-jobs$/);
208
@@ -188,8 +217,14 @@ test('approve callback executes exactly once and replay is rejected', async () =
217 assert.equal(replay.ok, false);
218 assert.match(String(replay.error || ''), /used|replay|approval/i);
219
191 - const writesAfterReplay = mock.githubCalls.filter(call => call.method === 'POST');
192 - assert.equal(writesAfterReplay.length, 1, 'replay must not perform a second GitHub write');
220 + const writesAfterReplay = mock.githubCalls.filter(
221 + (call) => call.method === 'POST'
222 + );
223 + assert.equal(
224 + writesAfterReplay.length,
225 + 1,
226 + 'replay must not perform a second GitHub write'
227 + );
228 } finally {
229 mock.restore();
230 }
@@ -198,23 +233,34 @@ test('approve callback executes exactly once and replay is rejected', async () =
233 test('WRITE approval falls back to the configured Telegram webhook secret when no dedicated signing secret exists', async () => {
234 const mock = installMock();
235 try {
201 - const result = await sendUpdate({
202 - callback_query: {
203 - id: 'fallback-signing-secret',
204 - from: { id: 123 },
205 - data: 'rerun:1001:55',
206 - message: { message_id: 702, chat: { id: 123 } }
236 + const result = await sendUpdate(
237 + {
238 + callback_query: {
239 + id: 'fallback-signing-secret',
240 + from: { id: 123 },
241 + data: 'rerun:1001:55',
242 + message: { message_id: 702, chat: { id: 123 } }
243 + }
244 + },
245 + {
246 + ...env,
247 + APPROVAL_SIGNING_SECRET: ''
248 }
208 - }, {
209 - ...env,
210 - APPROVAL_SIGNING_SECRET: ''
211 - });
249 + );
250
251 assert.equal(result.ok, true);
252 assert.equal(result.approvalRequired, true);
253 assert.equal(mock.githubCalls.length, 0);
216 - const edit = mock.telegramCalls.filter(call => call.method === 'editMessageText').at(-1);
217 - assert.ok(edit.body.reply_markup.inline_keyboard.flat().some(button => String(button.callback_data || '').startsWith('approve:')));
254 + const edit = mock.telegramCalls
255 + .filter((call) => call.method === 'editMessageText')
256 + .at(-1);
257 + assert.ok(
258 + edit.body.reply_markup.inline_keyboard
259 + .flat()
260 + .some((button) =>
261 + String(button.callback_data || '').startsWith('approve:')
262 + )
263 + );
264 } finally {
265 mock.restore();
266 }
@@ -238,11 +284,13 @@ test('approval lifecycle is audited without logging signed callback tokens', asy
284 });
285
286 const approvalEdit = mock.telegramCalls
241 - .filter(call => call.method === 'editMessageText')
287 + .filter((call) => call.method === 'editMessageText')
288 .at(-1);
289 const approveButton = approvalEdit.body.reply_markup.inline_keyboard
290 .flat()
245 - .find(button => String(button.callback_data || '').startsWith('approve:'));
291 + .find((button) =>
292 + String(button.callback_data || '').startsWith('approve:')
293 + );
294 assert.ok(approveButton);
295
296 await sendUpdate({
@@ -263,11 +311,18 @@ test('approval lifecycle is audited without logging signed callback tokens', asy
311 }
312 });
313
266 - const auditText = logs.filter(line => line.startsWith('nexa_audit ')).join('\n');
314 + const auditText = logs
315 + .filter((line) => line.startsWith('nexa_audit '))
316 + .join('\n');
317 assert.match(auditText, /"event":"approval_issued"/);
318 assert.match(auditText, /"event":"approval_verified"/);
319 assert.match(auditText, /"event":"approval_rejected"/);
270 - assert.doesNotMatch(auditText, new RegExp(approveButton.callback_data.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));
320 + assert.doesNotMatch(
321 + auditText,
322 + new RegExp(
323 + approveButton.callback_data.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
324 + )
325 + );
326 } finally {
327 console.log = originalLog;
328 mock.restore();
test/approval-provider-error-ui.test.js
+56 -15
@@ -5,13 +5,19 @@ import worker from '../src/index.js';
5 function makeReplayNamespace() {
6 const used = new Set();
7 return {
8 - idFromName(name) { return String(name); },
8 + idFromName(name) {
9 + return String(name);
10 + },
11 get(id) {
12 return {
13 async fetch(request) {
14 const body = await request.json();
15 const key = String(id);
14 - if (used.has(key)) return Response.json({ accepted: false, reason: 'already_used' }, { status: 409 });
16 + if (used.has(key))
17 + return Response.json(
18 + { accepted: false, reason: 'already_used' },
19 + { status: 409 }
20 + );
21 used.add(key);
22 return Response.json({ accepted: true, expiresAt: body.expiresAt });
23 }
@@ -59,20 +65,39 @@ function installMock() {
65 const method = value.split('/').at(-1);
66 const body = options.body ? JSON.parse(options.body) : {};
67 telegramCalls.push({ method, body });
62 - return json({ ok: true, result: { message_id: body.message_id || 950, ...body } });
68 + return json({
69 + ok: true,
70 + result: { message_id: body.message_id || 950, ...body }
71 + });
72 }
73 if (value === 'https://api.github.com/repositories/1001') {
74 githubCalls.push({ url: value, method: options.method || 'GET' });
66 - return json({ id: 1001, name: 'demo', full_name: 'davoodmehraban89/demo' });
75 + return json({
76 + id: 1001,
77 + name: 'demo',
78 + full_name: 'davoodmehraban89/demo'
79 + });
80 }
68 - if (value === 'https://api.github.com/repos/davoodmehraban89/demo/actions/runs/55/rerun-failed-jobs') {
81 + if (
82 + value ===
83 + 'https://api.github.com/repos/davoodmehraban89/demo/actions/runs/55/rerun-failed-jobs'
84 + ) {
85 githubCalls.push({ url: value, method: options.method || 'GET' });
70 - return json({ message: 'Resource not accessible by personal access token' }, 403);
86 + return json(
87 + { message: 'Resource not accessible by personal access token' },
88 + 403
89 + );
90 }
91 throw new Error(`Unexpected URL: ${value}`);
92 };
93
75 - return { telegramCalls, githubCalls, restore() { globalThis.fetch = originalFetch; } };
94 + return {
95 + telegramCalls,
96 + githubCalls,
97 + restore() {
98 + globalThis.fetch = originalFetch;
99 + }
100 + };
101 }
102
103 async function sendUpdate(update) {
@@ -95,10 +120,14 @@ test('approved GitHub WRITE provider failure visibly updates Telegram and does n
120 });
121 assert.equal(issued.approvalRequired, true);
122
98 - const approvalEdit = mock.telegramCalls.filter(call => call.method === 'editMessageText').at(-1);
123 + const approvalEdit = mock.telegramCalls
124 + .filter((call) => call.method === 'editMessageText')
125 + .at(-1);
126 const approveButton = approvalEdit.body.reply_markup.inline_keyboard
127 .flat()
101 - .find(button => String(button.callback_data || '').startsWith('approve:'));
128 + .find((button) =>
129 + String(button.callback_data || '').startsWith('approve:')
130 + );
131 assert.ok(approveButton);
132
133 const result = await sendUpdate({
@@ -115,19 +144,31 @@ test('approved GitHub WRITE provider failure visibly updates Telegram and does n
144 });
145
146 assert.equal(result.ok, false);
118 - const posts = mock.githubCalls.filter(call => call.method === 'POST');
119 - assert.equal(posts.length, 1, 'approved provider write should be attempted exactly once');
147 + const posts = mock.githubCalls.filter((call) => call.method === 'POST');
148 + assert.equal(
149 + posts.length,
150 + 1,
151 + 'approved provider write should be attempted exactly once'
152 + );
153
121 - const edits = mock.telegramCalls.filter(call => call.method === 'editMessageText');
122 - assert.equal(edits.length, 2, 'provider failure must visibly replace the approval message');
154 + const edits = mock.telegramCalls.filter(
155 + (call) => call.method === 'editMessageText'
156 + );
157 + assert.equal(
158 + edits.length,
159 + 2,
160 + 'provider failure must visibly replace the approval message'
161 + );
162 const feedback = edits.at(-1);
163 assert.match(feedback.body.text, /اجرا نشد|GitHub|403|دسترسی/);
164 assert.doesNotMatch(feedback.body.text, /عملیات با موفقیت|success/i);
165 assert.ok(
127 - feedback.body.reply_markup.inline_keyboard.flat().some(button => button.callback_data === 'run:1001:55'),
166 + feedback.body.reply_markup.inline_keyboard
167 + .flat()
168 + .some((button) => button.callback_data === 'run:1001:55'),
169 'provider failure must provide a safe route back to the run'
170 );
171 } finally {
172 mock.restore();
173 }
133 -});
\ No newline at end of file
174 +});
test/approval.test.js
+62 -22
@@ -1,7 +1,9 @@
1 import test from 'node:test';
2 import assert from 'node:assert/strict';
3
4 -const approvalModule = await import('../src/core/approval.js').catch(() => null);
4 +const approvalModule = await import('../src/core/approval.js').catch(
5 + () => null
6 +);
7
8 function makeReplayStore() {
9 const used = new Set();
@@ -21,7 +23,10 @@ test('ApprovalService module exists', () => {
23 });
24
25 test('ApprovalService issues and verifies a signed owner-bound token', async () => {
24 - assert.ok(approvalModule?.ApprovalService, 'ApprovalService module must exist');
26 + assert.ok(
27 + approvalModule?.ApprovalService,
28 + 'ApprovalService module must exist'
29 + );
30 let now = 1_700_000_000_000;
31 const service = new approvalModule.ApprovalService({
32 secret: 'test-signing-secret',
@@ -37,7 +42,10 @@ test('ApprovalService issues and verifies a signed owner-bound token', async ()
42 input: { repoId: 7, runId: 9 }
43 });
44
40 - assert.ok(`approve:${token}`.length <= 64, 'approval callback must fit Telegram callback_data');
45 + assert.ok(
46 + `approve:${token}`.length <= 64,
47 + 'approval callback must fit Telegram callback_data'
48 + );
49
50 const payload = await service.verify(token, {
51 ownerId: '42',
@@ -58,7 +66,10 @@ test('ApprovalService issues and verifies a signed owner-bound token', async ()
66 });
67
68 test('ApprovalService rejects tampered, expired and mismatched tokens', async () => {
61 - assert.ok(approvalModule?.ApprovalService, 'ApprovalService module must exist');
69 + assert.ok(
70 + approvalModule?.ApprovalService,
71 + 'ApprovalService module must exist'
72 + );
73 let now = 1_700_000_000_000;
74 const service = new approvalModule.ApprovalService({
75 secret: 'test-signing-secret',
@@ -73,18 +84,34 @@ test('ApprovalService rejects tampered, expired and mismatched tokens', async ()
84 input: { repoId: 7, runId: 9 }
85 });
86
76 - await assert.rejects(() => service.verify(`${token}x`, { ownerId: '42' }), /invalid approval/i);
77 - await assert.rejects(() => service.verify(token, { ownerId: '99' }), /owner/i);
78 - await assert.rejects(() => service.verify(token, {
79 - ownerId: '42',
80 - actionId: 'github.workflow.run.rerun_failed'
81 - }), /action/i);
87 + await assert.rejects(
88 + () => service.verify(`${token}x`, { ownerId: '42' }),
89 + /invalid approval/i
90 + );
91 + await assert.rejects(
92 + () => service.verify(token, { ownerId: '99' }),
93 + /owner/i
94 + );
95 + await assert.rejects(
96 + () =>
97 + service.verify(token, {
98 + ownerId: '42',
99 + actionId: 'github.workflow.run.rerun_failed'
100 + }),
101 + /action/i
102 + );
103 now += 2000;
83 - await assert.rejects(() => service.verify(token, { ownerId: '42' }), /expired/i);
104 + await assert.rejects(
105 + () => service.verify(token, { ownerId: '42' }),
106 + /expired/i
107 + );
108 });
109
110 test('ApprovalService consume is one-time and rejects replay', async () => {
87 - assert.ok(approvalModule?.ApprovalService, 'ApprovalService module must exist');
111 + assert.ok(
112 + approvalModule?.ApprovalService,
113 + 'ApprovalService module must exist'
114 + );
115 const service = new approvalModule.ApprovalService({
116 secret: 'test-signing-secret',
117 now: () => 1_700_000_000_000,
@@ -100,7 +127,10 @@ test('ApprovalService consume is one-time and rejects replay', async () => {
127
128 const first = await service.consume(token, { ownerId: '42' });
129 assert.equal(first.actionId, 'github.workflow.run.cancel');
103 - await assert.rejects(() => service.consume(token, { ownerId: '42' }), /already used/i);
130 + await assert.rejects(
131 + () => service.consume(token, { ownerId: '42' }),
132 + /already used/i
133 + );
134 });
135
136 test('ApprovalService fails closed for missing replay protection on consume', async () => {
@@ -116,11 +146,17 @@ test('ApprovalService fails closed for missing replay protection on consume', as
146 input: { repoId: 7, runId: 9 }
147 });
148
119 - await assert.rejects(() => service.consume(token, { ownerId: '42' }), /replay protection is not configured/i);
149 + await assert.rejects(
150 + () => service.consume(token, { ownerId: '42' }),
151 + /replay protection is not configured/i
152 + );
153 });
154
155 test('ApprovalService fails closed for missing secret and oversized callback token', async () => {
123 - assert.ok(approvalModule?.ApprovalService, 'ApprovalService module must exist');
156 + assert.ok(
157 + approvalModule?.ApprovalService,
158 + 'ApprovalService module must exist'
159 + );
160 const missing = new approvalModule.ApprovalService({ secret: '' });
161 await assert.rejects(() => missing.issue({ pluginId: 'github' }), /secret/i);
162
@@ -129,11 +165,15 @@ test('ApprovalService fails closed for missing secret and oversized callback tok
165 maxTokenLength: 64,
166 now: () => 1_700_000_000_000
167 });
132 - await assert.rejects(() => service.issue({
133 - pluginId: 'github',
134 - actionId: 'github.workflow.run.cancel',
135 - risk: 'WRITE',
136 - ownerId: '42',
137 - input: { text: 'x'.repeat(200) }
138 - }), /too large/i);
168 + await assert.rejects(
169 + () =>
170 + service.issue({
171 + pluginId: 'github',
172 + actionId: 'github.workflow.run.cancel',
173 + risk: 'WRITE',
174 + ownerId: '42',
175 + input: { text: 'x'.repeat(200) }
176 + }),
177 + /too large/i
178 + );
179 });
test/audit.test.js
+10 -8
@@ -6,7 +6,7 @@ test('AuditLogger redacts configured secrets recursively', () => {
6 const events = [];
7 const logger = new AuditLogger({
8 secrets: ['bot-secret', 'github-secret'],
9 - sink: event => events.push(event)
9 + sink: (event) => events.push(event)
10 });
11
12 logger.log({
@@ -18,14 +18,16 @@ test('AuditLogger redacts configured secrets recursively', () => {
18 }
19 });
20
21 - assert.deepEqual(events, [{
22 - event: 'action_error',
23 - message: 'token [REDACTED] failed',
24 - nested: {
25 - detail: '[REDACTED] present',
26 - values: ['safe', '[REDACTED]']
21 + assert.deepEqual(events, [
22 + {
23 + event: 'action_error',
24 + message: 'token [REDACTED] failed',
25 + nested: {
26 + detail: '[REDACTED] present',
27 + values: ['safe', '[REDACTED]']
28 + }
29 }
28 - }]);
30 + ]);
31 });
32
33 test('AuditLogger sink failures never escape to the caller', () => {
test/automation.test.js
+35 -3
@@ -1,3 +1,35 @@
1 -import test from 'node:test';import assert from 'node:assert/strict';import {createAutomation,transitionAutomation}from'../src/core/automation.js';
2 -test('CP7 state machine pauses resumes and completes',()=>{let s=createAutomation({id:'1',ownerId:'o',recipe:'ci-recovery',steps:[{key:'a'},{key:'b'}]});s=transitionAutomation(s,{type:'pause',intent:{key:'a'}});assert.equal(s.status,'awaiting_approval');s=transitionAutomation(s,{type:'resume',key:'a'});s=transitionAutomation(s,{type:'complete_step',key:'a'});assert.equal(s.cursor,1);s=transitionAutomation(s,{type:'complete_step',key:'b'});assert.equal(s.status,'completed');});
3 -test('CP7 idempotency prevents duplicate step effects',()=>{let s=createAutomation({id:'1',ownerId:'o',recipe:'r',steps:[{key:'a'}]});s=transitionAutomation(s,{type:'complete_step',key:'a'});assert.equal(transitionAutomation(s,{type:'inspect'}).status,'completed');assert.throws(()=>transitionAutomation(s,{type:'resume',key:'a'}));});
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import {
4 + createAutomation,
5 + transitionAutomation
6 +} from '../src/core/automation.js';
7 +test('CP7 state machine pauses resumes and completes', () => {
8 + let s = createAutomation({
9 + id: '1',
10 + ownerId: 'o',
11 + recipe: 'ci-recovery',
12 + steps: [{ key: 'a' }, { key: 'b' }]
13 + });
14 + s = transitionAutomation(s, { type: 'pause', intent: { key: 'a' } });
15 + assert.equal(s.status, 'awaiting_approval');
16 + s = transitionAutomation(s, { type: 'resume', key: 'a' });
17 + s = transitionAutomation(s, { type: 'complete_step', key: 'a' });
18 + assert.equal(s.cursor, 1);
19 + s = transitionAutomation(s, { type: 'complete_step', key: 'b' });
20 + assert.equal(s.status, 'completed');
21 +});
22 +test('CP7 idempotency prevents duplicate step effects', () => {
23 + let s = createAutomation({
24 + id: '1',
25 + ownerId: 'o',
26 + recipe: 'r',
27 + steps: [{ key: 'a' }]
28 + });
29 + s = transitionAutomation(s, { type: 'complete_step', key: 'a' });
30 + assert.equal(
31 + transitionAutomation(s, { type: 'inspect' }).status,
32 + 'completed'
33 + );
34 + assert.throws(() => transitionAutomation(s, { type: 'resume', key: 'a' }));
35 +});
test/bot.test.js
+67 -19
@@ -19,13 +19,15 @@ const fakeGitHub = {
19 };
20 },
21 async listPullRequests() {
22 - return [{
23 - number: 43,
24 - title: 'Ops: strengthen long-running execution heartbeat rule',
25 - author: 'davoodmehraban89',
26 - state: 'open',
27 - merged: false
28 - }];
22 + return [
23 + {
24 + number: 43,
25 + title: 'Ops: strengthen long-running execution heartbeat rule',
26 + author: 'davoodmehraban89',
27 + state: 'open',
28 + merged: false
29 + }
30 + ];
31 },
32 async listCommits() {
33 return [];
@@ -47,14 +49,20 @@ function makeBot() {
49 describe('Nexa Dev Bot - Cloudflare plugin registration', () => {
50 it('registers the Cloudflare READ plugin and fails closed when provider config is absent', async () => {
51 const bot = new NexaDevBot();
50 - assert.ok(bot.registry.getPlugin('cloudflare'), 'cloudflare plugin must be registered');
52 + assert.ok(
53 + bot.registry.getPlugin('cloudflare'),
54 + 'cloudflare plugin must be registered'
55 + );
56 assert.deepEqual(bot.registry.getAction('cloudflare.worker.status'), {
57 pluginId: 'cloudflare',
58 actionId: 'cloudflare.worker.status',
59 risk: 'READ'
60 });
61
57 - const view = await bot.router.dispatchCallback('cf:status', { isOwner: true, ownerId: '123' });
62 + const view = await bot.router.dispatchCallback('cf:status', {
63 + isOwner: true,
64 + ownerId: '123'
65 + });
66 assert.match(view.text, /پیکربندی نشده|not configured/i);
67 });
68 });
@@ -128,7 +136,12 @@ describe('Nexa Dev Bot - Webhook Dispatcher & In-Place Editing', () => {
136 answeredCallbacks.push(id);
137 return { ok: true };
138 };
131 - bot.telegram.editMessageText = async (chatId, messageId, text, replyMarkup) => {
139 + bot.telegram.editMessageText = async (
140 + chatId,
141 + messageId,
142 + text,
143 + replyMarkup
144 + ) => {
145 editedMessages.push({ chatId, messageId, text, replyMarkup });
146 return { ok: true };
147 };
@@ -172,7 +185,12 @@ describe('Nexa Dev Bot - Webhook Dispatcher & In-Place Editing', () => {
185 reply_markup: { inline_keyboard: [] }
186 };
187 };
175 - bot.telegram.editMessageText = async (chatId, messageId, text, replyMarkup) => {
188 + bot.telegram.editMessageText = async (
189 + chatId,
190 + messageId,
191 + text,
192 + replyMarkup
193 + ) => {
194 edits.push({ chatId, messageId, text, replyMarkup });
195 return { ok: true };
196 };
@@ -197,11 +215,23 @@ describe('Nexa Dev Bot - Webhook Dispatcher & In-Place Editing', () => {
215 const edits = [];
216 bot.telegram.answerCallbackQuery = async () => ({ ok: true });
217 bot.router.dispatchCallback = async () => null;
200 - bot.telegram.editMessageText = async (chatId, messageId, text, replyMarkup) => {
218 + bot.telegram.editMessageText = async (
219 + chatId,
220 + messageId,
221 + text,
222 + replyMarkup
223 + ) => {
224 edits.push({ chatId, messageId, text, replyMarkup });
225 return { ok: true };
226 };
204 - const res = await bot.handleUpdate({ callback_query: { id: 'cb_main_local', data: 'menu:main', from: { id: 123456 }, message: { message_id: 501, chat: { id: 123456 } } } });
227 + const res = await bot.handleUpdate({
228 + callback_query: {
229 + id: 'cb_main_local',
230 + data: 'menu:main',
231 + from: { id: 123456 },
232 + message: { message_id: 501, chat: { id: 123456 } }
233 + }
234 + });
235 assert.equal(res.ok, true);
236 assert.equal(res.edited, true);
237 assert.equal(edits.length, 1);
@@ -213,9 +243,16 @@ describe('Nexa Dev Bot - Webhook Dispatcher & In-Place Editing', () => {
243 const bot = makeBot();
244
245 bot.telegram.answerCallbackQuery = async () => {
216 - throw new Error('Telegram API answerCallbackQuery failed: query is too old');
246 + throw new Error(
247 + 'Telegram API answerCallbackQuery failed: query is too old'
248 + );
249 };
218 - bot.telegram.editMessageText = async (chatId, messageId, text, replyMarkup) => {
250 + bot.telegram.editMessageText = async (
251 + chatId,
252 + messageId,
253 + text,
254 + replyMarkup
255 + ) => {
256 editedMessages.push({ chatId, messageId, text, replyMarkup });
257 return { ok: true };
258 };
@@ -239,13 +276,24 @@ describe('Nexa Dev Bot - Webhook Dispatcher & In-Place Editing', () => {
276 const edits = [];
277 const bot = makeBot();
278 bot.telegram.answerCallbackQuery = async () => ({ ok: true });
242 - bot.telegram.editMessageText = async (chatId, messageId, text, replyMarkup) => {
279 + bot.telegram.editMessageText = async (
280 + chatId,
281 + messageId,
282 + text,
283 + replyMarkup
284 + ) => {
285 edits.push({ chatId, messageId, text, replyMarkup });
286 return { ok: true };
287 };
288
289 const message = { message_id: 501, chat: { id: 123456 } };
248 - for (const data of ['repo:Factor-easy', 'pr:Factor-easy', 'repo:Factor-easy', 'menu:repos', 'menu:main']) {
290 + for (const data of [
291 + 'repo:Factor-easy',
292 + 'pr:Factor-easy',
293 + 'repo:Factor-easy',
294 + 'menu:repos',
295 + 'menu:main'
296 + ]) {
297 const result = await bot.handleUpdate({
298 callback_query: { id: data, data, message }
299 });
@@ -253,10 +301,10 @@ describe('Nexa Dev Bot - Webhook Dispatcher & In-Place Editing', () => {
301 }
302
303 assert.equal(edits.length, 5);
256 - assert.ok(edits.every(edit => edit.messageId === 501));
304 + assert.ok(edits.every((edit) => edit.messageId === 501));
305 assert.match(edits[0].text, /پروژه: Factor-easy/);
306 assert.match(edits[1].text, /#43/);
307 assert.match(edits[3].text, /فهرست مخزن‌ها/);
308 assert.match(edits[4].text, /Nexa Dev Bot/);
309 });
262 -});
\ No newline at end of file
310 +});
test/bounded-json.test.js
+35 -12
@@ -2,33 +2,56 @@ import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import { readBoundedJson } from '../src/core/bounded-json.js';
4
5 -const req = (s, headers) => new Request('https://example.com', { method: 'PUT', body: s, headers });
5 +const req = (s, headers) =>
6 + new Request('https://example.com', { method: 'PUT', body: s, headers });
7
7 -test('valid UTF-8 JSON', async () => assert.deepEqual(await readBoundedJson(req('{"x":"✓"}'), 30), { x: '✓' }));
8 -test('exact byte boundary', async () => assert.deepEqual(await readBoundedJson(req('{}'), 2), {}));
9 -test('one byte over', async () => await assert.rejects(readBoundedJson(req('{}'), 1), RangeError));
8 +test('valid UTF-8 JSON', async () =>
9 + assert.deepEqual(await readBoundedJson(req('{"x":"✓"}'), 30), { x: '✓' }));
10 +test('exact byte boundary', async () =>
11 + assert.deepEqual(await readBoundedJson(req('{}'), 2), {}));
12 +test('one byte over', async () =>
13 + await assert.rejects(readBoundedJson(req('{}'), 1), RangeError));
14 test('missing Content-Length still enforces stream cap', async () => {
15 const request = req('x'.repeat(100));
16 request.headers.delete('content-length');
17 await assert.rejects(readBoundedJson(request, 10), RangeError);
18 });
19 test('oversized declared length is rejected', async () =>
16 - await assert.rejects(readBoundedJson(req('{}', { 'content-length': '100' }), 10), RangeError));
17 -test('malformed JSON', async () => await assert.rejects(readBoundedJson(req('{'), 10), SyntaxError));
20 + await assert.rejects(
21 + readBoundedJson(req('{}', { 'content-length': '100' }), 10),
22 + RangeError
23 + ));
24 +test('malformed JSON', async () =>
25 + await assert.rejects(readBoundedJson(req('{'), 10), SyntaxError));
26 test('invalid UTF-8', async () => {
19 - const request = new Request('https://example.com', { method: 'PUT', body: new Uint8Array([255]) });
27 + const request = new Request('https://example.com', {
28 + method: 'PUT',
29 + body: new Uint8Array([255])
30 + });
31 await assert.rejects(readBoundedJson(request, 10), SyntaxError);
32 });
33 test('empty body', async () =>
23 - await assert.rejects(readBoundedJson(new Request('https://example.com', { method: 'PUT' }), 10), SyntaxError));
24 -test('invalid maximum', async () => await assert.rejects(readBoundedJson(req('{}'), 0), RangeError));
34 + await assert.rejects(
35 + readBoundedJson(new Request('https://example.com', { method: 'PUT' }), 10),
36 + SyntaxError
37 + ));
38 +test('invalid maximum', async () =>
39 + await assert.rejects(readBoundedJson(req('{}'), 0), RangeError));
40 test('body stream error propagates', async () => {
41 const request = new Request('https://example.com', {
27 - method: 'PUT', duplex: 'half',
28 - body: new ReadableStream({ pull(controller) { controller.error(new Error('io fail')); } })
42 + method: 'PUT',
43 + duplex: 'half',
44 + body: new ReadableStream({
45 + pull(controller) {
46 + controller.error(new Error('io fail'));
47 + }
48 + })
49 });
50 await assert.rejects(readBoundedJson(request, 10), /io fail/);
51 });
52
53 test('non-integer Content-Length is rejected', async () =>
34 - await assert.rejects(readBoundedJson(req('{}', { 'content-length': '1.5' }), 10), RangeError));
54 + await assert.rejects(
55 + readBoundedJson(req('{}', { 'content-length': '1.5' }), 10),
56 + RangeError
57 + ));
test/cicd-control-plane.test.js
+136 -30
@@ -2,42 +2,148 @@ import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import { correlateDeliveryState } from '../src/core/cicd-control-plane.js';
4
5 -const sha='a'.repeat(40);
6 -const active={deployment:{id:'dep',versions:[{versionId:'v1',percentage:100}]}};
5 +const sha = 'a'.repeat(40);
6 +const active = {
7 + deployment: { id: 'dep', versions: [{ versionId: 'v1', percentage: 100 }] }
8 +};
9
8 -test('CP5 correlates exact SHA across CI and deploy before declaring success',()=>{
9 - assert.equal(correlateDeliveryState({targetSha:sha,ci:{sha,status:'completed',conclusion:'success'},deploy:{sha,status:'completed',conclusion:'success'},runtime:active}).state,'success');
10 - assert.equal(correlateDeliveryState({targetSha:sha,ci:{sha,status:'completed',conclusion:'success'},deploy:{sha:'b'.repeat(40),status:'completed',conclusion:'success'},runtime:active}).state,'mismatch');
10 +test('CP5 correlates exact SHA across CI and deploy before declaring success', () => {
11 + assert.equal(
12 + correlateDeliveryState({
13 + targetSha: sha,
14 + ci: { sha, status: 'completed', conclusion: 'success' },
15 + deploy: { sha, status: 'completed', conclusion: 'success' },
16 + runtime: active
17 + }).state,
18 + 'success'
19 + );
20 + assert.equal(
21 + correlateDeliveryState({
22 + targetSha: sha,
23 + ci: { sha, status: 'completed', conclusion: 'success' },
24 + deploy: {
25 + sha: 'b'.repeat(40),
26 + status: 'completed',
27 + conclusion: 'success'
28 + },
29 + runtime: active
30 + }).state,
31 + 'mismatch'
32 + );
33 });
34
13 -test('CP5 never promotes pending, failed, or missing evidence to success',()=>{
14 - assert.equal(correlateDeliveryState({targetSha:sha,ci:{sha,status:'in_progress'},deploy:{sha,status:'queued'},runtime:active}).state,'pending');
15 - assert.equal(correlateDeliveryState({targetSha:sha,ci:{sha,status:'completed',conclusion:'failure'},deploy:{sha,status:'completed',conclusion:'success'},runtime:active}).state,'failed');
16 - assert.equal(correlateDeliveryState({targetSha:sha,ci:null,deploy:null,runtime:null}).state,'unknown');
35 +test('CP5 never promotes pending, failed, or missing evidence to success', () => {
36 + assert.equal(
37 + correlateDeliveryState({
38 + targetSha: sha,
39 + ci: { sha, status: 'in_progress' },
40 + deploy: { sha, status: 'queued' },
41 + runtime: active
42 + }).state,
43 + 'pending'
44 + );
45 + assert.equal(
46 + correlateDeliveryState({
47 + targetSha: sha,
48 + ci: { sha, status: 'completed', conclusion: 'failure' },
49 + deploy: { sha, status: 'completed', conclusion: 'success' },
50 + runtime: active
51 + }).state,
52 + 'failed'
53 + );
54 + assert.equal(
55 + correlateDeliveryState({
56 + targetSha: sha,
57 + ci: null,
58 + deploy: null,
59 + runtime: null
60 + }).state,
61 + 'unknown'
62 + );
63 });
64
19 -test('CP5 flags runtime traffic that is absent or split as mismatch',()=>{
20 - assert.equal(correlateDeliveryState({targetSha:sha,ci:{sha,status:'completed',conclusion:'success'},deploy:{sha,status:'completed',conclusion:'success'},runtime:{deployment:null}}).state,'mismatch');
21 - assert.equal(correlateDeliveryState({targetSha:sha,ci:{sha,status:'completed',conclusion:'success'},deploy:{sha,status:'completed',conclusion:'success'},runtime:{deployment:{versions:[{versionId:'v1',percentage:50},{versionId:'v2',percentage:50}]}}}).state,'mismatch');
65 +test('CP5 flags runtime traffic that is absent or split as mismatch', () => {
66 + assert.equal(
67 + correlateDeliveryState({
68 + targetSha: sha,
69 + ci: { sha, status: 'completed', conclusion: 'success' },
70 + deploy: { sha, status: 'completed', conclusion: 'success' },
71 + runtime: { deployment: null }
72 + }).state,
73 + 'mismatch'
74 + );
75 + assert.equal(
76 + correlateDeliveryState({
77 + targetSha: sha,
78 + ci: { sha, status: 'completed', conclusion: 'success' },
79 + deploy: { sha, status: 'completed', conclusion: 'success' },
80 + runtime: {
81 + deployment: {
82 + versions: [
83 + { versionId: 'v1', percentage: 50 },
84 + { versionId: 'v2', percentage: 50 }
85 + ]
86 + }
87 + }
88 + }).state,
89 + 'mismatch'
90 + );
91 });
92
24 -
25 -test('CP5 Cloudflare plugin exposes owner delivery view from live provider evidence', async()=>{
26 - const { createCloudflarePlugin } = await import('../src/plugins/cloudflare/plugin.js');
27 - const target='c'.repeat(40);
28 - const github={
29 - async listRepositories(){return [{id:'123',name:'nexa-dev-bot',defaultBranch:'main'}]},
30 - async listCommits(){return [{fullSha:target}]},
31 - async listWorkflowRuns(){return [
32 - {name:'CI',branch:'main',fullSha:target,sha:target.slice(0,7),status:'completed',conclusion:'success'},
33 - {name:'Deploy Cloudflare Worker',branch:'main',fullSha:target,sha:target.slice(0,7),status:'completed',conclusion:'success'}
34 - ]}
93 +test('CP5 Cloudflare plugin exposes owner delivery view from live provider evidence', async () => {
94 + const { createCloudflarePlugin } = await import(
95 + '../src/plugins/cloudflare/plugin.js'
96 + );
97 + const target = 'c'.repeat(40);
98 + const github = {
99 + async listRepositories() {
100 + return [{ id: '123', name: 'nexa-dev-bot', defaultBranch: 'main' }];
101 + },
102 + async listCommits() {
103 + return [{ fullSha: target }];
104 + },
105 + async listWorkflowRuns() {
106 + return [
107 + {
108 + name: 'CI',
109 + branch: 'main',
110 + fullSha: target,
111 + sha: target.slice(0, 7),
112 + status: 'completed',
113 + conclusion: 'success'
114 + },
115 + {
116 + name: 'Deploy Cloudflare Worker',
117 + branch: 'main',
118 + fullSha: target,
119 + sha: target.slice(0, 7),
120 + status: 'completed',
121 + conclusion: 'success'
122 + }
123 + ];
124 + }
125 + };
126 + const cloudflare = {
127 + isConfigured() {
128 + return true;
129 + },
130 + async getWorkerSnapshot() {
131 + return {
132 + workerName: 'nexa-dev-bot',
133 + deployment: {
134 + id: 'dep',
135 + versions: [{ versionId: 'v1', percentage: 100 }]
136 + },
137 + version: { id: 'v1' },
138 + bindings: [],
139 + observability: {}
140 + };
141 + }
142 };
36 - const cloudflare={isConfigured(){return true},async getWorkerSnapshot(){return {workerName:'nexa-dev-bot',deployment:{id:'dep',versions:[{versionId:'v1',percentage:100}]},version:{id:'v1'},bindings:[],observability:{}}}};
37 - const plugin=createCloudflarePlugin({cloudflare,github});
38 - const route=plugin.resolveCallback('cf:delivery');
39 - assert.equal(route.actionId,'cloudflare.delivery.status');
40 - const view=await route.execute();
41 - assert.match(view.text,/SUCCESS|موفق/i);
42 - assert.match(view.text,new RegExp(target.slice(0,12)));
143 + const plugin = createCloudflarePlugin({ cloudflare, github });
144 + const route = plugin.resolveCallback('cf:delivery');
145 + assert.equal(route.actionId, 'cloudflare.delivery.status');
146 + const view = await route.execute();
147 + assert.match(view.text, /SUCCESS|موفق/i);
148 + assert.match(view.text, new RegExp(target.slice(0, 12)));
149 });
test/cloudflare-deploy-config.test.js
+4 -1
@@ -3,7 +3,10 @@ import assert from 'node:assert/strict';
3 import { readFileSync } from 'node:fs';
4
5 test('production deploy syncs Cloudflare status credentials before Worker deploy', () => {
6 - const workflow = readFileSync(new URL('../.github/workflows/deploy.yml', import.meta.url), 'utf8');
6 + const workflow = readFileSync(
7 + new URL('../.github/workflows/deploy.yml', import.meta.url),
8 + 'utf8'
9 + );
10 assert.match(workflow, /secret put CLOUDFLARE_API_TOKEN/);
11 assert.match(workflow, /secret put CLOUDFLARE_ACCOUNT_ID/);
12 assert.match(workflow, /Deploy verified commit to Cloudflare Workers/);
test/cloudflare-menu.test.js
+20 -6
@@ -3,17 +3,31 @@ import assert from 'node:assert/strict';
3 import { CloudflareMenuManager } from '../src/cloudflare-menu.js';
4
5 function callbacks(view) {
6 - return (view.reply_markup?.inline_keyboard || []).flat().map(button => button.callback_data).filter(Boolean);
6 + return (view.reply_markup?.inline_keyboard || [])
7 + .flat()
8 + .map((button) => button.callback_data)
9 + .filter(Boolean);
10 }
11
12 test('tools menu includes Cloudflare status', () => {
10 - const menu = new CloudflareMenuManager({}, {
11 - getSnapshot() { return { runtime: 'Cloudflare Worker', githubOwner: 'owner', pluginCount: 2 }; },
12 - getPluginSummary() { return { pluginCount: 2, actionCount: 2, plugins: [] }; }
13 - });
13 + const menu = new CloudflareMenuManager(
14 + {},
15 + {
16 + getSnapshot() {
17 + return {
18 + runtime: 'Cloudflare Worker',
19 + githubOwner: 'owner',
20 + pluginCount: 2
21 + };
22 + },
23 + getPluginSummary() {
24 + return { pluginCount: 2, actionCount: 2, plugins: [] };
25 + }
26 + }
27 + );
28 const values = callbacks(menu.getToolsView());
29 assert.ok(values.includes('cf:status'));
16 - assert.equal(values.filter(value => value === 'cf:status').length, 1);
30 + assert.equal(values.filter((value) => value === 'cf:status').length, 1);
31 assert.ok(values.includes('ops:github'));
32 assert.ok(values.includes('menu:main'));
33 });
test/cloudflare-ops-completion.test.js
+112 -36
@@ -4,46 +4,122 @@ import { CloudflareService } from '../src/plugins/cloudflare/service.js';
4 import { createCloudflarePlugin } from '../src/plugins/cloudflare/plugin.js';
5 import { cloudflarePluginManifest } from '../src/plugins/cloudflare/manifest.js';
6
7 -const cf=(result,status=200)=>new Response(JSON.stringify({success:status<400,result,errors:status<400?[]:[{message:'bad'}]}),{status});
8 -const uuid='11111111-1111-4111-8111-111111111111';
7 +const cf = (result, status = 200) =>
8 + new Response(
9 + JSON.stringify({
10 + success: status < 400,
11 + result,
12 + errors: status < 400 ? [] : [{ message: 'bad' }]
13 + }),
14 + { status }
15 + );
16 +const uuid = '11111111-1111-4111-8111-111111111111';
17
10 -test('CP4 service lists versions and deploys exact known version at 100 percent then verifies it',async()=>{
11 - const calls=[];
12 - const service=new CloudflareService({token:'token',accountId:'acct',workerName:'nexa-dev-bot',fetchImpl:async(url,opt={})=>{
13 - calls.push({url:String(url),method:opt.method||'GET',body:opt.body});
14 - if((opt.method||'GET')==='POST') return cf({id:'dep-new',versions:[{version_id:uuid,percentage:100}]});
15 - if(String(url).endsWith('/deployments')) return cf({deployments:[{id:'dep-new',created_on:'2026-10-05T00:00:00Z',versions:[{version_id:uuid,percentage:100}]}]});
16 - if(String(url).endsWith('/versions')) return cf({items:[{id:uuid,created_on:'2026-10-04T00:00:00Z'}]});
17 - if(String(url).endsWith('/settings')) return cf({bindings:[{name:'SECRET',type:'secret_text'}],observability:{enabled:true,logs:{enabled:true,invocation_logs:true}}});
18 - return cf(null,404);
19 - }});
20 - const versions=await service.listVersions();
21 - assert.equal(versions[0].id,uuid);
22 - const deployed=await service.deployVersion(uuid);
23 - assert.equal(deployed.versionId,uuid);
24 - assert.equal(calls.find(c=>c.method==='POST').body.includes(uuid),true);
25 - assert.deepEqual((await service.getWorkerSnapshot()).bindings,[{name:'SECRET',type:'secret_text'}]);
18 +test('CP4 service lists versions and deploys exact known version at 100 percent then verifies it', async () => {
19 + const calls = [];
20 + const service = new CloudflareService({
21 + token: 'token',
22 + accountId: 'acct',
23 + workerName: 'nexa-dev-bot',
24 + fetchImpl: async (url, opt = {}) => {
25 + calls.push({
26 + url: String(url),
27 + method: opt.method || 'GET',
28 + body: opt.body
29 + });
30 + if ((opt.method || 'GET') === 'POST')
31 + return cf({
32 + id: 'dep-new',
33 + versions: [{ version_id: uuid, percentage: 100 }]
34 + });
35 + if (String(url).endsWith('/deployments'))
36 + return cf({
37 + deployments: [
38 + {
39 + id: 'dep-new',
40 + created_on: '2026-10-05T00:00:00Z',
41 + versions: [{ version_id: uuid, percentage: 100 }]
42 + }
43 + ]
44 + });
45 + if (String(url).endsWith('/versions'))
46 + return cf({
47 + items: [{ id: uuid, created_on: '2026-10-04T00:00:00Z' }]
48 + });
49 + if (String(url).endsWith('/settings'))
50 + return cf({
51 + bindings: [{ name: 'SECRET', type: 'secret_text' }],
52 + observability: {
53 + enabled: true,
54 + logs: { enabled: true, invocation_logs: true }
55 + }
56 + });
57 + return cf(null, 404);
58 + }
59 + });
60 + const versions = await service.listVersions();
61 + assert.equal(versions[0].id, uuid);
62 + const deployed = await service.deployVersion(uuid);
63 + assert.equal(deployed.versionId, uuid);
64 + assert.equal(
65 + calls.find((c) => c.method === 'POST').body.includes(uuid),
66 + true
67 + );
68 + assert.deepEqual((await service.getWorkerSnapshot()).bindings, [
69 + { name: 'SECRET', type: 'secret_text' }
70 + ]);
71 });
72
28 -test('CP4 plugin declares deploy as DESTRUCTIVE and read drill-down stays source-backed',async()=>{
29 - assert.equal(cloudflarePluginManifest.actions['cloudflare.worker.deploy_version']?.risk,'DESTRUCTIVE');
30 - const cloudflare={
31 - isConfigured(){return true},
32 - async getWorkerSnapshot(){return {workerName:'nexa-dev-bot',deployment:{id:'dep',versions:[{versionId:uuid,percentage:100}]},version:{id:uuid},bindings:[],observability:{}}},
33 - async listVersions(){return [{id:uuid,createdOn:'2026-10-04T00:00:00Z',triggeredBy:'upload'}]},
34 - async deployVersion(){throw new Error('must not run before approval')}
73 +test('CP4 plugin declares deploy as DESTRUCTIVE and read drill-down stays source-backed', async () => {
74 + assert.equal(
75 + cloudflarePluginManifest.actions['cloudflare.worker.deploy_version']?.risk,
76 + 'DESTRUCTIVE'
77 + );
78 + const cloudflare = {
79 + isConfigured() {
80 + return true;
81 + },
82 + async getWorkerSnapshot() {
83 + return {
84 + workerName: 'nexa-dev-bot',
85 + deployment: {
86 + id: 'dep',
87 + versions: [{ versionId: uuid, percentage: 100 }]
88 + },
89 + version: { id: uuid },
90 + bindings: [],
91 + observability: {}
92 + };
93 + },
94 + async listVersions() {
95 + return [
96 + { id: uuid, createdOn: '2026-10-04T00:00:00Z', triggeredBy: 'upload' }
97 + ];
98 + },
99 + async deployVersion() {
100 + throw new Error('must not run before approval');
101 + }
102 };
36 - const plugin=createCloudflarePlugin({cloudflare});
37 - const list=plugin.resolveCallback('cf:versions');
38 - assert.equal(list.actionId,'cloudflare.worker.versions');
39 - const view=await list.execute();
40 - assert.ok(view.reply_markup.inline_keyboard.flat().some(b=>b.callback_data===`cfdeploy:${uuid}`));
41 - const mutation=plugin.resolveCallback(`cfdeploy:${uuid}`);
42 - assert.equal(mutation.actionId,'cloudflare.worker.deploy_version');
43 - assert.deepEqual(mutation.approval.input,{versionId:uuid});
103 + const plugin = createCloudflarePlugin({ cloudflare });
104 + const list = plugin.resolveCallback('cf:versions');
105 + assert.equal(list.actionId, 'cloudflare.worker.versions');
106 + const view = await list.execute();
107 + assert.ok(
108 + view.reply_markup.inline_keyboard
109 + .flat()
110 + .some((b) => b.callback_data === `cfdeploy:${uuid}`)
111 + );
112 + const mutation = plugin.resolveCallback(`cfdeploy:${uuid}`);
113 + assert.equal(mutation.actionId, 'cloudflare.worker.deploy_version');
114 + assert.deepEqual(mutation.approval.input, { versionId: uuid });
115 });
116
46 -test('CP4 provider errors never become fake success',async()=>{
47 - const service=new CloudflareService({token:'token',accountId:'acct',workerName:'nexa-dev-bot',fetchImpl:async()=>cf(null,409)});
48 - await assert.rejects(()=>service.deployVersion(uuid),/409|bad/i);
117 +test('CP4 provider errors never become fake success', async () => {
118 + const service = new CloudflareService({
119 + token: 'token',
120 + accountId: 'acct',
121 + workerName: 'nexa-dev-bot',
122 + fetchImpl: async () => cf(null, 409)
123 + });
124 + await assert.rejects(() => service.deployVersion(uuid), /409|bad/i);
125 });
test/cloudflare-plugin.test.js
+35 -8
@@ -3,7 +3,10 @@ import assert from 'node:assert/strict';
3 import { createCloudflarePlugin } from '../src/plugins/cloudflare/plugin.js';
4
5 function callbacks(view) {
6 - return (view.reply_markup?.inline_keyboard || []).flat().map(button => button.callback_data).filter(Boolean);
6 + return (view.reply_markup?.inline_keyboard || [])
7 + .flat()
8 + .map((button) => button.callback_data)
9 + .filter(Boolean);
10 }
11
12 function telegramContract(view) {
@@ -15,7 +18,9 @@ function telegramContract(view) {
18 }
19
20 test('Cloudflare plugin exposes CP4 read and destructive actions explicitly', () => {
18 - const plugin = createCloudflarePlugin({ cloudflare: { isConfigured: () => true } });
21 + const plugin = createCloudflarePlugin({
22 + cloudflare: { isConfigured: () => true }
23 + });
24 assert.equal(plugin.manifest.id, 'cloudflare');
25 assert.deepEqual(plugin.manifest.actions, {
26 'cloudflare.worker.status': { risk: 'READ' },
@@ -31,13 +36,26 @@ test('cf:status renders source-backed worker deployment details with refresh and
36 async getWorkerSnapshot() {
37 return {
38 workerName: 'nexa-dev-bot',
34 - deployment: { id: 'dep-1', createdOn: '2026-10-04T19:34:03Z', versions: [{ versionId: 'ver-1', percentage: 100 }] },
35 - version: { id: 'ver-1', createdOn: '2026-10-04T19:34:01Z', triggeredBy: 'upload' },
39 + deployment: {
40 + id: 'dep-1',
41 + createdOn: '2026-10-04T19:34:03Z',
42 + versions: [{ versionId: 'ver-1', percentage: 100 }]
43 + },
44 + version: {
45 + id: 'ver-1',
46 + createdOn: '2026-10-04T19:34:01Z',
47 + triggeredBy: 'upload'
48 + },
49 bindings: [
50 { name: 'WORKSPACE_STORE', type: 'durable_object_namespace' },
51 { name: 'GITHUB_TOKEN', type: 'secret_text' }
52 ],
40 - observability: { enabled: true, logsEnabled: true, invocationLogs: true, tracesEnabled: false }
53 + observability: {
54 + enabled: true,
55 + logsEnabled: true,
56 + invocationLogs: true,
57 + tracesEnabled: false
58 + }
59 };
60 }
61 };
@@ -57,7 +75,9 @@ test('cf:status renders source-backed worker deployment details with refresh and
75 });
76
77 test('Cloudflare plugin renders explicit unavailable state without fabricating health', async () => {
60 - const plugin = createCloudflarePlugin({ cloudflare: { isConfigured: () => false } });
78 + const plugin = createCloudflarePlugin({
79 + cloudflare: { isConfigured: () => false }
80 + });
81 const view = await plugin.resolveCallback('cf:status').execute();
82 telegramContract(view);
83 assert.match(view.text, /پیکربندی نشده|not configured/i);
@@ -73,11 +93,18 @@ test('Cloudflare plugin escapes provider-controlled text and handles empty provi
93 deployment: null,
94 version: null,
95 bindings: [{ name: '<TOKEN>', type: 'secret_text' }],
76 - observability: { enabled: false, logsEnabled: false, invocationLogs: false, tracesEnabled: false }
96 + observability: {
97 + enabled: false,
98 + logsEnabled: false,
99 + invocationLogs: false,
100 + tracesEnabled: false
101 + }
102 };
103 }
104 };
80 - const view = await createCloudflarePlugin({ cloudflare }).resolveCallback('cf:status').execute();
105 + const view = await createCloudflarePlugin({ cloudflare })
106 + .resolveCallback('cf:status')
107 + .execute();
108 telegramContract(view);
109 assert.doesNotMatch(view.text, /<worker&name>|<TOKEN>/);
110 assert.match(view.text, /&lt;worker&amp;name&gt;/);
test/cloudflare-service.test.js
+89 -21
@@ -10,7 +10,9 @@ function response(body, status = 200) {
10 return {
11 ok: status >= 200 && status < 300,
12 status,
13 - async text() { return JSON.stringify(body); }
13 + async text() {
14 + return JSON.stringify(body);
15 + }
16 };
17 }
18
@@ -32,13 +34,59 @@ test('CloudflareService normalizes deployment, version, bindings and observabili
34 const fetchImpl = async (url, options = {}) => {
35 calls.push({ url: String(url), options });
36 const value = String(url);
35 - if (value.endsWith('/deployments')) return response({ success: true, result: { deployments: [{ id: 'dep-1', created_on: '2026-10-04T19:34:03Z', versions: [{ version_id: 'ver-1', percentage: 100 }] }] } });
36 - if (value.endsWith('/versions')) return response({ success: true, result: { items: [{ id: 'ver-1', created_on: '2026-10-04T19:34:01Z', annotations: { 'workers/triggered_by': 'upload' } }] } });
37 - if (value.endsWith('/settings')) return response({ success: true, result: { bindings: [{ name: 'WORKSPACE_STORE', type: 'durable_object_namespace' }, { name: 'GITHUB_TOKEN', type: 'secret_text' }], observability: { enabled: true, logs: { enabled: true, invocation_logs: true }, traces: { enabled: false } } } });
38 - return response({ success: false, errors: [{ message: 'Not Found' }] }, 404);
37 + if (value.endsWith('/deployments'))
38 + return response({
39 + success: true,
40 + result: {
41 + deployments: [
42 + {
43 + id: 'dep-1',
44 + created_on: '2026-10-04T19:34:03Z',
45 + versions: [{ version_id: 'ver-1', percentage: 100 }]
46 + }
47 + ]
48 + }
49 + });
50 + if (value.endsWith('/versions'))
51 + return response({
52 + success: true,
53 + result: {
54 + items: [
55 + {
56 + id: 'ver-1',
57 + created_on: '2026-10-04T19:34:01Z',
58 + annotations: { 'workers/triggered_by': 'upload' }
59 + }
60 + ]
61 + }
62 + });
63 + if (value.endsWith('/settings'))
64 + return response({
65 + success: true,
66 + result: {
67 + bindings: [
68 + { name: 'WORKSPACE_STORE', type: 'durable_object_namespace' },
69 + { name: 'GITHUB_TOKEN', type: 'secret_text' }
70 + ],
71 + observability: {
72 + enabled: true,
73 + logs: { enabled: true, invocation_logs: true },
74 + traces: { enabled: false }
75 + }
76 + }
77 + });
78 + return response(
79 + { success: false, errors: [{ message: 'Not Found' }] },
80 + 404
81 + );
82 };
83
41 - const service = new CloudflareService({ token, accountId, workerName, fetchImpl });
84 + const service = new CloudflareService({
85 + token,
86 + accountId,
87 + workerName,
88 + fetchImpl
89 + });
90 assert.equal(service.isConfigured(), true);
91 const snapshot = await service.getWorkerSnapshot();
92
@@ -65,14 +113,22 @@ test('CloudflareService normalizes deployment, version, bindings and observabili
113 });
114
115 test('CloudflareService returns explicit empty state when provider has no deployment or version items', async () => {
68 - const fetchImpl = async url => {
116 + const fetchImpl = async (url) => {
117 const value = String(url);
70 - if (value.endsWith('/deployments')) return response({ success: true, result: { deployments: [] } });
71 - if (value.endsWith('/versions')) return response({ success: true, result: { items: [] } });
72 - if (value.endsWith('/settings')) return response({ success: true, result: {} });
118 + if (value.endsWith('/deployments'))
119 + return response({ success: true, result: { deployments: [] } });
120 + if (value.endsWith('/versions'))
121 + return response({ success: true, result: { items: [] } });
122 + if (value.endsWith('/settings'))
123 + return response({ success: true, result: {} });
124 throw new Error('unexpected URL');
125 };
75 - const service = new CloudflareService({ token, accountId, workerName, fetchImpl });
126 + const service = new CloudflareService({
127 + token,
128 + accountId,
129 + workerName,
130 + fetchImpl
131 + });
132 const snapshot = await service.getWorkerSnapshot();
133 assert.equal(snapshot.deployment, null);
134 assert.equal(snapshot.version, null);
@@ -86,15 +142,27 @@ test('CloudflareService returns explicit empty state when provider has no deploy
142 });
143
144 test('CloudflareService reports provider failure without leaking token', async () => {
89 - const fetchImpl = async () => response({ success: false, errors: [{ message: `bad credential ${token}` }] }, 403);
90 - const service = new CloudflareService({ token, accountId, workerName, fetchImpl });
91 -
92 - await assert.rejects(async () => {
93 - await service.getWorkerSnapshot();
94 - }, error => {
95 - assert.match(error.message, /403/);
96 - assert.doesNotMatch(error.message, new RegExp(token));
97 - assert.match(error.message, /\[REDACTED\]/);
98 - return true;
145 + const fetchImpl = async () =>
146 + response(
147 + { success: false, errors: [{ message: `bad credential ${token}` }] },
148 + 403
149 + );
150 + const service = new CloudflareService({
151 + token,
152 + accountId,
153 + workerName,
154 + fetchImpl
155 });
156 +
157 + await assert.rejects(
158 + async () => {
159 + await service.getWorkerSnapshot();
160 + },
161 + (error) => {
162 + assert.match(error.message, /403/);
163 + assert.doesNotMatch(error.message, new RegExp(token));
164 + assert.match(error.message, /\[REDACTED\]/);
165 + return true;
166 + }
167 + );
168 });
test/destructive-second-factor.test.js
+76 -15
@@ -13,7 +13,8 @@ function decodeBase32(value) {
13 bits += index.toString(2).padStart(5, '0');
14 }
15 const out = [];
16 - for (let i = 0; i + 8 <= bits.length; i += 8) out.push(Number.parseInt(bits.slice(i, i + 8), 2));
16 + for (let i = 0; i + 8 <= bits.length; i += 8)
17 + out.push(Number.parseInt(bits.slice(i, i + 8), 2));
18 return new Uint8Array(out);
19 }
20
@@ -23,10 +24,20 @@ async function currentTotp(secret, now = Date.now()) {
24 const view = new DataView(buffer);
25 view.setUint32(0, Math.floor(counter / 2 ** 32));
26 view.setUint32(4, counter >>> 0);
26 - const key = await crypto.subtle.importKey('raw', decodeBase32(secret), { name: 'HMAC', hash: 'SHA-1' }, false, ['sign']);
27 + const key = await crypto.subtle.importKey(
28 + 'raw',
29 + decodeBase32(secret),
30 + { name: 'HMAC', hash: 'SHA-1' },
31 + false,
32 + ['sign']
33 + );
34 const digest = new Uint8Array(await crypto.subtle.sign('HMAC', key, buffer));
35 const offset = digest[digest.length - 1] & 0x0f;
29 - const binary = ((digest[offset] & 0x7f) << 24) | (digest[offset + 1] << 16) | (digest[offset + 2] << 8) | digest[offset + 3];
36 + const binary =
37 + ((digest[offset] & 0x7f) << 24) |
38 + (digest[offset + 1] << 16) |
39 + (digest[offset + 2] << 8) |
40 + digest[offset + 3];
41 return String(binary % 1_000_000).padStart(6, '0');
42 }
43
@@ -48,22 +59,49 @@ function makeBot(secret = TOTP_SECRET) {
59 let executeCount = 0;
60
61 bot.approvals.verify = async () => payload;
51 - bot.approvals.consume = async () => { consumeCount += 1; return payload; };
52 - bot.replayStore.setSecondFactorPending = async ({ ownerId, token, expiresAt }) => {
62 + bot.approvals.consume = async () => {
63 + consumeCount += 1;
64 + return payload;
65 + };
66 + bot.replayStore.setSecondFactorPending = async ({
67 + ownerId,
68 + token,
69 + expiresAt
70 + }) => {
71 pending.set(String(ownerId), { token, expiresAt });
72 return true;
73 };
56 - bot.replayStore.getSecondFactorPending = async ({ ownerId }) => pending.get(String(ownerId)) || null;
57 - bot.replayStore.clearSecondFactorPending = async ({ ownerId }) => { pending.delete(String(ownerId)); return true; };
74 + bot.replayStore.getSecondFactorPending = async ({ ownerId }) =>
75 + pending.get(String(ownerId)) || null;
76 + bot.replayStore.clearSecondFactorPending = async ({ ownerId }) => {
77 + pending.delete(String(ownerId));
78 + return true;
79 + };
80 bot.router.dispatchCallback = async (_data, context) => {
81 if (context?.approved) executeCount += 1;
82 return { text: 'executed', reply_markup: { inline_keyboard: [] } };
83 };
84 bot.telegram.answerCallbackQuery = async () => ({ ok: true });
63 - bot.telegram.editMessageText = async (_chatId, _messageId, text, replyMarkup) => ({ ok: true, result: { text, reply_markup: replyMarkup } });
64 - bot.telegram.sendMessage = async (_chatId, text, replyMarkup) => ({ ok: true, result: { text, reply_markup: replyMarkup } });
85 + bot.telegram.editMessageText = async (
86 + _chatId,
87 + _messageId,
88 + text,
89 + replyMarkup
90 + ) => ({ ok: true, result: { text, reply_markup: replyMarkup } });
91 + bot.telegram.sendMessage = async (_chatId, text, replyMarkup) => ({
92 + ok: true,
93 + result: { text, reply_markup: replyMarkup }
94 + });
95
66 - return { bot, get consumeCount() { return consumeCount; }, get executeCount() { return executeCount; } };
96 + return {
97 + bot,
98 + get consumeCount() {
99 + return consumeCount;
100 + },
101 + get executeCount() {
102 + return executeCount;
103 + }
104 + };
105 }
106
107 test('DESTRUCTIVE approval fails closed when second-factor secret is not configured', async () => {
@@ -78,8 +116,16 @@ test('DESTRUCTIVE approval fails closed when second-factor secret is not configu
116 });
117
118 assert.equal(result.ok, false);
81 - assert.equal(harness.consumeCount, 0, 'approval must not be consumed without second factor');
82 - assert.equal(harness.executeCount, 0, 'DESTRUCTIVE provider action must not execute without second factor');
119 + assert.equal(
120 + harness.consumeCount,
121 + 0,
122 + 'approval must not be consumed without second factor'
123 + );
124 + assert.equal(
125 + harness.executeCount,
126 + 0,
127 + 'DESTRUCTIVE provider action must not execute without second factor'
128 + );
129 assert.match(String(result.error || ''), /second factor|totp|configured/i);
130 });
131
@@ -101,7 +147,12 @@ test('DESTRUCTIVE approval requires valid TOTP before consuming approval or exec
147 assert.equal(harness.executeCount, 0);
148
149 const wrong = await harness.bot.handleUpdate({
104 - message: { message_id: 902, chat: { id: 123 }, from: { id: 123 }, text: '/totp 000000' }
150 + message: {
151 + message_id: 902,
152 + chat: { id: 123 },
153 + from: { id: 123 },
154 + text: '/totp 000000'
155 + }
156 });
157 assert.equal(wrong.ok, false);
158 assert.equal(wrong.secondFactorRejected, true);
@@ -110,7 +161,12 @@ test('DESTRUCTIVE approval requires valid TOTP before consuming approval or exec
161
162 const code = await currentTotp(TOTP_SECRET);
163 const accepted = await harness.bot.handleUpdate({
113 - message: { message_id: 903, chat: { id: 123 }, from: { id: 123 }, text: `/totp ${code}` }
164 + message: {
165 + message_id: 903,
166 + chat: { id: 123 },
167 + from: { id: 123 },
168 + text: `/totp ${code}`
169 + }
170 });
171 assert.equal(accepted.ok, true);
172 assert.equal(accepted.secondFactorVerified, true);
@@ -134,7 +190,12 @@ test('TOTP code and signed approval token are never written to audit output', as
190 });
191 const code = await currentTotp(TOTP_SECRET);
192 await harness.bot.handleUpdate({
137 - message: { message_id: 905, chat: { id: 123 }, from: { id: 123 }, text: `/totp ${code}` }
193 + message: {
194 + message_id: 905,
195 + chat: { id: 123 },
196 + from: { id: 123 },
197 + text: `/totp ${code}`
198 + }
199 });
200 const output = logs.join('\n');
201 assert.doesNotMatch(output, new RegExp(code));
test/durable-replay.test.js
+95 -39
@@ -1,7 +1,9 @@
1 import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import { readFile } from 'node:fs/promises';
4 -import worker, { ApprovalReplayGuard as ExportedApprovalReplayGuard } from '../src/index.js';
4 +import worker, {
5 + ApprovalReplayGuard as ExportedApprovalReplayGuard
6 +} from '../src/index.js';
7 import { DurableApprovalReplayStore } from '../src/core/durable-replay-store.js';
8 import { ApprovalReplayGuard } from '../src/durable/approval-replay-guard.js';
9
@@ -28,17 +30,26 @@ function makeState() {
30 let alarm = null;
31 return {
32 data,
31 - get alarm() { return alarm; },
33 + get alarm() {
34 + return alarm;
35 + },
36 storage: {
37 async transaction(fn) {
38 return fn({
35 - get: key => data.get(key),
36 - put: (key, value) => { data.set(key, value); },
37 - delete: key => data.delete(key)
39 + get: (key) => data.get(key),
40 + put: (key, value) => {
41 + data.set(key, value);
42 + },
43 + delete: (key) => data.delete(key)
44 });
45 },
40 - async setAlarm(value) { alarm = value; },
41 - async deleteAll() { data.clear(); alarm = null; }
46 + async setAlarm(value) {
47 + alarm = value;
48 + },
49 + async deleteAll() {
50 + data.clear();
51 + alarm = null;
52 + }
53 }
54 };
55 }
@@ -46,7 +57,12 @@ function makeState() {
57 test('DurableApprovalReplayStore fails closed without a Durable Object namespace', async () => {
58 const store = new DurableApprovalReplayStore();
59 await assert.rejects(
49 - () => store.consume({ ownerId: '123', nonce: 'abc', expiresAt: Date.now() + 10_000 }),
60 + () =>
61 + store.consume({
62 + ownerId: '123',
63 + nonce: 'abc',
64 + expiresAt: Date.now() + 10_000
65 + }),
66 /not configured/i
67 );
68 });
@@ -69,10 +85,16 @@ test('DurableApprovalReplayStore scopes one-time consumption by owner and nonce'
85 });
86
87 test('DurableApprovalReplayStore rejects a replay response from the Durable Object', async () => {
72 - const namespace = makeNamespace(async () => Response.json({ accepted: false, reason: 'already_used' }, { status: 409 }));
88 + const namespace = makeNamespace(async () =>
89 + Response.json({ accepted: false, reason: 'already_used' }, { status: 409 })
90 + );
91 const store = new DurableApprovalReplayStore({ namespace });
92
75 - const accepted = await store.consume({ ownerId: '123', nonce: 'nonce-2', expiresAt: 42_000 });
93 + const accepted = await store.consume({
94 + ownerId: '123',
95 + nonce: 'nonce-2',
96 + expiresAt: 42_000
97 + });
98 assert.equal(accepted, false);
99 });
100
@@ -80,11 +102,12 @@ test('ApprovalReplayGuard atomically accepts once and schedules cleanup', async
102 const state = makeState();
103 const guard = new ApprovalReplayGuard(state);
104 const expiresAt = Date.now() + 60_000;
83 - const request = () => new Request('https://approval-replay/consume', {
84 - method: 'POST',
85 - headers: { 'content-type': 'application/json' },
86 - body: JSON.stringify({ expiresAt })
87 - });
105 + const request = () =>
106 + new Request('https://approval-replay/consume', {
107 + method: 'POST',
108 + headers: { 'content-type': 'application/json' },
109 + body: JSON.stringify({ expiresAt })
110 + });
111
112 const first = await guard.fetch(request());
113 assert.equal(first.status, 200);
@@ -94,17 +117,22 @@ test('ApprovalReplayGuard atomically accepts once and schedules cleanup', async
117
118 const second = await guard.fetch(request());
119 assert.equal(second.status, 409);
97 - assert.deepEqual(await second.json(), { accepted: false, reason: 'already_used' });
120 + assert.deepEqual(await second.json(), {
121 + accepted: false,
122 + reason: 'already_used'
123 + });
124 });
125
126 test('ApprovalReplayGuard fails closed for expired requests and alarm removes storage', async () => {
127 const state = makeState();
128 const guard = new ApprovalReplayGuard(state);
103 - const response = await guard.fetch(new Request('https://approval-replay/consume', {
104 - method: 'POST',
105 - headers: { 'content-type': 'application/json' },
106 - body: JSON.stringify({ expiresAt: Date.now() - 1 })
107 - }));
129 + const response = await guard.fetch(
130 + new Request('https://approval-replay/consume', {
131 + method: 'POST',
132 + headers: { 'content-type': 'application/json' },
133 + body: JSON.stringify({ expiresAt: Date.now() - 1 })
134 + })
135 + );
136
137 assert.equal(response.status, 410);
138 assert.equal((await response.json()).accepted, false);
@@ -118,18 +146,24 @@ test('Worker exports ApprovalReplayGuard and Wrangler declares SQLite durable bi
146 assert.ok(worker && typeof worker.fetch === 'function');
147 assert.equal(ExportedApprovalReplayGuard, ApprovalReplayGuard);
148
121 - const configText = await readFile(new URL('../wrangler.jsonc', import.meta.url), 'utf8');
149 + const configText = await readFile(
150 + new URL('../wrangler.jsonc', import.meta.url),
151 + 'utf8'
152 + );
153 const config = JSON.parse(configText);
123 - assert.ok(config.durable_objects?.bindings?.some(binding =>
124 - binding.name === 'APPROVAL_REPLAY_GUARD' && binding.class_name === 'ApprovalReplayGuard'
125 - ));
154 + assert.ok(
155 + config.durable_objects?.bindings?.some(
156 + (binding) =>
157 + binding.name === 'APPROVAL_REPLAY_GUARD' &&
158 + binding.class_name === 'ApprovalReplayGuard'
159 + )
160 + );
161 assert.deepEqual(config.exports?.ApprovalReplayGuard, {
162 type: 'durable-object',
163 storage: 'sqlite'
164 });
165 });
166
132 -
167 test('DurableApprovalReplayStore persists owner-scoped second-factor pending state without exposing it in logs', async () => {
168 let stored = null;
169 const namespace = makeNamespace(async (_id, request) => {
@@ -139,7 +173,9 @@ test('DurableApprovalReplayStore persists owner-scoped second-factor pending sta
173 return Response.json({ stored: true });
174 }
175 if (request.method === 'GET' && url.pathname === '/second-factor/get') {
142 - return stored ? Response.json({ pending: stored }) : Response.json({ pending: null }, { status: 404 });
176 + return stored
177 + ? Response.json({ pending: stored })
178 + : Response.json({ pending: null }, { status: 404 });
179 }
180 if (request.method === 'POST' && url.pathname === '/second-factor/clear') {
181 stored = null;
@@ -150,11 +186,19 @@ test('DurableApprovalReplayStore persists owner-scoped second-factor pending sta
186 const store = new DurableApprovalReplayStore({ namespace });
187 const expiresAt = Date.now() + 60_000;
188
153 - await store.setSecondFactorPending({ ownerId: '123', token: 'signed-token', expiresAt });
154 - assert.deepEqual(await store.getSecondFactorPending({ ownerId: '123' }), { token: 'signed-token', expiresAt, attempts: 0 });
189 + await store.setSecondFactorPending({
190 + ownerId: '123',
191 + token: 'signed-token',
192 + expiresAt
193 + });
194 + assert.deepEqual(await store.getSecondFactorPending({ ownerId: '123' }), {
195 + token: 'signed-token',
196 + expiresAt,
197 + attempts: 0
198 + });
199 await store.clearSecondFactorPending({ ownerId: '123' });
200 assert.equal(await store.getSecondFactorPending({ ownerId: '123' }), null);
157 - assert.ok(namespace.ids.every(id => id === '123:second-factor'));
201 + assert.ok(namespace.ids.every((id) => id === '123:second-factor'));
202 });
203
204 test('ApprovalReplayGuard expires and clears second-factor pending state fail-closed', async () => {
@@ -162,19 +206,31 @@ test('ApprovalReplayGuard expires and clears second-factor pending state fail-cl
206 const guard = new ApprovalReplayGuard(state);
207 const expiresAt = Date.now() + 60_000;
208
165 - const put = await guard.fetch(new Request('https://approval-replay/second-factor/put', {
166 - method: 'POST',
167 - headers: { 'content-type': 'application/json' },
168 - body: JSON.stringify({ token: 'signed-token', expiresAt })
169 - }));
209 + const put = await guard.fetch(
210 + new Request('https://approval-replay/second-factor/put', {
211 + method: 'POST',
212 + headers: { 'content-type': 'application/json' },
213 + body: JSON.stringify({ token: 'signed-token', expiresAt })
214 + })
215 + );
216 assert.equal(put.status, 200);
217
172 - const get = await guard.fetch(new Request('https://approval-replay/second-factor/get'));
218 + const get = await guard.fetch(
219 + new Request('https://approval-replay/second-factor/get')
220 + );
221 assert.equal(get.status, 200);
174 - assert.deepEqual(await get.json(), { pending: { token: 'signed-token', expiresAt, attempts: 0 } });
222 + assert.deepEqual(await get.json(), {
223 + pending: { token: 'signed-token', expiresAt, attempts: 0 }
224 + });
225
176 - const clear = await guard.fetch(new Request('https://approval-replay/second-factor/clear', { method: 'POST' }));
226 + const clear = await guard.fetch(
227 + new Request('https://approval-replay/second-factor/clear', {
228 + method: 'POST'
229 + })
230 + );
231 assert.equal(clear.status, 200);
178 - const after = await guard.fetch(new Request('https://approval-replay/second-factor/get'));
232 + const after = await guard.fetch(
233 + new Request('https://approval-replay/second-factor/get')
234 + );
235 assert.equal(after.status, 404);
236 });
test/final-acceptance-contract.test.js
+2 -1
@@ -2,7 +2,8 @@ import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import fs from 'node:fs';
4
5 -const read = path => fs.readFileSync(new URL(`../${path}`, import.meta.url), 'utf8');
5 +const read = (path) =>
6 + fs.readFileSync(new URL(`../${path}`, import.meta.url), 'utf8');
7
8 test('final acceptance record closes workspace, exhaustive menu and security gates', () => {
9 const acceptance = read('docs/FINAL_ACCEPTANCE_V2_1.md');
test/final-delivery.test.js
+24 -6
@@ -1,6 +1,10 @@
1 import test from 'node:test';
2 import assert from 'node:assert/strict';
3 -import { evaluateFinalDelivery, getFinalDeliveryRows, renderFinalDeliverySummary } from '../src/core/final-delivery.js';
3 +import {
4 + evaluateFinalDelivery,
5 + getFinalDeliveryRows,
6 + renderFinalDeliverySummary
7 +} from '../src/core/final-delivery.js';
8
9 const accepted = {
10 mainSha: '3fdcbe613b02768a24a3bbfbf66fb247a0897092',
@@ -19,24 +23,38 @@ const accepted = {
23 };
24
25 test('rows 16-20 are explicit and stable', () => {
22 - assert.deepEqual(getFinalDeliveryRows().map(row => row.id), [16, 17, 18, 19, 20]);
26 + assert.deepEqual(
27 + getFinalDeliveryRows().map((row) => row.id),
28 + [16, 17, 18, 19, 20]
29 + );
30 });
31
32 test('final acceptance is fail closed when evidence is absent', () => {
33 const report = evaluateFinalDelivery({});
34 assert.equal(report.complete, false);
28 - assert.equal(report.rows.every(row => row.complete === false), true);
35 + assert.equal(
36 + report.rows.every((row) => row.complete === false),
37 + true
38 + );
39 });
40
41 test('final acceptance passes only with all required evidence', () => {
42 const report = evaluateFinalDelivery(accepted);
43 assert.equal(report.complete, true);
34 - assert.equal(report.rows.every(row => row.complete), true);
35 - assert.match(renderFinalDeliverySummary(accepted), /Final delivery: ACCEPTED/);
44 + assert.equal(
45 + report.rows.every((row) => row.complete),
46 + true
47 + );
48 + assert.match(
49 + renderFinalDeliverySummary(accepted),
50 + /Final delivery: ACCEPTED/
51 + );
52 });
53
54 test('one failed runtime gate blocks the whole delivery', () => {
55 const report = evaluateFinalDelivery({ ...accepted, runtimeHealthy: false });
56 assert.equal(report.complete, false);
41 - assert.deepEqual(report.rows.find(row => row.id === 17).missing, ['runtimeHealthy']);
57 + assert.deepEqual(report.rows.find((row) => row.id === 17).missing, [
58 + 'runtimeHealthy'
59 + ]);
60 });
test/github-advanced-plugin.test.js
+260 -35
@@ -6,30 +6,184 @@ import { githubPluginManifest } from '../src/plugins/github/manifest.js';
6 const sha = 'a'.repeat(40);
7
8 function callbacks(view) {
9 - return (view?.reply_markup?.inline_keyboard || []).flat().map(button => button.callback_data).filter(Boolean);
9 + return (view?.reply_markup?.inline_keyboard || [])
10 + .flat()
11 + .map((button) => button.callback_data)
12 + .filter(Boolean);
13 }
14
15 function makeGitHub() {
16 const calls = [];
14 - const hit = (name, value) => { calls.push([name, value]); return value; };
17 + const hit = (name, value) => {
18 + calls.push([name, value]);
19 + return value;
20 + };
21 return {
22 calls,
17 - async getRepository(id) { return hit('getRepository', { id: String(id), name: 'nexa-dev-bot', defaultBranch: 'main' }); },
18 - async listWorkflowRuns() { return [{ id: 77, name: 'CI', status: 'completed', conclusion: 'success', branch: 'main', sha: 'abc1234', runNumber: 44 }]; },
19 - async getWorkflowRun(repo, run) { return hit('getWorkflowRun', { id: run, name: 'CI', status: 'completed', conclusion: 'failure', runNumber: 134, branch: 'main', sha: 'abc1234', event: 'push' }); },
20 - async listWorkflowJobs() { return hit('listWorkflowJobs', [{ id: 88, name: 'test', status: 'completed', conclusion: 'failure', steps: [{ number: 1, name: 'Run tests', conclusion: 'failure' }] }]); },
21 - async getWorkflowJob() { return hit('getWorkflowJob', { id: 88, name: 'test', status: 'completed', conclusion: 'failure', steps: [{ number: 1, name: 'Run tests', conclusion: 'failure' }] }); },
22 - async getWorkflowJobLog() { return hit('getWorkflowJobLog', { text: '<token>\nFAIL expected', truncated: true }); },
23 - async listWorkflowArtifacts() { return hit('listWorkflowArtifacts', [{ id: 9, name: 'coverage', size: 1234, expired: false, createdAt: '2026-10-03T00:00:00Z', expiresAt: '2026-10-10T00:00:00Z' }]); },
24 - async listBranches() { return hit('listBranches', [{ name: 'feature/x', sha, protected: false }]); },
25 - async compareWithDefault() { return hit('compareWithDefault', { base: 'main', head: sha, status: 'ahead', aheadBy: 2, behindBy: 0, totalCommits: 2, files: [{ filename: 'src/x.js', status: 'modified', additions: 3, deletions: 1, changes: 4, patch: '+x' }] }); },
26 - async listPullRequests() { return hit('listPullRequests', [{ number: 19, title: 'Feature', author: 'dev', state: 'open', merged: false }]); },
27 - async getPullRequest() { return hit('getPullRequest', { number: 19, title: 'Feature', author: 'dev', state: 'open', merged: false, body: 'Body', head: 'feature/x', headSha: sha, base: 'main', additions: 3, deletions: 1, changedFiles: 1 }); },
28 - async listPullRequestFiles() { return hit('listPullRequestFiles', [{ filename: 'src/x.js', status: 'modified', additions: 3, deletions: 1, changes: 4, patch: '+x' }]); },
29 - async listCommitChecks() { return hit('listCommitChecks', [{ id: 7, name: 'CI', status: 'completed', conclusion: 'success' }]); },
30 - async listIssues() { return hit('listIssues', [{ number: 4, title: 'Bug', state: 'open', author: 'u', comments: 2 }]); },
31 - async listIssuesPage() { return hit('listIssuesPage', { items: [{ number: 4, title: 'Bug', state: 'open', author: 'u', comments: 2 }], hasMore: false }); },
32 - async listReleases() { return hit('listReleases', [{ id: 6, tag: 'v1.2.0', name: 'Release 1.2', draft: false, prerelease: false, publishedAt: '2026-10-03T00:00:00Z' }]); },
23 + async getRepository(id) {
24 + return hit('getRepository', {
25 + id: String(id),
26 + name: 'nexa-dev-bot',
27 + defaultBranch: 'main'
28 + });
29 + },
30 + async listWorkflowRuns() {
31 + return [
32 + {
33 + id: 77,
34 + name: 'CI',
35 + status: 'completed',
36 + conclusion: 'success',
37 + branch: 'main',
38 + sha: 'abc1234',
39 + runNumber: 44
40 + }
41 + ];
42 + },
43 + async getWorkflowRun(repo, run) {
44 + return hit('getWorkflowRun', {
45 + id: run,
46 + name: 'CI',
47 + status: 'completed',
48 + conclusion: 'failure',
49 + runNumber: 134,
50 + branch: 'main',
51 + sha: 'abc1234',
52 + event: 'push'
53 + });
54 + },
55 + async listWorkflowJobs() {
56 + return hit('listWorkflowJobs', [
57 + {
58 + id: 88,
59 + name: 'test',
60 + status: 'completed',
61 + conclusion: 'failure',
62 + steps: [{ number: 1, name: 'Run tests', conclusion: 'failure' }]
63 + }
64 + ]);
65 + },
66 + async getWorkflowJob() {
67 + return hit('getWorkflowJob', {
68 + id: 88,
69 + name: 'test',
70 + status: 'completed',
71 + conclusion: 'failure',
72 + steps: [{ number: 1, name: 'Run tests', conclusion: 'failure' }]
73 + });
74 + },
75 + async getWorkflowJobLog() {
76 + return hit('getWorkflowJobLog', {
77 + text: '<token>\nFAIL expected',
78 + truncated: true
79 + });
80 + },
81 + async listWorkflowArtifacts() {
82 + return hit('listWorkflowArtifacts', [
83 + {
84 + id: 9,
85 + name: 'coverage',
86 + size: 1234,
87 + expired: false,
88 + createdAt: '2026-10-03T00:00:00Z',
89 + expiresAt: '2026-10-10T00:00:00Z'
90 + }
91 + ]);
92 + },
93 + async listBranches() {
94 + return hit('listBranches', [
95 + { name: 'feature/x', sha, protected: false }
96 + ]);
97 + },
98 + async compareWithDefault() {
99 + return hit('compareWithDefault', {
100 + base: 'main',
101 + head: sha,
102 + status: 'ahead',
103 + aheadBy: 2,
104 + behindBy: 0,
105 + totalCommits: 2,
106 + files: [
107 + {
108 + filename: 'src/x.js',
109 + status: 'modified',
110 + additions: 3,
111 + deletions: 1,
112 + changes: 4,
113 + patch: '+x'
114 + }
115 + ]
116 + });
117 + },
118 + async listPullRequests() {
119 + return hit('listPullRequests', [
120 + {
121 + number: 19,
122 + title: 'Feature',
123 + author: 'dev',
124 + state: 'open',
125 + merged: false
126 + }
127 + ]);
128 + },
129 + async getPullRequest() {
130 + return hit('getPullRequest', {
131 + number: 19,
132 + title: 'Feature',
133 + author: 'dev',
134 + state: 'open',
135 + merged: false,
136 + body: 'Body',
137 + head: 'feature/x',
138 + headSha: sha,
139 + base: 'main',
140 + additions: 3,
141 + deletions: 1,
142 + changedFiles: 1
143 + });
144 + },
145 + async listPullRequestFiles() {
146 + return hit('listPullRequestFiles', [
147 + {
148 + filename: 'src/x.js',
149 + status: 'modified',
150 + additions: 3,
151 + deletions: 1,
152 + changes: 4,
153 + patch: '+x'
154 + }
155 + ]);
156 + },
157 + async listCommitChecks() {
158 + return hit('listCommitChecks', [
159 + { id: 7, name: 'CI', status: 'completed', conclusion: 'success' }
160 + ]);
161 + },
162 + async listIssues() {
163 + return hit('listIssues', [
164 + { number: 4, title: 'Bug', state: 'open', author: 'u', comments: 2 }
165 + ]);
166 + },
167 + async listIssuesPage() {
168 + return hit('listIssuesPage', {
169 + items: [
170 + { number: 4, title: 'Bug', state: 'open', author: 'u', comments: 2 }
171 + ],
172 + hasMore: false
173 + });
174 + },
175 + async listReleases() {
176 + return hit('listReleases', [
177 + {
178 + id: 6,
179 + tag: 'v1.2.0',
180 + name: 'Release 1.2',
181 + draft: false,
182 + prerelease: false,
183 + publishedAt: '2026-10-03T00:00:00Z'
184 + }
185 + ]);
186 + },
187 async rerunFailedWorkflowRun() {},
188 async cancelWorkflowRun() {}
189 };
@@ -37,11 +191,24 @@ function makeGitHub() {
191
192 function makeMenu() {
193 return {
40 - async getReposListView() { return { text: 'repos', reply_markup: { inline_keyboard: [] } }; },
194 + async getReposListView() {
195 + return { text: 'repos', reply_markup: { inline_keyboard: [] } };
196 + },
197 async renderByCallback(data) {
198 if (String(data).startsWith('repo:')) {
199 const repoId = String(data).split(':')[1];
44 - return { text: 'repo', reply_markup: { inline_keyboard: [[{ text: 'PRها', callback_data: `pr:${repoId}` }, { text: 'وضعیت', callback_data: `status:${repoId}` }], [{ text: 'back', callback_data: 'menu:repos' }]] } };
200 + return {
201 + text: 'repo',
202 + reply_markup: {
203 + inline_keyboard: [
204 + [
205 + { text: 'PRها', callback_data: `pr:${repoId}` },
206 + { text: 'وضعیت', callback_data: `status:${repoId}` }
207 + ],
208 + [{ text: 'back', callback_data: 'menu:repos' }]
209 + ]
210 + }
211 + };
212 }
213 return { text: `legacy:${data}`, reply_markup: { inline_keyboard: [] } };
214 }
@@ -49,13 +216,26 @@ function makeMenu() {
216 }
217
218 const advancedReadActions = [
52 - 'github.workflow.job.detail', 'github.workflow.job.log', 'github.workflow.artifacts.list',
53 - 'github.branches.list', 'github.compare.read', 'github.pr.advanced.list', 'github.pr.detail',
54 - 'github.pr.files.list', 'github.pr.checks.list', 'github.issues.list', 'github.releases.list'
219 + 'github.workflow.job.detail',
220 + 'github.workflow.job.log',
221 + 'github.workflow.artifacts.list',
222 + 'github.branches.list',
223 + 'github.compare.read',
224 + 'github.pr.advanced.list',
225 + 'github.pr.detail',
226 + 'github.pr.files.list',
227 + 'github.pr.checks.list',
228 + 'github.issues.list',
229 + 'github.releases.list'
230 ];
231
232 test('GitHub Advanced manifest declares every new action as READ', () => {
58 - for (const actionId of advancedReadActions) assert.equal(githubPluginManifest.actions[actionId]?.risk, 'READ', actionId);
233 + for (const actionId of advancedReadActions)
234 + assert.equal(
235 + githubPluginManifest.actions[actionId]?.risk,
236 + 'READ',
237 + actionId
238 + );
239 });
240
241 test('advanced callbacks resolve without provider side effects and callbacks stay Telegram-safe', async () => {
@@ -77,9 +257,17 @@ test('advanced callbacks resolve without provider side effects and callbacks sta
257 for (const [data, actionId] of samples) {
258 const route = plugin.resolveCallback(data);
259 assert.equal(route?.actionId, actionId, data);
80 - assert.equal(github.calls.length, 0, `provider called during resolve: ${data}`);
260 + assert.equal(
261 + github.calls.length,
262 + 0,
263 + `provider called during resolve: ${data}`
264 + );
265 const view = await route.execute();
82 - for (const callback of callbacks(view)) assert.ok(callback.length <= 64, `${callback} exceeds Telegram callback_data limit`);
266 + for (const callback of callbacks(view))
267 + assert.ok(
268 + callback.length <= 64,
269 + `${callback} exceeds Telegram callback_data limit`
270 + );
271 github.calls.length = 0;
272 }
273 });
@@ -89,9 +277,22 @@ test('repository and workflow views expose Advanced READ navigation', async () =
277 const plugin = createGitHubPlugin({ github, menu: makeMenu() });
278 const repoView = await plugin.resolveCallback('repo:123').execute();
279 const repoCallbacks = callbacks(repoView);
92 - for (const expected of ['status:123', 'branches:123', 'pr:123', 'issues:123', 'releases:123']) assert.ok(repoCallbacks.includes(expected), expected);
93 - assert.ok(!repoCallbacks.includes('prs:123'), 'repository view must not expose a duplicate advanced PR entry');
94 - assert.ok(!repoCallbacks.includes('runs:123'), 'repository view must not expose a duplicate CI entry');
280 + for (const expected of [
281 + 'status:123',
282 + 'branches:123',
283 + 'pr:123',
284 + 'issues:123',
285 + 'releases:123'
286 + ])
287 + assert.ok(repoCallbacks.includes(expected), expected);
288 + assert.ok(
289 + !repoCallbacks.includes('prs:123'),
290 + 'repository view must not expose a duplicate advanced PR entry'
291 + );
292 + assert.ok(
293 + !repoCallbacks.includes('runs:123'),
294 + 'repository view must not expose a duplicate CI entry'
295 + );
296
297 const runView = await plugin.resolveCallback('run:123:77').execute();
298 assert.ok(callbacks(runView).includes('artifacts:123:77'));
@@ -108,7 +309,10 @@ test('legacy repository status button resolves to actionable workflow runs', asy
309 const route = plugin.resolveCallback('status:123');
310 assert.equal(route?.actionId, 'github.workflow.runs.list');
311 const view = await route.execute();
111 - assert.ok(callbacks(view).includes('run:123:77'), 'repository status button must drill into workflow run detail');
312 + assert.ok(
313 + callbacks(view).includes('run:123:77'),
314 + 'repository status button must drill into workflow run detail'
315 + );
316 });
317
318 test('legacy repository PR button resolves to the actionable advanced PR report', async () => {
@@ -116,7 +320,10 @@ test('legacy repository PR button resolves to the actionable advanced PR report'
320 const route = plugin.resolveCallback('pr:123');
321 assert.equal(route?.actionId, 'github.pr.advanced.list');
322 const view = await route.execute();
119 - assert.ok(callbacks(view).includes('prdetail:123:19'), 'repository PR button must drill into PR detail');
323 + assert.ok(
324 + callbacks(view).includes('prdetail:123:19'),
325 + 'repository PR button must drill into PR detail'
326 + );
327 });
328
329 test('failed job log is escaped and bounded-tail state is visible', async () => {
@@ -149,13 +356,22 @@ test('artifacts support bounded page navigation instead of silently stopping at
356 const github = makeGitHub();
357 github.listWorkflowArtifacts = async (repoId, runId, options) => {
358 calls.push({ repoId, runId, options });
152 - return Array.from({ length: 10 }, (_, i) => ({ id: i + 1, name: `artifact-${i + 1}`, size: 1, expired: false }));
359 + return Array.from({ length: 10 }, (_, i) => ({
360 + id: i + 1,
361 + name: `artifact-${i + 1}`,
362 + size: 1,
363 + expired: false
364 + }));
365 };
366 const plugin = createGitHubPlugin({ github, menu: makeMenu() });
367 const route = plugin.resolveCallback('artifacts:123:77:2');
368 assert.equal(route?.actionId, 'github.workflow.artifacts.list');
369 const view = await route.execute();
158 - assert.deepEqual(calls[0], { repoId: 123, runId: 77, options: { perPage: 10, page: 2 } });
370 + assert.deepEqual(calls[0], {
371 + repoId: 123,
372 + runId: 77,
373 + options: { perPage: 10, page: 2 }
374 + });
375 assert.ok(callbacks(view).includes('artifacts:123:77:1'));
376 assert.ok(callbacks(view).includes('artifacts:123:77:3'));
377 });
@@ -166,12 +382,21 @@ test('PR diff pages request only the number of files they can render and expose
382 github.listPullRequestFiles = async (repoId, prNumber, options) => {
383 calls.push({ repoId, prNumber, options });
384 return Array.from({ length: 8 }, (_, i) => ({
169 - filename: `src/file-${i + 1}.js`, status: 'modified', additions: 1, deletions: 0, changes: 1, patch: '+x'
385 + filename: `src/file-${i + 1}.js`,
386 + status: 'modified',
387 + additions: 1,
388 + deletions: 0,
389 + changes: 1,
390 + patch: '+x'
391 }));
392 };
393 const plugin = createGitHubPlugin({ github, menu: makeMenu() });
394 const view = await plugin.resolveCallback('prfiles:123:19:1').execute();
174 - assert.deepEqual(calls[0], { repoId: 123, prNumber: 19, options: { perPage: 8, page: 1 } });
395 + assert.deepEqual(calls[0], {
396 + repoId: 123,
397 + prNumber: 19,
398 + options: { perPage: 8, page: 1 }
399 + });
400 assert.match(view.text, /file-8\.js/);
401 assert.ok(callbacks(view).includes('prfiles:123:19:2'));
402 });
test/github-advanced-read-error-ui.test.js
+13 -3
@@ -10,12 +10,19 @@ test('Advanced READ provider failures visibly update Telegram instead of appeari
10 });
11 const edits = [];
12 bot.telegram.answerCallbackQuery = async () => ({ ok: true });
13 - bot.telegram.editMessageText = async (chatId, messageId, text, replyMarkup) => {
13 + bot.telegram.editMessageText = async (
14 + chatId,
15 + messageId,
16 + text,
17 + replyMarkup
18 + ) => {
19 edits.push({ chatId, messageId, text, replyMarkup });
20 return { ok: true };
21 };
22 bot.router.dispatchCallback = async () => {
18 - throw new Error('GitHub check runs failed: 403 Resource not accessible by personal access token');
23 + throw new Error(
24 + 'GitHub check runs failed: 403 Resource not accessible by personal access token'
25 + );
26 };
27
28 const result = await bot.handleCallbackQuery({
@@ -30,5 +37,8 @@ test('Advanced READ provider failures visibly update Telegram instead of appeari
37 assert.equal(edits.length, 1);
38 assert.match(edits[0].text, /دریافت اطلاعات|خطا/);
39 assert.match(edits[0].text, /مجوز|دسترسی/);
33 - assert.doesNotMatch(edits[0].text, /github-test-token|telegram-test-token|webhook-test-secret/);
40 + assert.doesNotMatch(
41 + edits[0].text,
42 + /github-test-token|telegram-test-token|webhook-test-secret/
43 + );
44 });
test/github-advanced-read.test.js
+294 -92
@@ -5,11 +5,18 @@ import { GitHubService } from '../src/github.js';
5 async function withFetch(mock, fn) {
6 const originalFetch = globalThis.fetch;
7 globalThis.fetch = mock;
8 - try { return await fn(); } finally { globalThis.fetch = originalFetch; }
8 + try {
9 + return await fn();
10 + } finally {
11 + globalThis.fetch = originalFetch;
12 + }
13 }
14
15 function json(data, status = 200) {
12 - return new Response(JSON.stringify(data), { status, headers: { 'content-type': 'application/json' } });
16 + return new Response(JSON.stringify(data), {
17 + status,
18 + headers: { 'content-type': 'application/json' }
19 + });
20 }
21
22 const repo = {
@@ -24,113 +31,308 @@ const repoUrl = 'https://api.github.com/repos/davoodmehraban89/nexa-dev-bot';
31
32 test('GitHub Advanced reads expose job detail and bounded raw job logs', async () => {
33 const calls = [];
27 - await withFetch(async (url) => {
28 - const value = String(url); calls.push(value);
29 - if (value === 'https://api.github.com/repositories/123') return json(repo);
30 - if (value === `${repoUrl}/actions/jobs/88`) return json({ id: 88, name: 'test', status: 'completed', conclusion: 'failure', steps: [] });
31 - if (value === `${repoUrl}/actions/jobs/88/logs`) return new Response('0123456789ABCDEFGHIJ', { status: 200 });
32 - return json({ message: 'Not Found' }, 404);
33 - }, async () => {
34 - const service = new GitHubService('token');
35 - const job = await service.getWorkflowJob(123, 88);
36 - assert.equal(job.id, 88);
37 - const log = await service.getWorkflowJobLog(123, 88, { maxChars: 10 });
38 - assert.deepEqual(log, { text: 'ABCDEFGHIJ', truncated: true });
39 - assert.ok(calls.includes(`${repoUrl}/actions/jobs/88/logs`));
40 - });
34 + await withFetch(
35 + async (url) => {
36 + const value = String(url);
37 + calls.push(value);
38 + if (value === 'https://api.github.com/repositories/123')
39 + return json(repo);
40 + if (value === `${repoUrl}/actions/jobs/88`)
41 + return json({
42 + id: 88,
43 + name: 'test',
44 + status: 'completed',
45 + conclusion: 'failure',
46 + steps: []
47 + });
48 + if (value === `${repoUrl}/actions/jobs/88/logs`)
49 + return new Response('0123456789ABCDEFGHIJ', { status: 200 });
50 + return json({ message: 'Not Found' }, 404);
51 + },
52 + async () => {
53 + const service = new GitHubService('token');
54 + const job = await service.getWorkflowJob(123, 88);
55 + assert.equal(job.id, 88);
56 + const log = await service.getWorkflowJobLog(123, 88, { maxChars: 10 });
57 + assert.deepEqual(log, { text: 'ABCDEFGHIJ', truncated: true });
58 + assert.ok(calls.includes(`${repoUrl}/actions/jobs/88/logs`));
59 + }
60 + );
61 });
62
63 test('GitHub Advanced reads list bounded workflow artifacts and branches', async () => {
64 const calls = [];
45 - await withFetch(async (url) => {
46 - const value = String(url); calls.push(value);
47 - if (value === 'https://api.github.com/repositories/123') return json(repo);
48 - if (value === `${repoUrl}/actions/runs/77/artifacts?per_page=20&page=100`) return json({ artifacts: [{ id: 9, name: 'coverage', size_in_bytes: 1234, expired: false, created_at: '2026-10-03T00:00:00Z', expires_at: '2026-10-10T00:00:00Z', archive_download_url: 'https://api.github.com/a' }] });
49 - if (value === `${repoUrl}/branches?per_page=20&page=100`) return json([{ name: 'feature/x', commit: { sha: 'a'.repeat(40) }, protected: false }]);
50 - return json({ message: 'Not Found' }, 404);
51 - }, async () => {
52 - const service = new GitHubService('token');
53 - const artifacts = await service.listWorkflowArtifacts(123, 77, { perPage: 999, page: 999 });
54 - assert.deepEqual(artifacts[0], { id: 9, name: 'coverage', size: 1234, expired: false, createdAt: '2026-10-03T00:00:00Z', expiresAt: '2026-10-10T00:00:00Z', downloadUrl: 'https://api.github.com/a' });
55 - const branches = await service.listBranches(123, { perPage: 999, page: 999 });
56 - assert.deepEqual(branches[0], { name: 'feature/x', sha: 'a'.repeat(40), protected: false });
57 - });
65 + await withFetch(
66 + async (url) => {
67 + const value = String(url);
68 + calls.push(value);
69 + if (value === 'https://api.github.com/repositories/123')
70 + return json(repo);
71 + if (value === `${repoUrl}/actions/runs/77/artifacts?per_page=20&page=100`)
72 + return json({
73 + artifacts: [
74 + {
75 + id: 9,
76 + name: 'coverage',
77 + size_in_bytes: 1234,
78 + expired: false,
79 + created_at: '2026-10-03T00:00:00Z',
80 + expires_at: '2026-10-10T00:00:00Z',
81 + archive_download_url: 'https://api.github.com/a'
82 + }
83 + ]
84 + });
85 + if (value === `${repoUrl}/branches?per_page=20&page=100`)
86 + return json([
87 + {
88 + name: 'feature/x',
89 + commit: { sha: 'a'.repeat(40) },
90 + protected: false
91 + }
92 + ]);
93 + return json({ message: 'Not Found' }, 404);
94 + },
95 + async () => {
96 + const service = new GitHubService('token');
97 + const artifacts = await service.listWorkflowArtifacts(123, 77, {
98 + perPage: 999,
99 + page: 999
100 + });
101 + assert.deepEqual(artifacts[0], {
102 + id: 9,
103 + name: 'coverage',
104 + size: 1234,
105 + expired: false,
106 + createdAt: '2026-10-03T00:00:00Z',
107 + expiresAt: '2026-10-10T00:00:00Z',
108 + downloadUrl: 'https://api.github.com/a'
109 + });
110 + const branches = await service.listBranches(123, {
111 + perPage: 999,
112 + page: 999
113 + });
114 + assert.deepEqual(branches[0], {
115 + name: 'feature/x',
116 + sha: 'a'.repeat(40),
117 + protected: false
118 + });
119 + }
120 + );
121 });
122
123 test('GitHub compare validates a 40-hex head and returns bounded file summaries', async () => {
124 const head = 'b'.repeat(40);
62 - await withFetch(async (url) => {
63 - const value = String(url);
64 - if (value === 'https://api.github.com/repositories/123') return json(repo);
65 - if (value === `${repoUrl}/compare/main...${head}`) return json({ status: 'ahead', ahead_by: 2, behind_by: 0, total_commits: 2, base_commit: { sha: 'a'.repeat(40) }, merge_base_commit: { sha: 'c'.repeat(40) }, files: [{ filename: 'src/x.js', status: 'modified', additions: 3, deletions: 1, changes: 4, patch: '+'.repeat(2000) }] });
66 - return json({ message: 'Not Found' }, 404);
67 - }, async () => {
68 - const service = new GitHubService('token');
69 - await assert.rejects(() => service.compareWithDefault(123, 'not-a-sha'), /SHA/i);
70 - const result = await service.compareWithDefault(123, head);
71 - assert.equal(result.base, 'main');
72 - assert.equal(result.head, head);
73 - assert.equal(result.aheadBy, 2);
74 - assert.ok(result.files[0].patch.length <= 1200);
75 - });
125 + await withFetch(
126 + async (url) => {
127 + const value = String(url);
128 + if (value === 'https://api.github.com/repositories/123')
129 + return json(repo);
130 + if (value === `${repoUrl}/compare/main...${head}`)
131 + return json({
132 + status: 'ahead',
133 + ahead_by: 2,
134 + behind_by: 0,
135 + total_commits: 2,
136 + base_commit: { sha: 'a'.repeat(40) },
137 + merge_base_commit: { sha: 'c'.repeat(40) },
138 + files: [
139 + {
140 + filename: 'src/x.js',
141 + status: 'modified',
142 + additions: 3,
143 + deletions: 1,
144 + changes: 4,
145 + patch: '+'.repeat(2000)
146 + }
147 + ]
148 + });
149 + return json({ message: 'Not Found' }, 404);
150 + },
151 + async () => {
152 + const service = new GitHubService('token');
153 + await assert.rejects(
154 + () => service.compareWithDefault(123, 'not-a-sha'),
155 + /SHA/i
156 + );
157 + const result = await service.compareWithDefault(123, head);
158 + assert.equal(result.base, 'main');
159 + assert.equal(result.head, head);
160 + assert.equal(result.aheadBy, 2);
161 + assert.ok(result.files[0].patch.length <= 1200);
162 + }
163 + );
164 });
165
166 test('GitHub PR detail exposes files and checks with bounded pagination', async () => {
167 const sha = 'd'.repeat(40);
80 - await withFetch(async (url) => {
81 - const value = String(url);
82 - if (value === 'https://api.github.com/repositories/123') return json(repo);
83 - if (value === `${repoUrl}/pulls/18`) return json({ number: 18, title: 'feat', state: 'open', merged: false, user: { login: 'dev' }, body: 'body', html_url: 'https://github.com/x/pull/18', head: { ref: 'feat/x', sha }, base: { ref: 'main' }, additions: 10, deletions: 2, changed_files: 1 });
84 - if (value === `${repoUrl}/pulls/18/files?per_page=20&page=100`) return json([{ filename: 'src/x.js', status: 'modified', additions: 10, deletions: 2, changes: 12, patch: '+'.repeat(2000) }]);
85 - if (value === `${repoUrl}/commits/${sha}/check-runs?per_page=20&page=100`) return json({ check_runs: [{ id: 7, name: 'CI', status: 'completed', conclusion: 'success', html_url: 'https://github.com/check/7' }] });
86 - return json({ message: 'Not Found' }, 404);
87 - }, async () => {
88 - const service = new GitHubService('token');
89 - const pr = await service.getPullRequest(123, 18);
90 - assert.equal(pr.headSha, sha);
91 - const files = await service.listPullRequestFiles(123, 18, { perPage: 999, page: 999 });
92 - assert.ok(files[0].patch.length <= 1200);
93 - const checks = await service.listCommitChecks(123, sha, { perPage: 999, page: 999 });
94 - assert.deepEqual(checks[0], { id: 7, name: 'CI', status: 'completed', conclusion: 'success', url: 'https://github.com/check/7' });
95 - });
168 + await withFetch(
169 + async (url) => {
170 + const value = String(url);
171 + if (value === 'https://api.github.com/repositories/123')
172 + return json(repo);
173 + if (value === `${repoUrl}/pulls/18`)
174 + return json({
175 + number: 18,
176 + title: 'feat',
177 + state: 'open',
178 + merged: false,
179 + user: { login: 'dev' },
180 + body: 'body',
181 + html_url: 'https://github.com/x/pull/18',
182 + head: { ref: 'feat/x', sha },
183 + base: { ref: 'main' },
184 + additions: 10,
185 + deletions: 2,
186 + changed_files: 1
187 + });
188 + if (value === `${repoUrl}/pulls/18/files?per_page=20&page=100`)
189 + return json([
190 + {
191 + filename: 'src/x.js',
192 + status: 'modified',
193 + additions: 10,
194 + deletions: 2,
195 + changes: 12,
196 + patch: '+'.repeat(2000)
197 + }
198 + ]);
199 + if (value === `${repoUrl}/commits/${sha}/check-runs?per_page=20&page=100`)
200 + return json({
201 + check_runs: [
202 + {
203 + id: 7,
204 + name: 'CI',
205 + status: 'completed',
206 + conclusion: 'success',
207 + html_url: 'https://github.com/check/7'
208 + }
209 + ]
210 + });
211 + return json({ message: 'Not Found' }, 404);
212 + },
213 + async () => {
214 + const service = new GitHubService('token');
215 + const pr = await service.getPullRequest(123, 18);
216 + assert.equal(pr.headSha, sha);
217 + const files = await service.listPullRequestFiles(123, 18, {
218 + perPage: 999,
219 + page: 999
220 + });
221 + assert.ok(files[0].patch.length <= 1200);
222 + const checks = await service.listCommitChecks(123, sha, {
223 + perPage: 999,
224 + page: 999
225 + });
226 + assert.deepEqual(checks[0], {
227 + id: 7,
228 + name: 'CI',
229 + status: 'completed',
230 + conclusion: 'success',
231 + url: 'https://github.com/check/7'
232 + });
233 + }
234 + );
235 });
236
237 test('GitHub issues exclude pull requests and releases are source-backed', async () => {
99 - await withFetch(async (url) => {
100 - const value = String(url);
101 - if (value === 'https://api.github.com/repositories/123') return json(repo);
102 - if (value === `${repoUrl}/issues?state=all&per_page=10&page=2`) return json([{ number: 4, title: 'bug', state: 'open', user: { login: 'u' }, comments: 2, html_url: 'https://github.com/i/4' }, { number: 5, title: 'pr', pull_request: {}, state: 'open' }]);
103 - if (value === `${repoUrl}/releases?per_page=10&page=2`) return json([{ id: 6, tag_name: 'v1.2.0', name: 'Release 1.2', draft: false, prerelease: false, published_at: '2026-10-03T00:00:00Z', html_url: 'https://github.com/r/6' }]);
104 - return json({ message: 'Not Found' }, 404);
105 - }, async () => {
106 - const service = new GitHubService('token');
107 - const issues = await service.listIssues(123, { page: 2 });
108 - assert.equal(issues.length, 1);
109 - assert.equal(issues[0].number, 4);
110 - const releases = await service.listReleases(123, { page: 2 });
111 - assert.equal(releases[0].tag, 'v1.2.0');
112 - });
238 + await withFetch(
239 + async (url) => {
240 + const value = String(url);
241 + if (value === 'https://api.github.com/repositories/123')
242 + return json(repo);
243 + if (value === `${repoUrl}/issues?state=all&per_page=10&page=2`)
244 + return json([
245 + {
246 + number: 4,
247 + title: 'bug',
248 + state: 'open',
249 + user: { login: 'u' },
250 + comments: 2,
251 + html_url: 'https://github.com/i/4'
252 + },
253 + { number: 5, title: 'pr', pull_request: {}, state: 'open' }
254 + ]);
255 + if (value === `${repoUrl}/releases?per_page=10&page=2`)
256 + return json([
257 + {
258 + id: 6,
259 + tag_name: 'v1.2.0',
260 + name: 'Release 1.2',
261 + draft: false,
262 + prerelease: false,
263 + published_at: '2026-10-03T00:00:00Z',
264 + html_url: 'https://github.com/r/6'
265 + }
266 + ]);
267 + return json({ message: 'Not Found' }, 404);
268 + },
269 + async () => {
270 + const service = new GitHubService('token');
271 + const issues = await service.listIssues(123, { page: 2 });
272 + assert.equal(issues.length, 1);
273 + assert.equal(issues[0].number, 4);
274 + const releases = await service.listReleases(123, { page: 2 });
275 + assert.equal(releases[0].tag, 'v1.2.0');
276 + }
277 + );
278 });
279
115 -
280 test('GitHub commit detail is source-backed and returns bounded file summaries', async () => {
281 const sha = 'e'.repeat(40);
118 - await withFetch(async (url) => {
119 - const value = String(url);
120 - if (value === 'https://api.github.com/repositories/123') return json(repo);
121 - if (value === `${repoUrl}/commits?per_page=5`) return json([{ sha, commit: { message: 'subject\n\nbody', author: { name: 'Dev', date: '2026-10-04T12:00:00Z' } }, author: { login: 'dev' } }]);
122 - if (value === `${repoUrl}/commits/${sha}`) return json({ sha, commit: { message: 'subject\n\nbody', author: { name: 'Dev', date: '2026-10-04T12:00:00Z' } }, author: { login: 'dev' }, stats: { additions: 12, deletions: 4 }, files: [{ filename: 'src/menu.js', status: 'modified', additions: 8, deletions: 2, changes: 10 }] });
123 - return json({ message: 'Not Found' }, 404);
124 - }, async () => {
125 - const service = new GitHubService('token');
126 - const list = await service.listCommits(123);
127 - assert.equal(list[0].sha, sha.slice(0, 7));
128 - assert.equal(list[0].fullSha, sha);
129 - const detail = await service.getCommit(123, sha);
130 - assert.equal(detail.sha, sha);
131 - assert.equal(detail.message, 'subject\n\nbody');
132 - assert.equal(detail.additions, 12);
133 - assert.equal(detail.deletions, 4);
134 - assert.deepEqual(detail.files[0], { filename: 'src/menu.js', status: 'modified', additions: 8, deletions: 2, changes: 10 });
135 - });
282 + await withFetch(
283 + async (url) => {
284 + const value = String(url);
285 + if (value === 'https://api.github.com/repositories/123')
286 + return json(repo);
287 + if (value === `${repoUrl}/commits?per_page=5`)
288 + return json([
289 + {
290 + sha,
291 + commit: {
292 + message: 'subject\n\nbody',
293 + author: { name: 'Dev', date: '2026-10-04T12:00:00Z' }
294 + },
295 + author: { login: 'dev' }
296 + }
297 + ]);
298 + if (value === `${repoUrl}/commits/${sha}`)
299 + return json({
300 + sha,
301 + commit: {
302 + message: 'subject\n\nbody',
303 + author: { name: 'Dev', date: '2026-10-04T12:00:00Z' }
304 + },
305 + author: { login: 'dev' },
306 + stats: { additions: 12, deletions: 4 },
307 + files: [
308 + {
309 + filename: 'src/menu.js',
310 + status: 'modified',
311 + additions: 8,
312 + deletions: 2,
313 + changes: 10
314 + }
315 + ]
316 + });
317 + return json({ message: 'Not Found' }, 404);
318 + },
319 + async () => {
320 + const service = new GitHubService('token');
321 + const list = await service.listCommits(123);
322 + assert.equal(list[0].sha, sha.slice(0, 7));
323 + assert.equal(list[0].fullSha, sha);
324 + const detail = await service.getCommit(123, sha);
325 + assert.equal(detail.sha, sha);
326 + assert.equal(detail.message, 'subject\n\nbody');
327 + assert.equal(detail.additions, 12);
328 + assert.equal(detail.deletions, 4);
329 + assert.deepEqual(detail.files[0], {
330 + filename: 'src/menu.js',
331 + status: 'modified',
332 + additions: 8,
333 + deletions: 2,
334 + changes: 10
335 + });
336 + }
337 + );
338 });
test/github-advanced-write-completion.test.js
+111 -37
@@ -4,48 +4,122 @@ import { GitHubService } from '../src/github.js';
4 import { createGitHubPlugin } from '../src/plugins/github/plugin.js';
5 import { githubPluginManifest } from '../src/plugins/github/manifest.js';
6
7 -const json=(data,status=200)=>new Response(JSON.stringify(data),{status,headers:{'content-type':'application/json'}});
8 -const repoContext={id:123,name:'nexa-dev-bot',full_name:'davoodmehraban89/nexa-dev-bot',default_branch:'main',private:true};
7 +const json = (data, status = 200) =>
8 + new Response(JSON.stringify(data), {
9 + status,
10 + headers: { 'content-type': 'application/json' }
11 + });
12 +const repoContext = {
13 + id: 123,
14 + name: 'nexa-dev-bot',
15 + full_name: 'davoodmehraban89/nexa-dev-bot',
16 + default_branch: 'main',
17 + private: true
18 +};
19
10 -test('CP3 provider dispatches workflow and reruns a job using GitHub POST endpoints', async()=>{
11 - const calls=[]; const original=globalThis.fetch;
12 - globalThis.fetch=async(url,options={})=>{const value=String(url);calls.push({url:value,method:options.method||'GET',body:options.body});
13 - if(value==='https://api.github.com/repositories/123') return json(repoContext);
14 - if(value.endsWith('/actions/workflows/999/dispatches')) return new Response(null,{status:204});
15 - if(value.endsWith('/actions/jobs/88/rerun')) return new Response(null,{status:201});
16 - return json({message:'Not Found'},404);
20 +test('CP3 provider dispatches workflow and reruns a job using GitHub POST endpoints', async () => {
21 + const calls = [];
22 + const original = globalThis.fetch;
23 + globalThis.fetch = async (url, options = {}) => {
24 + const value = String(url);
25 + calls.push({
26 + url: value,
27 + method: options.method || 'GET',
28 + body: options.body
29 + });
30 + if (value === 'https://api.github.com/repositories/123')
31 + return json(repoContext);
32 + if (value.endsWith('/actions/workflows/999/dispatches'))
33 + return new Response(null, { status: 204 });
34 + if (value.endsWith('/actions/jobs/88/rerun'))
35 + return new Response(null, { status: 201 });
36 + return json({ message: 'Not Found' }, 404);
37 };
18 - try{
19 - const service=new GitHubService('token');
20 - assert.deepEqual(await service.dispatchWorkflow(123,999,{ref:'main',inputs:{mode:'safe'}}),{accepted:true,status:204});
21 - assert.deepEqual(await service.rerunJob(123,88),{accepted:true,status:201});
22 - const dispatch=calls.find(c=>c.url.endsWith('/actions/workflows/999/dispatches'));
23 - assert.equal(dispatch.method,'POST'); assert.deepEqual(JSON.parse(dispatch.body),{ref:'main',inputs:{mode:'safe'}});
24 - assert.equal(calls.find(c=>c.url.endsWith('/actions/jobs/88/rerun')).method,'POST');
25 - }finally{globalThis.fetch=original;}
38 + try {
39 + const service = new GitHubService('token');
40 + assert.deepEqual(
41 + await service.dispatchWorkflow(123, 999, {
42 + ref: 'main',
43 + inputs: { mode: 'safe' }
44 + }),
45 + { accepted: true, status: 204 }
46 + );
47 + assert.deepEqual(await service.rerunJob(123, 88), {
48 + accepted: true,
49 + status: 201
50 + });
51 + const dispatch = calls.find((c) =>
52 + c.url.endsWith('/actions/workflows/999/dispatches')
53 + );
54 + assert.equal(dispatch.method, 'POST');
55 + assert.deepEqual(JSON.parse(dispatch.body), {
56 + ref: 'main',
57 + inputs: { mode: 'safe' }
58 + });
59 + assert.equal(
60 + calls.find((c) => c.url.endsWith('/actions/jobs/88/rerun')).method,
61 + 'POST'
62 + );
63 + } finally {
64 + globalThis.fetch = original;
65 + }
66 });
67
28 -test('CP3 manifest declares workflow dispatch and job rerun as WRITE',()=>{
29 - assert.equal(githubPluginManifest.actions['github.workflow.dispatch']?.risk,'WRITE');
30 - assert.equal(githubPluginManifest.actions['github.workflow.job.rerun']?.risk,'WRITE');
68 +test('CP3 manifest declares workflow dispatch and job rerun as WRITE', () => {
69 + assert.equal(
70 + githubPluginManifest.actions['github.workflow.dispatch']?.risk,
71 + 'WRITE'
72 + );
73 + assert.equal(
74 + githubPluginManifest.actions['github.workflow.job.rerun']?.risk,
75 + 'WRITE'
76 + );
77 });
78
33 -test('CP3 source-backed callbacks require approval and do not mutate provider before approval',async()=>{
34 - const writes=[];
35 - const github={
36 - async getWorkflowRun(){return {id:77,name:'CI',status:'completed',conclusion:'failure',branch:'main',workflowId:999,runNumber:7};},
37 - async getWorkflowJob(){return {id:88,name:'test',status:'completed',conclusion:'failure'};},
38 - async dispatchWorkflow(...args){writes.push(['dispatch',...args]);},
39 - async rerunJob(...args){writes.push(['job',...args]);}
79 +test('CP3 source-backed callbacks require approval and do not mutate provider before approval', async () => {
80 + const writes = [];
81 + const github = {
82 + async getWorkflowRun() {
83 + return {
84 + id: 77,
85 + name: 'CI',
86 + status: 'completed',
87 + conclusion: 'failure',
88 + branch: 'main',
89 + workflowId: 999,
90 + runNumber: 7
91 + };
92 + },
93 + async getWorkflowJob() {
94 + return {
95 + id: 88,
96 + name: 'test',
97 + status: 'completed',
98 + conclusion: 'failure'
99 + };
100 + },
101 + async dispatchWorkflow(...args) {
102 + writes.push(['dispatch', ...args]);
103 + },
104 + async rerunJob(...args) {
105 + writes.push(['job', ...args]);
106 + }
107 };
41 - const menu={async renderByCallback(){return {text:'x',reply_markup:{inline_keyboard:[]}}},async getReposListView(){return {text:'r',reply_markup:{inline_keyboard:[]}}}};
42 - const plugin=createGitHubPlugin({github,menu});
43 - const dispatch=await plugin.resolveCallback('dispatchwf:123:77');
44 - assert.equal(dispatch.actionId,'github.workflow.dispatch');
45 - assert.deepEqual(dispatch.approval.input,{repoId:123,runId:77});
46 - assert.equal(writes.length,0);
47 - const rerun=await plugin.resolveCallback('rerunjob:123:88');
48 - assert.equal(rerun.actionId,'github.workflow.job.rerun');
49 - assert.deepEqual(rerun.approval.input,{repoId:123,runId:88,jobId:88});
50 - assert.equal(writes.length,0);
108 + const menu = {
109 + async renderByCallback() {
110 + return { text: 'x', reply_markup: { inline_keyboard: [] } };
111 + },
112 + async getReposListView() {
113 + return { text: 'r', reply_markup: { inline_keyboard: [] } };
114 + }
115 + };
116 + const plugin = createGitHubPlugin({ github, menu });
117 + const dispatch = await plugin.resolveCallback('dispatchwf:123:77');
118 + assert.equal(dispatch.actionId, 'github.workflow.dispatch');
119 + assert.deepEqual(dispatch.approval.input, { repoId: 123, runId: 77 });
120 + assert.equal(writes.length, 0);
121 + const rerun = await plugin.resolveCallback('rerunjob:123:88');
122 + assert.equal(rerun.actionId, 'github.workflow.job.rerun');
123 + assert.deepEqual(rerun.approval.input, { repoId: 123, runId: 88, jobId: 88 });
124 + assert.equal(writes.length, 0);
125 });
test/github-issues-pagination.test.js
+41 -11
@@ -12,18 +12,37 @@ const repo = {
12 };
13
14 function json(data, status = 200) {
15 - return new Response(JSON.stringify(data), { status, headers: { 'content-type': 'application/json' } });
15 + return new Response(JSON.stringify(data), {
16 + status,
17 + headers: { 'content-type': 'application/json' }
18 + });
19 }
20
21 test('GitHub issue page keeps raw-page hasMore even when pull requests are filtered out', async () => {
22 const originalFetch = globalThis.fetch;
20 - globalThis.fetch = async url => {
23 + globalThis.fetch = async (url) => {
24 const value = String(url);
25 if (value === 'https://api.github.com/repositories/123') return json(repo);
23 - if (value === 'https://api.github.com/repos/davoodmehraban89/nexa-dev-bot/issues?state=all&per_page=20&page=2') {
24 - const mixed = Array.from({ length: 20 }, (_, index) => index < 7
25 - ? { number: index + 1, title: `issue-${index + 1}`, state: 'open', user: { login: 'u' }, comments: 0 }
26 - : { number: index + 1, title: `pr-${index + 1}`, state: 'open', pull_request: {} });
26 + if (
27 + value ===
28 + 'https://api.github.com/repos/davoodmehraban89/nexa-dev-bot/issues?state=all&per_page=20&page=2'
29 + ) {
30 + const mixed = Array.from({ length: 20 }, (_, index) =>
31 + index < 7
32 + ? {
33 + number: index + 1,
34 + title: `issue-${index + 1}`,
35 + state: 'open',
36 + user: { login: 'u' },
37 + comments: 0
38 + }
39 + : {
40 + number: index + 1,
41 + title: `pr-${index + 1}`,
42 + state: 'open',
43 + pull_request: {}
44 + }
45 + );
46 return json(mixed);
47 }
48 return json({ message: 'Not Found' }, 404);
@@ -41,21 +60,32 @@ test('GitHub issue page keeps raw-page hasMore even when pull requests are filte
60
61 test('Issues view shows older-page navigation from provider hasMore, not filtered item count', async () => {
62 const github = {
44 - async getRepository() { return { id: '123', name: 'nexa-dev-bot', defaultBranch: 'main' }; },
63 + async getRepository() {
64 + return { id: '123', name: 'nexa-dev-bot', defaultBranch: 'main' };
65 + },
66 async listIssuesPage() {
67 return {
47 - items: [{ number: 4, title: 'Bug', state: 'open', author: 'u', comments: 0 }],
68 + items: [
69 + { number: 4, title: 'Bug', state: 'open', author: 'u', comments: 0 }
70 + ],
71 hasMore: true
72 };
73 }
74 };
75 const menu = {
53 - async getReposListView() { return { text: 'repos', reply_markup: { inline_keyboard: [] } }; },
54 - async renderByCallback() { return { text: 'legacy', reply_markup: { inline_keyboard: [] } }; }
76 + async getReposListView() {
77 + return { text: 'repos', reply_markup: { inline_keyboard: [] } };
78 + },
79 + async renderByCallback() {
80 + return { text: 'legacy', reply_markup: { inline_keyboard: [] } };
81 + }
82 };
83 const plugin = createGitHubPlugin({ github, menu });
84 const view = await plugin.resolveCallback('issues:123:2').execute();
58 - const callbacks = view.reply_markup.inline_keyboard.flat().map(button => button.callback_data).filter(Boolean);
85 + const callbacks = view.reply_markup.inline_keyboard
86 + .flat()
87 + .map((button) => button.callback_data)
88 + .filter(Boolean);
89 assert.ok(callbacks.includes('issues:123:1'));
90 assert.ok(callbacks.includes('issues:123:3'));
91 });
test/github-live-findings.test.js
+25 -7
@@ -11,12 +11,19 @@ test('Issues 403 tells the owner the exact fine-grained permission required', as
11 });
12 const edits = [];
13 bot.telegram.answerCallbackQuery = async () => ({ ok: true });
14 - bot.telegram.editMessageText = async (chatId, messageId, text, replyMarkup) => {
14 + bot.telegram.editMessageText = async (
15 + chatId,
16 + messageId,
17 + text,
18 + replyMarkup
19 + ) => {
20 edits.push({ chatId, messageId, text, replyMarkup });
21 return { ok: true };
22 };
23 bot.router.dispatchCallback = async () => {
19 - throw new Error('GitHub issues failed: 403 Resource not accessible by personal access token');
24 + throw new Error(
25 + 'GitHub issues failed: 403 Resource not accessible by personal access token'
26 + );
27 };
28
29 const result = await bot.handleCallbackQuery({
@@ -36,16 +43,27 @@ test('Issues 403 tells the owner the exact fine-grained permission required', as
43
44 test('empty Releases view clearly states that GitHub has no releases for the repository', async () => {
45 const github = {
39 - async getRepository(id) { return { id: String(id), name: 'nexa-dev-bot', defaultBranch: 'main' }; },
40 - async listReleases() { return []; }
46 + async getRepository(id) {
47 + return { id: String(id), name: 'nexa-dev-bot', defaultBranch: 'main' };
48 + },
49 + async listReleases() {
50 + return [];
51 + }
52 };
53 const menu = {
43 - async getReposListView() { return { text: 'repos', reply_markup: { inline_keyboard: [] } }; },
44 - async renderByCallback() { return { text: 'menu', reply_markup: { inline_keyboard: [] } }; }
54 + async getReposListView() {
55 + return { text: 'repos', reply_markup: { inline_keyboard: [] } };
56 + },
57 + async renderByCallback() {
58 + return { text: 'menu', reply_markup: { inline_keyboard: [] } };
59 + }
60 };
61 const plugin = createGitHubPlugin({ github, menu });
62 const view = await plugin.resolveCallback('releases:123').execute();
63
49 - assert.match(view.text, /هیچ Release منتشرشده‌ای برای این مخزن در GitHub وجود ندارد/);
64 + assert.match(
65 + view.text,
66 + /هیچ Release منتشرشده‌ای برای این مخزن در GitHub وجود ندارد/
67 + );
68 assert.doesNotMatch(view.text, /Releaseی یافت نشد/);
69 });
test/github-pagination.test.js
+36 -17
@@ -22,22 +22,35 @@ function json(data, status = 200) {
22
23 test('GitHubService requests a bounded workflow-runs page', async () => {
24 const requested = [];
25 - await withFetch(async url => {
26 - const value = String(url);
27 - requested.push(value);
28 - if (value === 'https://api.github.com/repositories/123') {
29 - return json({ id: 123, name: 'nexa-dev-bot', full_name: 'davoodmehraban89/nexa-dev-bot' });
30 - }
31 - if (value === 'https://api.github.com/repos/davoodmehraban89/nexa-dev-bot/actions/runs?per_page=10&page=2') {
32 - return json({ workflow_runs: [] });
25 + await withFetch(
26 + async (url) => {
27 + const value = String(url);
28 + requested.push(value);
29 + if (value === 'https://api.github.com/repositories/123') {
30 + return json({
31 + id: 123,
32 + name: 'nexa-dev-bot',
33 + full_name: 'davoodmehraban89/nexa-dev-bot'
34 + });
35 + }
36 + if (
37 + value ===
38 + 'https://api.github.com/repos/davoodmehraban89/nexa-dev-bot/actions/runs?per_page=10&page=2'
39 + ) {
40 + return json({ workflow_runs: [] });
41 + }
42 + return json({ message: 'Not Found' }, 404);
43 + },
44 + async () => {
45 + const service = new GitHubService('token');
46 + await service.listWorkflowRuns(123, { perPage: 10, page: 2 });
47 }
34 - return json({ message: 'Not Found' }, 404);
35 - }, async () => {
36 - const service = new GitHubService('token');
37 - await service.listWorkflowRuns(123, { perPage: 10, page: 2 });
38 - });
48 + );
49
40 - assert.equal(requested.at(-1), 'https://api.github.com/repos/davoodmehraban89/nexa-dev-bot/actions/runs?per_page=10&page=2');
50 + assert.equal(
51 + requested.at(-1),
52 + 'https://api.github.com/repos/davoodmehraban89/nexa-dev-bot/actions/runs?per_page=10&page=2'
53 + );
54 });
55
56 test('GitHub plugin navigates older and newer CI pages without write side effects', async () => {
@@ -60,8 +73,12 @@ test('GitHub plugin navigates older and newer CI pages without write side effect
73 }
74 };
75 const menu = {
63 - async getReposListView() { return { text: 'repos', reply_markup: { inline_keyboard: [] } }; },
64 - async renderByCallback(data) { return { text: data, reply_markup: { inline_keyboard: [] } }; }
76 + async getReposListView() {
77 + return { text: 'repos', reply_markup: { inline_keyboard: [] } };
78 + },
79 + async renderByCallback(data) {
80 + return { text: data, reply_markup: { inline_keyboard: [] } };
81 + }
82 };
83
84 const plugin = createGitHubPlugin({ github, menu });
@@ -72,7 +89,9 @@ test('GitHub plugin navigates older and newer CI pages without write side effect
89
90 const view = await route.execute();
91 assert.deepEqual(calls, [{ repoId: 123, options: { perPage: 10, page: 2 } }]);
75 - const callbacks = view.reply_markup.inline_keyboard.flat().map(button => button.callback_data);
92 + const callbacks = view.reply_markup.inline_keyboard
93 + .flat()
94 + .map((button) => button.callback_data);
95 assert.ok(callbacks.includes('runs:123:1'));
96 assert.ok(callbacks.includes('runs:123:3'));
97 });
test/github-plugin.test.js
+73 -28
@@ -37,19 +37,29 @@ function makeGitHub() {
37 },
38 async listPullRequests(repoId) {
39 calls.push(`pr:${repoId}`);
40 - return [{ number: 19, title: 'Feature', author: 'dev', state: 'open', merged: false }];
40 + return [
41 + {
42 + number: 19,
43 + title: 'Feature',
44 + author: 'dev',
45 + state: 'open',
46 + merged: false
47 + }
48 + ];
49 },
50 async listWorkflowRuns(repoId) {
51 calls.push(`runs:${repoId}`);
44 - return [{
45 - id: 77,
46 - name: 'CI',
47 - status: 'completed',
48 - conclusion: 'failure',
49 - branch: 'main',
50 - sha: 'abcdef0',
51 - runNumber: 12
52 - }];
52 + return [
53 + {
54 + id: 77,
55 + name: 'CI',
56 + status: 'completed',
57 + conclusion: 'failure',
58 + branch: 'main',
59 + sha: 'abcdef0',
60 + runNumber: 12
61 + }
62 + ];
63 },
64 async getWorkflowRun(repoId, runId) {
65 calls.push(`run:${repoId}:${runId}`);
@@ -65,16 +75,28 @@ function makeGitHub() {
75 },
76 async listWorkflowJobs(repoId, runId) {
77 calls.push(`jobs:${repoId}:${runId}`);
68 - return [{
69 - id: 88,
70 - name: 'test',
71 - status: 'completed',
72 - conclusion: 'failure',
73 - steps: [
74 - { number: 1, name: 'checkout', status: 'completed', conclusion: 'success' },
75 - { number: 2, name: 'test', status: 'completed', conclusion: 'failure' }
76 - ]
77 - }];
78 + return [
79 + {
80 + id: 88,
81 + name: 'test',
82 + status: 'completed',
83 + conclusion: 'failure',
84 + steps: [
85 + {
86 + number: 1,
87 + name: 'checkout',
88 + status: 'completed',
89 + conclusion: 'success'
90 + },
91 + {
92 + number: 2,
93 + name: 'test',
94 + status: 'completed',
95 + conclusion: 'failure'
96 + }
97 + ]
98 + }
99 + ];
100 },
101 async rerunFailedWorkflowRun(repoId, runId) {
102 calls.push(`rerun:${repoId}:${runId}`);
@@ -108,7 +130,10 @@ test('GitHub plugin manifest registers read and write workflow actions with expl
130 assert.equal(registry.getAction(actionId)?.risk, 'READ');
131 }
132
111 - assert.equal(registry.getAction('github.workflow.run.rerun_failed')?.risk, 'WRITE');
133 + assert.equal(
134 + registry.getAction('github.workflow.run.rerun_failed')?.risk,
135 + 'WRITE'
136 + );
137 assert.equal(registry.getAction('github.workflow.run.cancel')?.risk, 'WRITE');
138 });
139
@@ -148,8 +173,16 @@ test('GitHub plugin maps read callback families to declared actions without eage
173 const beforeGitHub = github.calls.length;
174 const route = plugin.resolveCallback(callbackData);
175 assert.equal(route.actionId, actionId);
151 - assert.equal(menu.calls.length, beforeMenu, 'route resolution must be side-effect-free');
152 - assert.equal(github.calls.length, beforeGitHub, 'route resolution must not call GitHub');
176 + assert.equal(
177 + menu.calls.length,
178 + beforeMenu,
179 + 'route resolution must be side-effect-free'
180 + );
181 + assert.equal(
182 + github.calls.length,
183 + beforeGitHub,
184 + 'route resolution must not call GitHub'
185 + );
186 const view = await route.execute();
187 assert.ok(view?.text);
188 }
@@ -160,7 +193,7 @@ test('repository detail view keeps its existing status entry without duplicate C
193 const plugin = createGitHubPlugin({ github: makeGitHub(), menu });
194 const view = await plugin.resolveCallback('repo:123').execute();
195 const buttons = view.reply_markup.inline_keyboard.flat();
163 - assert.ok(!buttons.some(button => button.callback_data === 'runs:123'));
196 + assert.ok(!buttons.some((button) => button.callback_data === 'runs:123'));
197 });
198
199 test('GitHub plugin write callbacks expose compact approval metadata and defer provider calls', async () => {
@@ -178,7 +211,11 @@ test('GitHub plugin write callbacks expose compact approval metadata and defer p
211 const rerunView = await rerun.execute();
212 assert.deepEqual(github.calls, ['rerun:123:77']);
213 assert.match(rerunView.text, /اجرا.*مجدد|دوباره/i);
181 - assert.ok(rerunView.reply_markup.inline_keyboard.flat().some(button => button.callback_data === 'run:123:77'));
214 + assert.ok(
215 + rerunView.reply_markup.inline_keyboard
216 + .flat()
217 + .some((button) => button.callback_data === 'run:123:77')
218 + );
219
220 github.calls.length = 0;
221 const cancel = plugin.resolveCallback('cancelrun:123:77');
@@ -198,12 +235,20 @@ test('GitHub workflow views expose bounded navigation and write-action callbacks
235
236 const runsView = await plugin.resolveCallback('runs:123').execute();
237 assert.match(runsView.text, /CI/);
201 - assert.ok(runsView.reply_markup.inline_keyboard.flat().some(button => button.callback_data === 'run:123:77'));
238 + assert.ok(
239 + runsView.reply_markup.inline_keyboard
240 + .flat()
241 + .some((button) => button.callback_data === 'run:123:77')
242 + );
243
244 const runView = await plugin.resolveCallback('run:123:77').execute();
245 const runButtons = runView.reply_markup.inline_keyboard.flat();
205 - assert.ok(runButtons.some(button => button.callback_data === 'jobs:123:77'));
206 - assert.ok(runButtons.some(button => button.callback_data === 'rerun:123:77'));
246 + assert.ok(
247 + runButtons.some((button) => button.callback_data === 'jobs:123:77')
248 + );
249 + assert.ok(
250 + runButtons.some((button) => button.callback_data === 'rerun:123:77')
251 + );
252
253 const jobsView = await plugin.resolveCallback('jobs:123:77').execute();
254 assert.match(jobsView.text, /checkout/);
test/github-pr-merge.test.js
+74 -13
@@ -5,22 +5,83 @@ import { githubPluginManifest } from '../src/plugins/github/manifest.js';
5 import { ApprovalService } from '../src/core/approval.js';
6 const HEAD_SHA = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
7 function replayStore() {
8 - const used = new Set(); const payloads = new Map();
8 + const used = new Set();
9 + const payloads = new Map();
10 return {
10 - async put({ ownerId, nonce, payload }) { payloads.set(`${ownerId}:${nonce}`, payload); return true; },
11 - async peek({ ownerId, nonce }) { return payloads.get(`${ownerId}:${nonce}`) || null; },
12 - async consume({ ownerId, nonce }) { const key = `${ownerId}:${nonce}`; if (used.has(key)) return false; used.add(key); return true; }
11 + async put({ ownerId, nonce, payload }) {
12 + payloads.set(`${ownerId}:${nonce}`, payload);
13 + return true;
14 + },
15 + async peek({ ownerId, nonce }) {
16 + return payloads.get(`${ownerId}:${nonce}`) || null;
17 + },
18 + async consume({ ownerId, nonce }) {
19 + const key = `${ownerId}:${nonce}`;
20 + if (used.has(key)) return false;
21 + used.add(key);
22 + return true;
23 + }
24 };
25 }
15 -test('PR merge is a DESTRUCTIVE GitHub action', () => { assert.deepEqual(githubPluginManifest.actions['github.pull_request.merge'], { risk: 'DESTRUCTIVE' }); });
16 -test('mergePullRequest requires an exact full PR head SHA', async () => { const github = new GitHubService('token', 'owner'); await assert.rejects(github.mergePullRequest('repo', 42, { expectedHeadSha: 'abc123', mergeMethod: 'squash' }), /head sha|required|expected|invalid/i); });
17 -test('mergePullRequest rejects missing exact-head binding before provider mutation', async () => { const github = new GitHubService('token', 'owner'); await assert.rejects(github.mergePullRequest('repo', 42, { mergeMethod: 'squash' }), /head sha|required|expected/i); });
18 -test('mergePullRequest only accepts supported merge methods', async () => { const github = new GitHubService('token', 'owner'); await assert.rejects(github.mergePullRequest('repo', 42, { expectedHeadSha: HEAD_SHA, mergeMethod: 'octopus' }), /merge method|unsupported/i); });
26 +test('PR merge is a DESTRUCTIVE GitHub action', () => {
27 + assert.deepEqual(githubPluginManifest.actions['github.pull_request.merge'], {
28 + risk: 'DESTRUCTIVE'
29 + });
30 +});
31 +test('mergePullRequest requires an exact full PR head SHA', async () => {
32 + const github = new GitHubService('token', 'owner');
33 + await assert.rejects(
34 + github.mergePullRequest('repo', 42, {
35 + expectedHeadSha: 'abc123',
36 + mergeMethod: 'squash'
37 + }),
38 + /head sha|required|expected|invalid/i
39 + );
40 +});
41 +test('mergePullRequest rejects missing exact-head binding before provider mutation', async () => {
42 + const github = new GitHubService('token', 'owner');
43 + await assert.rejects(
44 + github.mergePullRequest('repo', 42, { mergeMethod: 'squash' }),
45 + /head sha|required|expected/i
46 + );
47 +});
48 +test('mergePullRequest only accepts supported merge methods', async () => {
49 + const github = new GitHubService('token', 'owner');
50 + await assert.rejects(
51 + github.mergePullRequest('repo', 42, {
52 + expectedHeadSha: HEAD_SHA,
53 + mergeMethod: 'octopus'
54 + }),
55 + /merge method|unsupported/i
56 + );
57 +});
58 test('destructive merge approval is owner/action/risk/repo/PR/head bound and replay-safe', async () => {
20 - const service = new ApprovalService({ secret: 'test-secret', now: () => 1700000000000, replayStore: replayStore() });
21 - const token = await service.issue({ pluginId: 'github', actionId: 'github.pull_request.merge', risk: 'DESTRUCTIVE', ownerId: '42', input: { repoId: 7, prNumber: 39, headSha: HEAD_SHA } });
59 + const service = new ApprovalService({
60 + secret: 'test-secret',
61 + now: () => 1700000000000,
62 + replayStore: replayStore()
63 + });
64 + const token = await service.issue({
65 + pluginId: 'github',
66 + actionId: 'github.pull_request.merge',
67 + risk: 'DESTRUCTIVE',
68 + ownerId: '42',
69 + input: { repoId: 7, prNumber: 39, headSha: HEAD_SHA }
70 + });
71 assert.ok(`approve:${token}`.length <= 64);
23 - const payload = await service.consume(token, { ownerId: '42', pluginId: 'github', actionId: 'github.pull_request.merge', risk: 'DESTRUCTIVE' });
24 - assert.deepEqual(payload.input, { repoId: 7, prNumber: 39, headSha: HEAD_SHA });
25 - await assert.rejects(() => service.consume(token, { ownerId: '42' }), /already used/i);
72 + const payload = await service.consume(token, {
73 + ownerId: '42',
74 + pluginId: 'github',
75 + actionId: 'github.pull_request.merge',
76 + risk: 'DESTRUCTIVE'
77 + });
78 + assert.deepEqual(payload.input, {
79 + repoId: 7,
80 + prNumber: 39,
81 + headSha: HEAD_SHA
82 + });
83 + await assert.rejects(
84 + () => service.consume(token, { ownerId: '42' }),
85 + /already used/i
86 + );
87 });
test/github-repository-fallback.test.js
+43 -26
@@ -14,7 +14,7 @@ test('numeric private repository lookup falls back through accessible repositori
14 const calls = [];
15 const repoId = 1401612143;
16
17 - globalThis.fetch = async url => {
17 + globalThis.fetch = async (url) => {
18 const value = String(url);
19 calls.push(value);
20
@@ -23,21 +23,25 @@ test('numeric private repository lookup falls back through accessible repositori
23 }
24
25 if (value.startsWith('https://api.github.com/user/repos?')) {
26 - return json([{
27 - id: repoId,
28 - name: 'nexa-dev-bot',
29 - full_name: 'davoodmehraban89/nexa-dev-bot',
30 - private: true,
31 - default_branch: 'main',
32 - archived: false,
33 - description: 'Personal Telegram developer console for GitHub',
34 - html_url: 'https://github.com/davoodmehraban89/nexa-dev-bot',
35 - stargazers_count: 0,
36 - forks_count: 0
37 - }]);
26 + return json([
27 + {
28 + id: repoId,
29 + name: 'nexa-dev-bot',
30 + full_name: 'davoodmehraban89/nexa-dev-bot',
31 + private: true,
32 + default_branch: 'main',
33 + archived: false,
34 + description: 'Personal Telegram developer console for GitHub',
35 + html_url: 'https://github.com/davoodmehraban89/nexa-dev-bot',
36 + stargazers_count: 0,
37 + forks_count: 0
38 + }
39 + ]);
40 }
41
40 - if (value === 'https://api.github.com/repos/davoodmehraban89/nexa-dev-bot') {
42 + if (
43 + value === 'https://api.github.com/repos/davoodmehraban89/nexa-dev-bot'
44 + ) {
45 return json({
46 id: repoId,
47 name: 'nexa-dev-bot',
@@ -62,8 +66,16 @@ test('numeric private repository lookup falls back through accessible repositori
66 assert.equal(repo.id, String(repoId));
67 assert.equal(repo.fullName, 'davoodmehraban89/nexa-dev-bot');
68 assert.ok(calls.includes(`https://api.github.com/repositories/${repoId}`));
65 - assert.ok(calls.some(value => value.startsWith('https://api.github.com/user/repos?')));
66 - assert.ok(calls.includes('https://api.github.com/repos/davoodmehraban89/nexa-dev-bot'));
69 + assert.ok(
70 + calls.some((value) =>
71 + value.startsWith('https://api.github.com/user/repos?')
72 + )
73 + );
74 + assert.ok(
75 + calls.includes(
76 + 'https://api.github.com/repos/davoodmehraban89/nexa-dev-bot'
77 + )
78 + );
79 } finally {
80 globalThis.fetch = originalFetch;
81 }
@@ -74,11 +86,14 @@ test('numeric repository lookup does not fall back for non-404 provider failures
86 const calls = [];
87 const repoId = 1401612143;
88
77 - globalThis.fetch = async url => {
89 + globalThis.fetch = async (url) => {
90 const value = String(url);
91 calls.push(value);
92 if (value === `https://api.github.com/repositories/${repoId}`) {
81 - return json({ message: 'Resource not accessible by personal access token' }, 403);
93 + return json(
94 + { message: 'Resource not accessible by personal access token' },
95 + 403
96 + );
97 }
98 throw new Error(`Unexpected fallback URL: ${value}`);
99 };
@@ -100,20 +115,22 @@ test('numeric repository 404 preserves the original failure when no accessible r
115 const calls = [];
116 const repoId = 1401612143;
117
103 - globalThis.fetch = async url => {
118 + globalThis.fetch = async (url) => {
119 const value = String(url);
120 calls.push(value);
121 if (value === `https://api.github.com/repositories/${repoId}`) {
122 return json({ message: 'Not Found' }, 404);
123 }
124 if (value.startsWith('https://api.github.com/user/repos?')) {
110 - return json([{
111 - id: 42,
112 - name: 'another-repo',
113 - full_name: 'davoodmehraban89/another-repo',
114 - private: true,
115 - default_branch: 'main'
116 - }]);
125 + return json([
126 + {
127 + id: 42,
128 + name: 'another-repo',
129 + full_name: 'davoodmehraban89/another-repo',
130 + private: true,
131 + default_branch: 'main'
132 + }
133 + ]);
134 }
135 throw new Error(`Unexpected URL: ${value}`);
136 };
test/github-workspace-approval.test.js
+253 -68
@@ -78,34 +78,59 @@ function makeWorkspace(overrides = {}) {
78 };
79 }
80
81 -function makeWorkspaces({ intent = makeIntent(), workspace = makeWorkspace(), disposition = 'start' } = {}) {
81 +function makeWorkspaces({
82 + intent = makeIntent(),
83 + workspace = makeWorkspace(),
84 + disposition = 'start'
85 +} = {}) {
86 const calls = [];
87 let mutableIntent = structuredClone(intent);
88 return {
89 calls,
90 async getIntent({ ownerId, intentId }) {
91 calls.push(['getIntent', ownerId, intentId]);
88 - return ownerId === OWNER && intentId === mutableIntent.id ? structuredClone(mutableIntent) : null;
92 + return ownerId === OWNER && intentId === mutableIntent.id
93 + ? structuredClone(mutableIntent)
94 + : null;
95 },
96 async getWorkspace({ ownerId, workspaceId }) {
97 calls.push(['getWorkspace', ownerId, workspaceId]);
92 - return ownerId === OWNER && workspaceId === workspace.id ? structuredClone(workspace) : null;
98 + return ownerId === OWNER && workspaceId === workspace.id
99 + ? structuredClone(workspace)
100 + : null;
101 },
102 async beginCommit({ ownerId, intentId }) {
103 calls.push(['beginCommit', ownerId, intentId]);
96 - if (mutableIntent.state === 'COMMITTED') return { disposition: 'committed', intent: structuredClone(mutableIntent) };
97 - if (mutableIntent.state === 'COMMITTING') return { disposition: 'resume', intent: structuredClone(mutableIntent) };
104 + if (mutableIntent.state === 'COMMITTED')
105 + return {
106 + disposition: 'committed',
107 + intent: structuredClone(mutableIntent)
108 + };
109 + if (mutableIntent.state === 'COMMITTING')
110 + return {
111 + disposition: 'resume',
112 + intent: structuredClone(mutableIntent)
113 + };
114 mutableIntent = { ...mutableIntent, state: 'COMMITTING' };
115 return { disposition, intent: structuredClone(mutableIntent) };
116 },
117 async setCandidateCommit({ ownerId, intentId, commitSha }) {
118 calls.push(['setCandidateCommit', ownerId, intentId, commitSha]);
103 - mutableIntent = { ...mutableIntent, candidateCommitSha: commitSha, state: 'COMMITTING' };
119 + mutableIntent = {
120 + ...mutableIntent,
121 + candidateCommitSha: commitSha,
122 + state: 'COMMITTING'
123 + };
124 return structuredClone(mutableIntent);
125 },
126 async completeCommit({ ownerId, intentId, commitSha, branch }) {
127 calls.push(['completeCommit', ownerId, intentId, commitSha, branch]);
108 - mutableIntent = { ...mutableIntent, commitSha, branch, state: 'COMMITTED' };
128 + mutableIntent = {
129 + ...mutableIntent,
130 + commitSha,
131 + branch,
132 + state: 'COMMITTED'
133 + };
134 return structuredClone(mutableIntent);
135 },
136 async markStale({ ownerId, intentId, reason }) {
@@ -116,7 +141,11 @@ function makeWorkspaces({ intent = makeIntent(), workspace = makeWorkspace(), di
141 };
142 }
143
119 -function makeGitHub({ baseHead = BASE_HEAD, existingRef = null, createRefError = null } = {}) {
144 +function makeGitHub({
145 + baseHead = BASE_HEAD,
146 + existingRef = null,
147 + createRefError = null
148 +} = {}) {
149 const calls = [];
150 return {
151 calls,
@@ -150,8 +179,12 @@ function makeGitHub({ baseHead = BASE_HEAD, existingRef = null, createRefError =
179
180 function minimalMenu() {
181 return {
153 - async getReposListView() { return { text: 'repos', reply_markup: { inline_keyboard: [] } }; },
154 - async renderByCallback(data) { return { text: `legacy:${data}`, reply_markup: { inline_keyboard: [] } }; }
182 + async getReposListView() {
183 + return { text: 'repos', reply_markup: { inline_keyboard: [] } };
184 + },
185 + async renderByCallback(data) {
186 + return { text: `legacy:${data}`, reply_markup: { inline_keyboard: [] } };
187 + }
188 };
189 }
190
@@ -179,33 +212,59 @@ test('workspace approval uses compact <=56 byte token and binds owner action ris
212 risk: 'WRITE'
213 });
214 assert.deepEqual(payload.input, { repoId: REPO_ID, intentId: INTENT_ID });
182 - await assert.rejects(() => approvals.consume(token, { ownerId: OWNER }), /already used/i);
215 + await assert.rejects(
216 + () => approvals.consume(token, { ownerId: OWNER }),
217 + /already used/i
218 + );
219
220 const second = await approvals.issue({
185 - pluginId: 'github', actionId: 'github.workspace.commit_branch', risk: 'WRITE', ownerId: OWNER,
221 + pluginId: 'github',
222 + actionId: 'github.workspace.commit_branch',
223 + risk: 'WRITE',
224 + ownerId: OWNER,
225 input: { repoId: REPO_ID, intentId: INTENT_ID }
226 });
227 now += 121_000;
189 - await assert.rejects(() => approvals.verify(second, { ownerId: OWNER }), /expired/i);
190 - await assert.rejects(() => approvals.issue({
191 - pluginId: 'github', actionId: 'github.workspace.commit_branch', risk: 'WRITE', ownerId: OWNER,
192 - input: { repoId: REPO_ID, intentId: 'too-short' }
193 - }), /intent/i);
228 + await assert.rejects(
229 + () => approvals.verify(second, { ownerId: OWNER }),
230 + /expired/i
231 + );
232 + await assert.rejects(
233 + () =>
234 + approvals.issue({
235 + pluginId: 'github',
236 + actionId: 'github.workspace.commit_branch',
237 + risk: 'WRITE',
238 + ownerId: OWNER,
239 + input: { repoId: REPO_ID, intentId: 'too-short' }
240 + }),
241 + /intent/i
242 + );
243 });
244
245 test('wscommit resolves to WRITE approval metadata before execution and performs zero GitHub or workspace calls pre-approval', async () => {
246 const github = makeGitHub();
247 const workspaces = makeWorkspaces();
199 - const plugin = createGitHubPlugin({ github, menu: minimalMenu(), workspaces });
248 + const plugin = createGitHubPlugin({
249 + github,
250 + menu: minimalMenu(),
251 + workspaces
252 + });
253 const router = new PluginRouter({
254 registry: new PluginRegistry([plugin]),
255 policy: new ActionPolicy(),
256 audit: new AuditLogger({ sink: () => {} })
257 });
205 - const result = await router.dispatchCallback(`wscommit:${REPO_ID}:${INTENT_ID}`, { isOwner: true, ownerId: OWNER });
258 + const result = await router.dispatchCallback(
259 + `wscommit:${REPO_ID}:${INTENT_ID}`,
260 + { isOwner: true, ownerId: OWNER }
261 + );
262 assert.equal(result.requiresApproval, true);
263 assert.equal(result.actionId, 'github.workspace.commit_branch');
208 - assert.deepEqual(result.approval.input, { repoId: REPO_ID, intentId: INTENT_ID });
264 + assert.deepEqual(result.approval.input, {
265 + repoId: REPO_ID,
266 + intentId: INTENT_ID
267 + });
268 assert.equal(result.approval.cancelCallback, `repo:${REPO_ID}`);
269 assert.deepEqual(github.calls, []);
270 assert.deepEqual(workspaces.calls, []);
@@ -214,75 +273,179 @@ test('wscommit resolves to WRITE approval metadata before execution and performs
273 test('approved orchestration fails closed on changed workspace material or stale base before any Git object creation', async () => {
274 assert.equal(typeof workspaceModule.commitWorkspaceIntent, 'function');
275
217 - const changedWorkspaces = makeWorkspaces({ workspace: makeWorkspace({ currentIntentId: null, draftDigest: '9'.repeat(64) }) });
276 + const changedWorkspaces = makeWorkspaces({
277 + workspace: makeWorkspace({
278 + currentIntentId: null,
279 + draftDigest: '9'.repeat(64)
280 + })
281 + });
282 const changedGitHub = makeGitHub();
219 - await assert.rejects(() => workspaceModule.commitWorkspaceIntent({
220 - github: changedGitHub, workspaces: changedWorkspaces, ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID
221 - }), /intent|material|changed|stale/i);
222 - assert.equal(changedGitHub.calls.some(call => call[0].startsWith('createGit')), false);
283 + await assert.rejects(
284 + () =>
285 + workspaceModule.commitWorkspaceIntent({
286 + github: changedGitHub,
287 + workspaces: changedWorkspaces,
288 + ownerId: OWNER,
289 + repoId: REPO_ID,
290 + intentId: INTENT_ID
291 + }),
292 + /intent|material|changed|stale/i
293 + );
294 + assert.equal(
295 + changedGitHub.calls.some((call) => call[0].startsWith('createGit')),
296 + false
297 + );
298
299 const staleWorkspaces = makeWorkspaces();
300 const staleGitHub = makeGitHub({ baseHead: '9'.repeat(40) });
226 - await assert.rejects(() => workspaceModule.commitWorkspaceIntent({
227 - github: staleGitHub, workspaces: staleWorkspaces, ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID
228 - }), /base|stale|changed/i);
229 - assert.equal(staleGitHub.calls.some(call => call[0].startsWith('createGit')), false);
230 - assert.ok(staleWorkspaces.calls.some(call => call[0] === 'markStale'));
301 + await assert.rejects(
302 + () =>
303 + workspaceModule.commitWorkspaceIntent({
304 + github: staleGitHub,
305 + workspaces: staleWorkspaces,
306 + ownerId: OWNER,
307 + repoId: REPO_ID,
308 + intentId: INTENT_ID
309 + }),
310 + /base|stale|changed/i
311 + );
312 + assert.equal(
313 + staleGitHub.calls.some((call) => call[0].startsWith('createGit')),
314 + false
315 + );
316 + assert.ok(staleWorkspaces.calls.some((call) => call[0] === 'markStale'));
317 });
318
319 test('approved orchestration rejects an unexpected existing target branch without creating Git objects', async () => {
320 const workspaces = makeWorkspaces();
235 - const github = makeGitHub({ existingRef: { branch: TARGET_BRANCH, sha: '8'.repeat(40) } });
236 - await assert.rejects(() => workspaceModule.commitWorkspaceIntent({
237 - github, workspaces, ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID
238 - }), /already exists|target branch|unexpected/i);
239 - assert.equal(github.calls.some(call => call[0].startsWith('createGit')), false);
321 + const github = makeGitHub({
322 + existingRef: { branch: TARGET_BRANCH, sha: '8'.repeat(40) }
323 + });
324 + await assert.rejects(
325 + () =>
326 + workspaceModule.commitWorkspaceIntent({
327 + github,
328 + workspaces,
329 + ownerId: OWNER,
330 + repoId: REPO_ID,
331 + intentId: INTENT_ID
332 + }),
333 + /already exists|target branch|unexpected/i
334 + );
335 + assert.equal(
336 + github.calls.some((call) => call[0].startsWith('createGit')),
337 + false
338 + );
339 });
340
341 test('successful approved orchestration is blob -> tree -> commit -> durable candidate -> create ref -> durable COMMITTED', async () => {
342 const workspaces = makeWorkspaces();
343 const github = makeGitHub();
245 - const result = await workspaceModule.commitWorkspaceIntent({ github, workspaces, ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID });
246 - assert.deepEqual(result, { commitSha: COMMIT_SHA, branch: TARGET_BRANCH, idempotent: false });
247 - assert.deepEqual(github.calls.map(call => call[0]), [
248 - 'getBranchSnapshot', 'getGitRef', 'createGitBlob', 'createGitTree', 'createGitCommit', 'createGitBranchRef'
249 - ]);
250 - const blobCall = github.calls.find(call => call[0] === 'createGitBlob');
344 + const result = await workspaceModule.commitWorkspaceIntent({
345 + github,
346 + workspaces,
347 + ownerId: OWNER,
348 + repoId: REPO_ID,
349 + intentId: INTENT_ID
350 + });
351 + assert.deepEqual(result, {
352 + commitSha: COMMIT_SHA,
353 + branch: TARGET_BRANCH,
354 + idempotent: false
355 + });
356 + assert.deepEqual(
357 + github.calls.map((call) => call[0]),
358 + [
359 + 'getBranchSnapshot',
360 + 'getGitRef',
361 + 'createGitBlob',
362 + 'createGitTree',
363 + 'createGitCommit',
364 + 'createGitBranchRef'
365 + ]
366 + );
367 + const blobCall = github.calls.find((call) => call[0] === 'createGitBlob');
368 assert.equal(blobCall[2], 'after\n');
252 - const treeCall = github.calls.find(call => call[0] === 'createGitTree');
369 + const treeCall = github.calls.find((call) => call[0] === 'createGitTree');
370 assert.deepEqual(treeCall[2], {
371 baseTreeSha: BASE_TREE,
255 - entries: [{ path: 'src/app.js', mode: '100644', type: 'blob', sha: CONTENT_BLOB }]
372 + entries: [
373 + { path: 'src/app.js', mode: '100644', type: 'blob', sha: CONTENT_BLOB }
374 + ]
375 });
257 - const commitCall = github.calls.find(call => call[0] === 'createGitCommit');
376 + const commitCall = github.calls.find((call) => call[0] === 'createGitCommit');
377 assert.deepEqual(commitCall[2], {
259 - message: 'edit app', treeSha: NEW_TREE, parentSha: BASE_HEAD, timestamp: TIMESTAMP
378 + message: 'edit app',
379 + treeSha: NEW_TREE,
380 + parentSha: BASE_HEAD,
381 + timestamp: TIMESTAMP
382 });
261 - assert.ok(workspaces.calls.some(call => call[0] === 'setCandidateCommit' && call[3] === COMMIT_SHA));
262 - assert.ok(workspaces.calls.some(call => call[0] === 'completeCommit' && call[3] === COMMIT_SHA && call[4] === TARGET_BRANCH));
383 + assert.ok(
384 + workspaces.calls.some(
385 + (call) => call[0] === 'setCandidateCommit' && call[3] === COMMIT_SHA
386 + )
387 + );
388 + assert.ok(
389 + workspaces.calls.some(
390 + (call) =>
391 + call[0] === 'completeCommit' &&
392 + call[3] === COMMIT_SHA &&
393 + call[4] === TARGET_BRANCH
394 + )
395 + );
396 });
397
398 test('COMMITTED and COMMITTING retries reconcile idempotently without a second provider write', async () => {
266 - const committedIntent = makeIntent({ state: 'COMMITTED', commitSha: COMMIT_SHA, branch: TARGET_BRANCH });
399 + const committedIntent = makeIntent({
400 + state: 'COMMITTED',
401 + commitSha: COMMIT_SHA,
402 + branch: TARGET_BRANCH
403 + });
404 const committedWorkspaces = makeWorkspaces({ intent: committedIntent });
405 const committedGitHub = makeGitHub();
269 - assert.deepEqual(await workspaceModule.commitWorkspaceIntent({
270 - github: committedGitHub, workspaces: committedWorkspaces, ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID
271 - }), { commitSha: COMMIT_SHA, branch: TARGET_BRANCH, idempotent: true });
406 + assert.deepEqual(
407 + await workspaceModule.commitWorkspaceIntent({
408 + github: committedGitHub,
409 + workspaces: committedWorkspaces,
410 + ownerId: OWNER,
411 + repoId: REPO_ID,
412 + intentId: INTENT_ID
413 + }),
414 + { commitSha: COMMIT_SHA, branch: TARGET_BRANCH, idempotent: true }
415 + );
416 assert.deepEqual(committedGitHub.calls, []);
417
274 - const resumingIntent = makeIntent({ state: 'COMMITTING', candidateCommitSha: COMMIT_SHA });
418 + const resumingIntent = makeIntent({
419 + state: 'COMMITTING',
420 + candidateCommitSha: COMMIT_SHA
421 + });
422 const resumingWorkspaces = makeWorkspaces({ intent: resumingIntent });
276 - const resumingGitHub = makeGitHub({ existingRef: { branch: TARGET_BRANCH, sha: COMMIT_SHA } });
277 - assert.deepEqual(await workspaceModule.commitWorkspaceIntent({
278 - github: resumingGitHub, workspaces: resumingWorkspaces, ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID
279 - }), { commitSha: COMMIT_SHA, branch: TARGET_BRANCH, idempotent: true });
280 - assert.deepEqual(resumingGitHub.calls.map(call => call[0]), ['getGitRef']);
281 - assert.ok(resumingWorkspaces.calls.some(call => call[0] === 'completeCommit'));
423 + const resumingGitHub = makeGitHub({
424 + existingRef: { branch: TARGET_BRANCH, sha: COMMIT_SHA }
425 + });
426 + assert.deepEqual(
427 + await workspaceModule.commitWorkspaceIntent({
428 + github: resumingGitHub,
429 + workspaces: resumingWorkspaces,
430 + ownerId: OWNER,
431 + repoId: REPO_ID,
432 + intentId: INTENT_ID
433 + }),
434 + { commitSha: COMMIT_SHA, branch: TARGET_BRANCH, idempotent: true }
435 + );
436 + assert.deepEqual(
437 + resumingGitHub.calls.map((call) => call[0]),
438 + ['getGitRef']
439 + );
440 + assert.ok(
441 + resumingWorkspaces.calls.some((call) => call[0] === 'completeCommit')
442 + );
443 });
444
445 test('ambiguous create-ref error reconciles only the exact candidate SHA and rejects different or missing refs', async () => {
285 - const ambiguous = new Error('GitHub create branch ref failed: 422 Reference already exists');
446 + const ambiguous = new Error(
447 + 'GitHub create branch ref failed: 422 Reference already exists'
448 + );
449 const sequenceGitHub = makeGitHub({ createRefError: ambiguous });
450 let refReads = 0;
451 sequenceGitHub.getGitRef = async (repoId, branch, options) => {
@@ -291,9 +454,16 @@ test('ambiguous create-ref error reconciles only the exact candidate SHA and rej
454 return refReads === 1 ? null : { branch, sha: COMMIT_SHA };
455 };
456 const workspaces = makeWorkspaces();
294 - assert.deepEqual(await workspaceModule.commitWorkspaceIntent({
295 - github: sequenceGitHub, workspaces, ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID
296 - }), { commitSha: COMMIT_SHA, branch: TARGET_BRANCH, idempotent: true });
457 + assert.deepEqual(
458 + await workspaceModule.commitWorkspaceIntent({
459 + github: sequenceGitHub,
460 + workspaces,
461 + ownerId: OWNER,
462 + repoId: REPO_ID,
463 + intentId: INTENT_ID
464 + }),
465 + { commitSha: COMMIT_SHA, branch: TARGET_BRANCH, idempotent: true }
466 + );
467
468 for (const ref of [null, { branch: TARGET_BRANCH, sha: '7'.repeat(40) }]) {
469 const github = makeGitHub({ createRefError: ambiguous });
@@ -303,16 +473,30 @@ test('ambiguous create-ref error reconciles only the exact candidate SHA and rej
473 reads += 1;
474 return reads === 1 ? null : ref;
475 };
306 - await assert.rejects(() => workspaceModule.commitWorkspaceIntent({
307 - github, workspaces: makeWorkspaces(), ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID
308 - }), /422|reconcile|branch|candidate/i);
476 + await assert.rejects(
477 + () =>
478 + workspaceModule.commitWorkspaceIntent({
479 + github,
480 + workspaces: makeWorkspaces(),
481 + ownerId: OWNER,
482 + repoId: REPO_ID,
483 + intentId: INTENT_ID
484 + }),
485 + /422|reconcile|branch|candidate/i
486 + );
487 }
488 });
489
490 test('router audit merges only allowlisted workspace metadata and never source draft text or signed token material', async () => {
491 const events = [];
492 const plugin = {
315 - manifest: { id: 'safe', name: 'safe', version: 1, commands: [], actions: { 'safe.write': { risk: 'WRITE' } } },
493 + manifest: {
494 + id: 'safe',
495 + name: 'safe',
496 + version: 1,
497 + commands: [],
498 + actions: { 'safe.write': { risk: 'WRITE' } }
499 + },
500 resolveCallback() {
501 return {
502 actionId: 'safe.write',
@@ -331,8 +515,9 @@ test('router audit merges only allowlisted workspace metadata and never source d
515 }
516 };
517 const router = new PluginRouter({
334 - registry: new PluginRegistry([plugin]), policy: new ActionPolicy(),
335 - audit: new AuditLogger({ sink: event => events.push(event) })
518 + registry: new PluginRegistry([plugin]),
519 + policy: new ActionPolicy(),
520 + audit: new AuditLogger({ sink: (event) => events.push(event) })
521 });
522 await router.dispatchCallback('x', { isOwner: true, approved: true });
523 const serialized = JSON.stringify(events);
test/github-workspace-bot-approval.test.js
+36 -9
@@ -24,7 +24,9 @@ function buttons(markup) {
24 }
25
26 test('bot workspace commit approval uses repository cancel fallback, executes only after approval and rejects replay', async () => {
27 - const bot = new NexaDevBot({ TELEGRAM_WEBHOOK_SECRET: 'workspace-test-secret' });
27 + const bot = new NexaDevBot({
28 + TELEGRAM_WEBHOOK_SECRET: 'workspace-test-secret'
29 + });
30 bot.approvals = new ApprovalService({
31 secret: 'workspace-test-secret',
32 replayStore: oneShotReplayStore()
@@ -38,7 +40,11 @@ test('bot workspace commit approval uses repository cancel fallback, executes on
40 if (context.approved === true) {
41 return {
42 text: '✅ committed',
41 - reply_markup: { inline_keyboard: [[{ text: 'project', callback_data: `repo:${REPO_ID}` }]] }
43 + reply_markup: {
44 + inline_keyboard: [
45 + [{ text: 'project', callback_data: `repo:${REPO_ID}` }]
46 + ]
47 + }
48 };
49 }
50 return {
@@ -59,7 +65,9 @@ test('bot workspace commit approval uses repository cancel fallback, executes on
65
66 const edits = [];
67 bot.telegram = {
62 - async answerCallbackQuery() { return { ok: true }; },
68 + async answerCallbackQuery() {
69 + return { ok: true };
70 + },
71 async editMessageText(chatId, messageId, text, replyMarkup) {
72 edits.push({ chatId, messageId, text, replyMarkup });
73 return { ok: true };
@@ -71,26 +79,45 @@ test('bot workspace commit approval uses repository cancel fallback, executes on
79 from: { id: OWNER },
80 message: { chat: { id: 7 }, message_id: 9 }
81 };
74 - const prepare = await bot.handleCallbackQuery({ ...baseQuery, data: `wscommit:${REPO_ID}:${INTENT_ID}` });
82 + const prepare = await bot.handleCallbackQuery({
83 + ...baseQuery,
84 + data: `wscommit:${REPO_ID}:${INTENT_ID}`
85 + });
86 assert.equal(prepare.approvalRequired, true);
87 assert.equal(routeCalls.length, 1);
88 assert.notEqual(routeCalls[0].context.approved, true);
89
90 const approvalButtons = buttons(edits.at(-1).replyMarkup);
80 - const confirm = approvalButtons.find(button => button.callback_data?.startsWith('approve:'));
81 - const cancel = approvalButtons.find(button => button.text.includes('انصراف'));
91 + const confirm = approvalButtons.find((button) =>
92 + button.callback_data?.startsWith('approve:')
93 + );
94 + const cancel = approvalButtons.find((button) =>
95 + button.text.includes('انصراف')
96 + );
97 assert.ok(confirm);
98 assert.equal(cancel.callback_data, `repo:${REPO_ID}`);
99 assert.ok(new TextEncoder().encode(confirm.callback_data).byteLength <= 64);
100
86 - const approved = await bot.handleCallbackQuery({ ...baseQuery, id: 'cb-2', data: confirm.callback_data });
101 + const approved = await bot.handleCallbackQuery({
102 + ...baseQuery,
103 + id: 'cb-2',
104 + data: confirm.callback_data
105 + });
106 assert.equal(approved.approved, true);
107 assert.equal(routeCalls.length, 2);
108 assert.equal(routeCalls[1].data, `wscommit:${REPO_ID}:${INTENT_ID}`);
90 - assert.deepEqual(routeCalls[1].context, { isOwner: true, ownerId: String(OWNER), approved: true });
109 + assert.deepEqual(routeCalls[1].context, {
110 + isOwner: true,
111 + ownerId: String(OWNER),
112 + approved: true
113 + });
114 assert.match(edits.at(-1).text, /committed/);
115
93 - const replay = await bot.handleCallbackQuery({ ...baseQuery, id: 'cb-3', data: confirm.callback_data });
116 + const replay = await bot.handleCallbackQuery({
117 + ...baseQuery,
118 + id: 'cb-3',
119 + data: confirm.callback_data
120 + });
121 assert.equal(replay.approvalRejected, true);
122 assert.match(replay.error, /already used/i);
123 assert.equal(routeCalls.length, 2);
test/github-workspace-file-upload.test.js
+103 -29
@@ -8,8 +8,12 @@ const WORKSPACE_ID = 'W000000001';
8
9 function makeMenu() {
10 return {
11 - async getReposListView() { return { text: 'repos', reply_markup: { inline_keyboard: [] } }; },
12 - async renderByCallback(data) { return { text: `legacy:${data}`, reply_markup: { inline_keyboard: [] } }; }
11 + async getReposListView() {
12 + return { text: 'repos', reply_markup: { inline_keyboard: [] } };
13 + },
14 + async renderByCallback(data) {
15 + return { text: `legacy:${data}`, reply_markup: { inline_keyboard: [] } };
16 + }
17 };
18 }
19
@@ -32,7 +36,9 @@ function makeWorkspaces() {
36 return {
37 workspace,
38 async getWorkspace({ ownerId, workspaceId }) {
35 - return ownerId === OWNER && workspaceId === WORKSPACE_ID ? structuredClone(workspace) : null;
39 + return ownerId === OWNER && workspaceId === WORKSPACE_ID
40 + ? structuredClone(workspace)
41 + : null;
42 },
43 async setPendingInput({ ownerId, workspaceId, mode }) {
44 assert.equal(ownerId, OWNER);
@@ -43,7 +49,13 @@ function makeWorkspaces() {
49 return ownerId === OWNER && pending ? structuredClone(pending) : null;
50 },
51 async consumePendingInput({ ownerId, workspaceId, mode }) {
46 - if (ownerId !== OWNER || !pending || pending.workspaceId !== workspaceId || pending.mode !== mode) return false;
52 + if (
53 + ownerId !== OWNER ||
54 + !pending ||
55 + pending.workspaceId !== workspaceId ||
56 + pending.mode !== mode
57 + )
58 + return false;
59 pending = null;
60 return true;
61 },
@@ -62,22 +74,37 @@ function makePlugin() {
74 const workspaces = makeWorkspaces();
75 const github = {
76 async getRepository(repoId) {
65 - return { id: String(repoId), name: 'demo', fullName: 'davood/demo', defaultBranch: 'main', archived: false };
77 + return {
78 + id: String(repoId),
79 + name: 'demo',
80 + fullName: 'davood/demo',
81 + defaultBranch: 'main',
82 + archived: false
83 + };
84 }
85 };
68 - return { workspaces, plugin: createGitHubPlugin({ github, menu: makeMenu(), workspaces }) };
86 + return {
87 + workspaces,
88 + plugin: createGitHubPlugin({ github, menu: makeMenu(), workspaces })
89 + };
90 }
91
92 test('workspace keeps file upload as a secondary bounded draft input route', async () => {
93 const { workspaces, plugin } = makePlugin();
73 - const workspaceView = await plugin.resolveCallback(`ws:${WORKSPACE_ID}`, { ownerId: OWNER }).execute();
94 + const workspaceView = await plugin
95 + .resolveCallback(`ws:${WORKSPACE_ID}`, { ownerId: OWNER })
96 + .execute();
97 const buttons = workspaceView.reply_markup.inline_keyboard.flat();
75 - const upload = buttons.find(button => button.callback_data === `wfile:${WORKSPACE_ID}`);
98 + const upload = buttons.find(
99 + (button) => button.callback_data === `wfile:${WORKSPACE_ID}`
100 + );
101 assert.ok(upload);
102 assert.match(upload.text, /file|فایل|upload|بارگذاری/i);
103 assert.ok(new TextEncoder().encode(upload.callback_data).byteLength <= 64);
104
80 - const route = plugin.resolveCallback(upload.callback_data, { ownerId: OWNER });
105 + const route = plugin.resolveCallback(upload.callback_data, {
106 + ownerId: OWNER
107 + });
108 assert.equal(route.actionId, 'github.workspace.input.prepare');
109 const prompt = await route.execute();
110 assert.match(prompt.text, /65,?536|65536/);
@@ -91,12 +118,21 @@ test('workspace keeps file upload as a secondary bounded draft input route', asy
118
119 test('uploaded text file replaces only the local draft and preserves the repository target path', async () => {
120 const { workspaces, plugin } = makePlugin();
94 - await plugin.resolveCallback(`wfile:${WORKSPACE_ID}`, { ownerId: OWNER }).execute();
121 + await plugin
122 + .resolveCallback(`wfile:${WORKSPACE_ID}`, { ownerId: OWNER })
123 + .execute();
124 const pending = await workspaces.getPendingInput({ ownerId: OWNER });
96 - const route = plugin.resolveMessage({
97 - pending,
98 - file: { name: 'replacement.txt', text: 'node_modules/\n# smoke\n', byteLength: 22 }
99 - }, { ownerId: OWNER });
125 + const route = plugin.resolveMessage(
126 + {
127 + pending,
128 + file: {
129 + name: 'replacement.txt',
130 + text: 'node_modules/\n# smoke\n',
131 + byteLength: 22
132 + }
133 + },
134 + { ownerId: OWNER }
135 + );
136 assert.equal(route.actionId, 'github.workspace.input.apply');
137 const view = await route.execute();
138 assert.match(view.text, /Draft|ذخیره|فایل/i);
@@ -118,7 +154,11 @@ test('bot downloads a pending workspace document using the expanded workspace by
154 bot.telegram = {
155 async downloadTextFile(fileId, options) {
156 calls.push(['downloadTextFile', fileId, options]);
121 - return { text: 'node_modules/\n# smoke\n', byteLength: 22, filePath: 'documents/replacement.txt' };
157 + return {
158 + text: 'node_modules/\n# smoke\n',
159 + byteLength: 22,
160 + filePath: 'documents/replacement.txt'
161 + };
162 },
163 async sendMessage(chatId, text, replyMarkup) {
164 calls.push(['sendMessage', chatId, text, replyMarkup]);
@@ -127,7 +167,11 @@ test('bot downloads a pending workspace document using the expanded workspace by
167 };
168 bot.router = {
169 async dispatchMessage(payload, context) {
130 - calls.push(['dispatchMessage', structuredClone(payload), structuredClone(context)]);
170 + calls.push([
171 + 'dispatchMessage',
172 + structuredClone(payload),
173 + structuredClone(context)
174 + ]);
175 return { text: 'file accepted', reply_markup: { inline_keyboard: [] } };
176 }
177 };
@@ -135,12 +179,19 @@ test('bot downloads a pending workspace document using the expanded workspace by
179 const result = await bot.handleMessage({
180 chat: { id: 7 },
181 from: { id: 42 },
138 - document: { file_id: 'FILE123', file_name: 'replacement.txt', file_size: 22 }
182 + document: {
183 + file_id: 'FILE123',
184 + file_name: 'replacement.txt',
185 + file_size: 22
186 + }
187 });
188
189 assert.equal(result.workspaceInput, true);
142 - assert.deepEqual(calls.find(call => call[0] === 'downloadTextFile'), ['downloadTextFile', 'FILE123', { maxBytes: 65536 }]);
143 - const dispatch = calls.find(call => call[0] === 'dispatchMessage');
190 + assert.deepEqual(
191 + calls.find((call) => call[0] === 'downloadTextFile'),
192 + ['downloadTextFile', 'FILE123', { maxBytes: 65536 }]
193 + );
194 + const dispatch = calls.find((call) => call[0] === 'dispatchMessage');
195 assert.deepEqual(dispatch[1].file, {
196 name: 'replacement.txt',
197 text: 'node_modules/\n# smoke\n',
@@ -154,17 +205,30 @@ test('wrong message type while file upload is pending does not dispatch or consu
205 let dispatches = 0;
206 bot.workspaceStore = {
207 isConfigured: () => true,
157 - async getPendingInput() { return { workspaceId: WORKSPACE_ID, mode: 'draft_file' }; }
208 + async getPendingInput() {
209 + return { workspaceId: WORKSPACE_ID, mode: 'draft_file' };
210 + }
211 };
212 bot.telegram = {
160 - async sendMessage() { return { ok: true }; },
161 - async downloadTextFile() { throw new Error('must not download'); }
213 + async sendMessage() {
214 + return { ok: true };
215 + },
216 + async downloadTextFile() {
217 + throw new Error('must not download');
218 + }
219 };
220 bot.router = {
164 - async dispatchMessage() { dispatches += 1; return null; }
221 + async dispatchMessage() {
222 + dispatches += 1;
223 + return null;
224 + }
225 };
226
167 - const result = await bot.handleMessage({ chat: { id: 7 }, from: { id: 42 }, text: 'not a file' });
227 + const result = await bot.handleMessage({
228 + chat: { id: 7 },
229 + from: { id: 42 },
230 + text: 'not a file'
231 + });
232 assert.equal(result.workspaceInput, true);
233 assert.equal(result.inputRequired, 'document');
234 assert.equal(dispatches, 0);
@@ -176,14 +240,24 @@ test('oversized Telegram document is rejected before download or workspace dispa
240 let dispatches = 0;
241 bot.workspaceStore = {
242 isConfigured: () => true,
179 - async getPendingInput() { return { workspaceId: WORKSPACE_ID, mode: 'draft_file' }; }
243 + async getPendingInput() {
244 + return { workspaceId: WORKSPACE_ID, mode: 'draft_file' };
245 + }
246 };
247 bot.telegram = {
182 - async sendMessage() { return { ok: true }; },
183 - async downloadTextFile() { downloads += 1; return { text: 'unexpected', byteLength: 10 }; }
248 + async sendMessage() {
249 + return { ok: true };
250 + },
251 + async downloadTextFile() {
252 + downloads += 1;
253 + return { text: 'unexpected', byteLength: 10 };
254 + }
255 };
256 bot.router = {
186 - async dispatchMessage() { dispatches += 1; return null; }
257 + async dispatchMessage() {
258 + dispatches += 1;
259 + return null;
260 + }
261 };
262
263 const result = await bot.handleMessage({
@@ -194,4 +268,4 @@ test('oversized Telegram document is rejected before download or workspace dispa
268 assert.equal(result.inputRejected, true);
269 assert.equal(downloads, 0);
270 assert.equal(dispatches, 0);
197 -});
\ No newline at end of file
271 +});
test/github-workspace-integration.test.js
+136 -35
@@ -17,8 +17,12 @@ function flatten(view) {
17
18 function makeMenu() {
19 return {
20 - async getReposListView() { return { text: 'repos', reply_markup: { inline_keyboard: [] } }; },
21 - async renderByCallback(data) { return { text: `legacy:${data}`, reply_markup: { inline_keyboard: [] } }; }
20 + async getReposListView() {
21 + return { text: 'repos', reply_markup: { inline_keyboard: [] } };
22 + },
23 + async renderByCallback(data) {
24 + return { text: `legacy:${data}`, reply_markup: { inline_keyboard: [] } };
25 + }
26 };
27 }
28
@@ -28,7 +32,13 @@ function makeGitHub() {
32 calls,
33 async getRepository(repoId) {
34 calls.push(['getRepository', Number(repoId)]);
31 - return { id: String(repoId), name: 'demo', fullName: 'davood/demo', defaultBranch: 'main', archived: false };
35 + return {
36 + id: String(repoId),
37 + name: 'demo',
38 + fullName: 'davood/demo',
39 + defaultBranch: 'main',
40 + archived: false
41 + };
42 }
43 };
44 }
@@ -63,7 +73,9 @@ function makeWorkspaces() {
73 intents,
74 async getWorkspace({ ownerId, workspaceId }) {
75 calls.push(['getWorkspace', ownerId, workspaceId]);
66 - return ownerId === OWNER && workspaceId === WORKSPACE_ID ? structuredClone(workspace) : null;
76 + return ownerId === OWNER && workspaceId === WORKSPACE_ID
77 + ? structuredClone(workspace)
78 + : null;
79 },
80 async setPendingInput({ ownerId, workspaceId, mode }) {
81 calls.push(['setPendingInput', ownerId, workspaceId, mode]);
@@ -76,7 +88,13 @@ function makeWorkspaces() {
88 },
89 async consumePendingInput({ ownerId, workspaceId, mode }) {
90 calls.push(['consumePendingInput', ownerId, workspaceId, mode]);
79 - if (ownerId !== OWNER || !pending || pending.workspaceId !== workspaceId || pending.mode !== mode) return false;
91 + if (
92 + ownerId !== OWNER ||
93 + !pending ||
94 + pending.workspaceId !== workspaceId ||
95 + pending.mode !== mode
96 + )
97 + return false;
98 pending = null;
99 return true;
100 },
@@ -100,11 +118,17 @@ function makeWorkspaces() {
118 calls.push(['sealIntent', ownerId, workspaceId, structuredClone(intent)]);
119 if (workspace.currentIntentId) {
120 const existing = intents.get(workspace.currentIntentId);
103 - if (existing?.intentDigest === intent.intentDigest) return structuredClone(existing);
121 + if (existing?.intentDigest === intent.intentDigest)
122 + return structuredClone(existing);
123 }
124 intentCounter += 1;
125 const id = `I${String(intentCounter).padStart(7, '0')}`;
107 - const sealed = { ...structuredClone(intent), id, workspaceId, state: 'READY' };
126 + const sealed = {
127 + ...structuredClone(intent),
128 + id,
129 + workspaceId,
130 + state: 'READY'
131 + };
132 intents.set(id, sealed);
133 workspace.currentIntentId = id;
134 workspace.state = 'READY';
@@ -123,25 +147,42 @@ function makePlugin() {
147 test('PluginRouter dispatchMessage applies the same policy boundary without auditing source text', async () => {
148 const auditEvents = [];
149 const plugin = {
126 - manifest: { id: 'demo', name: 'Demo', version: 1, commands: [], actions: { 'demo.message': { risk: 'READ' } } },
150 + manifest: {
151 + id: 'demo',
152 + name: 'Demo',
153 + version: 1,
154 + commands: [],
155 + actions: { 'demo.message': { risk: 'READ' } }
156 + },
157 resolveMessage(payload) {
158 if (!payload?.pending) return null;
129 - return { actionId: 'demo.message', execute: async () => ({ text: 'accepted' }) };
159 + return {
160 + actionId: 'demo.message',
161 + execute: async () => ({ text: 'accepted' })
162 + };
163 }
164 };
165 const router = new PluginRouter({
166 registry: new PluginRegistry([plugin]),
167 policy: new ActionPolicy(),
135 - audit: new AuditLogger({ sink: event => auditEvents.push(event) })
168 + audit: new AuditLogger({ sink: (event) => auditEvents.push(event) })
169 });
137 - const result = await router.dispatchMessage({ pending: { mode: 'draft' }, text: 'TOP SECRET SOURCE' }, { isOwner: true, ownerId: OWNER });
170 + const result = await router.dispatchMessage(
171 + { pending: { mode: 'draft' }, text: 'TOP SECRET SOURCE' },
172 + { isOwner: true, ownerId: OWNER }
173 + );
174 assert.equal(result.text, 'accepted');
139 - assert.equal(JSON.stringify(auditEvents).includes('TOP SECRET SOURCE'), false);
175 + assert.equal(
176 + JSON.stringify(auditEvents).includes('TOP SECRET SOURCE'),
177 + false
178 + );
179 });
180
181 test('legacy draft input is prepared without GitHub calls and the next owner text is consumed exactly once', async () => {
182 const { github, workspaces, plugin } = makePlugin();
144 - const prepare = plugin.resolveCallback(`wtext:${WORKSPACE_ID}`, { ownerId: OWNER });
183 + const prepare = plugin.resolveCallback(`wtext:${WORKSPACE_ID}`, {
184 + ownerId: OWNER
185 + });
186 assert.equal(prepare.actionId, 'github.workspace.input.prepare');
187 assert.deepEqual(github.calls, []);
188 const prompt = await prepare.execute();
@@ -150,14 +191,23 @@ test('legacy draft input is prepared without GitHub calls and the next owner tex
191
192 const pending = await workspaces.getPendingInput({ ownerId: OWNER });
193 assert.deepEqual(pending, { workspaceId: WORKSPACE_ID, mode: 'draft' });
153 - const route = plugin.resolveMessage({ pending, text: 'after <tag>\n' }, { ownerId: OWNER });
194 + const route = plugin.resolveMessage(
195 + { pending, text: 'after <tag>\n' },
196 + { ownerId: OWNER }
197 + );
198 assert.equal(route.actionId, 'github.workspace.input.apply');
199 const view = await route.execute();
200 assert.match(view.text, /ذخیره|Draft|پیش.?نویس/i);
201 assert.equal(workspaces.workspace.draftText, 'after <tag>\n');
202 assert.equal(await workspaces.getPendingInput({ ownerId: OWNER }), null);
203
160 - const late = plugin.resolveMessage({ pending: await workspaces.getPendingInput({ ownerId: OWNER }), text: 'late mutation' }, { ownerId: OWNER });
204 + const late = plugin.resolveMessage(
205 + {
206 + pending: await workspaces.getPendingInput({ ownerId: OWNER }),
207 + text: 'late mutation'
208 + },
209 + { ownerId: OWNER }
210 + );
211 assert.equal(late, null);
212 assert.equal(workspaces.workspace.draftText, 'after <tag>\n');
213 assert.deepEqual(github.calls, []);
@@ -165,10 +215,15 @@ test('legacy draft input is prepared without GitHub calls and the next owner tex
215
216 test('oversized multibyte legacy draft input is visibly rejected without mutating the old draft', async () => {
217 const { workspaces, plugin } = makePlugin();
168 - await plugin.resolveCallback(`wtext:${WORKSPACE_ID}`, { ownerId: OWNER }).execute();
218 + await plugin
219 + .resolveCallback(`wtext:${WORKSPACE_ID}`, { ownerId: OWNER })
220 + .execute();
221 const before = workspaces.workspace.draftText;
222 const pending = await workspaces.getPendingInput({ ownerId: OWNER });
171 - const route = plugin.resolveMessage({ pending, text: '😀'.repeat(16385) }, { ownerId: OWNER });
223 + const route = plugin.resolveMessage(
224 + { pending, text: '😀'.repeat(16385) },
225 + { ownerId: OWNER }
226 + );
227 const view = await route.execute();
228 assert.match(view.text, /65,536|65536|20,000|20000|مجاز|حد/i);
229 assert.equal(workspaces.workspace.draftText, before);
@@ -177,14 +232,25 @@ test('oversized multibyte legacy draft input is visibly rejected without mutatin
232
233 test('commit message input normalizes text and diff renders escaped bounded exact counts without GitHub mutation', async () => {
234 const { github, workspaces, plugin } = makePlugin();
180 - await plugin.resolveCallback(`wmsg:${WORKSPACE_ID}`, { ownerId: OWNER }).execute();
235 + await plugin
236 + .resolveCallback(`wmsg:${WORKSPACE_ID}`, { ownerId: OWNER })
237 + .execute();
238 const pending = await workspaces.getPendingInput({ ownerId: OWNER });
182 - await plugin.resolveMessage({ pending, text: ' chore: update workspace ' }, { ownerId: OWNER }).execute();
239 + await plugin
240 + .resolveMessage(
241 + { pending, text: ' chore: update workspace ' },
242 + { ownerId: OWNER }
243 + )
244 + .execute();
245 assert.equal(workspaces.workspace.commitMessage, 'chore: update workspace');
246
247 workspaces.workspace.draftText = 'after <script>\n';
186 - workspaces.workspace.draftDigest = await digestText(workspaces.workspace.draftText);
187 - const diffRoute = plugin.resolveCallback(`wdiff:${WORKSPACE_ID}`, { ownerId: OWNER });
248 + workspaces.workspace.draftDigest = await digestText(
249 + workspaces.workspace.draftText
250 + );
251 + const diffRoute = plugin.resolveCallback(`wdiff:${WORKSPACE_ID}`, {
252 + ownerId: OWNER
253 + });
254 assert.equal(diffRoute.actionId, 'github.workspace.diff');
255 const diffView = await diffRoute.execute();
256 assert.match(diffView.text, /\+1/);
@@ -199,26 +265,40 @@ test('READY rejects no-change, reuses identical material and mints a new intent
265 workspaces.workspace.commitMessage = 'edit app';
266 workspaces.workspace.commitMessageDigest = await digestText('edit app');
267
202 - const noChange = plugin.resolveCallback(`wready:${WORKSPACE_ID}`, { ownerId: OWNER });
268 + const noChange = plugin.resolveCallback(`wready:${WORKSPACE_ID}`, {
269 + ownerId: OWNER
270 + });
271 await assert.rejects(() => noChange.execute(), /change|تغییر|بدون/i);
272
273 workspaces.workspace.draftText = 'after\n';
274 workspaces.workspace.draftDigest = await digestText('after\n');
207 - const ready1 = await plugin.resolveCallback(`wready:${WORKSPACE_ID}`, { ownerId: OWNER }).execute();
208 - const commit1 = flatten(ready1).find(button => button.callback_data?.startsWith('wscommit:'))?.callback_data;
275 + const ready1 = await plugin
276 + .resolveCallback(`wready:${WORKSPACE_ID}`, { ownerId: OWNER })
277 + .execute();
278 + const commit1 = flatten(ready1).find((button) =>
279 + button.callback_data?.startsWith('wscommit:')
280 + )?.callback_data;
281 assert.match(commit1, /^wscommit:123:[A-Za-z0-9_-]{8}$/);
282 assert.ok(new TextEncoder().encode(commit1).byteLength <= 64);
283
212 - const ready2 = await plugin.resolveCallback(`wready:${WORKSPACE_ID}`, { ownerId: OWNER }).execute();
213 - const commit2 = flatten(ready2).find(button => button.callback_data?.startsWith('wscommit:'))?.callback_data;
284 + const ready2 = await plugin
285 + .resolveCallback(`wready:${WORKSPACE_ID}`, { ownerId: OWNER })
286 + .execute();
287 + const commit2 = flatten(ready2).find((button) =>
288 + button.callback_data?.startsWith('wscommit:')
289 + )?.callback_data;
290 assert.equal(commit2, commit1);
291
292 workspaces.workspace.draftText = 'after again\n';
293 workspaces.workspace.draftDigest = await digestText('after again\n');
294 workspaces.workspace.currentIntentId = null;
295 workspaces.workspace.state = 'DRAFT';
220 - const ready3 = await plugin.resolveCallback(`wready:${WORKSPACE_ID}`, { ownerId: OWNER }).execute();
221 - const commit3 = flatten(ready3).find(button => button.callback_data?.startsWith('wscommit:'))?.callback_data;
296 + const ready3 = await plugin
297 + .resolveCallback(`wready:${WORKSPACE_ID}`, { ownerId: OWNER })
298 + .execute();
299 + const commit3 = flatten(ready3).find((button) =>
300 + button.callback_data?.startsWith('wscommit:')
301 + )?.callback_data;
302 assert.notEqual(commit3, commit1);
303 assert.deepEqual(github.calls, []);
304 });
@@ -241,18 +321,39 @@ test('bot preserves command precedence and routes raw pending workspace text exa
321 };
322 bot.router = {
323 async dispatchMessage(payload, context) {
244 - calls.push(['dispatchMessage', structuredClone(payload), structuredClone(context)]);
245 - return { text: 'workspace accepted', reply_markup: { inline_keyboard: [] } };
324 + calls.push([
325 + 'dispatchMessage',
326 + structuredClone(payload),
327 + structuredClone(context)
328 + ]);
329 + return {
330 + text: 'workspace accepted',
331 + reply_markup: { inline_keyboard: [] }
332 + };
333 }
334 };
335
249 - await bot.handleMessage({ chat: { id: 7 }, from: { id: 42 }, text: '/status' });
250 - assert.equal(calls.some(call => call[0] === 'getPendingInput'), false);
251 - assert.equal(calls.some(call => call[0] === 'dispatchMessage'), false);
336 + await bot.handleMessage({
337 + chat: { id: 7 },
338 + from: { id: 42 },
339 + text: '/status'
340 + });
341 + assert.equal(
342 + calls.some((call) => call[0] === 'getPendingInput'),
343 + false
344 + );
345 + assert.equal(
346 + calls.some((call) => call[0] === 'dispatchMessage'),
347 + false
348 + );
349
350 calls.length = 0;
254 - await bot.handleMessage({ chat: { id: 7 }, from: { id: 42 }, text: ' exact draft text \n' });
255 - const dispatch = calls.find(call => call[0] === 'dispatchMessage');
351 + await bot.handleMessage({
352 + chat: { id: 7 },
353 + from: { id: 42 },
354 + text: ' exact draft text \n'
355 + });
356 + const dispatch = calls.find((call) => call[0] === 'dispatchMessage');
357 assert.equal(dispatch[1].text, ' exact draft text \n');
358 assert.deepEqual(dispatch[2], { isOwner: true, ownerId: OWNER });
359 });
test/github-workspace-provider-error-ui.test.js
+14 -4
@@ -4,21 +4,31 @@ import { NexaDevBot } from '../src/bot.js';
4 import { ApprovalService } from '../src/core/approval.js';
5
6 function replayStore() {
7 - return { async consume() { return true; } };
7 + return {
8 + async consume() {
9 + return true;
10 + }
11 + };
12 }
13
14 test('workspace approved provider errors are HTML-escaped before Telegram rendering', async () => {
15 const bot = new NexaDevBot({ TELEGRAM_WEBHOOK_SECRET: 'test-secret' });
12 - bot.approvals = new ApprovalService({ secret: 'test-secret', replayStore: replayStore() });
16 + bot.approvals = new ApprovalService({
17 + secret: 'test-secret',
18 + replayStore: replayStore()
19 + });
20 bot.router = {
21 async dispatchCallback(data, context) {
15 - if (context?.approved === true) throw new Error('GitHub provider <bad>& response');
22 + if (context?.approved === true)
23 + throw new Error('GitHub provider <bad>& response');
24 return null;
25 }
26 };
27 const edits = [];
28 bot.telegram = {
21 - async answerCallbackQuery() { return { ok: true }; },
29 + async answerCallbackQuery() {
30 + return { ok: true };
31 + },
32 async editMessageText(chatId, messageId, text, replyMarkup) {
33 edits.push({ chatId, messageId, text, replyMarkup });
34 return { ok: true };
test/github-workspace-provider.test.js
+252 -114
@@ -19,84 +19,158 @@ function withFetch(handler, run) {
19 globalThis.fetch = handler;
20 return Promise.resolve()
21 .then(run)
22 - .finally(() => { globalThis.fetch = original; });
22 + .finally(() => {
23 + globalThis.fetch = original;
24 + });
25 }
26
27 function repoResponse(url) {
28 if (String(url).endsWith('/repositories/123')) {
27 - return Response.json({ id: REPO, name: 'demo', full_name: 'davood/demo', default_branch: 'main' });
29 + return Response.json({
30 + id: REPO,
31 + name: 'demo',
32 + full_name: 'davood/demo',
33 + default_branch: 'main'
34 + });
35 }
36 return null;
37 }
38
39 test('getGitRef encodes slash branch names and only 404 may become an allowed missing ref', async () => {
40 const seen = [];
34 - await withFetch(async (url, options = {}) => {
35 - const repo = repoResponse(url);
36 - if (repo) return repo;
37 - seen.push([String(url), options.method || 'GET']);
38 - if (String(url).endsWith('/git/ref/heads/feature/mobile')) {
39 - return Response.json({ ref: 'refs/heads/feature/mobile', object: { type: 'commit', sha: HEAD } });
41 + await withFetch(
42 + async (url, options = {}) => {
43 + const repo = repoResponse(url);
44 + if (repo) return repo;
45 + seen.push([String(url), options.method || 'GET']);
46 + if (String(url).endsWith('/git/ref/heads/feature/mobile')) {
47 + return Response.json({
48 + ref: 'refs/heads/feature/mobile',
49 + object: { type: 'commit', sha: HEAD }
50 + });
51 + }
52 + return new Response(JSON.stringify({ message: 'Not Found' }), {
53 + status: 404,
54 + headers: { 'content-type': 'application/json' }
55 + });
56 + },
57 + async () => {
58 + const github = new GitHubService('token', 'davood');
59 + assert.deepEqual(await github.getGitRef(REPO, 'feature/mobile'), {
60 + branch: 'feature/mobile',
61 + sha: HEAD
62 + });
63 + assert.equal(
64 + await github.getGitRef(REPO, 'missing/branch', { allowMissing: true }),
65 + null
66 + );
67 + await assert.rejects(
68 + () => github.getGitRef(REPO, 'missing/branch'),
69 + /404/
70 + );
71 }
41 - return new Response(JSON.stringify({ message: 'Not Found' }), { status: 404, headers: { 'content-type': 'application/json' } });
42 - }, async () => {
43 - const github = new GitHubService('token', 'davood');
44 - assert.deepEqual(await github.getGitRef(REPO, 'feature/mobile'), { branch: 'feature/mobile', sha: HEAD });
45 - assert.equal(await github.getGitRef(REPO, 'missing/branch', { allowMissing: true }), null);
46 - await assert.rejects(() => github.getGitRef(REPO, 'missing/branch'), /404/);
47 - });
48 - assert.ok(seen.some(([url, method]) => url.endsWith('/git/ref/heads/feature/mobile') && method === 'GET'));
72 + );
73 + assert.ok(
74 + seen.some(
75 + ([url, method]) =>
76 + url.endsWith('/git/ref/heads/feature/mobile') && method === 'GET'
77 + )
78 + );
79 });
80
81 test('getGitRef still propagates non-404 provider errors and validates returned full SHA', async () => {
52 - await withFetch(async (url) => {
53 - const repo = repoResponse(url);
54 - if (repo) return repo;
55 - return new Response(JSON.stringify({ message: 'Forbidden' }), { status: 403, headers: { 'content-type': 'application/json' } });
56 - }, async () => {
57 - const github = new GitHubService('token', 'davood');
58 - await assert.rejects(() => github.getGitRef(REPO, 'main', { allowMissing: true }), /403 Forbidden/);
59 - });
82 + await withFetch(
83 + async (url) => {
84 + const repo = repoResponse(url);
85 + if (repo) return repo;
86 + return new Response(JSON.stringify({ message: 'Forbidden' }), {
87 + status: 403,
88 + headers: { 'content-type': 'application/json' }
89 + });
90 + },
91 + async () => {
92 + const github = new GitHubService('token', 'davood');
93 + await assert.rejects(
94 + () => github.getGitRef(REPO, 'main', { allowMissing: true }),
95 + /403 Forbidden/
96 + );
97 + }
98 + );
99
61 - await withFetch(async (url) => {
62 - const repo = repoResponse(url);
63 - if (repo) return repo;
64 - return Response.json({ ref: 'refs/heads/main', object: { sha: 'short' } });
65 - }, async () => {
66 - const github = new GitHubService('token', 'davood');
67 - await assert.rejects(() => github.getGitRef(REPO, 'main'), /SHA/);
68 - });
100 + await withFetch(
101 + async (url) => {
102 + const repo = repoResponse(url);
103 + if (repo) return repo;
104 + return Response.json({
105 + ref: 'refs/heads/main',
106 + object: { sha: 'short' }
107 + });
108 + },
109 + async () => {
110 + const github = new GitHubService('token', 'davood');
111 + await assert.rejects(() => github.getGitRef(REPO, 'main'), /SHA/);
112 + }
113 + );
114 });
115
116 test('Git Data primitives send exact blob tree commit and branch-ref requests', async () => {
117 const requests = [];
73 - await withFetch(async (url, options = {}) => {
74 - const repo = repoResponse(url);
75 - if (repo) return repo;
76 - requests.push({ url: String(url), method: options.method || 'GET', body: jsonBody(options) });
77 - const value = String(url);
78 - if (value.endsWith('/git/blobs')) return Response.json({ sha: BLOB1 }, { status: 201 });
79 - if (value.endsWith('/git/trees')) return Response.json({ sha: TREE }, { status: 201 });
80 - if (value.endsWith('/git/commits')) return Response.json({ sha: COMMIT }, { status: 201 });
81 - if (value.endsWith('/git/refs')) return Response.json({ ref: 'refs/heads/nexa/edit-W123456789', object: { sha: COMMIT } }, { status: 201 });
82 - return new Response('unexpected', { status: 500 });
83 - }, async () => {
84 - const github = new GitHubService('token', 'davood');
85 - assert.deepEqual(await github.createGitBlob(REPO, 'hello\n'), { sha: BLOB1 });
86 - assert.deepEqual(await github.createGitTree(REPO, {
87 - baseTreeSha: HEAD,
88 - entries: [
89 - { path: 'src/app.js', mode: '100644', type: 'blob', sha: BLOB1 },
90 - { path: 'src/other.js', mode: '100644', type: 'blob', sha: BLOB2 }
91 - ]
92 - }), { sha: TREE });
93 - assert.deepEqual(await github.createGitCommit(REPO, {
94 - message: 'edit app', treeSha: TREE, parentSha: HEAD, timestamp: TIMESTAMP
95 - }), { sha: COMMIT });
96 - assert.deepEqual(await github.createGitBranchRef(REPO, {
97 - branch: 'nexa/edit-W123456789', sha: COMMIT
98 - }), { ref: 'refs/heads/nexa/edit-W123456789', sha: COMMIT });
99 - });
118 + await withFetch(
119 + async (url, options = {}) => {
120 + const repo = repoResponse(url);
121 + if (repo) return repo;
122 + requests.push({
123 + url: String(url),
124 + method: options.method || 'GET',
125 + body: jsonBody(options)
126 + });
127 + const value = String(url);
128 + if (value.endsWith('/git/blobs'))
129 + return Response.json({ sha: BLOB1 }, { status: 201 });
130 + if (value.endsWith('/git/trees'))
131 + return Response.json({ sha: TREE }, { status: 201 });
132 + if (value.endsWith('/git/commits'))
133 + return Response.json({ sha: COMMIT }, { status: 201 });
134 + if (value.endsWith('/git/refs'))
135 + return Response.json(
136 + { ref: 'refs/heads/nexa/edit-W123456789', object: { sha: COMMIT } },
137 + { status: 201 }
138 + );
139 + return new Response('unexpected', { status: 500 });
140 + },
141 + async () => {
142 + const github = new GitHubService('token', 'davood');
143 + assert.deepEqual(await github.createGitBlob(REPO, 'hello\n'), {
144 + sha: BLOB1
145 + });
146 + assert.deepEqual(
147 + await github.createGitTree(REPO, {
148 + baseTreeSha: HEAD,
149 + entries: [
150 + { path: 'src/app.js', mode: '100644', type: 'blob', sha: BLOB1 },
151 + { path: 'src/other.js', mode: '100644', type: 'blob', sha: BLOB2 }
152 + ]
153 + }),
154 + { sha: TREE }
155 + );
156 + assert.deepEqual(
157 + await github.createGitCommit(REPO, {
158 + message: 'edit app',
159 + treeSha: TREE,
160 + parentSha: HEAD,
161 + timestamp: TIMESTAMP
162 + }),
163 + { sha: COMMIT }
164 + );
165 + assert.deepEqual(
166 + await github.createGitBranchRef(REPO, {
167 + branch: 'nexa/edit-W123456789',
168 + sha: COMMIT
169 + }),
170 + { ref: 'refs/heads/nexa/edit-W123456789', sha: COMMIT }
171 + );
172 + }
173 + );
174
175 assert.deepEqual(requests, [
176 {
@@ -122,8 +196,16 @@ test('Git Data primitives send exact blob tree commit and branch-ref requests',
196 message: 'edit app',
197 tree: TREE,
198 parents: [HEAD],
125 - author: { name: 'Nexa Dev Bot', email: 'nexa-dev-bot@users.noreply.github.com', date: TIMESTAMP },
126 - committer: { name: 'Nexa Dev Bot', email: 'nexa-dev-bot@users.noreply.github.com', date: TIMESTAMP }
199 + author: {
200 + name: 'Nexa Dev Bot',
201 + email: 'nexa-dev-bot@users.noreply.github.com',
202 + date: TIMESTAMP
203 + },
204 + committer: {
205 + name: 'Nexa Dev Bot',
206 + email: 'nexa-dev-bot@users.noreply.github.com',
207 + date: TIMESTAMP
208 + }
209 }
210 },
211 {
@@ -136,68 +218,124 @@ test('Git Data primitives send exact blob tree commit and branch-ref requests',
218
219 test('Git Data primitives validate all full SHAs and preserve deterministic retry bodies', async () => {
220 const commitBodies = [];
139 - await withFetch(async (url, options = {}) => {
140 - const repo = repoResponse(url);
141 - if (repo) return repo;
142 - if (String(url).endsWith('/git/commits')) {
143 - commitBodies.push(jsonBody(options));
144 - return Response.json({ sha: COMMIT }, { status: 201 });
145 - }
146 - return Response.json({ sha: TREE }, { status: 201 });
147 - }, async () => {
148 - const github = new GitHubService('token', 'davood');
149 - await assert.rejects(() => github.createGitTree(REPO, { baseTreeSha: 'short', entries: [] }), /SHA/);
150 - await assert.rejects(() => github.createGitTree(REPO, {
151 - baseTreeSha: TREE,
152 - entries: [{ path: 'a.js', mode: '100644', type: 'blob', sha: 'short' }]
153 - }), /SHA/);
154 - await assert.rejects(() => github.createGitCommit(REPO, { message: 'x', treeSha: 'short', parentSha: HEAD, timestamp: TIMESTAMP }), /SHA/);
155 - await assert.rejects(() => github.createGitCommit(REPO, { message: 'x', treeSha: TREE, parentSha: 'short', timestamp: TIMESTAMP }), /SHA/);
156 - await assert.rejects(() => github.createGitBranchRef(REPO, { branch: 'nexa/edit-W123456789', sha: 'short' }), /SHA/);
221 + await withFetch(
222 + async (url, options = {}) => {
223 + const repo = repoResponse(url);
224 + if (repo) return repo;
225 + if (String(url).endsWith('/git/commits')) {
226 + commitBodies.push(jsonBody(options));
227 + return Response.json({ sha: COMMIT }, { status: 201 });
228 + }
229 + return Response.json({ sha: TREE }, { status: 201 });
230 + },
231 + async () => {
232 + const github = new GitHubService('token', 'davood');
233 + await assert.rejects(
234 + () => github.createGitTree(REPO, { baseTreeSha: 'short', entries: [] }),
235 + /SHA/
236 + );
237 + await assert.rejects(
238 + () =>
239 + github.createGitTree(REPO, {
240 + baseTreeSha: TREE,
241 + entries: [
242 + { path: 'a.js', mode: '100644', type: 'blob', sha: 'short' }
243 + ]
244 + }),
245 + /SHA/
246 + );
247 + await assert.rejects(
248 + () =>
249 + github.createGitCommit(REPO, {
250 + message: 'x',
251 + treeSha: 'short',
252 + parentSha: HEAD,
253 + timestamp: TIMESTAMP
254 + }),
255 + /SHA/
256 + );
257 + await assert.rejects(
258 + () =>
259 + github.createGitCommit(REPO, {
260 + message: 'x',
261 + treeSha: TREE,
262 + parentSha: 'short',
263 + timestamp: TIMESTAMP
264 + }),
265 + /SHA/
266 + );
267 + await assert.rejects(
268 + () =>
269 + github.createGitBranchRef(REPO, {
270 + branch: 'nexa/edit-W123456789',
271 + sha: 'short'
272 + }),
273 + /SHA/
274 + );
275
158 - const input = { message: 'same material', treeSha: TREE, parentSha: HEAD, timestamp: TIMESTAMP };
159 - await github.createGitCommit(REPO, input);
160 - await github.createGitCommit(REPO, input);
161 - });
276 + const input = {
277 + message: 'same material',
278 + treeSha: TREE,
279 + parentSha: HEAD,
280 + timestamp: TIMESTAMP
281 + };
282 + await github.createGitCommit(REPO, input);
283 + await github.createGitCommit(REPO, input);
284 + }
285 + );
286 assert.equal(commitBodies.length, 2);
287 assert.deepEqual(commitBodies[0], commitBodies[1]);
288 });
289
290 test('provider 409 and 422 remain explicit and an existing different target ref never triggers an update or force endpoint', async () => {
291 for (const status of [409, 422]) {
168 - await withFetch(async (url, options = {}) => {
169 - const repo = repoResponse(url);
170 - if (repo) return repo;
171 - return new Response(JSON.stringify({ message: 'Reference conflict' }), {
172 - status,
173 - headers: { 'content-type': 'application/json' }
174 - });
175 - }, async () => {
176 - const github = new GitHubService('token', 'davood');
177 - await assert.rejects(
178 - () => github.createGitBranchRef(REPO, { branch: 'nexa/edit-W123456789', sha: COMMIT }),
179 - new RegExp(String(status))
180 - );
181 - });
292 + await withFetch(
293 + async (url, options = {}) => {
294 + const repo = repoResponse(url);
295 + if (repo) return repo;
296 + return new Response(JSON.stringify({ message: 'Reference conflict' }), {
297 + status,
298 + headers: { 'content-type': 'application/json' }
299 + });
300 + },
301 + async () => {
302 + const github = new GitHubService('token', 'davood');
303 + await assert.rejects(
304 + () =>
305 + github.createGitBranchRef(REPO, {
306 + branch: 'nexa/edit-W123456789',
307 + sha: COMMIT
308 + }),
309 + new RegExp(String(status))
310 + );
311 + }
312 + );
313 }
314
315 const calls = [];
185 - await withFetch(async (url, options = {}) => {
186 - const repo = repoResponse(url);
187 - if (repo) return repo;
188 - calls.push({ url: String(url), method: options.method || 'GET' });
189 - if (String(url).endsWith('/git/ref/heads/nexa/edit-W123456789')) {
190 - return Response.json({ object: { sha: HEAD } });
316 + await withFetch(
317 + async (url, options = {}) => {
318 + const repo = repoResponse(url);
319 + if (repo) return repo;
320 + calls.push({ url: String(url), method: options.method || 'GET' });
321 + if (String(url).endsWith('/git/ref/heads/nexa/edit-W123456789')) {
322 + return Response.json({ object: { sha: HEAD } });
323 + }
324 + return new Response('unexpected', { status: 500 });
325 + },
326 + async () => {
327 + const github = new GitHubService('token', 'davood');
328 + const existing = await github.getGitRef(REPO, 'nexa/edit-W123456789', {
329 + allowMissing: true
330 + });
331 + assert.deepEqual(existing, { branch: 'nexa/edit-W123456789', sha: HEAD });
332 + assert.notEqual(existing.sha, COMMIT);
333 + }
334 + );
335 + assert.deepEqual(calls, [
336 + {
337 + url: 'https://api.github.com/repos/davood/demo/git/ref/heads/nexa/edit-W123456789',
338 + method: 'GET'
339 }
192 - return new Response('unexpected', { status: 500 });
193 - }, async () => {
194 - const github = new GitHubService('token', 'davood');
195 - const existing = await github.getGitRef(REPO, 'nexa/edit-W123456789', { allowMissing: true });
196 - assert.deepEqual(existing, { branch: 'nexa/edit-W123456789', sha: HEAD });
197 - assert.notEqual(existing.sha, COMMIT);
198 - });
199 - assert.deepEqual(calls, [{
200 - url: 'https://api.github.com/repos/davood/demo/git/ref/heads/nexa/edit-W123456789',
201 - method: 'GET'
202 - }]);
340 + ]);
341 });
test/github-workspace-ui.test.js
+218 -50
@@ -7,8 +7,14 @@ function makeMenu() {
7 const calls = [];
8 return {
9 calls,
10 - async getReposListView() { calls.push('/repos'); return { text: 'repos', reply_markup: { inline_keyboard: [] } }; },
11 - async renderByCallback(data) { calls.push(data); return { text: `legacy:${data}`, reply_markup: { inline_keyboard: [] } }; }
10 + async getReposListView() {
11 + calls.push('/repos');
12 + return { text: 'repos', reply_markup: { inline_keyboard: [] } };
13 + },
14 + async renderByCallback(data) {
15 + calls.push(data);
16 + return { text: `legacy:${data}`, reply_markup: { inline_keyboard: [] } };
17 + }
18 };
19 }
20
@@ -23,7 +29,7 @@ function makeWorkspaces() {
29 workspaces,
30 async createNavigationRefs({ ownerId, refs: input }) {
31 calls.push(['createNavigationRefs', ownerId, structuredClone(input)]);
26 - return input.map(ref => {
32 + return input.map((ref) => {
33 refCounter += 1;
34 const refId = `R${String(refCounter).padStart(9, '0')}`;
35 refs.set(`${ownerId}:${refId}`, structuredClone(ref));
@@ -35,8 +41,18 @@ function makeWorkspaces() {
41 return refs.get(`${ownerId}:${refId}`) || null;
42 },
43 async createWorkspace(payload) {
38 - calls.push(['createWorkspace', payload.ownerId, payload.path, payload.baseHeadSha]);
39 - const workspace = { id: 'W000000001', state: 'DRAFT', draftText: payload.originalText, ...payload };
44 + calls.push([
45 + 'createWorkspace',
46 + payload.ownerId,
47 + payload.path,
48 + payload.baseHeadSha
49 + ]);
50 + const workspace = {
51 + id: 'W000000001',
52 + state: 'DRAFT',
53 + draftText: payload.originalText,
54 + ...payload
55 + };
56 workspaces.set(`${payload.ownerId}:${workspace.id}`, workspace);
57 return workspace;
58 },
@@ -47,7 +63,11 @@ function makeWorkspaces() {
63 };
64 }
65
50 -function makeGitHub({ archived = false, fileText = 'export const ok = true;\n', filePath = 'src/deep/really-long-file-name-for-mobile-editor.js' } = {}) {
66 +function makeGitHub({
67 + archived = false,
68 + fileText = 'export const ok = true;\n',
69 + filePath = 'src/deep/really-long-file-name-for-mobile-editor.js'
70 +} = {}) {
71 const calls = [];
72 const headSha = 'a'.repeat(40);
73 const treeSha = 'b'.repeat(40);
@@ -59,16 +79,42 @@ function makeGitHub({ archived = false, fileText = 'export const ok = true;\n',
79 blobSha,
80 async getRepository(repoId) {
81 calls.push(['getRepository', Number(repoId)]);
62 - return { id: String(repoId), name: 'demo', fullName: 'davood/demo', defaultBranch: 'main', archived };
82 + return {
83 + id: String(repoId),
84 + name: 'demo',
85 + fullName: 'davood/demo',
86 + defaultBranch: 'main',
87 + archived
88 + };
89 },
90 async listFiles(repoId, path = '', options = {}) {
91 calls.push(['listFiles', Number(repoId), path, options.ref || null]);
92 if (path === 'src/deep') {
67 - return [{ name: 'nested.js', path: 'src/deep/nested.js', type: 'file', size: 20, sha: 'd'.repeat(40) }];
93 + return [
94 + {
95 + name: 'nested.js',
96 + path: 'src/deep/nested.js',
97 + type: 'file',
98 + size: 20,
99 + sha: 'd'.repeat(40)
100 + }
101 + ];
102 }
103 return [
70 - { name: 'deep', path: 'src/deep', type: 'dir', size: 0, sha: 'e'.repeat(40) },
71 - { name: 'really-long-file-name-for-mobile-editor.js', path: filePath, type: 'file', size: new TextEncoder().encode(fileText).byteLength, sha: blobSha }
104 + {
105 + name: 'deep',
106 + path: 'src/deep',
107 + type: 'dir',
108 + size: 0,
109 + sha: 'e'.repeat(40)
110 + },
111 + {
112 + name: 'really-long-file-name-for-mobile-editor.js',
113 + path: filePath,
114 + type: 'file',
115 + size: new TextEncoder().encode(fileText).byteLength,
116 + sha: blobSha
117 + }
118 ];
119 },
120 async getBranchSnapshot(repoId, branch) {
@@ -104,7 +150,9 @@ test('exact files callback resolves side-effect-free then renders path-safe shor
150 assert.deepEqual(workspaces.calls, []);
151
152 const view = await route.execute();
107 - const buttons = flatten(view).filter(button => button.callback_data?.startsWith('wnav:'));
153 + const buttons = flatten(view).filter((button) =>
154 + button.callback_data?.startsWith('wnav:')
155 + );
156 assert.equal(buttons.length, 2);
157 for (const button of buttons) {
158 assert.match(button.callback_data, /^wnav:[A-Za-z0-9_-]{10}$/);
@@ -118,8 +166,12 @@ test('nested directory resolves through short ref and preserves the full server-
166 const github = makeGitHub();
167 const workspaces = makeWorkspaces();
168 const plugin = createGitHubPlugin({ github, menu: makeMenu(), workspaces });
121 - const root = await plugin.resolveCallback('files:123', { ownerId: '42' }).execute();
122 - const dirCallback = flatten(root).find(button => button.text?.includes('deep'))?.callback_data;
169 + const root = await plugin
170 + .resolveCallback('files:123', { ownerId: '42' })
171 + .execute();
172 + const dirCallback = flatten(root).find((button) =>
173 + button.text?.includes('deep')
174 + )?.callback_data;
175 assert.match(dirCallback, /^wnav:/);
176
177 github.calls.length = 0;
@@ -129,26 +181,64 @@ test('nested directory resolves through short ref and preserves the full server-
181 assert.deepEqual(github.calls, []);
182 assert.deepEqual(workspaces.calls, []);
183 const nested = await route.execute();
132 - assert.ok(flatten(nested).some(button => /^wnav:/.test(button.callback_data || '')));
133 - assert.ok(github.calls.some(call => call[0] === 'listFiles' && call[2] === 'src/deep'));
184 + assert.ok(
185 + flatten(nested).some((button) => /^wnav:/.test(button.callback_data || ''))
186 + );
187 + assert.ok(
188 + github.calls.some(
189 + (call) => call[0] === 'listFiles' && call[2] === 'src/deep'
190 + )
191 + );
192 });
193
194 test('eligible file preview including README shows Edit while risky or truly oversized content stays readable with explicit disabled reason', async () => {
195 for (const fixture of [
196 { path: 'src/app.js', text: 'console.log(1);\n', editable: true },
139 - { path: 'README.md', text: `# Nexa Dev Bot\n\n${'x'.repeat(8200)}`, editable: true },
140 - { path: '.env.production', text: 'NOT_A_REAL_SECRET=value\n', editable: false, reason: /sensitive/i },
141 - { path: 'large.txt', text: 'x'.repeat(20001), editable: false, reason: /20,000|20000/ },
142 - { path: 'asset.txt', text: 'version https://git-lfs.github.com/spec/v1\noid sha256:abc\nsize 9\n', editable: false, reason: /LFS/i }
197 + {
198 + path: 'README.md',
199 + text: `# Nexa Dev Bot\n\n${'x'.repeat(8200)}`,
200 + editable: true
201 + },
202 + {
203 + path: '.env.production',
204 + text: 'NOT_A_REAL_SECRET=value\n',
205 + editable: false,
206 + reason: /sensitive/i
207 + },
208 + {
209 + path: 'large.txt',
210 + text: 'x'.repeat(20001),
211 + editable: false,
212 + reason: /20,000|20000/
213 + },
214 + {
215 + path: 'asset.txt',
216 + text: 'version https://git-lfs.github.com/spec/v1\noid sha256:abc\nsize 9\n',
217 + editable: false,
218 + reason: /LFS/i
219 + }
220 ]) {
144 - const github = makeGitHub({ fileText: fixture.text, filePath: fixture.path });
221 + const github = makeGitHub({
222 + fileText: fixture.text,
223 + filePath: fixture.path
224 + });
225 const workspaces = makeWorkspaces();
226 const plugin = createGitHubPlugin({ github, menu: makeMenu(), workspaces });
147 - const root = await plugin.resolveCallback('files:123', { ownerId: '42' }).execute();
148 - const fileCallback = flatten(root).find(button => button.callback_data?.startsWith('wnav:') && !button.text?.includes('deep'))?.callback_data;
149 - const view = await plugin.resolveCallback(fileCallback, { ownerId: '42' }).execute();
227 + const root = await plugin
228 + .resolveCallback('files:123', { ownerId: '42' })
229 + .execute();
230 + const fileCallback = flatten(root).find(
231 + (button) =>
232 + button.callback_data?.startsWith('wnav:') &&
233 + !button.text?.includes('deep')
234 + )?.callback_data;
235 + const view = await plugin
236 + .resolveCallback(fileCallback, { ownerId: '42' })
237 + .execute();
238 assert.match(view.text, /پیش.?نمایش|فایل/i);
151 - const edit = flatten(view).find(button => button.callback_data?.startsWith('wedit:'));
239 + const edit = flatten(view).find((button) =>
240 + button.callback_data?.startsWith('wedit:')
241 + );
242 if (fixture.editable) {
243 assert.ok(edit, fixture.path);
244 } else {
@@ -162,10 +252,20 @@ test('wedit pins default-branch snapshot and exact file before creating a durabl
252 const github = makeGitHub({ filePath: 'src/app.js', fileText: 'before\n' });
253 const workspaces = makeWorkspaces();
254 const plugin = createGitHubPlugin({ github, menu: makeMenu(), workspaces });
165 - const root = await plugin.resolveCallback('files:123', { ownerId: '42' }).execute();
166 - const fileCallback = flatten(root).find(button => button.callback_data?.startsWith('wnav:') && !button.text?.includes('deep'))?.callback_data;
167 - const fileView = await plugin.resolveCallback(fileCallback, { ownerId: '42' }).execute();
168 - const editCallback = flatten(fileView).find(button => button.callback_data?.startsWith('wedit:'))?.callback_data;
255 + const root = await plugin
256 + .resolveCallback('files:123', { ownerId: '42' })
257 + .execute();
258 + const fileCallback = flatten(root).find(
259 + (button) =>
260 + button.callback_data?.startsWith('wnav:') &&
261 + !button.text?.includes('deep')
262 + )?.callback_data;
263 + const fileView = await plugin
264 + .resolveCallback(fileCallback, { ownerId: '42' })
265 + .execute();
266 + const editCallback = flatten(fileView).find((button) =>
267 + button.callback_data?.startsWith('wedit:')
268 + )?.callback_data;
269
270 github.calls.length = 0;
271 workspaces.calls.length = 0;
@@ -175,27 +275,58 @@ test('wedit pins default-branch snapshot and exact file before creating a durabl
275 assert.deepEqual(workspaces.calls, []);
276 const draftView = await route.execute();
277
178 - const snapshotIndex = github.calls.findIndex(call => call[0] === 'getBranchSnapshot');
179 - const fileIndex = github.calls.findIndex(call => call[0] === 'getFileAtRef');
180 - const createCall = workspaces.calls.find(call => call[0] === 'createWorkspace');
278 + const snapshotIndex = github.calls.findIndex(
279 + (call) => call[0] === 'getBranchSnapshot'
280 + );
281 + const fileIndex = github.calls.findIndex(
282 + (call) => call[0] === 'getFileAtRef'
283 + );
284 + const createCall = workspaces.calls.find(
285 + (call) => call[0] === 'createWorkspace'
286 + );
287 assert.ok(snapshotIndex >= 0 && fileIndex > snapshotIndex);
182 - assert.deepEqual(github.calls[fileIndex].slice(2), ['src/app.js', github.headSha]);
183 - assert.deepEqual(createCall, ['createWorkspace', '42', 'src/app.js', github.headSha]);
288 + assert.deepEqual(github.calls[fileIndex].slice(2), [
289 + 'src/app.js',
290 + github.headSha
291 + ]);
292 + assert.deepEqual(createCall, [
293 + 'createWorkspace',
294 + '42',
295 + 'src/app.js',
296 + github.headSha
297 + ]);
298 assert.match(draftView.text, /Draft|پیش.?نویس/i);
185 - assert.ok(flatten(draftView).some(button => button.callback_data === 'ws:W000000001'));
299 + assert.ok(
300 + flatten(draftView).some(
301 + (button) => button.callback_data === 'ws:W000000001'
302 + )
303 + );
304 });
305
306 test('archived repository cannot create an editable workspace', async () => {
307 const github = makeGitHub({ archived: true, filePath: 'src/app.js' });
308 const workspaces = makeWorkspaces();
309 const plugin = createGitHubPlugin({ github, menu: makeMenu(), workspaces });
192 - const root = await plugin.resolveCallback('files:123', { ownerId: '42' }).execute();
193 - const fileCallback = flatten(root).find(button => button.callback_data?.startsWith('wnav:') && !button.text?.includes('deep'))?.callback_data;
194 - const fileView = await plugin.resolveCallback(fileCallback, { ownerId: '42' }).execute();
195 - const editCallback = flatten(fileView).find(button => button.callback_data?.startsWith('wedit:'))?.callback_data;
310 + const root = await plugin
311 + .resolveCallback('files:123', { ownerId: '42' })
312 + .execute();
313 + const fileCallback = flatten(root).find(
314 + (button) =>
315 + button.callback_data?.startsWith('wnav:') &&
316 + !button.text?.includes('deep')
317 + )?.callback_data;
318 + const fileView = await plugin
319 + .resolveCallback(fileCallback, { ownerId: '42' })
320 + .execute();
321 + const editCallback = flatten(fileView).find((button) =>
322 + button.callback_data?.startsWith('wedit:')
323 + )?.callback_data;
324 assert.equal(editCallback, undefined);
325 assert.match(fileView.text, /archiv|آرشیو/i);
198 - assert.equal(workspaces.calls.some(call => call[0] === 'createWorkspace'), false);
326 + assert.equal(
327 + workspaces.calls.some((call) => call[0] === 'createWorkspace'),
328 + false
329 + );
330 });
331
332 test('legacy tree blob and path-bearing files callbacks remain on MenuManager path', async () => {
@@ -216,7 +347,11 @@ test('legacy tree blob and path-bearing files callbacks remain on MenuManager pa
347 });
348
349 test('workspace READ actions are declared and all short callback families fit Telegram limit', () => {
219 - const plugin = createGitHubPlugin({ github: makeGitHub(), menu: makeMenu(), workspaces: makeWorkspaces() });
350 + const plugin = createGitHubPlugin({
351 + github: makeGitHub(),
352 + menu: makeMenu(),
353 + workspaces: makeWorkspaces()
354 + });
355 for (const actionId of [
356 'github.workspace.navigate',
357 'github.workspace.create',
@@ -229,8 +364,14 @@ test('workspace READ actions are declared and all short callback families fit Te
364 assert.equal(plugin.manifest.actions[actionId]?.risk, 'READ', actionId);
365 }
366 for (const callback of [
232 - 'wnav:R123456789', 'wedit:R123456789', 'ws:W123456789', 'wtext:W123456789',
233 - 'wmsg:W123456789', 'wdiff:W123456789', 'wready:W123456789', 'wcancel:W123456789'
367 + 'wnav:R123456789',
368 + 'wedit:R123456789',
369 + 'ws:W123456789',
370 + 'wtext:W123456789',
371 + 'wmsg:W123456789',
372 + 'wdiff:W123456789',
373 + 'wready:W123456789',
374 + 'wcancel:W123456789'
375 ]) {
376 assert.ok(new TextEncoder().encode(callback).byteLength <= 64, callback);
377 }
@@ -245,21 +386,48 @@ test('GitHubService reads pinned branch snapshot and UTF-8 file at full SHA', as
386 globalThis.fetch = async (url, options = {}) => {
387 seen.push([String(url), options.method || 'GET']);
388 const value = String(url);
248 - if (value.endsWith('/repositories/123')) return Response.json({ id: 123, name: 'demo', full_name: 'davood/demo', default_branch: 'main' });
249 - if (value.endsWith('/repos/davood/demo/git/ref/heads/main')) return Response.json({ object: { sha: headSha } });
250 - if (value.endsWith(`/repos/davood/demo/git/commits/${headSha}`)) return Response.json({ sha: headSha, tree: { sha: treeSha } });
251 - if (value.endsWith(`/repos/davood/demo/contents/src/app.js?ref=${headSha}`)) {
252 - return Response.json({ type: 'file', path: 'src/app.js', sha: blobSha, size: 6, encoding: 'base64', content: btoa('hello\n') });
389 + if (value.endsWith('/repositories/123'))
390 + return Response.json({
391 + id: 123,
392 + name: 'demo',
393 + full_name: 'davood/demo',
394 + default_branch: 'main'
395 + });
396 + if (value.endsWith('/repos/davood/demo/git/ref/heads/main'))
397 + return Response.json({ object: { sha: headSha } });
398 + if (value.endsWith(`/repos/davood/demo/git/commits/${headSha}`))
399 + return Response.json({ sha: headSha, tree: { sha: treeSha } });
400 + if (
401 + value.endsWith(`/repos/davood/demo/contents/src/app.js?ref=${headSha}`)
402 + ) {
403 + return Response.json({
404 + type: 'file',
405 + path: 'src/app.js',
406 + sha: blobSha,
407 + size: 6,
408 + encoding: 'base64',
409 + content: btoa('hello\n')
410 + });
411 }
412 return new Response('unexpected', { status: 500 });
413 };
414 try {
415 const github = new GitHubService('token', 'davood');
258 - assert.deepEqual(await github.getBranchSnapshot(123, 'main'), { branch: 'main', headSha, treeSha });
416 + assert.deepEqual(await github.getBranchSnapshot(123, 'main'), {
417 + branch: 'main',
418 + headSha,
419 + treeSha
420 + });
421 assert.deepEqual(await github.getFileAtRef(123, 'src/app.js', headSha), {
260 - path: 'src/app.js', sha: blobSha, size: 6, encoding: 'utf-8', content: 'hello\n'
422 + path: 'src/app.js',
423 + sha: blobSha,
424 + size: 6,
425 + encoding: 'utf-8',
426 + content: 'hello\n'
427 });
262 - assert.ok(seen.some(([url]) => url.endsWith(`/contents/src/app.js?ref=${headSha}`)));
428 + assert.ok(
429 + seen.some(([url]) => url.endsWith(`/contents/src/app.js?ref=${headSha}`))
430 + );
431 } finally {
432 globalThis.fetch = originalFetch;
433 }
test/github.test.js
+190 -125
@@ -39,158 +39,223 @@ test('GitHubService surfaces GitHub API failures instead of returning sample dat
39 async () => json({ message: 'Bad credentials' }, 401),
40 async () => {
41 const service = new GitHubService('bad-token', 'davoodmehraban89');
42 - await assert.rejects(() => service.listPullRequests('Factor-easy'), /401|Bad credentials/i);
42 + await assert.rejects(
43 + () => service.listPullRequests('Factor-easy'),
44 + /401|Bad credentials/i
45 + );
46 }
47 );
48 });
49
50 test('GitHubService repository listing uses the authenticated user endpoint', async () => {
51 let requestedUrl = '';
49 - await withFetch(async (url) => {
50 - requestedUrl = String(url);
51 - if (requestedUrl.startsWith('https://api.github.com/user/repos?')) {
52 - return json([
53 - {
54 - name: 'nexa-dev-bot',
55 - full_name: 'davoodmehraban89/nexa-dev-bot',
56 - private: true,
57 - stargazers_count: 0,
58 - forks_count: 0,
59 - description: 'Personal Telegram developer console for GitHub'
60 - }
61 - ]);
52 + await withFetch(
53 + async (url) => {
54 + requestedUrl = String(url);
55 + if (requestedUrl.startsWith('https://api.github.com/user/repos?')) {
56 + return json([
57 + {
58 + name: 'nexa-dev-bot',
59 + full_name: 'davoodmehraban89/nexa-dev-bot',
60 + private: true,
61 + stargazers_count: 0,
62 + forks_count: 0,
63 + description: 'Personal Telegram developer console for GitHub'
64 + }
65 + ]);
66 + }
67 + return json({ message: 'Not Found' }, 404);
68 + },
69 + async () => {
70 + const service = new GitHubService('token', 'davoodmehraban89');
71 + const repos = await service.listRepositories();
72 + assert.match(requestedUrl, /\/user\/repos\?/);
73 + assert.equal(repos.length, 1);
74 + assert.equal(repos[0].name, 'nexa-dev-bot');
75 + assert.equal(repos[0].private, true);
76 }
63 - return json({ message: 'Not Found' }, 404);
64 - }, async () => {
65 - const service = new GitHubService('token', 'davoodmehraban89');
66 - const repos = await service.listRepositories();
67 - assert.match(requestedUrl, /\/user\/repos\?/);
68 - assert.equal(repos.length, 1);
69 - assert.equal(repos[0].name, 'nexa-dev-bot');
70 - assert.equal(repos[0].private, true);
71 - });
77 + );
78 });
79
80 test('GitHubService lists and maps workflow runs for a numeric repository id', async () => {
81 const calls = [];
76 - await withFetch(async (url, options = {}) => {
77 - const value = String(url);
78 - calls.push({ url: value, method: options.method || 'GET' });
79 - if (value === 'https://api.github.com/repositories/123') return json(repositoryContext());
80 - if (value === 'https://api.github.com/repos/davoodmehraban89/nexa-dev-bot/actions/runs?per_page=10') {
81 - return json({ workflow_runs: [{
82 + await withFetch(
83 + async (url, options = {}) => {
84 + const value = String(url);
85 + calls.push({ url: value, method: options.method || 'GET' });
86 + if (value === 'https://api.github.com/repositories/123')
87 + return json(repositoryContext());
88 + if (
89 + value ===
90 + 'https://api.github.com/repos/davoodmehraban89/nexa-dev-bot/actions/runs?per_page=10'
91 + ) {
92 + return json({
93 + workflow_runs: [
94 + {
95 + id: 77,
96 + name: 'CI',
97 + status: 'completed',
98 + conclusion: 'failure',
99 + event: 'push',
100 + head_branch: 'main',
101 + head_sha: 'abcdef0123456789',
102 + run_number: 12,
103 + html_url: 'https://github.com/x/actions/runs/77',
104 + created_at: '2026-10-03T00:00:00Z',
105 + updated_at: '2026-10-03T00:01:00Z'
106 + }
107 + ]
108 + });
109 + }
110 + return json({ message: 'Not Found' }, 404);
111 + },
112 + async () => {
113 + const service = new GitHubService('token');
114 + const runs = await service.listWorkflowRuns(123);
115 + assert.equal(runs.length, 1);
116 + assert.deepEqual(runs[0], {
117 id: 77,
118 name: 'CI',
119 status: 'completed',
120 conclusion: 'failure',
121 event: 'push',
87 - head_branch: 'main',
88 - head_sha: 'abcdef0123456789',
89 - run_number: 12,
90 - html_url: 'https://github.com/x/actions/runs/77',
91 - created_at: '2026-10-03T00:00:00Z',
92 - updated_at: '2026-10-03T00:01:00Z'
93 - }] });
122 + branch: 'main',
123 + sha: 'abcdef0',
124 + runNumber: 12,
125 + url: 'https://github.com/x/actions/runs/77',
126 + createdAt: '2026-10-03T00:00:00Z',
127 + updatedAt: '2026-10-03T00:01:00Z'
128 + });
129 + assert.equal(calls.at(-1).method, 'GET');
130 }
95 - return json({ message: 'Not Found' }, 404);
96 - }, async () => {
97 - const service = new GitHubService('token');
98 - const runs = await service.listWorkflowRuns(123);
99 - assert.equal(runs.length, 1);
100 - assert.deepEqual(runs[0], {
101 - id: 77,
102 - name: 'CI',
103 - status: 'completed',
104 - conclusion: 'failure',
105 - event: 'push',
106 - branch: 'main',
107 - sha: 'abcdef0',
108 - runNumber: 12,
109 - url: 'https://github.com/x/actions/runs/77',
110 - createdAt: '2026-10-03T00:00:00Z',
111 - updatedAt: '2026-10-03T00:01:00Z'
112 - });
113 - assert.equal(calls.at(-1).method, 'GET');
114 - });
131 + );
132 });
133
134 test('GitHubService gets workflow run and lists jobs with bounded step details', async () => {
118 - await withFetch(async (url) => {
119 - const value = String(url);
120 - if (value === 'https://api.github.com/repositories/123') return json(repositoryContext());
121 - if (value.endsWith('/actions/runs/77')) {
122 - return json({
123 - id: 77,
124 - name: 'CI',
125 - status: 'completed',
126 - conclusion: 'failure',
127 - event: 'push',
128 - head_branch: 'main',
129 - head_sha: 'abcdef0123456789',
130 - run_number: 12,
131 - html_url: 'https://github.com/x/actions/runs/77',
132 - created_at: '2026-10-03T00:00:00Z',
133 - updated_at: '2026-10-03T00:01:00Z'
134 - });
135 - }
136 - if (value.endsWith('/actions/runs/77/jobs?per_page=20')) {
137 - return json({ jobs: [{
138 - id: 88,
139 - name: 'test',
140 - status: 'completed',
141 - conclusion: 'failure',
142 - started_at: '2026-10-03T00:00:10Z',
143 - completed_at: '2026-10-03T00:00:50Z',
144 - html_url: 'https://github.com/x/actions/runs/77/job/88',
145 - steps: [
146 - { number: 1, name: 'checkout', status: 'completed', conclusion: 'success' },
147 - { number: 2, name: 'test', status: 'completed', conclusion: 'failure' }
148 - ]
149 - }] });
135 + await withFetch(
136 + async (url) => {
137 + const value = String(url);
138 + if (value === 'https://api.github.com/repositories/123')
139 + return json(repositoryContext());
140 + if (value.endsWith('/actions/runs/77')) {
141 + return json({
142 + id: 77,
143 + name: 'CI',
144 + status: 'completed',
145 + conclusion: 'failure',
146 + event: 'push',
147 + head_branch: 'main',
148 + head_sha: 'abcdef0123456789',
149 + run_number: 12,
150 + html_url: 'https://github.com/x/actions/runs/77',
151 + created_at: '2026-10-03T00:00:00Z',
152 + updated_at: '2026-10-03T00:01:00Z'
153 + });
154 + }
155 + if (value.endsWith('/actions/runs/77/jobs?per_page=20')) {
156 + return json({
157 + jobs: [
158 + {
159 + id: 88,
160 + name: 'test',
161 + status: 'completed',
162 + conclusion: 'failure',
163 + started_at: '2026-10-03T00:00:10Z',
164 + completed_at: '2026-10-03T00:00:50Z',
165 + html_url: 'https://github.com/x/actions/runs/77/job/88',
166 + steps: [
167 + {
168 + number: 1,
169 + name: 'checkout',
170 + status: 'completed',
171 + conclusion: 'success'
172 + },
173 + {
174 + number: 2,
175 + name: 'test',
176 + status: 'completed',
177 + conclusion: 'failure'
178 + }
179 + ]
180 + }
181 + ]
182 + });
183 + }
184 + return json({ message: 'Not Found' }, 404);
185 + },
186 + async () => {
187 + const service = new GitHubService('token');
188 + const run = await service.getWorkflowRun(123, 77);
189 + assert.equal(run.id, 77);
190 + assert.equal(run.sha, 'abcdef0');
191 + const jobs = await service.listWorkflowJobs(123, 77);
192 + assert.equal(jobs.length, 1);
193 + assert.equal(jobs[0].id, 88);
194 + assert.equal(jobs[0].steps[1].conclusion, 'failure');
195 }
151 - return json({ message: 'Not Found' }, 404);
152 - }, async () => {
153 - const service = new GitHubService('token');
154 - const run = await service.getWorkflowRun(123, 77);
155 - assert.equal(run.id, 77);
156 - assert.equal(run.sha, 'abcdef0');
157 - const jobs = await service.listWorkflowJobs(123, 77);
158 - assert.equal(jobs.length, 1);
159 - assert.equal(jobs[0].id, 88);
160 - assert.equal(jobs[0].steps[1].conclusion, 'failure');
161 - });
196 + );
197 });
198
199 test('GitHubService uses POST endpoints for rerun failed and cancel and accepts empty success bodies', async () => {
200 const calls = [];
166 - await withFetch(async (url, options = {}) => {
167 - const value = String(url);
168 - calls.push({ url: value, method: options.method || 'GET', headers: options.headers });
169 - if (value === 'https://api.github.com/repositories/123') return json(repositoryContext());
170 - if (value.endsWith('/actions/runs/77/rerun-failed-jobs')) return new Response(null, { status: 201 });
171 - if (value.endsWith('/actions/runs/77/cancel')) return new Response(null, { status: 202 });
172 - return json({ message: 'Not Found' }, 404);
173 - }, async () => {
174 - const service = new GitHubService('token');
175 - assert.deepEqual(await service.rerunFailedWorkflowRun(123, 77), { accepted: true, status: 201 });
176 - assert.deepEqual(await service.cancelWorkflowRun(123, 77), { accepted: true, status: 202 });
177 - assert.equal(calls.find(call => call.url.endsWith('/rerun-failed-jobs')).method, 'POST');
178 - assert.equal(calls.find(call => call.url.endsWith('/cancel')).method, 'POST');
179 - });
180 -});
181 -
182 -test('GitHubService write actions surface provider permission/state errors', async () => {
183 - for (const [status, message] of [[403, 'Resource not accessible by personal access token'], [409, 'Conflict'], [422, 'Validation Failed']]) {
184 - await withFetch(async (url) => {
201 + await withFetch(
202 + async (url, options = {}) => {
203 const value = String(url);
186 - if (value === 'https://api.github.com/repositories/123') return json(repositoryContext());
187 - return json({ message }, status);
188 - }, async () => {
204 + calls.push({
205 + url: value,
206 + method: options.method || 'GET',
207 + headers: options.headers
208 + });
209 + if (value === 'https://api.github.com/repositories/123')
210 + return json(repositoryContext());
211 + if (value.endsWith('/actions/runs/77/rerun-failed-jobs'))
212 + return new Response(null, { status: 201 });
213 + if (value.endsWith('/actions/runs/77/cancel'))
214 + return new Response(null, { status: 202 });
215 + return json({ message: 'Not Found' }, 404);
216 + },
217 + async () => {
218 const service = new GitHubService('token');
190 - await assert.rejects(
191 - () => service.rerunFailedWorkflowRun(123, 77),
192 - new RegExp(`${status}|${message}`, 'i')
219 + assert.deepEqual(await service.rerunFailedWorkflowRun(123, 77), {
220 + accepted: true,
221 + status: 201
222 + });
223 + assert.deepEqual(await service.cancelWorkflowRun(123, 77), {
224 + accepted: true,
225 + status: 202
226 + });
227 + assert.equal(
228 + calls.find((call) => call.url.endsWith('/rerun-failed-jobs')).method,
229 + 'POST'
230 + );
231 + assert.equal(
232 + calls.find((call) => call.url.endsWith('/cancel')).method,
233 + 'POST'
234 );
194 - });
235 + }
236 + );
237 +});
238 +
239 +test('GitHubService write actions surface provider permission/state errors', async () => {
240 + for (const [status, message] of [
241 + [403, 'Resource not accessible by personal access token'],
242 + [409, 'Conflict'],
243 + [422, 'Validation Failed']
244 + ]) {
245 + await withFetch(
246 + async (url) => {
247 + const value = String(url);
248 + if (value === 'https://api.github.com/repositories/123')
249 + return json(repositoryContext());
250 + return json({ message }, status);
251 + },
252 + async () => {
253 + const service = new GitHubService('token');
254 + await assert.rejects(
255 + () => service.rerunFailedWorkflowRun(123, 77),
256 + new RegExp(`${status}|${message}`, 'i')
257 + );
258 + }
259 + );
260 }
261 });
test/help-guide.test.js
+156 -24
@@ -6,14 +6,26 @@ import { GuidedNexaDevBot } from '../src/guide-bot.js';
6
7 const github = {
8 owner: 'davoodmehraban89',
9 - async listRepositories() { return []; },
9 + async listRepositories() {
10 + return [];
11 + },
12 async getRepository(repo) {
11 - return { id: repo, name: String(repo), fullName: `davoodmehraban89/${repo}`, private: true, defaultBranch: 'main', archived: false };
13 + return {
14 + id: repo,
15 + name: String(repo),
16 + fullName: `davoodmehraban89/${repo}`,
17 + private: true,
18 + defaultBranch: 'main',
19 + archived: false
20 + };
21 }
22 };
23
24 function callbacks(view) {
16 - return (view.reply_markup?.inline_keyboard || []).flat().map(button => button.callback_data).filter(Boolean);
25 + return (view.reply_markup?.inline_keyboard || [])
26 + .flat()
27 + .map((button) => button.callback_data)
28 + .filter(Boolean);
29 }
30
31 describe('Nexa Dev Bot - in-app V2.1 guide', () => {
@@ -22,47 +34,120 @@ describe('Nexa Dev Bot - in-app V2.1 guide', () => {
34 it('exposes Guide from the main inline menu', () => {
35 const view = menu.getMainMenuView();
36 assert.ok(callbacks(view).includes('menu:help'));
25 - assert.ok(view.reply_markup.inline_keyboard.flat().some(button => button.text.includes('راهنما')));
37 + assert.ok(
38 + view.reply_markup.inline_keyboard
39 + .flat()
40 + .some((button) => button.text.includes('راهنما'))
41 + );
42 });
43
44 it('guide index and pages identify V2.1 and expose all seven navigable chapters', async () => {
45 const index = await menu.renderByCallback('menu:help');
46 assert.match(index.text, /راهنمای Nexa Dev.*V2\.1/);
47 const indexCallbacks = callbacks(index);
32 - for (const callback of ['help:1', 'help:2', 'help:3', 'help:4', 'help:5', 'help:6', 'help:7']) {
48 + for (const callback of [
49 + 'help:1',
50 + 'help:2',
51 + 'help:3',
52 + 'help:4',
53 + 'help:5',
54 + 'help:6',
55 + 'help:7'
56 + ]) {
57 assert.ok(indexCallbacks.includes(callback), `missing ${callback}`);
58 }
59
60 const menuHelp = await menu.renderByCallback('help:1');
37 - for (const label of ['منوی اصلی', 'پروژه‌ها', 'وضعیت', 'ابزارها', 'پیکربندی', 'امنیت', 'راهنما']) {
61 + for (const label of [
62 + 'منوی اصلی',
63 + 'پروژه‌ها',
64 + 'وضعیت',
65 + 'ابزارها',
66 + 'پیکربندی',
67 + 'امنیت',
68 + 'راهنما'
69 + ]) {
70 assert.ok(menuHelp.text.includes(label), `menu guide missing ${label}`);
71 }
72
73 const repoHelp = await menu.renderByCallback('help:2');
42 - for (const label of ['فایل‌ها', 'Pull Request', 'Commit', 'جزئیات Commit', 'CI / Actions', 'Branches', 'Issues', 'Releases', 'جزئیات Issue', 'Release notes']) {
74 + for (const label of [
75 + 'فایل‌ها',
76 + 'Pull Request',
77 + 'Commit',
78 + 'جزئیات Commit',
79 + 'CI / Actions',
80 + 'Branches',
81 + 'Issues',
82 + 'Releases',
83 + 'جزئیات Issue',
84 + 'Release notes'
85 + ]) {
86 assert.ok(repoHelp.text.includes(label), `repo guide missing ${label}`);
87 }
88
89 const workspaceHelp = await menu.renderByCallback('help:3');
47 - for (const label of ['Edit', 'Editor', 'Mini App', 'WORKSPACE_STORE', 'بارگذاری فایل', 'Paste متن', 'پیام Commit', 'Diff', 'آماده Commit', 'لغو Draft']) {
48 - assert.ok(workspaceHelp.text.includes(label), `workspace guide missing ${label}`);
90 + for (const label of [
91 + 'Edit',
92 + 'Editor',
93 + 'Mini App',
94 + 'WORKSPACE_STORE',
95 + 'بارگذاری فایل',
96 + 'Paste متن',
97 + 'پیام Commit',
98 + 'Diff',
99 + 'آماده Commit',
100 + 'لغو Draft'
101 + ]) {
102 + assert.ok(
103 + workspaceHelp.text.includes(label),
104 + `workspace guide missing ${label}`
105 + );
106 }
107
108 const ciHelp = await menu.renderByCallback('help:5');
52 - for (const label of ['Job', 'Artifacts', 'log', 'اجرای مجدد', 'لغو Workflow', 'بروزرسانی', 'جدیدتر', 'قدیمی‌تر']) {
109 + for (const label of [
110 + 'Job',
111 + 'Artifacts',
112 + 'log',
113 + 'اجرای مجدد',
114 + 'لغو Workflow',
115 + 'بروزرسانی',
116 + 'جدیدتر',
117 + 'قدیمی‌تر'
118 + ]) {
119 assert.ok(ciHelp.text.includes(label), `CI guide missing ${label}`);
120 }
121 });
122
123 it('documents operational diagnostics, read-only configuration and Security Center controls', async () => {
124 const menuHelp = await menu.renderByCallback('help:1');
59 - for (const label of ['خودآزمایی', 'تست اتصال GitHub', 'Runtime', 'Plugin Registry', 'پیکربندی', 'فقط‌خواندنی']) {
60 - assert.ok(menuHelp.text.includes(label), `operational guide missing ${label}`);
125 + for (const label of [
126 + 'خودآزمایی',
127 + 'تست اتصال GitHub',
128 + 'Runtime',
129 + 'Plugin Registry',
130 + 'پیکربندی',
131 + 'فقط‌خواندنی'
132 + ]) {
133 + assert.ok(
134 + menuHelp.text.includes(label),
135 + `operational guide missing ${label}`
136 + );
137 }
138
139 const securityHelp = await menu.renderByCallback('help:6');
64 - for (const label of ['مرکز امنیت', 'سیاست عملیات', 'Safe Approval', 'Replay', 'Owner-only']) {
65 - assert.ok(securityHelp.text.includes(label), `security guide missing ${label}`);
140 + for (const label of [
141 + 'مرکز امنیت',
142 + 'سیاست عملیات',
143 + 'Safe Approval',
144 + 'Replay',
145 + 'Owner-only'
146 + ]) {
147 + assert.ok(
148 + securityHelp.text.includes(label),
149 + `security guide missing ${label}`
150 + );
151 }
152 });
153
@@ -82,13 +167,23 @@ describe('Nexa Dev Bot - in-app V2.1 guide', () => {
167 'nexa/edit-',
168 'main'
169 ];
85 - for (const item of expected) assert.ok(view.text.includes(item), `file-edit guide missing ${item}`);
170 + for (const item of expected)
171 + assert.ok(view.text.includes(item), `file-edit guide missing ${item}`);
172 assert.match(view.text, /main.*مستقیم.*تغییر|شاخه.*پیش.?فرض.*تغییر.*نمی/);
173 });
174
175 it('documents production, Cloudflare deployment, preview isolation and the public status boundary', async () => {
176 const view = await menu.renderByCallback('help:7');
91 - for (const label of ['Production', 'Cloudflare', 'Deploy', 'Preview', 'Durable Object', '/status', 'حداقلی', 'Observability']) {
177 + for (const label of [
178 + 'Production',
179 + 'Cloudflare',
180 + 'Deploy',
181 + 'Preview',
182 + 'Durable Object',
183 + '/status',
184 + 'حداقلی',
185 + 'Observability'
186 + ]) {
187 assert.ok(view.text.includes(label), `production guide missing ${label}`);
188 }
189 assert.match(view.text, /داخل Telegram.*جزئیات|جزئیات.*داخل Telegram/);
@@ -96,11 +191,26 @@ describe('Nexa Dev Bot - in-app V2.1 guide', () => {
191
192 it('keeps every guide page and callback within Telegram limits', async () => {
193 const encoder = new TextEncoder();
99 - for (const callback of ['menu:help', 'help:1', 'help:2', 'help:3', 'help:4', 'help:5', 'help:6', 'help:7']) {
194 + for (const callback of [
195 + 'menu:help',
196 + 'help:1',
197 + 'help:2',
198 + 'help:3',
199 + 'help:4',
200 + 'help:5',
201 + 'help:6',
202 + 'help:7'
203 + ]) {
204 const view = await menu.renderByCallback(callback);
101 - assert.ok(view.text.length <= 4096, `${callback} exceeds Telegram message limit`);
205 + assert.ok(
206 + view.text.length <= 4096,
207 + `${callback} exceeds Telegram message limit`
208 + );
209 for (const value of callbacks(view)) {
103 - assert.ok(encoder.encode(value).length <= 64, `${value} exceeds Telegram callback limit`);
210 + assert.ok(
211 + encoder.encode(value).length <= 64,
212 + `${value} exceeds Telegram callback limit`
213 + );
214 }
215 }
216 });
@@ -113,18 +223,40 @@ describe('Nexa Dev Bot - in-app V2.1 guide', () => {
223 return { ok: true };
224 };
225
116 - await bot.handleMessage({ chat: { id: 1 }, from: { id: 1 }, text: '/start' });
117 - const quickKeyboard = sent[0].replyMarkup.keyboard.flat().map(button => button.text);
226 + await bot.handleMessage({
227 + chat: { id: 1 },
228 + from: { id: 1 },
229 + text: '/start'
230 + });
231 + const quickKeyboard = sent[0].replyMarkup.keyboard
232 + .flat()
233 + .map((button) => button.text);
234 assert.ok(quickKeyboard.includes('📘 راهنما'));
235
236 sent.length = 0;
121 - await bot.handleMessage({ chat: { id: 1 }, from: { id: 1 }, text: '📘 راهنما' });
237 + await bot.handleMessage({
238 + chat: { id: 1 },
239 + from: { id: 1 },
240 + text: '📘 راهنما'
241 + });
242 assert.match(sent[0].text, /راهنمای Nexa Dev.*V2\.1/);
243 });
244
245 it('keeps README aligned with the deployed V2.1 architecture', () => {
126 - const readme = readFileSync(new URL('../README.md', import.meta.url), 'utf8');
127 - for (const label of ['Workspace Editor', 'WORKSPACE_STORE', 'APPROVAL_REPLAY_GUARD', 'Ops Console', 'پیکربندی', 'Worker Preview', 'Mini App', '/status']) {
246 + const readme = readFileSync(
247 + new URL('../README.md', import.meta.url),
248 + 'utf8'
249 + );
250 + for (const label of [
251 + 'Workspace Editor',
252 + 'WORKSPACE_STORE',
253 + 'APPROVAL_REPLAY_GUARD',
254 + 'Ops Console',
255 + 'پیکربندی',
256 + 'Worker Preview',
257 + 'Mini App',
258 + '/status'
259 + ]) {
260 assert.ok(readme.includes(label), `README missing ${label}`);
261 }
262 assert.doesNotMatch(readme, /ناوبری callback به‌صورت stateless/);
test/incidents.test.js
+35 -4
@@ -1,4 +1,35 @@
1 -import test from 'node:test';import assert from 'node:assert/strict';import {incidentFingerprint,redactIncidentText,normalizeIncident} from '../src/core/incidents.js';
2 -test('CP6 fingerprint separates provider repo sha and kind',()=>{assert.notEqual(incidentFingerprint({provider:'github',repo:'a',sha:'1',kind:'ci'}),incidentFingerprint({provider:'github',repo:'a',sha:'2',kind:'ci'}));});
3 -test('CP6 redacts token/query material',()=>{const s=redactIncidentText('token=abc https://x.test/a?secret=bad');assert.doesNotMatch(s,/abc|bad/);});
4 -test('CP6 normalized incidents are open and source backed',()=>{const i=normalizeIncident({provider:'github',repo:'r',sha:'a'.repeat(40),kind:'ci',ciFailure:true,summary:'failed'});assert.equal(i.status,'open');assert.equal(i.severity,'high');assert.match(i.fingerprint,/github/);});
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import {
4 + incidentFingerprint,
5 + redactIncidentText,
6 + normalizeIncident
7 +} from '../src/core/incidents.js';
8 +test('CP6 fingerprint separates provider repo sha and kind', () => {
9 + assert.notEqual(
10 + incidentFingerprint({
11 + provider: 'github',
12 + repo: 'a',
13 + sha: '1',
14 + kind: 'ci'
15 + }),
16 + incidentFingerprint({ provider: 'github', repo: 'a', sha: '2', kind: 'ci' })
17 + );
18 +});
19 +test('CP6 redacts token/query material', () => {
20 + const s = redactIncidentText('token=abc https://x.test/a?secret=bad');
21 + assert.doesNotMatch(s, /abc|bad/);
22 +});
23 +test('CP6 normalized incidents are open and source backed', () => {
24 + const i = normalizeIncident({
25 + provider: 'github',
26 + repo: 'r',
27 + sha: 'a'.repeat(40),
28 + kind: 'ci',
29 + ciFailure: true,
30 + summary: 'failed'
31 + });
32 + assert.equal(i.status, 'open');
33 + assert.equal(i.severity, 'high');
34 + assert.match(i.fingerprint, /github/);
35 +});
test/index.test.js
+57 -26
@@ -32,7 +32,10 @@ function webhookRequest(update = startUpdate) {
32
33 describe('Nexa Dev Bot - Cloudflare Worker Entrypoint', () => {
34 it('GET / returns online status without fabricated uptime', async () => {
35 - const res = await worker.fetch(new Request('https://example.test/', { method: 'GET' }), runtime);
35 + const res = await worker.fetch(
36 + new Request('https://example.test/', { method: 'GET' }),
37 + runtime
38 + );
39 assert.equal(res.status, 200);
40 const body = await res.json();
41 assert.equal(body.status, 'online');
@@ -42,14 +45,33 @@ describe('Nexa Dev Bot - Cloudflare Worker Entrypoint', () => {
45 });
46
47 it('GET /status stays public-minimal and does not expose owner-only operational diagnostics', async () => {
45 - const res = await worker.fetch(new Request('https://example.test/status', { method: 'GET' }), runtime);
48 + const res = await worker.fetch(
49 + new Request('https://example.test/status', { method: 'GET' }),
50 + runtime
51 + );
52 assert.equal(res.status, 200);
53 const body = await res.json();
48 - assert.deepEqual(Object.keys(body).sort(), ['bot', 'mode', 'status', 'version']);
54 + assert.deepEqual(Object.keys(body).sort(), [
55 + 'bot',
56 + 'mode',
57 + 'status',
58 + 'version'
59 + ]);
60 assert.equal(body.status, 'online');
61 const serialized = JSON.stringify(body);
51 - for (const privateDetail of ['WORKSPACE_STORE', 'APPROVAL_REPLAY_GUARD', 'GitHub live READ', 'Cloudflare deployment', 'observability', 'credential', 'configured']) {
52 - assert.ok(!serialized.includes(privateDetail), `public status leaked ${privateDetail}`);
62 + for (const privateDetail of [
63 + 'WORKSPACE_STORE',
64 + 'APPROVAL_REPLAY_GUARD',
65 + 'GitHub live READ',
66 + 'Cloudflare deployment',
67 + 'observability',
68 + 'credential',
69 + 'configured'
70 + ]) {
71 + assert.ok(
72 + !serialized.includes(privateDetail),
73 + `public status leaked ${privateDetail}`
74 + );
75 }
76 });
77
@@ -57,10 +79,13 @@ describe('Nexa Dev Bot - Cloudflare Worker Entrypoint', () => {
79 const originalFetch = globalThis.fetch;
80 globalThis.fetch = async (url) => {
81 if (String(url).startsWith('https://api.telegram.org/')) {
60 - return new Response(JSON.stringify({ ok: true, result: { message_id: 303 } }), {
61 - status: 200,
62 - headers: { 'content-type': 'application/json' }
63 - });
82 + return new Response(
83 + JSON.stringify({ ok: true, result: { message_id: 303 } }),
84 + {
85 + status: 200,
86 + headers: { 'content-type': 'application/json' }
87 + }
88 + );
89 }
90 return originalFetch(url);
91 };
@@ -87,11 +112,14 @@ describe('Nexa Dev Bot - Cloudflare Worker Entrypoint', () => {
112 });
113
114 it('arbitrary POST paths are not treated as webhooks', async () => {
90 - const res = await worker.fetch(new Request('https://example.test/', {
91 - method: 'POST',
92 - headers: { 'Content-Type': 'application/json' },
93 - body: '{}'
94 - }), runtime);
115 + const res = await worker.fetch(
116 + new Request('https://example.test/', {
117 + method: 'POST',
118 + headers: { 'Content-Type': 'application/json' },
119 + body: '{}'
120 + }),
121 + runtime
122 + );
123 assert.equal(res.status, 404);
124 });
125
@@ -105,13 +133,16 @@ describe('Nexa Dev Bot - Cloudflare Worker Entrypoint', () => {
133
134 globalThis.fetch = async (url) => {
135 if (String(url).startsWith('https://api.telegram.org/')) {
108 - return new Response(JSON.stringify({
109 - ok: false,
110 - description: `Unauthorized ${approvalSecret} ${cloudflareSecret}`
111 - }), {
112 - status: 401,
113 - headers: { 'content-type': 'application/json' }
114 - });
136 + return new Response(
137 + JSON.stringify({
138 + ok: false,
139 + description: `Unauthorized ${approvalSecret} ${cloudflareSecret}`
140 + }),
141 + {
142 + status: 401,
143 + headers: { 'content-type': 'application/json' }
144 + }
145 + );
146 }
147 return originalFetch(url);
148 };
@@ -125,11 +156,11 @@ describe('Nexa Dev Bot - Cloudflare Worker Entrypoint', () => {
156 CLOUDFLARE_API_TOKEN: cloudflareSecret
157 });
158 assert.equal(res.status, 400);
128 - assert.ok(logs.some(line => /telegram_webhook_error/i.test(line)));
129 - assert.ok(logs.some(line => /401|Unauthorized/i.test(line)));
130 - assert.ok(logs.every(line => !line.includes(secretToken)));
131 - assert.ok(logs.every(line => !line.includes(approvalSecret)));
132 - assert.ok(logs.every(line => !line.includes(cloudflareSecret)));
159 + assert.ok(logs.some((line) => /telegram_webhook_error/i.test(line)));
160 + assert.ok(logs.some((line) => /401|Unauthorized/i.test(line)));
161 + assert.ok(logs.every((line) => !line.includes(secretToken)));
162 + assert.ok(logs.every((line) => !line.includes(approvalSecret)));
163 + assert.ok(logs.every((line) => !line.includes(cloudflareSecret)));
164 } finally {
165 globalThis.fetch = originalFetch;
166 console.error = originalError;
test/kill-switch.test.js
+137 -6
@@ -3,9 +3,140 @@ import assert from 'node:assert/strict';
3 import { KillSwitch } from '../src/core/kill-switch.js';
4 import { PluginRouter } from '../src/core/router.js';
5 import { AutomationRunner } from '../src/core/automation-runner.js';
6 -function registryFor(risk,execute){const actionId=`test.${risk.toLowerCase()}`;const plugin={manifest:{id:'test'},async resolveCallback(){return{actionId,execute};}};return{getPlugins:()=>[plugin],getAction:()=>({pluginId:'test',actionId,risk})};}
7 -const audit={log(){}};const policy={evaluate:({action})=>({allowed:true,requiresApproval:false,risk:action.risk})};
8 -test('LOCKED kill switch allows READ but blocks WRITE before provider mutation',async()=>{let reads=0,writes=0;const killSwitch=new KillSwitch({store:{get:async()=>({mode:'LOCKED'})}});const readRouter=new PluginRouter({registry:registryFor('READ',async()=>{reads++;return{ok:true};}),policy,audit,killSwitch});const writeRouter=new PluginRouter({registry:registryFor('WRITE',async()=>{writes++;return{ok:true};}),policy,audit,killSwitch});assert.equal((await readRouter.dispatchCallback('x',{isOwner:true})).ok,true);const blocked=await writeRouter.dispatchCallback('x',{isOwner:true,approved:true});assert.equal(blocked.ok,false);assert.equal(blocked.killSwitchLocked,true);assert.equal(reads,1);assert.equal(writes,0);});
9 -test('kill switch fails closed for WRITE when durable state cannot be read',async()=>{let writes=0;const killSwitch=new KillSwitch({store:{get:async()=>{throw new Error('durable unavailable');}}});const router=new PluginRouter({registry:registryFor('WRITE',async()=>{writes++;return{ok:true};}),policy,audit,killSwitch});const blocked=await router.dispatchCallback('x',{isOwner:true,approved:true});assert.equal(blocked.ok,false);assert.equal(blocked.killSwitchLocked,true);assert.equal(writes,0);});
10 -test('LOCKED kill switch blocks automation advance before routing any step',async()=>{let routed=0;const runner=new AutomationRunner({router:{dispatchCallback:async()=>{routed++;return{ok:true};}},store:{put:async state=>state},killSwitch:new KillSwitch({store:{get:async()=>({mode:'LOCKED'})}})});const state={status:'ready',cursor:0,ownerId:'123',steps:[{callback:'write:x',key:'k1'}]};const blocked=await runner.advance(state);assert.equal(blocked.status,'paused_kill_switch');assert.equal(routed,0);});
11 -test('only owner-approved control can change lock state and unlock is sensitive',async()=>{const calls=[];const store={get:async()=>({mode:'NORMAL'}),set:async next=>{calls.push(next);return next;}};const killSwitch=new KillSwitch({store});await assert.rejects(()=>killSwitch.lock({isOwner:false,approved:true}),/owner/i);await assert.rejects(()=>killSwitch.lock({isOwner:true,approved:false}),/approval/i);await killSwitch.lock({isOwner:true,approved:true});await assert.rejects(()=>killSwitch.unlock({isOwner:true,approved:false}),/approval/i);await killSwitch.unlock({isOwner:true,approved:true});assert.deepEqual(calls.map(x=>x.mode),['LOCKED','NORMAL']);});
6 +function registryFor(risk, execute) {
7 + const actionId = `test.${risk.toLowerCase()}`;
8 + const plugin = {
9 + manifest: { id: 'test' },
10 + async resolveCallback() {
11 + return { actionId, execute };
12 + }
13 + };
14 + return {
15 + getPlugins: () => [plugin],
16 + getAction: () => ({ pluginId: 'test', actionId, risk })
17 + };
18 +}
19 +const audit = { log() {} };
20 +const policy = {
21 + evaluate: ({ action }) => ({
22 + allowed: true,
23 + requiresApproval: false,
24 + risk: action.risk
25 + })
26 +};
27 +test('LOCKED kill switch allows READ but blocks WRITE before provider mutation', async () => {
28 + let reads = 0,
29 + writes = 0;
30 + const killSwitch = new KillSwitch({
31 + store: { get: async () => ({ mode: 'LOCKED' }) }
32 + });
33 + const readRouter = new PluginRouter({
34 + registry: registryFor('READ', async () => {
35 + reads++;
36 + return { ok: true };
37 + }),
38 + policy,
39 + audit,
40 + killSwitch
41 + });
42 + const writeRouter = new PluginRouter({
43 + registry: registryFor('WRITE', async () => {
44 + writes++;
45 + return { ok: true };
46 + }),
47 + policy,
48 + audit,
49 + killSwitch
50 + });
51 + assert.equal(
52 + (await readRouter.dispatchCallback('x', { isOwner: true })).ok,
53 + true
54 + );
55 + const blocked = await writeRouter.dispatchCallback('x', {
56 + isOwner: true,
57 + approved: true
58 + });
59 + assert.equal(blocked.ok, false);
60 + assert.equal(blocked.killSwitchLocked, true);
61 + assert.equal(reads, 1);
62 + assert.equal(writes, 0);
63 +});
64 +test('kill switch fails closed for WRITE when durable state cannot be read', async () => {
65 + let writes = 0;
66 + const killSwitch = new KillSwitch({
67 + store: {
68 + get: async () => {
69 + throw new Error('durable unavailable');
70 + }
71 + }
72 + });
73 + const router = new PluginRouter({
74 + registry: registryFor('WRITE', async () => {
75 + writes++;
76 + return { ok: true };
77 + }),
78 + policy,
79 + audit,
80 + killSwitch
81 + });
82 + const blocked = await router.dispatchCallback('x', {
83 + isOwner: true,
84 + approved: true
85 + });
86 + assert.equal(blocked.ok, false);
87 + assert.equal(blocked.killSwitchLocked, true);
88 + assert.equal(writes, 0);
89 +});
90 +test('LOCKED kill switch blocks automation advance before routing any step', async () => {
91 + let routed = 0;
92 + const runner = new AutomationRunner({
93 + router: {
94 + dispatchCallback: async () => {
95 + routed++;
96 + return { ok: true };
97 + }
98 + },
99 + store: { put: async (state) => state },
100 + killSwitch: new KillSwitch({
101 + store: { get: async () => ({ mode: 'LOCKED' }) }
102 + })
103 + });
104 + const state = {
105 + status: 'ready',
106 + cursor: 0,
107 + ownerId: '123',
108 + steps: [{ callback: 'write:x', key: 'k1' }]
109 + };
110 + const blocked = await runner.advance(state);
111 + assert.equal(blocked.status, 'paused_kill_switch');
112 + assert.equal(routed, 0);
113 +});
114 +test('only owner-approved control can change lock state and unlock is sensitive', async () => {
115 + const calls = [];
116 + const store = {
117 + get: async () => ({ mode: 'NORMAL' }),
118 + set: async (next) => {
119 + calls.push(next);
120 + return next;
121 + }
122 + };
123 + const killSwitch = new KillSwitch({ store });
124 + await assert.rejects(
125 + () => killSwitch.lock({ isOwner: false, approved: true }),
126 + /owner/i
127 + );
128 + await assert.rejects(
129 + () => killSwitch.lock({ isOwner: true, approved: false }),
130 + /approval/i
131 + );
132 + await killSwitch.lock({ isOwner: true, approved: true });
133 + await assert.rejects(
134 + () => killSwitch.unlock({ isOwner: true, approved: false }),
135 + /approval/i
136 + );
137 + await killSwitch.unlock({ isOwner: true, approved: true });
138 + assert.deepEqual(
139 + calls.map((x) => x.mode),
140 + ['LOCKED', 'NORMAL']
141 + );
142 +});
test/menu.test.js
+46 -11
@@ -22,10 +22,25 @@ const github = {
22 };
23 },
24 async listPullRequests() {
25 - return [{ number: 43, title: 'Ops: strengthen long-running execution heartbeat rule', author: 'davoodmehraban89', state: 'open', merged: false }];
25 + return [
26 + {
27 + number: 43,
28 + title: 'Ops: strengthen long-running execution heartbeat rule',
29 + author: 'davoodmehraban89',
30 + state: 'open',
31 + merged: false
32 + }
33 + ];
34 },
35 async listCommits() {
28 - return [{ sha: '87b25b1', message: 'feat: mobile GitHub repository browser UX', author: 'davoodmehraban89', date: '2026-10-02' }];
36 + return [
37 + {
38 + sha: '87b25b1',
39 + message: 'feat: mobile GitHub repository browser UX',
40 + author: 'davoodmehraban89',
41 + date: '2026-10-02'
42 + }
43 + ];
44 },
45 async listFiles() {
46 return [{ name: 'src', path: 'src', type: 'dir', size: 0 }];
@@ -33,7 +48,14 @@ const github = {
48 async getRepoStatus() {
49 return {
50 defaultBranch: 'main',
36 - lastRuns: [{ name: 'CI', status: 'completed', conclusion: 'success', commit: 'fix mobile menu' }]
51 + lastRuns: [
52 + {
53 + name: 'CI',
54 + status: 'completed',
55 + conclusion: 'success',
56 + commit: 'fix mobile menu'
57 + }
58 + ]
59 };
60 }
61 };
@@ -46,7 +68,9 @@ describe('Nexa Dev Bot - MenuManager & Navigation', () => {
68 assert.ok(view.text.includes('Nexa Dev Bot'));
69 assert.doesNotMatch(view.text, /✅\s*متصل|تایید شده/);
70
49 - const callbacks = view.reply_markup.inline_keyboard.flat().map(b => b.callback_data);
71 + const callbacks = view.reply_markup.inline_keyboard
72 + .flat()
73 + .map((b) => b.callback_data);
74 assert.ok(callbacks.includes('menu:repos'));
75 assert.ok(callbacks.includes('menu:status'));
76 assert.ok(callbacks.includes('menu:tools'));
@@ -58,9 +82,9 @@ describe('Nexa Dev Bot - MenuManager & Navigation', () => {
82 const view = await menu.getReposListView();
83 assert.ok(view.text.includes('فهرست مخزن‌ها'));
84 const buttons = view.reply_markup.inline_keyboard.flat();
61 - assert.ok(buttons.some(b => b.text.includes('Factor-easy')));
62 - assert.ok(buttons.some(b => b.callback_data === 'repo:Factor-easy'));
63 - assert.ok(buttons.some(b => b.callback_data === 'menu:main'));
85 + assert.ok(buttons.some((b) => b.text.includes('Factor-easy')));
86 + assert.ok(buttons.some((b) => b.callback_data === 'repo:Factor-easy'));
87 + assert.ok(buttons.some((b) => b.callback_data === 'menu:main'));
88 });
89
90 it('repository detail is based on live repository metadata', async () => {
@@ -70,7 +94,9 @@ describe('Nexa Dev Bot - MenuManager & Navigation', () => {
94 assert.ok(view.text.includes('خصوصی'));
95 assert.doesNotMatch(view.text, /اتصال GitHub: ✅ تایید شده/);
96
73 - const callbacks = view.reply_markup.inline_keyboard.flat().map(b => b.callback_data);
97 + const callbacks = view.reply_markup.inline_keyboard
98 + .flat()
99 + .map((b) => b.callback_data);
100 assert.ok(callbacks.includes('files:Factor-easy'));
101 assert.ok(callbacks.includes('pr:Factor-easy'));
102 assert.ok(callbacks.includes('commits:Factor-easy'));
@@ -81,7 +107,11 @@ describe('Nexa Dev Bot - MenuManager & Navigation', () => {
107 it('pull requests, commits, files and workflow status render source-backed data', async () => {
108 const prView = await menu.getPullRequestsView('Factor-easy');
109 assert.ok(prView.text.includes('#43'));
84 - assert.ok(prView.text.includes('Ops: strengthen long-running execution heartbeat rule'));
110 + assert.ok(
111 + prView.text.includes(
112 + 'Ops: strengthen long-running execution heartbeat rule'
113 + )
114 + );
115
116 const commitsView = await menu.getCommitsView('Factor-easy');
117 assert.ok(commitsView.text.includes('87b25b1'));
@@ -102,7 +132,10 @@ describe('Nexa Dev Bot - MenuManager & Navigation', () => {
132 assert.doesNotMatch(pingView.text, /12ms|پایدار است/);
133
134 const securityView = menu.getSecurityView();
105 - assert.doesNotMatch(securityView.text, /5000 req\/hr|فعال و ایمن|Fine-grained Personal Access Token/i);
135 + assert.doesNotMatch(
136 + securityView.text,
137 + /5000 req\/hr|فعال و ایمن|Fine-grained Personal Access Token/i
138 + );
139 });
140
141 it('callback router preserves hierarchical back navigation', async () => {
@@ -115,7 +148,9 @@ describe('Nexa Dev Bot - MenuManager & Navigation', () => {
148 const prView = await menu.renderByCallback('pr:Factor-easy');
149 assert.ok(prView.text.includes('Pull Request'));
150
118 - const backCallbacks = prView.reply_markup.inline_keyboard.flat().map(b => b.callback_data);
151 + const backCallbacks = prView.reply_markup.inline_keyboard
152 + .flat()
153 + .map((b) => b.callback_data);
154 assert.ok(backCallbacks.includes('repo:Factor-easy'));
155 });
156 });
test/navigation.test.js
+267 -67
@@ -3,19 +3,28 @@ import assert from 'node:assert/strict';
3 import worker from '../src/index.js';
4
5 const env = {
6 - TELEGRAM_WEBHOOK_SECRET: 'right', OWNER_TELEGRAM_ID: '123',
7 - TELEGRAM_BOT_TOKEN: 'telegram-test-token', GITHUB_TOKEN: 'github-test-token',
6 + TELEGRAM_WEBHOOK_SECRET: 'right',
7 + OWNER_TELEGRAM_ID: '123',
8 + TELEGRAM_BOT_TOKEN: 'telegram-test-token',
9 + GITHUB_TOKEN: 'github-test-token',
10 GITHUB_OWNER: 'davoodmehraban89'
11 };
12
13 function webhook(update) {
14 return new Request('https://example.test/telegram/webhook', {
15 method: 'POST',
14 - headers: { 'content-type': 'application/json', 'X-Telegram-Bot-Api-Secret-Token': 'right' },
16 + headers: {
17 + 'content-type': 'application/json',
18 + 'X-Telegram-Bot-Api-Secret-Token': 'right'
19 + },
20 body: JSON.stringify(update)
21 });
22 }
18 -const json = (data, status = 200) => new Response(JSON.stringify(data), { status, headers: { 'content-type': 'application/json' } });
23 +const json = (data, status = 200) =>
24 + new Response(JSON.stringify(data), {
25 + status,
26 + headers: { 'content-type': 'application/json' }
27 + });
28
29 function installApiMock() {
30 const telegramCalls = [];
@@ -31,49 +40,149 @@ function installApiMock() {
40 const method = value.split('/').at(-1);
41 const body = options.body ? JSON.parse(options.body) : {};
42 telegramCalls.push({ method, body });
34 - return json({ ok: true, result: { message_id: body.message_id || 700, ...body } });
43 + return json({
44 + ok: true,
45 + result: { message_id: body.message_id || 700, ...body }
46 + });
47 }
36 - if (!value.startsWith('https://api.github.com/')) throw new Error(`Unexpected URL: ${value}`);
48 + if (!value.startsWith('https://api.github.com/'))
49 + throw new Error(`Unexpected URL: ${value}`);
50 githubCalls.push(value);
51
39 - if (value.startsWith('https://api.github.com/user/repos?')) return json([{
40 - id: 1001, name: 'demo', full_name: 'davoodmehraban89/demo', private: true,
41 - default_branch: 'main', stargazers_count: 0, forks_count: 0, description: 'Demo repository'
42 - }]);
43 - if (value === 'https://api.github.com/repositories/1001' || value === 'https://api.github.com/repos/davoodmehraban89/demo') return json({
44 - id: 1001, name: 'demo', full_name: 'davoodmehraban89/demo', private: true,
45 - default_branch: 'main', archived: false, description: 'Demo repository', html_url: 'https://github.com/davoodmehraban89/demo'
46 - });
47 - if (value === 'https://api.github.com/repos/davoodmehraban89/demo/contents') return json([
48 - { name: 'src', path: 'src', type: 'dir', size: 0, sha: folderSha },
49 - { name: 'README.md', path: 'README.md', type: 'file', size: 100, sha: fileSha }
50 - ]);
51 - if (value === `https://api.github.com/repos/davoodmehraban89/demo/git/trees/${folderSha}`) return json({ tree: [
52 - { path: 'index.js', type: 'blob', size: 42, sha: nestedFileSha }
53 - ] });
54 - if (value === `https://api.github.com/repos/davoodmehraban89/demo/git/blobs/${nestedFileSha}`) return json({
55 - encoding: 'base64', size: 21, content: btoa('console.log("hello")\n')
56 - });
57 - if (value === 'https://api.github.com/repos/davoodmehraban89/demo/commits?per_page=5') return json([{
58 - sha: '1234567890abcdef', commit: { message: 'fix mobile menu', author: { name: 'Davood', date: '2026-10-02T10:00:00Z' } },
59 - author: { login: 'davoodmehraban89' }
60 - }]);
61 - if (value === 'https://api.github.com/repos/davoodmehraban89/demo/pulls?state=all&per_page=10') return json([{
62 - number: 7, title: 'Improve bot UI', state: 'open', merged_at: null, created_at: '2026-10-02T10:00:00Z',
63 - html_url: 'https://github.com/davoodmehraban89/demo/pull/7', user: { login: 'davoodmehraban89' }
64 - }]);
65 - if (value === 'https://api.github.com/repos/davoodmehraban89/demo/actions/runs?per_page=3') return json({ workflow_runs: [{
66 - id: 1, name: 'CI', status: 'completed', conclusion: 'success', head_branch: 'main', head_sha: '1234567890abcdef1234567890abcdef12345678', run_number: 1,
67 - head_commit: { message: 'fix mobile menu' }, html_url: 'https://github.com/davoodmehraban89/demo/actions/runs/1'
68 - }] });
69 - if (value === 'https://api.github.com/repos/davoodmehraban89/demo/actions/runs?per_page=10') return json({ workflow_runs: [{
70 - id: 1, name: 'CI', status: 'completed', conclusion: 'success', head_branch: 'main', head_sha: '1234567890abcdef1234567890abcdef12345678', run_number: 1,
71 - event: 'push', head_commit: { message: 'fix mobile menu' }, html_url: 'https://github.com/davoodmehraban89/demo/actions/runs/1'
72 - }] });
52 + if (value.startsWith('https://api.github.com/user/repos?'))
53 + return json([
54 + {
55 + id: 1001,
56 + name: 'demo',
57 + full_name: 'davoodmehraban89/demo',
58 + private: true,
59 + default_branch: 'main',
60 + stargazers_count: 0,
61 + forks_count: 0,
62 + description: 'Demo repository'
63 + }
64 + ]);
65 + if (
66 + value === 'https://api.github.com/repositories/1001' ||
67 + value === 'https://api.github.com/repos/davoodmehraban89/demo'
68 + )
69 + return json({
70 + id: 1001,
71 + name: 'demo',
72 + full_name: 'davoodmehraban89/demo',
73 + private: true,
74 + default_branch: 'main',
75 + archived: false,
76 + description: 'Demo repository',
77 + html_url: 'https://github.com/davoodmehraban89/demo'
78 + });
79 + if (value === 'https://api.github.com/repos/davoodmehraban89/demo/contents')
80 + return json([
81 + { name: 'src', path: 'src', type: 'dir', size: 0, sha: folderSha },
82 + {
83 + name: 'README.md',
84 + path: 'README.md',
85 + type: 'file',
86 + size: 100,
87 + sha: fileSha
88 + }
89 + ]);
90 + if (
91 + value ===
92 + `https://api.github.com/repos/davoodmehraban89/demo/git/trees/${folderSha}`
93 + )
94 + return json({
95 + tree: [{ path: 'index.js', type: 'blob', size: 42, sha: nestedFileSha }]
96 + });
97 + if (
98 + value ===
99 + `https://api.github.com/repos/davoodmehraban89/demo/git/blobs/${nestedFileSha}`
100 + )
101 + return json({
102 + encoding: 'base64',
103 + size: 21,
104 + content: btoa('console.log("hello")\n')
105 + });
106 + if (
107 + value ===
108 + 'https://api.github.com/repos/davoodmehraban89/demo/commits?per_page=5'
109 + )
110 + return json([
111 + {
112 + sha: '1234567890abcdef',
113 + commit: {
114 + message: 'fix mobile menu',
115 + author: { name: 'Davood', date: '2026-10-02T10:00:00Z' }
116 + },
117 + author: { login: 'davoodmehraban89' }
118 + }
119 + ]);
120 + if (
121 + value ===
122 + 'https://api.github.com/repos/davoodmehraban89/demo/pulls?state=all&per_page=10'
123 + )
124 + return json([
125 + {
126 + number: 7,
127 + title: 'Improve bot UI',
128 + state: 'open',
129 + merged_at: null,
130 + created_at: '2026-10-02T10:00:00Z',
131 + html_url: 'https://github.com/davoodmehraban89/demo/pull/7',
132 + user: { login: 'davoodmehraban89' }
133 + }
134 + ]);
135 + if (
136 + value ===
137 + 'https://api.github.com/repos/davoodmehraban89/demo/actions/runs?per_page=3'
138 + )
139 + return json({
140 + workflow_runs: [
141 + {
142 + id: 1,
143 + name: 'CI',
144 + status: 'completed',
145 + conclusion: 'success',
146 + head_branch: 'main',
147 + head_sha: '1234567890abcdef1234567890abcdef12345678',
148 + run_number: 1,
149 + head_commit: { message: 'fix mobile menu' },
150 + html_url: 'https://github.com/davoodmehraban89/demo/actions/runs/1'
151 + }
152 + ]
153 + });
154 + if (
155 + value ===
156 + 'https://api.github.com/repos/davoodmehraban89/demo/actions/runs?per_page=10'
157 + )
158 + return json({
159 + workflow_runs: [
160 + {
161 + id: 1,
162 + name: 'CI',
163 + status: 'completed',
164 + conclusion: 'success',
165 + head_branch: 'main',
166 + head_sha: '1234567890abcdef1234567890abcdef12345678',
167 + run_number: 1,
168 + event: 'push',
169 + head_commit: { message: 'fix mobile menu' },
170 + html_url: 'https://github.com/davoodmehraban89/demo/actions/runs/1'
171 + }
172 + ]
173 + });
174 return json({ message: 'Not Found' }, 404);
175 };
176
76 - return { telegramCalls, githubCalls, folderSha, nestedFileSha, restore: () => { globalThis.fetch = originalFetch; } };
177 + return {
178 + telegramCalls,
179 + githubCalls,
180 + folderSha,
181 + nestedFileSha,
182 + restore: () => {
183 + globalThis.fetch = originalFetch;
184 + }
185 + };
186 }
187
188 async function sendUpdate(update) {
@@ -85,8 +194,17 @@ async function sendUpdate(update) {
194 test('persistent quick menu bootstrap keeps later inline navigation on one Telegram message', async () => {
195 const mock = installApiMock();
196 try {
88 - await sendUpdate({ message: { message_id: 1, from: { id: 123 }, chat: { id: 123 }, text: '/start' } });
89 - const startSends = mock.telegramCalls.filter(call => call.method === 'sendMessage');
197 + await sendUpdate({
198 + message: {
199 + message_id: 1,
200 + from: { id: 123 },
201 + chat: { id: 123 },
202 + text: '/start'
203 + }
204 + });
205 + const startSends = mock.telegramCalls.filter(
206 + (call) => call.method === 'sendMessage'
207 + );
208 assert.equal(startSends.length, 2);
209 assert.equal(startSends[0].body.reply_markup.is_persistent, true);
210 assert.ok(startSends[0].body.reply_markup.keyboard);
@@ -94,61 +212,143 @@ test('persistent quick menu bootstrap keeps later inline navigation on one Teleg
212
213 const message = { message_id: 700, chat: { id: 123 } };
214 for (const data of ['menu:repos', 'repo:1001', 'menu:repos', 'menu:main']) {
97 - await sendUpdate({ callback_query: { id: data, from: { id: 123 }, data, message } });
215 + await sendUpdate({
216 + callback_query: { id: data, from: { id: 123 }, data, message }
217 + });
218 }
99 - const edits = mock.telegramCalls.filter(call => call.method === 'editMessageText');
219 + const edits = mock.telegramCalls.filter(
220 + (call) => call.method === 'editMessageText'
221 + );
222 assert.equal(edits.length, 4);
101 - assert.ok(edits.every(call => call.body.message_id === 700));
223 + assert.ok(edits.every((call) => call.body.message_id === 700));
224 assert.match(edits[0].body.text, /فهرست مخزن‌ها/);
225 assert.match(edits[1].body.text, /پروژه: demo/);
226 assert.match(edits[3].body.text, /Nexa Dev Bot/);
105 - assert.equal(mock.telegramCalls.filter(call => call.method === 'sendMessage').length, 2, 'callbacks must not create extra chat messages');
106 - } finally { mock.restore(); }
227 + assert.equal(
228 + mock.telegramCalls.filter((call) => call.method === 'sendMessage').length,
229 + 2,
230 + 'callbacks must not create extra chat messages'
231 + );
232 + } finally {
233 + mock.restore();
234 + }
235 });
236
237 test('repository activity views use live GitHub responses and edit in place', async () => {
238 const mock = installApiMock();
239 try {
240 const message = { message_id: 701, chat: { id: 123 } };
113 - for (const data of ['files:1001', 'commits:1001', 'pr:1001', 'status:1001']) {
114 - await sendUpdate({ callback_query: { id: data, from: { id: 123 }, data, message } });
241 + for (const data of [
242 + 'files:1001',
243 + 'commits:1001',
244 + 'pr:1001',
245 + 'status:1001'
246 + ]) {
247 + await sendUpdate({
248 + callback_query: { id: data, from: { id: 123 }, data, message }
249 + });
250 }
116 - const edits = mock.telegramCalls.filter(call => call.method === 'editMessageText');
251 + const edits = mock.telegramCalls.filter(
252 + (call) => call.method === 'editMessageText'
253 + );
254 assert.equal(edits.length, 4);
255 assert.match(edits[0].body.text, /README\.md/);
256 assert.match(edits[1].body.text, /fix mobile menu/);
257 assert.match(edits[2].body.text, /#7/);
258 assert.match(edits[3].body.text, /CI/);
122 - } finally { mock.restore(); }
259 + } finally {
260 + mock.restore();
261 + }
262 });
263
264 test('/repos uses numeric repository ids in callbacks', async () => {
265 const mock = installApiMock();
266 try {
128 - await sendUpdate({ message: { message_id: 1, from: { id: 123 }, chat: { id: 123 }, text: '/repos' } });
129 - const sent = mock.telegramCalls.find(call => call.method === 'sendMessage');
267 + await sendUpdate({
268 + message: {
269 + message_id: 1,
270 + from: { id: 123 },
271 + chat: { id: 123 },
272 + text: '/repos'
273 + }
274 + });
275 + const sent = mock.telegramCalls.find(
276 + (call) => call.method === 'sendMessage'
277 + );
278 const buttons = sent.body.reply_markup.inline_keyboard.flat();
131 - assert.ok(buttons.some(button => button.callback_data === 'repo:1001'));
132 - assert.ok(mock.githubCalls.some(url => url.startsWith('https://api.github.com/user/repos?')));
133 - } finally { mock.restore(); }
279 + assert.ok(buttons.some((button) => button.callback_data === 'repo:1001'));
280 + assert.ok(
281 + mock.githubCalls.some((url) =>
282 + url.startsWith('https://api.github.com/user/repos?')
283 + )
284 + );
285 + } finally {
286 + mock.restore();
287 + }
288 });
289
290 test('deep file browser opens directory and file previews in the same Telegram message', async () => {
291 const mock = installApiMock();
292 try {
293 const message = { message_id: 702, chat: { id: 123 } };
140 - await sendUpdate({ callback_query: { id: 'root', from: { id: 123 }, data: 'files:1001', message } });
141 - let edits = mock.telegramCalls.filter(call => call.method === 'editMessageText');
142 - assert.ok(edits.at(-1).body.reply_markup.inline_keyboard.flat().some(button => button.callback_data === `tree:1001:${mock.folderSha}`));
294 + await sendUpdate({
295 + callback_query: {
296 + id: 'root',
297 + from: { id: 123 },
298 + data: 'files:1001',
299 + message
300 + }
301 + });
302 + let edits = mock.telegramCalls.filter(
303 + (call) => call.method === 'editMessageText'
304 + );
305 + assert.ok(
306 + edits
307 + .at(-1)
308 + .body.reply_markup.inline_keyboard.flat()
309 + .some(
310 + (button) => button.callback_data === `tree:1001:${mock.folderSha}`
311 + )
312 + );
313
144 - await sendUpdate({ callback_query: { id: 'tree', from: { id: 123 }, data: `tree:1001:${mock.folderSha}`, message } });
145 - edits = mock.telegramCalls.filter(call => call.method === 'editMessageText');
146 - assert.ok(edits.at(-1).body.reply_markup.inline_keyboard.flat().some(button => button.callback_data === `blob:1001:${mock.nestedFileSha}`));
314 + await sendUpdate({
315 + callback_query: {
316 + id: 'tree',
317 + from: { id: 123 },
318 + data: `tree:1001:${mock.folderSha}`,
319 + message
320 + }
321 + });
322 + edits = mock.telegramCalls.filter(
323 + (call) => call.method === 'editMessageText'
324 + );
325 + assert.ok(
326 + edits
327 + .at(-1)
328 + .body.reply_markup.inline_keyboard.flat()
329 + .some(
330 + (button) => button.callback_data === `blob:1001:${mock.nestedFileSha}`
331 + )
332 + );
333
148 - await sendUpdate({ callback_query: { id: 'blob', from: { id: 123 }, data: `blob:1001:${mock.nestedFileSha}`, message } });
149 - edits = mock.telegramCalls.filter(call => call.method === 'editMessageText');
334 + await sendUpdate({
335 + callback_query: {
336 + id: 'blob',
337 + from: { id: 123 },
338 + data: `blob:1001:${mock.nestedFileSha}`,
339 + message
340 + }
341 + });
342 + edits = mock.telegramCalls.filter(
343 + (call) => call.method === 'editMessageText'
344 + );
345 assert.match(edits.at(-1).body.text, /console\.log/);
346 assert.equal(edits.at(-1).body.message_id, 702);
152 - assert.equal(mock.telegramCalls.filter(call => call.method === 'sendMessage').length, 0);
153 - } finally { mock.restore(); }
347 + assert.equal(
348 + mock.telegramCalls.filter((call) => call.method === 'sendMessage').length,
349 + 0
350 + );
351 + } finally {
352 + mock.restore();
353 + }
354 });
test/ops-console.test.js
+108 -30
@@ -7,15 +7,17 @@ import { OpsMenuManager } from '../src/ops-menu.js';
7 function fakeRegistry() {
8 return {
9 getPlugins() {
10 - return [{
11 - manifest: {
12 - id: 'github',
13 - actions: {
14 - 'github.repos.list': { risk: 'READ' },
15 - 'github.workspace.commit_branch': { risk: 'WRITE' }
10 + return [
11 + {
12 + manifest: {
13 + id: 'github',
14 + actions: {
15 + 'github.repos.list': { risk: 'READ' },
16 + 'github.workspace.commit_branch': { risk: 'WRITE' }
17 + }
18 }
19 }
18 - }];
20 + ];
21 }
22 };
23 }
@@ -51,7 +53,10 @@ function diagnosticsForMenus({ githubFailure = false } = {}) {
53 }
54
55 function callbacks(view) {
54 - return (view.reply_markup?.inline_keyboard || []).flat().map(button => button.callback_data).filter(Boolean);
56 + return (view.reply_markup?.inline_keyboard || [])
57 + .flat()
58 + .map((button) => button.callback_data)
59 + .filter(Boolean);
60 }
61
62 describe('Nexa Dev Bot - operational diagnostics', () => {
@@ -79,7 +84,9 @@ describe('Nexa Dev Bot - operational diagnostics', () => {
84 assert.equal(snapshot.actionCount, 2);
85
86 const serialized = JSON.stringify(snapshot);
82 - for (const secret of Object.values(env).filter(value => String(value).includes('secret'))) {
87 + for (const secret of Object.values(env).filter((value) =>
88 + String(value).includes('secret')
89 + )) {
90 assert.ok(!serialized.includes(secret), `snapshot leaked ${secret}`);
91 }
92 });
@@ -104,7 +111,9 @@ describe('Nexa Dev Bot - operational diagnostics', () => {
111 env: {},
112 github: {
113 owner: 'davoodmehraban89',
107 - async listRepositories() { throw new Error('GITHUB_TOKEN is missing'); }
114 + async listRepositories() {
115 + throw new Error('GITHUB_TOKEN is missing');
116 + }
117 },
118 registry: fakeRegistry(),
119 replayStore: { isConfigured: () => false },
@@ -114,20 +123,37 @@ describe('Nexa Dev Bot - operational diagnostics', () => {
123
124 const report = await diagnostics.runSelfCheck();
125 assert.equal(report.ok, false);
117 - const byId = Object.fromEntries(report.checks.map(check => [check.id, check]));
118 - for (const id of ['telegram', 'webhook', 'owner', 'github-token', 'replay-guard', 'workspace-store', 'approval-signer', 'github-live']) {
126 + const byId = Object.fromEntries(
127 + report.checks.map((check) => [check.id, check])
128 + );
129 + for (const id of [
130 + 'telegram',
131 + 'webhook',
132 + 'owner',
133 + 'github-token',
134 + 'replay-guard',
135 + 'workspace-store',
136 + 'approval-signer',
137 + 'github-live'
138 + ]) {
139 assert.equal(byId[id]?.ok, false, `${id} should fail closed`);
140 }
141 });
142
143 it('configures Cloudflare Worker Previews with isolated Durable Object bindings', () => {
124 - const config = JSON.parse(readFileSync(new URL('../wrangler.jsonc', import.meta.url), 'utf8'));
144 + const config = JSON.parse(
145 + readFileSync(new URL('../wrangler.jsonc', import.meta.url), 'utf8')
146 + );
147 const production = config.durable_objects?.bindings || [];
148 const preview = config.previews?.durable_objects?.bindings || [];
149 assert.ok(config.previews, 'wrangler previews block is required');
150 for (const binding of production) {
151 assert.ok(
130 - preview.some(candidate => candidate.name === binding.name && candidate.class_name === binding.class_name),
152 + preview.some(
153 + (candidate) =>
154 + candidate.name === binding.name &&
155 + candidate.class_name === binding.class_name
156 + ),
157 `preview missing durable binding ${binding.name}`
158 );
159 }
@@ -140,7 +166,13 @@ describe('Nexa Dev Bot - operational menu surfaces', () => {
166 const menu = new OpsMenuManager(github, diagnostics);
167 const view = menu.getToolsView();
168 const values = callbacks(view);
143 - for (const callback of ['ops:selfcheck', 'ops:github', 'ops:runtime', 'ops:plugins', 'tool:ping']) {
169 + for (const callback of [
170 + 'ops:selfcheck',
171 + 'ops:github',
172 + 'ops:runtime',
173 + 'ops:plugins',
174 + 'tool:ping'
175 + ]) {
176 assert.ok(values.includes(callback), `missing ${callback}`);
177 }
178 assert.match(view.text, /تشخیص|Diagnostics|عیب.?یابی/);
@@ -156,7 +188,10 @@ describe('Nexa Dev Bot - operational menu surfaces', () => {
188 assert.doesNotMatch(okView.text, /99\.9|100% SLA|ms latency/i);
189
190 const badContext = diagnosticsForMenus({ githubFailure: true });
159 - const badMenu = new OpsMenuManager(badContext.github, badContext.diagnostics);
191 + const badMenu = new OpsMenuManager(
192 + badContext.github,
193 + badContext.diagnostics
194 + );
195 const badView = await badMenu.getServiceStatusView();
196 assert.match(badView.text, /GitHub.*❌|❌.*GitHub/s);
197 assert.match(badView.text, /403/);
@@ -167,7 +202,11 @@ describe('Nexa Dev Bot - operational menu surfaces', () => {
202 const menu = new OpsMenuManager(github, diagnostics);
203
204 const security = menu.getSecurityView();
170 - for (const callback of ['security:selfcheck', 'security:policy', 'security:approval']) {
205 + for (const callback of [
206 + 'security:selfcheck',
207 + 'security:policy',
208 + 'security:approval'
209 + ]) {
210 assert.ok(callbacks(security).includes(callback), `missing ${callback}`);
211 }
212 assert.match(security.text, /مرکز امنیت/);
@@ -175,7 +214,12 @@ describe('Nexa Dev Bot - operational menu surfaces', () => {
214 const config = menu.getSettingsView();
215 assert.match(config.text, /پیکربندی/);
216 assert.doesNotMatch(config.text, /تنظیمات Nexa Dev/);
178 - for (const callback of ['config:runtime', 'config:providers', 'config:editor', 'config:plugins']) {
217 + for (const callback of [
218 + 'config:runtime',
219 + 'config:providers',
220 + 'config:editor',
221 + 'config:plugins'
222 + ]) {
223 assert.ok(callbacks(config).includes(callback), `missing ${callback}`);
224 }
225 });
@@ -185,18 +229,35 @@ describe('Nexa Dev Bot - operational menu surfaces', () => {
229 const menu = new OpsMenuManager(github, diagnostics);
230 const encoder = new TextEncoder();
231 const routes = [
188 - 'menu:status', 'menu:tools', 'menu:security', 'menu:settings',
189 - 'ops:selfcheck', 'ops:github', 'ops:runtime', 'ops:plugins',
190 - 'security:selfcheck', 'security:policy', 'security:approval',
191 - 'config:runtime', 'config:providers', 'config:editor', 'config:plugins'
232 + 'menu:status',
233 + 'menu:tools',
234 + 'menu:security',
235 + 'menu:settings',
236 + 'ops:selfcheck',
237 + 'ops:github',
238 + 'ops:runtime',
239 + 'ops:plugins',
240 + 'security:selfcheck',
241 + 'security:policy',
242 + 'security:approval',
243 + 'config:runtime',
244 + 'config:providers',
245 + 'config:editor',
246 + 'config:plugins'
247 ];
248
249 for (const route of routes) {
250 const view = await menu.renderByCallback(route);
251 assert.ok(view?.text, `${route} returned no text`);
197 - assert.ok(view.text.length <= 4096, `${route} exceeds Telegram message limit`);
252 + assert.ok(
253 + view.text.length <= 4096,
254 + `${route} exceeds Telegram message limit`
255 + );
256 for (const callback of callbacks(view)) {
199 - assert.ok(encoder.encode(callback).length <= 64, `${callback} exceeds callback limit`);
257 + assert.ok(
258 + encoder.encode(callback).length <= 64,
259 + `${callback} exceeds callback limit`
260 + );
261 }
262 }
263 });
@@ -206,12 +267,21 @@ describe('Nexa Dev Bot - operational menu surfaces', () => {
267 const menu = new OpsMenuManager(github, diagnostics);
268
269 const providers = await menu.renderByCallback('config:providers');
209 - assert.ok(callbacks(providers).includes('config:github'), 'provider report must offer a direct live GitHub probe');
270 + assert.ok(
271 + callbacks(providers).includes('config:github'),
272 + 'provider report must offer a direct live GitHub probe'
273 + );
274
275 const probe = await menu.renderByCallback('config:github');
276 assert.match(probe.text, /READ زنده موفق/);
213 - assert.ok(callbacks(probe).includes('config:github'), 'live probe must support refresh in the same context');
214 - assert.ok(callbacks(probe).includes('menu:settings'), 'live probe must recover to configuration, not strand the owner in tools');
277 + assert.ok(
278 + callbacks(probe).includes('config:github'),
279 + 'live probe must support refresh in the same context'
280 + );
281 + assert.ok(
282 + callbacks(probe).includes('menu:settings'),
283 + 'live probe must recover to configuration, not strand the owner in tools'
284 + );
285 });
286
287 it('never renders configured secrets in operational pages', async () => {
@@ -224,9 +294,17 @@ describe('Nexa Dev Bot - operational menu surfaces', () => {
294 menu.renderByCallback('security:selfcheck'),
295 menu.renderByCallback('config:providers')
296 ]);
227 - const combined = pages.map(page => page.text).join('\n');
228 - for (const secret of ['tg-secret-value', 'webhook-secret-value', 'github-secret-value', 'approval-secret-value']) {
229 - assert.ok(!combined.includes(secret), `operational page leaked ${secret}`);
297 + const combined = pages.map((page) => page.text).join('\n');
298 + for (const secret of [
299 + 'tg-secret-value',
300 + 'webhook-secret-value',
301 + 'github-secret-value',
302 + 'approval-secret-value'
303 + ]) {
304 + assert.ok(
305 + !combined.includes(secret),
306 + `operational page leaked ${secret}`
307 + );
308 }
309 });
310 });
test/phase2-controller.test.js
+221 -54
@@ -2,73 +2,240 @@ import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import { createWorkspaceController } from '../src/plugins/github/workspace.js';
4
5 -const ws = { id:'W000000001', repoId:1, repoFullName:'o/r', baseBranch:'main', baseHeadSha:'a'.repeat(40), baseTreeSha:'b'.repeat(40), state:'DRAFT', path:'README.md', originalText:'one', draftText:'two', commitMessage:'msg', files:[{path:'README.md',blobSha:'c'.repeat(40),originalText:'one',draftText:'two',draftDigest:'1'.repeat(64)},{path:'src/a.js',blobSha:'d'.repeat(40),originalText:'a',draftText:'b',draftDigest:'2'.repeat(64)}] };
5 +const ws = {
6 + id: 'W000000001',
7 + repoId: 1,
8 + repoFullName: 'o/r',
9 + baseBranch: 'main',
10 + baseHeadSha: 'a'.repeat(40),
11 + baseTreeSha: 'b'.repeat(40),
12 + state: 'DRAFT',
13 + path: 'README.md',
14 + originalText: 'one',
15 + draftText: 'two',
16 + commitMessage: 'msg',
17 + files: [
18 + {
19 + path: 'README.md',
20 + blobSha: 'c'.repeat(40),
21 + originalText: 'one',
22 + draftText: 'two',
23 + draftDigest: '1'.repeat(64)
24 + },
25 + {
26 + path: 'src/a.js',
27 + blobSha: 'd'.repeat(40),
28 + originalText: 'a',
29 + draftText: 'b',
30 + draftDigest: '2'.repeat(64)
31 + }
32 + ]
33 +};
34
7 -test('workspace view lists every change-set file and exposes add control', async()=>{
8 - const workspaces={async getWorkspace(){return structuredClone(ws)},async createNavigationRefs({refs}){return refs.map((_,i)=>({refId:`R00000000${i}`}))}};
9 - const c=createWorkspaceController({github:{},workspaces,editorUrl:'https://example.com/editor'});
10 - const v=await c.resolveCallback('ws:W000000001',{ownerId:'42'}).execute();
11 - assert.match(v.text,/README\.md/); assert.match(v.text,/src\/a\.js/); assert.match(v.text,/2 فایل/);
12 - assert.ok(v.reply_markup.inline_keyboard.flat().some(b=>b.callback_data==='wfiles:W000000001:1'));
35 +test('workspace view lists every change-set file and exposes add control', async () => {
36 + const workspaces = {
37 + async getWorkspace() {
38 + return structuredClone(ws);
39 + },
40 + async createNavigationRefs({ refs }) {
41 + return refs.map((_, i) => ({ refId: `R00000000${i}` }));
42 + }
43 + };
44 + const c = createWorkspaceController({
45 + github: {},
46 + workspaces,
47 + editorUrl: 'https://example.com/editor'
48 + });
49 + const v = await c
50 + .resolveCallback('ws:W000000001', { ownerId: '42' })
51 + .execute();
52 + assert.match(v.text, /README\.md/);
53 + assert.match(v.text, /src\/a\.js/);
54 + assert.match(v.text, /2 فایل/);
55 + assert.ok(
56 + v.reply_markup.inline_keyboard
57 + .flat()
58 + .some((b) => b.callback_data === 'wfiles:W000000001:1')
59 + );
60 });
61
15 -test('adding a file reads pinned source then upserts durable workspace only', async()=>{
16 - const calls=[];
17 - const workspaces={async resolveNavigationRef(){return {repoId:1,path:'src/b.js',type:'workspace-add',workspaceId:'W000000001'}},async getWorkspace(){return structuredClone(ws)},async upsertWorkspaceFile(x){calls.push(['upsert',x]);return {...ws,files:[...ws.files,x.file]}},async createNavigationRefs({refs}){return refs.map((_,i)=>({refId:`R00000000${i}`}))}};
18 - const github={async getRepository(){return {fullName:'o/r',defaultBranch:'main'}},async getBranchSnapshot(){return {headSha:ws.baseHeadSha,treeSha:ws.baseTreeSha}},async getFileAtRef(_r,path){calls.push(['read',path]);return {path,sha:'e'.repeat(40),content:'safe',size:4}}};
19 - const c=createWorkspaceController({github,workspaces});
20 - const v=await c.resolveCallback('wadd:R000000001',{ownerId:'42'}).execute();
21 - assert.equal(calls[0][0],'read'); assert.equal(calls[1][0],'upsert'); assert.match(v.text,/اضافه|added/i);
62 +test('adding a file reads pinned source then upserts durable workspace only', async () => {
63 + const calls = [];
64 + const workspaces = {
65 + async resolveNavigationRef() {
66 + return {
67 + repoId: 1,
68 + path: 'src/b.js',
69 + type: 'workspace-add',
70 + workspaceId: 'W000000001'
71 + };
72 + },
73 + async getWorkspace() {
74 + return structuredClone(ws);
75 + },
76 + async upsertWorkspaceFile(x) {
77 + calls.push(['upsert', x]);
78 + return { ...ws, files: [...ws.files, x.file] };
79 + },
80 + async createNavigationRefs({ refs }) {
81 + return refs.map((_, i) => ({ refId: `R00000000${i}` }));
82 + }
83 + };
84 + const github = {
85 + async getRepository() {
86 + return { fullName: 'o/r', defaultBranch: 'main' };
87 + },
88 + async getBranchSnapshot() {
89 + return { headSha: ws.baseHeadSha, treeSha: ws.baseTreeSha };
90 + },
91 + async getFileAtRef(_r, path) {
92 + calls.push(['read', path]);
93 + return { path, sha: 'e'.repeat(40), content: 'safe', size: 4 };
94 + }
95 + };
96 + const c = createWorkspaceController({ github, workspaces });
97 + const v = await c
98 + .resolveCallback('wadd:R000000001', { ownerId: '42' })
99 + .execute();
100 + assert.equal(calls[0][0], 'read');
101 + assert.equal(calls[1][0], 'upsert');
102 + assert.match(v.text, /اضافه|added/i);
103 });
104
24 -test('removing a change-set file uses opaque ref and durable remove', async()=>{
25 - let removed='';
26 - const workspaces={async resolveNavigationRef(){return {workspaceId:'W000000001',path:'src/a.js',type:'workspace-file'}},async removeWorkspaceFile({path}){removed=path;return {...ws,files:[ws.files[0]]}},async createNavigationRefs({refs}){return refs.map((_,i)=>({refId:`R00000000${i}`}))}};
27 - const c=createWorkspaceController({github:{},workspaces});
28 - const v=await c.resolveCallback('wremove:R000000001',{ownerId:'42'}).execute();
29 - assert.equal(removed,'src/a.js'); assert.match(v.text,/README\.md/);
105 +test('removing a change-set file uses opaque ref and durable remove', async () => {
106 + let removed = '';
107 + const workspaces = {
108 + async resolveNavigationRef() {
109 + return {
110 + workspaceId: 'W000000001',
111 + path: 'src/a.js',
112 + type: 'workspace-file'
113 + };
114 + },
115 + async removeWorkspaceFile({ path }) {
116 + removed = path;
117 + return { ...ws, files: [ws.files[0]] };
118 + },
119 + async createNavigationRefs({ refs }) {
120 + return refs.map((_, i) => ({ refId: `R00000000${i}` }));
121 + }
122 + };
123 + const c = createWorkspaceController({ github: {}, workspaces });
124 + const v = await c
125 + .resolveCallback('wremove:R000000001', { ownerId: '42' })
126 + .execute();
127 + assert.equal(removed, 'src/a.js');
128 + assert.match(v.text, /README\.md/);
129 });
130
32 -
33 -test('add-file callback actions are declared READ in the GitHub manifest', async()=>{
34 - const { githubPluginManifest } = await import('../src/plugins/github/manifest.js');
35 - for (const action of ['github.workspace.file.pick','github.workspace.file.add','github.workspace.file.remove']) {
36 - assert.equal(githubPluginManifest.actions[action]?.risk, 'READ', action + ' must be routed as owner-only READ');
37 - }
131 +test('add-file callback actions are declared READ in the GitHub manifest', async () => {
132 + const { githubPluginManifest } = await import(
133 + '../src/plugins/github/manifest.js'
134 + );
135 + for (const action of [
136 + 'github.workspace.file.pick',
137 + 'github.workspace.file.add',
138 + 'github.workspace.file.remove'
139 + ]) {
140 + assert.equal(
141 + githubPluginManifest.actions[action]?.risk,
142 + 'READ',
143 + action + ' must be routed as owner-only READ'
144 + );
145 + }
146 });
147
40 -
41 -test('file picker rejects a repo id that is not bound to the workspace', async()=>{
42 - const workspaces={async getWorkspace(){return structuredClone(ws)}};
43 - const c=createWorkspaceController({github:{async listFiles(){throw new Error('must not read mismatched repo')}},workspaces});
44 - await assert.rejects(()=>c.resolveCallback('wfiles:W000000001:2',{ownerId:'42'}).execute(),/repository mismatch/i);
148 +test('file picker rejects a repo id that is not bound to the workspace', async () => {
149 + const workspaces = {
150 + async getWorkspace() {
151 + return structuredClone(ws);
152 + }
153 + };
154 + const c = createWorkspaceController({
155 + github: {
156 + async listFiles() {
157 + throw new Error('must not read mismatched repo');
158 + }
159 + },
160 + workspaces
161 + });
162 + await assert.rejects(
163 + () => c.resolveCallback('wfiles:W000000001:2', { ownerId: '42' }).execute(),
164 + /repository mismatch/i
165 + );
166 });
167
47 -test('file picker lists candidates from the exact workspace base snapshot', async()=>{
48 - let seen;
49 - const workspaces={async getWorkspace(){return structuredClone(ws)},async createNavigationRefs({refs}){return refs.map((_,i)=>({refId:'R'+String(i).padStart(9,'0')}))}};
50 - const github={async listFiles(repoId,path,options){seen={repoId,path,options};return [{type:'file',path:'src/new.js',sha:'e'.repeat(40)}]}};
51 - const c=createWorkspaceController({github,workspaces});
52 - await c.resolveCallback('wfiles:W000000001:1',{ownerId:'42'}).execute();
53 - assert.deepEqual(seen,{repoId:1,path:'',options:{ref:ws.baseHeadSha}});
168 +test('file picker lists candidates from the exact workspace base snapshot', async () => {
169 + let seen;
170 + const workspaces = {
171 + async getWorkspace() {
172 + return structuredClone(ws);
173 + },
174 + async createNavigationRefs({ refs }) {
175 + return refs.map((_, i) => ({ refId: 'R' + String(i).padStart(9, '0') }));
176 + }
177 + };
178 + const github = {
179 + async listFiles(repoId, path, options) {
180 + seen = { repoId, path, options };
181 + return [{ type: 'file', path: 'src/new.js', sha: 'e'.repeat(40) }];
182 + }
183 + };
184 + const c = createWorkspaceController({ github, workspaces });
185 + await c.resolveCallback('wfiles:W000000001:1', { ownerId: '42' }).execute();
186 + assert.deepEqual(seen, {
187 + repoId: 1,
188 + path: '',
189 + options: { ref: ws.baseHeadSha }
190 + });
191 });
192
56 -test('multi-file workspace exposes a direct editor button for every file', async()=>{
57 - const workspaces={async getWorkspace(){return structuredClone(ws)},async createNavigationRefs({refs}){return refs.map((_,i)=>({refId:'R'+String(i).padStart(9,'0')}))}};
58 - const c=createWorkspaceController({github:{},workspaces,editorUrl:'https://example.com/workspace/editor'});
59 - const v=await c.resolveCallback('ws:W000000001',{ownerId:'42'}).execute();
60 - const editors=v.reply_markup.inline_keyboard.flat().filter(button=>button.web_app?.url);
61 - assert.equal(editors.length,2);
62 - assert.equal(editors[0].web_app.url,'https://example.com/workspace/editor?workspaceId=W000000001&path=README.md');
63 - assert.equal(editors[1].web_app.url,'https://example.com/workspace/editor?workspaceId=W000000001&path=src%2Fa.js');
64 - assert.match(editors[1].text,/src\/a\.js/);
193 +test('multi-file workspace exposes a direct editor button for every file', async () => {
194 + const workspaces = {
195 + async getWorkspace() {
196 + return structuredClone(ws);
197 + },
198 + async createNavigationRefs({ refs }) {
199 + return refs.map((_, i) => ({ refId: 'R' + String(i).padStart(9, '0') }));
200 + }
201 + };
202 + const c = createWorkspaceController({
203 + github: {},
204 + workspaces,
205 + editorUrl: 'https://example.com/workspace/editor'
206 + });
207 + const v = await c
208 + .resolveCallback('ws:W000000001', { ownerId: '42' })
209 + .execute();
210 + const editors = v.reply_markup.inline_keyboard
211 + .flat()
212 + .filter((button) => button.web_app?.url);
213 + assert.equal(editors.length, 2);
214 + assert.equal(
215 + editors[0].web_app.url,
216 + 'https://example.com/workspace/editor?workspaceId=W000000001&path=README.md'
217 + );
218 + assert.equal(
219 + editors[1].web_app.url,
220 + 'https://example.com/workspace/editor?workspaceId=W000000001&path=src%2Fa.js'
221 + );
222 + assert.match(editors[1].text, /src\/a\.js/);
223 });
224
67 -test('ready view lists every changed file in the sealed change set', async()=>{
68 - const workspaces={async getWorkspace(){return structuredClone(ws)},async sealIntent({intent}){return {id:'INTENT01',...intent}}};
69 - const c=createWorkspaceController({github:{},workspaces});
70 - const v=await c.resolveCallback('wready:W000000001',{ownerId:'42'}).execute();
71 - assert.match(v.text,/README\.md/);
72 - assert.match(v.text,/src\/a\.js/);
73 - assert.match(v.text,/2/);
225 +test('ready view lists every changed file in the sealed change set', async () => {
226 + const workspaces = {
227 + async getWorkspace() {
228 + return structuredClone(ws);
229 + },
230 + async sealIntent({ intent }) {
231 + return { id: 'INTENT01', ...intent };
232 + }
233 + };
234 + const c = createWorkspaceController({ github: {}, workspaces });
235 + const v = await c
236 + .resolveCallback('wready:W000000001', { ownerId: '42' })
237 + .execute();
238 + assert.match(v.text, /README\.md/);
239 + assert.match(v.text, /src\/a\.js/);
240 + assert.match(v.text, /2/);
241 });
test/phase2-editor-multifile.test.js
+98 -7
@@ -2,10 +2,101 @@ import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import { handleWorkspaceEditorRequest } from '../src/workspace-editor.js';
4 import { createHmac } from 'node:crypto';
5 -function initData(token='123:TEST',userId=42,authDate=1800000000){const p=new URLSearchParams({auth_date:String(authDate),query_id:'q',user:JSON.stringify({id:userId})});const s=[...p].sort(([a],[b])=>a.localeCompare(b)).map(([k,v])=>`${k}=${v}`).join('\n');const key=createHmac('sha256','WebAppData').update(token).digest();p.set('hash',createHmac('sha256',key).update(s).digest('hex'));return p.toString()}
6 -const workspace={id:'W000000001',state:'DRAFT',baseHeadSha:'a'.repeat(40),path:'README.md',draftText:'one',files:[{path:'README.md',draftText:'one',originalText:'zero'},{path:'src/a.js',draftText:'a',originalText:'a'}]};
7 -const context=(calls)=>({botToken:'123:TEST',ownerId:'42',now:()=>1800000000*1000,workspaces:{async getWorkspace(){return structuredClone(workspace)},async updateWorkspaceFileDraft(x){calls.push(x);return {...workspace,files:workspace.files.map(f=>f.path===x.path?{...f,draftText:x.text}:f)}}}});
8 -const headers={'x-telegram-init-data':initData()};
9 -test('editor GET exposes bounded file metadata and selects requested member path',async()=>{const r=await handleWorkspaceEditorRequest(new Request('https://x/workspace/api/editor?workspaceId=W000000001&path=src%2Fa.js',{headers}),context([]));assert.equal(r.status,200);const b=await r.json();assert.deepEqual(b.workspace.files.map(f=>f.path),['README.md','src/a.js']);assert.equal(b.workspace.path,'src/a.js');assert.equal(b.workspace.draftText,'a')});
10 -test('editor PUT updates selected member through path-scoped durable method',async()=>{const calls=[];const r=await handleWorkspaceEditorRequest(new Request('https://x/workspace/api/editor',{method:'PUT',headers:{...headers,'content-type':'application/json'},body:JSON.stringify({workspaceId:'W000000001',path:'src/a.js',text:'b'})}),context(calls));assert.equal(r.status,200);assert.equal(calls.length,1);assert.equal(calls[0].path,'src/a.js');assert.equal(calls[0].text,'b')});
11 -test('editor rejects path outside change set',async()=>{const r=await handleWorkspaceEditorRequest(new Request('https://x/workspace/api/editor',{method:'PUT',headers:{...headers,'content-type':'application/json'},body:JSON.stringify({workspaceId:'W000000001',path:'evil.js',text:'x'})}),context([]));assert.equal(r.status,400);const b=await r.json();assert.match(b.error,/path|member|change set/i)});
5 +function initData(token = '123:TEST', userId = 42, authDate = 1800000000) {
6 + const p = new URLSearchParams({
7 + auth_date: String(authDate),
8 + query_id: 'q',
9 + user: JSON.stringify({ id: userId })
10 + });
11 + const s = [...p]
12 + .sort(([a], [b]) => a.localeCompare(b))
13 + .map(([k, v]) => `${k}=${v}`)
14 + .join('\n');
15 + const key = createHmac('sha256', 'WebAppData').update(token).digest();
16 + p.set('hash', createHmac('sha256', key).update(s).digest('hex'));
17 + return p.toString();
18 +}
19 +const workspace = {
20 + id: 'W000000001',
21 + state: 'DRAFT',
22 + baseHeadSha: 'a'.repeat(40),
23 + path: 'README.md',
24 + draftText: 'one',
25 + files: [
26 + { path: 'README.md', draftText: 'one', originalText: 'zero' },
27 + { path: 'src/a.js', draftText: 'a', originalText: 'a' }
28 + ]
29 +};
30 +const context = (calls) => ({
31 + botToken: '123:TEST',
32 + ownerId: '42',
33 + now: () => 1800000000 * 1000,
34 + workspaces: {
35 + async getWorkspace() {
36 + return structuredClone(workspace);
37 + },
38 + async updateWorkspaceFileDraft(x) {
39 + calls.push(x);
40 + return {
41 + ...workspace,
42 + files: workspace.files.map((f) =>
43 + f.path === x.path ? { ...f, draftText: x.text } : f
44 + )
45 + };
46 + }
47 + }
48 +});
49 +const headers = { 'x-telegram-init-data': initData() };
50 +test('editor GET exposes bounded file metadata and selects requested member path', async () => {
51 + const r = await handleWorkspaceEditorRequest(
52 + new Request(
53 + 'https://x/workspace/api/editor?workspaceId=W000000001&path=src%2Fa.js',
54 + { headers }
55 + ),
56 + context([])
57 + );
58 + assert.equal(r.status, 200);
59 + const b = await r.json();
60 + assert.deepEqual(
61 + b.workspace.files.map((f) => f.path),
62 + ['README.md', 'src/a.js']
63 + );
64 + assert.equal(b.workspace.path, 'src/a.js');
65 + assert.equal(b.workspace.draftText, 'a');
66 +});
67 +test('editor PUT updates selected member through path-scoped durable method', async () => {
68 + const calls = [];
69 + const r = await handleWorkspaceEditorRequest(
70 + new Request('https://x/workspace/api/editor', {
71 + method: 'PUT',
72 + headers: { ...headers, 'content-type': 'application/json' },
73 + body: JSON.stringify({
74 + workspaceId: 'W000000001',
75 + path: 'src/a.js',
76 + text: 'b'
77 + })
78 + }),
79 + context(calls)
80 + );
81 + assert.equal(r.status, 200);
82 + assert.equal(calls.length, 1);
83 + assert.equal(calls[0].path, 'src/a.js');
84 + assert.equal(calls[0].text, 'b');
85 +});
86 +test('editor rejects path outside change set', async () => {
87 + const r = await handleWorkspaceEditorRequest(
88 + new Request('https://x/workspace/api/editor', {
89 + method: 'PUT',
90 + headers: { ...headers, 'content-type': 'application/json' },
91 + body: JSON.stringify({
92 + workspaceId: 'W000000001',
93 + path: 'evil.js',
94 + text: 'x'
95 + })
96 + }),
97 + context([])
98 + );
99 + assert.equal(r.status, 400);
100 + const b = await r.json();
101 + assert.match(b.error, /path|member|change set/i);
102 +});
test/phase2-multifile-acceptance.test.js
+19 -4
@@ -11,10 +11,25 @@ test('Phase 2 acceptance docs lock the multi-file safety contract', async () =>
11 read('docs/PHASE2_MULTIFILE_ACCEPTANCE.md')
12 ]);
13 const docs = `${readme}\n${runbook}\n${acceptance}`;
14 - for (const phrase of ['multi-file Change Set', 'nexa/edit-*', 'exact base SHA', 'Safe Approval', 'Kill Switch', 'single-file compatibility']) {
15 - assert.match(docs, new RegExp(phrase.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i'), `missing acceptance phrase: ${phrase}`);
14 + for (const phrase of [
15 + 'multi-file Change Set',
16 + 'nexa/edit-*',
17 + 'exact base SHA',
18 + 'Safe Approval',
19 + 'Kill Switch',
20 + 'single-file compatibility'
21 + ]) {
22 + assert.match(
23 + docs,
24 + new RegExp(phrase.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i'),
25 + `missing acceptance phrase: ${phrase}`
26 + );
27 }
17 - assert.match(docs, /no direct [`]?main[`]? mutation|main.*never.*mutat|direct.*main.*prohibit/i);
18 - for (const evidence of ['CI', 'deploy', 'Runtime', 'Owner-device']) assert.match(acceptance, new RegExp(evidence, 'i'));
28 + assert.match(
29 + docs,
30 + /no direct [`]?main[`]? mutation|main.*never.*mutat|direct.*main.*prohibit/i
31 + );
32 + for (const evidence of ['CI', 'deploy', 'Runtime', 'Owner-device'])
33 + assert.match(acceptance, new RegExp(evidence, 'i'));
34 assert.match(acceptance, /merge SHA/i);
35 });
test/phase2-ready.test.js
+72 -6
@@ -1,6 +1,72 @@
1 -import test from 'node:test';import assert from 'node:assert/strict';import {createWorkspaceController} from '../src/plugins/github/workspace.js';
2 -const files=[{path:'README.md',blobSha:'c'.repeat(40),originalText:'one',draftText:'two',draftDigest:'1'.repeat(64)},{path:'src/a.js',blobSha:'d'.repeat(40),originalText:'a',draftText:'b',draftDigest:'2'.repeat(64)}];
3 -function setup(order=files){let sealed;const workspace={id:'W000000001',repoId:1,baseBranch:'main',baseHeadSha:'a'.repeat(40),baseTreeSha:'b'.repeat(40),createdAt:1000,commitMessage:'msg',commitMessageDigest:'9'.repeat(64),files:order};const workspaces={async getWorkspace(){return structuredClone(workspace)},async sealIntent({intent}){sealed=intent;return{id:'I0000001',...intent}}};return{c:createWorkspaceController({github:{},workspaces}),get:()=>sealed}}
4 -test('Ready seals ordered descriptors for every changed file',async()=>{const x=setup();await x.c.resolveCallback('wready:W000000001',{ownerId:'42'}).execute();const i=x.get();assert.deepEqual(i.files.map(f=>f.path),['README.md','src/a.js']);assert.ok(i.files.every(f=>f.sourceBlobSha&&f.contentDigest));assert.equal(i.path,undefined)});
5 -test('file order changes aggregate intent digest',async()=>{const a=setup(files),b=setup([...files].reverse());await a.c.resolveCallback('wready:W000000001',{ownerId:'42'}).execute();await b.c.resolveCallback('wready:W000000001',{ownerId:'42'}).execute();assert.notEqual(a.get().intentDigest,b.get().intentDigest)});
6 -test('Ready rejects a change set with no changed files',async()=>{const same=files.map(f=>({...f,draftText:f.originalText}));const x=setup(same);await assert.rejects(()=>x.c.resolveCallback('wready:W000000001',{ownerId:'42'}).execute(),/No draft change/i)});
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { createWorkspaceController } from '../src/plugins/github/workspace.js';
4 +const files = [
5 + {
6 + path: 'README.md',
7 + blobSha: 'c'.repeat(40),
8 + originalText: 'one',
9 + draftText: 'two',
10 + draftDigest: '1'.repeat(64)
11 + },
12 + {
13 + path: 'src/a.js',
14 + blobSha: 'd'.repeat(40),
15 + originalText: 'a',
16 + draftText: 'b',
17 + draftDigest: '2'.repeat(64)
18 + }
19 +];
20 +function setup(order = files) {
21 + let sealed;
22 + const workspace = {
23 + id: 'W000000001',
24 + repoId: 1,
25 + baseBranch: 'main',
26 + baseHeadSha: 'a'.repeat(40),
27 + baseTreeSha: 'b'.repeat(40),
28 + createdAt: 1000,
29 + commitMessage: 'msg',
30 + commitMessageDigest: '9'.repeat(64),
31 + files: order
32 + };
33 + const workspaces = {
34 + async getWorkspace() {
35 + return structuredClone(workspace);
36 + },
37 + async sealIntent({ intent }) {
38 + sealed = intent;
39 + return { id: 'I0000001', ...intent };
40 + }
41 + };
42 + return {
43 + c: createWorkspaceController({ github: {}, workspaces }),
44 + get: () => sealed
45 + };
46 +}
47 +test('Ready seals ordered descriptors for every changed file', async () => {
48 + const x = setup();
49 + await x.c.resolveCallback('wready:W000000001', { ownerId: '42' }).execute();
50 + const i = x.get();
51 + assert.deepEqual(
52 + i.files.map((f) => f.path),
53 + ['README.md', 'src/a.js']
54 + );
55 + assert.ok(i.files.every((f) => f.sourceBlobSha && f.contentDigest));
56 + assert.equal(i.path, undefined);
57 +});
58 +test('file order changes aggregate intent digest', async () => {
59 + const a = setup(files),
60 + b = setup([...files].reverse());
61 + await a.c.resolveCallback('wready:W000000001', { ownerId: '42' }).execute();
62 + await b.c.resolveCallback('wready:W000000001', { ownerId: '42' }).execute();
63 + assert.notEqual(a.get().intentDigest, b.get().intentDigest);
64 +});
65 +test('Ready rejects a change set with no changed files', async () => {
66 + const same = files.map((f) => ({ ...f, draftText: f.originalText }));
67 + const x = setup(same);
68 + await assert.rejects(
69 + () => x.c.resolveCallback('wready:W000000001', { ownerId: '42' }).execute(),
70 + /No draft change/i
71 + );
72 +});
test/platform-experience.test.js
+57 -8
@@ -1,8 +1,57 @@
1 -import test from'node:test';import assert from'node:assert/strict';import{UX_CAPABILITIES,buildCopilotBrief,evaluateBrowserQa,buildPluginCatalog,buildPortfolio,searchCommandCenter}from'../src/core/platform-experience.js';import{platformHomeView,platformCapabilityView}from'../src/platform-menu.js';
2 -test('rows 8-12 are explicit and bounded',()=>assert.deepEqual(UX_CAPABILITIES.map(x=>x.id),[8,9,10,11,12]));
3 -test('copilot is evidence grounded and cannot mutate',()=>{const x=buildCopilotBrief({goal:'fix',evidence:['token=abc failure']});assert.equal(x.canMutate,false);assert.doesNotMatch(JSON.stringify(x),/abc/);});
4 -test('browser QA never invents pass without evidence',()=>{assert.equal(evaluateBrowserQa([{label:'home'}]).status,'blocked');assert.equal(evaluateBrowserQa([{label:'home',status:'pass',evidence:'HTTP 200'}]).status,'passed');});
5 -test('plugin catalog preserves declared risks',()=>assert.equal(buildPluginCatalog([{id:'g',actions:[{id:'x',risk:'WRITE'}]}])[0].actions[0].risk,'WRITE'));
6 -test('portfolio clamps unknown status',()=>assert.equal(buildPortfolio([{id:1,name:'a',status:'magic'}])[0].status,'unknown'));
7 -test('command center search is bounded',()=>assert.equal(searchCommandCenter('repo',Array.from({length:30},(_,i)=>({title:'repo '+i}))).length,12));
8 -test('platform UI exposes all five capabilities with safe callbacks',()=>{const v=platformHomeView();assert.equal(v.reply_markup.inline_keyboard.length,6);for(const c of UX_CAPABILITIES)assert.match(platformCapabilityView(c.key).text,new RegExp(String(c.id)));});
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import {
4 + UX_CAPABILITIES,
5 + buildCopilotBrief,
6 + evaluateBrowserQa,
7 + buildPluginCatalog,
8 + buildPortfolio,
9 + searchCommandCenter
10 +} from '../src/core/platform-experience.js';
11 +import {
12 + platformHomeView,
13 + platformCapabilityView
14 +} from '../src/platform-menu.js';
15 +test('rows 8-12 are explicit and bounded', () =>
16 + assert.deepEqual(
17 + UX_CAPABILITIES.map((x) => x.id),
18 + [8, 9, 10, 11, 12]
19 + ));
20 +test('copilot is evidence grounded and cannot mutate', () => {
21 + const x = buildCopilotBrief({ goal: 'fix', evidence: ['token=abc failure'] });
22 + assert.equal(x.canMutate, false);
23 + assert.doesNotMatch(JSON.stringify(x), /abc/);
24 +});
25 +test('browser QA never invents pass without evidence', () => {
26 + assert.equal(evaluateBrowserQa([{ label: 'home' }]).status, 'blocked');
27 + assert.equal(
28 + evaluateBrowserQa([{ label: 'home', status: 'pass', evidence: 'HTTP 200' }])
29 + .status,
30 + 'passed'
31 + );
32 +});
33 +test('plugin catalog preserves declared risks', () =>
34 + assert.equal(
35 + buildPluginCatalog([{ id: 'g', actions: [{ id: 'x', risk: 'WRITE' }] }])[0]
36 + .actions[0].risk,
37 + 'WRITE'
38 + ));
39 +test('portfolio clamps unknown status', () =>
40 + assert.equal(
41 + buildPortfolio([{ id: 1, name: 'a', status: 'magic' }])[0].status,
42 + 'unknown'
43 + ));
44 +test('command center search is bounded', () =>
45 + assert.equal(
46 + searchCommandCenter(
47 + 'repo',
48 + Array.from({ length: 30 }, (_, i) => ({ title: 'repo ' + i }))
49 + ).length,
50 + 12
51 + ));
52 +test('platform UI exposes all five capabilities with safe callbacks', () => {
53 + const v = platformHomeView();
54 + assert.equal(v.reply_markup.inline_keyboard.length, 6);
55 + for (const c of UX_CAPABILITIES)
56 + assert.match(platformCapabilityView(c.key).text, new RegExp(String(c.id)));
57 +});
test/plugin-registry.test.js
+9 -7
@@ -31,19 +31,21 @@ test('PluginRegistry rejects duplicate plugin ids', () => {
31
32 test('PluginRegistry rejects duplicate action ids across plugins', () => {
33 assert.throws(
34 - () => new PluginRegistry([
35 - plugin('github', { 'shared.read': { risk: 'READ' } }),
36 - plugin('cloudflare', { 'shared.read': { risk: 'READ' } })
37 - ]),
34 + () =>
35 + new PluginRegistry([
36 + plugin('github', { 'shared.read': { risk: 'READ' } }),
37 + plugin('cloudflare', { 'shared.read': { risk: 'READ' } })
38 + ]),
39 /duplicate action id/i
40 );
41 });
42
43 test('PluginRegistry rejects unknown action risk levels', () => {
44 assert.throws(
44 - () => new PluginRegistry([
45 - plugin('github', { 'github.repos.list': { risk: 'SUPERUSER' } })
46 - ]),
45 + () =>
46 + new PluginRegistry([
47 + plugin('github', { 'github.repos.list': { risk: 'SUPERUSER' } })
48 + ]),
49 /invalid action risk/i
50 );
51 });
test/plugin-router.test.js
+36 -27
@@ -6,7 +6,7 @@ import { PluginRouter } from '../src/core/router.js';
6
7 function auditCollector() {
8 const events = [];
9 - return { events, logger: { log: event => events.push(event) } };
9 + return { events, logger: { log: (event) => events.push(event) } };
10 }
11
12 test('PluginRouter dispatches the first matching READ command after policy evaluation', async () => {
@@ -20,15 +20,16 @@ test('PluginRouter dispatches the first matching READ command after policy evalu
20 id: 'second',
21 actions: { 'second.read': { risk: 'READ' } }
22 },
23 - resolveCommand: command => command === '/go'
24 - ? {
25 - actionId: 'second.read',
26 - execute: async () => {
27 - executed += 1;
28 - return { view: 'ok' };
23 + resolveCommand: (command) =>
24 + command === '/go'
25 + ? {
26 + actionId: 'second.read',
27 + execute: async () => {
28 + executed += 1;
29 + return { view: 'ok' };
30 + }
31 }
30 - }
31 - : null
32 + : null
33 };
34 const third = {
35 manifest: {
@@ -66,15 +67,16 @@ test('PluginRouter dispatches callbacks through the same policy boundary', async
67 id: 'sample',
68 actions: { 'sample.callback.read': { risk: 'READ' } }
69 },
69 - resolveCallback: data => data === 'sample:1'
70 - ? {
71 - actionId: 'sample.callback.read',
72 - execute: async () => {
73 - executed += 1;
74 - return { callback: 'ok' };
70 + resolveCallback: (data) =>
71 + data === 'sample:1'
72 + ? {
73 + actionId: 'sample.callback.read',
74 + execute: async () => {
75 + executed += 1;
76 + return { callback: 'ok' };
77 + }
78 }
76 - }
77 - : null
79 + : null
80 };
81 const router = new PluginRouter({
82 registry: new PluginRegistry([plugin]),
@@ -101,8 +103,14 @@ test('PluginRouter returns null when no plugin owns the route', async () => {
103 audit: { log() {} }
104 });
105
104 - assert.equal(await router.dispatchCommand('/unknown', { isOwner: true }), null);
105 - assert.equal(await router.dispatchCallback('unknown', { isOwner: true }), null);
106 + assert.equal(
107 + await router.dispatchCommand('/unknown', { isOwner: true }),
108 + null
109 + );
110 + assert.equal(
111 + await router.dispatchCallback('unknown', { isOwner: true }),
112 + null
113 + );
114 });
115
116 test('PluginRouter denies undeclared actions without executing plugin code', async () => {
@@ -169,15 +177,16 @@ test('PluginRouter executes an approved owner WRITE action exactly once', async
177 id: 'sample',
178 actions: { 'sample.write': { risk: 'WRITE' } }
179 },
172 - resolveCallback: data => data === 'write:1'
173 - ? {
174 - actionId: 'sample.write',
175 - execute: async () => {
176 - executed += 1;
177 - return { ok: true, view: 'done' };
180 + resolveCallback: (data) =>
181 + data === 'write:1'
182 + ? {
183 + actionId: 'sample.write',
184 + execute: async () => {
185 + executed += 1;
186 + return { ok: true, view: 'done' };
187 + }
188 }
179 - }
180 - : null
189 + : null
190 };
191 const router = new PluginRouter({
192 registry: new PluginRegistry([plugin]),
test/security.test.js
+44 -41
@@ -1,21 +1,21 @@
1 -import test from "node:test";
2 -import assert from "node:assert/strict";
3 -import worker from "../src/index.js";
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import worker from '../src/index.js';
4
5 function telegramRequest(secret, update) {
6 - const headers = { "content-type": "application/json" };
7 - if (secret !== undefined) headers["X-Telegram-Bot-Api-Secret-Token"] = secret;
6 + const headers = { 'content-type': 'application/json' };
7 + if (secret !== undefined) headers['X-Telegram-Bot-Api-Secret-Token'] = secret;
8
9 - return new Request("https://example.com/telegram/webhook", {
10 - method: "POST",
9 + return new Request('https://example.com/telegram/webhook', {
10 + method: 'POST',
11 headers,
12 - body: JSON.stringify(update),
12 + body: JSON.stringify(update)
13 });
14 }
15
16 -test("webhook fails closed when TELEGRAM_WEBHOOK_SECRET is missing", async () => {
16 +test('webhook fails closed when TELEGRAM_WEBHOOK_SECRET is missing', async () => {
17 const req = telegramRequest(undefined, {
18 - message: { text: "/status", from: { id: 123 }, chat: { id: 123 } },
18 + message: { text: '/status', from: { id: 123 }, chat: { id: 123 } }
19 });
20
21 let calls = 0;
@@ -23,43 +23,43 @@ test("webhook fails closed when TELEGRAM_WEBHOOK_SECRET is missing", async () =>
23 calls += 1;
24 return new Response(JSON.stringify({ ok: true }), {
25 status: 200,
26 - headers: { "content-type": "application/json" },
26 + headers: { 'content-type': 'application/json' }
27 });
28 };
29
30 const res = await worker.fetch(req, {
31 - OWNER_TELEGRAM_ID: "123",
32 - TELEGRAM_BOT_TOKEN: "token",
31 + OWNER_TELEGRAM_ID: '123',
32 + TELEGRAM_BOT_TOKEN: 'token'
33 });
34
35 assert.equal(res.status, 503);
36 assert.equal(calls, 0);
37 });
38
39 -test("webhook rejects a wrong Telegram secret", async () => {
40 - const req = telegramRequest("wrong", {
41 - message: { text: "/status", from: { id: 123 }, chat: { id: 123 } },
39 +test('webhook rejects a wrong Telegram secret', async () => {
40 + const req = telegramRequest('wrong', {
41 + message: { text: '/status', from: { id: 123 }, chat: { id: 123 } }
42 });
43
44 let calls = 0;
45 globalThis.fetch = async () => {
46 calls += 1;
47 - throw new Error("should not call network");
47 + throw new Error('should not call network');
48 };
49
50 const res = await worker.fetch(req, {
51 - TELEGRAM_WEBHOOK_SECRET: "right",
52 - OWNER_TELEGRAM_ID: "123",
53 - TELEGRAM_BOT_TOKEN: "token",
51 + TELEGRAM_WEBHOOK_SECRET: 'right',
52 + OWNER_TELEGRAM_ID: '123',
53 + TELEGRAM_BOT_TOKEN: 'token'
54 });
55
56 assert.equal(res.status, 403);
57 assert.equal(calls, 0);
58 });
59
60 -test("unauthorized Telegram users receive no bot response", async () => {
61 - const req = telegramRequest("right", {
62 - message: { text: "/status", from: { id: 999 }, chat: { id: 999 } },
60 +test('unauthorized Telegram users receive no bot response', async () => {
61 + const req = telegramRequest('right', {
62 + message: { text: '/status', from: { id: 999 }, chat: { id: 999 } }
63 });
64
65 let calls = 0;
@@ -67,43 +67,46 @@ test("unauthorized Telegram users receive no bot response", async () => {
67 calls += 1;
68 return new Response(JSON.stringify({ ok: true }), {
69 status: 200,
70 - headers: { "content-type": "application/json" },
70 + headers: { 'content-type': 'application/json' }
71 });
72 };
73
74 const res = await worker.fetch(req, {
75 - TELEGRAM_WEBHOOK_SECRET: "right",
76 - OWNER_TELEGRAM_ID: "123",
77 - TELEGRAM_BOT_TOKEN: "token",
75 + TELEGRAM_WEBHOOK_SECRET: 'right',
76 + OWNER_TELEGRAM_ID: '123',
77 + TELEGRAM_BOT_TOKEN: 'token'
78 });
79
80 assert.equal(res.status, 200);
81 assert.equal(calls, 0);
82 });
83
84 -test("temporary setup endpoint is disabled after webhook registration", async () => {
85 - const req = new Request("https://nexa-dev-bot.example.workers.dev/telegram/setup", {
86 - method: "GET",
87 - });
84 +test('temporary setup endpoint is disabled after webhook registration', async () => {
85 + const req = new Request(
86 + 'https://nexa-dev-bot.example.workers.dev/telegram/setup',
87 + {
88 + method: 'GET'
89 + }
90 + );
91
92 let calls = 0;
93 globalThis.fetch = async () => {
94 calls += 1;
92 - throw new Error("setup endpoint must not call Telegram after registration");
95 + throw new Error('setup endpoint must not call Telegram after registration');
96 };
97
98 const res = await worker.fetch(req, {
96 - TELEGRAM_WEBHOOK_SECRET: "secret",
97 - TELEGRAM_BOT_TOKEN: "token",
99 + TELEGRAM_WEBHOOK_SECRET: 'secret',
100 + TELEGRAM_BOT_TOKEN: 'token'
101 });
102
103 assert.equal(res.status, 404);
104 assert.equal(calls, 0);
105 });
106
104 -test("temporary diagnostic command no longer exposes Telegram ID", async () => {
105 - const req = telegramRequest("right", {
106 - message: { text: "/diag", from: { id: 123 }, chat: { id: 123 } },
107 +test('temporary diagnostic command no longer exposes Telegram ID', async () => {
108 + const req = telegramRequest('right', {
109 + message: { text: '/diag', from: { id: 123 }, chat: { id: 123 } }
110 });
111
112 const messages = [];
@@ -112,14 +115,14 @@ test("temporary diagnostic command no longer exposes Telegram ID", async () => {
115 messages.push(payload.text);
116 return new Response(JSON.stringify({ ok: true }), {
117 status: 200,
115 - headers: { "content-type": "application/json" },
118 + headers: { 'content-type': 'application/json' }
119 });
120 };
121
122 const res = await worker.fetch(req, {
120 - TELEGRAM_WEBHOOK_SECRET: "right",
121 - OWNER_TELEGRAM_ID: "123",
122 - TELEGRAM_BOT_TOKEN: "token",
123 + TELEGRAM_WEBHOOK_SECRET: 'right',
124 + OWNER_TELEGRAM_ID: '123',
125 + TELEGRAM_BOT_TOKEN: 'token'
126 });
127
128 assert.equal(res.status, 200);
test/telegram-file-upload.test.js
+27 -9
@@ -9,27 +9,42 @@ test('TelegramClient downloads a bounded UTF-8 document through getFile', async
9 seen.push([String(url), options.method || 'GET', options.body || null]);
10 if (String(url).endsWith('/getFile')) {
11 assert.deepEqual(JSON.parse(options.body), { file_id: 'FILE123' });
12 - return Response.json({ ok: true, result: { file_path: 'documents/replacement.txt', file_size: 6 } });
12 + return Response.json({
13 + ok: true,
14 + result: { file_path: 'documents/replacement.txt', file_size: 6 }
15 + });
16 }
14 - if (String(url) === 'https://api.telegram.org/file/bottoken/documents/replacement.txt') {
15 - return new Response(new TextEncoder().encode('hello\n'), { status: 200 });
17 + if (
18 + String(url) ===
19 + 'https://api.telegram.org/file/bottoken/documents/replacement.txt'
20 + ) {
21 + return new Response(new TextEncoder().encode('hello\n'), {
22 + status: 200
23 + });
24 }
25 return new Response('unexpected', { status: 500 });
26 }
27 });
28
29 const file = await client.downloadTextFile('FILE123', { maxBytes: 12000 });
22 - assert.deepEqual(file, { text: 'hello\n', byteLength: 6, filePath: 'documents/replacement.txt' });
30 + assert.deepEqual(file, {
31 + text: 'hello\n',
32 + byteLength: 6,
33 + filePath: 'documents/replacement.txt'
34 + });
35 assert.equal(seen.length, 2);
36 });
37
38 test('TelegramClient rejects oversized Telegram documents before downloading bytes', async () => {
39 let calls = 0;
40 const client = new TelegramClient('token', {
29 - fetch: async url => {
41 + fetch: async (url) => {
42 calls += 1;
43 assert.match(String(url), /\/getFile$/);
32 - return Response.json({ ok: true, result: { file_path: 'documents/huge.txt', file_size: 12001 } });
44 + return Response.json({
45 + ok: true,
46 + result: { file_path: 'documents/huge.txt', file_size: 12001 }
47 + });
48 }
49 });
50
@@ -42,9 +57,12 @@ test('TelegramClient rejects oversized Telegram documents before downloading byt
57
58 test('TelegramClient rejects non-UTF-8 document bytes', async () => {
59 const client = new TelegramClient('token', {
45 - fetch: async url => {
60 + fetch: async (url) => {
61 if (String(url).endsWith('/getFile')) {
47 - return Response.json({ ok: true, result: { file_path: 'documents/binary.bin', file_size: 2 } });
62 + return Response.json({
63 + ok: true,
64 + result: { file_path: 'documents/binary.bin', file_size: 2 }
65 + });
66 }
67 return new Response(Uint8Array.from([0xff, 0xfe]), { status: 200 });
68 }
@@ -54,4 +72,4 @@ test('TelegramClient rejects non-UTF-8 document bytes', async () => {
72 () => client.downloadTextFile('BINARY', { maxBytes: 12000 }),
73 /UTF-?8|text/i
74 );
57 -});
\ No newline at end of file
75 +});
test/telegram-menu-e2e.test.js
+156 -23
@@ -5,29 +5,139 @@ import { createGitHubPlugin } from '../src/plugins/github/plugin.js';
5 const repoId = 123;
6 const fullSha = '0123456789abcdef0123456789abcdef01234567';
7 const github = {
8 - async getRepository() { return { id: repoId, name: 'nexa-dev-bot', fullName: 'davoodmehraban89/nexa-dev-bot', defaultBranch: 'main' }; },
9 - async listCommits() { return [{ sha: fullSha, shortSha: fullSha.slice(0, 7), message: 'Audit commit report', author: 'owner', date: '2026-10-04T12:00:00Z' }]; },
10 - async getCommit() { return { sha: fullSha, shortSha: fullSha.slice(0, 7), message: 'Audit commit report\n\nDetailed commit body', author: 'owner', date: '2026-10-04T12:00:00Z', additions: 12, deletions: 4, changedFiles: 2, files: [{ filename: 'src/menu.js', status: 'modified', additions: 8, deletions: 2 }, { filename: 'test/menu.test.js', status: 'modified', additions: 4, deletions: 2 }] }; },
11 - async listIssuesPage() { return { items: [{ number: 7, title: 'Broken report', state: 'open', author: 'owner', comments: 3 }], hasMore: false }; },
12 - async getIssue() { return { number: 7, title: 'Broken report', state: 'open', author: 'owner', comments: 3, body: 'Reproduction and expected result', labels: ['bug'], assignees: ['owner'], createdAt: '2026-10-04T10:00:00Z', updatedAt: '2026-10-04T11:00:00Z' }; },
13 - async listReleases() { return [{ id: 9, tag: 'v2.1.0', name: 'V2.1', draft: false, prerelease: false, publishedAt: '2026-10-04T10:00:00Z' }]; },
14 - async getRelease() { return { id: 9, tag: 'v2.1.0', name: 'V2.1', body: 'Production release notes', draft: false, prerelease: false, publishedAt: '2026-10-04T10:00:00Z', author: 'owner', target: 'main' }; }
8 + async getRepository() {
9 + return {
10 + id: repoId,
11 + name: 'nexa-dev-bot',
12 + fullName: 'davoodmehraban89/nexa-dev-bot',
13 + defaultBranch: 'main'
14 + };
15 + },
16 + async listCommits() {
17 + return [
18 + {
19 + sha: fullSha,
20 + shortSha: fullSha.slice(0, 7),
21 + message: 'Audit commit report',
22 + author: 'owner',
23 + date: '2026-10-04T12:00:00Z'
24 + }
25 + ];
26 + },
27 + async getCommit() {
28 + return {
29 + sha: fullSha,
30 + shortSha: fullSha.slice(0, 7),
31 + message: 'Audit commit report\n\nDetailed commit body',
32 + author: 'owner',
33 + date: '2026-10-04T12:00:00Z',
34 + additions: 12,
35 + deletions: 4,
36 + changedFiles: 2,
37 + files: [
38 + {
39 + filename: 'src/menu.js',
40 + status: 'modified',
41 + additions: 8,
42 + deletions: 2
43 + },
44 + {
45 + filename: 'test/menu.test.js',
46 + status: 'modified',
47 + additions: 4,
48 + deletions: 2
49 + }
50 + ]
51 + };
52 + },
53 + async listIssuesPage() {
54 + return {
55 + items: [
56 + {
57 + number: 7,
58 + title: 'Broken report',
59 + state: 'open',
60 + author: 'owner',
61 + comments: 3
62 + }
63 + ],
64 + hasMore: false
65 + };
66 + },
67 + async getIssue() {
68 + return {
69 + number: 7,
70 + title: 'Broken report',
71 + state: 'open',
72 + author: 'owner',
73 + comments: 3,
74 + body: 'Reproduction and expected result',
75 + labels: ['bug'],
76 + assignees: ['owner'],
77 + createdAt: '2026-10-04T10:00:00Z',
78 + updatedAt: '2026-10-04T11:00:00Z'
79 + };
80 + },
81 + async listReleases() {
82 + return [
83 + {
84 + id: 9,
85 + tag: 'v2.1.0',
86 + name: 'V2.1',
87 + draft: false,
88 + prerelease: false,
89 + publishedAt: '2026-10-04T10:00:00Z'
90 + }
91 + ];
92 + },
93 + async getRelease() {
94 + return {
95 + id: 9,
96 + tag: 'v2.1.0',
97 + name: 'V2.1',
98 + body: 'Production release notes',
99 + draft: false,
100 + prerelease: false,
101 + publishedAt: '2026-10-04T10:00:00Z',
102 + author: 'owner',
103 + target: 'main'
104 + };
105 + }
106 +};
107 +const menu = {
108 + async renderByCallback() {
109 + return { text: 'fallback', reply_markup: { inline_keyboard: [] } };
110 + }
111 +};
112 +const workspaces = {
113 + async getWorkspace() {
114 + return null;
115 + }
116 };
16 -const menu = { async renderByCallback() { return { text: 'fallback', reply_markup: { inline_keyboard: [] } }; } };
17 -const workspaces = { async getWorkspace() { return null; } };
117
19 -function callbacks(view) { return view.reply_markup.inline_keyboard.flat().map(button => button.callback_data).filter(Boolean); }
118 +function callbacks(view) {
119 + return view.reply_markup.inline_keyboard
120 + .flat()
121 + .map((button) => button.callback_data)
122 + .filter(Boolean);
123 +}
124 function assertTelegramContract(view) {
125 assert.ok(view.text && view.text.length <= 4096);
22 - for (const callback of callbacks(view)) assert.ok(Buffer.byteLength(callback, 'utf8') <= 64, callback);
126 + for (const callback of callbacks(view))
127 + assert.ok(Buffer.byteLength(callback, 'utf8') <= 64, callback);
128 }
129
130 test('commit list drills into source-backed commit detail and preserves recovery navigation', async () => {
131 const plugin = createGitHubPlugin({ github, menu, workspaces });
132 const list = await plugin.resolveCallback(`commits:${repoId}`).execute();
133 assertTelegramContract(list);
29 - assert.ok(callbacks(list).includes(`commitdetail:${repoId}:${fullSha}`), 'commit list must expose detail drill-down');
30 - const detail = await plugin.resolveCallback(`commitdetail:${repoId}:${fullSha}`).execute();
134 + assert.ok(
135 + callbacks(list).includes(`commitdetail:${repoId}:${fullSha}`),
136 + 'commit list must expose detail drill-down'
137 + );
138 + const detail = await plugin
139 + .resolveCallback(`commitdetail:${repoId}:${fullSha}`)
140 + .execute();
141 assertTelegramContract(detail);
142 assert.match(detail.text, /Detailed commit body/);
143 assert.match(detail.text, /src\/menu\.js/);
@@ -39,8 +149,13 @@ test('issue list drills into actionable issue detail and preserves recovery navi
149 const plugin = createGitHubPlugin({ github, menu, workspaces });
150 const list = await plugin.resolveCallback(`issues:${repoId}`).execute();
151 assertTelegramContract(list);
42 - assert.ok(callbacks(list).includes(`issuedetail:${repoId}:7`), 'issue list must expose detail drill-down');
43 - const detail = await plugin.resolveCallback(`issuedetail:${repoId}:7`).execute();
152 + assert.ok(
153 + callbacks(list).includes(`issuedetail:${repoId}:7`),
154 + 'issue list must expose detail drill-down'
155 + );
156 + const detail = await plugin
157 + .resolveCallback(`issuedetail:${repoId}:7`)
158 + .execute();
159 assertTelegramContract(detail);
160 assert.match(detail.text, /Reproduction and expected result/);
161 assert.ok(callbacks(detail).includes(`issues:${repoId}`));
@@ -50,8 +165,13 @@ test('release list drills into source-backed release notes and preserves recover
165 const plugin = createGitHubPlugin({ github, menu, workspaces });
166 const list = await plugin.resolveCallback(`releases:${repoId}`).execute();
167 assertTelegramContract(list);
53 - assert.ok(callbacks(list).includes(`releasedetail:${repoId}:9`), 'release list must expose detail drill-down');
54 - const detail = await plugin.resolveCallback(`releasedetail:${repoId}:9`).execute();
168 + assert.ok(
169 + callbacks(list).includes(`releasedetail:${repoId}:9`),
170 + 'release list must expose detail drill-down'
171 + );
172 + const detail = await plugin
173 + .resolveCallback(`releasedetail:${repoId}:9`)
174 + .execute();
175 assertTelegramContract(detail);
176 assert.match(detail.text, /Production release notes/);
177 assert.ok(callbacks(detail).includes(`releases:${repoId}`));
@@ -60,14 +180,27 @@ test('release list drills into source-backed release notes and preserves recover
180 test('repository report views always retain a project recovery route', async () => {
181 const emptyGithub = {
182 ...github,
63 - async listCommits() { return []; },
64 - async listIssuesPage() { return { items: [], hasMore: false }; },
65 - async listReleases() { return []; }
183 + async listCommits() {
184 + return [];
185 + },
186 + async listIssuesPage() {
187 + return { items: [], hasMore: false };
188 + },
189 + async listReleases() {
190 + return [];
191 + }
192 };
193 const plugin = createGitHubPlugin({ github: emptyGithub, menu, workspaces });
68 - for (const callback of [`commits:${repoId}`, `issues:${repoId}`, `releases:${repoId}`]) {
194 + for (const callback of [
195 + `commits:${repoId}`,
196 + `issues:${repoId}`,
197 + `releases:${repoId}`
198 + ]) {
199 const view = await plugin.resolveCallback(callback).execute();
200 assertTelegramContract(view);
71 - assert.ok(callbacks(view).includes(`repo:${repoId}`), `${callback} must retain project recovery`);
201 + assert.ok(
202 + callbacks(view).includes(`repo:${repoId}`),
203 + `${callback} must retain project recovery`
204 + );
205 }
73 -});
\ No newline at end of file
206 +});
test/telegram-persistent-menu-input.test.js
+23 -11
@@ -12,19 +12,20 @@ test('/start installs a persistent bottom quick menu and still sends the inline
12 return { ok: true, result: { message_id: 100 + sent.length } };
13 };
14
15 - const result = await bot.handleMessage({ chat: { id: 7 }, from: { id: 42 }, text: '/start' });
15 + const result = await bot.handleMessage({
16 + chat: { id: 7 },
17 + from: { id: 42 },
18 + text: '/start'
19 + });
20
21 assert.equal(result.ok, true);
22 assert.equal(sent.length, 2);
23 assert.equal(sent[0].replyMarkup.is_persistent, true);
24 assert.equal(sent[0].replyMarkup.resize_keyboard, true);
21 - assert.deepEqual(sent[0].replyMarkup.keyboard.flat().map(button => button.text), [
22 - '🏠 منوی اصلی',
23 - '📁 پروژه‌ها',
24 - '📊 وضعیت',
25 - '🔧 ابزارها',
26 - '🔐 امنیت'
27 - ]);
25 + assert.deepEqual(
26 + sent[0].replyMarkup.keyboard.flat().map((button) => button.text),
27 + ['🏠 منوی اصلی', '📁 پروژه‌ها', '📊 وضعیت', '🔧 ابزارها', '🔐 امنیت']
28 + );
29 assert.ok(sent[1].replyMarkup.inline_keyboard);
30 });
31
@@ -44,7 +45,10 @@ test('persistent menu text has precedence over pending draft input', async () =>
45 bot.router = {
46 async dispatchMessage() {
47 workspaceDispatches += 1;
47 - return { text: 'should not happen', reply_markup: { inline_keyboard: [] } };
48 + return {
49 + text: 'should not happen',
50 + reply_markup: { inline_keyboard: [] }
51 + };
52 }
53 };
54 bot.telegram.sendMessage = async (chatId, text, replyMarkup) => {
@@ -52,7 +56,11 @@ test('persistent menu text has precedence over pending draft input', async () =>
56 return { ok: true };
57 };
58
55 - const result = await bot.handleMessage({ chat: { id: 7 }, from: { id: 42 }, text: '🏠 منوی اصلی' });
59 + const result = await bot.handleMessage({
60 + chat: { id: 7 },
61 + from: { id: 42 },
62 + text: '🏠 منوی اصلی'
63 + });
64
65 assert.equal(result.ok, true);
66 assert.equal(result.quickMenu, 'main');
@@ -79,7 +87,11 @@ test('Paste text opens a focused ForceReply prompt without replacing the workspa
87 assert.equal(data, `wtext:${WORKSPACE_ID}`);
88 return {
89 text: '📝 متن جدید Draft را ارسال کنید',
82 - reply_markup: { inline_keyboard: [[{ text: '↩️ بازگشت', callback_data: `ws:${WORKSPACE_ID}` }]] }
90 + reply_markup: {
91 + inline_keyboard: [
92 + [{ text: '↩️ بازگشت', callback_data: `ws:${WORKSPACE_ID}` }]
93 + ]
94 + }
95 };
96 };
97
test/telegram.test.js
+23 -13
@@ -13,10 +13,11 @@ test('TelegramClient fails closed when TELEGRAM_BOT_TOKEN is missing', async ()
13
14 test('TelegramClient rejects HTTP-level Telegram API failures', async () => {
15 const client = new TelegramClient('token', {
16 - fetch: async () => new Response(JSON.stringify({ ok: false, description: 'Bad Request' }), {
17 - status: 400,
18 - headers: { 'content-type': 'application/json' }
19 - })
16 + fetch: async () =>
17 + new Response(JSON.stringify({ ok: false, description: 'Bad Request' }), {
18 + status: 400,
19 + headers: { 'content-type': 'application/json' }
20 + })
21 });
22
23 await assert.rejects(
@@ -27,10 +28,14 @@ test('TelegramClient rejects HTTP-level Telegram API failures', async () => {
28
29 test('TelegramClient rejects Telegram ok:false responses even with HTTP 200', async () => {
30 const client = new TelegramClient('token', {
30 - fetch: async () => new Response(JSON.stringify({ ok: false, description: 'message is not modified' }), {
31 - status: 200,
32 - headers: { 'content-type': 'application/json' }
33 - })
31 + fetch: async () =>
32 + new Response(
33 + JSON.stringify({ ok: false, description: 'message is not modified' }),
34 + {
35 + status: 200,
36 + headers: { 'content-type': 'application/json' }
37 + }
38 + )
39 });
40
41 await assert.rejects(
@@ -46,12 +51,17 @@ test('TelegramClient invokes the default fetch without a TelegramClient receiver
51 globalThis.fetch = async function () {
52 observedThis = this;
53 if (this instanceof TelegramClient) {
49 - throw new TypeError('Illegal invocation: function called with incorrect this reference');
54 + throw new TypeError(
55 + 'Illegal invocation: function called with incorrect this reference'
56 + );
57 }
51 - return new Response(JSON.stringify({ ok: true, result: { message_id: 1 } }), {
52 - status: 200,
53 - headers: { 'content-type': 'application/json' }
54 - });
58 + return new Response(
59 + JSON.stringify({ ok: true, result: { message_id: 1 } }),
60 + {
61 + status: 200,
62 + headers: { 'content-type': 'application/json' }
63 + }
64 + );
65 };
66
67 try {
test/workspace-approved-recovery.test.js
+26 -7
@@ -15,7 +15,10 @@ const payload = {
15 input: { repoId: REPO_ID, intentId: INTENT_ID }
16 };
17
18 -const callbacksOf = view => view.reply_markup.inline_keyboard.flat().map(button => button.callback_data);
18 +const callbacksOf = (view) =>
19 + view.reply_markup.inline_keyboard
20 + .flat()
21 + .map((button) => button.callback_data);
22
23 function workspaceStore() {
24 return {
@@ -30,7 +33,9 @@ function workspaceStore() {
33 test('approved workspace provider failure offers fresh Ready, Draft, Project and Main recovery', async () => {
34 const view = await buildApprovedActionFailedView({
35 payload,
33 - error: new Error('GitHub create ref failed: 403 Resource not accessible by personal access token'),
36 + error: new Error(
37 + 'GitHub create ref failed: 403 Resource not accessible by personal access token'
38 + ),
39 ownerId: OWNER,
40 workspaces: workspaceStore()
41 });
@@ -43,14 +48,26 @@ test('approved workspace provider failure offers fresh Ready, Draft, Project and
48 });
49
50 test('bot uses durable intent context when approved workspace provider execution fails', async () => {
46 - const bot = new NexaDevBot({ TELEGRAM_WEBHOOK_SECRET: 'approved-recovery-test' });
47 - bot.approvals = { async consume() { return payload; } };
51 + const bot = new NexaDevBot({
52 + TELEGRAM_WEBHOOK_SECRET: 'approved-recovery-test'
53 + });
54 + bot.approvals = {
55 + async consume() {
56 + return payload;
57 + }
58 + };
59 bot.workspaceStore = workspaceStore();
49 - bot.router = { async dispatchCallback() { throw new Error('temporary GitHub provider failure'); } };
60 + bot.router = {
61 + async dispatchCallback() {
62 + throw new Error('temporary GitHub provider failure');
63 + }
64 + };
65
66 const edits = [];
67 bot.telegram = {
53 - async answerCallbackQuery() { return { ok: true }; },
68 + async answerCallbackQuery() {
69 + return { ok: true };
70 + },
71 async editMessageText(chatId, messageId, text, replyMarkup) {
72 edits.push({ chatId, messageId, text, replyMarkup });
73 return { ok: true };
@@ -67,7 +84,9 @@ test('bot uses durable intent context when approved workspace provider execution
84 assert.equal(result.ok, false);
85 assert.equal(result.approved, true);
86 assert.equal(edits.length, 1);
70 - const callbacks = edits[0].replyMarkup.inline_keyboard.flat().map(button => button.callback_data);
87 + const callbacks = edits[0].replyMarkup.inline_keyboard
88 + .flat()
89 + .map((button) => button.callback_data);
90 assert.ok(callbacks.includes(`wready:${WORKSPACE_ID}`));
91 assert.ok(callbacks.includes(`ws:${WORKSPACE_ID}`));
92 assert.ok(callbacks.includes(`repo:${REPO_ID}`));
test/workspace-editor-dom-safety.test.js
+106 -34
@@ -8,15 +8,29 @@ function element(tagName) {
8 const listeners = new Map();
9 let value;
10 return {
11 - children: [], textContent: '', className: '', disabled: true,
11 + children: [],
12 + textContent: '',
13 + className: '',
14 + disabled: true,
15 get value() {
13 - if (tagName === 'select') return this.children.find(option => option.value === value)?.value || '';
16 + if (tagName === 'select')
17 + return (
18 + this.children.find((option) => option.value === value)?.value || ''
19 + );
20 return value ?? (tagName === 'option' ? this.textContent : '');
21 },
16 - set value(next) { value = String(next); },
17 - replaceChildren(...children) { this.children = children; },
18 - appendChild(child) { this.children.push(child); },
19 - addEventListener(type, listener) { listeners.set(type, listener); },
22 + set value(next) {
23 + value = String(next);
24 + },
25 + replaceChildren(...children) {
26 + this.children = children;
27 + },
28 + appendChild(child) {
29 + this.children.push(child);
30 + },
31 + addEventListener(type, listener) {
32 + listeners.set(type, listener);
33 + },
34 async dispatch(type) {
35 assert.ok(listeners.has(type), `missing ${type} listener`);
36 await listeners.get(type)();
@@ -25,31 +39,55 @@ function element(tagName) {
39 }
40
41 async function bootEditor(workspace, search = '?workspaceId=W000000001') {
28 - const elements = Object.fromEntries(['editor', 'status', 'path', 'files', 'counter', 'save', 'close']
29 - .map(id => [id, element(id === 'files' ? 'select' : id)]));
42 + const elements = Object.fromEntries(
43 + ['editor', 'status', 'path', 'files', 'counter', 'save', 'close'].map(
44 + (id) => [id, element(id === 'files' ? 'select' : id)]
45 + )
46 + );
47 const requests = [];
48 const location = { search };
49 // Both load success and failure display status. Await that observable completion,
50 // rather than sleeping or guessing how many promise microtasks need draining.
51 let displayStatus;
35 - const loaded = new Promise(resolve => { displayStatus = resolve; });
52 + const loaded = new Promise((resolve) => {
53 + displayStatus = resolve;
54 + });
55 let statusClassName = '';
56 Object.defineProperty(elements.status, 'className', {
57 get: () => statusClassName,
39 - set(value) { statusClassName = value; displayStatus(); }
58 + set(value) {
59 + statusClassName = value;
60 + displayStatus();
61 + }
62 });
41 - const script = renderWorkspaceEditorPage().match(/<script>\s*([\s\S]*?)<\/script>/)[1];
63 + const script = renderWorkspaceEditorPage().match(
64 + /<script>\s*([\s\S]*?)<\/script>/
65 + )[1];
66 vm.runInNewContext(script, {
43 - document: { getElementById: id => elements[id], createElement: element },
44 - window: { Telegram: { WebApp: { initData: 'signed telegram data', ready() {}, expand() {} } } },
45 - location, URLSearchParams, TextEncoder,
67 + document: { getElementById: (id) => elements[id], createElement: element },
68 + window: {
69 + Telegram: {
70 + WebApp: { initData: 'signed telegram data', ready() {}, expand() {} }
71 + }
72 + },
73 + location,
74 + URLSearchParams,
75 + TextEncoder,
76 async fetch(url, options) {
77 requests.push({ url, ...JSON.parse(JSON.stringify(options)) });
78 return {
49 - ok: true, status: 200,
79 + ok: true,
80 + status: 200,
81 async json() {
82 return options.method === 'PUT'
52 - ? { ok: true, workspace: { id: 'W000000001', path: workspace.path, state: 'DRAFT' } }
83 + ? {
84 + ok: true,
85 + workspace: {
86 + id: 'W000000001',
87 + path: workspace.path,
88 + state: 'DRAFT'
89 + }
90 + }
91 : { workspace, limits: { maxChars: 20000, maxBytes: 65536 } };
92 }
93 };
@@ -67,23 +105,37 @@ const markup = 'docs/<img src=x onerror=alert(1)>.md';
105 const unicode = 'docs/راهنما-日本語-🧪.md';
106 const filenames = [quoted, entity, markup, unicode];
107 const workspace = {
70 - id: 'W000000001', path: entity, files: filenames.map(path => ({ path })),
71 - state: 'DRAFT', baseHeadSha: 'abcdef1234', draftText: '# existing draft\n'
108 + id: 'W000000001',
109 + path: entity,
110 + files: filenames.map((path) => ({ path })),
111 + state: 'DRAFT',
112 + baseHeadSha: 'abcdef1234',
113 + draftText: '# existing draft\n'
114 };
115
116 test('editor preserves exact option labels and values for repository-controlled filenames', async () => {
75 - const { elements, requests } = await bootEditor(workspace,
76 - '?workspaceId=W000000001&path=docs%2F%26quot%3B%26amp%3B%26%2339%3B%26%23x3C%3B.md');
117 + const { elements, requests } = await bootEditor(
118 + workspace,
119 + '?workspaceId=W000000001&path=docs%2F%26quot%3B%26amp%3B%26%2339%3B%26%23x3C%3B.md'
120 + );
121 assert.equal(elements.files.children.length, 4);
78 - assert.deepEqual(elements.files.children.map(option => option.textContent), filenames);
79 - assert.deepEqual(elements.files.children.map(option => option.value), filenames);
122 + assert.deepEqual(
123 + elements.files.children.map((option) => option.textContent),
124 + filenames
125 + );
126 + assert.deepEqual(
127 + elements.files.children.map((option) => option.value),
128 + filenames
129 + );
130 assert.equal(elements.files.value, entity);
131 assert.equal(elements.path.textContent, entity);
132 assert.equal(elements.editor.value, '# existing draft\n');
83 - assert.deepEqual(requests, [{
84 - url: '/workspace/api/editor?workspaceId=W000000001&path=docs%2F%26quot%3B%26amp%3B%26%2339%3B%26%23x3C%3B.md',
85 - headers: { 'x-telegram-init-data': 'signed telegram data' }
86 - }]);
133 + assert.deepEqual(requests, [
134 + {
135 + url: '/workspace/api/editor?workspaceId=W000000001&path=docs%2F%26quot%3B%26amp%3B%26%2339%3B%26%23x3C%3B.md',
136 + headers: { 'x-telegram-init-data': 'signed telegram data' }
137 + }
138 + ]);
139 });
140
141 test('saving sends the selected literal filename and draft with Telegram authentication', async () => {
@@ -95,10 +147,13 @@ test('saving sends the selected literal filename and draft with Telegram authent
147 assert.equal(saved.url, '/workspace/api/editor');
148 assert.equal(saved.method, 'PUT');
149 assert.deepEqual(saved.headers, {
98 - 'content-type': 'application/json', 'x-telegram-init-data': 'signed telegram data'
150 + 'content-type': 'application/json',
151 + 'x-telegram-init-data': 'signed telegram data'
152 });
153 assert.deepEqual(JSON.parse(saved.body), {
101 - workspaceId: 'W000000001', path: 'docs/&quot;&amp;&#39;&#x3C;.md', text: '# edited & <literal> 🧪\n'
154 + workspaceId: 'W000000001',
155 + path: 'docs/&quot;&amp;&#39;&#x3C;.md',
156 + text: '# edited & <literal> 🧪\n'
157 });
158 assert.equal(elements.status.className, 'status ok');
159 assert.equal(elements.save.disabled, false);
@@ -106,18 +161,27 @@ test('saving sends the selected literal filename and draft with Telegram authent
161
162 test('legacy workspace without a files array exposes its one literal filename', async () => {
163 const { elements } = await bootEditor({
109 - id: 'W000000001', path: 'legacy/&quot; & "draft".md', state: 'DRAFT',
110 - baseHeadSha: 'abcdef1234', draftText: 'legacy draft'
164 + id: 'W000000001',
165 + path: 'legacy/&quot; & "draft".md',
166 + state: 'DRAFT',
167 + baseHeadSha: 'abcdef1234',
168 + draftText: 'legacy draft'
169 });
170 assert.equal(elements.files.children.length, 1);
113 - assert.equal(elements.files.children[0].textContent, 'legacy/&quot; & "draft".md');
171 + assert.equal(
172 + elements.files.children[0].textContent,
173 + 'legacy/&quot; & "draft".md'
174 + );
175 assert.equal(elements.files.children[0].value, 'legacy/&quot; & "draft".md');
176 assert.equal(elements.files.value, 'legacy/&quot; & "draft".md');
177 assert.equal(elements.editor.value, 'legacy draft');
178 });
179
180 test('changing files preserves special filenames through navigation and the next load', async () => {
120 - const first = await bootEditor(workspace, '?workspaceId=W000000001&source=telegram');
181 + const first = await bootEditor(
182 + workspace,
183 + '?workspaceId=W000000001&source=telegram'
184 + );
185 for (const filename of filenames) {
186 first.elements.files.value = filename;
187 await first.elements.files.dispatch('change');
@@ -125,8 +189,16 @@ test('changing files preserves special filenames through navigation and the next
189 assert.equal(params.get('path'), filename);
190 assert.equal(params.get('workspaceId'), 'W000000001');
191 assert.equal(params.get('source'), 'telegram');
128 - const next = await bootEditor({ ...workspace, path: filename }, first.location.search);
129 - assert.equal(new URL(next.requests[0].url, 'https://example.test').searchParams.get('path'), filename);
192 + const next = await bootEditor(
193 + { ...workspace, path: filename },
194 + first.location.search
195 + );
196 + assert.equal(
197 + new URL(next.requests[0].url, 'https://example.test').searchParams.get(
198 + 'path'
199 + ),
200 + filename
201 + );
202 assert.equal(next.elements.files.value, filename);
203 assert.equal(next.elements.path.textContent, filename);
204 }
test/workspace-editor-v2.test.js
+92 -36
@@ -29,10 +29,13 @@ async function hmacSha256(keyBytes, value) {
29 false,
30 ['sign']
31 );
32 - return new Uint8Array(await crypto.subtle.sign('HMAC', key, encoder.encode(value)));
32 + return new Uint8Array(
33 + await crypto.subtle.sign('HMAC', key, encoder.encode(value))
34 + );
35 }
36
35 -const hex = bytes => Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');
37 +const hex = (bytes) =>
38 + Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
39
40 async function signedInitData({ botToken, userId, authDate }) {
41 const fields = new URLSearchParams({
@@ -55,11 +58,18 @@ test('README-sized Markdown is editable while the expanded editor ceiling remain
58 const accepted = validateEditableFile({ path: 'README.md', text: readme });
59 assert.equal(accepted.editable, true, accepted.reason);
60
58 - const tooManyChars = validateEditableFile({ path: 'README.md', text: 'x'.repeat(20001) });
61 + const tooManyChars = validateEditableFile({
62 + path: 'README.md',
63 + text: 'x'.repeat(20001)
64 + });
65 assert.equal(tooManyChars.editable, false);
66 assert.match(tooManyChars.reason, /20,000|20000/);
67
62 - const tooManyBytes = validateEditableFile({ path: 'README.md', text: 'ok', byteLength: 65537 });
68 + const tooManyBytes = validateEditableFile({
69 + path: 'README.md',
70 + text: 'ok',
71 + byteLength: 65537
72 + });
73 assert.equal(tooManyBytes.editable, false);
74 assert.match(tooManyBytes.reason, /65,536|65536/);
75 });
@@ -84,21 +94,37 @@ test('Workspace view exposes a real Telegram Web App editor instead of primary F
94 workspaces,
95 editorUrl: 'https://example.com/workspace/editor'
96 });
87 - const view = await controller.resolveCallback('ws:W000000001', { ownerId: '42' }).execute();
97 + const view = await controller
98 + .resolveCallback('ws:W000000001', { ownerId: '42' })
99 + .execute();
100 const buttons = view.reply_markup.inline_keyboard.flat();
89 - const editor = buttons.find(button => button.web_app?.url);
101 + const editor = buttons.find((button) => button.web_app?.url);
102 assert.ok(editor, 'Workspace must include a web_app editor button');
91 - assert.equal(editor.web_app.url, 'https://example.com/workspace/editor?workspaceId=W000000001');
103 + assert.equal(
104 + editor.web_app.url,
105 + 'https://example.com/workspace/editor?workspaceId=W000000001'
106 + );
107 assert.doesNotMatch(editor.text, /Paste/i);
93 - assert.equal(buttons.some(button => button.callback_data === 'wtext:W000000001'), false);
108 + assert.equal(
109 + buttons.some((button) => button.callback_data === 'wtext:W000000001'),
110 + false
111 + );
112 });
113
114 test('Telegram Mini App initData validation is owner-bound, tamper-resistant and freshness-bounded', async () => {
115 const auth = await loadWebAppAuth();
98 - assert.equal(typeof auth.validateTelegramWebAppInitData, 'function', 'Mini App auth helper must exist');
116 + assert.equal(
117 + typeof auth.validateTelegramWebAppInitData,
118 + 'function',
119 + 'Mini App auth helper must exist'
120 + );
121 const botToken = '123456:TEST_ONLY_TOKEN';
122 const nowSeconds = 1_800_000_000;
101 - const initData = await signedInitData({ botToken, userId: 42, authDate: nowSeconds - 30 });
123 + const initData = await signedInitData({
124 + botToken,
125 + userId: 42,
126 + authDate: nowSeconds - 30
127 + });
128
129 const valid = await auth.validateTelegramWebAppInitData(initData, {
130 botToken,
@@ -110,45 +136,67 @@ test('Telegram Mini App initData validation is owner-bound, tamper-resistant and
136 assert.equal(valid.authDate, nowSeconds - 30);
137
138 await assert.rejects(
113 - () => auth.validateTelegramWebAppInitData(initData.replace('Owner', 'Intruder'), {
114 - botToken,
115 - ownerId: '42',
116 - now: () => nowSeconds * 1000,
117 - maxAgeSeconds: 3600
118 - }),
139 + () =>
140 + auth.validateTelegramWebAppInitData(
141 + initData.replace('Owner', 'Intruder'),
142 + {
143 + botToken,
144 + ownerId: '42',
145 + now: () => nowSeconds * 1000,
146 + maxAgeSeconds: 3600
147 + }
148 + ),
149 /signature|hash|invalid/i
150 );
151
152 await assert.rejects(
123 - () => auth.validateTelegramWebAppInitData(initData, {
124 - botToken,
125 - ownerId: '99',
126 - now: () => nowSeconds * 1000,
127 - maxAgeSeconds: 3600
128 - }),
153 + () =>
154 + auth.validateTelegramWebAppInitData(initData, {
155 + botToken,
156 + ownerId: '99',
157 + now: () => nowSeconds * 1000,
158 + maxAgeSeconds: 3600
159 + }),
160 /owner|forbidden/i
161 );
162
132 - const stale = await signedInitData({ botToken, userId: 42, authDate: nowSeconds - 7200 });
163 + const stale = await signedInitData({
164 + botToken,
165 + userId: 42,
166 + authDate: nowSeconds - 7200
167 + });
168 await assert.rejects(
134 - () => auth.validateTelegramWebAppInitData(stale, {
135 - botToken,
136 - ownerId: '42',
137 - now: () => nowSeconds * 1000,
138 - maxAgeSeconds: 3600
139 - }),
169 + () =>
170 + auth.validateTelegramWebAppInitData(stale, {
171 + botToken,
172 + ownerId: '42',
173 + now: () => nowSeconds * 1000,
174 + maxAgeSeconds: 3600
175 + }),
176 /expired|stale|auth_date/i
177 );
178 });
179
180 test('Workspace editor HTTP handler loads and saves only the durable draft and never performs a provider write', async () => {
181 const editorModule = await loadWorkspaceEditor();
146 - assert.equal(typeof editorModule.handleWorkspaceEditorRequest, 'function', 'Workspace editor HTTP handler must exist');
147 - assert.equal(typeof editorModule.renderWorkspaceEditorPage, 'function', 'Workspace editor page renderer must exist');
182 + assert.equal(
183 + typeof editorModule.handleWorkspaceEditorRequest,
184 + 'function',
185 + 'Workspace editor HTTP handler must exist'
186 + );
187 + assert.equal(
188 + typeof editorModule.renderWorkspaceEditorPage,
189 + 'function',
190 + 'Workspace editor page renderer must exist'
191 + );
192
193 const botToken = '123456:TEST_ONLY_TOKEN';
194 const nowSeconds = 1_800_000_000;
151 - const initData = await signedInitData({ botToken, userId: 42, authDate: nowSeconds - 10 });
195 + const initData = await signedInitData({
196 + botToken,
197 + userId: 42,
198 + authDate: nowSeconds - 10
199 + });
200 const calls = [];
201 const workspaces = {
202 async getWorkspace({ ownerId, workspaceId }) {
@@ -163,7 +211,12 @@ test('Workspace editor HTTP handler loads and saves only the durable draft and n
211 },
212 async updateDraft({ ownerId, workspaceId, text, digest }) {
213 calls.push(['updateDraft', ownerId, workspaceId, text, digest]);
166 - return { id: workspaceId, path: 'README.md', state: 'DRAFT', draftText: text };
214 + return {
215 + id: workspaceId,
216 + path: 'README.md',
217 + state: 'DRAFT',
218 + draftText: text
219 + };
220 }
221 };
222 const context = {
@@ -175,7 +228,10 @@ test('Workspace editor HTTP handler loads and saves only the durable draft and n
228 const headers = { 'x-telegram-init-data': initData };
229
230 const getResponse = await editorModule.handleWorkspaceEditorRequest(
178 - new Request('https://example.com/workspace/api/editor?workspaceId=W000000001', { headers }),
231 + new Request(
232 + 'https://example.com/workspace/api/editor?workspaceId=W000000001',
233 + { headers }
234 + ),
235 context
236 );
237 assert.equal(getResponse.status, 200);
@@ -193,8 +249,8 @@ test('Workspace editor HTTP handler loads and saves only the durable draft and n
249 context
250 );
251 assert.equal(putResponse.status, 200);
196 - assert.equal(calls.filter(call => call[0] === 'updateDraft').length, 1);
197 - assert.equal(calls.find(call => call[0] === 'updateDraft')[3], '# new\n');
252 + assert.equal(calls.filter((call) => call[0] === 'updateDraft').length, 1);
253 + assert.equal(calls.find((call) => call[0] === 'updateDraft')[3], '# new\n');
254
255 const html = editorModule.renderWorkspaceEditorPage();
256 assert.match(html, /<textarea/i);
test/workspace-editor-worker.test.js
+8 -2
@@ -3,7 +3,11 @@ import assert from 'node:assert/strict';
3 import worker from '../src/index.js';
4
5 test('Worker serves Workspace Mini App with no-store and a restrictive CSP', async () => {
6 - const response = await worker.fetch(new Request('https://example.com/workspace/editor'), {}, {});
6 + const response = await worker.fetch(
7 + new Request('https://example.com/workspace/editor'),
8 + {},
9 + {}
10 + );
11 assert.equal(response.status, 200);
12 assert.match(response.headers.get('content-type') || '', /text\/html/i);
13 assert.equal(response.headers.get('cache-control'), 'no-store');
@@ -18,7 +22,9 @@ test('Worker serves Workspace Mini App with no-store and a restrictive CSP', asy
22
23 test('Worker editor API rejects requests that do not carry valid Telegram initData', async () => {
24 const response = await worker.fetch(
21 - new Request('https://example.com/workspace/api/editor?workspaceId=W000000001'),
25 + new Request(
26 + 'https://example.com/workspace/api/editor?workspaceId=W000000001'
27 + ),
28 { TELEGRAM_BOT_TOKEN: '123456:TEST_ONLY_TOKEN', OWNER_TELEGRAM_ID: '42' },
29 {}
30 );
test/workspace-multifile-commit.test.js
+88 -19
@@ -2,25 +2,94 @@ import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import { commitWorkspaceIntent } from '../src/plugins/github/workspace-commit.js';
4
5 -const sha = c => c.repeat(40);
5 +const sha = (c) => c.repeat(40);
6
7 test('approved multi-file intent creates one blob per file and one atomic tree/commit', async () => {
8 - const calls=[];
9 - const workspace={id:'AbCdEf1234',repoId:7,baseBranch:'main',baseHeadSha:sha('a'),baseTreeSha:sha('b'),commitMessage:'feat: multi',commitMessageDigest:'m',currentIntentId:'AbCd1234',files:[
10 - {path:'a.txt',blobSha:sha('c'),draftText:'A2',draftDigest:'d1'},
11 - {path:'b.txt',blobSha:sha('d'),draftText:'B2',draftDigest:'d2'}
12 - ]};
13 - const intent={id:'AbCd1234',workspaceId:workspace.id,repoId:7,state:'READY',baseBranch:'main',baseHeadSha:sha('a'),baseTreeSha:sha('b'),commitMessageDigest:'m',targetBranch:'nexa/edit-AbCdEf1234',commitTimestamp:'2026-10-05T00:00:00.000Z',files:[
14 - {path:'a.txt',sourceBlobSha:sha('c'),contentDigest:'d1'},
15 - {path:'b.txt',sourceBlobSha:sha('d'),contentDigest:'d2'}
16 - ]};
17 - const workspaces={async getIntent(){return intent},async getWorkspace(){return workspace},async beginCommit(){return{disposition:'start',intent}},async setCandidateCommit(){},async completeCommit(){},async markStale(){}};
18 - const github={async getBranchSnapshot(){return{headSha:sha('a')}},async getGitRef(){return null},async createGitBlob(_r,text){calls.push(['blob',text]);return{sha:text==='A2'?sha('e'):sha('f')}},async createGitTree(_r,input){calls.push(['tree',input]);return{sha:sha('1')}},async createGitCommit(_r,input){calls.push(['commit',input]);return{sha:sha('2')}},async createGitBranchRef(_r,input){calls.push(['ref',input])}};
19 - const result=await commitWorkspaceIntent({github,workspaces,ownerId:'42',repoId:7,intentId:'AbCd1234'});
20 - assert.equal(result.commitSha,sha('2'));
21 - assert.deepEqual(calls.filter(c=>c[0]==='blob').map(c=>c[1]),['A2','B2']);
22 - const tree=calls.find(c=>c[0]==='tree')[1];
23 - assert.deepEqual(tree.entries.map(e=>e.path),['a.txt','b.txt']);
24 - assert.equal(calls.filter(c=>c[0]==='tree').length,1);
25 - assert.equal(calls.filter(c=>c[0]==='commit').length,1);
8 + const calls = [];
9 + const workspace = {
10 + id: 'AbCdEf1234',
11 + repoId: 7,
12 + baseBranch: 'main',
13 + baseHeadSha: sha('a'),
14 + baseTreeSha: sha('b'),
15 + commitMessage: 'feat: multi',
16 + commitMessageDigest: 'm',
17 + currentIntentId: 'AbCd1234',
18 + files: [
19 + { path: 'a.txt', blobSha: sha('c'), draftText: 'A2', draftDigest: 'd1' },
20 + { path: 'b.txt', blobSha: sha('d'), draftText: 'B2', draftDigest: 'd2' }
21 + ]
22 + };
23 + const intent = {
24 + id: 'AbCd1234',
25 + workspaceId: workspace.id,
26 + repoId: 7,
27 + state: 'READY',
28 + baseBranch: 'main',
29 + baseHeadSha: sha('a'),
30 + baseTreeSha: sha('b'),
31 + commitMessageDigest: 'm',
32 + targetBranch: 'nexa/edit-AbCdEf1234',
33 + commitTimestamp: '2026-10-05T00:00:00.000Z',
34 + files: [
35 + { path: 'a.txt', sourceBlobSha: sha('c'), contentDigest: 'd1' },
36 + { path: 'b.txt', sourceBlobSha: sha('d'), contentDigest: 'd2' }
37 + ]
38 + };
39 + const workspaces = {
40 + async getIntent() {
41 + return intent;
42 + },
43 + async getWorkspace() {
44 + return workspace;
45 + },
46 + async beginCommit() {
47 + return { disposition: 'start', intent };
48 + },
49 + async setCandidateCommit() {},
50 + async completeCommit() {},
51 + async markStale() {}
52 + };
53 + const github = {
54 + async getBranchSnapshot() {
55 + return { headSha: sha('a') };
56 + },
57 + async getGitRef() {
58 + return null;
59 + },
60 + async createGitBlob(_r, text) {
61 + calls.push(['blob', text]);
62 + return { sha: text === 'A2' ? sha('e') : sha('f') };
63 + },
64 + async createGitTree(_r, input) {
65 + calls.push(['tree', input]);
66 + return { sha: sha('1') };
67 + },
68 + async createGitCommit(_r, input) {
69 + calls.push(['commit', input]);
70 + return { sha: sha('2') };
71 + },
72 + async createGitBranchRef(_r, input) {
73 + calls.push(['ref', input]);
74 + }
75 + };
76 + const result = await commitWorkspaceIntent({
77 + github,
78 + workspaces,
79 + ownerId: '42',
80 + repoId: 7,
81 + intentId: 'AbCd1234'
82 + });
83 + assert.equal(result.commitSha, sha('2'));
84 + assert.deepEqual(
85 + calls.filter((c) => c[0] === 'blob').map((c) => c[1]),
86 + ['A2', 'B2']
87 + );
88 + const tree = calls.find((c) => c[0] === 'tree')[1];
89 + assert.deepEqual(
90 + tree.entries.map((e) => e.path),
91 + ['a.txt', 'b.txt']
92 + );
93 + assert.equal(calls.filter((c) => c[0] === 'tree').length, 1);
94 + assert.equal(calls.filter((c) => c[0] === 'commit').length, 1);
95 });
test/workspace-multifile.test.js
+126 -18
@@ -5,18 +5,60 @@ import { DurableWorkspaceStoreClient } from '../src/core/workspace-store.js';
5
6 function makeState() {
7 const data = new Map();
8 - const api = { async get(k){return data.get(k)}, async put(k,v){data.set(k, structuredClone(v))}, async delete(k){return data.delete(k)}, async list(){return new Map(data)} };
9 - return { storage: { ...api, async transaction(fn){return fn(api)}, async setAlarm(){} } };
8 + const api = {
9 + async get(k) {
10 + return data.get(k);
11 + },
12 + async put(k, v) {
13 + data.set(k, structuredClone(v));
14 + },
15 + async delete(k) {
16 + return data.delete(k);
17 + },
18 + async list() {
19 + return new Map(data);
20 + }
21 + };
22 + return {
23 + storage: {
24 + ...api,
25 + async transaction(fn) {
26 + return fn(api);
27 + },
28 + async setAlarm() {}
29 + }
30 + };
31 }
32 function makeNamespace() {
33 const states = new Map();
13 - return { idFromName:n=>String(n), get(id){ if(!states.has(id)) states.set(id,makeState()); const store=new WorkspaceStore(states.get(id)); return {fetch:r=>store.fetch(r)}; } };
34 + return {
35 + idFromName: (n) => String(n),
36 + get(id) {
37 + if (!states.has(id)) states.set(id, makeState());
38 + const store = new WorkspaceStore(states.get(id));
39 + return { fetch: (r) => store.fetch(r) };
40 + }
41 + };
42 }
15 -const base = { repoId:1, repoFullName:'davoodmehraban89/nexa-dev-bot', baseBranch:'main', baseHeadSha:'a'.repeat(40), baseTreeSha:'b'.repeat(40), path:'README.md', blobSha:'c'.repeat(40), originalText:'one\n', originalDigest:'d'.repeat(64), expiresAt:999999 };
43 +const base = {
44 + repoId: 1,
45 + repoFullName: 'davoodmehraban89/nexa-dev-bot',
46 + baseBranch: 'main',
47 + baseHeadSha: 'a'.repeat(40),
48 + baseTreeSha: 'b'.repeat(40),
49 + path: 'README.md',
50 + blobSha: 'c'.repeat(40),
51 + originalText: 'one\n',
52 + originalDigest: 'd'.repeat(64),
53 + expiresAt: 999999
54 +};
55
56 test('new workspace exposes versioned files while preserving legacy fields', async () => {
18 - const client = new DurableWorkspaceStoreClient({ namespace:makeNamespace(), now:()=>1000 });
19 - const ws = await client.createWorkspace({ownerId:'A', ...base});
57 + const client = new DurableWorkspaceStoreClient({
58 + namespace: makeNamespace(),
59 + now: () => 1000
60 + });
61 + const ws = await client.createWorkspace({ ownerId: 'A', ...base });
62 assert.equal(ws.schemaVersion, 2);
63 assert.equal(ws.files.length, 1);
64 assert.equal(ws.files[0].path, 'README.md');
@@ -24,20 +66,86 @@ test('new workspace exposes versioned files while preserving legacy fields', asy
66 });
67
68 test('workspace can add update and remove files and material changes invalidate READY intent', async () => {
27 - const client = new DurableWorkspaceStoreClient({ namespace:makeNamespace(), now:()=>1000 });
28 - let ws = await client.createWorkspace({ownerId:'A', ...base});
29 - ws = await client.upsertWorkspaceFile({ownerId:'A', workspaceId:ws.id, file:{path:'src/a.js', blobSha:'e'.repeat(40), originalText:'a\n', originalDigest:'1'.repeat(64), draftText:'b\n', draftDigest:'2'.repeat(64)}});
30 - assert.deepEqual(ws.files.map(f=>f.path), ['README.md','src/a.js']);
69 + const client = new DurableWorkspaceStoreClient({
70 + namespace: makeNamespace(),
71 + now: () => 1000
72 + });
73 + let ws = await client.createWorkspace({ ownerId: 'A', ...base });
74 + ws = await client.upsertWorkspaceFile({
75 + ownerId: 'A',
76 + workspaceId: ws.id,
77 + file: {
78 + path: 'src/a.js',
79 + blobSha: 'e'.repeat(40),
80 + originalText: 'a\n',
81 + originalDigest: '1'.repeat(64),
82 + draftText: 'b\n',
83 + draftDigest: '2'.repeat(64)
84 + }
85 + });
86 + assert.deepEqual(
87 + ws.files.map((f) => f.path),
88 + ['README.md', 'src/a.js']
89 + );
90 assert.equal(ws.currentIntentId, null);
32 - ws = await client.updateWorkspaceFileDraft({ownerId:'A', workspaceId:ws.id, path:'README.md', text:'changed\n', digest:'3'.repeat(64)});
33 - assert.equal(ws.files.find(f=>f.path==='README.md').draftText, 'changed\n');
34 - ws = await client.removeWorkspaceFile({ownerId:'A', workspaceId:ws.id, path:'src/a.js'});
35 - assert.deepEqual(ws.files.map(f=>f.path), ['README.md']);
91 + ws = await client.updateWorkspaceFileDraft({
92 + ownerId: 'A',
93 + workspaceId: ws.id,
94 + path: 'README.md',
95 + text: 'changed\n',
96 + digest: '3'.repeat(64)
97 + });
98 + assert.equal(
99 + ws.files.find((f) => f.path === 'README.md').draftText,
100 + 'changed\n'
101 + );
102 + ws = await client.removeWorkspaceFile({
103 + ownerId: 'A',
104 + workspaceId: ws.id,
105 + path: 'src/a.js'
106 + });
107 + assert.deepEqual(
108 + ws.files.map((f) => f.path),
109 + ['README.md']
110 + );
111 });
112
113 test('workspace rejects duplicate normalized paths and aggregate oversize payloads', async () => {
39 - const client = new DurableWorkspaceStoreClient({ namespace:makeNamespace(), now:()=>1000 });
40 - const ws = await client.createWorkspace({ownerId:'A', ...base});
41 - await assert.rejects(() => client.upsertWorkspaceFile({ownerId:'A', workspaceId:ws.id, file:{path:'README.md', blobSha:'x', originalText:'x', originalDigest:'1', draftText:'x', draftDigest:'2'}}), /already exists|duplicate/i);
42 - await assert.rejects(() => client.upsertWorkspaceFile({ownerId:'A', workspaceId:ws.id, file:{path:'huge.txt', blobSha:'x', originalText:'', originalDigest:'1', draftText:'x'.repeat(262145), draftDigest:'2'}}), /aggregate|large|size/i);
114 + const client = new DurableWorkspaceStoreClient({
115 + namespace: makeNamespace(),
116 + now: () => 1000
117 + });
118 + const ws = await client.createWorkspace({ ownerId: 'A', ...base });
119 + await assert.rejects(
120 + () =>
121 + client.upsertWorkspaceFile({
122 + ownerId: 'A',
123 + workspaceId: ws.id,
124 + file: {
125 + path: 'README.md',
126 + blobSha: 'x',
127 + originalText: 'x',
128 + originalDigest: '1',
129 + draftText: 'x',
130 + draftDigest: '2'
131 + }
132 + }),
133 + /already exists|duplicate/i
134 + );
135 + await assert.rejects(
136 + () =>
137 + client.upsertWorkspaceFile({
138 + ownerId: 'A',
139 + workspaceId: ws.id,
140 + file: {
141 + path: 'huge.txt',
142 + blobSha: 'x',
143 + originalText: '',
144 + originalDigest: '1',
145 + draftText: 'x'.repeat(262145),
146 + draftDigest: '2'
147 + }
148 + }),
149 + /aggregate|large|size/i
150 + );
151 });
test/workspace-policy.test.js
+40 -8
@@ -8,14 +8,17 @@ try {
8 policy = {};
9 }
10
11 -const requireFn = name => {
11 +const requireFn = (name) => {
12 assert.equal(typeof policy[name], 'function', `${name} must be implemented`);
13 return policy[name];
14 };
15
16 test('editable file policy accepts bounded UTF-8 text', () => {
17 const validateEditableFile = requireFn('validateEditableFile');
18 - const result = validateEditableFile({ path: 'src/app.js', text: 'export const ok = true;\n' });
18 + const result = validateEditableFile({
19 + path: 'src/app.js',
20 + text: 'export const ok = true;\n'
21 + });
22 assert.deepEqual(result, {
23 editable: true,
24 reason: '',
@@ -27,7 +30,18 @@ test('editable file policy accepts bounded UTF-8 text', () => {
30
31 test('editable file policy rejects sensitive paths binary markers LFS and both size ceilings', () => {
32 const validateEditableFile = requireFn('validateEditableFile');
30 - for (const path of ['.env', '.env.production', 'keys/id_rsa', 'id_ed25519', 'tls/cert.pem', 'tls/private.key', 'a.p12', 'a.pfx', 'credentials.json', 'service-account-prod.json']) {
33 + for (const path of [
34 + '.env',
35 + '.env.production',
36 + 'keys/id_rsa',
37 + 'id_ed25519',
38 + 'tls/cert.pem',
39 + 'tls/private.key',
40 + 'a.p12',
41 + 'a.pfx',
42 + 'credentials.json',
43 + 'service-account-prod.json'
44 + ]) {
45 const result = validateEditableFile({ path, text: 'safe-looking text' });
46 assert.equal(result.editable, false, path);
47 assert.match(result.reason, /sensitive/i);
@@ -37,15 +51,25 @@ test('editable file policy rejects sensitive paths binary markers LFS and both s
51 assert.equal(binary.editable, false);
52 assert.match(binary.reason, /binary/i);
53
40 - const lfs = validateEditableFile({ path: 'asset.txt', text: 'version https://git-lfs.github.com/spec/v1\noid sha256:abc\nsize 123\n' });
54 + const lfs = validateEditableFile({
55 + path: 'asset.txt',
56 + text: 'version https://git-lfs.github.com/spec/v1\noid sha256:abc\nsize 123\n'
57 + });
58 assert.equal(lfs.editable, false);
59 assert.match(lfs.reason, /LFS/i);
60
44 - const tooManyChars = validateEditableFile({ path: 'large.txt', text: 'a'.repeat(20001) });
61 + const tooManyChars = validateEditableFile({
62 + path: 'large.txt',
63 + text: 'a'.repeat(20001)
64 + });
65 assert.equal(tooManyChars.editable, false);
66 assert.match(tooManyChars.reason, /20,000|20000/);
67
48 - const explicitTooManyBytes = validateEditableFile({ path: 'large.txt', text: 'ok', byteLength: 65537 });
68 + const explicitTooManyBytes = validateEditableFile({
69 + path: 'large.txt',
70 + text: 'ok',
71 + byteLength: 65537
72 + });
73 assert.equal(explicitTooManyBytes.editable, false);
74 assert.match(explicitTooManyBytes.reason, /65,536|65536/);
75 });
@@ -70,7 +94,10 @@ test('commit message and target branch normalization fail closed on empty or uns
94 const normalizeCommitMessage = requireFn('normalizeCommitMessage');
95 const makeTargetBranch = requireFn('makeTargetBranch');
96
73 - assert.equal(normalizeCommitMessage(' test: verify mobile editor '), 'test: verify mobile editor');
97 + assert.equal(
98 + normalizeCommitMessage(' test: verify mobile editor '),
99 + 'test: verify mobile editor'
100 + );
101 assert.throws(() => normalizeCommitMessage(' '), /commit message/i);
102 assert.throws(() => normalizeCommitMessage('x'.repeat(121)), /120/);
103
@@ -83,7 +110,12 @@ test('unified diff reports exact additions deletions and marks bounded truncatio
110 const buildUnifiedDiff = requireFn('buildUnifiedDiff');
111 const before = 'alpha\nbeta\ngamma\n';
112 const after = 'alpha\nBETA\ngamma\ndelta\n';
86 - const full = buildUnifiedDiff({ path: 'src/app.js', before, after, maxChars: 2600 });
113 + const full = buildUnifiedDiff({
114 + path: 'src/app.js',
115 + before,
116 + after,
117 + maxChars: 2600
118 + });
119 assert.equal(full.additions, 2);
120 assert.equal(full.deletions, 1);
121 assert.equal(full.truncated, false);
test/workspace-recovery-validation.test.js
+22 -7
@@ -10,8 +10,13 @@ function buttons(markup) {
10 return markup?.inline_keyboard?.flat() || [];
11 }
12
13 -function makeBot({ routerError, workspace = { id: WORKSPACE_ID, repoId: REPO_ID } } = {}) {
14 - const bot = new NexaDevBot({ TELEGRAM_WEBHOOK_SECRET: 'recovery-test-secret' });
13 +function makeBot({
14 + routerError,
15 + workspace = { id: WORKSPACE_ID, repoId: REPO_ID }
16 +} = {}) {
17 + const bot = new NexaDevBot({
18 + TELEGRAM_WEBHOOK_SECRET: 'recovery-test-secret'
19 + });
20 bot.router = {
21 async dispatchCallback() {
22 throw routerError || new Error('temporary provider failure');
@@ -26,7 +31,9 @@ function makeBot({ routerError, workspace = { id: WORKSPACE_ID, repoId: REPO_ID
31 };
32 const edits = [];
33 bot.telegram = {
29 - async answerCallbackQuery() { return { ok: true }; },
34 + async answerCallbackQuery() {
35 + return { ok: true };
36 + },
37 async editMessageText(chatId, messageId, text, replyMarkup) {
38 edits.push({ chatId, messageId, text, replyMarkup });
39 return { ok: true };
@@ -45,7 +52,9 @@ function query(data) {
52 }
53
54 test('ready without a commit message shows explicit validation and preserves workspace recovery actions', async () => {
48 - const { bot, edits } = makeBot({ routerError: new Error('Commit message is required') });
55 + const { bot, edits } = makeBot({
56 + routerError: new Error('Commit message is required')
57 + });
58
59 const result = await bot.handleCallbackQuery(query(`wready:${WORKSPACE_ID}`));
60
@@ -54,7 +63,9 @@ test('ready without a commit message shows explicit validation and preserves wor
63 assert.match(edits[0].text, /پیام Commit/);
64 assert.doesNotMatch(edits[0].text, /دریافت اطلاعات از سرویس/);
65
57 - const callbacks = buttons(edits[0].replyMarkup).map(button => button.callback_data);
66 + const callbacks = buttons(edits[0].replyMarkup).map(
67 + (button) => button.callback_data
68 + );
69 assert.ok(callbacks.includes(`wmsg:${WORKSPACE_ID}`));
70 assert.ok(callbacks.includes(`ws:${WORKSPACE_ID}`));
71 assert.ok(callbacks.includes(`repo:${REPO_ID}`));
@@ -62,13 +73,17 @@ test('ready without a commit message shows explicit validation and preserves wor
73 });
74
75 test('workspace callback failure keeps retry, draft, project and main-menu recovery routes', async () => {
65 - const { bot, edits } = makeBot({ routerError: new Error('temporary provider failure') });
76 + const { bot, edits } = makeBot({
77 + routerError: new Error('temporary provider failure')
78 + });
79
80 const result = await bot.handleCallbackQuery(query(`wdiff:${WORKSPACE_ID}`));
81
82 assert.equal(result.ok, false);
83 assert.equal(edits.length, 1);
71 - const callbacks = buttons(edits[0].replyMarkup).map(button => button.callback_data);
84 + const callbacks = buttons(edits[0].replyMarkup).map(
85 + (button) => button.callback_data
86 + );
87 assert.ok(callbacks.includes(`wdiff:${WORKSPACE_ID}`));
88 assert.ok(callbacks.includes(`ws:${WORKSPACE_ID}`));
89 assert.ok(callbacks.includes(`repo:${REPO_ID}`));
test/workspace-store-file-input.test.js
+37 -11
@@ -6,15 +6,25 @@ import { WorkspaceStore } from '../src/durable/workspace-store.js';
6 function makeState() {
7 const data = new Map();
8 const api = {
9 - async get(key) { return data.get(key); },
10 - async put(key, value) { data.set(key, structuredClone(value)); },
11 - async delete(key) { return data.delete(key); },
12 - async list() { return new Map(data); }
9 + async get(key) {
10 + return data.get(key);
11 + },
12 + async put(key, value) {
13 + data.set(key, structuredClone(value));
14 + },
15 + async delete(key) {
16 + return data.delete(key);
17 + },
18 + async list() {
19 + return new Map(data);
20 + }
21 };
22 return {
23 storage: {
24 ...api,
17 - async transaction(fn) { return fn(api); },
25 + async transaction(fn) {
26 + return fn(api);
27 + },
28 async setAlarm() {}
29 }
30 };
@@ -23,17 +33,22 @@ function makeState() {
33 function makeNamespace() {
34 const states = new Map();
35 return {
26 - idFromName(name) { return String(name); },
36 + idFromName(name) {
37 + return String(name);
38 + },
39 get(id) {
40 if (!states.has(id)) states.set(id, makeState());
41 const store = new WorkspaceStore(states.get(id));
30 - return { fetch: request => store.fetch(request) };
42 + return { fetch: (request) => store.fetch(request) };
43 }
44 };
45 }
46
47 test('durable workspace store accepts draft_file as an owner-scoped pending input mode', async () => {
36 - const client = new DurableWorkspaceStoreClient({ namespace: makeNamespace(), now: () => 1000 });
48 + const client = new DurableWorkspaceStoreClient({
49 + namespace: makeNamespace(),
50 + now: () => 1000
51 + });
52 const workspace = await client.createWorkspace({
53 ownerId: '42',
54 repoId: 123,
@@ -48,10 +63,21 @@ test('durable workspace store accepts draft_file as an owner-scoped pending inpu
63 expiresAt: 1000 + 30 * 60_000
64 });
65
51 - await client.setPendingInput({ ownerId: '42', workspaceId: workspace.id, mode: 'draft_file' });
66 + await client.setPendingInput({
67 + ownerId: '42',
68 + workspaceId: workspace.id,
69 + mode: 'draft_file'
70 + });
71 assert.deepEqual(await client.getPendingInput({ ownerId: '42' }), {
72 workspaceId: workspace.id,
73 mode: 'draft_file'
74 });
56 - assert.equal(await client.consumePendingInput({ ownerId: '42', workspaceId: workspace.id, mode: 'draft_file' }), true);
57 -});
\ No newline at end of file
75 + assert.equal(
76 + await client.consumePendingInput({
77 + ownerId: '42',
78 + workspaceId: workspace.id,
79 + mode: 'draft_file'
80 + }),
81 + true
82 + );
83 +});
test/workspace-store.test.js
+269 -59
@@ -5,9 +5,15 @@ import { readFile } from 'node:fs/promises';
5 let clientModule = {};
6 let durableModule = {};
7 let indexModule = {};
8 -try { clientModule = await import('../src/core/workspace-store.js'); } catch {}
9 -try { durableModule = await import('../src/durable/workspace-store.js'); } catch {}
10 -try { indexModule = await import('../src/index.js'); } catch {}
8 +try {
9 + clientModule = await import('../src/core/workspace-store.js');
10 +} catch {}
11 +try {
12 + durableModule = await import('../src/durable/workspace-store.js');
13 +} catch {}
14 +try {
15 + indexModule = await import('../src/index.js');
16 +} catch {}
17
18 const requireExport = (mod, name) => {
19 assert.equal(typeof mod[name], 'function', `${name} must be implemented`);
@@ -18,19 +24,36 @@ function makeState() {
24 const data = new Map();
25 let alarm = null;
26 const api = {
21 - async get(key) { return data.get(key); },
22 - async put(key, value) { data.set(key, structuredClone(value)); },
23 - async delete(key) { return data.delete(key); },
24 - async list() { return new Map(data); }
27 + async get(key) {
28 + return data.get(key);
29 + },
30 + async put(key, value) {
31 + data.set(key, structuredClone(value));
32 + },
33 + async delete(key) {
34 + return data.delete(key);
35 + },
36 + async list() {
37 + return new Map(data);
38 + }
39 };
40 return {
41 data,
28 - get alarm() { return alarm; },
42 + get alarm() {
43 + return alarm;
44 + },
45 storage: {
46 ...api,
31 - async transaction(fn) { return fn(api); },
32 - async setAlarm(value) { alarm = value; },
33 - async deleteAll() { data.clear(); alarm = null; }
47 + async transaction(fn) {
48 + return fn(api);
49 + },
50 + async setAlarm(value) {
51 + alarm = value;
52 + },
53 + async deleteAll() {
54 + data.clear();
55 + alarm = null;
56 + }
57 }
58 };
59 }
@@ -38,12 +61,14 @@ function makeState() {
61 function makeNamespace(StoreClass, states = new Map()) {
62 return {
63 states,
41 - idFromName(name) { return String(name); },
64 + idFromName(name) {
65 + return String(name);
66 + },
67 get(id) {
68 if (!states.has(id)) states.set(id, makeState());
69 const state = states.get(id);
70 const instance = new StoreClass(state);
46 - return { fetch: request => instance.fetch(request) };
71 + return { fetch: (request) => instance.fetch(request) };
72 }
73 };
74 }
@@ -85,7 +110,10 @@ test('DurableWorkspaceStoreClient fails closed without WORKSPACE_STORE', async (
110 const Client = requireExport(clientModule, 'DurableWorkspaceStoreClient');
111 const client = new Client();
112 assert.equal(client.isConfigured(), false);
88 - await assert.rejects(() => client.getWorkspace({ ownerId: 'owner', workspaceId: 'Ab3_-xYz09' }), /not configured/i);
113 + await assert.rejects(
114 + () => client.getWorkspace({ ownerId: 'owner', workspaceId: 'Ab3_-xYz09' }),
115 + /not configured/i
116 + );
117 });
118
119 test('workspace store isolates refs and workspaces by owner', async () => {
@@ -94,15 +122,37 @@ test('workspace store isolates refs and workspaces by owner', async () => {
122 const namespace = makeNamespace(Store);
123 const client = new Client({ namespace, now: () => 1_000 });
124
97 - const [ref] = await client.createNavigationRefs({ ownerId: 'A', refs: [{ repoId: 123, path: 'src/app.js', type: 'file', sha: 'a'.repeat(40) }] });
125 + const [ref] = await client.createNavigationRefs({
126 + ownerId: 'A',
127 + refs: [
128 + { repoId: 123, path: 'src/app.js', type: 'file', sha: 'a'.repeat(40) }
129 + ]
130 + });
131 assert.match(ref.refId, /^[A-Za-z0-9_-]{10}$/);
99 - assert.equal((await client.resolveNavigationRef({ ownerId: 'A', refId: ref.refId })).path, 'src/app.js');
100 - assert.equal(await client.resolveNavigationRef({ ownerId: 'B', refId: ref.refId }), null);
132 + assert.equal(
133 + (await client.resolveNavigationRef({ ownerId: 'A', refId: ref.refId }))
134 + .path,
135 + 'src/app.js'
136 + );
137 + assert.equal(
138 + await client.resolveNavigationRef({ ownerId: 'B', refId: ref.refId }),
139 + null
140 + );
141
102 - const workspace = await client.createWorkspace({ ownerId: 'A', ...baseWorkspace() });
142 + const workspace = await client.createWorkspace({
143 + ownerId: 'A',
144 + ...baseWorkspace()
145 + });
146 assert.match(workspace.id, /^[A-Za-z0-9_-]{10}$/);
104 - assert.equal((await client.getWorkspace({ ownerId: 'A', workspaceId: workspace.id })).path, 'README.md');
105 - assert.equal(await client.getWorkspace({ ownerId: 'B', workspaceId: workspace.id }), null);
147 + assert.equal(
148 + (await client.getWorkspace({ ownerId: 'A', workspaceId: workspace.id }))
149 + .path,
150 + 'README.md'
151 + );
152 + assert.equal(
153 + await client.getWorkspace({ ownerId: 'B', workspaceId: workspace.id }),
154 + null
155 + );
156 });
157
158 test('workspace navigation refs preserve bounded workspace metadata', async () => {
@@ -111,10 +161,29 @@ test('workspace navigation refs preserve bounded workspace metadata', async () =
161 const namespace = makeNamespace(Store);
162 const client = new Client({ namespace, now: () => 1_000 });
163
114 - const [ref] = await client.createNavigationRefs({ ownerId: 'A', refs: [{ repoId: 1, workspaceId: 'W000000001', path: 'src/a.js', type: 'workspace-add', sha: 'a'.repeat(40) }] });
115 - assert.deepEqual(await client.resolveNavigationRef({ ownerId: 'A', refId: ref.refId }), {
116 - repoId: 1, workspaceId: 'W000000001', path: 'src/a.js', type: 'workspace-add', sha: 'a'.repeat(40), expiresAt: 901000
164 + const [ref] = await client.createNavigationRefs({
165 + ownerId: 'A',
166 + refs: [
167 + {
168 + repoId: 1,
169 + workspaceId: 'W000000001',
170 + path: 'src/a.js',
171 + type: 'workspace-add',
172 + sha: 'a'.repeat(40)
173 + }
174 + ]
175 });
176 + assert.deepEqual(
177 + await client.resolveNavigationRef({ ownerId: 'A', refId: ref.refId }),
178 + {
179 + repoId: 1,
180 + workspaceId: 'W000000001',
181 + path: 'src/a.js',
182 + type: 'workspace-add',
183 + sha: 'a'.repeat(40),
184 + expiresAt: 901000
185 + }
186 + );
187 });
188
189 test('expired refs and workspaces read as missing and schedule cleanup', async () => {
@@ -124,67 +193,184 @@ test('expired refs and workspaces read as missing and schedule cleanup', async (
193 const namespace = makeNamespace(Store);
194 const client = new Client({ namespace, now: () => now });
195
127 - const [ref] = await client.createNavigationRefs({ ownerId: 'A', refs: [{ repoId: 1, path: 'a.txt', type: 'file', sha: 'a'.repeat(40) }], ttlMs: 50 });
128 - const workspace = await client.createWorkspace({ ownerId: 'A', ...baseWorkspace(now), expiresAt: now + 50 });
196 + const [ref] = await client.createNavigationRefs({
197 + ownerId: 'A',
198 + refs: [{ repoId: 1, path: 'a.txt', type: 'file', sha: 'a'.repeat(40) }],
199 + ttlMs: 50
200 + });
201 + const workspace = await client.createWorkspace({
202 + ownerId: 'A',
203 + ...baseWorkspace(now),
204 + expiresAt: now + 50
205 + });
206 now = 1_051;
207
131 - assert.equal(await client.resolveNavigationRef({ ownerId: 'A', refId: ref.refId }), null);
132 - assert.equal(await client.getWorkspace({ ownerId: 'A', workspaceId: workspace.id }), null);
208 + assert.equal(
209 + await client.resolveNavigationRef({ ownerId: 'A', refId: ref.refId }),
210 + null
211 + );
212 + assert.equal(
213 + await client.getWorkspace({ ownerId: 'A', workspaceId: workspace.id }),
214 + null
215 + );
216 assert.ok(namespace.states.get('A').alarm !== null);
217 });
218
219 test('pending workspace input is owner scoped and consumed exactly once', async () => {
220 const Client = requireExport(clientModule, 'DurableWorkspaceStoreClient');
221 const Store = requireExport(durableModule, 'WorkspaceStore');
139 - const client = new Client({ namespace: makeNamespace(Store), now: () => 1_000 });
140 - const workspace = await client.createWorkspace({ ownerId: 'A', ...baseWorkspace() });
222 + const client = new Client({
223 + namespace: makeNamespace(Store),
224 + now: () => 1_000
225 + });
226 + const workspace = await client.createWorkspace({
227 + ownerId: 'A',
228 + ...baseWorkspace()
229 + });
230
142 - await client.setPendingInput({ ownerId: 'A', workspaceId: workspace.id, mode: 'draft' });
143 - assert.deepEqual(await client.getPendingInput({ ownerId: 'A' }), { workspaceId: workspace.id, mode: 'draft' });
231 + await client.setPendingInput({
232 + ownerId: 'A',
233 + workspaceId: workspace.id,
234 + mode: 'draft'
235 + });
236 + assert.deepEqual(await client.getPendingInput({ ownerId: 'A' }), {
237 + workspaceId: workspace.id,
238 + mode: 'draft'
239 + });
240 assert.equal(await client.getPendingInput({ ownerId: 'B' }), null);
145 - assert.equal(await client.consumePendingInput({ ownerId: 'A', workspaceId: workspace.id, mode: 'draft' }), true);
146 - assert.equal(await client.consumePendingInput({ ownerId: 'A', workspaceId: workspace.id, mode: 'draft' }), false);
241 + assert.equal(
242 + await client.consumePendingInput({
243 + ownerId: 'A',
244 + workspaceId: workspace.id,
245 + mode: 'draft'
246 + }),
247 + true
248 + );
249 + assert.equal(
250 + await client.consumePendingInput({
251 + ownerId: 'A',
252 + workspaceId: workspace.id,
253 + mode: 'draft'
254 + }),
255 + false
256 + );
257 });
258
259 test('material draft or message changes invalidate READY intent while identical values reuse it', async () => {
260 const Client = requireExport(clientModule, 'DurableWorkspaceStoreClient');
261 const Store = requireExport(durableModule, 'WorkspaceStore');
152 - const client = new Client({ namespace: makeNamespace(Store), now: () => 1_000 });
153 - let workspace = await client.createWorkspace({ ownerId: 'A', ...baseWorkspace() });
154 - workspace = await client.updateDraft({ ownerId: 'A', workspaceId: workspace.id, text: 'after\n', digest: '1'.repeat(64) });
155 - workspace = await client.setCommitMessage({ ownerId: 'A', workspaceId: workspace.id, message: 'test: edit', digest: '2'.repeat(64) });
262 + const client = new Client({
263 + namespace: makeNamespace(Store),
264 + now: () => 1_000
265 + });
266 + let workspace = await client.createWorkspace({
267 + ownerId: 'A',
268 + ...baseWorkspace()
269 + });
270 + workspace = await client.updateDraft({
271 + ownerId: 'A',
272 + workspaceId: workspace.id,
273 + text: 'after\n',
274 + digest: '1'.repeat(64)
275 + });
276 + workspace = await client.setCommitMessage({
277 + ownerId: 'A',
278 + workspaceId: workspace.id,
279 + message: 'test: edit',
280 + digest: '2'.repeat(64)
281 + });
282
157 - const first = await client.sealIntent({ ownerId: 'A', workspaceId: workspace.id, intent: baseIntent(workspace) });
283 + const first = await client.sealIntent({
284 + ownerId: 'A',
285 + workspaceId: workspace.id,
286 + intent: baseIntent(workspace)
287 + });
288 assert.match(first.id, /^[A-Za-z0-9_-]{8}$/);
159 - const same = await client.sealIntent({ ownerId: 'A', workspaceId: workspace.id, intent: baseIntent(workspace) });
289 + const same = await client.sealIntent({
290 + ownerId: 'A',
291 + workspaceId: workspace.id,
292 + intent: baseIntent(workspace)
293 + });
294 assert.equal(same.id, first.id);
295
162 - await client.updateDraft({ ownerId: 'A', workspaceId: workspace.id, text: 'after\n', digest: '1'.repeat(64) });
163 - assert.equal((await client.getWorkspace({ ownerId: 'A', workspaceId: workspace.id })).currentIntentId, first.id);
296 + await client.updateDraft({
297 + ownerId: 'A',
298 + workspaceId: workspace.id,
299 + text: 'after\n',
300 + digest: '1'.repeat(64)
301 + });
302 + assert.equal(
303 + (await client.getWorkspace({ ownerId: 'A', workspaceId: workspace.id }))
304 + .currentIntentId,
305 + first.id
306 + );
307
165 - await client.updateDraft({ ownerId: 'A', workspaceId: workspace.id, text: 'changed\n', digest: '9'.repeat(64) });
166 - const changed = await client.getWorkspace({ ownerId: 'A', workspaceId: workspace.id });
308 + await client.updateDraft({
309 + ownerId: 'A',
310 + workspaceId: workspace.id,
311 + text: 'changed\n',
312 + digest: '9'.repeat(64)
313 + });
314 + const changed = await client.getWorkspace({
315 + ownerId: 'A',
316 + workspaceId: workspace.id
317 + });
318 assert.equal(changed.currentIntentId, null);
319 assert.equal(changed.state, 'DRAFT');
169 - assert.equal((await client.getIntent({ ownerId: 'A', intentId: first.id })).intentDigest, first.intentDigest);
320 + assert.equal(
321 + (await client.getIntent({ ownerId: 'A', intentId: first.id })).intentDigest,
322 + first.intentDigest
323 + );
324 });
325
326 test('sealed intent is immutable and beginCommit is atomic through COMMITTED result', async () => {
327 const Client = requireExport(clientModule, 'DurableWorkspaceStoreClient');
328 const Store = requireExport(durableModule, 'WorkspaceStore');
175 - const client = new Client({ namespace: makeNamespace(Store), now: () => 1_000 });
176 - let workspace = await client.createWorkspace({ ownerId: 'A', ...baseWorkspace() });
177 - workspace = await client.updateDraft({ ownerId: 'A', workspaceId: workspace.id, text: 'after\n', digest: '1'.repeat(64) });
178 - workspace = await client.setCommitMessage({ ownerId: 'A', workspaceId: workspace.id, message: 'test: edit', digest: '2'.repeat(64) });
179 - const intent = await client.sealIntent({ ownerId: 'A', workspaceId: workspace.id, intent: baseIntent(workspace) });
329 + const client = new Client({
330 + namespace: makeNamespace(Store),
331 + now: () => 1_000
332 + });
333 + let workspace = await client.createWorkspace({
334 + ownerId: 'A',
335 + ...baseWorkspace()
336 + });
337 + workspace = await client.updateDraft({
338 + ownerId: 'A',
339 + workspaceId: workspace.id,
340 + text: 'after\n',
341 + digest: '1'.repeat(64)
342 + });
343 + workspace = await client.setCommitMessage({
344 + ownerId: 'A',
345 + workspaceId: workspace.id,
346 + message: 'test: edit',
347 + digest: '2'.repeat(64)
348 + });
349 + const intent = await client.sealIntent({
350 + ownerId: 'A',
351 + workspaceId: workspace.id,
352 + intent: baseIntent(workspace)
353 + });
354
355 const start = await client.beginCommit({ ownerId: 'A', intentId: intent.id });
356 assert.equal(start.disposition, 'start');
183 - const resume = await client.beginCommit({ ownerId: 'A', intentId: intent.id });
357 + const resume = await client.beginCommit({
358 + ownerId: 'A',
359 + intentId: intent.id
360 + });
361 assert.equal(resume.disposition, 'resume');
362
186 - await client.setCandidateCommit({ ownerId: 'A', intentId: intent.id, commitSha: 'e'.repeat(40) });
187 - const completed = await client.completeCommit({ ownerId: 'A', intentId: intent.id, commitSha: 'e'.repeat(40), branch: intent.targetBranch });
363 + await client.setCandidateCommit({
364 + ownerId: 'A',
365 + intentId: intent.id,
366 + commitSha: 'e'.repeat(40)
367 + });
368 + const completed = await client.completeCommit({
369 + ownerId: 'A',
370 + intentId: intent.id,
371 + commitSha: 'e'.repeat(40),
372 + branch: intent.targetBranch
373 + });
374 assert.equal(completed.state, 'COMMITTED');
375 assert.equal(completed.commitSha, 'e'.repeat(40));
376 assert.equal(completed.branch, intent.targetBranch);
@@ -201,19 +387,43 @@ test('sealed intent is immutable and beginCommit is atomic through COMMITTED res
387 test('cancelWorkspace removes draft and matching pending input', async () => {
388 const Client = requireExport(clientModule, 'DurableWorkspaceStoreClient');
389 const Store = requireExport(durableModule, 'WorkspaceStore');
204 - const client = new Client({ namespace: makeNamespace(Store), now: () => 1_000 });
205 - const workspace = await client.createWorkspace({ ownerId: 'A', ...baseWorkspace() });
206 - await client.setPendingInput({ ownerId: 'A', workspaceId: workspace.id, mode: 'commit_message' });
390 + const client = new Client({
391 + namespace: makeNamespace(Store),
392 + now: () => 1_000
393 + });
394 + const workspace = await client.createWorkspace({
395 + ownerId: 'A',
396 + ...baseWorkspace()
397 + });
398 + await client.setPendingInput({
399 + ownerId: 'A',
400 + workspaceId: workspace.id,
401 + mode: 'commit_message'
402 + });
403 await client.cancelWorkspace({ ownerId: 'A', workspaceId: workspace.id });
208 - assert.equal(await client.getWorkspace({ ownerId: 'A', workspaceId: workspace.id }), null);
404 + assert.equal(
405 + await client.getWorkspace({ ownerId: 'A', workspaceId: workspace.id }),
406 + null
407 + );
408 assert.equal(await client.getPendingInput({ ownerId: 'A' }), null);
409 });
410
411 test('Worker exports WorkspaceStore and Wrangler declares SQLite durable binding without legacy migrations', async () => {
412 const Store = requireExport(durableModule, 'WorkspaceStore');
413 assert.equal(indexModule.WorkspaceStore, Store);
215 - const config = JSON.parse(await readFile(new URL('../wrangler.jsonc', import.meta.url), 'utf8'));
216 - assert.ok(config.durable_objects?.bindings?.some(binding => binding.name === 'WORKSPACE_STORE' && binding.class_name === 'WorkspaceStore'));
217 - assert.deepEqual(config.exports?.WorkspaceStore, { type: 'durable-object', storage: 'sqlite' });
414 + const config = JSON.parse(
415 + await readFile(new URL('../wrangler.jsonc', import.meta.url), 'utf8')
416 + );
417 + assert.ok(
418 + config.durable_objects?.bindings?.some(
419 + (binding) =>
420 + binding.name === 'WORKSPACE_STORE' &&
421 + binding.class_name === 'WorkspaceStore'
422 + )
423 + );
424 + assert.deepEqual(config.exports?.WorkspaceStore, {
425 + type: 'durable-object',
426 + storage: 'sqlite'
427 + });
428 assert.equal('migrations' in config, false);
429 });
wrangler.jsonc
+39 -1
@@ -1 +1,39 @@
1 -{"$schema":"node_modules/wrangler/config-schema.json","name":"nexa-dev-bot","main":"src/index.js","compatibility_date":"2026-10-02","workers_dev":true,"keep_vars":true,"observability":{"enabled":true},"durable_objects":{"bindings":[{"name":"APPROVAL_REPLAY_GUARD","class_name":"ApprovalReplayGuard"},{"name":"WORKSPACE_STORE","class_name":"WorkspaceStore"},{"name":"INCIDENT_STORE","class_name":"IncidentStore"},{"name":"AUTOMATION_STORE","class_name":"AutomationStore"},{"name":"KILL_SWITCH_STORE","class_name":"KillSwitchStore"}]},"previews":{"durable_objects":{"bindings":[{"name":"APPROVAL_REPLAY_GUARD","class_name":"ApprovalReplayGuard"},{"name":"WORKSPACE_STORE","class_name":"WorkspaceStore"},{"name":"INCIDENT_STORE","class_name":"IncidentStore"},{"name":"AUTOMATION_STORE","class_name":"AutomationStore"},{"name":"KILL_SWITCH_STORE","class_name":"KillSwitchStore"}]}},"exports":{"ApprovalReplayGuard":{"type":"durable-object","storage":"sqlite"},"WorkspaceStore":{"type":"durable-object","storage":"sqlite"},"IncidentStore":{"type":"durable-object","storage":"sqlite"},"AutomationStore":{"type":"durable-object","storage":"sqlite"},"KillSwitchStore":{"type":"durable-object","storage":"sqlite"}}}
1 +{
2 + "$schema": "node_modules/wrangler/config-schema.json",
3 + "name": "nexa-dev-bot",
4 + "main": "src/index.js",
5 + "compatibility_date": "2026-10-02",
6 + "workers_dev": true,
7 + "keep_vars": true,
8 + "observability": { "enabled": true },
9 + "durable_objects": {
10 + "bindings": [
11 + { "name": "APPROVAL_REPLAY_GUARD", "class_name": "ApprovalReplayGuard" },
12 + { "name": "WORKSPACE_STORE", "class_name": "WorkspaceStore" },
13 + { "name": "INCIDENT_STORE", "class_name": "IncidentStore" },
14 + { "name": "AUTOMATION_STORE", "class_name": "AutomationStore" },
15 + { "name": "KILL_SWITCH_STORE", "class_name": "KillSwitchStore" }
16 + ]
17 + },
18 + "previews": {
19 + "durable_objects": {
20 + "bindings": [
21 + {
22 + "name": "APPROVAL_REPLAY_GUARD",
23 + "class_name": "ApprovalReplayGuard"
24 + },
25 + { "name": "WORKSPACE_STORE", "class_name": "WorkspaceStore" },
26 + { "name": "INCIDENT_STORE", "class_name": "IncidentStore" },
27 + { "name": "AUTOMATION_STORE", "class_name": "AutomationStore" },
28 + { "name": "KILL_SWITCH_STORE", "class_name": "KillSwitchStore" }
29 + ]
30 + }
31 + },
32 + "exports": {
33 + "ApprovalReplayGuard": { "type": "durable-object", "storage": "sqlite" },
34 + "WorkspaceStore": { "type": "durable-object", "storage": "sqlite" },
35 + "IncidentStore": { "type": "durable-object", "storage": "sqlite" },
36 + "AutomationStore": { "type": "durable-object", "storage": "sqlite" },
37 + "KillSwitchStore": { "type": "durable-object", "storage": "sqlite" }
38 + }
39 +}