@procedures/browser 0.0.0-stage → 0.55.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/CHANGELOG.md +23 -0
- package/LICENSE +21 -0
- package/README.md +79 -2
- package/dist/browser.d.ts +37 -0
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +84 -0
- package/dist/browser.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/pdf.d.ts +28 -0
- package/dist/pdf.d.ts.map +1 -0
- package/dist/pdf.js +38 -0
- package/dist/pdf.js.map +1 -0
- package/dist/run.d.ts +69 -0
- package/dist/run.d.ts.map +1 -0
- package/dist/run.js +111 -0
- package/dist/run.js.map +1 -0
- package/dist/screenshot.d.ts +63 -0
- package/dist/screenshot.d.ts.map +1 -0
- package/dist/screenshot.js +108 -0
- package/dist/screenshot.js.map +1 -0
- package/package.json +66 -3
- package/src/browser.ts +99 -0
- package/src/index.ts +5 -0
- package/src/pdf.ts +52 -0
- package/src/run.ts +152 -0
- package/src/screenshot.ts +141 -0
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A screenshot of a page with a headless Chromium browser that is already installed. The render
|
|
3
|
+
* uses the headless run of `run.ts`. The browser loads the page in a window of the given size, and
|
|
4
|
+
* writes a PNG, JPEG or WebP picture of the window.
|
|
5
|
+
*/
|
|
6
|
+
import { extname } from "node:path";
|
|
7
|
+
import { headlessRender, readHead } from "./run.js";
|
|
8
|
+
/** The default size of the window: a common size of a desktop screen. */
|
|
9
|
+
export const DEFAULT_SCREENSHOT_SIZE = { width: 1280, height: 800 };
|
|
10
|
+
/** The largest side of the window, in CSS pixels. */
|
|
11
|
+
export const MAX_SCREENSHOT_SIDE = 16_384;
|
|
12
|
+
/** The extension of the temporary file of each format. */
|
|
13
|
+
export const SCREENSHOT_EXTENSIONS = { png: ".png", jpeg: ".jpg", webp: ".webp" };
|
|
14
|
+
/** The format of each extension of an output file. */
|
|
15
|
+
const FORMAT_OF_EXTENSION = { ".png": "png", ".jpg": "jpeg", ".jpeg": "jpeg", ".webp": "webp" };
|
|
16
|
+
/** The schemes of an address that the browser can load. */
|
|
17
|
+
const SCHEMES = new Set(["http:", "https:", "file:"]);
|
|
18
|
+
/**
|
|
19
|
+
* This function gives the format of a screenshot from the option `format` and the extension of
|
|
20
|
+
* the output file. It throws when the extension is not of a format, or when the two disagree.
|
|
21
|
+
*/
|
|
22
|
+
export function screenshotFormatOf(output, format) {
|
|
23
|
+
if (output === undefined)
|
|
24
|
+
return format ?? "png";
|
|
25
|
+
const extension = extname(output).toLowerCase();
|
|
26
|
+
const fromFile = FORMAT_OF_EXTENSION[extension];
|
|
27
|
+
if (fromFile === undefined)
|
|
28
|
+
throw new Error(`The output of a screenshot ends with .png, .jpg, .jpeg or .webp, not "${extension}"`);
|
|
29
|
+
if (format !== undefined && format !== fromFile)
|
|
30
|
+
throw new Error(`The output ${output} is a ${fromFile} file, and the format is ${format}`);
|
|
31
|
+
return fromFile;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* This function gives the argv of the browser. The argv has the flags of a headless screenshot,
|
|
35
|
+
* the profile folder, the window size and the time budget. The extra flags and the page follow.
|
|
36
|
+
*/
|
|
37
|
+
export function screenshotArgs(page, output, profile, size, budget, extra = []) {
|
|
38
|
+
return [
|
|
39
|
+
"--headless",
|
|
40
|
+
"--disable-gpu",
|
|
41
|
+
"--hide-scrollbars",
|
|
42
|
+
"--mute-audio",
|
|
43
|
+
"--no-first-run",
|
|
44
|
+
// A separate profile keeps the screenshot apart from a browser that the user has open
|
|
45
|
+
`--user-data-dir=${profile}`,
|
|
46
|
+
`--window-size=${size.width},${size.height}`,
|
|
47
|
+
...(budget !== undefined ? [`--virtual-time-budget=${budget}`] : []),
|
|
48
|
+
`--screenshot=${output}`,
|
|
49
|
+
...extra,
|
|
50
|
+
page,
|
|
51
|
+
];
|
|
52
|
+
}
|
|
53
|
+
/** This function tells if a file starts with the signature of a picture of the format. */
|
|
54
|
+
export function isImageFile(path, format) {
|
|
55
|
+
const head = readHead(path, 12);
|
|
56
|
+
if (format === "png")
|
|
57
|
+
return head.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));
|
|
58
|
+
if (format === "jpeg")
|
|
59
|
+
return head.subarray(0, 3).equals(Buffer.from([0xff, 0xd8, 0xff]));
|
|
60
|
+
return head.subarray(0, 4).toString("latin1") === "RIFF" && head.subarray(8, 12).toString("latin1") === "WEBP";
|
|
61
|
+
}
|
|
62
|
+
const isSide = (value) => Number.isInteger(value) && value >= 1 && value <= MAX_SCREENSHOT_SIDE;
|
|
63
|
+
/** This function gives the page of the options, and throws when they give not exactly one page. */
|
|
64
|
+
function pageOf({ url, html, file }) {
|
|
65
|
+
const count = [url, html, file].filter((each) => each !== undefined).length;
|
|
66
|
+
if (count !== 1)
|
|
67
|
+
throw new Error("renderScreenshot needs one of url, html and file");
|
|
68
|
+
if (url === undefined)
|
|
69
|
+
return html !== undefined ? { html } : { file: file };
|
|
70
|
+
let scheme;
|
|
71
|
+
try {
|
|
72
|
+
scheme = new URL(url).protocol;
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
scheme = "";
|
|
76
|
+
}
|
|
77
|
+
// An address with no scheme, for example "--flag", never reaches the argv of the browser
|
|
78
|
+
if (!SCHEMES.has(scheme))
|
|
79
|
+
throw new Error(`renderScreenshot needs an http, https or file address, not "${url}"`);
|
|
80
|
+
return { url };
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* This function loads a page in a headless browser, and writes a picture of the window. It gives
|
|
84
|
+
* the path and the size of the file and its format. It throws when it finds no browser, at the time
|
|
85
|
+
* limit, and when the file is not a picture of the format.
|
|
86
|
+
*
|
|
87
|
+
* The page can load each address that it names. Give an address that you trust, or a page of your
|
|
88
|
+
* own.
|
|
89
|
+
*/
|
|
90
|
+
export async function renderScreenshot(options) {
|
|
91
|
+
const source = pageOf(options);
|
|
92
|
+
const format = screenshotFormatOf(options.output, options.format);
|
|
93
|
+
const size = options.size ?? DEFAULT_SCREENSHOT_SIZE;
|
|
94
|
+
if (!isSide(size.width) || !isSide(size.height))
|
|
95
|
+
throw new Error(`The width and the height of a screenshot are integers from 1 to ${MAX_SCREENSHOT_SIDE}`);
|
|
96
|
+
const { budget } = options;
|
|
97
|
+
if (budget !== undefined && !(Number.isInteger(budget) && budget > 0))
|
|
98
|
+
throw new Error("The budget of a screenshot is a positive integer of milliseconds");
|
|
99
|
+
const render = {
|
|
100
|
+
prefix: "procedures-screenshot-",
|
|
101
|
+
file: `page${SCREENSHOT_EXTENSIONS[format]}`,
|
|
102
|
+
noun: `${format.toUpperCase()} file`,
|
|
103
|
+
argv: (page, output, profile, extra) => screenshotArgs(page, output, profile, size, budget, extra),
|
|
104
|
+
isValid: (path) => isImageFile(path, format),
|
|
105
|
+
};
|
|
106
|
+
return { ...(await headlessRender(render, source, options)), format };
|
|
107
|
+
}
|
|
108
|
+
//# sourceMappingURL=screenshot.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"screenshot.js","sourceRoot":"","sources":["../src/screenshot.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAiF,MAAM,UAAU,CAAC;AAWnI,yEAAyE;AACzE,MAAM,CAAC,MAAM,uBAAuB,GAAmB,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC;AAEpF,qDAAqD;AACrD,MAAM,CAAC,MAAM,mBAAmB,GAAG,MAAM,CAAC;AAE1C,0DAA0D;AAC1D,MAAM,CAAC,MAAM,qBAAqB,GAA+C,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,M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,MAAM,CAAC,IAAI,MAAM,GAAG,CAAC,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,kEAAkE,CAAC,CAAC;IAC3J,MAAM,MAAM,GAAmB;QAC7B,MAAM,EAAE,wBAAwB;QAChC,IAAI,EAAE,OAAO,qBAAqB,CAAC,MAAM,CAAC,EAAE;QAC5C,IAAI,EAAE,GAAG,MAAM,CAAC,WAAW,EAAE,OAAO;QACpC,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,CAAC,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC;QAClG,OAAO,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,WAAW,CAAC,IAAI,EAAE,MAAM,CAAC;KAC7C,CAAC;IACF,OAAO,EAAE,GAAG,CAAC,MAAM,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC;AACxE,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,69 @@
|
|
|
1
1
|
{
|
|
2
|
+
"$schema": "https://json.schemastore.org/package",
|
|
2
3
|
"name": "@procedures/browser",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
4
|
+
"version": "0.55.0",
|
|
5
|
+
"description": "Find a Chromium browser that is already installed (Edge, Chrome or Chromium), and render a page with it: a PDF file or a screenshot, with no browser download.",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"browser",
|
|
8
|
+
"headless",
|
|
9
|
+
"chrome",
|
|
10
|
+
"edge",
|
|
11
|
+
"pdf",
|
|
12
|
+
"screenshot",
|
|
13
|
+
"procedures"
|
|
14
|
+
],
|
|
15
|
+
"homepage": "https://mark1russell7.github.io/client/",
|
|
16
|
+
"bugs": {
|
|
17
|
+
"url": "https://github.com/mark1russell7/client/issues"
|
|
18
|
+
},
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "git+https://github.com/mark1russell7/client.git",
|
|
22
|
+
"directory": "packages/browser"
|
|
23
|
+
},
|
|
24
|
+
"license": "MIT",
|
|
25
|
+
"author": "Mark Russell (https://github.com/mark1russell7)",
|
|
26
|
+
"type": "module",
|
|
27
|
+
"main": "./dist/index.js",
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"import": "./dist/index.js"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"files": [
|
|
36
|
+
"dist",
|
|
37
|
+
"!dist/.tsbuildinfo",
|
|
38
|
+
"src",
|
|
39
|
+
"!src/**/*.test.ts",
|
|
40
|
+
"!src/**/*.test.tsx",
|
|
41
|
+
"!src/**/__tests__",
|
|
42
|
+
"CHANGELOG.md"
|
|
43
|
+
],
|
|
44
|
+
"sideEffects": false,
|
|
45
|
+
"engines": {
|
|
46
|
+
"node": ">=22"
|
|
47
|
+
},
|
|
48
|
+
"publishConfig": {
|
|
49
|
+
"access": "public",
|
|
50
|
+
"provenance": true
|
|
51
|
+
},
|
|
52
|
+
"dependencies": {
|
|
53
|
+
"@procedures/shell": "0.55.0"
|
|
54
|
+
},
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"typescript": "^7.0.2",
|
|
57
|
+
"@types/node": "^22.0.0",
|
|
58
|
+
"@mark1russell7/cue": "^2.1.1",
|
|
59
|
+
"vitest": "^5.0.3"
|
|
60
|
+
},
|
|
61
|
+
"client": null,
|
|
62
|
+
"scripts": {
|
|
63
|
+
"build": "tsc -b",
|
|
64
|
+
"typecheck": "tsc --noEmit && tsc -p tsconfig.test.json",
|
|
65
|
+
"clean": "rm -rf dist .tsbuildinfo",
|
|
66
|
+
"test": "vitest run",
|
|
67
|
+
"test:watch": "vitest"
|
|
68
|
+
}
|
|
6
69
|
}
|
package/src/browser.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Find a Chromium browser that is already installed: Microsoft Edge, Google Chrome or Chromium.
|
|
3
|
+
* The package does not download a browser.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { existsSync } from "node:fs";
|
|
7
|
+
import { posix, win32 } from "node:path";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The environment variable that names the browser program. It comes before the search. The name
|
|
11
|
+
* comes from `@procedures/pdf`, the first home of the search, and each render reads it.
|
|
12
|
+
*/
|
|
13
|
+
export const BROWSER_ENV = "PDF_BROWSER";
|
|
14
|
+
|
|
15
|
+
/** The second environment variable for the browser program. Other tools use this name too. */
|
|
16
|
+
export const CHROME_PATH_ENV = "CHROME_PATH";
|
|
17
|
+
|
|
18
|
+
/** The program names that the search looks for on the `PATH`, in order. */
|
|
19
|
+
export const BROWSER_NAMES: readonly string[] = [
|
|
20
|
+
"google-chrome",
|
|
21
|
+
"google-chrome-stable",
|
|
22
|
+
"chromium",
|
|
23
|
+
"chromium-browser",
|
|
24
|
+
"microsoft-edge",
|
|
25
|
+
"microsoft-edge-stable",
|
|
26
|
+
];
|
|
27
|
+
|
|
28
|
+
/** The program names on the `PATH` of Windows, in order. */
|
|
29
|
+
export const WINDOWS_BROWSER_NAMES: readonly string[] = ["msedge.exe", "chrome.exe"];
|
|
30
|
+
|
|
31
|
+
/** The options of `findBrowser`. Each one has a default from the host. */
|
|
32
|
+
export interface FindBrowserOptions {
|
|
33
|
+
/** The browser program. When it is set, the search does not occur. */
|
|
34
|
+
readonly executable?: string | undefined;
|
|
35
|
+
/** The environment (default: `process.env`). */
|
|
36
|
+
readonly env?: Readonly<Record<string, string | undefined>> | undefined;
|
|
37
|
+
/** The operating system (default: `process.platform`). */
|
|
38
|
+
readonly platform?: NodeJS.Platform | undefined;
|
|
39
|
+
/** The function that tells if a file exists (default: `existsSync`). */
|
|
40
|
+
readonly exists?: ((path: string) => boolean) | undefined;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** This function gives the folders of the `PATH`, in order. */
|
|
44
|
+
function pathFolders(env: Readonly<Record<string, string | undefined>>, windows: boolean): string[] {
|
|
45
|
+
const value = windows ? (env["Path"] ?? env["PATH"]) : env["PATH"];
|
|
46
|
+
if (value === undefined) return [];
|
|
47
|
+
return value.split(windows ? ";" : ":").filter((folder) => folder.length > 0);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* This function gives the paths that the search examines on an operating system, in order. The
|
|
52
|
+
* install folders come first, then the folders of the `PATH`.
|
|
53
|
+
*/
|
|
54
|
+
export function browserCandidates(platform: NodeJS.Platform, env: Readonly<Record<string, string | undefined>>): string[] {
|
|
55
|
+
if (platform === "win32") {
|
|
56
|
+
const programFiles = env["ProgramFiles"] ?? env["PROGRAMFILES"] ?? "C:\\Program Files";
|
|
57
|
+
const programFilesX86 = env["ProgramFiles(x86)"] ?? env["PROGRAMFILES(X86)"] ?? "C:\\Program Files (x86)";
|
|
58
|
+
const localAppData = env["LOCALAPPDATA"];
|
|
59
|
+
const installed = [
|
|
60
|
+
win32.join(programFilesX86, "Microsoft", "Edge", "Application", "msedge.exe"),
|
|
61
|
+
win32.join(programFiles, "Microsoft", "Edge", "Application", "msedge.exe"),
|
|
62
|
+
win32.join(programFiles, "Google", "Chrome", "Application", "chrome.exe"),
|
|
63
|
+
win32.join(programFilesX86, "Google", "Chrome", "Application", "chrome.exe"),
|
|
64
|
+
...(localAppData !== undefined
|
|
65
|
+
? [win32.join(localAppData, "Google", "Chrome", "Application", "chrome.exe"), win32.join(localAppData, "Chromium", "Application", "chrome.exe")]
|
|
66
|
+
: []),
|
|
67
|
+
];
|
|
68
|
+
const onPath = pathFolders(env, true).flatMap((folder) => WINDOWS_BROWSER_NAMES.map((name) => win32.join(folder, name)));
|
|
69
|
+
return [...installed, ...onPath];
|
|
70
|
+
}
|
|
71
|
+
const installed: string[] = [];
|
|
72
|
+
if (platform === "darwin") {
|
|
73
|
+
const bundles = [
|
|
74
|
+
"Google Chrome.app/Contents/MacOS/Google Chrome",
|
|
75
|
+
"Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
|
|
76
|
+
"Chromium.app/Contents/MacOS/Chromium",
|
|
77
|
+
];
|
|
78
|
+
const home = env["HOME"];
|
|
79
|
+
installed.push(...bundles.map((bundle) => posix.join("/Applications", bundle)));
|
|
80
|
+
if (home !== undefined) installed.push(...bundles.map((bundle) => posix.join(home, "Applications", bundle)));
|
|
81
|
+
}
|
|
82
|
+
const onPath = pathFolders(env, false).flatMap((folder) => BROWSER_NAMES.map((name) => posix.join(folder, name)));
|
|
83
|
+
return [...installed, ...onPath];
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* This function finds the browser program. The order is `executable`, then `PDF_BROWSER`, then
|
|
88
|
+
* `CHROME_PATH`, then the install folders and the `PATH`. It gives `undefined` when it finds none.
|
|
89
|
+
*/
|
|
90
|
+
export function findBrowser(options: FindBrowserOptions = {}): string | undefined {
|
|
91
|
+
if (options.executable !== undefined && options.executable.length > 0) return options.executable;
|
|
92
|
+
const env = options.env ?? process.env;
|
|
93
|
+
for (const name of [BROWSER_ENV, CHROME_PATH_ENV]) {
|
|
94
|
+
const value = env[name];
|
|
95
|
+
if (value !== undefined && value.length > 0) return value;
|
|
96
|
+
}
|
|
97
|
+
const exists = options.exists ?? existsSync;
|
|
98
|
+
return browserCandidates(options.platform ?? process.platform, env).find((candidate) => exists(candidate));
|
|
99
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// The package has no procedures. It gives functions only: the search, the run and the renders.
|
|
2
|
+
export * from "./browser.js";
|
|
3
|
+
export { DEFAULT_TIMEOUT_MS, type CommandRunner, type HeadlessOptions, type RenderResult } from "./run.js";
|
|
4
|
+
export { isPdfFile, pdfArgs, renderPdf, type RenderPdfOptions, type RenderPdfResult } from "./pdf.js";
|
|
5
|
+
export * from "./screenshot.js";
|
package/src/pdf.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTML to PDF with a headless Chromium browser that is already installed. The render uses the
|
|
3
|
+
* headless run of `run.ts`.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { headlessRender, readHead, type HeadlessOptions, type HeadlessRender, type RenderResult } from "./run.js";
|
|
7
|
+
|
|
8
|
+
/** The options of `renderPdf`. Give `html` or `file`, not the two. */
|
|
9
|
+
export interface RenderPdfOptions extends HeadlessOptions {
|
|
10
|
+
/** The HTML text. The function writes it to a temporary file. */
|
|
11
|
+
readonly html?: string | undefined;
|
|
12
|
+
/** The path of an HTML file. */
|
|
13
|
+
readonly file?: string | undefined;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** The result of `renderPdf`: the path and the size of the PDF file, and the browser program. */
|
|
17
|
+
export type RenderPdfResult = RenderResult;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* This function gives the argv of the browser. The argv has the flags of a headless print, the
|
|
21
|
+
* profile folder, the extra flags and the address of the page.
|
|
22
|
+
*/
|
|
23
|
+
export function pdfArgs(page: string, output: string, profile: string, extra: readonly string[] = []): string[] {
|
|
24
|
+
return [
|
|
25
|
+
"--headless",
|
|
26
|
+
"--disable-gpu",
|
|
27
|
+
"--no-pdf-header-footer",
|
|
28
|
+
// A separate profile keeps the print apart from a browser that the user has open
|
|
29
|
+
`--user-data-dir=${profile}`,
|
|
30
|
+
`--print-to-pdf=${output}`,
|
|
31
|
+
...extra,
|
|
32
|
+
page,
|
|
33
|
+
];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** This function tells if a file starts with the signature of a PDF file (`%PDF`). */
|
|
37
|
+
export function isPdfFile(path: string): boolean {
|
|
38
|
+
return readHead(path, 4).toString("latin1") === "%PDF";
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const PDF: HeadlessRender = { prefix: "procedures-pdf-", file: "page.pdf", noun: "PDF file", argv: pdfArgs, isValid: isPdfFile };
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* This function prints an HTML page to a PDF file with a headless browser. It gives the path and
|
|
45
|
+
* the size of the file. It throws when it finds no browser, at the time limit, and when the file
|
|
46
|
+
* is not a PDF file.
|
|
47
|
+
*/
|
|
48
|
+
export async function renderPdf(options: RenderPdfOptions): Promise<RenderPdfResult> {
|
|
49
|
+
const { html, file } = options;
|
|
50
|
+
if ((html === undefined) === (file === undefined)) throw new Error("renderPdf needs html or file, and not the two");
|
|
51
|
+
return headlessRender(PDF, html !== undefined ? { html } : { file: file! }, options);
|
|
52
|
+
}
|
package/src/run.ts
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The headless run of a browser that is already installed. The run starts the browser one time with
|
|
3
|
+
* argv, in a new temporary folder with its own profile. Each render of this package (the PDF file,
|
|
4
|
+
* the screenshot) uses this run, and gives only its flags and the check of its file.
|
|
5
|
+
*
|
|
6
|
+
* The browser starts through `runCommand` of `@procedures/shell`, not through a shell. A time limit
|
|
7
|
+
* and the signal of the call stop its process tree.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { closeSync, copyFileSync, mkdirSync, mkdtempSync, openSync, readSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { tmpdir } from "node:os";
|
|
12
|
+
import { dirname, join, resolve } from "node:path";
|
|
13
|
+
import { pathToFileURL } from "node:url";
|
|
14
|
+
import { runCommand, type CommandOptions, type CommandResult } from "@procedures/shell/command";
|
|
15
|
+
import { BROWSER_ENV, findBrowser, type FindBrowserOptions } from "./browser.js";
|
|
16
|
+
|
|
17
|
+
/** The default time limit of one render, in milliseconds. */
|
|
18
|
+
export const DEFAULT_TIMEOUT_MS = 60_000;
|
|
19
|
+
|
|
20
|
+
/** The function that runs a program. The default is `runCommand` of `@procedures/shell`. */
|
|
21
|
+
export type CommandRunner = (command: string, options: CommandOptions) => Promise<CommandResult>;
|
|
22
|
+
|
|
23
|
+
/** The options of each render. */
|
|
24
|
+
export interface HeadlessOptions extends FindBrowserOptions {
|
|
25
|
+
/** The path of the output file. The default is a file in a new temporary folder. */
|
|
26
|
+
readonly output?: string | undefined;
|
|
27
|
+
/** More flags for the browser, after the default flags. */
|
|
28
|
+
readonly args?: readonly string[] | undefined;
|
|
29
|
+
/** The time limit, in milliseconds (default: 60000). */
|
|
30
|
+
readonly timeout?: number | undefined;
|
|
31
|
+
/** When the signal aborts, the browser stops. */
|
|
32
|
+
readonly signal?: AbortSignal | undefined;
|
|
33
|
+
/** The function that runs the browser (default: `runCommand`). The tests give their own. */
|
|
34
|
+
readonly runner?: CommandRunner | undefined;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The result of a render. */
|
|
38
|
+
export interface RenderResult {
|
|
39
|
+
/** The absolute path of the output file. */
|
|
40
|
+
readonly path: string;
|
|
41
|
+
/** The size of the output file, in bytes. */
|
|
42
|
+
readonly bytes: number;
|
|
43
|
+
/** The browser program that made the file. */
|
|
44
|
+
readonly browser: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The page of a render: an address, an HTML text or the path of an HTML file. */
|
|
48
|
+
export type PageSource = { readonly url: string } | { readonly html: string } | { readonly file: string };
|
|
49
|
+
|
|
50
|
+
/** One kind of render: its flags, the name of its file and the check of the file. */
|
|
51
|
+
export interface HeadlessRender {
|
|
52
|
+
/** The start of the name of the temporary folder, for example `procedures-pdf-`. */
|
|
53
|
+
readonly prefix: string;
|
|
54
|
+
/** The name of the file that the browser writes in the temporary folder, for example `page.pdf`. */
|
|
55
|
+
readonly file: string;
|
|
56
|
+
/** The kind of the file in an error, for example `PDF file`. */
|
|
57
|
+
readonly noun: string;
|
|
58
|
+
/** This function gives the argv of the browser: the flags, the extra flags, then the page. */
|
|
59
|
+
argv(page: string, output: string, profile: string, extra: readonly string[]): string[];
|
|
60
|
+
/** This function tells if the file that the browser wrote is a file of this kind. */
|
|
61
|
+
isValid(path: string): boolean;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** This function gives the first bytes of a file, at most `count` bytes. */
|
|
65
|
+
export function readHead(path: string, count: number): Buffer {
|
|
66
|
+
const fd = openSync(path, "r");
|
|
67
|
+
try {
|
|
68
|
+
const head = Buffer.alloc(count);
|
|
69
|
+
const read = readSync(fd, head, 0, count, 0);
|
|
70
|
+
return head.subarray(0, read);
|
|
71
|
+
} finally {
|
|
72
|
+
closeSync(fd);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function fileSize(path: string): number | undefined {
|
|
77
|
+
try {
|
|
78
|
+
return statSync(path).size;
|
|
79
|
+
} catch {
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function lastLines(text: string, count = 5): string {
|
|
85
|
+
return text.trim().split(/\r?\n/).slice(-count).join("\n");
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* This function starts the browser one time for a render, and gives the path and the size of the
|
|
90
|
+
* file. It throws when it finds no browser, at the time limit and after a cancel. It also throws
|
|
91
|
+
* when the file is missing, empty or not of the kind of the render.
|
|
92
|
+
*
|
|
93
|
+
* An existing output file changes only after the check of the new file. Thus a failed render keeps
|
|
94
|
+
* an old output file.
|
|
95
|
+
*/
|
|
96
|
+
export async function headlessRender(render: HeadlessRender, source: PageSource, options: HeadlessOptions): Promise<RenderResult> {
|
|
97
|
+
const browser = findBrowser(options);
|
|
98
|
+
if (browser === undefined) {
|
|
99
|
+
throw new Error(`No browser found. Install Microsoft Edge, Google Chrome or Chromium, or set ${BROWSER_ENV} to the browser program.`);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const work = mkdtempSync(join(tmpdir(), render.prefix));
|
|
103
|
+
const profile = join(work, "profile");
|
|
104
|
+
const htmlFile = join(work, "page.html");
|
|
105
|
+
const output = resolve(options.output ?? join(work, render.file));
|
|
106
|
+
const written = join(work, render.file);
|
|
107
|
+
let made = false;
|
|
108
|
+
try {
|
|
109
|
+
let page: string;
|
|
110
|
+
if ("html" in source) {
|
|
111
|
+
writeFileSync(htmlFile, source.html, "utf8");
|
|
112
|
+
page = pathToFileURL(htmlFile).href;
|
|
113
|
+
} else if ("file" in source) {
|
|
114
|
+
page = pathToFileURL(resolve(source.file)).href;
|
|
115
|
+
} else {
|
|
116
|
+
page = source.url;
|
|
117
|
+
}
|
|
118
|
+
mkdirSync(dirname(output), { recursive: true });
|
|
119
|
+
|
|
120
|
+
const run = options.runner ?? runCommand;
|
|
121
|
+
const timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
|
|
122
|
+
const result = await run(browser, {
|
|
123
|
+
args: render.argv(page, written, profile, options.args ?? []),
|
|
124
|
+
timeout,
|
|
125
|
+
signal: options.signal,
|
|
126
|
+
maxOutputBytes: 64 * 1024,
|
|
127
|
+
keep: "tail",
|
|
128
|
+
});
|
|
129
|
+
if (result.error !== undefined) throw new Error(`The browser did not start: ${result.error}`);
|
|
130
|
+
if (result.timedOut === true) throw new Error(`The browser did not finish in ${timeout} ms`);
|
|
131
|
+
if (result.aborted === true) throw new Error("The render was cancelled");
|
|
132
|
+
|
|
133
|
+
const bytes = fileSize(written);
|
|
134
|
+
if (bytes === undefined || bytes === 0) {
|
|
135
|
+
const detail = lastLines(result.stderr || result.stdout);
|
|
136
|
+
throw new Error(`The browser made no ${render.noun} (exit code ${result.exitCode})${detail ? `: ${detail}` : ""}`);
|
|
137
|
+
}
|
|
138
|
+
if (!render.isValid(written)) throw new Error(`The file ${output} is not a ${render.noun}`);
|
|
139
|
+
// The temporary folder goes in `finally`, so a copy is enough, also across two drives
|
|
140
|
+
if (written !== output) copyFileSync(written, output);
|
|
141
|
+
made = true;
|
|
142
|
+
return { path: output, bytes, browser };
|
|
143
|
+
} finally {
|
|
144
|
+
// The temporary page and profile go. A default output stays in its folder after a success.
|
|
145
|
+
if (made && options.output === undefined) {
|
|
146
|
+
rmSync(profile, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
|
|
147
|
+
rmSync(htmlFile, { force: true });
|
|
148
|
+
} else {
|
|
149
|
+
rmSync(work, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A screenshot of a page with a headless Chromium browser that is already installed. The render
|
|
3
|
+
* uses the headless run of `run.ts`. The browser loads the page in a window of the given size, and
|
|
4
|
+
* writes a PNG, JPEG or WebP picture of the window.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { extname } from "node:path";
|
|
8
|
+
import { headlessRender, readHead, type HeadlessOptions, type HeadlessRender, type PageSource, type RenderResult } from "./run.js";
|
|
9
|
+
|
|
10
|
+
/** The formats of a screenshot. The browser chooses the format from the extension of the file. */
|
|
11
|
+
export type ScreenshotFormat = "png" | "jpeg" | "webp";
|
|
12
|
+
|
|
13
|
+
/** The size of the window of a screenshot, in CSS pixels. */
|
|
14
|
+
export interface ScreenshotSize {
|
|
15
|
+
readonly width: number;
|
|
16
|
+
readonly height: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The default size of the window: a common size of a desktop screen. */
|
|
20
|
+
export const DEFAULT_SCREENSHOT_SIZE: ScreenshotSize = { width: 1280, height: 800 };
|
|
21
|
+
|
|
22
|
+
/** The largest side of the window, in CSS pixels. */
|
|
23
|
+
export const MAX_SCREENSHOT_SIDE = 16_384;
|
|
24
|
+
|
|
25
|
+
/** The extension of the temporary file of each format. */
|
|
26
|
+
export const SCREENSHOT_EXTENSIONS: Readonly<Record<ScreenshotFormat, string>> = { png: ".png", jpeg: ".jpg", webp: ".webp" };
|
|
27
|
+
|
|
28
|
+
/** The format of each extension of an output file. */
|
|
29
|
+
const FORMAT_OF_EXTENSION: Readonly<Record<string, ScreenshotFormat>> = { ".png": "png", ".jpg": "jpeg", ".jpeg": "jpeg", ".webp": "webp" };
|
|
30
|
+
|
|
31
|
+
/** The schemes of an address that the browser can load. */
|
|
32
|
+
const SCHEMES: ReadonlySet<string> = new Set(["http:", "https:", "file:"]);
|
|
33
|
+
|
|
34
|
+
/** The options of `renderScreenshot`. Give one of `url`, `html` and `file`. */
|
|
35
|
+
export interface RenderScreenshotOptions extends HeadlessOptions {
|
|
36
|
+
/** The address of the page: `http`, `https` or `file`. */
|
|
37
|
+
readonly url?: string | undefined;
|
|
38
|
+
/** The HTML text. The function writes it to a temporary file. */
|
|
39
|
+
readonly html?: string | undefined;
|
|
40
|
+
/** The path of an HTML file. */
|
|
41
|
+
readonly file?: string | undefined;
|
|
42
|
+
/** The format. The default is the format of the extension of `output`, else `png`. */
|
|
43
|
+
readonly format?: ScreenshotFormat | undefined;
|
|
44
|
+
/** The size of the window (default: 1280 by 800). */
|
|
45
|
+
readonly size?: ScreenshotSize | undefined;
|
|
46
|
+
/**
|
|
47
|
+
* The virtual time that the scripts and the timers of the page get before the picture, in
|
|
48
|
+
* milliseconds. Without it, the picture follows the load event.
|
|
49
|
+
*/
|
|
50
|
+
readonly budget?: number | undefined;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The result of `renderScreenshot`: the path and the size of the picture, the browser program and the format. */
|
|
54
|
+
export interface RenderScreenshotResult extends RenderResult {
|
|
55
|
+
readonly format: ScreenshotFormat;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* This function gives the format of a screenshot from the option `format` and the extension of
|
|
60
|
+
* the output file. It throws when the extension is not of a format, or when the two disagree.
|
|
61
|
+
*/
|
|
62
|
+
export function screenshotFormatOf(output?: string, format?: ScreenshotFormat): ScreenshotFormat {
|
|
63
|
+
if (output === undefined) return format ?? "png";
|
|
64
|
+
const extension = extname(output).toLowerCase();
|
|
65
|
+
const fromFile = FORMAT_OF_EXTENSION[extension];
|
|
66
|
+
if (fromFile === undefined) throw new Error(`The output of a screenshot ends with .png, .jpg, .jpeg or .webp, not "${extension}"`);
|
|
67
|
+
if (format !== undefined && format !== fromFile) throw new Error(`The output ${output} is a ${fromFile} file, and the format is ${format}`);
|
|
68
|
+
return fromFile;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* This function gives the argv of the browser. The argv has the flags of a headless screenshot,
|
|
73
|
+
* the profile folder, the window size and the time budget. The extra flags and the page follow.
|
|
74
|
+
*/
|
|
75
|
+
export function screenshotArgs(page: string, output: string, profile: string, size: ScreenshotSize, budget?: number, extra: readonly string[] = []): string[] {
|
|
76
|
+
return [
|
|
77
|
+
"--headless",
|
|
78
|
+
"--disable-gpu",
|
|
79
|
+
"--hide-scrollbars",
|
|
80
|
+
"--mute-audio",
|
|
81
|
+
"--no-first-run",
|
|
82
|
+
// A separate profile keeps the screenshot apart from a browser that the user has open
|
|
83
|
+
`--user-data-dir=${profile}`,
|
|
84
|
+
`--window-size=${size.width},${size.height}`,
|
|
85
|
+
...(budget !== undefined ? [`--virtual-time-budget=${budget}`] : []),
|
|
86
|
+
`--screenshot=${output}`,
|
|
87
|
+
...extra,
|
|
88
|
+
page,
|
|
89
|
+
];
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** This function tells if a file starts with the signature of a picture of the format. */
|
|
93
|
+
export function isImageFile(path: string, format: ScreenshotFormat): boolean {
|
|
94
|
+
const head = readHead(path, 12);
|
|
95
|
+
if (format === "png") return head.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));
|
|
96
|
+
if (format === "jpeg") return head.subarray(0, 3).equals(Buffer.from([0xff, 0xd8, 0xff]));
|
|
97
|
+
return head.subarray(0, 4).toString("latin1") === "RIFF" && head.subarray(8, 12).toString("latin1") === "WEBP";
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const isSide = (value: unknown): boolean => Number.isInteger(value) && (value as number) >= 1 && (value as number) <= MAX_SCREENSHOT_SIDE;
|
|
101
|
+
|
|
102
|
+
/** This function gives the page of the options, and throws when they give not exactly one page. */
|
|
103
|
+
function pageOf({ url, html, file }: RenderScreenshotOptions): PageSource {
|
|
104
|
+
const count = [url, html, file].filter((each) => each !== undefined).length;
|
|
105
|
+
if (count !== 1) throw new Error("renderScreenshot needs one of url, html and file");
|
|
106
|
+
if (url === undefined) return html !== undefined ? { html } : { file: file! };
|
|
107
|
+
let scheme: string;
|
|
108
|
+
try {
|
|
109
|
+
scheme = new URL(url).protocol;
|
|
110
|
+
} catch {
|
|
111
|
+
scheme = "";
|
|
112
|
+
}
|
|
113
|
+
// An address with no scheme, for example "--flag", never reaches the argv of the browser
|
|
114
|
+
if (!SCHEMES.has(scheme)) throw new Error(`renderScreenshot needs an http, https or file address, not "${url}"`);
|
|
115
|
+
return { url };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* This function loads a page in a headless browser, and writes a picture of the window. It gives
|
|
120
|
+
* the path and the size of the file and its format. It throws when it finds no browser, at the time
|
|
121
|
+
* limit, and when the file is not a picture of the format.
|
|
122
|
+
*
|
|
123
|
+
* The page can load each address that it names. Give an address that you trust, or a page of your
|
|
124
|
+
* own.
|
|
125
|
+
*/
|
|
126
|
+
export async function renderScreenshot(options: RenderScreenshotOptions): Promise<RenderScreenshotResult> {
|
|
127
|
+
const source = pageOf(options);
|
|
128
|
+
const format = screenshotFormatOf(options.output, options.format);
|
|
129
|
+
const size = options.size ?? DEFAULT_SCREENSHOT_SIZE;
|
|
130
|
+
if (!isSide(size.width) || !isSide(size.height)) throw new Error(`The width and the height of a screenshot are integers from 1 to ${MAX_SCREENSHOT_SIDE}`);
|
|
131
|
+
const { budget } = options;
|
|
132
|
+
if (budget !== undefined && !(Number.isInteger(budget) && budget > 0)) throw new Error("The budget of a screenshot is a positive integer of milliseconds");
|
|
133
|
+
const render: HeadlessRender = {
|
|
134
|
+
prefix: "procedures-screenshot-",
|
|
135
|
+
file: `page${SCREENSHOT_EXTENSIONS[format]}`,
|
|
136
|
+
noun: `${format.toUpperCase()} file`,
|
|
137
|
+
argv: (page, output, profile, extra) => screenshotArgs(page, output, profile, size, budget, extra),
|
|
138
|
+
isValid: (path) => isImageFile(path, format),
|
|
139
|
+
};
|
|
140
|
+
return { ...(await headlessRender(render, source, options)), format };
|
|
141
|
+
}
|