-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.js
More file actions
909 lines (823 loc) · 27.9 KB
/
main.js
File metadata and controls
909 lines (823 loc) · 27.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
const { app, BrowserWindow, ipcMain, dialog, shell } = require("electron");
const path = require("node:path");
const fs = require("node:fs/promises");
const { Client } = require("@modelcontextprotocol/sdk/client/index.js");
const {
SSEClientTransport,
} = require("@modelcontextprotocol/sdk/client/sse.js");
const { CallToolResultSchema } = require("@modelcontextprotocol/sdk/types.js");
const SERVER_URL = "http://localhost:6767/sse";
const DEFAULT_REPO =
"https://raw.githubusercontent.com/JiriKrblich/Affinity-Community-Scripts/refs/heads/main/registry.json";
let client;
let transport;
let localScriptsDir;
let configPath;
let win;
ipcMain.on("app-version-sync", (e) => {
e.returnValue = app.getVersion();
});
// --- Helper Functions ---
function getTextContent(result) {
return (result.content || [])
.filter((i) => i && i.type === "text")
.map((i) => i.text)
.join("\n");
}
function parseCsvTextContent(result) {
const textChunks = (result.content || [])
.filter((i) => i && i.type === "text")
.map((i) => i.text);
return [
...new Set(
textChunks
.join(",")
.split(",")
.map((n) => n.trim())
.filter(Boolean),
),
];
}
function resolveCommunityAssetUrl(registryUrl, assetUrl) {
if (!assetUrl) return "";
try {
return new URL(assetUrl, registryUrl).toString();
} catch {
return assetUrl;
}
}
function assertLocalScriptFilename(filename) {
if (!filename || typeof filename !== "string") {
throw new Error("Missing script filename.");
}
if (path.basename(filename) !== filename || path.extname(filename) !== ".js") {
throw new Error("Invalid script filename.");
}
return filename;
}
function localScriptFilenameFromInput(input) {
const base = String(input || "")
.trim()
.replace(/\.js$/i, "")
.toLowerCase()
.replace(/[^a-z0-9_-]/g, "-")
.replace(/^-+|-+$/g, "");
if (!base) throw new Error("Please enter a valid script name.");
return `${base}.js`;
}
function readMetadataField(header, field) {
const re = new RegExp(`^\\s*\\*?\\s*${field}:\\s*(.*)$`, "im");
const match = header.match(re);
return match ? match[1].trim() : "";
}
function parseScriptMetadata(code, fallbackName = "") {
const meta = {
name: fallbackName,
description: "",
version: "",
author: "",
};
const headerMatch = String(code || "").match(/^\s*\/\*\*([\s\S]*?)\*\//);
if (!headerMatch) return meta;
const header = headerMatch[1];
meta.name = readMetadataField(header, "name") || meta.name;
meta.description = readMetadataField(header, "description");
meta.version = readMetadataField(header, "version");
meta.author = readMetadataField(header, "author");
return meta;
}
function metadataValue(value) {
return String(value || "").replace(/\s*\n+\s*/g, " ").trim();
}
function upsertMetadataHeader(code, metadata) {
const fields = {
name: metadataValue(metadata.name),
description: metadataValue(metadata.description),
version: metadataValue(metadata.version),
author: metadataValue(metadata.author),
};
const presentFields = Object.entries(fields).filter(([, value]) => value);
if (presentFields.length === 0) return code;
const source = String(code || "");
const headerMatch = source.match(/^\s*\/\*\*([\s\S]*?)\*\//);
if (!headerMatch) {
const header =
"/**\n" +
presentFields.map(([key, value]) => ` * ${key}: ${value}`).join("\n") +
"\n */\n\n";
return header + source.replace(/^\s+/, "");
}
let header = headerMatch[1];
for (const [key, value] of presentFields) {
const re = new RegExp(`(^\\s*\\*?\\s*${key}:\\s*).*$`, "im");
if (re.test(header)) {
header = header.replace(re, (line, prefix) => `${prefix}${value}`);
} else {
header += `\n * ${key}: ${value}`;
}
}
return source.replace(headerMatch[0], `/**${header}*/`);
}
let mcpConnected = false;
let mcpConnectPromise = null;
// Establish (or re-establish) the MCP session. Safe to call multiple times — concurrent callers
// share the same in-flight promise. Throws if the bridge is unreachable so callers can surface
// a real error instead of falling through with a stale client.
async function ensureMcpConnected() {
if (mcpConnected && client && transport) return;
if (mcpConnectPromise) return mcpConnectPromise;
mcpConnectPromise = (async () => {
try {
if (transport) {
try {
await transport.close();
} catch {}
}
client = new Client({ name: "script-mgr-ui", version: "1.0.0" });
transport = new SSEClientTransport(new URL(SERVER_URL));
await client.connect(transport);
// Affinity's MCP requires reading the preamble doc once per session before other
// SDK-doc tools will return real data — otherwise list_sdk_documentation etc. respond
// with an "ERROR: Listing failed" payload. Prime it best-effort.
try {
await client.request(
{
method: "tools/call",
params: {
name: "read_sdk_documentation_topic",
arguments: { filename: "preamble" },
},
},
CallToolResultSchema,
);
} catch (primeErr) {
console.warn("[MCP] preamble prime failed:", primeErr.message);
}
mcpConnected = true;
} catch (err) {
mcpConnected = false;
throw err;
} finally {
mcpConnectPromise = null;
}
})();
return mcpConnectPromise;
}
async function callTool(_clientIgnored, name, args) {
await ensureMcpConnected();
try {
return await client.request(
{ method: "tools/call", params: { name, arguments: args } },
CallToolResultSchema,
);
} catch (err) {
// If the session dropped (bridge restarted, etc.), reconnect once and retry.
const msg = err && err.message ? err.message : String(err);
if (
/session not initialized|not connected|disconnected|closed/i.test(msg)
) {
mcpConnected = false;
await ensureMcpConnected();
return client.request(
{ method: "tools/call", params: { name, arguments: args } },
CallToolResultSchema,
);
}
throw err;
}
}
// --- Bezpečná správa konfigurace ---
async function getConfig() {
let config = {};
let needsSave = false;
try {
const data = await fs.readFile(configPath, "utf8");
config = JSON.parse(data);
} catch (e) {
needsSave = true;
}
if (!config.repositories || !Array.isArray(config.repositories)) {
config.repositories = [DEFAULT_REPO];
needsSave = true;
} else if (!config.repositories.includes(DEFAULT_REPO)) {
config.repositories.unshift(DEFAULT_REPO);
needsSave = true;
}
if (
!config.favoriteCommunityScripts ||
!Array.isArray(config.favoriteCommunityScripts)
) {
config.favoriteCommunityScripts = [];
needsSave = true;
}
if (typeof config.sidebarCollapsed !== "boolean") {
config.sidebarCollapsed = false;
needsSave = true;
}
if (needsSave) await saveConfig(config);
return config;
}
async function saveConfig(config) {
await fs.writeFile(configPath, JSON.stringify(config, null, 2), "utf8");
}
// --- Watch mode: re-push edited scripts to the bridge and notify the renderer ---
async function startWatcher() {
const pending = new Map(); // filename -> timer (debounce)
const handleChange = async (filename) => {
if (!filename || !filename.endsWith(".js")) return;
const full = path.join(localScriptsDir, filename);
let exists = false;
try {
await fs.stat(full);
exists = true;
} catch {}
if (exists) {
// Only auto-sync if the script is already installed in Affinity. New or
// newly-saved files stay local until the user explicitly clicks the
// install dot in My Scripts.
try {
const listResult = await callTool(client, "list_library_scripts", {});
const titles = parseCsvTextContent(listResult).map((t) =>
t.toLowerCase(),
);
const stem = path.parse(filename).name.toLowerCase();
if (titles.includes(stem)) {
const code = await fs.readFile(full, "utf8");
const metadata = parseScriptMetadata(code, path.parse(filename).name);
await callTool(client, "save_script_to_library", {
title: metadata.name || path.parse(filename).name,
description: metadata.description,
code,
}).catch(() => {});
}
} catch {} // bridge offline or not installed — renderer still gets the change ping
}
if (win && !win.isDestroyed())
win.webContents.send("local-scripts-changed");
};
const debounced = (filename) => {
const prev = pending.get(filename);
if (prev) clearTimeout(prev);
pending.set(
filename,
setTimeout(() => {
pending.delete(filename);
handleChange(filename);
}, 300),
);
};
try {
const watcher = fs.watch(localScriptsDir);
for await (const { filename } of watcher) {
debounced(filename);
}
} catch (err) {
console.warn("watch mode error:", err.message);
}
}
app.whenReady().then(async () => {
localScriptsDir = path.join(app.getPath("userData"), "MyScripts");
configPath = path.join(app.getPath("userData"), "config.json");
await fs.mkdir(localScriptsDir, { recursive: true });
// Eagerly attempt to connect so the Server Bridge status is accurate on first paint;
// failure is non-fatal — ensureMcpConnected() will retry on demand when a tool call
// happens (user opens Documentation, SDK search, etc.).
ensureMcpConnected().catch((err) =>
console.warn("[MCP] initial connect failed:", err.message),
);
startWatcher(); // fire-and-forget
win = new BrowserWindow({
width: 1200,
height: 820,
title: "Script Manager for Affinity",
minWidth: 960,
minHeight: 600,
backgroundColor: "#1f1f1f",
...(process.platform === "darwin"
? {
titleBarStyle: "hiddenInset",
trafficLightPosition: { x: 14, y: 16 },
}
: {}),
webPreferences: {
preload: path.join(__dirname, "preload.js"),
contextIsolation: true,
},
});
// ==========================================
// --- LOCAL SCRIPTS & MCP ---
// ==========================================
ipcMain.handle("list-local-scripts", async () => {
try {
const files = (await fs.readdir(localScriptsDir)).filter((f) =>
f.endsWith(".js"),
);
const out = [];
for (const file of files) {
const full = path.join(localScriptsDir, file);
const stat = await fs.stat(full);
let metadata = {
name: path.parse(file).name,
description: "",
version: "",
};
try {
const head = (await fs.readFile(full, "utf8")).slice(0, 4096);
metadata = parseScriptMetadata(head, metadata.name);
} catch {}
out.push({
file,
name: metadata.name,
description: metadata.description,
version: metadata.version,
size: stat.size,
modified: stat.mtimeMs,
});
}
return { success: true, data: out };
} catch (e) {
return { success: false, error: e.message };
}
});
ipcMain.handle("delete-local-script", async (e, filename) => {
try {
await fs.unlink(path.join(localScriptsDir, filename));
return { success: true };
} catch (e) {
return { success: false, error: e.message };
}
});
ipcMain.handle("read-local-script", async (e, filename) => {
try {
const code = await fs.readFile(
path.join(localScriptsDir, filename),
"utf8",
);
return { success: true, data: { code } };
} catch (err) {
return { success: false, error: err.message };
}
});
ipcMain.handle("save-local-script", async (e, filename, code) => {
try {
await fs.writeFile(path.join(localScriptsDir, filename), code, "utf8");
return { success: true };
} catch (err) {
return { success: false, error: err.message };
}
});
ipcMain.handle("rename-local-script", async (e, filename, newName) => {
try {
const oldFilename = assertLocalScriptFilename(filename);
const nextFilename = localScriptFilenameFromInput(newName);
if (oldFilename === nextFilename) {
return { success: true, data: { filename: nextFilename } };
}
const oldPath = path.join(localScriptsDir, oldFilename);
const nextPath = path.join(localScriptsDir, nextFilename);
try {
await fs.access(nextPath);
return {
success: false,
error: `A script named ${nextFilename} already exists.`,
};
} catch {}
await fs.rename(oldPath, nextPath);
win.webContents.send("local-scripts-changed");
return { success: true, data: { filename: nextFilename } };
} catch (err) {
return { success: false, error: err.message };
}
});
ipcMain.handle("select-file", async () => {
const { canceled, filePaths } = await dialog.showOpenDialog(win, {
properties: ["openFile"],
filters: [{ name: "JavaScript", extensions: ["js"] }],
});
if (canceled || filePaths.length === 0) return { success: false };
const code = await fs.readFile(filePaths[0], "utf8");
// Výchozí hodnoty (pokud skript nemá hlavičku)
const metadata = parseScriptMetadata(code, path.parse(filePaths[0]).name);
return {
success: true,
data: {
name: metadata.name,
description: metadata.description,
code,
},
};
});
ipcMain.handle("export-to-disk", async (event, filename) => {
try {
const code = await fs.readFile(
path.join(localScriptsDir, filename),
"utf8",
);
const { canceled, filePath } = await dialog.showSaveDialog(win, {
defaultPath: filename,
});
if (canceled || !filePath) return { success: false, error: "Cancelled" };
await fs.writeFile(filePath, code, "utf8");
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
});
ipcMain.handle("push-to-mcp", async (event, filename) => {
try {
const filePath = path.join(localScriptsDir, filename);
const code = await fs.readFile(filePath, "utf8");
const metadata = parseScriptMetadata(code, path.parse(filename).name);
await callTool(client, "save_script_to_library", {
title: metadata.name || path.parse(filename).name,
description: metadata.description,
code,
});
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
});
ipcMain.handle("list-mcp-scripts", async () => {
try {
const result = await callTool(client, "list_library_scripts", {});
return { success: true, data: getTextContent(result) || result };
} catch (error) {
return { success: false, error: error.message };
}
});
// "Add Script" — writes to disk only. Does NOT push to MCP: installation is an explicit
// action via the install dot on the My Scripts row.
ipcMain.handle("save-script", async (event, title, description, code) => {
try {
const safeFilename =
title.toLowerCase().replace(/[^a-z0-9_-]/g, "-") + ".js";
const codeWithMetadata = upsertMetadataHeader(code, {
name: title,
description,
});
await fs.writeFile(
path.join(localScriptsDir, safeFilename),
codeWithMetadata,
"utf8",
);
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
});
ipcMain.handle("download-from-mcp", async (event, mcpTitle, localName) => {
try {
const result = await callTool(client, "read_library_script", {
title: mcpTitle,
});
const code = getTextContent(result);
if (!code) return { success: false, error: "Empty script." };
const safeFilename =
localName.toLowerCase().replace(/[^a-z0-9_-]/g, "-") + ".js";
await fs.writeFile(
path.join(localScriptsDir, safeFilename),
code,
"utf8",
);
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
});
// ==========================================
// --- COMMUNITY SCRIPTS & SETTINGS ---
// ==========================================
ipcMain.handle("get-repos", async () => {
const config = await getConfig();
return { success: true, data: config.repositories };
});
ipcMain.handle("add-repo", async (event, url) => {
try {
let rawUrl = url;
if (url.includes("github.com")) {
const match = url.match(/github\.com\/([^\/]+\/[^\/\?#]+)/);
if (match) {
const cleanRepo = match[1].replace(".git", "");
rawUrl = `https://raw.githubusercontent.com/${cleanRepo}/refs/heads/main/registry.json`;
} else {
return {
success: false,
error:
"Invalid GitHub URL format. Use https://github.com/user/repo",
};
}
} else if (!url.includes("raw.githubusercontent.com")) {
return {
success: false,
error: "Please provide a valid GitHub repository URL.",
};
}
const config = await getConfig();
if (!config.repositories.includes(rawUrl)) {
config.repositories.push(rawUrl);
await saveConfig(config);
win.webContents.send("repos-changed");
}
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
});
ipcMain.handle("remove-repo", async (event, url) => {
if (url === DEFAULT_REPO)
return { success: false, error: "Cannot remove default repository." };
try {
const config = await getConfig();
config.repositories = config.repositories.filter((r) => r !== url);
await saveConfig(config);
win.webContents.send("repos-changed");
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
});
ipcMain.handle("list-community-scripts", async () => {
try {
const config = await getConfig();
let allScripts = [];
let communityOrder = 0;
for (const url of config.repositories) {
try {
const response = await fetch(url);
if (response.ok) {
const registry = await response.json();
const scriptsWithSource = (registry.scripts || []).map((script) => ({
...script,
_source: url,
_imageUrl: resolveCommunityAssetUrl(
url,
script.image ||
script.image_url ||
script.preview_image ||
script.screenshot,
),
_communityOrder: communityOrder++,
}));
allScripts = allScripts.concat(scriptsWithSource);
}
} catch (err) {
console.warn(`Failed to fetch repo: ${url}`);
}
}
return { success: true, data: allScripts };
} catch (error) {
return { success: false, error: error.message };
}
});
ipcMain.handle("get-community-favorites", async () => {
try {
const config = await getConfig();
return { success: true, data: config.favoriteCommunityScripts };
} catch (error) {
return { success: false, error: error.message };
}
});
ipcMain.handle("toggle-community-favorite", async (event, favorite) => {
try {
if (!favorite || !favorite.repo || !favorite.id) {
return { success: false, error: "Missing favorite repo or id." };
}
const config = await getConfig();
const index = config.favoriteCommunityScripts.findIndex(
(item) => item.repo === favorite.repo && item.id === favorite.id,
);
if (index >= 0) {
config.favoriteCommunityScripts.splice(index, 1);
} else {
config.favoriteCommunityScripts.push({
repo: favorite.repo,
id: favorite.id,
});
}
await saveConfig(config);
return { success: true, data: config.favoriteCommunityScripts };
} catch (error) {
return { success: false, error: error.message };
}
});
ipcMain.handle("get-sidebar-collapsed", async () => {
try {
const config = await getConfig();
return { success: true, data: config.sidebarCollapsed };
} catch (error) {
return { success: false, error: error.message };
}
});
ipcMain.handle("set-sidebar-collapsed", async (event, collapsed) => {
try {
const config = await getConfig();
config.sidebarCollapsed = Boolean(collapsed);
await saveConfig(config);
return { success: true, data: config.sidebarCollapsed };
} catch (error) {
return { success: false, error: error.message };
}
});
ipcMain.handle(
"download-community-script",
async (event, downloadUrl, filename, metadata = {}) => {
try {
const response = await fetch(downloadUrl);
if (!response.ok)
throw new Error("Error downloading file from server.");
const code = await response.text();
const downloadedMetadata = parseScriptMetadata(code, filename);
const finalMetadata = {
...downloadedMetadata,
name: metadata.name || filename,
description: metadata.description || downloadedMetadata.description,
version: metadata.version || downloadedMetadata.version,
author: metadata.author || downloadedMetadata.author,
};
const codeWithMetadata = upsertMetadataHeader(code, finalMetadata);
const safeName =
filename.toLowerCase().replace(/[^a-z0-9_-]/g, "-") + ".js";
await fs.writeFile(
path.join(localScriptsDir, safeName),
codeWithMetadata,
"utf8",
);
try {
await callTool(client, "save_script_to_library", {
title: finalMetadata.name || filename,
description: finalMetadata.description,
code: codeWithMetadata,
});
} catch (mcpErr) {}
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
},
);
// Save-only: download to disk without pushing to the MCP bridge. Used by the "save" icon
// next to Install on community cards, for users who want to inspect / edit before activating.
ipcMain.handle(
"save-community-script",
async (event, downloadUrl, filename, metadata = {}) => {
try {
const response = await fetch(downloadUrl);
if (!response.ok)
throw new Error("Error downloading file from server.");
const code = await response.text();
const downloadedMetadata = parseScriptMetadata(code, filename);
const finalMetadata = {
...downloadedMetadata,
name: metadata.name || filename,
description: metadata.description || downloadedMetadata.description,
version: metadata.version || downloadedMetadata.version,
author: metadata.author || downloadedMetadata.author,
};
const codeWithMetadata = upsertMetadataHeader(code, finalMetadata);
const safeName =
filename.toLowerCase().replace(/[^a-z0-9_-]/g, "-") + ".js";
await fs.writeFile(
path.join(localScriptsDir, safeName),
codeWithMetadata,
"utf8",
);
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
},
);
// ==========================================
// --- DOCUMENTATION, SEARCH & UPDATES ---
// ==========================================
ipcMain.on("open-external-repo", () =>
shell.openExternal(
"https://github.com/JiriKrblich/Affinity-Community-Scripts/issues/new?template=contribute-script.md",
),
);
ipcMain.on("open-url", (event, url) => shell.openExternal(url));
ipcMain.handle("fetch-docs", async () => {
try {
const listResult = await callTool(client, "list_sdk_documentation", {});
const rawText = getTextContent(listResult).trim();
// Affinity's tools occasionally return an error message as content with a successful RPC.
if (!rawText || /^error[:\s]/i.test(rawText)) {
return {
success: false,
error:
"Affinity did not return a topic list: " +
(rawText || "empty response"),
};
}
const fileNames = parseCsvTextContent(listResult).filter(
(n) => n && !/^error/i.test(n) && n !== "preamble",
); // preamble is an init marker, not a user-facing topic
const docs = [];
for (const fileName of fileNames) {
try {
const readResult = await callTool(
client,
"read_sdk_documentation_topic",
{ filename: fileName },
);
const content = getTextContent(readResult);
// Skip topics whose content is itself an error response.
if (content && !/^error[:\s]/i.test(content.trim())) {
docs.push({ title: fileName, content });
}
} catch (e) {}
}
return { success: true, data: docs };
} catch (error) {
return { success: false, error: error.message };
}
});
ipcMain.handle("search-docs", async (event, query) => {
try {
const result = await callTool(client, "search_sdk_hints", {
prompt: query,
});
return {
success: true,
data: getTextContent(result) || JSON.stringify(result, null, 2),
};
} catch (error) {
return { success: false, error: error.message };
}
});
async function checkForUpdates(isManualCheck = false) {
try {
const currentVersion = app.getVersion();
const response = await fetch(
`https://api.github.com/repos/JiriKrblich/Affinity-Script-Manager/releases/latest`,
);
if (!response.ok) throw new Error("Could not connect to GitHub.");
const release = await response.json();
const latestVersion = release.tag_name.replace("v", "");
const v1 = latestVersion.split(".").map(Number);
const v2 = currentVersion.split(".").map(Number);
let isNewer = false;
for (let i = 0; i < 3; i++) {
if ((v1[i] || 0) > (v2[i] || 0)) {
isNewer = true;
break;
}
if ((v1[i] || 0) < (v2[i] || 0)) {
break;
}
}
if (isNewer) {
win.webContents.send(
"update-available",
release.html_url,
latestVersion,
);
const { response: btnIndex } = await dialog.showMessageBox(win, {
type: "info",
title: "Update Available",
message: `A new version of Affinity Script Manager (v${latestVersion}) is available!`,
detail: "Would you like to download it now?",
buttons: ["Update", "Later"],
defaultId: 0,
cancelId: 1,
});
if (btnIndex === 0) shell.openExternal(release.html_url);
return { success: true, hasUpdate: true };
} else {
return { success: true, hasUpdate: false };
}
} catch (error) {
if (isManualCheck)
dialog.showErrorBox("Update Check Failed", error.message);
return { success: false, error: error.message };
}
}
ipcMain.handle("check-updates", async () => await checkForUpdates(true));
win.webContents.once("did-finish-load", () => checkForUpdates(false));
win.loadFile("index.html");
});
app.on("window-all-closed", async () => {
if (process.platform !== "darwin") {
if (transport) await transport.close().catch(() => {});
app.quit();
}
});
// Activation of window for macOS when user closes window
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
win = new BrowserWindow({
width: 1200,
height: 820,
title: "Script Manager for Affinity",
minWidth: 960,
minHeight: 600,
backgroundColor: "#1f1f1f",
webPreferences: {
preload: path.join(__dirname, "preload.js"),
contextIsolation: true,
},
});
win.loadFile("index.html");
}
});