launch-film 0.2.0 → 0.3.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/src/chrome.js CHANGED
@@ -8,23 +8,51 @@
8
8
  // On a Mac, Chrome asks for the login keychain under a fresh profile unless
9
9
  // it is given a mock keychain and a basic password store: without them a
10
10
  // dialog came up on every render. The real HOME stays, so Chrome finds its
11
- // own files; the profile is a temp folder of its own.
11
+ // own files; the profile is a temp folder of its own, removed once Chrome
12
+ // has gone (and on a stop, with the pages' folders: out.js).
13
+ //
14
+ // A page can make Chrome save a file of its choosing, of any size, into the
15
+ // Downloads folder of the user it runs as, where nothing removes it: a site a
16
+ // plan read filled that folder, outside every folder of the run's. So every
17
+ // Chrome is told to refuse downloads before any page opens, and its profile
18
+ // names a folder inside it for them, should one still be saved.
12
19
 
13
20
  const fs = require("fs");
14
21
  const os = require("os");
15
22
  const path = require("path");
16
23
  const { spawn } = require("child_process");
17
24
  const { encoder } = require("./ffmpeg");
25
+ const { getSystemErrorMap } = require("util");
26
+ const { tempDir, tempEnv, release, track, socketFolder, closeProfile, save, socketFits, fetching, SOCKET_ROOM } = require("./out");
27
+
28
+ // A wait on Chrome that ran out, said with what to do: a machine too busy for
29
+ // Chrome is what made it this slow in the runs seen. A render of more than
30
+ // one clip at once adds that one at a time eases it (film.js).
31
+ function late(what) {
32
+ return Object.assign(new Error(`${what}, most often because the machine is too busy: run again once it is less busy`), { slow: true });
33
+ }
34
+
35
+ // Chrome or its page ended part way, as the system ends a process when
36
+ // memory runs out, said with what to do. A render of more than one clip at
37
+ // once adds that one at a time needs less (film.js): in a container of 2 GB
38
+ // two clips at once ran out of it some of the time.
39
+ function starved(what) {
40
+ return Object.assign(new Error(`${what}, most often because the system ran out of memory: run again once more of it is free`), { memory: true });
41
+ }
18
42
 
19
- function onPath(name) {
43
+ // The first program by `name` on PATH that the system would start: past a
44
+ // folder, a file it may not run and a script or a program whose interpreter
45
+ // or loader is not there, as programs.js looks. `passed`, when given, keeps
46
+ // the first it passed over in its `file`. A folder passed the X_OK this
47
+ // took, so a google-chrome folder first on PATH was taken for Chrome.
48
+ function onPath(name, passed = null) {
49
+ const { look } = require("./programs");
20
50
  for (const dir of String(process.env.PATH || "").split(path.delimiter)) {
21
- const file = path.join(dir, name);
22
- try {
23
- fs.accessSync(file, fs.constants.X_OK);
24
- return file;
25
- } catch {
26
- // Not here.
27
- }
51
+ const file = path.resolve(dir || ".", name);
52
+ const seen = look(file);
53
+ if (seen.missing) continue;
54
+ if (!seen.skip) return file;
55
+ if (passed && !passed.file) passed.file = file;
28
56
  }
29
57
  return null;
30
58
  }
@@ -33,7 +61,11 @@ function onPath(name) {
33
61
  // or Chromium.
34
62
  function findChrome() {
35
63
  const given = process.env.LAUNCH_FILM_CHROME || process.env.CHROME_PATH;
36
- if (given) return fs.existsSync(given) ? given : null;
64
+ // On Windows a path without .exe is the .exe, as spawn starts it.
65
+ if (given) {
66
+ const file = require("./programs").thereOf(given);
67
+ return fs.existsSync(file) ? file : null;
68
+ }
37
69
  const mac = [
38
70
  "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
39
71
  "/Applications/Chromium.app/Contents/MacOS/Chromium",
@@ -47,55 +79,336 @@ function findChrome() {
47
79
  ];
48
80
  const listed = process.platform === "darwin" ? mac : process.platform === "win32" ? win : [];
49
81
  for (const file of listed) if (file && fs.existsSync(file)) return file;
82
+ // When every one on PATH is passed over, the first is given, so that the
83
+ // look at it says what is wrong with it (programs.js).
84
+ const passed = {};
50
85
  for (const name of ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "chrome"]) {
51
- const found = onPath(name);
86
+ const found = onPath(name, passed);
52
87
  if (found) return found;
53
88
  }
54
- return null;
89
+ return passed.file || null;
55
90
  }
56
91
 
57
- // A browser with its own temp profile, answering protocol calls by promise.
58
- async function launch({ W = 1920, H = 1080, network = false } = {}) {
59
- const chrome = findChrome();
60
- if (!chrome) throw new Error("Chrome was not found. Install Google Chrome or Chromium, or set LAUNCH_FILM_CHROME to its path.");
61
- const profile = fs.mkdtempSync(path.join(os.tmpdir(), "launch-film-chrome-"));
62
- const args = [
92
+ // Why Chrome stopped. A sandbox it could not start ends Chrome at once,
93
+ // whatever signal or code it ends with, and is said as that, with what to do:
94
+ // as root Chrome runs without one, but anyone else gets it.
95
+ function stoppedWhy(code, signal, stderr) {
96
+ const fatal = /^.*:FATAL:[^\]]*\]\s*(.*\bsandbox\b.*)$/im.exec(stderr || "");
97
+ if (fatal) {
98
+ const said = fatal[1].split(/(?<=!)\s|\.\s/)[0].replace(/!$/, "").slice(0, 160);
99
+ return `Chrome could not start its sandbox (${said}). Run launch-film where Chrome's sandbox can start: Google Chrome's own package sets it up, and a container needs --security-opt seccomp=unconfined`;
100
+ }
101
+ if (signal === "SIGKILL") return starved("Chrome was stopped by SIGKILL").message;
102
+ if (signal) return `Chrome was stopped by ${signal}`;
103
+ return `Chrome stopped (exit ${code})${stderr ? `: ${stderr.trim().split("\n").slice(-2).join(" | ")}` : ""}`;
104
+ }
105
+
106
+ // ─── addresses that are no web page's ──────────────────────────────────────
107
+ // Chrome hands an address of a kind no page shows to the system, and a
108
+ // mailto:, news: or snews: one without asking: on Linux to xdg-email or
109
+ // xdg-open, which it finds on PATH. A page that went to mailto: as it loaded
110
+ // started the user's mail program, and on a server ran xdg-open with the
111
+ // site's address. So every Chrome launch-film starts, and the one
112
+ // easybrandkit starts for it (brand.js), has a folder of stand-ins first on
113
+ // its PATH, in a temp folder of the run's own, for each program Chrome or
114
+ // xdg-open hands such an address to, and for xdg-settings, which Chrome asks
115
+ // first which program takes its kind. A stand-in starts nothing and ends
116
+ // well, and notes what it was given beside it. Linux only: macOS and Windows hand
117
+ // the address to the system by no PATH, and no switch of Chrome's,
118
+ // preference of its profile or call of the DevTools protocol stops these
119
+ // three kinds there (README). A stand-in that cannot be run, from a temp
120
+ // folder on a disk mounted noexec, would be passed over for the real
121
+ // program, so no Chrome starts then. A plan says which addresses a page
122
+ // asked for (opened): those a page of launch-film's Chrome went to or opened
123
+ // a window for, and those that reached a stand-in, as from easybrandkit's.
124
+ // A page can ask for as many as it likes, each as long as it likes: the
125
+ // first NOTED of them are kept, each cut to NOTED_LENGTH characters, and the
126
+ // rest are counted, in memory and in the stand-ins' note alike.
127
+ const OPENERS = ["xdg-open", "xdg-email", "x-www-browser", "www-browser", "sensible-browser", "xdg-settings"];
128
+ const NOTED = 5;
129
+ const NOTED_LENGTH = 200;
130
+ const STAND_IN = `#!/bin/sh
131
+ d=\${0%/*}
132
+ a=$(printf '%s' "$*" | tr -d '\\r\\n' | head -c ${NOTED_LENGTH})
133
+ grep -qxF -- "$a" "$d/opened" 2>/dev/null && exit 0
134
+ if [ "$(wc -l < "$d/opened" 2>/dev/null || echo 0)" -lt ${NOTED} ]; then printf '%s\\n' "$a" >> "$d/opened"; else printf . >> "$d/more"; fi
135
+ exit 0
136
+ `;
137
+ let openers = null;
138
+ const asked = new Set();
139
+ let askedMore = 0;
140
+ // An address a page of launch-film's Chrome asked for, kept as the
141
+ // stand-ins keep one.
142
+ function ask(url) {
143
+ const address = String(url).replace(/[\r\n]/g, "").slice(0, NOTED_LENGTH);
144
+ if (asked.has(address)) return;
145
+ if (asked.size < NOTED) asked.add(address);
146
+ else askedMore++;
147
+ }
148
+ // The kinds of address a page shows, or that Chrome keeps to itself: any
149
+ // other it hands to the system.
150
+ const SHOWN = new Set(["http:", "https:", "data:", "blob:", "about:", "javascript:", "file:", "filesystem:", "chrome:", "chrome-error:", "chrome-untrusted:", "devtools:", "view-source:", "ws:", "wss:"]);
151
+ function handedOn(url) {
152
+ try {
153
+ return !SHOWN.has(new URL(String(url)).protocol);
154
+ } catch {
155
+ return false;
156
+ }
157
+ }
158
+ function openerFolder() {
159
+ if (process.platform !== "linux") return null;
160
+ if (openers && fs.existsSync(path.join(openers, "opened"))) return openers;
161
+ // PATH reads a ":" as the end of a folder, so a stand-ins' folder whose
162
+ // path holds one would be passed over for what comes after it on PATH,
163
+ // while the try below, which runs a stand-in by its path, still passed.
164
+ if (os.tmpdir().includes(path.delimiter)) {
165
+ throw new Error(`launch-film cannot put its stand-ins for xdg-open, which keep a page from starting a program of the machine's, first on Chrome's PATH from the temp folder ${os.tmpdir()}, ` +
166
+ `as PATH reads the "${path.delimiter}" in its path as the end of a folder: set TMPDIR to a folder whose path has no "${path.delimiter}"`);
167
+ }
168
+ // Chrome makes a socket in a folder of its own in the temp folder: where
169
+ // that socket's path would pass what a socket may have, every Chrome
170
+ // stopped with SIGABRT as it started, which said nothing of why, and left
171
+ // that folder behind. A socket's path is counted in bytes, and a letter
172
+ // outside ASCII takes two or more, so the message counts in bytes too.
173
+ if (!socketFits(os.tmpdir())) {
174
+ throw new Error(`launch-film cannot start Chrome from the temp folder ${os.tmpdir()}, as the socket Chrome makes in a folder there would have a path longer than the 107 bytes ` +
175
+ `a socket's path may have: set TMPDIR to a folder whose path takes at most ${SOCKET_ROOM} bytes (this one takes ${Buffer.byteLength(os.tmpdir())}, and a letter outside ASCII takes two or more)`);
176
+ }
177
+ const dir = tempDir("launch-film-bin-");
178
+ for (const name of OPENERS) save(path.join(dir, name), name === "xdg-settings" ? "#!/bin/sh\nexit 0\n" : STAND_IN);
179
+ for (const name of OPENERS) fs.chmodSync(path.join(dir, name), 0o700);
180
+ // As long as a program is given to say its version (programs.js): a busy
181
+ // machine took more than 20 s to start one.
182
+ const { ASK, short: shortOf } = require("./programs");
183
+ const tried = require("child_process").spawnSync(path.join(dir, OPENERS[0]), [], { timeout: ASK });
184
+ if (tried.error || tried.status !== 0) {
185
+ release(dir);
186
+ // The system short of a file descriptor or a process is not the disk,
187
+ // and neither is a machine too busy to start the stand-in in that time.
188
+ const short = shortOf(tried.error, "its stand-ins for xdg-open");
189
+ if (short) throw Object.assign(new Error(short), { short: true });
190
+ if (tried.error && tried.error.code === "ETIMEDOUT") {
191
+ throw Object.assign(new Error("launch-film could not run its stand-ins for xdg-open: they did not answer within two minutes, most often because the machine is too busy. Run it again once it is less busy."), { short: true });
192
+ }
193
+ const why = tried.error && `${(getSystemErrorMap().get(tried.error.errno) || [])[1] || tried.error.code}, ${tried.error.code}`;
194
+ throw new Error(`launch-film could not run its stand-ins for xdg-open in ${dir}${why ? ` (${why})` : ""}, which keep a page from starting a program of the machine's: ` +
195
+ "set TMPDIR to a folder on a disk where programs may run, as one mounted noexec runs none");
196
+ }
197
+ // The try is not an address a page asked for.
198
+ save(path.join(dir, "opened"), "");
199
+ fs.rmSync(path.join(dir, "more"), { force: true });
200
+ openers = dir;
201
+ return dir;
202
+ }
203
+
204
+ // The environment `env` with the stand-ins first on its PATH (Linux).
205
+ function withoutOpeners(env = process.env) {
206
+ const dir = openerFolder();
207
+ if (!dir) return env;
208
+ return { ...env, PATH: env.PATH ? `${dir}${path.delimiter}${env.PATH}` : `${dir}${path.delimiter}/usr/bin${path.delimiter}/bin` };
209
+ }
210
+
211
+ // On a Linux desktop Chrome hands such an address, from a frame, a redirect
212
+ // or a page, to the desktop's portal over the session bus
213
+ // (org.freedesktop.portal.OpenURI), which opens the program set for it, and
214
+ // never looks on PATH: a page read on a desktop opened the mail program so.
215
+ // So every Chrome launch-film starts there, and easybrandkit with the Chrome
216
+ // it starts, is given a session bus that leads nowhere, a socket in a folder
217
+ // of the run's own (`folder`) that is never made. Left unset, the bus would
218
+ // be looked for in XDG_RUNTIME_DIR, where the desktop's is. Chrome draws
219
+ // offscreen, so it is given no display either: no X display, and as its
220
+ // Wayland display a path in that folder that is never made, which Wayland
221
+ // takes as the display's socket itself. Left unset, that display too is
222
+ // looked for in XDG_RUNTIME_DIR, as wayland-0, which a Wayland desktop's
223
+ // is, so a program Chrome starts could open a window there. A display
224
+ // handed down already open (WAYLAND_SOCKET) goes as well.
225
+ function offTheDesktop(env, folder) {
226
+ if (process.platform !== "linux") return env;
227
+ const { DISPLAY, WAYLAND_DISPLAY, WAYLAND_SOCKET, ...rest } = env;
228
+ return { ...rest, DBUS_SESSION_BUS_ADDRESS: `unix:path=${busPath(path.join(folder, "no-bus"))}`, WAYLAND_DISPLAY: path.join(folder, "no-display") };
229
+ }
230
+
231
+ // A path as a bus address holds it: every byte but a letter, a digit and
232
+ // -_/.\* as %xx, so a comma, a semicolon or an equals sign in the temp
233
+ // folder's path is not read as the address's own.
234
+ function busPath(file) {
235
+ return [...Buffer.from(file, "utf8")].map((b) => (/[-0-9A-Za-z_/.\\*]/.test(String.fromCharCode(b)) ? String.fromCharCode(b) : `%${b.toString(16).padStart(2, "0")}`)).join("");
236
+ }
237
+
238
+ // What Chrome prints of the bus it was kept from, at every start
239
+ // ("ERROR:dbus/bus.cc:405] Failed to connect to the bus"): a line to pass
240
+ // over when what it said is told.
241
+ const BUS_NOISE = /^\[[^\]]*:ERROR:dbus\//;
242
+
243
+ // The addresses no page shows that pages asked for since the last call:
244
+ // those launch-film's Chrome saw a page go to or open a window for, and
245
+ // those handed to a stand-in. { list, more }: the first NOTED, each once,
246
+ // and how many more times one was asked for.
247
+ function opened() {
248
+ let text = "";
249
+ let more = 0;
250
+ if (openers) {
251
+ try {
252
+ text = fs.readFileSync(path.join(openers, "opened"), "utf8");
253
+ more = fs.statSync(path.join(openers, "more")).size;
254
+ } catch {
255
+ // None handed on, or none past the first.
256
+ }
257
+ save(path.join(openers, "opened"), "");
258
+ fs.rmSync(path.join(openers, "more"), { force: true });
259
+ }
260
+ const all = [...new Set([...asked, ...text.split("\n").filter(handedOn)])];
261
+ const list = all.slice(0, NOTED);
262
+ more += askedMore + all.length - list.length;
263
+ asked.clear();
264
+ askedMore = 0;
265
+ return { list, more };
266
+ }
267
+
268
+ // What Chrome is started with: the browser that renders the clips' pages
269
+ // (offline), or the one that reads a site's words (network).
270
+ function chromeArgs({ W = 1920, H = 1080, network = false, profile }) {
271
+ return [
63
272
  "--headless=new", "--hide-scrollbars", "--mute-audio", "--no-first-run", "--no-default-browser-check",
64
273
  "--disable-extensions", "--disable-sync", "--disable-default-apps", "--disable-background-networking",
65
274
  "--disable-component-update", "--disable-domain-reliability", "--disable-breakpad", "--metrics-recording-only",
66
275
  "--disable-features=Translate,MediaRouter,OptimizationHints,AutofillServerCommunication",
67
276
  "--use-mock-keychain", "--password-store=basic", "--force-color-profile=srgb", "--font-render-hinting=none",
68
- "--allow-file-access-from-files",
69
- ...(process.platform === "linux" ? ["--no-sandbox", "--disable-dev-shm-usage"] : []),
277
+ // Chrome's sandbox does not start as root; anyone else keeps it, so a
278
+ // page that breaks into Chrome's renderer is held there.
279
+ ...(process.getuid && process.getuid() === 0 ? ["--no-sandbox"] : []),
280
+ ...(process.platform === "linux" ? ["--disable-dev-shm-usage"] : []),
70
281
  ...(process.env.LAUNCH_FILM_GPU === "0" ? ["--disable-gpu"] : []),
71
- // Pages render offline: they carry their fonts and pictures with them.
72
- ...(network ? [] : ["--proxy-server=http://127.0.0.1:9", "--proxy-bypass-list=<-loopback>"]),
282
+ // Pages render offline: they carry their fonts and pictures with them,
283
+ // and are given their files by openPage. WebRTC goes around a proxy over
284
+ // UDP, so it is let send nothing but through the proxy, which is none.
285
+ ...(network ? [] : ["--proxy-server=http://127.0.0.1:9", "--proxy-bypass-list=<-loopback>", "--webrtc-ip-handling-policy=disable_non_proxied_udp"]),
73
286
  "--remote-debugging-pipe", `--user-data-dir=${profile}`, `--window-size=${W},${H}`, "about:blank",
74
287
  ];
75
- const child = spawn(chrome, args, { stdio: ["ignore", "ignore", "pipe", "pipe", "pipe"] });
288
+ }
289
+
290
+ // Whether the folder `dir` is a profile launch made: it holds the
291
+ // Preferences launch writes there before Chrome starts, which Chrome keeps,
292
+ // naming the folder's own Downloads. Other programs may name their folders
293
+ // lf- too, so of the folders so named that killed runs may have left, only
294
+ // such a profile goes (out.js, tempDir). Only a plain file is read: a pipe
295
+ // of that name would keep the read waiting.
296
+ function ownProfile(dir) {
297
+ const file = path.join(dir, "Default", "Preferences");
298
+ try {
299
+ return fs.lstatSync(file).isFile() && JSON.parse(fs.readFileSync(file, "utf8")).download.default_directory === path.join(dir, "Downloads");
300
+ } catch {
301
+ return false;
302
+ }
303
+ }
304
+
305
+ // A browser with its own temp profile, answering protocol calls by promise.
306
+ async function launch({ W = 1920, H = 1080, network = false } = {}) {
307
+ const chrome = findChrome();
308
+ if (!chrome) throw new Error("Chrome was not found. Install Google Chrome or Chromium, or set LAUNCH_FILM_CHROME to its path.");
309
+ // The stand-ins first, so a temp folder they cannot run in starts no Chrome.
310
+ openerFolder();
311
+ // Removed with the socket folder Chrome links from it, however the run
312
+ // ends: Chrome killed by a stop leaves that folder in the temp folder.
313
+ let socket = null;
314
+ // A Chrome with network access fetches a component in its first seconds,
315
+ // into folders it makes in its TMPDIR, and one that ends before that is
316
+ // done leaves them there (out.js, fetching). On Linux it is given its
317
+ // profile as its TMPDIR, so they go with the profile, and the socket
318
+ // Chrome makes in a folder there has to fit under it too (socketFits).
319
+ // Where TMPDIR leaves no room for that under the profile's usual name, the
320
+ // profile takes a shorter one where that leaves room for Chromium's socket
321
+ // as well, in a folder whose name is four bytes longer
322
+ // (org.chromium.Chromium.XXXXXX). Where it leaves none, as past 44 bytes
323
+ // with a pid of seven digits, Chrome is given TMPDIR itself, and the
324
+ // folders of that kind that came there while it ran go once it has ended
325
+ // (closeProfile).
326
+ const named = (prefix) => path.join(os.tmpdir(), `${prefix}${process.pid}-XXXXXX`);
327
+ const linux = network && process.platform === "linux";
328
+ const short = linux && !socketFits(named("launch-film-chrome-")) && Buffer.byteLength(named("lf-")) + 4 <= SOCKET_ROOM;
329
+ let fetched = null;
330
+ const profile = tempDir(short ? "lf-" : "launch-film-chrome-", (dir) => closeProfile(dir, socket, fetched), short ? ownProfile : null);
331
+ // Downloads, should Chrome save one in spite of the refusal below, go in
332
+ // the profile, which goes with the run.
333
+ fs.mkdirSync(path.join(profile, "Default"));
334
+ save(path.join(profile, "Default", "Preferences"), JSON.stringify({ download: { default_directory: path.join(profile, "Downloads"), prompt_for_download: false } }));
335
+ const args = chromeArgs({ W, H, network, profile });
336
+ const env = network ? tempEnv(profile) : process.env;
337
+ if (linux && env === process.env) fetched = fetching();
338
+ const child = track(spawn(chrome, args, { stdio: ["ignore", "ignore", "pipe", "pipe", "pipe"], env: withoutOpeners(offTheDesktop(env, profile)) }));
339
+ // One the system had no file descriptor for comes back with no pipes, and
340
+ // its error comes next (ffmpeg.js run): that is all there is to wait for.
341
+ if (!child.stdio) {
342
+ const err = await new Promise((resolve) => child.once("error", resolve));
343
+ release(profile);
344
+ const { short } = require("./programs");
345
+ throw Object.assign(new Error(short(err, "Chrome") || `Chrome could not be started from ${chrome}: ${err.message}`), { short: Boolean(short(err, "Chrome")) });
346
+ }
347
+ // What Chrome says, its lines about the bus it was kept from passed over,
348
+ // so they do not crowd out the line that says why it stopped.
76
349
  let stderr = "";
77
- child.stderr.on("data", (d) => (stderr = (stderr + d).slice(-4000)));
350
+ let partial = "";
351
+ const keep = (line) => {
352
+ if (!BUS_NOISE.test(line)) stderr = `${stderr}${line}\n`.slice(-4000);
353
+ };
354
+ child.stderr.on("data", (d) => {
355
+ const lines = `${partial}${d}`.split("\n");
356
+ partial = lines.pop().slice(-4000);
357
+ lines.forEach(keep);
358
+ });
359
+ child.stderr.on("end", () => {
360
+ if (partial) keep(partial);
361
+ partial = "";
362
+ });
78
363
  const pending = new Map();
79
364
  const listeners = new Set();
80
365
  let id = 0;
81
366
  let buf = Buffer.alloc(0);
82
367
  let dead = null;
83
- child.on("exit", (code) => {
84
- dead = new Error(`Chrome stopped (exit ${code})${stderr ? `: ${stderr.trim().split("\n").slice(-2).join(" | ")}` : ""}`);
368
+ let exited = false;
369
+ let closing = false;
370
+ const end = (err) => {
371
+ dead = err;
85
372
  for (const w of pending.values()) w.reject(dead);
86
373
  pending.clear();
374
+ };
375
+ // What Chrome printed last can come in after it exits, from a helper that
376
+ // holds its stderr: what is said of it waits for that, a second at most.
377
+ child.on("exit", (code, signal) => {
378
+ exited = true;
379
+ let told = false;
380
+ const tell = () => {
381
+ if (told) return;
382
+ told = true;
383
+ end(Object.assign(new Error(stoppedWhy(code, signal, stderr)), { memory: signal === "SIGKILL" }));
384
+ };
385
+ if (child.stderr.readableEnded) return tell();
386
+ child.stderr.once("end", tell);
387
+ setTimeout(tell, 1000).unref();
388
+ });
389
+ // A Chrome that cannot be started at all (a file that may not be run, or
390
+ // the folder Google Chrome.app) has no process to end, so its calls fail
391
+ // here. They waited for an answer that never came, and with nothing left
392
+ // to wait on, the run ended with 0 and no word.
393
+ child.on("error", (err) => {
394
+ const { short } = require("./programs");
395
+ if (short(err, "Chrome")) return end(Object.assign(new Error(short(err, "Chrome")), { short: true }));
396
+ const why = { EACCES: "permission denied", ENOENT: "no such file" }[err.code];
397
+ end(new Error(`Chrome could not be started from ${chrome}: ${why ? `${why} (${err.code})` : err.message}. Set LAUNCH_FILM_CHROME to the Chrome program itself, or install Google Chrome or Chromium`));
87
398
  });
88
- child.on("error", (e) => (dead = e));
89
399
  child.stdio[4].on("data", (chunk) => {
90
400
  buf = Buffer.concat([buf, chunk]);
91
401
  let i;
92
402
  while ((i = buf.indexOf(0)) >= 0) {
93
403
  const msg = JSON.parse(buf.subarray(0, i).toString("utf8"));
94
404
  buf = buf.subarray(i + 1);
405
+ // An address no page shows, that a page went to or opened a window
406
+ // for: Chrome would hand it to the system (above).
407
+ if ((msg.method === "Page.frameRequestedNavigation" || msg.method === "Page.windowOpen") && msg.params && handedOn(msg.params.url)) ask(msg.params.url);
95
408
  if (msg.id && pending.has(msg.id)) {
96
409
  const w = pending.get(msg.id);
97
410
  pending.delete(msg.id);
98
- if (msg.error) w.reject(new Error(msg.error.message));
411
+ if (msg.error) w.reject(Object.assign(new Error(msg.error.message), { answered: true }));
99
412
  else w.resolve(msg.result || {});
100
413
  } else for (const l of listeners) l(msg);
101
414
  }
@@ -106,13 +419,27 @@ async function launch({ W = 1920, H = 1080, network = false } = {}) {
106
419
  const n = ++id;
107
420
  // A call with no answer in 60 s is an error, not a hang.
108
421
  const timer = setTimeout(() => {
109
- if (pending.delete(n)) reject(new Error(`Chrome did not answer ${method} within 60 s`));
422
+ if (pending.delete(n)) reject(late(`Chrome did not answer ${method} within 60 s`));
110
423
  }, 60_000);
111
424
  timer.unref();
112
425
  pending.set(n, { resolve: (v) => (clearTimeout(timer), resolve(v)), reject: (e) => (clearTimeout(timer), reject(e)) });
113
426
  child.stdio[3].write(JSON.stringify({ id: n, method, params, ...(sessionId ? { sessionId } : {}) }) + "\0");
114
427
  });
115
- await send("Browser.getVersion");
428
+ // A Chrome that does not answer its first call, in time or at all, is
429
+ // ended here with its profile, since the caller never gets it to close:
430
+ // left running, its pipes kept the process up after doctor or a plan that
431
+ // went on with the page's HTML had ended. One that does not take the
432
+ // refusal of downloads is ended the same way, before it opens a page.
433
+ try {
434
+ await send("Browser.getVersion");
435
+ await send("Browser.setDownloadBehavior", { behavior: "deny" });
436
+ } catch (err) {
437
+ if (!exited) child.kill("SIGKILL");
438
+ release(profile);
439
+ for (const stream of [child.stderr, child.stdio[3], child.stdio[4]]) if (stream) stream.destroy();
440
+ throw err;
441
+ }
442
+ socket = socketFolder(profile);
116
443
  return {
117
444
  send,
118
445
  on: (fn) => listeners.add(fn),
@@ -122,9 +449,20 @@ async function launch({ W = 1920, H = 1080, network = false } = {}) {
122
449
  const { sessionId } = await send("Target.attachToTarget", { targetId, flatten: true });
123
450
  return { sessionId, targetId, call: (m, p) => send(m, p, sessionId) };
124
451
  },
452
+ // Chrome is asked to close, so its helpers (the GPU, network and page
453
+ // processes) end with it: killed outright, they went on writing to the
454
+ // profile for seconds. One that has not gone in 3 s is killed. The
455
+ // profile is removed once it has gone.
125
456
  close() {
126
- child.kill("SIGKILL");
127
- setTimeout(() => fs.rmSync(profile, { recursive: true, force: true }), 300).unref();
457
+ if (closing) return;
458
+ closing = true;
459
+ const gone = () => release(profile);
460
+ if (dead || exited) return gone();
461
+ child.once("exit", gone);
462
+ const timer = setTimeout(() => child.kill("SIGKILL"), 3000);
463
+ timer.unref();
464
+ child.once("exit", () => clearTimeout(timer));
465
+ send("Browser.close").catch(() => {});
128
466
  },
129
467
  };
130
468
  }
@@ -207,8 +545,13 @@ const CLOCK = String.raw`(() => {
207
545
  };
208
546
  })();`;
209
547
 
548
+ // Runs `expression` in the page. Chrome ends a script that runs on past
549
+ // `timeout` with no word but "Internal error", which is said here as that.
210
550
  async function evaluate(page, expression, timeout = 20_000) {
211
- const r = await page.call("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true, timeout });
551
+ const started = Date.now();
552
+ const r = await page.call("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true, timeout }).catch((err) => {
553
+ throw err.answered && Date.now() - started >= timeout ? late(`the page's script did not finish within ${timeout / 1000} s`) : err;
554
+ });
212
555
  if (r.exceptionDetails) {
213
556
  const d = r.exceptionDetails;
214
557
  throw new Error(`the page failed: ${((d.exception && d.exception.description) || d.text || "error").split("\n")[0]}`);
@@ -216,13 +559,79 @@ async function evaluate(page, expression, timeout = 20_000) {
216
559
  return r.result ? r.result.value : undefined;
217
560
  }
218
561
 
562
+ // A page is given its files by this process, at an https address of its
563
+ // own that leads nowhere on the network, and is never opened from the disk:
564
+ // it gets the files of its folder and nothing else. Chrome lets an https
565
+ // page open no file of the machine's, and every other address it asks for
566
+ // fails here. The folder's name is in the address, so no page is given
567
+ // another's file of the same name from Chrome's cache. Returns the page's
568
+ // address.
569
+ //
570
+ // Each file goes to Chrome in one DevTools message, which Chrome takes only
571
+ // up to 100 MB once the file is in base64: past that it answered nothing
572
+ // more, and the page waited out its load. So a file larger than
573
+ // PAGE_FILE_MAX fails the page at once, by name, and so does one Chrome
574
+ // refuses (fail): the pictures a film names are given as smaller copies when
575
+ // they are larger than this (film.js).
576
+ const PAGES = "https://launch-film.invalid";
577
+ const TYPES = { ".html": "text/html; charset=utf-8", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".svg": "image/svg+xml", ".webp": "image/webp" };
578
+ const PAGE_FILE_MAX = 64 * 1024 * 1024;
579
+ function serve(browser, page, dir, fail = () => {}) {
580
+ const base = `/${encodeURIComponent(path.basename(dir))}/`;
581
+ browser.on((msg) => {
582
+ if (msg.sessionId !== page.sessionId || msg.method !== "Fetch.requestPaused") return;
583
+ const { requestId, request } = msg.params;
584
+ let file = null;
585
+ try {
586
+ const u = new URL(request.url);
587
+ if (u.origin === PAGES && u.pathname.startsWith(base)) {
588
+ const at = path.join(dir, ...u.pathname.slice(base.length).split("/").map(decodeURIComponent));
589
+ const rel = path.relative(dir, at);
590
+ if (rel && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel)) file = at;
591
+ }
592
+ } catch {
593
+ // An address no page of ours has.
594
+ }
595
+ if (!file) return page.call("Fetch.failRequest", { requestId, errorReason: "BlockedByClient" }).catch(() => {});
596
+ const name = path.relative(dir, file).split(path.sep).join("/");
597
+ let size = 0;
598
+ try {
599
+ size = fs.statSync(file).size;
600
+ } catch {
601
+ // Not there: it is answered with a 404 below.
602
+ }
603
+ if (size > PAGE_FILE_MAX) {
604
+ page.call("Fetch.failRequest", { requestId, errorReason: "Failed" }).catch(() => {});
605
+ return fail(new Error(`the page's ${name} is ${Math.round(size / 1048576)} MB, more than the ${PAGE_FILE_MAX / 1048576} MB Chrome is given in one file`));
606
+ }
607
+ fs.readFile(file, (err, data) => {
608
+ const headers = [{ name: "Cache-Control", value: "no-store" }];
609
+ const answer = err ? { responseCode: 404, responseHeaders: headers, body: "" }
610
+ : { responseCode: 200, responseHeaders: [...headers, { name: "Content-Type", value: TYPES[path.extname(file).toLowerCase()] || "application/octet-stream" }], body: data.toString("base64") };
611
+ // A Chrome that refuses the file, or that has stopped, fails the page
612
+ // now. One too slow to answer is told of as that by the page's load.
613
+ page.call("Fetch.fulfillRequest", { requestId, ...answer }).catch((e) => e.slow || fail(e.answered ? new Error(`Chrome did not take the page's ${name}: ${e.message}`) : e));
614
+ });
615
+ });
616
+ return `${PAGES}${base}index.html`;
617
+ }
618
+
219
619
  // Opens a page from a folder (index.html and the files next to it) with the
220
620
  // clock in place, and waits for its fonts and pictures.
221
621
  async function openPage(browser, dir, { W, H, scale = 1 }) {
222
622
  const page = await browser.page();
223
623
  const exceptions = [];
624
+ // A page whose process the system ended, as it does when memory runs out,
625
+ // answers no call again: Chrome says so once, and every call that waits
626
+ // on the page fails then, where it failed after 60 s as a busy machine.
627
+ let crash = null;
628
+ const crashed = new Promise((resolve, reject) => (crash = reject));
629
+ crashed.catch(() => {});
630
+ const call = page.call;
631
+ page.call = (method, params) => Promise.race([call(method, params), crashed]);
224
632
  browser.on((msg) => {
225
633
  if (msg.sessionId !== page.sessionId) return;
634
+ if (msg.method === "Inspector.targetCrashed") crash(starved("Chrome's page crashed"));
226
635
  if (msg.method === "Runtime.exceptionThrown" && exceptions.length < 20) {
227
636
  const d = msg.params.exceptionDetails || {};
228
637
  exceptions.push(String((d.exception && d.exception.description) || d.text || "error").split("\n")[0].slice(0, 300));
@@ -242,33 +651,42 @@ async function openPage(browser, dir, { W, H, scale = 1 }) {
242
651
  browser.on(on);
243
652
  setTimeout(() => resolve(false), 30_000).unref();
244
653
  });
245
- const url = `file://${path.join(dir, "index.html").split(path.sep).map((p, i) => (i ? encodeURIComponent(p) : p)).join("/")}`;
654
+ // A file the page cannot be given fails it at once (serve).
655
+ let fail = null;
656
+ const failed = new Promise((resolve, reject) => (fail = reject));
657
+ failed.catch(() => {});
658
+ const url = serve(browser, page, dir, (err) => fail(err));
659
+ await page.call("Fetch.enable", { patterns: [{ urlPattern: "*" }] });
246
660
  await page.call("Page.navigate", { url });
247
- if (!(await loaded)) throw new Error("the page did not load within 30 s");
661
+ if (!(await Promise.race([loaded, failed, crashed]))) throw late("the page did not load within 30 s");
248
662
  const failedFonts = await evaluate(page, `Promise.all([document.fonts.ready, ...[...document.images].map((i) => i.decode().catch(() => {}))])
249
663
  .then(() => document.fonts.ready).then(() => [...document.fonts].filter((f) => f.status === "error").map((f) => f.family))`);
250
664
  return { page, exceptions, failedFonts: failedFonts || [] };
251
665
  }
252
666
 
253
667
  // Renders a page to a silent MP4: `seconds` at `fps`, each frame drawn for
254
- // its time and captured as a JPEG into ffmpeg. files: { name: Buffer } served
255
- // next to the page.
256
- async function renderPage({ html, files = {}, output, seconds, W = 1920, H = 1080, scale = 1, fps = 25, onFrame = null }) {
257
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "launch-film-page-"));
258
- fs.writeFileSync(path.join(dir, "index.html"), html);
668
+ // its time and captured as a JPEG into ffmpeg, whose libx264 is given
669
+ // `threads` when it is given. files: { name: Buffer } served next to the
670
+ // page.
671
+ async function renderPage({ html, files = {}, output, seconds, W = 1920, H = 1080, scale = 1, fps = 25, threads = 0, onFrame = null }) {
672
+ const dir = tempDir("launch-film-page-");
673
+ save(path.join(dir, "index.html"), html);
259
674
  for (const [name, data] of Object.entries(files)) {
260
675
  const file = path.join(dir, name);
261
676
  fs.mkdirSync(path.dirname(file), { recursive: true });
262
- fs.writeFileSync(file, data);
677
+ save(file, data);
263
678
  }
264
679
  const browser = await launch({ W, H });
265
- const enc = encoder({ output, fps });
680
+ const enc = encoder({ output, fps, threads });
266
681
  try {
267
682
  const { page, exceptions, failedFonts } = await openPage(browser, dir, { W, H, scale });
268
683
  const frames = Math.round(seconds * fps);
269
684
  for (let f = 0; f < frames; f++) {
270
685
  await evaluate(page, `__lfAdvance(${((f * 1000) / fps).toFixed(3)})`);
271
- const shot = await page.call("Page.captureScreenshot", { format: "jpeg", quality: 92, optimizeForSpeed: true });
686
+ // Chrome refused a frame of a page it had drawn others of: the page is
687
+ // fine, and what failed was Chrome, short of memory in the runs seen.
688
+ const shot = await page.call("Page.captureScreenshot", { format: "jpeg", quality: 92, optimizeForSpeed: true })
689
+ .catch((err) => Promise.reject(f > 0 && err.answered ? starved(`Chrome could not capture frame ${f + 1} (${err.message})`) : err));
272
690
  await enc.write(Buffer.from(shot.data, "base64"));
273
691
  if (onFrame) onFrame(f + 1, frames);
274
692
  }
@@ -280,15 +698,15 @@ async function renderPage({ html, files = {}, output, seconds, W = 1920, H = 108
280
698
  throw err;
281
699
  } finally {
282
700
  browser.close();
283
- fs.rmSync(dir, { recursive: true, force: true });
701
+ release(dir);
284
702
  }
285
703
  }
286
704
 
287
705
  // One still of a page at a time (ms), as PNG: for checks and tests.
288
706
  async function stillOf({ html, files = {}, at = 0, W = 1920, H = 1080, scale = 1 }) {
289
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "launch-film-page-"));
290
- fs.writeFileSync(path.join(dir, "index.html"), html);
291
- for (const [name, data] of Object.entries(files)) fs.writeFileSync(path.join(dir, name), data);
707
+ const dir = tempDir("launch-film-page-");
708
+ save(path.join(dir, "index.html"), html);
709
+ for (const [name, data] of Object.entries(files)) save(path.join(dir, name), data);
292
710
  const browser = await launch({ W, H });
293
711
  try {
294
712
  const { page, exceptions } = await openPage(browser, dir, { W, H, scale });
@@ -300,7 +718,7 @@ async function stillOf({ html, files = {}, at = 0, W = 1920, H = 1080, scale = 1
300
718
  return { png: Buffer.from(shot.data, "base64"), errors: exceptions };
301
719
  } finally {
302
720
  browser.close();
303
- fs.rmSync(dir, { recursive: true, force: true });
721
+ release(dir);
304
722
  }
305
723
  }
306
724
 
@@ -312,10 +730,10 @@ async function snapshots(pages) {
312
730
  const out = [];
313
731
  try {
314
732
  for (const p of pages) {
315
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "launch-film-page-"));
733
+ const dir = tempDir("launch-film-page-");
316
734
  try {
317
- fs.writeFileSync(path.join(dir, "index.html"), p.html);
318
- for (const [name, data] of Object.entries(p.files || {})) fs.writeFileSync(path.join(dir, name), data);
735
+ save(path.join(dir, "index.html"), p.html);
736
+ for (const [name, data] of Object.entries(p.files || {})) save(path.join(dir, name), data);
319
737
  const { page, exceptions } = await openPage(browser, dir, { W: p.W, H: p.H, scale: p.scale || 1 });
320
738
  let at = p.at || 0;
321
739
  if (at === "end") at = Math.round(Number(await evaluate(page, "window.__end ? window.__end() : 0")) || 0) + 150;
@@ -327,7 +745,7 @@ async function snapshots(pages) {
327
745
  out.push({ png: Buffer.from(shot.data, "base64"), errors: exceptions });
328
746
  await browser.send("Target.closeTarget", { targetId: page.targetId }).catch(() => {});
329
747
  } finally {
330
- fs.rmSync(dir, { recursive: true, force: true });
748
+ release(dir);
331
749
  }
332
750
  }
333
751
  } finally {
@@ -336,4 +754,4 @@ async function snapshots(pages) {
336
754
  return out;
337
755
  }
338
756
 
339
- module.exports = { findChrome, onPath, launch, openPage, renderPage, stillOf, snapshots, evaluate, CLOCK };
757
+ module.exports = { findChrome, onPath, chromeArgs, launch, openPage, renderPage, stillOf, snapshots, evaluate, standIns: openerFolder, withoutOpeners, offTheDesktop, busPath, opened, CLOCK, PAGE_FILE_MAX, OPENERS };