/
index.js
77 lines (63 loc) · 1.83 KB
/
index.js
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
'use strict';
const fs = require('fs');
const path = require('path');
const {promisify} = require('util');
const electron = require('electron');
const stat = promisify(fs.stat);
// See https://cs.chromium.org/chromium/src/net/base/net_error_list.h
const FILE_NOT_FOUND = -6;
const getPath = async path_ => {
try {
const result = await stat(path_);
if (result.isFile()) {
return path_;
}
if (result.isDirectory()) {
return getPath(path.join(path_, 'index.html'));
}
} catch (_) {}
};
module.exports = options => {
options = Object.assign({
isCorsEnabled: true,
scheme: 'app'
}, options);
if (!options.directory) {
throw new Error('The `directory` option is required');
}
options.directory = path.resolve(electron.app.getAppPath(), options.directory);
const handler = async (request, callback) => {
const indexPath = path.join(options.directory, 'index.html');
const filePath = path.join(options.directory, decodeURIComponent(new URL(request.url).pathname));
const resolvedPath = await getPath(filePath);
const fileExtension = path.extname(filePath);
if (resolvedPath || !fileExtension || fileExtension === '.html' || fileExtension === '.asar') {
callback({
path: resolvedPath || indexPath
});
} else {
callback({error: FILE_NOT_FOUND});
}
};
electron.protocol.registerSchemesAsPrivileged([
{
scheme: options.scheme,
privileges: {
standard: true,
secure: true,
allowServiceWorkers: true,
supportFetchAPI: true,
corsEnabled: options.isCorsEnabled
}
}
]);
electron.app.on('ready', () => {
const session = options.partition ?
electron.session.fromPartition(options.partition) :
electron.session.defaultSession;
session.protocol.registerFileProtocol(options.scheme, handler);
});
return async window_ => {
await window_.loadURL(`${options.scheme}://-`);
};
};