This repository has been archived by the owner on Jan 11, 2023. It is now read-only.
/
trim.ts
350 lines (312 loc) · 8.25 KB
/
trim.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
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
import { createPackageWithOptions } from 'asar';
import json5 from 'json5';
import { convert } from 'convert';
import consola from 'consola';
import { walkDir, fileExists } from '../utils';
import { Option, Command } from 'clipanion';
import { join, resolve, basename } from 'node:path';
import { rm, stat, unlink, readFile, writeFile } from 'node:fs/promises';
import { Worker } from 'node:worker_threads';
import type { CreateOptions } from 'asar';
import type { BaseContext } from 'clipanion';
export class TrimCommand extends Command<BaseContext> {
public static override paths = [Command.Default];
public asarPath = Option.String();
public hintFilePath = Option.String('-h,--hint-file', {
description: 'Path to your app\'s load order hint file, used to optimize file ordering',
arity: 1,
required: false,
});
public backup = Option.Boolean('-b,--backup', false, {
description: 'Whether to backup the original app.asar file'
});
public keepExtracted = Option.Boolean('-k,--keep-extracted', false, {
description: 'Whether to keep the extracted app.asar contents after optimizing instead of deleting them'
});
private _savedBytes: number = 0;
private readonly _deletables = {
files: [
'.airtap.yml',
'.babelrc',
'.editorconfig',
'.eslintignore',
'.eslintrc',
'.eslintrc.js',
'.eslintrc.json',
'.eslintrc.yml',
'.gitmodules',
'.jscs.json',
'.jshintignore',
'.lint',
'.npmignore',
'.nycrc.json',
'.testignore',
'.travis.yml',
'.yarnrc.yml',
'3rdpartylicenses.txt',
'authors',
'bower.json',
'browsers.json',
'changes',
'ci.yml',
'commitlint.config.js',
'copyrightnotice.txt',
'dependabot.yml',
'funding.yml',
'jasmine.json',
'jest.config.js',
'jsl.node.conf',
'licence',
'license',
'license-mit.txt',
'license.txt',
'lint.yml',
'makefile',
'mocha.opts',
'notice',
'.nvmrc',
'.nycrc',
'rollup.config.js',
'tsconfig.build.json',
'tsconfig.eslint.json',
'tsconfig.json',
'tsdoc-metadata.json',
'tslint.json',
'webpack.build.config.js',
'webpack.config.js',
'yarn.lock',
],
extensions: [
'.__ivy_ngcc_bak',
'.ai',
'.apache2',
'.applescript',
'.babelrc',
'.bak',
'.c',
'.cmd',
'.coffee',
'.cpp',
'.cs',
'.dds',
'.dockerignore',
'.flow',
'.gyp',
'.gypi',
'.gz',
'.h',
'.hbs',
'.hpp',
'.huskyrc',
'.ilk',
'.info',
'.inl',
'.iobj',
'.ipdb',
'.jsdoc',
'.jst',
'.jsx',
'.lib',
'.license',
'.license.txt',
'.lintstagedrc',
'.lock',
'.log',
'.map',
'.markdown',
'.md',
'.mit',
'.mkd',
'.nix',
'.patch',
'.pdf',
'.prettierignore',
'.prettierrc',
'.scss',
'.spec.js',
'.swf',
'.targ',
'.template',
'.toml',
'.tga',
'.tgz',
'.tlog',
'.ts',
'.tsbuildinfo',
'.tsx',
'.vcxproj',
'.vdproj',
'.vue',
'.webmanifest',
'.wrapped',
'.x',
],
packageJSONProperties: [
'author',
'authors',
'bin',
'browser',
'browserslist',
'bundlesize',
'commitlint',
'config',
'dependencies',
'description',
'devDependencies',
'directories',
'engine',
'engines',
'es2015',
'es2020',
'eslintIgnore',
'esm2020',
'exports',
'fesm2015',
'fesm2020',
'files',
'funding',
'gh-pages-deploy',
'gypfile',
'homepage',
'husky',
'imports',
'jest',
'jsdelivr',
'license',
'licenses',
'licenses',
'lint-staged',
'locales',
'maintainers',
'mocha',
'modes',
'ng-update',
'np',
'optionalDependencies',
'optionalDevDependencies',
'packageManager',
'peerDependencies',
'peerDependenciesMeta',
'pre-commit',
'prettier',
'private',
'publishConfig',
'react-native',
'readme',
'readmeFilename',
'repository',
'schematics',
'sideEffects',
'standard',
'testling',
'tsd',
'types',
'typesVersions',
'typescript',
'typings',
'typings',
'unpkg',
'verb',
]
};
public async execute(): Promise<number | void> {
this.asarPath = resolve(this.asarPath);
const asarFile = resolve(this.asarPath, 'app.asar');
if (!(await fileExists(asarFile))) {
consola.fatal('app.asar not found at', this.asarPath);
return 1;
}
if (this.backup) {
const { backupFile } = await import('../utils');
consola.info('Backing up app.asar');
try {
await backupFile(asarFile);
} catch (err: unknown) {
consola.fatal(err);
return 1;
}
}
consola.info('Extracting app.asar');
const appDir = join(this.asarPath, 'app');
const extractionResult = await new Promise<number | Error>((res, rej) => {
const workerPath = join(__dirname, 'extractWorker.js');
const worker = new Worker(workerPath, { workerData: [asarFile, appDir] });
worker.once('error', (err: Error) => rej(err));
worker.once('exit', (code: number) => res(code));
});
if (extractionResult !== 0) {
consola.fatal(extractionResult);
return 1;
}
consola.info('Extracted app.asar, processing files');
// TODO rewrite pretty much all of this
walk:
for await (const file of walkDir(appDir)) {
const { path, stats } = file;
const { size } = stats;
const filename = basename(path);
for (const deletableFile of this._deletables.files) {
if (filename.toLowerCase() !== deletableFile) continue;
this._savedBytes = this._savedBytes + size;
await unlink(path);
continue walk;
}
for (const deletableExtension of this._deletables.extensions) {
if (path.toLowerCase().endsWith(deletableExtension)) {
if (!await fileExists(path) || stats.isDirectory()) continue;
this._savedBytes = this._savedBytes + size;
await unlink(path);
continue walk;
}
}
if (filename === 'package.json') {
const bytesSaved = await this._minifyPackageJSON(path);
this._savedBytes = this._savedBytes + bytesSaved;
} else if (filename.endsWith('.json') || filename.endsWith('.json5')) {
const contents = await readFile(path, { encoding: 'utf8' });
try {
const json = json5.parse(contents);
const newJSON = JSON.stringify(json);
await writeFile(path, newJSON);
const oldJSONSize = contents.length;
const newJSONSize = newJSON.length;
const jsonSizeDifference = oldJSONSize - newJSONSize;
this._savedBytes = this._savedBytes + jsonSizeDifference;
} catch {}
}
}
consola.info('Finished processing files, repacking');
const options: CreateOptions = {};
if (this.hintFilePath) {
this.hintFilePath = resolve(this.hintFilePath);
if (!await fileExists(this.hintFilePath)) {
consola.warn(`Hint file could not be found at ${this.hintFilePath}, skipping`);
} else {
consola.info(`Using hint file ${this.hintFilePath}`);
options.ordering = this.hintFilePath;
}
}
await createPackageWithOptions(appDir, asarFile, options);
if (!this.keepExtracted) {
await rm(appDir, { recursive: true });
}
const savedMB = convert(this._savedBytes, 'bytes').to('MB');
const roundedSavedMB = Math.round((savedMB + Number.EPSILON) * 100) / 100;
consola.info(`Reduced asar archive size by ${roundedSavedMB}MB`);
return 0;
};
private async _minifyPackageJSON(path: string): Promise<number> {
const { size: originalSize } = await stat(path);
const originalContents = await readFile(path, { encoding: 'utf8' });
const originalData = json5.parse(originalContents);
for (const packageProperty of this._deletables.packageJSONProperties) {
if (packageProperty in originalData) {
delete originalData[packageProperty];
}
}
const newContents = JSON.stringify(originalData);
await writeFile(path, newContents);
const { size: newSize } = await stat(path);
return originalSize - newSize;
};
};