@emabuild/export 0.0.0-stage → 0.1.1
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/README.md +165 -2
- package/dist/assets.d.ts +63 -0
- package/dist/assets.d.ts.map +1 -0
- package/dist/assets.js +218 -0
- package/dist/assets.js.map +1 -0
- package/dist/browser.d.ts +86 -0
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +93 -0
- package/dist/browser.js.map +1 -0
- package/dist/export.d.ts +81 -0
- package/dist/export.d.ts.map +1 -0
- package/dist/export.js +73 -0
- package/dist/export.js.map +1 -0
- package/dist/handler.d.ts +65 -0
- package/dist/handler.d.ts.map +1 -0
- package/dist/handler.js +208 -0
- package/dist/handler.js.map +1 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +16 -0
- package/dist/index.js.map +1 -0
- package/dist/input.d.ts +23 -0
- package/dist/input.d.ts.map +1 -0
- package/dist/input.js +15 -0
- package/dist/input.js.map +1 -0
- package/dist/net.d.ts +42 -0
- package/dist/net.d.ts.map +1 -0
- package/dist/net.js +118 -0
- package/dist/net.js.map +1 -0
- package/dist/node.d.ts +16 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/node.js +117 -0
- package/dist/node.js.map +1 -0
- package/dist/zip.d.ts +46 -0
- package/dist/zip.d.ts.map +1 -0
- package/dist/zip.js +178 -0
- package/dist/zip.js.map +1 -0
- package/package.json +59 -3
package/README.md
CHANGED
|
@@ -1,3 +1,166 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @emabuild/export
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Server-side export for the [@emabuild](https://www.npmjs.com/package/@emabuild/core) email editor. It turns a design or email HTML into:
|
|
4
|
+
|
|
5
|
+
- **PNG/JPEG images**, such as template thumbnails or previews (headless Chromium)
|
|
6
|
+
- **PDF** (headless Chromium)
|
|
7
|
+
- **ZIP**: the HTML plus every referenced image, downloaded into `images/` with the references rewritten to relative paths. This needs no extra dependencies.
|
|
8
|
+
|
|
9
|
+
It runs on Node 18.17+ and ships ESM only. It also includes a Web Fetch HTTP handler and a `node:http` / Express adapter.
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install @emabuild/export
|
|
13
|
+
# Only needed for image/PDF export:
|
|
14
|
+
npm install playwright-core
|
|
15
|
+
npx playwright-core install chromium
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
`playwright-core` is an **optional** peer dependency. It is loaded with a dynamic import only when `exportImage` or `exportPdf` runs. If it is missing, those functions throw a `BrowserUnavailableError` that explains how to install it. The ZIP export works without it.
|
|
19
|
+
|
|
20
|
+
## Usage
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
import { exportImage, exportPdf, exportZip } from '@emabuild/export';
|
|
24
|
+
|
|
25
|
+
// Input: an HTML string, anything with { html } (e.g. the editor's exportHtml() result),
|
|
26
|
+
// or { design, toolRenderers, options? } (rendered with @emabuild/email-renderer)
|
|
27
|
+
const png = await exportImage(html, { width: 600, fullPage: true, type: 'png', deviceScaleFactor: 2 });
|
|
28
|
+
const thumb = await exportImage(html, { type: 'jpeg', quality: 70, fullPage: false, height: 900, deviceScaleFactor: 0.5 });
|
|
29
|
+
const pdf = await exportPdf(html, { format: 'A4', printBackground: true });
|
|
30
|
+
const zip = await exportZip(html, { fetchImages: true });
|
|
31
|
+
|
|
32
|
+
await fs.writeFile('email.zip', zip); // every result is a Uint8Array
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
### `exportImage(input, options)`
|
|
36
|
+
|
|
37
|
+
| Option | Default | |
|
|
38
|
+
|---|---|---|
|
|
39
|
+
| `width` | `600` | Viewport width (CSS px) |
|
|
40
|
+
| `height` | `800` | Viewport height. This is the image height when `fullPage` is false. |
|
|
41
|
+
| `fullPage` | `true` | Capture the whole page |
|
|
42
|
+
| `type` | `'png'` | `'png'` or `'jpeg'` |
|
|
43
|
+
| `quality` | `85` | JPEG quality (0 to 100) |
|
|
44
|
+
| `deviceScaleFactor` | `2` | Pixel density. Use a value below 1 for small thumbnails. |
|
|
45
|
+
| `omitBackground` | `false` | Transparent PNG background |
|
|
46
|
+
|
|
47
|
+
### `exportPdf(input, options)`
|
|
48
|
+
|
|
49
|
+
| Option | Default | |
|
|
50
|
+
|---|---|---|
|
|
51
|
+
| `format` | `'A4'` | `Letter`, `Legal`, `A3`, … |
|
|
52
|
+
| `printBackground` | `true` | Print background colours and images |
|
|
53
|
+
| `landscape` | `false` | |
|
|
54
|
+
| `margin` | `0` on every side | `{ top, right, bottom, left }` as CSS lengths |
|
|
55
|
+
| `scale` | `1` | 0.1 to 2 |
|
|
56
|
+
| `media` | `'screen'` | Emulated CSS media, so the PDF looks like the email |
|
|
57
|
+
| `width` | `800` | Viewport width used for layout |
|
|
58
|
+
|
|
59
|
+
### Browser options (image and PDF)
|
|
60
|
+
|
|
61
|
+
| Option | |
|
|
62
|
+
|---|---|
|
|
63
|
+
| `browser` | A Playwright `Browser` you already launched. It is reused and not closed. **Recommended for servers.** |
|
|
64
|
+
| `launchOptions` / `executablePath` | Used when a browser is launched for this call |
|
|
65
|
+
| `chromium` | A custom `chromium` BrowserType, e.g. from `playwright` |
|
|
66
|
+
| `timeout` | Default `30000` ms |
|
|
67
|
+
| `allowRequest(url)` | Network policy for the page. Return `false` to block a request. |
|
|
68
|
+
| `javaScriptEnabled` | Default `false`. Email HTML needs no JavaScript. |
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
import { launchBrowser } from '@emabuild/export';
|
|
72
|
+
const browser = await launchBrowser({ executablePath: '/usr/bin/chromium' });
|
|
73
|
+
const png = await exportImage(html, { browser });
|
|
74
|
+
await browser.close();
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
### `exportZip(input, options)`
|
|
78
|
+
|
|
79
|
+
The archive contains `index.html` and `images/<name>.<ext>`. These references are found and rewritten:
|
|
80
|
+
|
|
81
|
+
- `src` on `<img>`, `<input>`, `<source>` and VML `<v:fill>` / `<v:image>`, including references inside Outlook conditional comments
|
|
82
|
+
- `srcset` and `poster`
|
|
83
|
+
- the `background` attribute
|
|
84
|
+
- CSS `url(…)` in `style` attributes and `<style>` blocks
|
|
85
|
+
|
|
86
|
+
Each URL is downloaded once. Duplicate file names get a `-1`, `-2` suffix. Some references are left as they are: `data:`, `cid:`, merge tags such as `{{avatar}}`, and relative URLs when no `baseUrl` is given. If an image fails to download, its remote URL is kept and the failure is passed to `onImageError`.
|
|
87
|
+
|
|
88
|
+
| Option | Default | |
|
|
89
|
+
|---|---|---|
|
|
90
|
+
| `fetchImages` | `true` | Download images and rewrite references |
|
|
91
|
+
| `fetch` | `globalThis.fetch` | Custom fetch, e.g. one that adds auth headers or goes through a proxy |
|
|
92
|
+
| `baseUrl` | none | Resolve relative references against this URL |
|
|
93
|
+
| `assetsDir` | `'images'` | Folder for the downloaded images |
|
|
94
|
+
| `htmlFileName` | `'index.html'` | |
|
|
95
|
+
| `allowUrl(url)` | any http(s) URL | URL policy. It is checked on every redirect hop. |
|
|
96
|
+
| `timeoutMs` / `maxImageBytes` / `maxImages` / `concurrency` | 15 s / 10 MB / 200 / 6 | Limits |
|
|
97
|
+
| `extraFiles` | `[]` | Extra entries, e.g. `{ name: 'email.txt', data: plainText }` |
|
|
98
|
+
| `onImageError(failed)` | none | `[{ url, error }]` |
|
|
99
|
+
|
|
100
|
+
`localizeImages(html, options)` does the download-and-rewrite step without building the archive. It returns `{ html, assets, failed }`. `createZip(entries)` and `readZip(bytes)` are the small zip writer and reader that the package uses: stored or deflate entries, UTF-8 names, CRC-checked.
|
|
101
|
+
|
|
102
|
+
## HTTP handler
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
import { createExportHandler, toNodeHandler } from '@emabuild/export';
|
|
106
|
+
|
|
107
|
+
const handler = createExportHandler({
|
|
108
|
+
cors: ['https://app.example.com'],
|
|
109
|
+
authorize: (req) => req.headers.get('authorization') === `Bearer ${process.env.TOKEN}`,
|
|
110
|
+
image: { width: 600 }, // server-side defaults
|
|
111
|
+
pdf: { format: 'A4' },
|
|
112
|
+
browser: { executablePath: process.env.CHROMIUM_PATH },
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
// Web Fetch runtimes (Next.js route handlers, Hono, Bun, Deno…)
|
|
116
|
+
export const POST = handler;
|
|
117
|
+
|
|
118
|
+
// node:http / Express
|
|
119
|
+
app.use(toNodeHandler(handler));
|
|
120
|
+
process.on('SIGTERM', () => handler.close()); // closes the shared browser
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
| Route | Response |
|
|
124
|
+
|---|---|
|
|
125
|
+
| `POST /export/image` | `image/png` or `image/jpeg` |
|
|
126
|
+
| `POST /export/pdf` | `application/pdf` |
|
|
127
|
+
| `POST /export/zip` | `application/zip` |
|
|
128
|
+
|
|
129
|
+
The request body is JSON: `{ "html": "…", "options": { … }, "filename": "spring-sale" }`. If you configure `toolRenderers`, the body can send `{ "design": … }` instead of `html`. The response is the file itself, with `Content-Disposition: attachment; filename="spring-sale.png"`.
|
|
130
|
+
|
|
131
|
+
Clients can only set a whitelisted, clamped subset of options:
|
|
132
|
+
|
|
133
|
+
- **image:** `width` (100 to 2000), `height`, `type`, `quality`, `fullPage`, `deviceScaleFactor` (0.25 to 3)
|
|
134
|
+
- **pdf:** `format`, `landscape`, `printBackground`, `scale`
|
|
135
|
+
- **zip:** `fetchImages`
|
|
136
|
+
|
|
137
|
+
Everything else comes from the server-side defaults.
|
|
138
|
+
|
|
139
|
+
Handler options:
|
|
140
|
+
|
|
141
|
+
| Option | Default | |
|
|
142
|
+
|---|---|---|
|
|
143
|
+
| `basePath` | `'/export'` | Set it to `''` to match `…/image`, `…/pdf` and `…/zip` under any prefix |
|
|
144
|
+
| `cors` | `false` | `"*"`, one origin or a list of origins |
|
|
145
|
+
| `authorize` | none | Return `false` to reject the request with 401 |
|
|
146
|
+
| `maxBodyBytes` | 5 MB | |
|
|
147
|
+
| `maxConcurrency` | `4` | Concurrent browser exports |
|
|
148
|
+
| `allowPrivateNetwork` | `false` | See below |
|
|
149
|
+
| `toolRenderers` | none | Lets clients send `{ design }` |
|
|
150
|
+
| `onError` | none | Logging hook |
|
|
151
|
+
|
|
152
|
+
Error responses:
|
|
153
|
+
|
|
154
|
+
- `400`: invalid body
|
|
155
|
+
- `401`: rejected by `authorize`
|
|
156
|
+
- `404`: unknown route
|
|
157
|
+
- `405`: method other than POST or OPTIONS
|
|
158
|
+
- `413`: body too large
|
|
159
|
+
- `501`: Chromium or `playwright-core` is unavailable
|
|
160
|
+
- `500`: the export failed
|
|
161
|
+
|
|
162
|
+
**Security.** The handler renders HTML sent by clients, so by default it blocks every request to loopback, private, link-local and `localhost` / `*.local` / `*.internal` hosts. This covers both the browser page's requests and the ZIP image downloads, redirects included. It also disables page JavaScript. The checks work on host names and literal IPs; they do not resolve DNS. If names could resolve to internal addresses, run the service behind an egress proxy as well.
|
|
163
|
+
|
|
164
|
+
## License
|
|
165
|
+
|
|
166
|
+
MIT
|
package/dist/assets.d.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module assets
|
|
3
|
+
*
|
|
4
|
+
* Find the images referenced by an HTML document, download them and rewrite
|
|
5
|
+
* the references to relative paths (for the ZIP export).
|
|
6
|
+
*
|
|
7
|
+
* References found: `src` of `<img>`, `<input>`, `<source>` and the VML
|
|
8
|
+
* `<v:fill>` / `<v:image>` / `<v:imagedata>` tags (also inside Outlook
|
|
9
|
+
* conditional comments), `srcset`, `poster`, the `background` attribute,
|
|
10
|
+
* and CSS `url(…)` in `style` attributes and `<style>` blocks.
|
|
11
|
+
*/
|
|
12
|
+
import { type UrlPolicy } from './net.js';
|
|
13
|
+
/** Options of {@link localizeImages} */
|
|
14
|
+
export interface LocalizeImagesOptions {
|
|
15
|
+
/** Fetch implementation (default `globalThis.fetch`) */
|
|
16
|
+
fetch?: typeof fetch;
|
|
17
|
+
/** Base URL to resolve relative references against (default: relative references are left alone) */
|
|
18
|
+
baseUrl?: string;
|
|
19
|
+
/** Folder for downloaded images inside the archive (default `images`) */
|
|
20
|
+
assetsDir?: string;
|
|
21
|
+
/** URL policy, checked for every request and redirect hop (default: any http/https URL) */
|
|
22
|
+
allowUrl?: UrlPolicy;
|
|
23
|
+
/** Per-image timeout in ms (default 15 000) */
|
|
24
|
+
timeoutMs?: number;
|
|
25
|
+
/** Per-image size limit in bytes (default 10 MB) */
|
|
26
|
+
maxImageBytes?: number;
|
|
27
|
+
/** Maximum number of images (default 200); the rest keep their remote URL */
|
|
28
|
+
maxImages?: number;
|
|
29
|
+
/** Parallel downloads (default 6) */
|
|
30
|
+
concurrency?: number;
|
|
31
|
+
}
|
|
32
|
+
/** A downloaded image */
|
|
33
|
+
export interface LocalAsset {
|
|
34
|
+
/** Original (resolved) URL */
|
|
35
|
+
url: string;
|
|
36
|
+
/** Relative path inside the archive (`images/logo.png`) */
|
|
37
|
+
path: string;
|
|
38
|
+
contentType: string;
|
|
39
|
+
data: Uint8Array;
|
|
40
|
+
}
|
|
41
|
+
/** Result of {@link localizeImages} */
|
|
42
|
+
export interface LocalizedHtml {
|
|
43
|
+
/** HTML with downloaded image references rewritten to relative paths */
|
|
44
|
+
html: string;
|
|
45
|
+
/** Downloaded files */
|
|
46
|
+
assets: LocalAsset[];
|
|
47
|
+
/** Images that could not be downloaded (their references are unchanged) */
|
|
48
|
+
failed: {
|
|
49
|
+
url: string;
|
|
50
|
+
error: string;
|
|
51
|
+
}[];
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Download every image referenced by `html` and rewrite the references to
|
|
55
|
+
* relative paths (`images/<name>.<ext>`). Images that fail (network error,
|
|
56
|
+
* blocked URL, not an image, too large) keep their original URL and are
|
|
57
|
+
* listed in `failed`. The same URL is downloaded once.
|
|
58
|
+
*
|
|
59
|
+
* @param html - HTML document
|
|
60
|
+
* @param options - Fetch, policy and naming options
|
|
61
|
+
*/
|
|
62
|
+
export declare function localizeImages(html: string, options?: LocalizeImagesOptions): Promise<LocalizedHtml>;
|
|
63
|
+
//# sourceMappingURL=assets.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"assets.d.ts","sourceRoot":"","sources":["../src/assets.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAA8B,KAAK,SAAS,EAAE,MAAM,UAAU,CAAC;AAEtE,wCAAwC;AACxC,MAAM,WAAW,qBAAqB;IACpC,wDAAwD;IACxD,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IACrB,oGAAoG;IACpG,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,yEAAyE;IACzE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,2FAA2F;IAC3F,QAAQ,CAAC,EAAE,SAAS,CAAC;IACrB,+CAA+C;IAC/C,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,oDAAoD;IACpD,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,6EAA6E;IAC7E,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,qCAAqC;IACrC,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,yBAAyB;AACzB,MAAM,WAAW,UAAU;IACzB,8BAA8B;IAC9B,GAAG,EAAE,MAAM,CAAC;IACZ,2DAA2D;IAC3D,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,UAAU,CAAC;CAClB;AAED,uCAAuC;AACvC,MAAM,WAAW,aAAa;IAC5B,wEAAwE;IACxE,IAAI,EAAE,MAAM,CAAC;IACb,uBAAuB;IACvB,MAAM,EAAE,UAAU,EAAE,CAAC;IACrB,2EAA2E;IAC3E,MAAM,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;CAC1C;AAmHD;;;;;;;;GAQG;AACH,wBAAsB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,qBAA0B,GAAG,OAAO,CAAC,aAAa,CAAC,CA4E9G"}
|
package/dist/assets.js
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module assets
|
|
3
|
+
*
|
|
4
|
+
* Find the images referenced by an HTML document, download them and rewrite
|
|
5
|
+
* the references to relative paths (for the ZIP export).
|
|
6
|
+
*
|
|
7
|
+
* References found: `src` of `<img>`, `<input>`, `<source>` and the VML
|
|
8
|
+
* `<v:fill>` / `<v:image>` / `<v:imagedata>` tags (also inside Outlook
|
|
9
|
+
* conditional comments), `srcset`, `poster`, the `background` attribute,
|
|
10
|
+
* and CSS `url(…)` in `style` attributes and `<style>` blocks.
|
|
11
|
+
*/
|
|
12
|
+
import { allowHttp, fetchWithPolicy } from './net.js';
|
|
13
|
+
const SRC_TAGS = new Set(['img', 'image', 'input', 'source', 'v:fill', 'v:image', 'v:imagedata', 'video']);
|
|
14
|
+
const EXT_BY_TYPE = {
|
|
15
|
+
'image/png': 'png',
|
|
16
|
+
'image/jpeg': 'jpg',
|
|
17
|
+
'image/jpg': 'jpg',
|
|
18
|
+
'image/pjpeg': 'jpg',
|
|
19
|
+
'image/gif': 'gif',
|
|
20
|
+
'image/webp': 'webp',
|
|
21
|
+
'image/avif': 'avif',
|
|
22
|
+
'image/svg+xml': 'svg',
|
|
23
|
+
'image/bmp': 'bmp',
|
|
24
|
+
'image/x-icon': 'ico',
|
|
25
|
+
'image/vnd.microsoft.icon': 'ico',
|
|
26
|
+
'image/tiff': 'tiff',
|
|
27
|
+
};
|
|
28
|
+
const IMAGE_EXTS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'avif', 'svg', 'bmp', 'ico', 'tif', 'tiff']);
|
|
29
|
+
const decodeAttr = (v) => v
|
|
30
|
+
.replace(/"/g, '"')
|
|
31
|
+
.replace(/�*39;|�*27;|'/gi, "'")
|
|
32
|
+
.replace(/</g, '<')
|
|
33
|
+
.replace(/>/g, '>')
|
|
34
|
+
.replace(/&/g, '&');
|
|
35
|
+
const CSS_URL = /url\(\s*("|�?39;|["']?)(.*?)\1\s*\)/gi;
|
|
36
|
+
function mapCss(css, map) {
|
|
37
|
+
return css.replace(CSS_URL, (whole, quote, value) => {
|
|
38
|
+
const next = map(decodeAttr(value.trim()));
|
|
39
|
+
return next === undefined ? whole : `url(${quote}${next}${quote})`;
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
function mapSrcset(value, map) {
|
|
43
|
+
return value
|
|
44
|
+
.split(',')
|
|
45
|
+
.map((candidate) => {
|
|
46
|
+
const m = candidate.match(/^(\s*)(\S+)(.*)$/s);
|
|
47
|
+
if (!m)
|
|
48
|
+
return candidate;
|
|
49
|
+
const next = map(decodeAttr(m[2]));
|
|
50
|
+
return next === undefined ? candidate : `${m[1]}${next}${m[3]}`;
|
|
51
|
+
})
|
|
52
|
+
.join(',');
|
|
53
|
+
}
|
|
54
|
+
const TAG = /<([a-zA-Z][\w:.-]*)(\s[^>]*?)?(\/?)>/g;
|
|
55
|
+
const ATTR = /(\s)(src|srcset|background|poster|style)(\s*=\s*)("([^"]*)"|'([^']*)')/gi;
|
|
56
|
+
const STYLE_BLOCK = /(<style\b[^>]*>)([\s\S]*?)(<\/style\s*>)/gi;
|
|
57
|
+
/**
|
|
58
|
+
* Apply a URL mapper to every image reference of a document. The mapper
|
|
59
|
+
* receives the HTML-decoded reference and returns its replacement (already
|
|
60
|
+
* attribute-safe) or `undefined` to keep it.
|
|
61
|
+
*/
|
|
62
|
+
function rewriteImageRefs(html, map) {
|
|
63
|
+
const withBlocks = html.replace(STYLE_BLOCK, (_w, open, css, close) => `${open}${mapCss(css, map)}${close}`);
|
|
64
|
+
return withBlocks.replace(TAG, (tag, name, attrs) => {
|
|
65
|
+
if (!attrs)
|
|
66
|
+
return tag;
|
|
67
|
+
const tagName = name.toLowerCase();
|
|
68
|
+
const nextAttrs = attrs.replace(ATTR, (whole, sp, attr, eq, quoted, dq, sq) => {
|
|
69
|
+
const value = dq ?? sq ?? '';
|
|
70
|
+
const q = quoted[0];
|
|
71
|
+
const a = attr.toLowerCase();
|
|
72
|
+
let next;
|
|
73
|
+
if (a === 'style')
|
|
74
|
+
next = mapCss(value, map);
|
|
75
|
+
else if (a === 'srcset')
|
|
76
|
+
next = mapSrcset(value, map);
|
|
77
|
+
else if (a === 'background')
|
|
78
|
+
next = map(decodeAttr(value.trim()));
|
|
79
|
+
else if (a === 'poster' || SRC_TAGS.has(tagName))
|
|
80
|
+
next = map(decodeAttr(value.trim()));
|
|
81
|
+
return next === undefined || next === value ? whole : `${sp}${attr}${eq}${q}${next}${q}`;
|
|
82
|
+
});
|
|
83
|
+
return nextAttrs === attrs ? tag : tag.replace(attrs, () => nextAttrs);
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
/** Resolve a reference to an absolute http(s) URL, or null when it must be left alone */
|
|
87
|
+
function resolveRef(raw, baseUrl) {
|
|
88
|
+
const value = raw.trim();
|
|
89
|
+
if (!value || value.startsWith('#') || /^(data|cid|blob|about|javascript|mailto|tel):/i.test(value))
|
|
90
|
+
return null;
|
|
91
|
+
// Merge / design tags (`{{img}}`, `*|IMG|*`, `{% … %}`) are resolved by the ESP later
|
|
92
|
+
if (/[{}]|\*\||\[\[/.test(value))
|
|
93
|
+
return null;
|
|
94
|
+
try {
|
|
95
|
+
const url = baseUrl ? new URL(value, baseUrl) : new URL(value.startsWith('//') ? `https:${value}` : value);
|
|
96
|
+
return url.protocol === 'http:' || url.protocol === 'https:' ? url.href : null;
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function fileBase(url) {
|
|
103
|
+
let last = '';
|
|
104
|
+
try {
|
|
105
|
+
last = decodeURIComponent(new URL(url).pathname.split('/').pop() ?? '');
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
/* keep empty */
|
|
109
|
+
}
|
|
110
|
+
const dot = last.lastIndexOf('.');
|
|
111
|
+
const ext = dot > 0 ? last.slice(dot + 1).toLowerCase() : '';
|
|
112
|
+
const base = (dot > 0 ? last.slice(0, dot) : last).replace(/[^A-Za-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40);
|
|
113
|
+
return { base: base || 'image', ext };
|
|
114
|
+
}
|
|
115
|
+
async function pool(items, size, fn) {
|
|
116
|
+
let next = 0;
|
|
117
|
+
const workers = Array.from({ length: Math.max(1, Math.min(size, items.length)) }, async () => {
|
|
118
|
+
while (next < items.length)
|
|
119
|
+
await fn(items[next++]);
|
|
120
|
+
});
|
|
121
|
+
await Promise.all(workers);
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Download every image referenced by `html` and rewrite the references to
|
|
125
|
+
* relative paths (`images/<name>.<ext>`). Images that fail (network error,
|
|
126
|
+
* blocked URL, not an image, too large) keep their original URL and are
|
|
127
|
+
* listed in `failed`. The same URL is downloaded once.
|
|
128
|
+
*
|
|
129
|
+
* @param html - HTML document
|
|
130
|
+
* @param options - Fetch, policy and naming options
|
|
131
|
+
*/
|
|
132
|
+
export async function localizeImages(html, options = {}) {
|
|
133
|
+
const { baseUrl, assetsDir = 'images', allowUrl = allowHttp, timeoutMs, maxImageBytes, maxImages = 200, concurrency = 6, } = options;
|
|
134
|
+
const dir = assetsDir.replace(/^\/+|\/+$/g, '').replace(/(^|\/)\.\.(?=\/|$)/g, '');
|
|
135
|
+
// 1. collect references
|
|
136
|
+
const urls = [];
|
|
137
|
+
const seen = new Set();
|
|
138
|
+
rewriteImageRefs(html, (raw) => {
|
|
139
|
+
const url = resolveRef(raw, baseUrl);
|
|
140
|
+
if (url && !seen.has(url)) {
|
|
141
|
+
seen.add(url);
|
|
142
|
+
urls.push(url);
|
|
143
|
+
}
|
|
144
|
+
return undefined;
|
|
145
|
+
});
|
|
146
|
+
// 2. download
|
|
147
|
+
const byUrl = new Map();
|
|
148
|
+
const failed = [];
|
|
149
|
+
const usedNames = new Set();
|
|
150
|
+
const results = new Map();
|
|
151
|
+
const todo = urls.slice(0, maxImages);
|
|
152
|
+
for (const url of urls.slice(maxImages))
|
|
153
|
+
failed.push({ url, error: `Image limit reached (${maxImages})` });
|
|
154
|
+
await pool(todo, concurrency, async (url) => {
|
|
155
|
+
try {
|
|
156
|
+
const res = await fetchWithPolicy(url, { fetch: options.fetch, allowUrl, timeoutMs, maxBytes: maxImageBytes });
|
|
157
|
+
results.set(url, res);
|
|
158
|
+
}
|
|
159
|
+
catch (err) {
|
|
160
|
+
results.set(url, { error: err instanceof Error ? err.message : String(err) });
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
// Name files in document order so output is deterministic
|
|
164
|
+
for (const url of todo) {
|
|
165
|
+
const res = results.get(url);
|
|
166
|
+
if ('error' in res) {
|
|
167
|
+
failed.push({ url, error: res.error });
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
const { base, ext: urlExt } = fileBase(url);
|
|
171
|
+
let ext = EXT_BY_TYPE[res.contentType];
|
|
172
|
+
if (!ext) {
|
|
173
|
+
const sniffed = sniffImage(res.data);
|
|
174
|
+
const generic = !res.contentType || res.contentType === 'application/octet-stream' || res.contentType === 'binary/octet-stream';
|
|
175
|
+
if (sniffed)
|
|
176
|
+
ext = sniffed;
|
|
177
|
+
else if (generic && IMAGE_EXTS.has(urlExt))
|
|
178
|
+
ext = urlExt === 'jpeg' ? 'jpg' : urlExt;
|
|
179
|
+
else if (res.contentType.startsWith('image/'))
|
|
180
|
+
ext = IMAGE_EXTS.has(urlExt) ? urlExt : 'img';
|
|
181
|
+
}
|
|
182
|
+
if (!ext) {
|
|
183
|
+
failed.push({ url, error: `Not an image (${res.contentType || 'unknown type'})` });
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
let name = `${base}.${ext}`;
|
|
187
|
+
for (let i = 1; usedNames.has(name.toLowerCase()); i++)
|
|
188
|
+
name = `${base}-${i}.${ext}`;
|
|
189
|
+
usedNames.add(name.toLowerCase());
|
|
190
|
+
const contentType = EXT_BY_TYPE[res.contentType] ? res.contentType : contentTypeOf(ext);
|
|
191
|
+
byUrl.set(url, { url, path: dir ? `${dir}/${name}` : name, contentType, data: res.data });
|
|
192
|
+
}
|
|
193
|
+
// 3. rewrite
|
|
194
|
+
const out = byUrl.size
|
|
195
|
+
? rewriteImageRefs(html, (raw) => {
|
|
196
|
+
const url = resolveRef(raw, baseUrl);
|
|
197
|
+
return url ? byUrl.get(url)?.path : undefined;
|
|
198
|
+
})
|
|
199
|
+
: html;
|
|
200
|
+
return { html: out, assets: [...byUrl.values()], failed };
|
|
201
|
+
}
|
|
202
|
+
function contentTypeOf(ext) {
|
|
203
|
+
const found = Object.entries(EXT_BY_TYPE).find(([, e]) => e === ext);
|
|
204
|
+
return found ? found[0] : 'application/octet-stream';
|
|
205
|
+
}
|
|
206
|
+
/** Detect common image formats from magic bytes */
|
|
207
|
+
function sniffImage(d) {
|
|
208
|
+
if (d.length >= 8 && d[0] === 0x89 && d[1] === 0x50 && d[2] === 0x4e && d[3] === 0x47)
|
|
209
|
+
return 'png';
|
|
210
|
+
if (d.length >= 3 && d[0] === 0xff && d[1] === 0xd8 && d[2] === 0xff)
|
|
211
|
+
return 'jpg';
|
|
212
|
+
if (d.length >= 6 && d[0] === 0x47 && d[1] === 0x49 && d[2] === 0x46 && d[3] === 0x38)
|
|
213
|
+
return 'gif';
|
|
214
|
+
if (d.length >= 12 && d[0] === 0x52 && d[1] === 0x49 && d[2] === 0x46 && d[3] === 0x46 && d[8] === 0x57 && d[9] === 0x45 && d[10] === 0x42 && d[11] === 0x50)
|
|
215
|
+
return 'webp';
|
|
216
|
+
return null;
|
|
217
|
+
}
|
|
218
|
+
//# sourceMappingURL=assets.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"assets.js","sourceRoot":"","sources":["../src/assets.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,SAAS,EAAE,eAAe,EAAk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CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IACpG,IAAI,CAAC,CAAC,MAAM,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,EAAE,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,EAAE,CAAC,KAAK,IAAI;QAAE,OAAO,MAAM,CAAC;IAC5K,OAAO,IAAI,CAAC;AACd,CAAC"}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module browser
|
|
3
|
+
*
|
|
4
|
+
* Headless Chromium via the optional peer dependency `playwright-core`
|
|
5
|
+
* (loaded with a dynamic import only when an image/PDF export runs).
|
|
6
|
+
* The structural types below avoid a hard type dependency on Playwright.
|
|
7
|
+
*/
|
|
8
|
+
/** The subset of Playwright's `Route` used here */
|
|
9
|
+
export interface RouteLike {
|
|
10
|
+
request(): {
|
|
11
|
+
url(): string;
|
|
12
|
+
};
|
|
13
|
+
continue(): Promise<void>;
|
|
14
|
+
abort(errorCode?: string): Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
/** The subset of Playwright's `Page` used here */
|
|
17
|
+
export interface PageLike {
|
|
18
|
+
route(url: string, handler: (route: RouteLike) => unknown): Promise<void>;
|
|
19
|
+
setContent(html: string, options?: {
|
|
20
|
+
waitUntil?: 'load' | 'domcontentloaded' | 'networkidle' | 'commit';
|
|
21
|
+
timeout?: number;
|
|
22
|
+
}): Promise<void>;
|
|
23
|
+
waitForLoadState(state?: 'load' | 'domcontentloaded' | 'networkidle', options?: {
|
|
24
|
+
timeout?: number;
|
|
25
|
+
}): Promise<void>;
|
|
26
|
+
emulateMedia(options: {
|
|
27
|
+
media?: 'screen' | 'print' | null;
|
|
28
|
+
}): Promise<void>;
|
|
29
|
+
screenshot(options?: Record<string, unknown>): Promise<Uint8Array>;
|
|
30
|
+
pdf(options?: Record<string, unknown>): Promise<Uint8Array>;
|
|
31
|
+
}
|
|
32
|
+
/** The subset of Playwright's `BrowserContext` used here */
|
|
33
|
+
export interface BrowserContextLike {
|
|
34
|
+
newPage(): Promise<PageLike>;
|
|
35
|
+
close(): Promise<void>;
|
|
36
|
+
}
|
|
37
|
+
/** The subset of Playwright's `Browser` used here */
|
|
38
|
+
export interface BrowserLike {
|
|
39
|
+
newContext(options?: Record<string, unknown>): Promise<BrowserContextLike>;
|
|
40
|
+
close(): Promise<void>;
|
|
41
|
+
isConnected?(): boolean;
|
|
42
|
+
}
|
|
43
|
+
/** The subset of Playwright's `chromium` BrowserType used here */
|
|
44
|
+
export interface ChromiumLike {
|
|
45
|
+
launch(options?: Record<string, unknown>): Promise<BrowserLike>;
|
|
46
|
+
}
|
|
47
|
+
/** Browser options shared by {@link exportImage} and {@link exportPdf} */
|
|
48
|
+
export interface BrowserOptions {
|
|
49
|
+
/** An already launched Playwright browser to reuse (not closed after the export) */
|
|
50
|
+
browser?: BrowserLike;
|
|
51
|
+
/** Playwright `chromium` (default: `(await import('playwright-core')).chromium`) */
|
|
52
|
+
chromium?: ChromiumLike;
|
|
53
|
+
/** Options for `chromium.launch()` when a browser is launched for the export */
|
|
54
|
+
launchOptions?: Record<string, unknown>;
|
|
55
|
+
/** Chromium executable (shortcut for `launchOptions.executablePath`) */
|
|
56
|
+
executablePath?: string;
|
|
57
|
+
/** Timeout for loading the page and producing the output, in ms (default 30 000) */
|
|
58
|
+
timeout?: number;
|
|
59
|
+
/**
|
|
60
|
+
* Network policy for requests made by the page (images, fonts, CSS).
|
|
61
|
+
* Return false to block. Default: everything allowed.
|
|
62
|
+
*/
|
|
63
|
+
allowRequest?: (url: string) => boolean | Promise<boolean>;
|
|
64
|
+
/** Run page JavaScript (default false — email HTML needs none) */
|
|
65
|
+
javaScriptEnabled?: boolean;
|
|
66
|
+
}
|
|
67
|
+
/** Thrown when `playwright-core` (or a Chromium build) is not available */
|
|
68
|
+
export declare class BrowserUnavailableError extends Error {
|
|
69
|
+
readonly code = "BROWSER_UNAVAILABLE";
|
|
70
|
+
constructor(message: string, options?: {
|
|
71
|
+
cause?: unknown;
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
/** Load Playwright's `chromium` (throws {@link BrowserUnavailableError} when not installed) */
|
|
75
|
+
export declare function loadChromium(): Promise<ChromiumLike>;
|
|
76
|
+
/**
|
|
77
|
+
* Launch a headless Chromium (reuse it across exports via the `browser`
|
|
78
|
+
* option, and close it when done).
|
|
79
|
+
*/
|
|
80
|
+
export declare function launchBrowser(options?: Pick<BrowserOptions, 'chromium' | 'launchOptions' | 'executablePath'>): Promise<BrowserLike>;
|
|
81
|
+
/**
|
|
82
|
+
* Open the HTML in a fresh browser context, run `fn` on the page, then close
|
|
83
|
+
* the context (and the browser when it was launched for this call).
|
|
84
|
+
*/
|
|
85
|
+
export declare function withPage<T>(html: string, options: BrowserOptions, contextOptions: Record<string, unknown>, fn: (page: PageLike, timeout: number) => Promise<T>): Promise<T>;
|
|
86
|
+
//# sourceMappingURL=browser.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser.d.ts","sourceRoot":"","sources":["../src/browser.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,mDAAmD;AACnD,MAAM,WAAW,SAAS;IACxB,OAAO,IAAI;QAAE,GAAG,IAAI,MAAM,CAAA;KAAE,CAAC;IAC7B,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1B,KAAK,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1C;AAED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AAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACvC,EAAE,EAAE,CAAC,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC,CAAC,GAClD,OAAO,CAAC,CAAC,CAAC,CA+BZ"}
|
package/dist/browser.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module browser
|
|
3
|
+
*
|
|
4
|
+
* Headless Chromium via the optional peer dependency `playwright-core`
|
|
5
|
+
* (loaded with a dynamic import only when an image/PDF export runs).
|
|
6
|
+
* The structural types below avoid a hard type dependency on Playwright.
|
|
7
|
+
*/
|
|
8
|
+
/** Thrown when `playwright-core` (or a Chromium build) is not available */
|
|
9
|
+
export class BrowserUnavailableError extends Error {
|
|
10
|
+
constructor(message, options) {
|
|
11
|
+
super(message, options);
|
|
12
|
+
this.code = 'BROWSER_UNAVAILABLE';
|
|
13
|
+
this.name = 'BrowserUnavailableError';
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
const MISSING_MESSAGE = 'Image and PDF export need the optional peer dependency "playwright-core" and a Chromium build: ' +
|
|
17
|
+
'`npm i playwright-core && npx playwright-core install chromium` ' +
|
|
18
|
+
'(or pass `executablePath` / `browser` / `chromium`).';
|
|
19
|
+
/** Load Playwright's `chromium` (throws {@link BrowserUnavailableError} when not installed) */
|
|
20
|
+
export async function loadChromium() {
|
|
21
|
+
const specifier = 'playwright-core';
|
|
22
|
+
try {
|
|
23
|
+
const mod = (await import(specifier));
|
|
24
|
+
const chromium = mod.chromium ?? mod.default?.chromium;
|
|
25
|
+
if (!chromium)
|
|
26
|
+
throw new Error('playwright-core has no chromium export');
|
|
27
|
+
return chromium;
|
|
28
|
+
}
|
|
29
|
+
catch (err) {
|
|
30
|
+
throw new BrowserUnavailableError(MISSING_MESSAGE, { cause: err });
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Launch a headless Chromium (reuse it across exports via the `browser`
|
|
35
|
+
* option, and close it when done).
|
|
36
|
+
*/
|
|
37
|
+
export async function launchBrowser(options = {}) {
|
|
38
|
+
const chromium = options.chromium ?? (await loadChromium());
|
|
39
|
+
const launchOptions = { headless: true, ...options.launchOptions };
|
|
40
|
+
if (options.executablePath)
|
|
41
|
+
launchOptions.executablePath = options.executablePath;
|
|
42
|
+
try {
|
|
43
|
+
return await chromium.launch(launchOptions);
|
|
44
|
+
}
|
|
45
|
+
catch (err) {
|
|
46
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
47
|
+
if (/Executable doesn't exist|executable.*not found|Failed to launch|ENOENT/i.test(message)) {
|
|
48
|
+
throw new BrowserUnavailableError(`${MISSING_MESSAGE}\n${message}`, { cause: err });
|
|
49
|
+
}
|
|
50
|
+
throw err;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Open the HTML in a fresh browser context, run `fn` on the page, then close
|
|
55
|
+
* the context (and the browser when it was launched for this call).
|
|
56
|
+
*/
|
|
57
|
+
export async function withPage(html, options, contextOptions, fn) {
|
|
58
|
+
const timeout = options.timeout ?? 30_000;
|
|
59
|
+
const owned = !options.browser;
|
|
60
|
+
const browser = options.browser ?? (await launchBrowser(options));
|
|
61
|
+
try {
|
|
62
|
+
const context = await browser.newContext({ javaScriptEnabled: options.javaScriptEnabled ?? false, ...contextOptions });
|
|
63
|
+
try {
|
|
64
|
+
const page = await context.newPage();
|
|
65
|
+
const allow = options.allowRequest;
|
|
66
|
+
if (allow) {
|
|
67
|
+
await page.route('**/*', async (route) => {
|
|
68
|
+
const url = route.request().url();
|
|
69
|
+
let ok = false;
|
|
70
|
+
try {
|
|
71
|
+
ok = url.startsWith('data:') || url.startsWith('about:') || (await allow(url));
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
ok = false;
|
|
75
|
+
}
|
|
76
|
+
return ok ? route.continue() : route.abort('blockedbyclient');
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
await page.setContent(html, { waitUntil: 'load', timeout });
|
|
80
|
+
// Give late images/fonts a moment, without failing on chatty pages
|
|
81
|
+
await page.waitForLoadState('networkidle', { timeout: Math.min(5_000, timeout) }).catch(() => undefined);
|
|
82
|
+
return await fn(page, timeout);
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
await context.close().catch(() => undefined);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
if (owned)
|
|
90
|
+
await browser.close().catch(() => undefined);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
//# sourceMappingURL=browser.js.map
|