-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·228 lines (188 loc) · 8.2 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
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
#!/usr/bin/env node
'use strict';
const fs = require('fs');
const path = require('path');
const toml = require('toml');
const mkdirp = require('mkdirp');
const markdown = require('markdown').markdown;
const requirejs = require('requirejs');
const yazl = require('yazl');
const crx = require('./crx.js');
const crx3 = require('crx3');
const argv = require('yargs')
.usage('Usage: $0 [options]')
.string('version')
.describe('version', 'Provide a specific version number to use. Defaults to metadata value.')
.alias('v', 'version')
.boolean('debug')
.describe('debug', 'Disable minification of the source code.')
.string('pem')
.describe('pem', 'Location of the PEM file.')
.demand(['pem'])
.help('h')
.alias('h', 'help')
.argv;
const INVALID_VERSION_ERR = 'Invalid version in Greasemonkey metadata. Version must be in the \
format x.x.x, where x is an integer (0 <= x <= 65535), without leading zeros';
// { name: 'Autopilot++', globalVariableName: "autopilot_pp", shortName: "app"
// , crxName: "gefs_gc-setup", licenseComment: "Copyright ...", requirejs: {} }
fs.promises.readFile('gefs-build-config.toml')
.then(file => toml.parse(file))
.then(magic);
const requirejsDefaults = {
baseUrl: 'source',
name: 'init',
stubModules: ['text', 'json'],
optimize: argv.debug ? 'none' : 'uglify2',
uglify2: {
output: {
max_line_len: 400,
screw_ie8: true
},
compress: {
global_defs: {
DEBUG: false
}
}
}
};
function customFormat(formatStr, ...params) {
let formattedStr = formatStr;
for (const [i, value] of params.entries()) {
formattedStr = formattedStr.replace(
new RegExp(`\\{${i}\\}`, 'g'),
value
);
}
return formattedStr;
}
function magic(config) {
config.requirejs = Object.assign(requirejsDefaults, config.requirejs);
// Insert Almond into the built file. For legacy reasons, 'name' is moved to 'include'.
if (config.requirejs.include) config.requirejs.include.push(config.requirejs.name);
else config.requirejs.include = [config.requirejs.name];
// Note that here the '.js' extension is necessary.
config.requirejs.name = path.join(__dirname, 'node_modules/almond/almond.js');
const optimizing = new Promise(function(resolve) {
console.log(`Building ${config.name}: ${argv.debug ? 'debug' : 'release'} mode`);
console.log('Waiting for RequireJS optimisation to complete...');
// Resolve promise with generated file after completing build.
config.requirejs.out = resolve;
// Print out information about build instead of leaving it as 'slient'.
config.requirejs.logLevel = 1;
// `buildResponse` is just a text output of the modules included. This is already sent to
// logger when logLevel is INFO, so this is not necessary.
// The default errback logs the error, then runs `process.exit(1)` -- this is what we want.
// `optimize(config, function (buildResponse) {}, errback);`
requirejs.optimize(config.requirejs);
});
const chromeManifest = {
manifest_version: 3,
content_scripts: [{
matches: [],
js: ['wrapper.js']
}],
web_accessible_resources: [{
matches: ['<all_urls>'],
resources: ['code.js']
}]
};
fs.promises.readFile(
path.join(config.requirejs.baseUrl, 'userscript.js'),
'utf-8'
).then(function(file) {
// Convert \r or \r\n newlines to Unix (\n) standard.
file = file.replace(/\r\n?/g, '\n');
// Find Greasemonkey metadata block.
const greasemonkey = file.slice(
file.indexOf('// ==UserScript==\n') + 17,
file.indexOf('// ==/UserScript==')
);
// Parse directives in metadata block.
const directives = [];
for (let line of greasemonkey.split('\n')) {
const match = line.match(/\/\/ @(\S+)(?:\s+(.*))?/);
if (match) directives.push(match.slice(1));
}
// Process directives that have been parsed.
for (let keyValue of directives) {
const key = keyValue[0];
const value = keyValue[1];
if (chromeManifest[key] !== undefined) {
if (Array.isArray(chromeManifest[key])) chromeManifest[key].push(value);
else chromeManifest[key] = [chromeManifest[key], value];
} else if (key === 'match') {
chromeManifest.content_scripts[0].matches.push(value);
// chromeManifest.web_accessible_resources[0].matches.push(value);
} else if (key === 'run-at') {
// Chrome uses underscores instead of hyphens.
chromeManifest.content_scripts[0]['run_at'] = value.replace('-', '_');
}
// elif key == 'namespace' or key == 'grant': pass
else chromeManifest[key] = value;
}
// Check if version was included as argument or not.
let version = argv.version;
if (!version) {
if (chromeManifest.version === undefined) {
throw new Error('Version missing from Greasemonkey metadata');
}
version = chromeManifest.version;
}
const list = version.split('.');
// REVIEW: should we allow other lengths?
if (list.length !== 3) throw new Error(INVALID_VERSION_ERR);
for (let val of list) {
if (!/^(0|[1-9][0-9]{0,4})$/.test(val) || parseInt(val) > 0xFFFF) {
throw new Error(INVALID_VERSION_ERR);
}
}
chromeManifest.version = version;
console.log('Version building: ' + version);
// Name of the ZIP file that will be used as a package.
const extension = `${config.shortName}_v${version}${argv.debug ? '-debug' : ''}`;
optimizing.then(async function (minified) {
minified += `\nvar a=window.${config.globalVariableName}={};a.version="${version}";\
a.require=require;a.requirejs=requirejs;a.define=define`;
const metadata = directives.map(([key, value]) => {
if (key === 'version') return '// @version ' + version;
return '// @' + key + ' ' + value;
}).join('\n');
let zip = new yazl.ZipFile();
// Make sure the string exists before attempting to trim it.
let licenseComment = config.licenseComment ? config.licenseComment.trim() : '';
if (licenseComment) {
licenseComment = '// ' + licenseComment.split(/\r?\n|\r/).join('\n// ') + '\n\n';
}
const userscript = `// ==UserScript==
${metadata}
// ==/UserScript==
${licenseComment}${minified}`;
zip.addBuffer(Buffer.from(userscript), extension + '.user.js');
// Convert README and LICENSE files from Markdown to HTML.
const readme = fs.promises.readFile(
path.join(config.requirejs.baseUrl, 'README.md'),
'utf-8'
).then(function(file) {
const html = markdown.toHTML(customFormat(file, version, extension, config.crxName));
zip.addBuffer(Buffer.from(html), 'README.html');
});
const license = fs.promises.readFile('LICENSE.md', 'utf-8').then(function(file) {
const html = markdown.toHTML(file);
zip.addBuffer(Buffer.from(html), 'LICENSE.html');
});
const creatingCrx = crx.createCrx3(minified, chromeManifest, argv.pem, `tmp/${config.crxName}.crx`)
.then(() => console.log('done'))
.then(() => zip.addFile(`tmp/${config.crxName}.crx`, `${config.crxName}.crx`, {
compress: false
}));
// Create the ZIP file once everything has been added to it.
await Promise.all([readme, license, creatingCrx]);
zip.end();
// Ensure the 'package' directory exists -- if not, create it.
await mkdirp('package');
// Write the ZIP file to the output folder.
zip.outputStream.pipe(fs.createWriteStream(`package/${extension}.zip`));
});
});
}