-
Notifications
You must be signed in to change notification settings - Fork 722
/
Copy pathremote-loader.ts
296 lines (258 loc) · 8.85 KB
/
remote-loader.ts
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
import semver from 'semver';
import {
EditorId,
EditorValues,
ElectronReleaseChannel,
GenericDialogType,
InstallState,
PACKAGE_NAME,
VersionSource,
} from '../interfaces';
import { ELECTRON_ORG, ELECTRON_REPO } from './constants';
import { AppState } from './state';
import { disableDownload } from './utils/disable-download';
import { isKnownFile, isSupportedFile } from './utils/editor-utils';
import { getOctokit } from './utils/octokit';
import { getReleaseChannel } from './versions';
export class RemoteLoader {
constructor(private readonly appState: AppState) {
for (const name of [
'fetchExampleAndLoad',
'fetchGistAndLoad',
'handleLoadingFailed',
'handleLoadingSuccess',
'loadFiddleFromElectronExample',
'loadFiddleFromGist',
'setElectronVersion',
'verifyReleaseChannelEnabled',
'verifyRemoteLoad',
] as const) {
this[name] = this[name].bind(this);
}
}
public async loadFiddleFromElectronExample(exampleInfo: {
path: string;
tag: string;
}) {
console.log(`Loading fiddle from Electron example`, exampleInfo);
const { path, tag } = exampleInfo;
const prettyName = path.replace('docs/fiddles/', '');
const ok = await this.verifyRemoteLoad(
`'${prettyName}' example from the Electron docs for version ${tag}`,
);
if (!ok) return;
this.fetchExampleAndLoad(tag, path);
}
public async loadFiddleFromGist(gistInfo: { id: string }) {
const { id } = gistInfo;
const ok = await this.verifyRemoteLoad(`gist`);
if (!ok) return;
this.fetchGistAndLoad(id);
}
public async fetchExampleAndLoad(
tag: string,
path: string,
): Promise<boolean> {
try {
const octo = await getOctokit(this.appState);
const folder = await octo.repos.getContents({
owner: ELECTRON_REPO,
repo: ELECTRON_ORG,
ref: tag,
path,
});
const index = tag.search(/\d/);
const version = tag.substring(index);
if (!semver.valid(version)) {
throw new Error('Could not determine Electron version for example');
}
const ok = await this.setElectronVersion(version);
if (!ok) return false;
const values = await window.ElectronFiddle.getTemplate(
this.appState.version,
);
if (!Array.isArray(folder.data)) {
throw new Error(
'The example Fiddle tried to launch is not a valid Electron example',
);
}
const loaders: Array<Promise<void>> = [];
for (const child of folder.data) {
if (!child.download_url) {
console.warn(`Could not find download_url for ${child.name}`);
continue;
}
if (isSupportedFile(child.name)) {
loaders.push(
fetch(child.download_url)
.then((r) => r.text())
.then((t) => {
values[child.name as EditorId] = t;
}),
);
}
}
await Promise.all(loaders);
return this.handleLoadingSuccess(values, '');
} catch (error) {
return this.handleLoadingFailed(error);
}
}
/**
* Load a fiddle
*/
public async fetchGistAndLoad(gistId: string): Promise<boolean> {
try {
const octo = await getOctokit(this.appState);
const gist = await octo.gists.get({ gist_id: gistId });
const values: EditorValues = {};
for (const [id, data] of Object.entries(gist.data.files)) {
if (id === PACKAGE_NAME) {
const { dependencies, devDependencies } = JSON.parse(data.content);
const deps: Record<string, string> = {
...dependencies,
...devDependencies,
};
// If the gist specifies an Electron version, we want to tell Fiddle to run
// it with that version by default.
const electronDeps = Object.keys(deps).filter((d) =>
['electron-nightly', 'electron'].includes(d),
);
for (const dep of electronDeps) {
// Strip off semver range prefixes, e.g:
// ^1.2.0 -> 1.2.0
// ~2.3.4 -> 2.3.4
const index = deps[dep].search(/\d/);
const version = deps[dep].substring(index);
if (
!semver.valid(version) ||
!(await window.ElectronFiddle.isReleasedMajor(
semver.major(version),
))
) {
await this.appState.showGenericDialog({
label: `The Electron version (${version}) in this gist's package.json is invalid. Falling back to last used version.`,
ok: 'Close',
type: GenericDialogType.warning,
wantsInput: false,
});
} else if (disableDownload(version)) {
await this.appState.showGenericDialog({
label: `This gist's Electron version (${version}) is not available on your current OS. Falling back to last used version.`,
ok: 'Close',
type: GenericDialogType.warning,
wantsInput: false,
});
} else {
this.setElectronVersion(version);
}
// We want to include all dependencies except Electron.
delete deps[dep];
}
this.appState.modules = new Map(Object.entries(deps));
}
if (!isSupportedFile(id)) continue;
if (isKnownFile(id) || (await this.confirmAddFile(id))) {
values[id] = data.content;
}
}
// If no files were populated into values, the Fiddle did not
// contain any supported files. Throw an error to let the user know.
if (Object.keys(values).length === 0) {
throw new Error(
'This Gist did not contain any supported files. Supported files must have one of the following extensions: .js, .css, or .html.',
);
}
return this.handleLoadingSuccess(values, gistId);
} catch (error) {
return this.handleLoadingFailed(error);
}
}
public async setElectronVersion(version: string): Promise<boolean> {
if (!this.appState.hasVersion(version)) {
const versionToDownload = {
source: VersionSource.remote,
state: InstallState.missing,
version,
};
try {
this.appState.addNewVersions([versionToDownload]);
await this.appState.downloadVersion(versionToDownload);
} catch {
await this.appState.removeVersion(versionToDownload);
this.handleLoadingFailed(
new Error(`Failed to download Electron version ${version}`),
);
return false;
}
}
// check if version is part of release channel
const versionReleaseChannel: ElectronReleaseChannel = getReleaseChannel(
version,
);
if (!this.appState.channelsToShow.includes(versionReleaseChannel)) {
const ok = await this.verifyReleaseChannelEnabled(versionReleaseChannel);
if (!ok) return false;
this.appState.channelsToShow.push(versionReleaseChannel);
}
this.appState.setVersion(version);
return true;
}
public confirmAddFile = (filename: string): Promise<boolean> => {
return this.appState.showConfirmDialog({
cancel: 'Skip',
label: `Do you want to add "${filename}"?`,
ok: 'Add',
});
};
/**
* Verifies from the user that we should be loading this fiddle.
*
* @param {string} what What are we loading from (gist, example, etc.)
*/
public verifyRemoteLoad(what: string): Promise<boolean> {
return this.appState.showConfirmDialog({
label: `Are you sure you want to load this ${what}? Only load and run it if you trust the source.`,
ok: 'Load',
});
}
public verifyReleaseChannelEnabled(channel: string): Promise<boolean> {
return this.appState.showConfirmDialog({
label: `You're loading an example with a version of Electron with an unincluded release
channel (${channel}). Do you want to enable the release channel to load the
version of Electron from the example?`,
ok: 'Enable',
});
}
/**
* Loading a fiddle from GitHub succeeded, let's move on.
*
* @param {EditorValues} values
* @param {string} gistId
* @returns {Promise<boolean>}
*/
private async handleLoadingSuccess(
values: EditorValues,
gistId: string,
): Promise<boolean> {
await window.ElectronFiddle.app.replaceFiddle(values, { gistId });
return true;
}
/**
* Loading a fiddle from GitHub failed - this method handles this case
* gracefully.
*
* @param {Error} error
* @returns {boolean}
*/
private handleLoadingFailed(error: Error): false {
const failedLabel = `Loading the fiddle failed: ${error.message}`;
this.appState.showErrorDialog(
this.appState.isOnline
? failedLabel
: `Your computer seems to be offline. ${failedLabel}`,
);
console.warn(`Loading Fiddle failed`, error);
return false;
}
}