-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub-sync.user.js
More file actions
2430 lines (2190 loc) · 109 KB
/
github-sync.user.js
File metadata and controls
2430 lines (2190 loc) · 109 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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name TRMNL GitHub Sync
// @namespace https://github.com/ExcuseMi/trmnl-userscripts
// @version 0.1.1
// @description Push your TRMNL plugin code to a GitHub repository and pull it back on demand.
// @author ExcuseMi
// @match https://trmnl.com/*
// @icon https://raw.githubusercontent.com/ExcuseMi/trmnl-userscripts/refs/heads/main/images/trmnl.svg
// @require https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js
// @downloadURL https://raw.githubusercontent.com/ExcuseMi/trmnl-userscripts/main/github-sync.user.js
// @updateURL https://raw.githubusercontent.com/ExcuseMi/trmnl-userscripts/main/github-sync.user.js
// @grant none
// @run-at document-body
// ==/UserScript==
(function () {
'use strict';
const LOG_PREFIX = '[TRMNL GH Sync]';
const log = (...a) => console.log(LOG_PREFIX, ...a);
const warn = (...a) => console.warn(LOG_PREFIX, ...a);
const PANEL_ID = 'trmnl-gh-panel';
const OVERLAY_ID = 'trmnl-gh-overlay';
const BTN_ID = 'trmnl-gh-btn';
const ACCT_BTN_ID = 'trmnl-gh-account-btn';
const PUSH_BTN_ID = 'trmnl-gh-push-btn'; // quick push in page header
const PULL_BTN_ID = 'trmnl-gh-pull-btn'; // pull indicator in page header
const STYLE_ID = 'trmnl-gh-style';
const LAST_PUSH_SHAS_KEY = 'trmnl_gh_shas'; // prefix; keyed per plugin
const LAST_PUSH_TIME_KEY = 'trmnl_gh_push_time'; // timestamp of last push, per plugin
const LIST_BADGE_ATTR = 'data-gh-sync-badge'; // marks rows on plugin list page
// Storage keys
const GH_TOKEN_KEY = 'trmnl_gh_token';
const GH_CONFIG_KEY = 'trmnl_gh_config';
const GH_API_KEY = 'trmnl_gh_api_key'; // TRMNL API key for uploads
const GH_CONFIG_REPO_KEY = 'trmnl_gh_config_repo'; // optional global config repo (owner/repo)
const DEFAULT_CONFIG = {
repo: '', // "owner/repo"
branch: 'main',
path: 'plugin',
commitMsg: 'TRMNL sync: {name} (plugin {id})',
autoPush: false,
};
const AUTOPUSH_KEY = 'trmnl_gh_autopush_pending'; // sessionStorage
const REMOTE_CONFIG_FILE = '.trmnl-sync.json'; // stored at repo root
// ---------------------------------------------------------------------------
// URL helpers
// ---------------------------------------------------------------------------
function getPluginId() {
const m = window.location.pathname.match(/\/plugin_settings\/(\d+)/);
return m ? m[1] : null;
}
function getPluginName() {
// Try the settings/edit page heading first
const h2 = document.querySelector('h2.font-heading');
if (h2) return h2.textContent.trim();
// On markup/edit and other sub-pages, look for a breadcrumb or nav link
// that contains the plugin name (typically an ancestor link to /edit)
const crumb = document.querySelector('a[href*="/plugin_settings/"][href$="/edit"]');
if (crumb) return crumb.textContent.trim();
return '';
}
function isAccountPage() {
return window.location.pathname.startsWith('/account');
}
// ---------------------------------------------------------------------------
// Config / token helpers
// ---------------------------------------------------------------------------
function cfgKey(pluginId) { return `${GH_CONFIG_KEY}_${pluginId}`; }
function getConfig(pluginId) {
try {
return { ...DEFAULT_CONFIG, ...JSON.parse(localStorage.getItem(cfgKey(pluginId)) || '{}') };
} catch { return { ...DEFAULT_CONFIG }; }
}
function saveConfig(pluginId, cfg) {
localStorage.setItem(cfgKey(pluginId), JSON.stringify(cfg));
}
function getToken() { return localStorage.getItem(GH_TOKEN_KEY) || ''; }
function saveToken(t) { t ? localStorage.setItem(GH_TOKEN_KEY, t) : localStorage.removeItem(GH_TOKEN_KEY); }
function getTrmnlKey() { return localStorage.getItem(GH_API_KEY) || ''; }
function saveTrmnlKey(k) { k ? localStorage.setItem(GH_API_KEY, k) : localStorage.removeItem(GH_API_KEY); }
function getConfigRepo() { return localStorage.getItem(GH_CONFIG_REPO_KEY) || ''; }
function saveConfigRepo(r) { r ? localStorage.setItem(GH_CONFIG_REPO_KEY, r) : localStorage.removeItem(GH_CONFIG_REPO_KEY); }
function effectiveRepo(cfg) { return (cfg && cfg.repo) || ''; }
// Returns {owner, repo, branch} for where .trmnl-sync.json lives.
// If a dedicated config repo is set, use that (always on main).
// Otherwise fall back to the per-plugin repo + branch.
function configRepoCoords(perPluginOwner, perPluginRepo, perPluginBranch) {
const cr = getConfigRepo().trim();
if (cr && cr.includes('/')) {
const [o, r] = cr.split('/');
return { owner: o, repo: r, branch: 'main' };
}
return { owner: perPluginOwner, repo: perPluginRepo, branch: perPluginBranch };
}
function resolvePath(template, pluginId) {
return template.replace(/\{id\}/g, pluginId).replace(/\/+$/, '');
}
// Extract the plugin name from settings.yml content (most reliable source).
function extractNameFromYaml(yaml) {
const m = (yaml || '').match(/^name:\s*["']?(.+?)["']?\s*$/m);
return m ? m[1].trim() : null;
}
function resolveMsg(template, pluginId, nameOverride) {
const name = nameOverride || getPluginName() || `plugin ${pluginId}`;
return template.replace(/\{id\}/g, pluginId).replace(/\{name\}/g, name);
}
// Accepts a full GitHub URL or bare "owner/repo" and returns "owner/repo"
function normalizeRepoInput(raw) {
let s = raw.trim();
// git@github.com:owner/repo.git
s = s.replace(/^git@github\.com:/, '');
// https://github.com/owner/repo[.git][/]
s = s.replace(/^https?:\/\/github\.com\//, '');
// strip trailing .git or /
s = s.replace(/\.git$/, '').replace(/\/$/, '');
return s;
}
function parseRepo(cfg) {
const parts = effectiveRepo(cfg).trim().split('/');
if (parts.length < 2 || !parts[0] || !parts[1]) {
throw new Error('Set a repository in the GitHub Sync panel.');
}
return { owner: parts[0], repo: parts[1] };
}
// ---------------------------------------------------------------------------
// Auto-push on save
// ---------------------------------------------------------------------------
function attachAutoSave(pluginId) {
const form =
document.querySelector('form[id^="edit_plugin_setting"]') ||
document.querySelector('[data-markup-target="enabledSaveButton"]')?.closest('form');
if (!form || form.dataset.ghSyncAttached) return;
form.dataset.ghSyncAttached = 'true';
form.addEventListener('submit', () => {
if (!getConfig(pluginId).autoPush) return;
sessionStorage.setItem(AUTOPUSH_KEY, pluginId);
log('Auto-push flagged for after reload');
});
}
async function checkAutoPush() {
const pendingId = sessionStorage.getItem(AUTOPUSH_KEY);
if (!pendingId) return;
sessionStorage.removeItem(AUTOPUSH_KEY);
if (getPluginId() !== pendingId) return;
if (!getConfig(pendingId).autoPush) return;
log('Auto-push triggered for plugin', pendingId);
try {
// Small delay to let TRMNL finish updating the archive after page reload
await new Promise(r => setTimeout(r, 1500));
const url = await push(pendingId, msg => log(msg));
log('Auto-push complete:', url);
// Hide pull/push indicators — GitHub API caches for minutes so re-querying
// immediately would return stale SHAs and falsely show the pull button.
document.getElementById(PULL_BTN_ID)?.style.setProperty('display', 'none');
document.getElementById(PUSH_BTN_ID)?.style.setProperty('display', 'none');
} catch (e) {
warn('Auto-push failed:', e.message);
}
}
// ---------------------------------------------------------------------------
// Last-push SHA tracking (for pull indicator)
// ---------------------------------------------------------------------------
function lastPushShasKey(pluginId) { return `${LAST_PUSH_SHAS_KEY}_${pluginId}`; }
function lastPushTimeKey(pluginId) { return `${LAST_PUSH_TIME_KEY}_${pluginId}`; }
function getLastPushShas(pluginId) {
try { return JSON.parse(localStorage.getItem(lastPushShasKey(pluginId)) || '{}'); } catch { return {}; }
}
function setLastPushShas(pluginId, shas) {
localStorage.setItem(lastPushShasKey(pluginId), JSON.stringify(shas));
}
function recordPushTime(pluginId) {
localStorage.setItem(lastPushTimeKey(pluginId), Date.now().toString());
}
// How many ms since the last push (Infinity if never pushed)
function pushAgeMs(pluginId) {
const t = localStorage.getItem(lastPushTimeKey(pluginId));
return t ? Date.now() - parseInt(t, 10) : Infinity;
}
// GitHub Contents API caches directory listings for several minutes after a
// push via the Git Trees API. Skip the pull-indicator check during that window.
const PUSH_GRACE_MS = 6 * 60 * 1000;
// ---------------------------------------------------------------------------
// Diff helpers (ported from editor-backups, using gh-diff-* CSS prefix)
// ---------------------------------------------------------------------------
function diffLines(a, b) {
const aL = a ? a.replace(/\r/g, '').split('\n') : [];
const bL = b ? b.replace(/\r/g, '').split('\n') : [];
const m = Math.min(aL.length, 800);
const n = Math.min(bL.length, 800);
const dp = Array.from({ length: m + 1 }, () => new Int16Array(n + 1));
for (let i = m - 1; i >= 0; i--)
for (let j = n - 1; j >= 0; j--)
dp[i][j] = aL[i] === bL[j] ? dp[i+1][j+1]+1 : Math.max(dp[i+1][j], dp[i][j+1]);
const out = [];
let i = 0, j = 0;
while (i < m || j < n) {
if (i < m && j < n && aL[i] === bL[j]) { out.push({ t: 'eq', l: aL[i] }); i++; j++; }
else if (i < m && (j >= n || dp[i+1][j] >= dp[i][j+1])) { out.push({ t: 'del', l: aL[i] }); i++; }
else { out.push({ t: 'add', l: bL[j] }); j++; }
}
return out;
}
const chevronUp = `<svg width="10" height="10" viewBox="0 0 256 256" fill="currentColor"><path d="M213.66,165.66a8,8,0,0,1-11.32,0L128,91.31,53.66,165.66A8,8,0,0,1,42.34,154.34l80-80a8,8,0,0,1,11.32,0l80,80A8,8,0,0,1,213.66,165.66Z"/></svg>`;
const chevronDown = `<svg width="10" height="10" viewBox="0 0 256 256" fill="currentColor"><path d="M213.66,101.66l-80,80a8,8,0,0,1-11.32,0l-80-80A8,8,0,0,1,53.66,90.34L128,164.69l74.34-74.35a8,8,0,0,1,11.32,11.32Z"/></svg>`;
function ghBuildDiffEl(oldText, newText) {
if (oldText === newText) {
const p = mk('p', 'text-xs text-gray-500 dark:text-gray-400 italic py-1');
p.textContent = 'No changes in this file.';
return p;
}
const CONTEXT = 3;
const diff = diffLines(oldText, newText);
const show = new Uint8Array(diff.length);
for (let i = 0; i < diff.length; i++)
if (diff[i].t !== 'eq')
for (let k = Math.max(0, i - CONTEXT); k <= Math.min(diff.length - 1, i + CONTEXT); k++)
show[k] = 1;
const pre = mk('pre', 'gh-diff');
let lastShown = -1;
const rendered = new Uint8Array(diff.length);
function appendIntraLine(row, marker, line, other, hlCls) {
let p = 0;
while (p < line.length && p < other.length && line[p] === other[p]) p++;
let lEnd = line.length, oEnd = other.length;
while (lEnd > p && oEnd > p && line[lEnd-1] === other[oEnd-1]) { lEnd--; oEnd--; }
row.appendChild(document.createTextNode(marker + line.slice(0, p)));
if (lEnd > p) row.appendChild(mk('mark', hlCls, line.slice(p, lEnd)));
if (lEnd < line.length) row.appendChild(document.createTextNode(line.slice(lEnd)));
}
diff.forEach((d, idx) => {
if (!show[idx] || rendered[idx]) return;
if (lastShown !== -1 && idx > lastShown + 1) pre.appendChild(mk('div', 'gh-diff-skip', '···'));
if (d.t === 'del') {
let k = idx;
const dels = [], adds = [];
while (k < diff.length && diff[k].t === 'del' && !rendered[k]) dels.push(k++);
while (k < diff.length && diff[k].t === 'add' && !rendered[k]) adds.push(k++);
dels.forEach(i => rendered[i] = 1);
adds.forEach(i => rendered[i] = 1);
const pairs = Math.min(dels.length, adds.length);
for (let p = 0; p < pairs; p++) {
const ol = diff[dels[p]].l, nl = diff[adds[p]].l;
const dr = mk('div', 'gh-diff-del'); appendIntraLine(dr, '− ', ol, nl, 'gh-hl-del'); pre.appendChild(dr);
const ar = mk('div', 'gh-diff-add'); appendIntraLine(ar, '+ ', nl, ol, 'gh-hl-add'); pre.appendChild(ar);
}
for (let p = pairs; p < dels.length; p++) {
const row = mk('div', 'gh-diff-del'); row.textContent = '− ' + diff[dels[p]].l; pre.appendChild(row);
}
for (let p = pairs; p < adds.length; p++) {
const row = mk('div', 'gh-diff-add'); row.textContent = '+ ' + diff[adds[p]].l; pre.appendChild(row);
}
lastShown = k - 1;
} else {
const row = mk('div', `gh-diff-${d.t}`);
row.textContent = (d.t === 'add' ? '+ ' : ' ') + d.l;
pre.appendChild(row);
lastShown = idx;
}
});
// Use a clipDiv to control vertical clipping — avoids the CSS overflow-x/y
// interaction bug where setting overflow-y:visible is silently overridden by
// the browser when overflow-x is already auto on the same element.
let expanded = false;
const clipDiv = mk('div', '');
clipDiv.style.overflow = 'hidden';
clipDiv.style.maxHeight = '10rem';
clipDiv.appendChild(pre);
const expandBtn = mk('button',
'w-full flex items-center justify-center gap-1.5 py-1.5 text-xs font-medium ' +
'text-gray-500 dark:text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 ' +
'border-t border-gray-200 dark:border-gray-700 cursor-pointer ' +
'bg-gray-50 dark:bg-gray-800 transition-colors'
);
expandBtn.type = 'button';
expandBtn.innerHTML = `${chevronDown}<span>Show full diff</span>`;
expandBtn.addEventListener('click', e => {
e.stopPropagation();
expanded = !expanded;
clipDiv.style.maxHeight = expanded ? 'none' : '10rem';
expandBtn.innerHTML = expanded
? `${chevronUp}<span>Collapse</span>`
: `${chevronDown}<span>Show full diff</span>`;
});
const wrap = mk('div', 'rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden mt-1');
wrap.append(clipDiv, expandBtn);
return wrap;
}
// Render a GitHub unified-diff patch string (from commits API files[].patch)
// into the same styled <pre> element as ghBuildDiffEl.
function renderPatch(patch) {
const pre = mk('pre', 'gh-diff');
if (!patch) { pre.textContent = '(binary or empty)'; return pre; }
for (const line of patch.split('\n')) {
let cls = 'gh-diff-eq';
if (line.startsWith('@@')) cls = 'gh-diff-skip';
else if (line.startsWith('+')) cls = 'gh-diff-add';
else if (line.startsWith('-')) cls = 'gh-diff-del';
const row = mk('div', cls);
row.textContent = line;
pre.appendChild(row);
}
const wrap = mk('div', 'rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden mt-1');
const clip = mk('div', '');
clip.style.overflow = 'hidden';
clip.style.maxHeight = '12rem';
clip.appendChild(pre);
const btn = mk('button',
'w-full flex items-center justify-center gap-1.5 py-1.5 text-xs font-medium ' +
'text-gray-500 dark:text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 ' +
'border-t border-gray-200 dark:border-gray-700 cursor-pointer ' +
'bg-gray-50 dark:bg-gray-800 transition-colors'
);
btn.type = 'button';
btn.innerHTML = `${chevronDown}<span>Show full diff</span>`;
let expanded = false;
btn.addEventListener('click', e => {
e.stopPropagation();
expanded = !expanded;
clip.style.maxHeight = expanded ? 'none' : '12rem';
btn.innerHTML = expanded
? `${chevronUp}<span>Collapse</span>`
: `${chevronDown}<span>Show full diff</span>`;
});
wrap.append(clip, btn);
return wrap;
}
// ---------------------------------------------------------------------------
// GitHub API
// ---------------------------------------------------------------------------
async function ghFetch(path, opts = {}) {
const token = getToken();
if (!token) throw new Error('GitHub token not configured. Open the GitHub Sync panel to set it.');
const res = await fetch(`https://api.github.com${path}`, {
cache: 'no-store',
...opts,
headers: {
Accept: 'application/vnd.github+json',
Authorization: `Bearer ${token}`,
'X-GitHub-Api-Version': '2022-11-28',
...(opts.headers || {}),
},
});
if (res.status === 204) return null;
const body = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(`GitHub ${res.status}: ${body.message || res.statusText}`);
return body;
}
// Check if a repo exists and is accessible.
// Returns { error: string|null, isPublic: bool }.
async function ghCheckRepo(owner, repo) {
try {
const data = await ghFetch(`/repos/${owner}/${repo}`);
return { error: null, isPublic: data.private === false };
} catch (e) {
if (e.message.includes('404')) return { error: `Repository "${owner}/${repo}" not found or not accessible.`, isPublic: false };
if (e.message.includes('401') || e.message.includes('403')) return { error: `No access to "${owner}/${repo}" — check your token permissions.`, isPublic: false };
return { error: e.message, isPublic: false };
}
}
// ---------------------------------------------------------------------------
// Remote config: read/write .trmnl-sync.json at the repo root
// Keys stored: branch, path, commitMsg, autoPush (repo + tokens stay local)
// ---------------------------------------------------------------------------
// Returns the full parsed .trmnl-sync.json object, or null if not found.
async function loadAllRemoteConfig(owner, repo, branch) {
const c = configRepoCoords(owner, repo, branch);
try {
const data = await ghFetch(
`/repos/${c.owner}/${c.repo}/contents/${REMOTE_CONFIG_FILE}?ref=${encodeURIComponent(c.branch)}`
);
const parsed = JSON.parse(b64ToUtf8(data.content));
return parsed;
} catch (e) {
if (e.message.includes('404')) return null;
throw e;
}
}
// Write a full config data object to the localStorage cache.
// The GitHub config repo is the source of truth; this is only a local cache
// so that non-panel operations (push, pull, auto-push) don't need a network round-trip.
function cacheConfigData(data) {
const g = data['_global'] || {};
if (g.ghToken) saveToken(g.ghToken);
if (g.trmnlApiKey) saveTrmnlKey(g.trmnlApiKey);
if (g.configRepo) saveConfigRepo(g.configRepo);
for (const [id, pc] of Object.entries(data)) {
if (id === '_global' || !pc || typeof pc !== 'object') continue;
saveConfig(id, { ...DEFAULT_CONFIG, ...pc });
}
}
// Serialise all remote config writes in the same tab so they never race.
let _configSaveLock = Promise.resolve();
async function saveRemoteConfig(owner, repo, branch, pluginId, cfg) {
const result = _configSaveLock.then(() => _doSaveRemoteConfig(owner, repo, branch, pluginId, cfg));
_configSaveLock = result.catch(() => {});
return result;
}
async function _doSaveRemoteConfig(owner, repo, branch, pluginId, cfg, retries = 3) {
const c = configRepoCoords(owner, repo, branch);
let existingSha;
let all = {};
// Always GET the current file so the SHA is fresh — eliminates stale-SHA 409s
// regardless of how many tabs or how quickly the user saves.
try {
const data = await ghFetch(
`/repos/${c.owner}/${c.repo}/contents/${REMOTE_CONFIG_FILE}?ref=${encodeURIComponent(c.branch)}`
);
existingSha = data.sha;
all = JSON.parse(b64ToUtf8(data.content));
} catch (e) {
if (!e.message.includes('404')) throw e;
// File doesn't exist yet — first-time setup, create from scratch.
}
all['_global'] = { ghToken: getToken(), trmnlApiKey: getTrmnlKey(), configRepo: getConfigRepo() };
// Store the full config including repo so other PCs can restore it from the config file.
// Omit empty-string repo to avoid poisoning the file with blank entries that would
// overwrite a valid repo on another PC when the file is loaded back.
const stored = { ...cfg };
if (!stored.repo) delete stored.repo;
all[pluginId] = stored;
const json = JSON.stringify(all, null, 2) + '\n';
const content = btoa(unescape(encodeURIComponent(json)));
const body = { message: 'chore: update TRMNL sync config', content, branch: c.branch };
if (existingSha) body.sha = existingSha;
try {
await ghFetch(`/repos/${c.owner}/${c.repo}/contents/${REMOTE_CONFIG_FILE}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
} catch (e) {
if (retries > 0 && e.message.includes('409')) {
// Concurrent write from another tab/device — back off and retry with fresh GET.
await new Promise(r => setTimeout(r, 300 * (4 - retries))); // 300 / 600 / 900 ms
return _doSaveRemoteConfig(owner, repo, branch, pluginId, cfg, retries - 1);
}
throw e;
}
}
// ---------------------------------------------------------------------------
// TRMNL archive helpers
// ---------------------------------------------------------------------------
async function fetchArchive(pluginId) {
const res = await fetch(`https://trmnl.com/api/plugin_settings/${pluginId}/archive`);
if (!res.ok) throw new Error(`TRMNL archive fetch failed: ${res.status}`);
const zip = await JSZip.loadAsync(await res.arrayBuffer());
const files = {};
await Promise.all(
Object.entries(zip.files)
.filter(([, e]) => !e.dir)
.map(async ([name, e]) => { files[name] = await e.async('text'); })
);
return files;
}
async function buildAndUpload(pluginId, files) {
const key = getTrmnlKey();
if (!key) throw new Error('TRMNL API key not set. Configure it in the GitHub Sync panel.');
const zip = new JSZip();
for (const [name, content] of Object.entries(files)) {
if (content != null) zip.file(name, content);
}
const raw = await zip.generateAsync({ type: 'blob', compression: 'DEFLATE' });
const blob = new Blob([raw], { type: 'application/zip' });
const fd = new FormData();
fd.append('file', blob, 'archive.zip');
const res = await fetch(`https://trmnl.com/api/plugin_settings/${pluginId}/archive`, {
method: 'POST', headers: { Authorization: `Bearer ${key}` }, body: fd,
});
if (!res.ok) {
const text = await res.text().catch(() => '');
throw new Error(`TRMNL upload ${res.status}${text ? ': ' + text.slice(0, 200) : ''}`);
}
}
// Normalize line endings to \n (GitHub always stores with \n).
// TRMNL's archive may return \r\n, causing false SHA mismatches.
function normalizeLF(s) { return s.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); }
// Compute the git blob SHA that GitHub uses, so we can diff without downloading file content.
// Formula: SHA1("blob " + byteLength + "\0" + content)
async function gitBlobSha(content) {
const enc = new TextEncoder();
const body = enc.encode(normalizeLF(content));
const header = enc.encode(`blob ${body.length}\0`);
const buf = new Uint8Array(header.length + body.length);
buf.set(header);
buf.set(body, header.length);
const digest = await crypto.subtle.digest('SHA-1', buf);
return Array.from(new Uint8Array(digest)).map(b => b.toString(16).padStart(2, '0')).join('');
}
// ---------------------------------------------------------------------------
// Push: TRMNL → GitHub
//
// Uses the Git Trees API to produce a single atomic commit for all files.
// ---------------------------------------------------------------------------
async function push(pluginId, onLog) {
const cfg = getConfig(pluginId);
const { owner, repo } = parseRepo(cfg);
const branch = cfg.branch.trim() || 'main';
const basePath = resolvePath(cfg.path, pluginId);
onLog('Fetching TRMNL archive…');
const files = await fetchArchive(pluginId);
const names = Object.keys(files);
if (!names.length) throw new Error('Plugin archive is empty.');
onLog(`${names.length} files: ${names.join(', ')}`);
// Use name from settings.yml (reliable across all TRMNL pages)
const pluginName = extractNameFromYaml(files['settings.yml'] || files['settings.yaml'] || '');
const message = resolveMsg(cfg.commitMsg, pluginId, pluginName);
// ── Change detection: compare git blob SHAs with what GitHub already has ──
onLog('Checking for changes…');
let currentShas = {};
try {
const dir = await ghFetch(
`/repos/${owner}/${repo}/contents/${basePath}?ref=${encodeURIComponent(branch)}`
);
if (Array.isArray(dir)) {
for (const f of dir) { if (f.type === 'file') currentShas[f.name] = f.sha; }
}
} catch (e) {
if (!e.message.includes('404') && !e.message.includes('409')) throw e;
// 404 = path doesn't exist yet; 409 = repo is empty — treat both as first push (all-new)
}
const trmnlShas = Object.fromEntries(
await Promise.all(names.map(async n => [n, await gitBlobSha(files[n])]))
);
const changed = names.filter(n => trmnlShas[n] !== currentShas[n]);
const deleted = Object.keys(currentShas).filter(n => !files[n]);
if (!changed.length && !deleted.length) {
onLog('Nothing to commit — plugin already matches GitHub.');
return null;
}
onLog(`Changes: ${[...changed, ...deleted.map(n => `${n} (deleted)`)].join(', ')}`);
onLog(`Reading branch "${branch}"…`);
let headSha = null;
let baseTree = null;
let repoIsEmpty = false;
try {
const refData = await ghFetch(`/repos/${owner}/${repo}/git/ref/heads/${encodeURIComponent(branch)}`);
headSha = refData.object.sha;
const headCommit = await ghFetch(`/repos/${owner}/${repo}/git/commits/${headSha}`);
baseTree = headCommit.tree.sha;
} catch (e) {
if (e.message.includes('409')) {
repoIsEmpty = true; // Git Data API unavailable until repo has at least one commit
onLog('Repository is empty — will initialize via Contents API.');
} else if (e.message.includes('404')) {
onLog(`Branch "${branch}" not found — will create it on first push.`);
} else {
throw e;
}
}
// ── Empty repo: Git Data API (blobs/trees/commits) returns 409 on repos with no commits.
// Use the Contents API instead — it works on empty repos and initializes the branch.
// This creates one commit per file; subsequent pushes use the efficient Data API path.
if (repoIsEmpty) {
onLog('Initializing repository…');
const pushedShas = {};
let lastCommitSha = null;
for (const name of names) {
const res = await ghFetch(`/repos/${owner}/${repo}/contents/${basePath}/${name}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: name === names[names.length - 1] ? message : `Initialize: add ${name}`,
content: btoa(unescape(encodeURIComponent(normalizeLF(files[name])))),
branch,
}),
});
pushedShas[name] = res.content.sha;
lastCommitSha = res.commit.sha;
}
setLastPushShas(pluginId, pushedShas);
recordPushTime(pluginId);
onLog(`✓ Pushed ${names.length} files to ${owner}/${repo}/${basePath}`);
return `https://github.com/${owner}/${repo}/commit/${lastCommitSha}`;
}
onLog('Creating blobs…');
// pushedShas maps filename → the exact SHA GitHub assigns to each blob.
// These will eventually match what the Contents API directory listing returns,
// so we store them as our baseline instead of locally-computed SHAs.
const pushedShas = {};
const treeItems = await Promise.all(names.map(async name => {
const blobData = await ghFetch(`/repos/${owner}/${repo}/git/blobs`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content: normalizeLF(files[name]), encoding: 'utf-8' }),
});
pushedShas[name] = blobData.sha;
return { path: `${basePath}/${name}`, mode: '100644', type: 'blob', sha: blobData.sha };
}));
onLog('Creating tree…');
const treePayload = { tree: treeItems };
if (baseTree) treePayload.base_tree = baseTree; // omit for a brand-new empty repo
const tree = await ghFetch(`/repos/${owner}/${repo}/git/trees`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(treePayload),
});
onLog('Creating commit…');
const commit = await ghFetch(`/repos/${owner}/${repo}/git/commits`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message, tree: tree.sha, parents: headSha ? [headSha] : [] }),
});
if (headSha) {
onLog('Updating branch…');
await ghFetch(`/repos/${owner}/${repo}/git/refs/heads/${encodeURIComponent(branch)}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sha: commit.sha, force: true }),
});
} else {
onLog(`Creating branch "${branch}"…`);
await ghFetch(`/repos/${owner}/${repo}/git/refs`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ref: `refs/heads/${branch}`, sha: commit.sha }),
});
}
setLastPushShas(pluginId, pushedShas);
recordPushTime(pluginId);
onLog(`✓ Pushed ${names.length} files to ${owner}/${repo}/${basePath}`);
return `https://github.com/${owner}/${repo}/commit/${commit.sha}`;
}
// ---------------------------------------------------------------------------
// Pull: GitHub → TRMNL
// ---------------------------------------------------------------------------
async function pull(pluginId, onLog) {
const cfg = getConfig(pluginId);
const { owner, repo } = parseRepo(cfg);
if (!getTrmnlKey()) throw new Error('TRMNL API key not configured. Open the GitHub Sync panel to set it.');
const branch = cfg.branch.trim() || 'main';
const basePath = resolvePath(cfg.path, pluginId);
onLog(`Fetching file list from ${owner}/${repo}/${basePath}…`);
let dir;
try {
dir = await ghFetch(`/repos/${owner}/${repo}/contents/${basePath}?ref=${encodeURIComponent(branch)}`);
} catch (e) {
throw new Error(`Could not read path "${basePath}": ${e.message}`);
}
if (!Array.isArray(dir)) throw new Error(`"${basePath}" is not a directory in the repository.`);
const fileEntries = dir.filter(f => f.type === 'file');
if (!fileEntries.length) throw new Error(`No files found at "${basePath}".`);
onLog(`${fileEntries.length} files: ${fileEntries.map(f => f.name).join(', ')}`);
onLog('Downloading files…');
const files = {};
await Promise.all(fileEntries.map(async entry => {
const data = await ghFetch(
`/repos/${owner}/${repo}/contents/${entry.path}?ref=${encodeURIComponent(branch)}`
);
// GitHub returns base64 content with embedded newlines
files[entry.name] = b64ToUtf8(data.content);
}));
onLog('Uploading to TRMNL…');
await buildAndUpload(pluginId, files);
onLog('✓ Pull complete! Redirecting…');
setTimeout(() => {
if (window.Turbo?.cache) window.Turbo.cache.clear();
window.location.href = `https://trmnl.com/plugin_settings/${pluginId}/edit`;
}, 1200);
}
// ---------------------------------------------------------------------------
// DOM helpers
// ---------------------------------------------------------------------------
// Decode a GitHub base64-encoded file content string to a proper UTF-8 string.
// atob() alone returns a binary (Latin-1) string and corrupts non-ASCII characters.
function b64ToUtf8(b64) {
const binary = atob(b64.replace(/\n/g, ''));
const bytes = Uint8Array.from(binary, c => c.charCodeAt(0));
return new TextDecoder().decode(bytes);
}
function mk(tag, cls, text) {
const el = document.createElement(tag);
if (cls) el.className = cls;
if (text !== undefined) el.textContent = text;
return el;
}
function mkInput(placeholder, value, type = 'text') {
const el = mk('input',
'w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg ' +
'bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-gray-100 ' +
'focus:ring-2 focus:ring-blue-500 focus:border-blue-500'
);
el.type = type;
el.placeholder = placeholder;
el.value = value;
el.style.boxSizing = 'border-box';
return el;
}
function mkFieldGroup(labelText) {
const wrap = mk('div', 'mb-4');
wrap.appendChild(mk('label', 'block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1', labelText));
return wrap;
}
function mkSectionHeader(text) {
return mk('p',
'text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400 mb-3',
text
);
}
// ---------------------------------------------------------------------------
// Panel
// ---------------------------------------------------------------------------
// Repo picker — searchable dropdown of the user's GitHub repos
async function showRepoPicker(anchorEl, onSelect) {
const PICKER_ID = 'gh-repo-picker';
document.getElementById(PICKER_ID)?.remove();
const picker = document.createElement('div');
picker.id = PICKER_ID;
picker.className = 'gh-repo-picker';
const searchIn = document.createElement('input');
searchIn.type = 'text';
searchIn.placeholder = 'Search repos…';
searchIn.className = 'gh-repo-picker-search';
searchIn.autocomplete = 'off';
const list = document.createElement('div');
list.className = 'gh-repo-picker-list';
list.textContent = 'Loading…';
picker.append(searchIn, list);
const rect = anchorEl.getBoundingClientRect();
const pickerW = Math.max(rect.width, 300);
const left = Math.min(rect.left, window.innerWidth - pickerW - 8);
picker.style.cssText = `position:fixed;left:${Math.max(8, left)}px;top:${rect.bottom + 4}px;` +
`width:${pickerW}px;z-index:999999;`;
document.body.appendChild(picker);
searchIn.focus();
let repos = [];
function renderList(items) {
list.innerHTML = '';
if (!items.length) { list.textContent = 'No repos found.'; return; }
items.slice(0, 80).forEach(r => {
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'gh-repo-picker-item';
const nameSpan = document.createElement('span');
nameSpan.textContent = r.full_name;
btn.appendChild(nameSpan);
if (r.private) {
const tag = document.createElement('span');
tag.className = 'gh-repo-picker-private';
tag.textContent = 'private';
btn.appendChild(tag);
}
btn.addEventListener('mousedown', e => {
e.preventDefault();
onSelect(r.full_name);
picker.remove();
});
list.appendChild(btn);
});
}
try {
repos = await ghFetch('/user/repos?per_page=100&sort=updated&type=all');
renderList(repos);
} catch(e) {
list.textContent = 'Error: ' + e.message;
}
searchIn.addEventListener('input', () => {
const q = searchIn.value.toLowerCase();
renderList(repos.filter(r => r.full_name.toLowerCase().includes(q)));
});
function onOutsideClick(e) {
if (!picker.contains(e.target)) {
picker.remove();
document.removeEventListener('mousedown', onOutsideClick);
}
}
setTimeout(() => document.addEventListener('mousedown', onOutsideClick), 0);
}
// remoteCfg: the per-plugin object read directly from the GitHub config repo.
// When present it is the source of truth; localStorage is only the fallback cache.
function buildPanel(pluginId, remoteCfg = null) {
const overlay = mk('div', '');
overlay.id = OVERLAY_ID;
overlay.addEventListener('click', closePanel);
const panel = mk('div', '');
panel.id = PANEL_ID;
// ── Header ────────────────────────────────────────────────────────────────
const hdr = mk('div',
'flex items-center justify-between px-5 py-4 border-b border-gray-200 dark:border-gray-700 flex-shrink-0'
);
const iconBtnCls =
'w-8 h-8 flex items-center justify-center rounded-lg text-gray-400 ' +
'hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors';
const closeBtn = mk('button', iconBtnCls, '✕');
closeBtn.type = 'button';
closeBtn.addEventListener('click', closePanel);
const title = mk('div', 'flex items-center gap-2');
title.innerHTML = ghIcon(15);
title.appendChild(mk('span', 'text-sm font-semibold text-gray-900 dark:text-gray-100', 'GitHub Sync'));
// Expand / restore panel width toggle
let panelExpanded = false;
const expandPanelBtn = mk('button', iconBtnCls);
expandPanelBtn.type = 'button';
expandPanelBtn.title = 'Expand panel';
expandPanelBtn.innerHTML =
`<svg width="14" height="14" viewBox="0 0 256 256" fill="currentColor">` +
`<path d="M224,48V96a8,8,0,0,1-16,0V67.31l-50.34,50.35a8,8,0,0,1-11.32-11.32L196.69,56H168a8,8,0,0,1,0-16h48A8,8,0,0,1,224,48ZM106.34,138.34,56,188.69V160a8,8,0,0,0-16,0v48a8,8,0,0,0,8,8H96a8,8,0,0,0,0-16H67.31l50.35-50.34a8,8,0,0,0-11.32-11.32Z"/>` +
`</svg>`;
expandPanelBtn.addEventListener('click', () => {
panelExpanded = !panelExpanded;
panel.style.width = panelExpanded ? 'min(95vw, 1100px)' : '';
expandPanelBtn.title = panelExpanded ? 'Restore panel size' : 'Expand panel';
expandPanelBtn.innerHTML = panelExpanded
? `<svg width="14" height="14" viewBox="0 0 256 256" fill="currentColor"><path d="M221.66,165.66l-48,48a8,8,0,0,1-11.32-11.32L204.69,160H176a8,8,0,0,1,0-16h48a8,8,0,0,1,8,8v48a8,8,0,0,1-16,0V171.31ZM80,96H51.31l42.35-42.34A8,8,0,0,0,82.34,42.34l-48,48A8,8,0,0,0,32,96v48a8,8,0,0,0,16,0V115.31l42.34,42.35a8,8,0,0,0,11.32-11.32Z"/></svg>`
: `<svg width="14" height="14" viewBox="0 0 256 256" fill="currentColor"><path d="M224,48V96a8,8,0,0,1-16,0V67.31l-50.34,50.35a8,8,0,0,1-11.32-11.32L196.69,56H168a8,8,0,0,1,0-16h48A8,8,0,0,1,224,48ZM106.34,138.34,56,188.69V160a8,8,0,0,0-16,0v48a8,8,0,0,0,8,8H96a8,8,0,0,0,0-16H67.31l50.35-50.34a8,8,0,0,0-11.32-11.32Z"/></svg>`;
});
const hdrBtns = mk('div', 'flex items-center gap-1 ml-auto');
hdrBtns.append(expandPanelBtn, closeBtn);
hdr.append(title, hdrBtns);
panel.appendChild(hdr);
// ── Scrollable body ───────────────────────────────────────────────────────
const scroll = mk('div', 'flex-1 overflow-y-auto');
// ── Shared helper: chip+Change / Not set+Set pattern for secret fields ────
function mkSecretSection(sectionTitle, currentValue, placeholder, hint, saveFn) {
const sec = mk('div', 'px-5 py-4 border-b border-gray-200 dark:border-gray-700');
sec.appendChild(mkSectionHeader(sectionTitle));
const chipSetCls = 'gh-chip-set';
const chipUnsetCls = 'gh-chip-unset';
const linkBtnCls = 'gh-link-btn';
const primaryBtnCls =
'cursor-pointer font-medium rounded-lg text-xs px-3 py-1.5 inline-flex items-center ' +
'transition duration-150 gap-1.5 border-0 ' +
'text-white bg-primary-500 dark:bg-primary-600 hover:bg-primary-600 dark:hover:bg-primary-500';
const row = mk('div', 'flex items-center gap-2 flex-wrap');
const inputWrap = mk('div', 'w-full mt-2 hidden');
const inp = mkInput(placeholder, currentValue, 'password');
inputWrap.appendChild(inp);
if (currentValue) {
const chip = mk('span', chipSetCls, '✓ Saved');
const changeBtn = mk('button', linkBtnCls, 'Change');
changeBtn.type = 'button';
changeBtn.style.setProperty('background', 'none', 'important');
changeBtn.addEventListener('click', () => {
inputWrap.classList.toggle('hidden');
if (!inputWrap.classList.contains('hidden')) inp.focus();
});
inp.addEventListener('change', () => {
const v = inp.value.trim();
saveFn(v);
chip.textContent = v ? '✓ Saved' : 'Cleared — reload panel';
});
row.append(chip, changeBtn);
} else {
const chip = mk('span', chipUnsetCls, 'Not set');
const setBtn = mk('button', primaryBtnCls, 'Set');
setBtn.type = 'button';
setBtn.addEventListener('click', () => {
inputWrap.classList.toggle('hidden');
if (!inputWrap.classList.contains('hidden')) inp.focus();
});
const saveBtn = mk('button', primaryBtnCls, 'Save');
saveBtn.type = 'button';
saveBtn.addEventListener('click', () => {
const v = inp.value.trim();
if (!v) return;
saveFn(v);
chip.className = chipSetCls;
chip.textContent = '✓ Saved';
inputWrap.classList.add('hidden');
});
inputWrap.appendChild(saveBtn);
row.append(chip, setBtn);
}
sec.append(row, inputWrap);
if (hint) sec.appendChild(hint);
return sec;
}
// ── Global Setup (collapsible) ────────────────────────────────────────────
function isGlobalConfigured() {
return !!(getToken() && getTrmnlKey() && getConfigRepo());
}
const globalSec = mk('div', 'border-b border-gray-200 dark:border-gray-700 flex-shrink-0');
const globalHdr = mk('div',
'gh-global-hdr flex items-center justify-between px-5 py-3 cursor-pointer select-none ' +
'hover:bg-gray-50 transition-colors'
);
const globalArrow = mk('span', 'text-gray-500 dark:text-gray-400 text-xs mr-2', isGlobalConfigured() ? '▸' : '▾');
const globalTitleRow = mk('div', 'flex items-center');
globalTitleRow.append(globalArrow, mk('span',
'text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400', 'Global Setup'
));
const globalChip = mk('span', isGlobalConfigured() ? 'gh-chip-set' : 'gh-chip-unset',
isGlobalConfigured() ? '✓ Ready' : 'Setup required'
);
globalHdr.append(globalTitleRow, globalChip);
const globalBody = mk('div', 'px-5 pb-5 pt-3 space-y-4');
globalBody.style.display = isGlobalConfigured() ? 'none' : '';
globalHdr.addEventListener('click', () => {
const open = globalBody.style.display !== 'none';
globalBody.style.display = open ? 'none' : '';
globalArrow.textContent = open ? '▸' : '▾';