@ponderdev/justfits 0.0.0-stage → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@ponderdev/justfits",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "productName": "Just Fits",
4
+ "version": "1.2.0",
5
+ "description": "Make a file small enough to send. Compresses video and images to an exact size limit, entirely on your own machine.",
6
+ "author": {
7
+ "name": "PonderDev",
8
+ "url": "https://ponderdev.com"
9
+ },
10
+ "homepage": "https://ponderdev.com",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/ponder-dev/just-fits.git"
14
+ },
15
+ "bugs": {
16
+ "url": "https://github.com/ponder-dev/just-fits/issues"
17
+ },
18
+ "license": "GPL-3.0-or-later",
19
+ "main": "src/main.cjs",
20
+ "bin": {
21
+ "justfits": "src/cli.cjs"
22
+ },
23
+ "scripts": {
24
+ "start": "electron .",
25
+ "test": "node test/plan.test.cjs && node test/contract.test.cjs",
26
+ "fetch-ffmpeg": "node scripts/fetch-ffmpeg.mjs",
27
+ "licences": "node scripts/make-licenses.mjs",
28
+ "icon": "node scripts/make-icon.mjs && electron scripts/icons.cjs && ./scripts/make-icns.sh",
29
+ "dist:mac": "npm run licences && electron-builder --mac",
30
+ "dist:win": "npm run licences && electron-builder --win",
31
+ "dist": "npm run licences && electron-builder --mac --win --linux",
32
+ "cli": "node src/cli.cjs",
33
+ "test:linux": "./scripts/test-linux.sh",
34
+ "test:cli": "node test/cli.test.cjs && node test/safety.test.cjs",
35
+ "test:window": "env -u ELECTRON_RUN_AS_NODE electron test/window.test.cjs",
36
+ "dist:linux": "npm run licences && electron-builder --linux"
37
+ },
38
+ "files": [
39
+ "src/**/*",
40
+ "LICENSE",
41
+ "THIRD-PARTY-NOTICES.md",
42
+ "licenses/**/*"
43
+ ]
44
+ }
@@ -0,0 +1,90 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * Finding ffmpeg and ffprobe.
5
+ *
6
+ * The desktop app carries its own copies, because someone downloading a free
7
+ * app should not then have to install a video encoder. The command line does
8
+ * not: anyone using a terminal on Linux either has ffmpeg or can install it
9
+ * with one command, and a 300MB npm package to avoid that would be rude.
10
+ *
11
+ * So: the bundled copy if there is one, otherwise whatever is on PATH.
12
+ */
13
+
14
+ const fs = require('node:fs');
15
+ const path = require('node:path');
16
+ const { execFileSync } = require('node:child_process');
17
+
18
+ const EXE = process.platform === 'win32' ? '.exe' : '';
19
+
20
+ function fromDir(dir, name) {
21
+ if (!dir) return null;
22
+ // Platform first: linux and mac both call themselves x64, so an arch alone
23
+ // is not enough to tell a linux binary from a mac one sitting side by side.
24
+ for (const candidate of [
25
+ `${name}-${process.platform}-${process.arch}${EXE}`,
26
+ `${name}-${process.arch}${EXE}`,
27
+ `${name}${EXE}`,
28
+ ]) {
29
+ const full = path.join(dir, candidate);
30
+ if (fs.existsSync(full)) return full;
31
+ }
32
+ return null;
33
+ }
34
+
35
+ // Walks PATH ourselves. Minimal Linux images (Fedora minimal, slim Docker
36
+ // bases) often have no `which`, and its absence used to read as "ffmpeg not
37
+ // found" to someone who had ffmpeg installed.
38
+ function scanPath(name) {
39
+ for (const dir of (process.env.PATH || '').split(path.delimiter)) {
40
+ if (!dir) continue;
41
+ const full = path.join(dir, name + EXE);
42
+ try {
43
+ if (fs.statSync(full).isFile()) {
44
+ if (process.platform !== 'win32') fs.accessSync(full, fs.constants.X_OK);
45
+ return full;
46
+ }
47
+ } catch {}
48
+ }
49
+ return null;
50
+ }
51
+
52
+ function fromPath(name) {
53
+ const finder = process.platform === 'win32' ? 'where' : 'which';
54
+ try {
55
+ const found = execFileSync(finder, [name + EXE], { stdio: ['ignore', 'pipe', 'ignore'] })
56
+ .toString().split('\n')[0].trim();
57
+ return found || scanPath(name);
58
+ } catch (err) {
59
+ return scanPath(name);
60
+ }
61
+ }
62
+
63
+ /**
64
+ * @param name 'ffmpeg' or 'ffprobe'
65
+ * @param dirs vendor directories to try first, in order
66
+ * @param allowPath false for the packaged app, which must not depend on the
67
+ * machine having its own ffmpeg
68
+ */
69
+ function resolve(name, dirs = [], allowPath = true) {
70
+ for (const dir of dirs) {
71
+ const hit = fromDir(dir, name);
72
+ if (hit) return hit;
73
+ }
74
+ if (allowPath) {
75
+ const hit = fromPath(name);
76
+ if (hit) return hit;
77
+ }
78
+ const where = allowPath ? 'bundled or on PATH' : 'bundled';
79
+ throw new Error(
80
+ `${name} not found (${where}).\n` +
81
+ (allowPath
82
+ ? `Install it with your package manager, for example:\n` +
83
+ ` arch sudo pacman -S ffmpeg\n` +
84
+ ` debian sudo apt install ffmpeg\n` +
85
+ ` mac brew install ffmpeg`
86
+ : 'Run: npm run fetch-ffmpeg'),
87
+ );
88
+ }
89
+
90
+ module.exports = { resolve, fromDir, fromPath };
package/src/cli.cjs ADDED
@@ -0,0 +1,399 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /*
5
+ * Just Fits on the command line.
6
+ *
7
+ * The decisions live in plan.js and the ffmpeg work in engine.cjs, neither of
8
+ * which knows anything about Electron, so this is a wrapper rather than a
9
+ * second implementation. The desktop app and this produce identical output for
10
+ * identical input.
11
+ *
12
+ * Progress goes to stderr so stdout stays clean enough to pipe.
13
+ */
14
+
15
+ const fs = require('node:fs');
16
+ const os = require('node:os');
17
+ const path = require('node:path');
18
+
19
+ const plan = require('./plan.js');
20
+ const engine = require('./engine.cjs');
21
+ const binaries = require('./binaries.cjs');
22
+
23
+ // Inside a packaged app the extras sit in the app's resources folder (as
24
+ // extraResources put them), not in vendor/. Run that way, by the tool belt or
25
+ // anyone, process.resourcesPath says where; under plain node it is undefined
26
+ // and only vendor/ is looked in.
27
+ const packaged = (name) => (process.resourcesPath ? [path.join(process.resourcesPath, name)] : []);
28
+ const VENDOR = [...packaged('ffmpeg'), path.join(__dirname, '..', 'vendor', 'ffmpeg')];
29
+ const MB = 1000 * 1000;
30
+
31
+ function human(bytes) {
32
+ if (bytes >= 1000 * MB) return (bytes / 1000 / MB).toFixed(1) + 'GB';
33
+ if (bytes >= MB) return (bytes / MB).toFixed(bytes >= 100 * MB ? 0 : 1) + 'MB';
34
+ return Math.max(1, Math.round(bytes / 1000)) + 'KB';
35
+ }
36
+
37
+ const VERSION = require('../package.json').version;
38
+
39
+ /*
40
+ * Every option, once. --help is printed from this and --describe is built from
41
+ * it, so the two cannot drift apart (CONTRACT.md section 3).
42
+ */
43
+ const OPTIONS = [
44
+ { flags: ['--to'], name: 'to', metavar: 'target', type: 'string', default: 'discord', help: 'where it is going, or a plain size like 25MB' },
45
+ { flags: ['-o', '--output', '--out'], name: 'output', metavar: 'path', type: 'path', default: null, help: 'where to write it. "-" means stdout. default: beside the input as name-fits.mp4' },
46
+ { flags: ['--json'], name: 'json', type: 'boolean', help: 'results as JSON lines on stdout (stderr when the file goes to stdout)' },
47
+ { flags: ['--progress'], name: 'progress', type: 'boolean', help: 'with --json, progress as JSON lines on stderr' },
48
+ { flags: ['--dry-run'], name: 'dry-run', type: 'boolean', help: 'say what would happen and write nothing' },
49
+ { flags: ['-q', '--quiet'], name: 'quiet', type: 'boolean', help: 'nothing on stderr but errors' },
50
+ { flags: ['-h', '--help'], name: 'help', type: 'boolean', help: 'this, and nothing else' },
51
+ { flags: ['-V', '--version'], name: 'version', type: 'boolean', help: 'the version number' },
52
+ { flags: ['--describe'], name: 'describe', type: 'boolean', help: 'what this command line accepts, as JSON' },
53
+ ];
54
+
55
+ const EXIT = [
56
+ { code: 0, meaning: 'Done, or it already fit.' },
57
+ { code: 1, meaning: 'Failed. Nothing usable was written.' },
58
+ { code: 2, meaning: 'Usage: a bad option, a missing value, an unknown target or a missing input. Nothing was started.' },
59
+ { code: 4, meaning: 'Done, but still over the target after every try. The closest result was written.' },
60
+ { code: 129, meaning: 'Stopped by a hang-up. Part files removed.' },
61
+ { code: 130, meaning: 'Stopped with Ctrl-C. Part files removed.' },
62
+ { code: 143, meaning: 'Stopped by a terminate signal. Part files removed.' },
63
+ ];
64
+
65
+ function usage() {
66
+ const targets = plan.TARGETS.map((t) => ` ${t.id.padEnd(16)} ${human(t.bytes).padStart(7)} ${t.label}`).join('\n');
67
+ const opts = OPTIONS.map((o) => {
68
+ const left = ` ${o.flags.join(', ')}${o.metavar ? ` <${o.metavar}>` : ''}`;
69
+ return `${left.padEnd(30)} ${o.help}`;
70
+ }).join('\n');
71
+ return `Just Fits ${VERSION}
72
+ Makes a file small enough to send.
73
+
74
+ justfits <file> [options]
75
+ cat clip.mp4 | justfits --to discord > small.mp4
76
+
77
+ Options
78
+ ${opts}
79
+
80
+ Targets
81
+ ${targets}
82
+
83
+ Exit status: 0 done, 1 failed, 2 usage, 4 still over the target after every try.
84
+
85
+ Your original is only ever read. Nothing is uploaded.`;
86
+ }
87
+
88
+ function describe() {
89
+ return {
90
+ schema: 'ponderdev.cli-describe/1',
91
+ name: 'justfits',
92
+ product: 'Just Fits',
93
+ version: VERSION,
94
+ licence: require('../package.json').license,
95
+ command: 'justfits',
96
+ job: 'Make a video or image small enough to send, under an exact size limit.',
97
+ network: false,
98
+ accepts: { mediaTypes: ['video/*', 'image/*'], extensions: ['.mp4', '.mov', '.m4v', '.mkv', '.webm', '.avi', '.jpg', '.jpeg', '.png', '.webp', '.gif'] },
99
+ emits: { mediaTypes: ['video/mp4', 'image/jpeg'], extensions: ['.mp4', '.jpg'] },
100
+ arguments: [{ name: 'file', type: 'path', required: false, repeatable: false, help: 'the file to shrink. "-" or none reads stdin' }],
101
+ options: OPTIONS.map((o) => (o.name === 'to' ? { ...o, values: plan.TARGETS.map((t) => t.id), valuesOpen: true } : o)),
102
+ targets: plan.TARGETS.map((t) => ({ id: t.id, bytes: t.bytes, label: t.label })),
103
+ output: { video: 'name-fits.mp4 beside the input', picture: 'name-fits.jpg beside the input', taken: 'name-fits 2.mp4, then 3, never over an existing file' },
104
+ result: { fields: { input: 'path', output: 'path', path: 'path', before: 'integer', after: 'integer', target: 'integer', attempts: 'integer', width: 'integer', height: 'integer' } },
105
+ // The desktop app carries ffmpeg; the npm command line uses the one on the
106
+ // PATH, and says how to install it if there is none.
107
+ needs: [{ id: 'ffmpeg', kind: 'binary', bundled: 'in the desktop app; the npm install uses ffmpeg from the PATH' }],
108
+ io: {
109
+ stdin: 'read when the file is "-", or when no file is named and stdin is not a terminal (gives up after 10 seconds of nothing)',
110
+ stdout: 'the file itself with -o -, or when the input came from stdin and no -o was given; otherwise JSON lines with --json, otherwise nothing',
111
+ stderr: 'progress and messages for people; JSON lines when stdout carries the file',
112
+ },
113
+ exitCodes: EXIT,
114
+ guarantees: ['never writes over an input or an existing file', 'nothing is uploaded'],
115
+ };
116
+ }
117
+
118
+ class UsageError extends Error {}
119
+
120
+ function parseTarget(value) {
121
+ if (value === null) return plan.TARGETS[0];
122
+ const preset = plan.TARGETS.find((t) => t.id === value.toLowerCase());
123
+ if (preset) return preset;
124
+
125
+ const m = /^(\d+(?:\.\d+)?)\s*(g|m|k)?b?$/i.exec(value.trim());
126
+ if (!m) throw new UsageError(`Unknown target "${value}". Try a preset from --help, or a size like 25MB.`);
127
+ const n = Number(m[1]);
128
+ const unit = (m[2] || 'm').toLowerCase();
129
+ const bytes = Math.round(n * (unit === 'g' ? 1000 * MB : unit === 'k' ? 1000 : MB));
130
+ if (!(bytes > 0)) throw new UsageError(`Target "${value}" is not more than zero.`);
131
+ return { id: 'custom', label: `${value}`, bytes };
132
+ }
133
+
134
+ // A missing or empty value is an error, never a silent default: a script
135
+ // passing an empty variable must not get a 10MB Discord file it did not ask
136
+ // for, or a file named after the next flag.
137
+ function needValue(flag, value, dashOk) {
138
+ if (value === undefined || value === '' || (value.startsWith('-') && !(dashOk && value === '-'))) {
139
+ throw new UsageError(`${flag} needs a value`);
140
+ }
141
+ return value;
142
+ }
143
+
144
+ function parseArgs(argv) {
145
+ const opts = { file: null, to: null, out: null, json: false, quiet: false, progress: false, dryRun: false };
146
+ let positional = false;
147
+ for (let i = 0; i < argv.length; i++) {
148
+ const a = argv[i];
149
+ if (positional || a === '-' || !a.startsWith('-')) {
150
+ if (opts.file !== null) throw new UsageError('Only one input file at a time');
151
+ opts.file = a;
152
+ }
153
+ else if (a === '--') positional = true;
154
+ else if (a === '--json') opts.json = true;
155
+ else if (a === '--progress') opts.progress = true;
156
+ else if (a === '--dry-run') opts.dryRun = true;
157
+ else if (a === '-q' || a === '--quiet') opts.quiet = true;
158
+ else if (a === '--to') opts.to = needValue(a, argv[++i], false);
159
+ else if (a === '-o' || a === '--out' || a === '--output') opts.out = needValue(a, argv[++i], true);
160
+ else if (a.startsWith('--to=')) opts.to = needValue('--to', a.slice(5), false);
161
+ else if (a.startsWith('--out=')) opts.out = needValue('--out', a.slice(6), true);
162
+ else if (a.startsWith('--output=')) opts.out = needValue('--output', a.slice(9), true);
163
+ else throw new UsageError(`Unknown option "${a}"`);
164
+ }
165
+ return opts;
166
+ }
167
+
168
+ // Checked before the encode rather than left to ffmpeg, whose complaint would
169
+ // name the working file it writes beside the result instead of the folder
170
+ // that is missing.
171
+ function checkFolder(requested, outPath) {
172
+ const dir = path.dirname(outPath);
173
+ let stat = null;
174
+ try { stat = fs.statSync(dir); } catch (e) { /* missing, said below */ }
175
+ if (!stat) throw new UsageError(`The folder ${path.dirname(requested)} does not exist.`);
176
+ if (!stat.isDirectory()) throw new UsageError(`${path.dirname(requested)} is not a folder.`);
177
+ }
178
+
179
+ // Reads all of stdin into a file. When nobody asked for stdin (no file named,
180
+ // no "-"), an open pipe that never sends anything is almost always a harness
181
+ // or CI job with a missing file argument, so give up with a usage error
182
+ // instead of hanging forever.
183
+ function readStdin(dest, implicit) {
184
+ return new Promise((resolve, reject) => {
185
+ const out = fs.createWriteStream(dest);
186
+ let got = 0;
187
+ const timer = implicit ? setTimeout(() => {
188
+ if (got) return;
189
+ process.stdin.unpipe(out);
190
+ process.stdin.destroy();
191
+ out.destroy();
192
+ reject(new Error('No input file, and nothing arrived on stdin. Name a file, or pass "-" to wait for stdin.'));
193
+ }, 10000) : null;
194
+ process.stdin.on('data', (c) => { got += c.length; });
195
+ process.stdin.pipe(out);
196
+ out.on('finish', () => {
197
+ clearTimeout(timer);
198
+ if (!got) reject(new Error('Nothing arrived on stdin.'));
199
+ else resolve();
200
+ });
201
+ out.on('error', (err) => { clearTimeout(timer); reject(err); });
202
+ });
203
+ }
204
+
205
+ // Waits until everything written to stdout has been handed to the OS, so
206
+ // exiting straight after cannot cut the end off a piped file.
207
+ function drainStdout() {
208
+ return new Promise((resolve) => process.stdout.write('', () => resolve()));
209
+ }
210
+
211
+ /*
212
+ * JSON lines (CONTRACT.md section 4): result, skip and error lines, then a
213
+ * done line, always. They go to stdout, or to stderr when stdout carries the
214
+ * file. The released fields (ok, path, before, after...) are kept as they were
215
+ * so a script reading them keeps working; type, input, output and done are new.
216
+ */
217
+ const report = {
218
+ stream: process.stdout,
219
+ on: false,
220
+ counts: { results: 0, skipped: 0, failed: 0 },
221
+ line(obj) { if (this.on) this.stream.write(JSON.stringify(obj) + '\n'); },
222
+ result(obj) { this.counts.results++; this.line({ type: 'result', ...obj }); },
223
+ skip(obj) { this.counts.skipped++; this.line({ type: 'skip', ...obj }); },
224
+ error(code, message) { this.counts.failed++; this.line({ type: 'error', ok: false, code, message }); },
225
+ done(exit) { this.line({ type: 'done', ok: exit === 0, ...this.counts, exit }); },
226
+ };
227
+
228
+ // Files to remove if a signal stops the run before it finishes.
229
+ const cleanup = new Set();
230
+
231
+ async function main(argv) {
232
+ // Answered before anything else is looked at: a bad option beside them still
233
+ // gets an answer, no file is opened and stdin is never read.
234
+ if (argv.includes('-h') || argv.includes('--help')) { console.log(usage()); return 0; }
235
+ if (argv.includes('-V') || argv.includes('--version')) { console.log(VERSION); return 0; }
236
+ if (argv.includes('--describe')) { console.log(JSON.stringify(describe(), null, 2)); return 0; }
237
+
238
+ report.on = argv.includes('--json');
239
+ const opts = parseArgs(argv);
240
+
241
+ const target = parseTarget(opts.to);
242
+
243
+ // Piped input has to be buffered, because two-pass encoding reads the input
244
+ // twice and a pipe cannot be rewound. Said plainly rather than hidden.
245
+ let input = opts.file;
246
+ let temp = null;
247
+ const fromStdin = input === '-' || (!input && !process.stdin.isTTY);
248
+ const toStdout = opts.out === '-' || (fromStdin && !opts.out);
249
+ if (toStdout) report.stream = process.stderr;
250
+ // Never over an existing file, the input included: `-o clip.mp4` on
251
+ // clip.mp4 used to replace the original with the compressed copy.
252
+ const outPath = opts.out && !toStdout ? path.resolve(opts.out) : null;
253
+ // Before the exists check, which a device can pass on Windows.
254
+ if (outPath && plan.isDeviceName(opts.out)) {
255
+ throw new UsageError(`${opts.out.split(/[\\/]/).pop()} is a name Windows keeps for a device, so nothing would be saved. Choose another name.`);
256
+ }
257
+ if (outPath && fs.existsSync(outPath)) throw new UsageError(`Will not overwrite ${outPath}, it already exists.`);
258
+ if (outPath) checkFolder(opts.out, outPath);
259
+ if (!fromStdin && !fs.existsSync(input)) throw new UsageError(`No such file: ${input}`);
260
+
261
+ const ffmpeg = binaries.resolve('ffmpeg', VENDOR);
262
+ const ffprobe = binaries.resolve('ffprobe', VENDOR);
263
+
264
+ let encodeDir = null;
265
+ try {
266
+ if (fromStdin) {
267
+ temp = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'justfits-')), 'input');
268
+ cleanup.add(path.dirname(temp));
269
+ if (!opts.quiet) process.stderr.write('Buffering stdin, two passes cannot read a pipe twice\n');
270
+ await readStdin(temp, input !== '-');
271
+ input = temp;
272
+ }
273
+
274
+ let info;
275
+ try {
276
+ info = await engine.probe(ffprobe, input);
277
+ } catch (err) {
278
+ // ffmpeg's own words ("Invalid data found when processing input") say
279
+ // nothing to a person. The same sentence the window uses.
280
+ throw Object.assign(new Error(`${fromStdin ? 'What arrived on stdin' : path.basename(input)} is not a video or picture that Just Fits can read.`), { code: 'not-media' });
281
+ }
282
+ const fits = info.bytes <= target.bytes && !toStdout;
283
+ if (opts.dryRun) {
284
+ const ext = info.kind === 'image' ? '.jpg' : '.mp4';
285
+ const would = fits ? (outPath || path.resolve(input)) : (outPath || (toStdout ? '-' : engine.outputPath(path.resolve(input), ext)));
286
+ report.result({ ok: true, dryRun: true, input: fromStdin ? '-' : path.resolve(input), output: would, before: info.bytes, target: target.bytes, fits });
287
+ if (!opts.quiet && !report.on) {
288
+ process.stderr.write(fits ? `${human(info.bytes)} already fits under ${human(target.bytes)}. Nothing would change.\n`
289
+ : `${human(info.bytes)} would be fitted under ${human(target.bytes)}${outPath ? `, to ${outPath}` : ''}.\n`);
290
+ }
291
+ return 0;
292
+ }
293
+ if (fits) {
294
+ // Same streams and same JSON shape as a real fit, and the file is where
295
+ // the caller asked for it, so a script can use the path either way.
296
+ let finalPath = path.resolve(input);
297
+ if (outPath) {
298
+ fs.copyFileSync(input, outPath, fs.constants.COPYFILE_EXCL);
299
+ finalPath = outPath;
300
+ }
301
+ const fields = {
302
+ ok: true, skipped: true, path: finalPath, input: path.resolve(input), output: finalPath,
303
+ before: info.bytes, after: info.bytes, target: target.bytes, bytes: info.bytes,
304
+ };
305
+ if (outPath) report.result(fields);
306
+ else report.skip({ ...fields, reason: 'fits-already', message: `${human(info.bytes)} already fits under ${human(target.bytes)}.` });
307
+ if (!report.on && !opts.quiet) {
308
+ process.stderr.write(`${human(info.bytes)} already fits under ${human(target.bytes)}. Nothing to do.${outPath ? ` ${outPath}` : ''}\n`);
309
+ }
310
+ return 0;
311
+ }
312
+
313
+ let last = '';
314
+ const onProgress = ({ stage, progress }) => {
315
+ if (report.on && opts.progress) {
316
+ process.stderr.write(JSON.stringify({ type: 'progress', stage, percent: Math.round(progress * 100) }) + '\n');
317
+ return;
318
+ }
319
+ if (opts.quiet || opts.json || !process.stderr.isTTY) return;
320
+ const line = `\r${stage} ${Math.round(progress * 100)}% `;
321
+ if (line !== last) { process.stderr.write(line); last = line; }
322
+ };
323
+
324
+ const args = { ffmpeg, file: input, info, targetBytes: target.bytes, onProgress };
325
+ // Writing to stdout still encodes to a real file first, for the same
326
+ // reason: the encoder needs somewhere it can seek.
327
+ if (toStdout) { args.outDir = encodeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'justfits-out-')); cleanup.add(encodeDir); }
328
+ else if (outPath) args.outDir = path.dirname(outPath);
329
+
330
+ const result = info.kind === 'image' ? await engine.fitImage(args) : await engine.fitVideo(args);
331
+ if (!opts.quiet && !opts.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
332
+
333
+ let finalPath = result.path;
334
+ if (toStdout) {
335
+ await new Promise((res, rej) => {
336
+ const rs = fs.createReadStream(result.path);
337
+ rs.pipe(process.stdout);
338
+ rs.on('end', res); rs.on('error', rej);
339
+ });
340
+ await drainStdout();
341
+ finalPath = '-';
342
+ } else if (outPath) {
343
+ // Checked again, since the encode can take minutes.
344
+ if (fs.existsSync(outPath)) throw new Error(`Will not overwrite ${outPath}, it appeared during the encode. The result is at ${result.path}`);
345
+ fs.renameSync(result.path, outPath);
346
+ finalPath = outPath;
347
+ }
348
+
349
+ report.result({
350
+ ok: !result.over, path: finalPath, input: fromStdin ? '-' : path.resolve(opts.file), output: finalPath,
351
+ before: info.bytes, after: result.bytes, bytes: result.bytes,
352
+ target: target.bytes, attempts: result.attempts,
353
+ width: result.plan.width, height: result.plan.height,
354
+ });
355
+ if (!report.on && !opts.quiet) {
356
+ const saved = Math.round((1 - result.bytes / info.bytes) * 100);
357
+ const where = finalPath === '-' ? '' : ` ${finalPath}`;
358
+ process.stderr.write(result.over
359
+ ? `Got to ${human(result.bytes)}, still over ${human(target.bytes)}.${where}\n`
360
+ : `${human(info.bytes)} to ${human(result.bytes)}, ${saved}% smaller.${where}\n`);
361
+ }
362
+ return result.over ? 4 : 0;
363
+ } finally {
364
+ if (temp) fs.rmSync(path.dirname(temp), { recursive: true, force: true });
365
+ if (encodeDir) fs.rmSync(encodeDir, { recursive: true, force: true });
366
+ }
367
+ }
368
+
369
+ // A reader that stops early (`| head`) is not an error worth a stack trace.
370
+ process.stdout.on('error', (err) => {
371
+ if (err.code === 'EPIPE') process.exit(0);
372
+ process.stderr.write(String(err.message || err) + '\n');
373
+ process.exit(1);
374
+ });
375
+
376
+ // Stopped by a signal: remove what this run made, and say so with the code
377
+ // the contract gives each signal.
378
+ for (const [sig, code] of [['SIGHUP', 129], ['SIGINT', 130], ['SIGTERM', 143]]) {
379
+ process.on(sig, () => {
380
+ for (const p of cleanup) { try { fs.rmSync(p, { recursive: true, force: true }); } catch (e) { /* gone already */ } }
381
+ process.exit(code);
382
+ });
383
+ }
384
+
385
+ module.exports = { describe, usage, OPTIONS, EXIT };
386
+
387
+ if (require.main === module) {
388
+ main(process.argv.slice(2))
389
+ .then(async (code) => { report.done(code); await drainStdout(); process.exit(code); })
390
+ .catch(async (err) => {
391
+ const usageError = err instanceof UsageError;
392
+ const code = usageError ? 2 : 1;
393
+ report.error(usageError ? 'usage' : (err.code || 'failed'), String(err.message || err));
394
+ process.stderr.write(String(err.message || err) + '\n');
395
+ report.done(code);
396
+ await drainStdout();
397
+ process.exit(code);
398
+ });
399
+ }