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.
@@ -4,6 +4,7 @@
4
4
 
5
5
  const fs = require("fs");
6
6
  const path = require("path");
7
+ const { listen, within, heldBackIn, shown, said, aftermath, noticed, stopping, exit, reason, save, copyPlain } = require("../src/out");
7
8
 
8
9
  const HELP = `launch-film: a 20-40 second launch film made from a product's own site.
9
10
 
@@ -21,28 +22,42 @@ Usage:
21
22
  launch-film looks List the looks.
22
23
  launch-film types List the scene types and their fields.
23
24
  launch-film icons <word> Find icon names for a scene.
24
- launch-film doctor Check that Chrome and ffmpeg are found.
25
+ launch-film doctor Check that Chrome starts and that ffmpeg
26
+ and ffprobe 4.4 or newer are found.
25
27
 
26
28
  Options:
27
29
  --out <dir> Folder for the brand, film.json and the film
28
- (default: ./launch-film-<site>).
30
+ (default: ./launch-film-<site>). With frames, the
31
+ folder for the stills (default: frames/ next to the
32
+ film).
29
33
  --brand <path> Use a kit you already have: an easybrandkit folder
30
34
  or its brand.json.
31
35
  --words <file> Use a words.json you already have instead of reading
32
36
  the page again.
33
37
  --easybrandkit <cmd> The easybrandkit to run: a command, or the path of
34
- its scripts/easybrandkit.js (default:
35
- LAUNCH_FILM_EASYBRANDKIT, an easybrandkit on PATH,
36
- else easybrandkit with npx).
38
+ its skills/easybrandkit/scripts/easybrandkit.js
39
+ (default: LAUNCH_FILM_EASYBRANDKIT, an easybrandkit on
40
+ PATH, else easybrandkit with npx).
37
41
  Install it with npm install -g easybrandkit.
38
42
  --look <name> launch, aurora, gridline, pop or journal (default: picked
39
43
  from the brand).
40
44
  --seconds <n> Aim for this length, 20-40 (default 30).
41
45
  --aspect <ratio> 16:9 (default) or 9:16.
42
- --jobs <n> Clips rendered at once (default 2).
43
- --no-music Leave out the music bed.
44
- --no-sfx Leave out the sound effects.
46
+ --jobs <n> Clips rendered at once, 1 to 4 (default 2).
47
+ --no-music Plan the film without the music bed (plan, the
48
+ one-go command and stills <url>; a render plays what
49
+ "music" in film.json says). In film.json, "music" is
50
+ true (the look's bed), false (none), { "volume": 0.55 }
51
+ (the bed at another level) or the path of your own
52
+ track, from film.json's folder or absolute, at least
53
+ as long as the film.
54
+ --no-sfx Plan the film without the sound effects (a render
55
+ plays what "sfx" in film.json says).
45
56
  --keep Keep the work files (each clip's MP4).
57
+ --verbose Also print what easybrandkit says as it works (plan,
58
+ the one-go command and stills <url>).
59
+ --output <file> Where render writes the film (default: film.mp4 next
60
+ to film.json).
46
61
 
47
62
  Check options (CHECK.md, check.json, sheet.png and wave.png go to --out,
48
63
  default check/ next to the film; it exits with 1 when the film fails):
@@ -58,30 +73,162 @@ default check/ next to the film; it exits with 1 when the film fails):
58
73
  Stills options (the pictures and STILLS.md go to stills/ next to film.json):
59
74
  --for <targets> Any of ph, og, x, play, chrome (default: all of them).
60
75
 
76
+ A run that fails or is stopped leaves the folder it writes to as it was.
77
+ Set LAUNCH_FILM_CONFINE=1 when others give launch-film their film.json,
78
+ brand.json, kit or film: each may then name only files in its own folder,
79
+ none of them a list of other files for ffmpeg to open, such as an HLS
80
+ playlist, a kit may hold no link out of it, and check and frames refuse a
81
+ film that is such a list.
61
82
  Everything renders on this machine with Chrome and ffmpeg. No account or key.
62
83
  `;
63
84
 
85
+ // What a plan puts in the film's folder: words.json and film.json, and
86
+ // brand/, which takes the place of the folder's own whole.
87
+ const PLANNED = ["words.json", "film.json", "brand"];
88
+
89
+ // The options each command takes, as they are written. Any other is refused
90
+ // by name: an option dropped without a word reads as one that worked.
91
+ const PLANS = ["out", "brand", "words", "easybrandkit", "look", "seconds", "aspect", "no-music", "no-sfx", "verbose"];
92
+ const OPTIONS = {
93
+ "<url>": [...PLANS, "jobs", "keep"],
94
+ plan: PLANS,
95
+ render: ["jobs", "keep", "output"],
96
+ frames: ["out"],
97
+ check: ["out", "expect", "seconds", "lufs", "cues", "cuts", "allow"],
98
+ stills: ["for", ...PLANS],
99
+ // Of a film.json: the plan is made already. makersmcp gives every stills
100
+ // call its easybrandkit.
101
+ "stills <film.json>": ["for", "easybrandkit"],
102
+ looks: [],
103
+ types: [],
104
+ icons: [],
105
+ doctor: [],
106
+ };
107
+ const SWITCHES = new Set(["keep", "verbose"]);
108
+ // What each command reads besides its options. An argument past that is
109
+ // refused by name, as an option it does not take is. The address of the
110
+ // one-go command stands where a command's name would.
111
+ const ARGUMENTS = { "<url>": "one address", plan: "one address", render: "one film.json", frames: "one film", check: "one film", stills: "one address or film.json",
112
+ "stills <film.json>": "one address or film.json", looks: "no arguments", types: "no arguments", icons: "one word", doctor: "no arguments" };
113
+
114
+ // given holds the options as they are written, bare the options that take a
115
+ // value and came without one, valued the switches given one with =.
64
116
  function parseArgs(argv) {
65
- const out = { _: [], flags: {} };
117
+ const out = { _: [], flags: {}, given: [], bare: [], valued: [] };
66
118
  for (let i = 0; i < argv.length; i++) {
67
119
  const a = argv[i];
68
120
  if (a === "--help" || a === "-h") out.flags.help = true;
69
121
  else if (a === "--version" || a === "-v") out.flags.version = true;
70
- else if (/^--no-/.test(a)) out.flags[a.slice(5)] = false;
71
- else if (a === "--keep") out.flags.keep = true;
72
- else if (a.startsWith("--")) {
73
- const [key, inline] = a.slice(2).split("=");
74
- out.flags[key] = inline !== undefined ? inline : argv[++i];
75
- } else out._.push(a);
122
+ else if (/^--no-/.test(a)) {
123
+ out.flags[a.slice(5)] = false;
124
+ out.given.push(a);
125
+ } else if (a.startsWith("--")) {
126
+ // The value is all that follows the first =: a folder's name can
127
+ // hold one. Without an =, the next word is the value unless it is
128
+ // written as an option; one with a single dash is a value (--lufs -14).
129
+ const eq = a.indexOf("=");
130
+ const key = a.slice(2, eq < 0 ? undefined : eq);
131
+ out.given.push(`--${key}`);
132
+ if (SWITCHES.has(key)) {
133
+ out.flags[key] = true;
134
+ if (eq >= 0) out.valued.push(key);
135
+ } else {
136
+ const value = eq >= 0 ? a.slice(eq + 1) : String(argv[i + 1] || "").startsWith("--") ? "" : argv[++i];
137
+ if (value) out.flags[key] = value;
138
+ else out.bare.push(key);
139
+ }
140
+ } else if (a.startsWith("-")) out.given.push(a);
141
+ else out._.push(a);
76
142
  }
77
143
  return out;
78
144
  }
79
145
 
146
+ // A list as it is said: "a, b and c".
147
+ const listed = (items) => `${items.slice(0, -1).join(", ")}${items.length > 1 ? " and " : ""}${items[items.length - 1]}`;
148
+
149
+ // Why an option is not one of `command`'s, or null when all of them are.
150
+ function notTaken(given, command) {
151
+ const key = given.find((k) => !OPTIONS[command].includes(k.replace(/^--/, "")));
152
+ if (key === undefined) return null;
153
+ if (key === "--music") return '--music is not an option: a film plays what "music" in film.json says. Give the path of the track there, from film.json\'s folder or absolute';
154
+ if (key === "--no-music" || key === "--no-sfx") return `${key} is for a plan: a render plays what "${key.slice(5)}" in film.json says. Set it to false there and render again`;
155
+ return `${key} is not an option of launch-film ${command}, which takes ${OPTIONS[command].length ? listed(OPTIONS[command].map((k) => `--${k}`)) : "no options"}.`;
156
+ }
157
+
158
+ // Why a value given to one of `command`'s options cannot be used, or null:
159
+ // put right without a word (an --aspect of 4:3 planned 16:9), it read as if
160
+ // it had been used. The --seconds of check is a length to check against,
161
+ // read there.
162
+ function unusable(flags, command) {
163
+ const takes = (key) => flags[key] !== undefined && OPTIONS[command].includes(key);
164
+ if (takes("aspect") && !["16:9", "9:16"].includes(flags.aspect)) return `--aspect "${flags.aspect}": choose 16:9 or 9:16`;
165
+ if (takes("seconds") && command !== "check" && !(/^\d+(?:\.\d+)?$/.test(flags.seconds) && flags.seconds >= 20 && flags.seconds <= 40)) {
166
+ return `--seconds "${flags.seconds}": give a length from 20 to 40 seconds, such as 30`;
167
+ }
168
+ if (takes("jobs") && !/^[1-4]$/.test(flags.jobs)) return `--jobs "${flags.jobs}": give a whole number from 1 to 4`;
169
+ return null;
170
+ }
171
+
172
+ // The programs a command runs, looked at before any work (programs.js): one
173
+ // that cannot be started stops it there, named with what is wrong with it. A
174
+ // plan alone starts launch-film's Chrome only to read the page's words when
175
+ // its HTML lacks them, and goes on with the HTML's words when that Chrome
176
+ // cannot start (words.js), so it looks at that Chrome only then; easybrandkit
177
+ // looks at its own. It runs ffmpeg and ffprobe only for a store's address,
178
+ // when easybrandkit could not read the listing's pictures.
179
+ function programsOf(takes, address) {
180
+ if (["<url>", "render", "stills", "stills <film.json>"].includes(takes)) return ["ffmpeg", "ffprobe", "chrome"];
181
+ if (takes === "check" || takes === "frames") return ["ffmpeg", "ffprobe"];
182
+ if (takes !== "plan") return [];
183
+ const { isStoreUrl } = require("../src/store");
184
+ return address && isStoreUrl(address) ? ["ffmpeg", "ffprobe"] : [];
185
+ }
186
+
187
+ // Why an argument past the ones a command reads is refused, or null. A first
188
+ // word that is neither a command nor an address is told of as that, below.
189
+ function oneTooMany(command, takes, rest) {
190
+ const extra = rest[takes === "<url>" || ARGUMENTS[takes] === "no arguments" ? 0 : 1];
191
+ if (extra === undefined || (takes === "<url>" && !normaliseUrl(command))) return null;
192
+ return `launch-film ${takes} takes ${ARGUMENTS[takes]}, so "${extra}" would not be read.`;
193
+ }
194
+
80
195
  const say = (text) => process.stderr.write(text);
196
+ // A message as the line that says it: after "launch-film: ", unless it names
197
+ // launch-film itself first, as "launch-film needs ffmpeg, and ..." does.
198
+ const lineOf = (text) => `${/^launch-film /.test(text) ? "" : "launch-film: "}${text}\n`;
199
+ // A command given wrong: said, and the process ends.
81
200
  function fail(message) {
82
- say(`launch-film: ${message}\n`);
83
- process.exit(1);
201
+ // A stop ends the process by its own signal once it has cleaned up.
202
+ if (stopping()) return;
203
+ say(lineOf(said(message)));
204
+ // At once, or once the Chrome and ffmpeg still running have stopped.
205
+ exit(1);
206
+ }
207
+ // A run that failed: said with what became of its folder. A Ctrl-C reaches
208
+ // ffmpeg or ffprobe as well, and one that ends them while launch-film waits
209
+ // on them fails the run before launch-film's own handler for the signal has
210
+ // run: that comes once the event loop polls again, so the failure waits that
211
+ // long and, when it was a stop, the stop is told of instead.
212
+ function failed(err) {
213
+ const message = err && err.message ? err.message : String(err);
214
+ setImmediate(() => setImmediate(() => {
215
+ if (stopping()) return;
216
+ // A failure that says itself what became of its folder is not told of
217
+ // twice.
218
+ const folders = aftermath().filter((f) => !message.includes(f));
219
+ say(`${lineOf(err && err.ownWords ? shown(message) : said(message))}${folders.length ? `launch-film: ${folders.join(" and ")}.\n` : ""}`);
220
+ exit(1);
221
+ }));
84
222
  }
223
+ // A path as it is once the run that makes it has ended, from here.
224
+ const where = (file) => path.relative(process.cwd(), shown(file)) || shown(file);
225
+ const isDir = (file) => {
226
+ try {
227
+ return fs.statSync(file).isDirectory();
228
+ } catch {
229
+ return false;
230
+ }
231
+ };
85
232
 
86
233
  function normaliseUrl(raw) {
87
234
  let s = String(raw || "").trim();
@@ -95,70 +242,159 @@ function normaliseUrl(raw) {
95
242
  }
96
243
  }
97
244
 
98
- async function makePlan(url, flags) {
99
- const { runEasybrandkit, readBrand } = require("../src/brand");
100
- const { readWords } = require("../src/words");
101
- const { planFilm } = require("../src/plan");
245
+ // The film's folder: --out, else launch-film-<site> here.
246
+ function folderFor(url, flags) {
102
247
  const host = new URL(url).hostname.replace(/^www\./, "");
103
- const out = path.resolve(flags.out || `launch-film-${host.replace(/[^a-z0-9.-]/gi, "-")}`);
104
- fs.mkdirSync(out, { recursive: true });
105
- const { isStoreUrl, appStoreId, storeBrand } = require("../src/store");
106
- let brandFile;
107
- let storeWords = null;
248
+ return path.resolve(flags.out || `launch-film-${host.replace(/[^a-z0-9.-]/gi, "-")}`);
249
+ }
250
+
251
+ // What a plan is given, read before anything else, the programs it runs
252
+ // too: the words.json of --words, and the brand.json of the kit --brand
253
+ // names. A wrong one refuses the plan before anything is fetched or started.
254
+ // So does a plan without --brand into a folder whose brand/ holds files and
255
+ // no brand.json at all: easybrandkit, which makes its kit again in the run's
256
+ // copy of brand/ (makePlan), makes none in a folder of files that are not a
257
+ // kit's, and every release of it refuses one. A brand/ that is a link is
258
+ // left to makePlan, and so is a plan of an App Store page, which is read
259
+ // from the store when easybrandkit cannot read it. An earlier file of the
260
+ // folder's that the run would not replace, among `outputs`, refuses it too,
261
+ // before the site is read (out.js heldBack), and so does a folder among them
262
+ // this user may not write in.
263
+ function planArgs(flags, url, outputs) {
264
+ if (!flags.brand && !require("../src/store").appStoreId(url)) {
265
+ const own = path.join(folderFor(url, flags), "brand");
266
+ let names = [];
267
+ try {
268
+ if (!fs.lstatSync(own).isSymbolicLink()) names = fs.readdirSync(own);
269
+ } catch {
270
+ // No brand/ there, or one that makePlan tells of.
271
+ }
272
+ if (names.some((name) => !name.startsWith(".")) && !names.includes("brand.json")) {
273
+ throw new Error(`${own} is not empty and holds no earlier brand kit, which a plan has easybrandkit make there: give a kit with --brand, move the files in it elsewhere, or pick another folder with --out`);
274
+ }
275
+ }
276
+ const held = heldBackIn(folderFor(url, flags), outputs);
277
+ if (held) throw new Error(held);
278
+ let words = null;
279
+ if (flags.words) {
280
+ try {
281
+ words = JSON.parse(fs.readFileSync(path.resolve(flags.words), "utf8"));
282
+ } catch (err) {
283
+ throw new Error(`--words ${flags.words}: ${err.code === "ENOENT" ? "no such file" : err.message}`);
284
+ }
285
+ }
286
+ let brandFile = null;
108
287
  if (flags.brand) {
109
288
  brandFile = path.resolve(flags.brand);
110
- if (fs.existsSync(brandFile) && fs.statSync(brandFile).isDirectory()) brandFile = path.join(brandFile, "brand.json");
111
- if (!fs.existsSync(brandFile)) fail(`no brand.json at ${brandFile}`);
112
- // The film refers to the brand by a path from its own folder.
113
- const local = path.join(out, "brand");
114
- if (path.dirname(brandFile) !== local) {
115
- fs.rmSync(local, { recursive: true, force: true });
116
- fs.cpSync(path.dirname(brandFile), local, { recursive: true });
117
- brandFile = path.join(local, path.basename(brandFile));
118
- }
119
- } else if (isStoreUrl(url)) {
120
- // easybrandkit reads a store listing and the maker's site it names. When
121
- // it cannot, an App Store listing is read here from Apple's lookup API.
122
- const dir = path.join(out, "brand");
123
- say(`Reading the store listing with easybrandkit...\n`);
289
+ if (isDir(brandFile)) brandFile = path.join(brandFile, "brand.json");
290
+ if (!fs.existsSync(brandFile)) throw new Error(`no brand.json at ${brandFile}`);
291
+ }
292
+ return { words, brandFile };
293
+ }
294
+
295
+ // Reads the brand and the page and plans the film, in the run's part
296
+ // folder: brand/, words.json and film.json take the place of the folder's
297
+ // own when the run ends well. `inputs` is what planArgs read. Returns the
298
+ // film.json and the film it holds.
299
+ async function makePlan(url, flags, run, inputs) {
300
+ const { runEasybrandkit, readBrand } = require("../src/brand");
301
+ const { readWords, webPage } = require("../src/words");
302
+ const { planFilm } = require("../src/plan");
303
+ const { isStoreUrl, appStoreId, storeBrand } = require("../src/store");
304
+ // The film refers to the brand by a path from its own folder. A kit is
305
+ // copied as plain files, every link in it followed, so nothing this run
306
+ // does to the copy reaches where a link leads (a brand/ that links to a
307
+ // kit other films share, or a kit with a link in it). With
308
+ // LAUNCH_FILM_CONFINE set, a link may lead only to a file in the kit, as
309
+ // a brand.json may name only those: the copy would make what it leads to
310
+ // the kit's own.
311
+ const confine = require("../src/confine");
312
+ const held = confine.confined();
313
+ const local = run.folder("brand");
314
+ const copy = (from) => {
124
315
  try {
125
- brandFile = await runEasybrandkit(url, dir, { command: flags.easybrandkit, log: (t) => flags.verbose && say(t) });
126
- const kit = JSON.parse(fs.readFileSync(brandFile, "utf8"));
127
- const listing = (kit.stores || []).find((s) => s && /appstore|googleplay/i.test(String(s.type)) && s.ok !== false);
128
- if (!listing) throw new Error("easybrandkit read no store listing from it");
129
- kit.app = { name: listing.name || kit.name || "", by: listing.by || "", site: listing.site || "" };
130
- fs.writeFileSync(brandFile, JSON.stringify(kit, null, 2) + "\n");
316
+ copyPlain(from, local, { held });
131
317
  } catch (err) {
132
- if (!appStoreId(url)) fail(`${err.message}`);
133
- say(`easybrandkit could not read the listing (${err.message.split(". ")[0]}); reading it from the App Store instead.\n`);
134
- fs.rmSync(dir, { recursive: true, force: true });
135
- const made = await storeBrand(url, dir, { runEasybrandkit: (u, d, o) => runEasybrandkit(u, d, { ...o, command: flags.easybrandkit }), log: say });
136
- brandFile = made.brandFile;
318
+ if (err.held) throw new Error(`${path.join(from, err.held)} leads out of the kit's folder through a link, and LAUNCH_FILM_CONFINE allows only files in it`);
319
+ throw new Error(`copying the brand kit ${from} to ${local}: ${reason(err)}`);
137
320
  }
321
+ };
322
+ let brandFile;
323
+ let storeWords = null;
324
+ if (inputs.brandFile) {
325
+ copy(path.dirname(inputs.brandFile));
326
+ brandFile = path.join(local, path.basename(inputs.brandFile));
138
327
  } else {
139
- say(`Reading the brand of ${url} with easybrandkit...\n`);
140
- brandFile = await runEasybrandkit(url, path.join(out, "brand"), { command: flags.easybrandkit, log: (t) => flags.verbose && say(t) });
328
+ // easybrandkit makes its kit again where an earlier one is, keeping the
329
+ // files that are not a kit's: it works on a copy of the folder's own,
330
+ // which with LAUNCH_FILM_CONFINE set may not be a link out of the folder,
331
+ // as film.json's brand may not.
332
+ const own = path.join(run.dir, "brand");
333
+ if (isDir(own)) {
334
+ const out = held && confine.outside(run.dir, "brand", "the film");
335
+ if (out) throw new Error(`${own} ${out}, and LAUNCH_FILM_CONFINE allows only files in it`);
336
+ copy(own);
337
+ }
338
+ if (isStoreUrl(url)) {
339
+ // easybrandkit reads a store listing and the maker's site it names.
340
+ // When it cannot, an App Store listing is read here from Apple's
341
+ // lookup API.
342
+ say(`Reading the store listing with easybrandkit...\n`);
343
+ try {
344
+ brandFile = await runEasybrandkit(url, local, { command: flags.easybrandkit, log: (t) => flags.verbose && say(shown(t)) });
345
+ const kit = JSON.parse(fs.readFileSync(brandFile, "utf8"));
346
+ const listing = (kit.stores || []).find((s) => s && /appstore|googleplay/i.test(String(s.type)) && s.ok !== false);
347
+ if (!listing) throw new Error("easybrandkit read no store listing from it");
348
+ kit.app = { name: listing.name || kit.name || "", by: listing.by || "", site: listing.site || "" };
349
+ save(brandFile, JSON.stringify(kit, null, 2) + "\n");
350
+ } catch (err) {
351
+ if (!appStoreId(url)) throw err;
352
+ say(`easybrandkit could not read the listing (${shown(err.message.split(". ")[0])}); reading it from the App Store instead.\n`);
353
+ fs.rmSync(local, { recursive: true, force: true });
354
+ const made = await storeBrand(url, local, { runEasybrandkit: (u, d, o) => runEasybrandkit(u, d, { ...o, command: flags.easybrandkit }), log: say });
355
+ brandFile = made.brandFile;
356
+ }
357
+ } else {
358
+ say(`Reading the brand of ${url} with easybrandkit...\n`);
359
+ brandFile = await runEasybrandkit(url, local, { command: flags.easybrandkit, log: (t) => flags.verbose && say(shown(t)) });
360
+ }
141
361
  }
142
362
  const brand = readBrand(brandFile);
143
363
  // A kit made from an App Store page carries the listing's description.
144
364
  if (!storeWords && brand.app && brand.stores[0]) storeWords = require("../src/store").wordsFromListing({ name: brand.name, description: brand.stores[0].description });
145
365
  let words;
146
- if (flags.words) words = JSON.parse(fs.readFileSync(path.resolve(flags.words), "utf8"));
366
+ if (flags.words) words = inputs.words;
147
367
  else if (storeWords) words = storeWords;
148
368
  else {
369
+ // The page is the kit's own address, else the one given. A kit whose
370
+ // address is not a web page's (a file: one, which Chrome would open with
371
+ // this machine's files in reach) is refused as the kit's.
372
+ if (brand.url && !webPage(brand.url)) {
373
+ throw new Error(`${path.basename(brandFile)} gives the site's address as "${confine.said(brand.url, 120)}", which is not an http or https address: give a kit made from the site, or the page's words with --words`);
374
+ }
149
375
  say(`Reading the words on the page...\n`);
150
376
  words = await readWords(brand.url || url, { log: say });
151
377
  }
152
- fs.writeFileSync(path.join(out, "words.json"), JSON.stringify(words, null, 2) + "\n");
378
+ save(run.out("words.json"), JSON.stringify(words, null, 2) + "\n");
153
379
  const seconds = Math.min(40, Math.max(20, Number(flags.seconds) || 30));
154
- const film = planFilm(brand, words, { look: flags.look, seconds, aspect: flags.aspect === "9:16" ? "9:16" : "16:9", filmDir: out });
380
+ const film = planFilm(brand, words, { look: flags.look, seconds, aspect: flags.aspect === "9:16" ? "9:16" : "16:9", filmDir: run.part });
155
381
  if (flags.music === false) film.music = false;
156
382
  if (flags.sfx === false) film.sfx = false;
157
- const filmFile = path.join(out, "film.json");
158
- fs.writeFileSync(filmFile, JSON.stringify(film, null, 2) + "\n");
159
- for (const note of brand.notes) say(`note: ${note}\n`);
160
- say(`Planned ${film.clips.length} clips in the ${film.look} look: ${path.relative(process.cwd(), filmFile) || filmFile}\n`);
161
- return { filmFile, out };
383
+ const filmFile = run.out("film.json");
384
+ save(filmFile, JSON.stringify(film, null, 2) + "\n");
385
+ // An address no page shows that a page of the site asked for, which
386
+ // Chrome would hand to a program of the machine: on Linux the stand-ins
387
+ // kept it from that (chrome.js), here and in easybrandkit's Chrome.
388
+ // The first few, and how many more times one was asked for.
389
+ const { opened } = require("../src/chrome");
390
+ const { list, more } = opened();
391
+ const linux = process.platform === "linux";
392
+ const tried = list.map((a) => `The page tried to open ${a.length > 120 ? `${a.slice(0, 120)}...` : a}, which is not a web address: ` +
393
+ `${linux ? "it was not opened." : "Chrome hands such an address to the system, which may have opened a program for it."}`);
394
+ if (more) tried.push(`The page tried to open such an address ${more} more time${more > 1 ? "s" : ""}: ${linux ? "none was opened." : "Chrome hands each to the system, which may have opened a program for it."}`);
395
+ for (const note of [...brand.notes, ...tried]) say(`note: ${note}\n`);
396
+ say(`Planned ${film.clips.length} clips in the ${film.look} look: ${where(filmFile)}\n`);
397
+ return { filmFile, film };
162
398
  }
163
399
 
164
400
  async function render(filmFile, flags) {
@@ -170,29 +406,50 @@ async function render(filmFile, flags) {
170
406
  keep: Boolean(flags.keep),
171
407
  log: say,
172
408
  });
173
- for (const note of result.notes) say(`note: ${note}\n`);
174
- say(`Rendered ${result.seconds.toFixed(1)} s in ${((Date.now() - started) / 1000).toFixed(0)} s: ${result.output}\n`);
409
+ for (const note of result.notes) say(`note: ${shown(note)}\n`);
410
+ say(`Rendered ${result.seconds.toFixed(1)} s in ${((Date.now() - started) / 1000).toFixed(0)} s: ${shown(result.output)}\n`);
175
411
  return result;
176
412
  }
177
413
 
178
414
  async function frames(file, flags) {
179
415
  const { saveFrames } = require("../src/frames");
180
416
  const r = await saveFrames(file, { out: flags.out });
181
- say(`Saved ${r.stills.length} stills and a contact sheet: ${r.sheet}\n`);
417
+ say(`Saved ${r.stills.length} stills and a contact sheet: ${shown(r.sheet)}\n`);
182
418
  return r;
183
419
  }
184
420
 
185
421
  async function main() {
186
- const { _: args, flags } = parseArgs(process.argv.slice(2));
422
+ const { _: args, flags, given, bare, valued } = parseArgs(process.argv.slice(2));
423
+ // Ctrl-C or a signal stops the run and leaves its folder as it was.
424
+ listen();
425
+ // A reader that stops reading, as head does once it has its lines, leaves
426
+ // nothing to write to: the command ends as it would have, without a word,
427
+ // where the write that failed ended it in Node's stack trace.
428
+ process.stdout.on("error", (err) => {
429
+ if (err.code !== "EPIPE") throw err;
430
+ exit(process.exitCode || 0);
431
+ });
187
432
  if (flags.version) {
188
433
  process.stdout.write(`${require("../package.json").version}\n`);
189
434
  return;
190
435
  }
191
- if (flags.help || !args.length) {
436
+ if (flags.help || (!args.length && !given.some((k) => !k.startsWith("--")))) {
192
437
  process.stdout.write(HELP);
193
438
  return;
194
439
  }
195
440
  const [command, ...rest] = args;
441
+ const takes = command === "stills" && /\.json$/i.test(rest[0] || "") ? "stills <film.json>" : Object.hasOwn(OPTIONS, command) ? command : "<url>";
442
+ // What a command would not read is refused before anything runs: dropped
443
+ // without a word, it reads as if it had been done.
444
+ const refused = notTaken(given, takes) || (bare.length ? `--${bare[0]} needs a value` : null) ||
445
+ (valued.length ? `--${valued[0]} takes no value: give it alone, or leave it out` : null) || oneTooMany(command, takes, rest);
446
+ if (refused) return fail(refused);
447
+ if (flags.look !== undefined && OPTIONS[takes].includes("look")) {
448
+ const { LOOKS } = require("../src/motion");
449
+ if (!Object.hasOwn(LOOKS, flags.look)) return fail(`--look "${flags.look}": choose from ${Object.keys(LOOKS).join(", ")}`);
450
+ }
451
+ const unfit = unusable(flags, takes);
452
+ if (unfit) return fail(unfit);
196
453
  if (command === "looks") {
197
454
  const { LOOKS } = require("../src/motion");
198
455
  for (const [name, look] of Object.entries(LOOKS)) process.stdout.write(`${name.padEnd(9)} ${look.about}. Suits ${look.suits}.\n`);
@@ -212,59 +469,128 @@ async function main() {
212
469
  return;
213
470
  }
214
471
  if (command === "doctor") {
215
- const { findChrome } = require("../src/chrome");
216
- const { available } = require("../src/ffmpeg");
217
- const chrome = findChrome();
218
- const ffmpeg = available();
472
+ const { launch, evaluate } = require("../src/chrome");
473
+ const { check } = require("../src/programs");
474
+ const [chrome, ffmpeg, ffprobe] = ["chrome", "ffmpeg", "ffprobe"].map(check);
219
475
  const node = Number(process.versions.node.split(".")[0]);
220
- process.stdout.write(`node ${process.versions.node}${node >= 22 ? "" : " (22 or newer is needed)"}\nchrome ${chrome || "not found: install Chrome or set LAUNCH_FILM_CHROME"}\nffmpeg ${ffmpeg || "not found: install ffmpeg or set LAUNCH_FILM_FFMPEG"}\n`);
221
- if (!chrome || !ffmpeg || node < 22) process.exitCode = 1;
476
+ // ffmpeg 4.3 has no scdet for check and frames, 4.2 no xfade for the
477
+ // render. A version it does not say plainly (a build from git) passes.
478
+ const version = (c) => (/^\S+ version (\S+)/.exec(c.version || "") || [])[1] || "unknown";
479
+ const old = (c) => {
480
+ const v = /^n?(\d+)\.(\d+)/.exec(version(c));
481
+ return Boolean(v) && Number(v[1]) * 100 + Number(v[2]) < 404;
482
+ };
483
+ // Chrome is started as a render starts it, and a page in it runs a
484
+ // script: one that is there but cannot start its sandbox, as in a
485
+ // container whose seccomp keeps it from making namespaces, passed here
486
+ // and failed every render.
487
+ let unstarted = null;
488
+ if (!chrome.problem) {
489
+ try {
490
+ const browser = await launch({ W: 320, H: 240 });
491
+ try {
492
+ await evaluate(await browser.page(), "1 + 1");
493
+ } finally {
494
+ browser.close();
495
+ }
496
+ } catch (err) {
497
+ unstarted = err.message;
498
+ }
499
+ }
500
+ // Each program on its line: its version, or what is wrong with it.
501
+ const line = (c) => (c.problem ? c.detail : `${version(c)}${old(c) ? " (4.4 or newer is needed)" : ""}`);
502
+ process.stdout.write(`node ${process.versions.node}${node >= 22 ? "" : " (22 or newer is needed)"}\n` +
503
+ `chrome ${chrome.problem ? chrome.detail : `${chrome.file}${unstarted ? `: ${unstarted}` : ""}`}\n` +
504
+ `ffmpeg ${line(ffmpeg)}\n` +
505
+ `ffprobe ${line(ffprobe)}\n`);
506
+ if (chrome.problem || unstarted || ffmpeg.problem || old(ffmpeg) || ffprobe.problem || old(ffprobe) || node < 22) process.exitCode = 1;
222
507
  return;
223
508
  }
509
+ // The programs the command runs can be started (programs.js), looked at
510
+ // once what the command was given has been: a command given wrong is told
511
+ // so first. A Ctrl-C that ended one as it was asked its version is told of
512
+ // as the stop (failed). A plan that may start a Chrome, easybrandkit's or
513
+ // its own for the page's words, as it may unless it is given both --brand
514
+ // and --words, tries the stand-ins that Chrome gets first (chrome.js): on
515
+ // a temp folder where they cannot run, it stops here, not as it starts one.
516
+ const ready = (address = null) => {
517
+ const program = require("../src/programs").unstartable(programsOf(takes, address));
518
+ if (program) throw new Error(program);
519
+ if (address && !(flags.brand && flags.words)) require("../src/chrome").standIns();
520
+ };
224
521
  if (command === "render") {
225
- if (!rest[0]) fail("give the film.json to render");
522
+ if (!rest[0]) return fail("give the film.json to render");
523
+ ready();
226
524
  await render(path.resolve(rest[0]), flags);
227
525
  return;
228
526
  }
229
527
  if (command === "frames") {
230
- if (!rest[0]) fail("give the film's MP4");
528
+ if (!rest[0]) return fail("give the film's MP4");
529
+ ready();
231
530
  await frames(path.resolve(rest[0]), flags);
232
531
  return;
233
532
  }
234
533
  if (command === "check") {
235
- if (!rest[0]) fail("give the film's MP4 to check");
534
+ if (!rest[0]) return fail("give the film's MP4 to check");
535
+ ready();
236
536
  const { checkFilm } = require("../src/check");
237
537
  const r = await checkFilm(path.resolve(rest[0]), { out: flags.out, expect: flags.expect, seconds: flags.seconds, lufs: flags.lufs, cues: flags.cues, cuts: flags.cuts, allow: flags.allow });
238
538
  for (const c of r.checks.filter((x) => x.status === "fail" || x.status === "warn")) say(` ${c.status.padEnd(5)} ${c.name}: ${c.found}${c.expected ? ` (asked for ${c.expected})` : ""}\n`);
239
- say(`${r.pass ? "PASS" : "FAIL"}${r.warnings.length ? `, ${r.warnings.length} warning${r.warnings.length > 1 ? "s" : ""}` : ""}: ${path.relative(process.cwd(), path.join(r.dir, "CHECK.md"))}\n`);
539
+ say(`${r.pass ? "PASS" : "FAIL"}${r.warnings.length ? `, ${r.warnings.length} warning${r.warnings.length > 1 ? "s" : ""}` : ""}: ${where(path.join(r.dir, "CHECK.md"))}\n`);
240
540
  if (!r.pass) process.exitCode = 1;
241
541
  return;
242
542
  }
243
543
  if (command === "stills") {
244
544
  if (!rest[0]) fail("give the site's address or a film.json, e.g. launch-film stills example.com --for ph,og");
245
- const { makeStills, parseTargets } = require("../src/stills");
545
+ const { makeStills, parseTargets, stillsMade } = require("../src/stills");
246
546
  parseTargets(flags.for);
247
- let filmFile;
547
+ let r;
248
548
  if (/\.json$/i.test(rest[0])) {
249
- filmFile = path.resolve(rest[0]);
250
- if (!fs.existsSync(filmFile)) fail(`${rest[0]} is not a file`);
549
+ const filmFile = path.resolve(rest[0]);
550
+ if (!fs.existsSync(filmFile)) return fail(`${rest[0]} is not a file`);
551
+ ready();
552
+ r = await makeStills(filmFile, { targets: flags.for, log: say });
251
553
  } else {
252
554
  const url = normaliseUrl(rest[0]);
253
- if (!url) fail(`"${rest[0]}" is not an address or a film.json`);
254
- ({ filmFile } = await makePlan(url, flags));
555
+ if (!url) return fail(`"${rest[0]}" is not an address or a film.json`);
556
+ const inputs = planArgs(flags, url, [...PLANNED, "stills", ...stillsMade(flags.for).map((name) => path.join("stills", name))]);
557
+ ready(url);
558
+ // The plan and the stills are one run: both go in, or neither.
559
+ r = await within(folderFor(url, flags), async (run) => {
560
+ const { filmFile, film } = await makePlan(url, flags, run, inputs);
561
+ // How many pictures Product Hunt's gallery has is the plan's, so
562
+ // its earlier ones are looked at once the plan is made.
563
+ const held = heldBackIn(path.join(run.dir, "stills"), stillsMade(flags.for, film.clips));
564
+ if (held) throw new Error(held);
565
+ return makeStills(filmFile, { targets: flags.for, log: say });
566
+ });
255
567
  }
256
- const r = await makeStills(filmFile, { targets: flags.for, log: say });
257
- for (const note of r.notes) say(`note: ${note}\n`);
258
- say(`Made ${r.files.length} stills: ${path.relative(process.cwd(), path.join(r.dir, "STILLS.md"))}\n`);
568
+ for (const note of r.notes) say(`note: ${shown(note)}\n`);
569
+ say(`Made ${r.files.length} stills: ${where(path.join(r.dir, "STILLS.md"))}\n`);
259
570
  return;
260
571
  }
261
572
  const isPlan = command === "plan";
262
573
  const url = normaliseUrl(isPlan ? rest[0] : command);
263
- if (!url) fail(isPlan ? "give the site's address, e.g. launch-film plan example.com" : `"${command}" is not a command or an address. Run launch-film --help.`);
264
- const { filmFile, out } = await makePlan(url, flags);
265
- if (isPlan) return;
266
- const result = await render(filmFile, flags);
267
- await frames(result.output, { out: path.join(out, "frames") });
574
+ if (!url) return fail(isPlan ? "give the site's address, e.g. launch-film plan example.com" : `"${command}" is not a command or an address. Run launch-film --help.`);
575
+ const { framesMade } = require("../src/frames");
576
+ const made = isPlan ? [] : ["film.mp4", "film.timeline.json", "frames", ...framesMade().map((name) => path.join("frames", name))];
577
+ const inputs = planArgs(flags, url, [...PLANNED, ...made]);
578
+ ready(url);
579
+ // The plan, the film and its frames are one run: all go in, or none.
580
+ await within(folderFor(url, flags), async (run) => {
581
+ const { filmFile, film } = await makePlan(url, flags, run, inputs);
582
+ if (isPlan) return;
583
+ // Two frames for each of the plan's clips, looked at once the plan is
584
+ // made, before the render.
585
+ const held = heldBackIn(path.join(run.dir, "frames"), framesMade(film.clips.length));
586
+ if (held) throw new Error(held);
587
+ const result = await render(filmFile, flags);
588
+ await frames(result.output, { out: path.join(run.part, "frames") });
589
+ });
268
590
  }
269
591
 
270
- main().catch((err) => fail(err && err.message ? err.message : String(err)));
592
+ // A run that ended well says last what it found left by runs killed
593
+ // outright.
594
+ main().then(() => {
595
+ for (const note of noticed()) say(`note: ${note}\n`);
596
+ }, failed);