-
Notifications
You must be signed in to change notification settings - Fork 627
Expand file tree
/
Copy pathworkspace.ts
More file actions
1858 lines (1630 loc) · 64.5 KB
/
workspace.ts
File metadata and controls
1858 lines (1630 loc) · 64.5 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
/// <reference path="../../built/pxtlib.d.ts" />
import * as db from "./db";
import * as core from "./core";
import * as data from "./data";
import * as browserworkspace from "./browserworkspace"
import * as fileworkspace from "./fileworkspace"
import * as memoryworkspace from "./memoryworkspace"
import * as iframeworkspace from "./iframeworkspace"
import * as cloudsync from "./cloudsync"
import * as indexedDBWorkspace from "./idbworkspace";
import * as compiler from "./compiler"
import * as auth from "./auth"
import * as cloud from "./cloud"
import * as pxteditor from "../../pxteditor";
import U = pxt.Util;
import Cloud = pxt.Cloud;
import * as pxtblockly from "../../pxtblocks";
import { getTextAtTime, HistoryFile } from "../../pxteditor/history";
import { Milestones } from "./constants";
// Avoid importing entire crypto-js
/* eslint-disable import/no-internal-modules */
const sha1 = require("crypto-js/sha1");
type Header = pxt.workspace.Header;
type ScriptText = pxt.workspace.ScriptText;
type WorkspaceProvider = pxt.workspace.WorkspaceProvider;
type InstallHeader = pxt.workspace.InstallHeader;
type File = pxt.workspace.File;
let allScripts: File[] = [];
let headerQ = new U.PromiseQueue();
let impl: WorkspaceProvider;
let implType: string;
export function getWorkspaceType(): string {
return implType
}
function lookup(id: string) {
return allScripts.find(x => x.header.id == id || x.header.path == id);
}
export function gitsha(data: string, encoding: "utf-8" | "base64" = "utf-8") {
if (encoding == "base64") {
const d = atob(data);
return (sha1("blob " + d.length + "\u0000" + d) + "")
} else
return (sha1("blob " + U.toUTF8(data).length + "\u0000" + data) + "")
}
export async function copyProjectToLegacyEditor(header: Header, majorVersion: number): Promise<Header> {
if (!isBrowserWorkspace()) {
return Promise.reject("Copy operation only works in browser workspace");
}
const script = await getTextAsync(header.id);
const newHeader = pxt.Util.clone(header);
delete (newHeader as any)._id;
delete newHeader._rev;
newHeader.id = pxt.Util.guidGen();
// We don't know if the legacy editor uses the indexedDB or PouchDB workspace, so we're going
// to copy the project to both places
try {
await browserworkspace.copyProjectToLegacyEditor(newHeader, script, majorVersion);
}
catch (e) {
pxt.reportException(e);
pxt.log("Unable to port project to PouchDB")
}
await indexedDBWorkspace.copyProjectToLegacyEditorAsync(newHeader, script, majorVersion);
return newHeader;
}
export function setupWorkspace(id: string) {
U.assert(!impl, "workspace set twice");
pxt.log(`workspace: ${id}`);
implType = id ?? "browser";
switch (id) {
case "fs":
case "file":
// Local file workspace, serializes data under target/projects/
impl = fileworkspace.provider;
break;
case "mem":
case "memory":
impl = memoryworkspace.provider;
break;
case "iframe":
// Iframe workspace, the editor relays sync messages back and forth when hosted in an iframe
impl = iframeworkspace.provider;
break;
case "pouch":
impl = browserworkspace.provider
break;
case "idb":
case "browser":
default:
impl = indexedDBWorkspace.provider;
break;
}
}
async function switchToMemoryWorkspace(reason: string): Promise<void> {
pxt.log(`workspace: error '${reason}', switching from ${implType} to memory workspace`);
const expectedMemWs = pxt.appTarget.appTheme.disableMemoryWorkspaceWarning
|| impl === memoryworkspace.provider
|| pxt.shell.isSandboxMode() || pxt.shell.isReadOnly() || pxt.BrowserUtils.isIFrame();
pxt.tickEvent(`workspace.syncerror`, {
ws: implType,
reason: reason,
expected: expectedMemWs ? 1 : 0
});
if (!expectedMemWs) {
await core.confirmAsync({
header: lf("Warning! Project Auto-Save Disabled"),
body: lf("We are unable to save your projects at this time. You can still manually save your project via direct download, or sharing your project."),
agreeLbl: lf("Continue"),
headerIcon: "warning",
agreeClass: "cancel",
agreeIcon: "cancel",
helpUrl: "/browsers/no-auto-save",
className: "auto-save-disabled-warning",
hasCloseIcon: true,
});
}
impl = memoryworkspace.provider;
implType = "mem";
}
export function getHeaders(withDeleted = false, filterByEditorType = true, cloudUserIdOverride?: string) {
maybeSyncHeadersAsync();
const cloudUserId = cloudUserIdOverride ?? auth.userProfile()?.id;
let r = allScripts.map(e => e.header).filter(h =>
// Filter deleted projects
(withDeleted || !h.isDeleted) &&
// Hide backup projects
!h.isBackup &&
// Filter to local projects and projects belonging to this signed in user
(!h.cloudUserId || h.cloudUserId === cloudUserId));
if (filterByEditorType) {
// If this is the skillmap editor, filter to only skillmap projects, otherwise filter out skillmap projects
r = r.filter(h => !!h.isSkillmapProject === pxt.BrowserUtils.isSkillmapEditor());
}
r.sort((a, b) => {
const aTime = a.cloudUserId ? Math.min(a.cloudLastSyncTime, a.modificationTime) : a.modificationTime
const bTime = b.cloudUserId ? Math.min(b.cloudLastSyncTime, b.modificationTime) : b.modificationTime
return bTime - aTime
})
return r
}
export function makeBackupAsync(h: Header, text: ScriptText): Promise<Header> {
let h2 = U.flatClone(h)
h2.id = U.guidGen()
delete h2._rev
delete (h2 as any)._id
h2.isBackup = true;
return importAsync(h2, text)
.then(() => {
h.backupRef = h2.id;
return forceSaveAsync(h2);
})
.then(() => h2)
}
export function restoreFromBackupAsync(h: Header) {
if (!h.backupRef || h.isDeleted) return Promise.resolve();
const refId = h.backupRef;
return getTextAsync(refId)
.then(files => {
delete h.backupRef;
return forceSaveAsync(h, files);
})
.then(() => {
const backup = getHeader(refId);
backup.isDeleted = true;
return forceSaveAsync(backup);
})
.catch(() => {
delete h.backupRef;
return forceSaveAsync(h);
});
}
function cleanupBackupsAsync() {
const allHeaders = allScripts.map(e => e.header);
const refMap: pxt.Map<boolean> = {};
// Figure out which scripts have backups
allHeaders.filter(h => h.backupRef).forEach(h => refMap[h.backupRef] = true);
// Delete the backups that don't have any scripts referencing them
return Promise.all(allHeaders.filter(h => (h.isBackup && !refMap[h.id])).map(h => {
h.isDeleted = true;
return forceSaveAsync(h);
}));
}
export function getHeader(id: string) {
maybeSyncHeadersAsync();
let e = lookup(id)
if (e && !e.header.isDeleted)
return e.header
return null
}
// this key is the max modificationTime value of the allHeaders
// it is used to track if allHeaders need to be refreshed (syncAsync)
let sessionID: string = "";
export function isHeadersSessionOutdated() {
return pxt.storage.getLocal('workspacesessionid') != sessionID;
}
function maybeSyncHeadersAsync(): Promise<void> {
if (isHeadersSessionOutdated()) // another tab took control
return syncAsync().then(() => { })
return Promise.resolve();
}
export function computeSessionId(hdrs: Header[]): string {
// use # of scripts + time of last mod as key
return hdrs.length + ' ' + hdrs
.map(h => h.modificationTime)
.reduce((l, r) => Math.max(l, r), 0)
.toString()
}
function refreshHeadersSession() {
sessionID = computeSessionId(allScripts.map(f => f.header))
if (isHeadersSessionOutdated()) {
pxt.storage.setLocal('workspacesessionid', sessionID);
pxt.debug(`workspace: refreshed headers session to ${sessionID}`);
data.invalidate("header:*");
data.invalidate("text:*");
}
}
// this is an identifier for the current frame
// in order to lock headers for editing
const workspaceID: string = pxt.Util.guidGen();
export function acquireHeaderSession(h: Header) {
if (h)
pxt.storage.setLocal('workspaceheadersessionid:' + h.id, workspaceID);
}
function clearHeaderSession(h: Header) {
if (h)
pxt.storage.removeLocal('workspaceheadersessionid:' + h.id);
}
export function isHeaderSessionOutdated(h: Header): boolean {
if (!h) return false;
const sid = pxt.storage.getLocal('workspaceheadersessionid:' + h.id);
return sid && sid != workspaceID;
}
function checkHeaderSession(h: Header): void {
if (isHeaderSessionOutdated(h)) {
pxt.tickEvent(`workspace.conflict.header`);
core.errorNotification(lf("This project is already opened elsewhere."))
pxt.debug(`saved session ID: ${pxt.storage.getLocal('workspaceheadersessionid:' + h.id)}`)
pxt.debug(`our session ID: ${workspaceID}`)
pxt.Util.assert(false, "trying to access outdated session")
}
}
// helps know when we last synced with the cloud (in seconds since epoch)
export function getHeaderLastCloudSync(h: Header): number {
return h.cloudLastSyncTime || 0/*never*/
}
export function getLastCloudSync(): number {
if (!auth.loggedIn())
return 0;
const userId = auth.userProfile()?.id;
const cloudHeaders = getHeaders(true)
.filter(h => h.cloudUserId && h.cloudUserId === userId);
if (!cloudHeaders.length)
return 0
return Math.min(...cloudHeaders.map(getHeaderLastCloudSync))
}
export function initAsync() {
if (!impl) {
impl = indexedDBWorkspace.provider;
implType = "browser";
}
return syncAsync()
.then(state => cleanupBackupsAsync().then(() => state))
.then(_ => {
pxt.perf.recordMilestone(Milestones.WorkspaceInitFinished)
return _
})
}
export async function getTextAsync(id: string, getSavedText = false): Promise<ScriptText> {
await maybeSyncHeadersAsync();
const e = lookup(id);
if (!e) return null;
if (e.text && !getSavedText) {
return e.text;
}
return headerQ.enqueue(id, async () => {
const resp = await impl.getAsync(e.header);
const fixedText = fixupFileNames(resp.text);
if (getSavedText) {
return fixedText;
}
else if (!e.text) {
e.text = fixedText;
}
e.version = resp.version;
return e.text
});
}
export async function saveSnapshotAsync(id: string): Promise<void> {
await enqueueHistoryOperationAsync(
id,
text => {
pxteditor.history.pushSnapshotOnHistory(text, Date.now())
}
);
}
export async function updateShareHistoryAsync(id: string): Promise<void> {
await enqueueHistoryOperationAsync(
id,
(text, header) => {
pxteditor.history.updateShareHistory(text, Date.now(), header.pubVersions || [])
}
);
}
async function enqueueHistoryOperationAsync(id: string, op: (text: ScriptText, header: Header) => void) {
await maybeSyncHeadersAsync();
const e = lookup(id);
if (!e) return;
await headerQ.enqueue(id, async () => {
const saved = await impl.getAsync(e.header);
const h = saved.header;
op(saved.text, h);
const ver = await impl.setAsync(h, saved.version, saved.text);
e.version = ver;
data.invalidate("text:" + h.id);
data.invalidate("pkg-git-status:" + h.id);
data.invalidateHeader("header", h);
refreshHeadersSession();
});
}
export interface ScriptMeta {
description: string;
blocksWidth?: number;
blocksHeight?: number;
}
function getScriptRequest(h: Header, text: ScriptText, meta: ScriptMeta, screenshotUri?: string) {
let thumbnailBuffer: string;
let thumbnailMimeType: string;
if (screenshotUri) {
const m = /^data:(image\/(png|gif));base64,([a-zA-Z0-9+/]+=*)$/.exec(screenshotUri);
if (m) {
thumbnailBuffer = m[3];
thumbnailMimeType = m[1];
}
}
return {
id: h.id,
shareId: h.pubPermalink,
name: h.name,
target: h.target,
targetVersion: h.targetVersion,
description: meta.description || lf("Made with ❤️ in {0}.", pxt.appTarget.title || pxt.appTarget.name),
editor: h.editor,
header: JSON.stringify(cloud.excludeLocalOnlyMetadataFields(h)),
text: JSON.stringify(text),
meta: {
versions: pxt.appTarget.versions,
blocksHeight: meta.blocksHeight,
blocksWidth: meta.blocksWidth
},
thumbnailBuffer,
thumbnailMimeType
}
}
// https://github.com/Microsoft/pxt-backend/blob/master/docs/sharing.md#anonymous-publishing
export async function anonymousPublishAsync(h: Header, text: ScriptText, meta: ScriptMeta, screenshotUri?: string) {
checkHeaderSession(h);
const saveId = {}
h.saveId = saveId
const scrReq = getScriptRequest(h, text, meta, screenshotUri)
pxt.debug(`publishing script; ${scrReq.text.length} bytes`)
const inf = await Cloud.privatePostAsync("scripts", scrReq, /* forceLiveEndpoint */ true) as Cloud.JsonScript;
if (!h.pubVersions) h.pubVersions = [];
h.pubVersions.push({ id: inf.id, type: "snapshot" });
if (inf.shortid) inf.id = inf.shortid;
h.pubId = inf.shortid
h.pubCurrent = h.saveId === saveId
h.meta = inf.meta;
pxt.debug(`published; id /${h.pubId}`)
await saveAsync(h);
await updateShareHistoryAsync(h.id);
return inf;
}
export async function persistentPublishAsync(h: Header, text: ScriptText, meta: ScriptMeta, screenshotUri?: string) {
checkHeaderSession(h);
const saveId = {}
h.saveId = saveId
const scrReq = getScriptRequest(h, text, meta, screenshotUri)
pxt.debug(`publishing script; ${scrReq.text.length} bytes`)
const { shareID, scr: script } = await cloud.shareAsync(h.id, scrReq);
if (!h.pubVersions) h.pubVersions = [];
h.pubVersions.push({ id: script.id, type: "permalink" });
h.pubId = shareID
h.pubCurrent = h.saveId === saveId
h.pubPermalink = shareID;
h.meta = script.meta;
pxt.debug(`published; id /${h.pubId}`)
await saveAsync(h);
await updateShareHistoryAsync(h.id);
return h;
}
function fixupVersionAsync(e: File) {
if (e.version !== undefined)
return Promise.resolve()
return impl.getAsync(e.header)
.then(resp => {
e.version = resp.version;
})
}
export function forceSaveAsync(h: Header, text?: ScriptText, isCloud?: boolean): Promise<void> {
clearHeaderSession(h);
return saveAsync(h, text, isCloud);
}
interface Change<K, V> {
kind: 'add' | 'del' | 'mod'
key: K,
oldVal?: V,
newVal?: V,
}
interface ProjectChanges {
header: Change<keyof Header, string>[],
files: Change<string, number>[],
}
function computeChangeSummary(a: {header: Header, text: ScriptText}, b: {header: Header, text: ScriptText}): ProjectChanges {
const aHdr = a.header || {} as Header
const bHdr = b.header || {} as Header
const aTxt = a.text || {}
const bTxt = b.text || {}
// headers
type HeaderK = keyof Header
const hdrKeys = U.unique([...Object.keys(aHdr), ...Object.keys(bHdr)], s => s) as HeaderK[]
const hasObjChanged = (a: any, b: any) => JSON.stringify(a) !== JSON.stringify(b)
const hasHdrChanged = (k: HeaderK) => hasObjChanged(aHdr[k], bHdr[k])
const hdrChanges = hdrKeys.filter(hasHdrChanged)
const hdrDels = hdrChanges.filter(k => (k in aHdr) && !(k in bHdr))
.map(k => ({kind: 'del', key: k, oldVal: aHdr[k]}) as Change<HeaderK, string>)
const hdrAdds = hdrChanges.filter(k => !(k in aHdr) && (k in bHdr))
.map(k => ({kind: 'add', key: k, newVal: bHdr[k]}) as Change<HeaderK, string>)
const hdrMods = hdrChanges.filter(k => (k in aHdr) && (k in bHdr))
.map(k => ({kind: 'mod', key: k, oldVal: aHdr[k], newVal: bHdr[k]}) as Change<HeaderK, string>)
// files
const filenames = U.unique([...Object.keys(aTxt), ...Object.keys(bTxt)], s => s)
const hasFileChanged = (filename: string) => aTxt[filename] !== bTxt[filename]
const fileChanges = filenames.filter(hasFileChanged)
const fileDels = fileChanges.filter(k => (k in aTxt) && !(k in bTxt) && !!b.text)
.map(k => ({kind: 'del', key: k, oldVal: aTxt[k].length}) as Change<string, number>)
const fileAdds = fileChanges.filter(k => !(k in aTxt) && (k in bTxt))
.map(k => ({kind: 'add', key: k, newVal: bTxt[k].length}) as Change<string, number>)
const fileMods = fileChanges.filter(k => (k in aTxt) && (k in bTxt))
.map(k => ({kind: 'mod', key: k, oldVal: aTxt[k].length, newVal: bTxt[k].length}) as Change<string, number>)
return {
header: [...hdrDels, ...hdrAdds, ...hdrMods],
files: [...fileDels, ...fileAdds, ...fileMods],
}
}
// useful for debugging
function stringifyChangeSummary(diff: ProjectChanges): string {
const indent = (s: string) => '\t' + s
const changeToStr = (c: Change<any,any>) => `${c.kind} ${c.key}: (${c.oldVal || ''}) => (${c.newVal || ''})`
let res = ''
const hdrDels = diff.header.filter(k => k.kind === 'del')
const hdrAdds = diff.header.filter(k => k.kind === 'add')
const hdrMods = diff.header.filter(k => k.kind === 'mod')
res += `HEADER (+${hdrAdds.length}-${hdrDels.length}~${hdrMods.length})`
res += '\n'
const hdrStrs = diff.header.map(changeToStr)
res += hdrStrs.map(indent).join("\n")
res += '\n'
const fileDels = diff.files.filter(k => k.kind === 'del')
const fileAdds = diff.files.filter(k => k.kind === 'add')
const fileMods = diff.files.filter(k => k.kind === 'mod')
res += `FILES (+${fileAdds.length}-${fileDels.length}~${fileMods.length})`
res += '\n'
const fileStrs = diff.files.map(changeToStr)
res += fileStrs.map(indent).join("\n")
res += '\n'
return res;
}
export async function partialSaveAsync(id: string, filename: string, content: string): Promise<void> {
const prev = lookup(id);
if (!prev) {
pxt.log("Failed to save to unknown project: " + id);
pxt.tickEvent(`workspace.invalidSaveToUnknownProject`);
return;
}
const newTxt = {...await getTextAsync(id)}
newTxt[filename] = content;
return saveAsync(prev.header, newTxt);
}
export async function saveAsync(h: Header, text?: ScriptText, fromCloudSync?: boolean): Promise<void> {
pxt.debug(`workspace.saveAsync ${dbgHdrToString(h)}`)
if (h.isDeleted)
clearHeaderSession(h);
checkHeaderSession(h);
U.assert(h.target == pxt.appTarget.id);
if (h.temporary)
return Promise.resolve()
let e = lookup(h.id)
const newSave = !e
if (newSave) {
e = {
header: h,
text,
version: null
}
}
const hasUserFileChanges = () => {
// we see lots of frequent "saves" that don't come from real changes made by the user. This
// causes problems for cloud sync since this can cause us to think the user is making when
// just reading a project. The "correct" solution would be to have a full history and .gitignore
// file.
if (newSave) {
// new project
return true
}
const prevProj = e
const allChanges = computeChangeSummary(prevProj, {header: h, text})
const ignoredFiles = [GIT_JSON, pxt.SIMSTATE_JSON, pxt.SERIAL_EDITOR_FILE]
const ignoredHeaderFields: (keyof Header)[] = ['recentUse', 'modificationTime', 'cloudCurrent', '_rev', '_id' as keyof Header, 'cloudVersion']
const userChanges: ProjectChanges = {
header: allChanges.header.filter(f => ignoredHeaderFields.indexOf(f.key) < 0),
files: allChanges.files.filter(f => ignoredFiles.indexOf(f.key) < 0)
}
const hasUserChanges = userChanges.header.length > 0 || userChanges.files.length > 0
if (hasUserChanges) {
pxt.debug("user changes:")
pxt.debug(stringifyChangeSummary(userChanges))
}
return hasUserChanges;
}
const isHeaderOnlyChange = !fromCloudSync && !text;
const isUserChange = !fromCloudSync
&& (h.isDeleted || text && hasUserFileChanges())
if (isHeaderOnlyChange || isUserChange) {
h.pubCurrent = false
h.cloudCurrent = false
h.modificationTime = U.nowSeconds();
h.targetVersion = h.targetVersion || "0.0.0";
// cloud user association
if (auth.hasIdentity() && auth.loggedIn()) {
h.cloudUserId = auth.userProfile()?.id
}
}
if (!fromCloudSync)
h.recentUse = U.nowSeconds()
if (!newSave) {
// persist header changes to our local cache, but keep the old
// reference around because (unfortunately) other layers (e.g. package.ts)
// assume the reference is stable per id.
Object.assign(e.header, h);
// Delete keys from `e.header` that don't exist in `h`. This will clear cloud state
// from the header in the case where the project is being exported to local from cloud.
Object.keys(e.header)
.filter(key => h[key as keyof Header] === undefined)
.forEach(key => delete e.header[key as keyof Header]);
h = e.header;
}
if (text)
e.text = text
if (text || h.isDeleted) {
h.saveId = null
}
// check if we have dynamic boards, store board info for home page rendering
if (text && pxt.appTarget.simulator && pxt.appTarget.simulator.dynamicBoardDefinition) {
const pxtjson = pxt.Package.parseAndValidConfig(text[pxt.CONFIG_NAME]);
if (pxtjson && pxtjson.dependencies)
h.board = Object.keys(pxtjson.dependencies)
.filter(p => !!pxt.bundledSvg(p))[0];
}
return headerQ.enqueue<void>(h.id, async () => {
await fixupVersionAsync(e);
let ver: any;
let toWrite = text ? e.text : null;
if (pxt.appTarget.appTheme.timeMachine) {
try {
const previous = await impl.getAsync(h);
if (previous) {
if (!toWrite && previous.header.pubVersions?.length !== h.pubVersions?.length) {
toWrite = { ...previous.text };
}
if (toWrite) {
pxteditor.history.updateHistory(previous.text, toWrite, Date.now(), h.pubVersions || [], diffText, patchText);
}
}
}
catch (e) {
// If this fails for some reason, the history is going to end
// up being corrupted. Should we switch to memory db?
pxt.reportException(e);
pxt.warn("Unable to update project history", e);
}
}
try {
ver = await impl.setAsync(h, e.version, toWrite);
} catch (e) {
// Write failed; use in memory db.
await switchToMemoryWorkspace("write failed");
ver = await impl.setAsync(h, e.version, toWrite);
}
if (!ver && text) {
// write failed due to conflict
pxt.debug('write rejected due to version conflict!')
}
if (text) {
e.version = ver;
}
if (newSave) {
allScripts.push(e);
}
if (isUserChange) {
h.pubCurrent = false;
h.cloudCurrent = false;
h.saveId = null;
}
if (text || h.isDeleted) {
data.invalidate("text:" + h.id);
data.invalidate("pkg-git-status:" + h.id);
}
data.invalidateHeader("header", h);
if (newSave) {
// the count of headers has changed
data.invalidate("headers:");
}
refreshHeadersSession();
});
}
function computePath(h: Header) {
let path = h.name.replace(/[^a-zA-Z0-9]+/g, " ").trim().replace(/ /g, "-")
if (!path)
path = "Untitled"; // do not translate
if (lookup(path)) {
let n = 2
while (lookup(path + "-" + n))
n++;
path += "-" + n
}
return path
}
function diffText(a: string, b: string) {
return pxt.diff.computePatch(a, b);
}
function patchText(patch: unknown, a: string) {
return pxt.diff.applyPatch(a, patch as any)
}
export function restoreTextToTime(text: ScriptText, history: HistoryFile, timestamp: number) {
return getTextAtTime(text, history, timestamp, patchText);
}
export function importAsync(h: Header, text: ScriptText, isCloud = false) {
h.path = computePath(h)
return forceSaveAsync(h, text, isCloud)
}
export async function installAsync(h0: InstallHeader, text: ScriptText, dontOverwriteID = false) {
U.assert(h0.target == pxt.appTarget.id);
const h = <Header>h0
if (!dontOverwriteID) h.id = ts.pxtc.Util.guidGen();
h.recentUse = U.nowSeconds()
h.modificationTime = h.recentUse;
const cfg: pxt.PackageConfig = pxt.Package.parseAndValidConfig(text[pxt.CONFIG_NAME]);
if (cfg && cfg.preferredEditor) {
h.editor = cfg.preferredEditor
pxt.shell.setEditorLanguagePref(cfg.preferredEditor);
}
await pxt.github.cacheProjectDependenciesAsync(cfg)
await importAsync(h, text);
return h;
}
export async function renameAsync(h: Header, newName: string): Promise<Header> {
const text = await getTextAsync(h.id);
let newHdr = U.flatClone(h)
const dupText = U.flatClone(text);
newHdr.name = newName;
const cfg = JSON.parse(text[pxt.CONFIG_NAME]) as pxt.PackageConfig;
cfg.name = newHdr.name;
dupText[pxt.CONFIG_NAME] = pxt.Package.stringifyConfig(cfg);
await importAsync(newHdr, dupText);
return newHdr;
}
export async function duplicateAsync(h: Header, newName?: string, newText?: ScriptText): Promise<Header> {
const text = newText || (await getTextAsync(h.id));
if (!newName)
newName = createDuplicateName(h);
let newHdr = U.flatClone(h)
const dupText = U.flatClone(text);
newHdr.id = U.guidGen()
newHdr.name = newName;
const cfg = JSON.parse(text[pxt.CONFIG_NAME]) as pxt.PackageConfig;
cfg.name = newHdr.name;
dupText[pxt.CONFIG_NAME] = pxt.Package.stringifyConfig(cfg);
delete newHdr._rev;
delete (newHdr as any)._id;
// Clear github metadata
delete newHdr.githubCurrent;
delete newHdr.githubId;
delete newHdr.githubTag;
// Clear publish metadata
delete newHdr.pubVersions;
delete newHdr.pubPermalink;
delete newHdr.anonymousSharePreference;
newHdr.pubId = "";
newHdr.pubCurrent = false;
if (newHdr.cloudVersion) {
pxt.tickEvent(`identity.duplicatingCloudProject`);
}
// drop cloud-related local metadata
newHdr = cloud.excludeLocalOnlyMetadataFields(newHdr)
return importAsync(newHdr, dupText)
.then(() => newHdr)
}
export function createDuplicateName(h: Header) {
let reducedName = h.name.indexOf("#") > -1 ?
h.name.substring(0, h.name.lastIndexOf('#')).trim() : h.name;
let names = U.toDictionary(allScripts.filter(e => !e.header.isDeleted), e => e.header.name)
let n = 2
while (names.hasOwnProperty(reducedName + " #" + n))
n++
return reducedName + " #" + n;
}
export function saveScreenshotAsync(h: Header, data: string, icon: string) {
checkHeaderSession(h);
return impl.saveScreenshotAsync
? impl.saveScreenshotAsync(h, data, icon)
: Promise.resolve();
}
export function fixupFileNames(txt: ScriptText) {
if (!txt) return txt;
["kind.json", "yelm.json"].forEach(oldName => {
if (!txt[pxt.CONFIG_NAME] && txt[oldName]) {
txt[pxt.CONFIG_NAME] = txt[oldName]
delete txt[oldName]
}
})
return txt
}
const scriptDlQ = new U.PromiseQueue();
export async function getPublishedScriptAsync(id: string) {
if (pxt.github.isGithubId(id))
id = pxt.github.normalizeRepoId(id)
const config = await pxt.packagesConfigAsync()
const eid = encodeURIComponent(pxt.github.upgradedPackageId(config, id))
return await scriptDlQ.enqueue(eid, async () => {
let files: ScriptText
const scriptCache = await getScriptCacheAsync();
try {
files = (await scriptCache.getAsync(eid)).files
} catch {
if (pxt.github.isGithubId(id)) {
files = (await pxt.github.downloadPackageAsync(id, config)).files
} else {
files = await (Cloud.downloadScriptFilesAsync(id)
.catch(core.handleNetworkError))
}
try {
await scriptCache.setAsync({ id: eid, files: files })
}
catch (e) {
// Don't fail if the indexeddb fails, but log it
pxt.log("Unable to cache script in DB");
}
}
return fixupFileNames(files)
})
}
export enum PullStatus {
NoSourceControl,
UpToDate,
GotChanges,
NeedsCommit,
BranchNotFound
}
const GIT_JSON = pxt.github.GIT_JSON
type GitJson = pxt.github.GitJson
export async function hasPullAsync(hd: Header) {
return (await pullAsync(hd, true)) == PullStatus.GotChanges
}
export async function pullAsync(hd: Header, checkOnly = false) {
let files = await getTextAsync(hd.id)
await recomputeHeaderFlagsAsync(hd, files)
let gitjsontext = files[GIT_JSON]
if (!gitjsontext)
return PullStatus.NoSourceControl
let gitjson = JSON.parse(gitjsontext) as GitJson
let parsed = pxt.github.parseRepoId(gitjson.repo)
const branch = parsed.tag;
const sha = await pxt.github.getRefAsync(parsed.slug, branch)
if (!sha) {
// 404: branch does not exist, repo is gone or no rights to access repo
// try to get the list of heads to see if we can access the project
const heads = await pxt.github.listRefsAsync(parsed.slug, "heads");
if (heads && heads.length)
return PullStatus.BranchNotFound;
else
return PullStatus.NoSourceControl; // something is wrong
} else if (sha == gitjson.commit.sha)
return PullStatus.UpToDate
if (checkOnly)
return PullStatus.GotChanges
try {
await githubUpdateToAsync(hd, { repo: gitjson.repo, sha, files, tryDiff3: true })
return PullStatus.GotChanges
} catch (e) {
if (e.isMergeError)
return PullStatus.NeedsCommit
else throw e
}
}
export async function revertAllAsync(hd: Header) {
const files = await getTextAsync(hd.id)
const gitjsontext = files[GIT_JSON]
if (!gitjsontext)
return PullStatus.NoSourceControl
const gitjson = JSON.parse(gitjsontext) as GitJson
const parsed = pxt.github.parseRepoId(hd.githubId)
const commit = gitjson.commit;
const configEntry = pxt.github.lookupFile(parsed, commit, pxt.CONFIG_NAME);
const config = pxt.Package.parseAndValidConfig(configEntry && configEntry.blobContent);
if (!config)
return PullStatus.NoSourceControl
const revertedFiles: pxt.Map<string> = {};
revertedFiles[GIT_JSON] = gitjsontext;
revertedFiles[pxt.CONFIG_NAME] = configEntry.blobContent;
for (const f of config.files.concat(config.testFiles)) {
const entry = pxt.github.lookupFile(parsed, commit, f);
if (!entry || entry.blobContent === undefined) {
pxt.log(`cannot revert ${f}, corrupted based commit`)
return PullStatus.NoSourceControl
}
revertedFiles[f] = entry.blobContent;
}
// save updated file content
await forceSaveAsync(hd, revertedFiles)
return PullStatus.UpToDate;
}
export async function hasMergeConflictMarkersAsync(hd: Header): Promise<boolean> {
const files = await getTextAsync(hd.id)
return !!Object.keys(files).find(k => pxt.diff.hasMergeConflictMarker(files[k]));
}
export async function prAsync(hd: Header, commitId: string, msg: string) {
let parsed = pxt.github.parseRepoId(hd.githubId)
// merge conflict - create a Pull Request
const branchName = await pxt.github.getNewBranchNameAsync(parsed.slug, "merge-")
await pxt.github.createNewBranchAsync(parsed.slug, branchName, commitId)
const url = await pxt.github.createPRFromBranchAsync(parsed.slug, parsed.tag, branchName, msg)
// force user back to master - we will instruct them to merge PR in github.com website
// and sync here to get the changes
let headCommit = await pxt.github.getRefAsync(parsed.slug, parsed.tag)
await githubUpdateToAsync(hd, {
repo: hd.githubId,
sha: headCommit,
files: {}
})
return url
}
export function bumpedVersion(cfg: pxt.PackageConfig) {
let v = pxt.semver.parse(cfg.version, "0.0.0")
v.patch++
return pxt.semver.stringify(v)
}
export async function bumpAsync(hd: Header, newVer = "") {
checkHeaderSession(hd);
const files = await getTextAsync(hd.id)
const cfg = pxt.Package.parseAndValidConfig(files[pxt.CONFIG_NAME]);
cfg.version = newVer || bumpedVersion(cfg)
const releaseTag = "v" + cfg.version;
// if any other github repo is referenced, unbound their version
// those extensions are part of the same repo and their version will be resolved
// at load time
if (cfg.dependencies) {
const gh = pxt.github.parseRepoId(hd.githubId);
Object.keys(cfg.dependencies).forEach(k => {
const ver = cfg.dependencies[k];