@nodepit/svg-to-img 4.0.0-beta.1 → 4.1.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/dist/constants.d.ts +1 -0
- package/dist/constants.js +2 -0
- package/dist/helpers.d.ts +4 -5
- package/dist/helpers.js +14 -18
- package/dist/index.d.ts +24 -5
- package/dist/index.js +152 -56
- package/dist/typings/index.d.ts +5 -0
- package/package.json +33 -72
- package/readme.md +142 -0
- package/README.md +0 -195
package/dist/constants.d.ts
CHANGED
package/dist/constants.js
CHANGED
|
@@ -4,6 +4,8 @@ exports.defaultWebpShorthandOptions = exports.defaultJpegShorthandOptions = expo
|
|
|
4
4
|
exports.config = {
|
|
5
5
|
supportedImageTypes: ["jpeg", "png", "webp"],
|
|
6
6
|
jpegBackground: "#fff",
|
|
7
|
+
// milliseconds a conversion may take to render, unless the `timeout` option says otherwise
|
|
8
|
+
timeout: 30_000,
|
|
7
9
|
puppeteer: {
|
|
8
10
|
args: ["--no-sandbox", "--disable-setuid-sandbox"]
|
|
9
11
|
}
|
package/dist/helpers.d.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { IBoundingBox, IOptions } from "./typings";
|
|
2
|
-
export declare
|
|
3
|
-
export declare
|
|
4
|
-
export declare
|
|
5
|
-
export declare const renderSvg: (svg: string, options: {
|
|
2
|
+
export declare function getFileTypeFromPath(path: string): string;
|
|
3
|
+
export declare function stringifyFunction(func: Function, ...argsArray: (string | object | number)[]): string;
|
|
4
|
+
export declare function renderSvg(svg: string, options: {
|
|
6
5
|
width?: IOptions["width"];
|
|
7
6
|
height?: IOptions["height"];
|
|
8
7
|
type: IOptions["type"];
|
|
@@ -10,4 +9,4 @@ export declare const renderSvg: (svg: string, options: {
|
|
|
10
9
|
background?: IOptions["background"];
|
|
11
10
|
clip?: IBoundingBox;
|
|
12
11
|
jpegBackground: string;
|
|
13
|
-
})
|
|
12
|
+
}): Promise<unknown>;
|
package/dist/helpers.js
CHANGED
|
@@ -1,21 +1,20 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.renderSvg = exports.writeFileAsync = exports.stringifyFunction = exports.getFileTypeFromPath = void 0;
|
|
4
|
-
const fs = require("fs");
|
|
5
|
-
const getFileTypeFromPath = (path) => {
|
|
6
|
-
return path.toLowerCase().replace(new RegExp("jpg", "g"), "jpeg").split(".").reverse()[0];
|
|
7
|
-
};
|
|
8
3
|
exports.getFileTypeFromPath = getFileTypeFromPath;
|
|
4
|
+
exports.stringifyFunction = stringifyFunction;
|
|
5
|
+
exports.renderSvg = renderSvg;
|
|
6
|
+
function getFileTypeFromPath(path) {
|
|
7
|
+
const normalized = path.toLowerCase().replace(/jpg/g, "jpeg");
|
|
8
|
+
return normalized.slice(normalized.lastIndexOf(".") + 1);
|
|
9
|
+
}
|
|
9
10
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
const functionString = func.toString().replace(/cov_(.+?)\+\+[,;]?/g, "");
|
|
11
|
+
function stringifyFunction(func, ...argsArray) {
|
|
12
|
+
const functionString = func.toString();
|
|
13
13
|
const args = [];
|
|
14
14
|
for (const argument of argsArray) {
|
|
15
15
|
switch (typeof argument) {
|
|
16
|
+
// a string as JSON too, so that a backtick or `${…}` in it (e.g. in the text of an SVG) is not read as code
|
|
16
17
|
case "string":
|
|
17
|
-
args.push("`" + argument + "`");
|
|
18
|
-
break;
|
|
19
18
|
case "object":
|
|
20
19
|
args.push(JSON.stringify(argument));
|
|
21
20
|
break;
|
|
@@ -24,16 +23,13 @@ const stringifyFunction = (func, ...argsArray) => {
|
|
|
24
23
|
}
|
|
25
24
|
}
|
|
26
25
|
return `(${functionString})(${args.join(",")})`;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
const writeFileAsync = (path, data) => fs.promises.writeFile(path, data);
|
|
30
|
-
exports.writeFileAsync = writeFileAsync;
|
|
31
|
-
const renderSvg = async (svg, options) => {
|
|
26
|
+
}
|
|
27
|
+
async function renderSvg(svg, options) {
|
|
32
28
|
return new Promise((resolve, reject) => {
|
|
33
29
|
const canvas = document.createElement("canvas");
|
|
34
30
|
const ctx = canvas.getContext("2d");
|
|
35
31
|
const img = new Image();
|
|
36
|
-
/*
|
|
32
|
+
/* v8 ignore if */
|
|
37
33
|
if (!ctx) {
|
|
38
34
|
return reject(new Error("Canvas not supported"));
|
|
39
35
|
}
|
|
@@ -43,6 +39,7 @@ const renderSvg = async (svg, options) => {
|
|
|
43
39
|
if (options.height) {
|
|
44
40
|
img.height = options.height;
|
|
45
41
|
}
|
|
42
|
+
// arrow functions, so that the narrowing of `ctx` above carries over into them
|
|
46
43
|
const onLoad = () => {
|
|
47
44
|
let imageWidth = img.naturalWidth;
|
|
48
45
|
let imageHeight = img.naturalHeight;
|
|
@@ -99,5 +96,4 @@ const renderSvg = async (svg, options) => {
|
|
|
99
96
|
const base64Svg = btoa(unescape(encodeURIComponent(svg)));
|
|
100
97
|
img.src = "data:image/svg+xml;base64," + base64Svg;
|
|
101
98
|
});
|
|
102
|
-
}
|
|
103
|
-
exports.renderSvg = renderSvg;
|
|
99
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,14 +1,33 @@
|
|
|
1
1
|
/// <reference types="node" preserve="true" />
|
|
2
2
|
import type * as puppeteer from "puppeteer-core" with { "resolution-mode": "import" };
|
|
3
|
-
import { IOptions, IShorthandOptions, IConnectOptions } from "./typings";
|
|
3
|
+
import { IBoundingBox, IOptions, IShorthandOptions, IConnectOptions } from "./typings";
|
|
4
|
+
/**
|
|
5
|
+
* Opens the browser for conversions, and lets go of it when idle.
|
|
6
|
+
*
|
|
7
|
+
* @internal exported for the tests only; not part of the public API, it can change in any release
|
|
8
|
+
*/
|
|
4
9
|
export declare class BrowserSource {
|
|
5
10
|
private readonly factory;
|
|
11
|
+
private readonly release;
|
|
6
12
|
private queue;
|
|
7
13
|
private browserDestructionTimeout;
|
|
8
14
|
private browserInstance;
|
|
9
15
|
private browserState;
|
|
10
|
-
|
|
16
|
+
private conversions;
|
|
17
|
+
/**
|
|
18
|
+
* @param factory opens a browser when a conversion needs one
|
|
19
|
+
* @param release lets go of the browser once it was idle for 500 ms; closes it by default
|
|
20
|
+
*/
|
|
21
|
+
constructor(factory: () => Promise<puppeteer.Browser>, release?: (browser: puppeteer.Browser) => Promise<void>);
|
|
22
|
+
/**
|
|
23
|
+
* Returns the browser, and opens it if none is open. Call `scheduleBrowserForDestruction` once for every call of
|
|
24
|
+
* `getBrowser`, also when using the browser failed: the browser is released only 500 ms after the last of these calls.
|
|
25
|
+
*/
|
|
11
26
|
getBrowser(): Promise<puppeteer.Browser>;
|
|
27
|
+
/**
|
|
28
|
+
* Lets go of a browser returned by `getBrowser`. When no other caller still uses it, the browser is passed to
|
|
29
|
+
* `release` after 500 ms, unless `getBrowser` is called again before.
|
|
30
|
+
*/
|
|
12
31
|
scheduleBrowserForDestruction(): void;
|
|
13
32
|
private executeQueuedRequests;
|
|
14
33
|
}
|
|
@@ -31,6 +50,6 @@ export declare class SvgToImg {
|
|
|
31
50
|
constructor(browserSource: BrowserSource);
|
|
32
51
|
from(svg: Buffer | string): Svg;
|
|
33
52
|
}
|
|
34
|
-
export declare
|
|
35
|
-
export declare
|
|
36
|
-
export { IOptions, IShorthandOptions, IConnectOptions };
|
|
53
|
+
export declare function from(svg: Buffer | string): Svg;
|
|
54
|
+
export declare function connect(options: IConnectOptions): SvgToImg;
|
|
55
|
+
export { IBoundingBox, IOptions, IShorthandOptions, IConnectOptions };
|
package/dist/index.js
CHANGED
|
@@ -1,69 +1,135 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
2
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.
|
|
36
|
+
exports.SvgToImg = exports.Svg = exports.BrowserSource = void 0;
|
|
37
|
+
exports.from = from;
|
|
38
|
+
exports.connect = connect;
|
|
39
|
+
const promises_1 = require("node:fs/promises");
|
|
4
40
|
const helpers_1 = require("./helpers");
|
|
5
41
|
const constants_1 = require("./constants");
|
|
42
|
+
/**
|
|
43
|
+
* Opens the browser for conversions, and lets go of it when idle.
|
|
44
|
+
*
|
|
45
|
+
* @internal exported for the tests only; not part of the public API, it can change in any release
|
|
46
|
+
*/
|
|
6
47
|
class BrowserSource {
|
|
7
48
|
factory;
|
|
49
|
+
release;
|
|
50
|
+
// conversions waiting for the browser to open
|
|
8
51
|
queue = [];
|
|
9
52
|
browserDestructionTimeout;
|
|
10
53
|
browserInstance;
|
|
11
54
|
browserState = "closed";
|
|
12
|
-
|
|
55
|
+
// conversions which called `getBrowser` and not yet `scheduleBrowserForDestruction`; the idle close waits for all
|
|
56
|
+
conversions = 0;
|
|
57
|
+
/**
|
|
58
|
+
* @param factory opens a browser when a conversion needs one
|
|
59
|
+
* @param release lets go of the browser once it was idle for 500 ms; closes it by default
|
|
60
|
+
*/
|
|
61
|
+
constructor(factory, release = (browser) => browser.close()) {
|
|
13
62
|
this.factory = factory;
|
|
63
|
+
this.release = release;
|
|
14
64
|
}
|
|
65
|
+
/**
|
|
66
|
+
* Returns the browser, and opens it if none is open. Call `scheduleBrowserForDestruction` once for every call of
|
|
67
|
+
* `getBrowser`, also when using the browser failed: the browser is released only 500 ms after the last of these calls.
|
|
68
|
+
*/
|
|
15
69
|
async getBrowser() {
|
|
70
|
+
this.conversions++;
|
|
16
71
|
return new Promise((resolve, reject) => {
|
|
17
|
-
/* istanbul ignore if */
|
|
18
72
|
if (this.browserDestructionTimeout) {
|
|
19
73
|
clearTimeout(this.browserDestructionTimeout);
|
|
20
74
|
}
|
|
21
|
-
/* istanbul ignore else */
|
|
22
75
|
if (this.browserState === "closed") {
|
|
23
76
|
// Browser is closed
|
|
24
|
-
this.queue.push(resolve);
|
|
77
|
+
this.queue.push({ resolve, reject });
|
|
25
78
|
this.browserState = "opening";
|
|
26
79
|
this.factory()
|
|
27
80
|
.then((browserInstance) => {
|
|
28
81
|
this.browserInstance = browserInstance;
|
|
29
82
|
this.browserState = "open";
|
|
83
|
+
// A crashed or restarted browser is replaced by the next conversion. The idle close disconnects too, but it
|
|
84
|
+
// has already let go of the browser, and a next one may be open by the time the event arrives
|
|
85
|
+
browserInstance.once("disconnected", () => {
|
|
86
|
+
if (this.browserInstance === browserInstance) {
|
|
87
|
+
this.browserInstance = undefined;
|
|
88
|
+
this.browserState = "closed";
|
|
89
|
+
}
|
|
90
|
+
});
|
|
30
91
|
this.executeQueuedRequests(this.browserInstance);
|
|
31
92
|
})
|
|
32
93
|
.catch((error) => {
|
|
33
94
|
this.browserState = "closed";
|
|
34
|
-
|
|
95
|
+
// passes on what Puppeteer rejected with, which is not necessarily an Error
|
|
96
|
+
const reason = unwrapConnectionError(error);
|
|
97
|
+
// every conversion which waited for this browser fails, not only the one which started opening it
|
|
98
|
+
for (const queued of this.queue.splice(0)) {
|
|
99
|
+
queued.reject(reason);
|
|
100
|
+
}
|
|
35
101
|
});
|
|
36
102
|
return;
|
|
37
103
|
}
|
|
38
|
-
/* istanbul ignore next */
|
|
39
104
|
if (this.browserState === "opening") {
|
|
40
105
|
// Queue request and wait for the browser to open
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
/* istanbul ignore next */
|
|
44
|
-
if (this.browserState === "open") {
|
|
45
|
-
// Browser is already open
|
|
46
|
-
if (this.browserInstance) {
|
|
47
|
-
return resolve(this.browserInstance);
|
|
48
|
-
}
|
|
106
|
+
this.queue.push({ resolve, reject });
|
|
107
|
+
return;
|
|
49
108
|
}
|
|
109
|
+
// Browser is already open, and an open browser always has an instance
|
|
110
|
+
resolve(this.browserInstance);
|
|
50
111
|
});
|
|
51
112
|
}
|
|
113
|
+
/**
|
|
114
|
+
* Lets go of a browser returned by `getBrowser`. When no other caller still uses it, the browser is passed to
|
|
115
|
+
* `release` after 500 ms, unless `getBrowser` is called again before.
|
|
116
|
+
*/
|
|
52
117
|
scheduleBrowserForDestruction() {
|
|
53
|
-
|
|
54
|
-
if (this.
|
|
55
|
-
|
|
118
|
+
this.conversions--;
|
|
119
|
+
if (this.conversions > 0) {
|
|
120
|
+
return;
|
|
56
121
|
}
|
|
57
|
-
this.browserDestructionTimeout = global.setTimeout(
|
|
58
|
-
|
|
59
|
-
if (
|
|
122
|
+
this.browserDestructionTimeout = global.setTimeout(() => {
|
|
123
|
+
const browser = this.browserInstance;
|
|
124
|
+
if (browser) {
|
|
125
|
+
this.browserInstance = undefined;
|
|
60
126
|
this.browserState = "closed";
|
|
61
|
-
|
|
127
|
+
void this.release(browser);
|
|
62
128
|
}
|
|
63
129
|
}, 500);
|
|
64
130
|
}
|
|
65
131
|
executeQueuedRequests(browser) {
|
|
66
|
-
for (const resolve of this.queue) {
|
|
132
|
+
for (const { resolve } of this.queue) {
|
|
67
133
|
resolve(browser);
|
|
68
134
|
}
|
|
69
135
|
// Clear items from the queue
|
|
@@ -93,10 +159,6 @@ class Svg {
|
|
|
93
159
|
async convertSvg(inputSvg, passedOptions, browserSource) {
|
|
94
160
|
const svg = Buffer.isBuffer(inputSvg) ? inputSvg.toString("utf8") : inputSvg;
|
|
95
161
|
const options = { ...constants_1.defaultOptions, ...passedOptions };
|
|
96
|
-
const browser = await browserSource.getBrowser();
|
|
97
|
-
const page = (await browser.pages())[0];
|
|
98
|
-
// ⚠️ Offline mode is enabled to prevent any HTTP requests over the network
|
|
99
|
-
await page.setOfflineMode(true);
|
|
100
162
|
// Infer the file type from the file path if no type is provided
|
|
101
163
|
if (!passedOptions.type && options.path) {
|
|
102
164
|
const fileType = (0, helpers_1.getFileTypeFromPath)(options.path);
|
|
@@ -104,19 +166,37 @@ class Svg {
|
|
|
104
166
|
options.type = fileType;
|
|
105
167
|
}
|
|
106
168
|
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
169
|
+
let base64;
|
|
170
|
+
try {
|
|
171
|
+
const browser = await browserSource.getBrowser();
|
|
172
|
+
// A page of its own, so that an SVG which keeps the page busy holds up no other conversion, and a page of another
|
|
173
|
+
// client of a browser reached with `connect` is never used
|
|
174
|
+
const page = await browser.newPage();
|
|
175
|
+
try {
|
|
176
|
+
// ⚠️ Offline mode is enabled to prevent any HTTP requests over the network
|
|
177
|
+
await page.setOfflineMode(true);
|
|
178
|
+
base64 = await withTimeout(page.evaluate((0, helpers_1.stringifyFunction)(helpers_1.renderSvg, svg, {
|
|
179
|
+
width: options.width,
|
|
180
|
+
height: options.height,
|
|
181
|
+
type: options.type,
|
|
182
|
+
quality: options.quality,
|
|
183
|
+
background: options.background,
|
|
184
|
+
clip: options.clip,
|
|
185
|
+
jpegBackground: constants_1.config.jpegBackground
|
|
186
|
+
})), options.timeout ?? constants_1.config.timeout);
|
|
187
|
+
}
|
|
188
|
+
finally {
|
|
189
|
+
// fails when the browser is gone, which the conversion's own error already tells
|
|
190
|
+
await page.close().catch(() => undefined);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
finally {
|
|
194
|
+
// also after a failed conversion: an open browser keeps the process from exiting
|
|
195
|
+
browserSource.scheduleBrowserForDestruction();
|
|
196
|
+
}
|
|
117
197
|
const buffer = Buffer.from(base64, "base64");
|
|
118
198
|
if (options.path) {
|
|
119
|
-
await (0,
|
|
199
|
+
await (0, promises_1.writeFile)(options.path, buffer);
|
|
120
200
|
}
|
|
121
201
|
if (options.encoding === "base64") {
|
|
122
202
|
return base64;
|
|
@@ -128,16 +208,31 @@ class Svg {
|
|
|
128
208
|
}
|
|
129
209
|
}
|
|
130
210
|
exports.Svg = Svg;
|
|
211
|
+
// An SVG can keep the page busy for good (e.g. `<use>` elements nested to a billion copies): the conversion fails
|
|
212
|
+
// instead of waiting forever, and closing the page ends the rendering
|
|
213
|
+
async function withTimeout(promise, timeout) {
|
|
214
|
+
let timer;
|
|
215
|
+
const timedOut = new Promise((_resolve, reject) => {
|
|
216
|
+
// `setTimeout` takes a longer delay (e.g. `Infinity`) as 1 ms; Puppeteer's `protocolTimeout` ends the call earlier
|
|
217
|
+
// anyway
|
|
218
|
+
timer = setTimeout(() => reject(new Error(`Rendering the SVG took longer than ${timeout} ms`)), Math.min(timeout, 2 ** 31 - 1));
|
|
219
|
+
});
|
|
220
|
+
try {
|
|
221
|
+
return await Promise.race([promise, timedOut]);
|
|
222
|
+
}
|
|
223
|
+
finally {
|
|
224
|
+
clearTimeout(timer);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
131
227
|
// Puppeteer 25 rejects a failed connection with an `ErrorEvent` wrapping Node's `AggregateError` (one error per
|
|
132
228
|
// resolved address), which has an empty message
|
|
133
|
-
|
|
134
|
-
const unwrapConnectionError = (error) => {
|
|
229
|
+
function unwrapConnectionError(error) {
|
|
135
230
|
const cause = error?.error ?? error;
|
|
136
231
|
const { message, errors, code } = cause;
|
|
137
232
|
if (message || !Array.isArray(errors))
|
|
138
233
|
return cause;
|
|
139
234
|
return Object.assign(new Error(errors.map((e) => e.message).join("; "), { cause }), { code });
|
|
140
|
-
}
|
|
235
|
+
}
|
|
141
236
|
class SvgToImg {
|
|
142
237
|
browserSource;
|
|
143
238
|
constructor(browserSource) {
|
|
@@ -149,28 +244,29 @@ class SvgToImg {
|
|
|
149
244
|
}
|
|
150
245
|
exports.SvgToImg = SvgToImg;
|
|
151
246
|
const defaultBrowserSource = new BrowserSource(async () => {
|
|
247
|
+
let puppeteerFull;
|
|
152
248
|
try {
|
|
153
|
-
//
|
|
154
|
-
|
|
155
|
-
|
|
249
|
+
// `puppeteer` is an optional peer dependency, so it is loaded only once a conversion needs it
|
|
250
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
251
|
+
puppeteerFull = require("puppeteer");
|
|
156
252
|
}
|
|
157
253
|
catch {
|
|
158
|
-
/*
|
|
159
|
-
throw new Error("NPM module `puppeteer` is not available. Either add it as " +
|
|
160
|
-
"
|
|
254
|
+
/* v8 ignore next */
|
|
255
|
+
throw new Error("NPM module `puppeteer` is not available. Either add it as a " +
|
|
256
|
+
"dependency to your project, or use the `connect` function and supply " +
|
|
161
257
|
"`browserWSEndpoint` if you want to use a running Puppeteer endpoint.");
|
|
162
258
|
}
|
|
259
|
+
return await puppeteerFull.launch(constants_1.config.puppeteer);
|
|
163
260
|
});
|
|
164
|
-
|
|
261
|
+
function from(svg) {
|
|
165
262
|
return new SvgToImg(defaultBrowserSource).from(svg);
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
/* istanbul ignore next */
|
|
169
|
-
const connect = (options) => {
|
|
263
|
+
}
|
|
264
|
+
function connect(options) {
|
|
170
265
|
return new SvgToImg(new BrowserSource(async () => {
|
|
171
266
|
// puppeteer-core is ESM-only, load it when the first conversion needs it and not when this library is imported (CJS tooling like Jest cannot load it)
|
|
172
|
-
const { connect } = await Promise.resolve().then(() => require("puppeteer-core"));
|
|
267
|
+
const { connect } = await Promise.resolve().then(() => __importStar(require("puppeteer-core")));
|
|
173
268
|
return connect(options);
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
|
|
269
|
+
},
|
|
270
|
+
// the browser belongs to whoever runs the endpoint, and may serve other clients: `close` would end it for all of them
|
|
271
|
+
(browser) => browser.disconnect()));
|
|
272
|
+
}
|
package/dist/typings/index.d.ts
CHANGED
|
@@ -13,6 +13,7 @@ export interface IOptions {
|
|
|
13
13
|
clip?: IBoundingBox;
|
|
14
14
|
background?: string;
|
|
15
15
|
encoding?: "base64" | "utf8" | "binary" | "hex";
|
|
16
|
+
timeout?: number;
|
|
16
17
|
}
|
|
17
18
|
export interface IShorthandOptions extends IOptions {
|
|
18
19
|
type?: never;
|
|
@@ -20,5 +21,9 @@ export interface IShorthandOptions extends IOptions {
|
|
|
20
21
|
export interface IConnectOptions {
|
|
21
22
|
browserWSEndpoint?: string;
|
|
22
23
|
browserURL?: string;
|
|
24
|
+
/**
|
|
25
|
+
* @deprecated Has no effect: Puppeteer 25 does not know this option. The SVG is rendered offline, from a data URL, so
|
|
26
|
+
* no HTTPS errors occur either.
|
|
27
|
+
*/
|
|
23
28
|
ignoreHTTPSErrors?: boolean;
|
|
24
29
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nodepit/svg-to-img",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.1.0",
|
|
4
4
|
"description": "A node.js library to convert SVGs to images built with Puppeteer.",
|
|
5
5
|
"homepage": "https://github.com/NodePit/svg-to-img",
|
|
6
6
|
"keywords": [
|
|
@@ -18,7 +18,8 @@
|
|
|
18
18
|
".": {
|
|
19
19
|
"types": "./dist/index.d.ts",
|
|
20
20
|
"default": "./dist/index.js"
|
|
21
|
-
}
|
|
21
|
+
},
|
|
22
|
+
"./package.json": "./package.json"
|
|
22
23
|
},
|
|
23
24
|
"files": [
|
|
24
25
|
"dist"
|
|
@@ -31,66 +32,24 @@
|
|
|
31
32
|
"Philipp Katz (https://gitlab.com/qqilihq)"
|
|
32
33
|
],
|
|
33
34
|
"scripts": {
|
|
34
|
-
"dev": "tsc --pretty --watch",
|
|
35
|
-
"
|
|
36
|
-
"
|
|
37
|
-
"
|
|
38
|
-
"
|
|
39
|
-
"
|
|
40
|
-
"
|
|
35
|
+
"dev": "tsc -p tsconfig.build.json --pretty --watch",
|
|
36
|
+
"clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
|
|
37
|
+
"lint": "pnpm run lint:eslint && pnpm run lint:format && pnpm run lint:types && pnpm run lint:knip && pnpm run lint:changelog",
|
|
38
|
+
"lint:eslint": "eslint .",
|
|
39
|
+
"lint:format": "prettier --check .",
|
|
40
|
+
"lint:types": "tsc --noEmit",
|
|
41
|
+
"lint:knip": "knip",
|
|
42
|
+
"lint:changelog": "changelog-keeper lint --section-types Added,Changed,Deprecated,Removed,Fixed,Security,Breaking",
|
|
43
|
+
"test": "vitest run --coverage",
|
|
44
|
+
"test:watch": "vitest",
|
|
45
|
+
"prebuild": "pnpm run clean",
|
|
46
|
+
"build": "tsc -p tsconfig.build.json --pretty",
|
|
41
47
|
"prepare": "pnpm run build && husky",
|
|
42
|
-
"
|
|
43
|
-
"
|
|
48
|
+
"prepublishOnly": "pnpm run lint && pnpm test",
|
|
49
|
+
"preversion": "pnpm run lint",
|
|
50
|
+
"version": "changelog-keeper verify --section-types Added,Changed,Deprecated,Removed,Fixed,Security,Breaking || (git checkout -- package.json && exit 1)",
|
|
44
51
|
"postversion": "git push --follow-tags"
|
|
45
52
|
},
|
|
46
|
-
"jest": {
|
|
47
|
-
"setupFiles": [
|
|
48
|
-
"jest-canvas-mock"
|
|
49
|
-
],
|
|
50
|
-
"transform": {
|
|
51
|
-
"^.+\\.tsx?$": "ts-jest",
|
|
52
|
-
"^.+\\.js$": [
|
|
53
|
-
"@swc/jest",
|
|
54
|
-
{
|
|
55
|
-
"module": {
|
|
56
|
-
"type": "commonjs"
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
]
|
|
60
|
-
},
|
|
61
|
-
"moduleFileExtensions": [
|
|
62
|
-
"ts",
|
|
63
|
-
"tsx",
|
|
64
|
-
"js",
|
|
65
|
-
"jsx",
|
|
66
|
-
"json",
|
|
67
|
-
"node"
|
|
68
|
-
],
|
|
69
|
-
"coveragePathIgnorePatterns": [
|
|
70
|
-
"/node_modules/",
|
|
71
|
-
"/coverage/",
|
|
72
|
-
"/dist/",
|
|
73
|
-
"/typings/",
|
|
74
|
-
"/tests/"
|
|
75
|
-
],
|
|
76
|
-
"coverageThreshold": {
|
|
77
|
-
"global": {
|
|
78
|
-
"branches": 100,
|
|
79
|
-
"functions": 100,
|
|
80
|
-
"lines": 100,
|
|
81
|
-
"statements": -10
|
|
82
|
-
}
|
|
83
|
-
},
|
|
84
|
-
"testMatch": [
|
|
85
|
-
"**/?(*.)(test).(tsx|ts)"
|
|
86
|
-
],
|
|
87
|
-
"collectCoverageFrom": [
|
|
88
|
-
"src/**/*.(tsx|ts)"
|
|
89
|
-
],
|
|
90
|
-
"transformIgnorePatterns": [
|
|
91
|
-
"/node_modules/(?!(?:\\.pnpm/[^/]+/node_modules/)?(?:puppeteer-core|puppeteer|@puppeteer/browsers)/)"
|
|
92
|
-
]
|
|
93
|
-
},
|
|
94
53
|
"repository": {
|
|
95
54
|
"type": "git",
|
|
96
55
|
"url": "git+https://github.com/NodePit/svg-to-img.git"
|
|
@@ -103,26 +62,28 @@
|
|
|
103
62
|
},
|
|
104
63
|
"license": "MIT",
|
|
105
64
|
"devDependencies": {
|
|
106
|
-
"@
|
|
107
|
-
"@
|
|
108
|
-
"@types/jest": "^29.5.14",
|
|
65
|
+
"@eslint/js": "^10.0.1",
|
|
66
|
+
"@qqilihq/changelog-keeper": "0.1.0-beta.3",
|
|
109
67
|
"@types/node": "~22.12.0",
|
|
110
68
|
"@types/pngjs": "^6.0.5",
|
|
111
|
-
"@
|
|
112
|
-
"@
|
|
113
|
-
"eslint": "^
|
|
114
|
-
"eslint-
|
|
69
|
+
"@vitest/coverage-v8": "^5.1.1",
|
|
70
|
+
"@vitest/eslint-plugin": "^1.6.28",
|
|
71
|
+
"eslint": "^10.15.0",
|
|
72
|
+
"eslint-config-prettier": "^10.1.8",
|
|
73
|
+
"eslint-plugin-n": "^18.5.0",
|
|
115
74
|
"husky": "^9.1.7",
|
|
116
75
|
"image-size": "^2.0.4",
|
|
117
|
-
"
|
|
118
|
-
"
|
|
119
|
-
"
|
|
76
|
+
"jsdom": "~28.1.0",
|
|
77
|
+
"knip": "^6.48.0",
|
|
78
|
+
"lint-staged": "^17.6.2",
|
|
120
79
|
"pngjs": "^7.0.0",
|
|
121
80
|
"prettier": "^3.9.10",
|
|
122
81
|
"puppeteer": "^25.13.0",
|
|
123
82
|
"ts-expect": "^1.3.0",
|
|
124
|
-
"
|
|
125
|
-
"typescript": "^
|
|
83
|
+
"typescript": "~6.0.3",
|
|
84
|
+
"typescript-eslint": "^8.73.0",
|
|
85
|
+
"vitest": "^5.1.1",
|
|
86
|
+
"vitest-canvas-mock": "^1.2.0"
|
|
126
87
|
},
|
|
127
88
|
"dependencies": {
|
|
128
89
|
"puppeteer-core": "^25.13.0"
|
|
@@ -138,7 +99,7 @@
|
|
|
138
99
|
"devEngines": {
|
|
139
100
|
"runtime": {
|
|
140
101
|
"name": "node",
|
|
141
|
-
"version": "
|
|
102
|
+
"version": "26.13.1",
|
|
142
103
|
"onFail": "warn"
|
|
143
104
|
}
|
|
144
105
|
},
|
package/readme.md
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
# svg-to-img
|
|
2
|
+
|
|
3
|
+
A Node.js library to convert SVGs to PNG, JPEG and WebP images, built with [Puppeteer](https://github.com/puppeteer/puppeteer).
|
|
4
|
+
|
|
5
|
+
This is a fork of Etienne Martin’s [svg-to-img](https://github.com/etienne-martin/svg-to-img). It can [connect to a running browser](#svgtoimgconnectoptions) instead of launching one, and fixes a number of issues of the original library (see the [changelog](https://github.com/NodePit/svg-to-img/blob/master/changelog.md)).
|
|
6
|
+
|
|
7
|
+
[](https://www.npmjs.com/package/%40nodepit%2Fsvg-to-img)
|
|
8
|
+
[](https://www.npmjs.com/package/%40nodepit%2Fsvg-to-img)
|
|
9
|
+
[](https://www.npmjs.com/package/%40nodepit%2Fsvg-to-img)
|
|
10
|
+
|
|
11
|
+
## Getting started
|
|
12
|
+
|
|
13
|
+
### Requirements
|
|
14
|
+
|
|
15
|
+
- Node.js 22.12 or later
|
|
16
|
+
- A Chrome recent enough for Puppeteer 25. Chrome 78, as shipped in `browserless/chrome:1.x`, is too old; use e.g. `ghcr.io/browserless/chromium`
|
|
17
|
+
|
|
18
|
+
### Installation
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
npm install @nodepit/svg-to-img
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
The library depends on `puppeteer-core`, which does not download a browser. To convert with `from`, which launches a local Chrome, also install `puppeteer`, which downloads one:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
npm install puppeteer
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
To use a browser which runs elsewhere, use `connect` instead.
|
|
31
|
+
|
|
32
|
+
If Chrome does not start on Linux, it is probably missing system libraries. Puppeteer’s [troubleshooting guide](https://pptr.dev/troubleshooting) lists them.
|
|
33
|
+
|
|
34
|
+
### Usage
|
|
35
|
+
|
|
36
|
+
```javascript
|
|
37
|
+
import * as svgToImg from "@nodepit/svg-to-img";
|
|
38
|
+
|
|
39
|
+
const svg = "<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100'/>";
|
|
40
|
+
|
|
41
|
+
// a PNG as a Buffer
|
|
42
|
+
const png = await svgToImg.from(svg).toPng();
|
|
43
|
+
|
|
44
|
+
// a JPEG saved as example.jpeg
|
|
45
|
+
await svgToImg.from(svg).toJpeg({ path: "./example.jpeg" });
|
|
46
|
+
|
|
47
|
+
// a WebP 300 pixels wide; the height scales proportionally
|
|
48
|
+
const webp = await svgToImg.from(svg).toWebp({ width: 300 });
|
|
49
|
+
|
|
50
|
+
// a PNG as a base64 string
|
|
51
|
+
const base64 = await svgToImg.from(svg).toPng({ encoding: "base64" });
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
To convert with a browser which runs elsewhere, e.g. in a Docker container, connect to it:
|
|
55
|
+
|
|
56
|
+
```javascript
|
|
57
|
+
const converter = svgToImg.connect({ browserWSEndpoint: "ws://localhost:3000" });
|
|
58
|
+
|
|
59
|
+
const image = await converter.from(svg).toPng();
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## API
|
|
63
|
+
|
|
64
|
+
### svgToImg.from(svg)
|
|
65
|
+
|
|
66
|
+
- `svg` (`Buffer | string`): The SVG markup to convert.
|
|
67
|
+
- returns `Svg`, whose methods below convert it.
|
|
68
|
+
|
|
69
|
+
The first conversion launches a local Chrome with `puppeteer`, and the library closes it 500 ms after the last conversion.
|
|
70
|
+
|
|
71
|
+
### svgToImg.connect(options)
|
|
72
|
+
|
|
73
|
+
- `options` (`object`): Where to find the browser, with one of these properties:
|
|
74
|
+
- `browserWSEndpoint` (`string`): The WebSocket URL of the browser, e.g. `ws://localhost:3000`.
|
|
75
|
+
- `browserURL` (`string`): The HTTP URL of the browser’s remote debugging port, e.g. `http://localhost:9222`.
|
|
76
|
+
- returns `SvgToImg`, whose `from` method works like `svgToImg.from`.
|
|
77
|
+
|
|
78
|
+
The connection opens on the first conversion, so `connect` returns even when the browser cannot be reached; the conversion fails then (see [Errors](#errors)).
|
|
79
|
+
|
|
80
|
+
Each conversion renders on a page of its own and closes it afterwards, so the pages of other clients of the browser are never touched. 500 ms after the last conversion, the library disconnects from the browser and leaves it running.
|
|
81
|
+
|
|
82
|
+
### svg.to(options)
|
|
83
|
+
|
|
84
|
+
- `options` (`object`):
|
|
85
|
+
- `type` (`"png" | "jpeg" | "webp"`): The image type. Defaults to `"png"`, or to the extension of `path`.
|
|
86
|
+
- `path` (`string`): The file to save the image to, relative to the current working directory. Without `path`, the image is not saved.
|
|
87
|
+
- `quality` (`number`): The quality of a JPEG or WebP image, between 0 and 1. Defaults to `1`.
|
|
88
|
+
- `width` (`number`): The width of the image. Defaults to the width of the SVG, or scales proportionally to `height`.
|
|
89
|
+
- `height` (`number`): The height of the image. Defaults to the height of the SVG, or scales proportionally to `width`.
|
|
90
|
+
- `clip` (`object`): The region of the image to keep, with the `x` and `y` of its top-left corner, its `width` and its `height`.
|
|
91
|
+
- `background` (`string`): The background color, as a [CSS color](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). JPEG images default to white.
|
|
92
|
+
- `encoding` (`"base64" | "utf8" | "binary" | "hex"`): Returns the image as a string in this encoding instead of a `Buffer`.
|
|
93
|
+
- `timeout` (`number`): The maximum time in milliseconds to render the SVG. Defaults to `30000`. Puppeteer’s own limit of 180 seconds applies as well, so a longer `timeout`, or `Infinity`, ends there.
|
|
94
|
+
- returns `Promise<Buffer | string>`: The image.
|
|
95
|
+
|
|
96
|
+
When converting SVGs from untrusted sources, limit how many conversions run at once: an SVG can keep its browser page and a CPU core busy until the timeout.
|
|
97
|
+
|
|
98
|
+
### svg.toPng([options]), svg.toJpeg([options]), svg.toWebp([options])
|
|
99
|
+
|
|
100
|
+
Shorthands for `to` with the `type` set. The `options` are those of `to`, except `type`.
|
|
101
|
+
|
|
102
|
+
### Errors
|
|
103
|
+
|
|
104
|
+
All conversion methods return a promise that rejects with an `Error` in these cases:
|
|
105
|
+
|
|
106
|
+
| Case | Error |
|
|
107
|
+
| --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
|
|
108
|
+
| The input is not a valid SVG | message `Malformed SVG` |
|
|
109
|
+
| The browser cannot be reached (`connect`) | message lists the refused addresses, `code` is `ECONNREFUSED`; the next call tries to connect again |
|
|
110
|
+
| `puppeteer` is not installed, and you use `from` (which launches a local browser) | message ``NPM module `puppeteer` is not available…`` |
|
|
111
|
+
| The `path` option cannot be written | the error of the file system, e.g. `ENOENT` |
|
|
112
|
+
| Rendering takes longer than the `timeout` option | message `Rendering the SVG took longer than … ms` |
|
|
113
|
+
|
|
114
|
+
Errors of the browser itself (e.g. the browser crashes during the conversion) are passed on unchanged. After the browser disconnected, the next call opens a new one.
|
|
115
|
+
|
|
116
|
+
## Contributing
|
|
117
|
+
|
|
118
|
+
Please discuss a change in an issue before you make it. Update the readme and the tests along with the code, and add the change to `changelog.md` under `## [Unreleased]`.
|
|
119
|
+
|
|
120
|
+
The toolchain is pinned: pnpm by `packageManager`, Node.js by `.node-version`.
|
|
121
|
+
|
|
122
|
+
```bash
|
|
123
|
+
pnpm install
|
|
124
|
+
pnpm run lint # ESLint, Prettier, the type check, Knip, and the changelog
|
|
125
|
+
pnpm test # needs Chrome, which the install of `puppeteer` downloads
|
|
126
|
+
pnpm run build
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### Releasing
|
|
130
|
+
|
|
131
|
+
1. In `changelog.md`, move the entries under `## [Unreleased]` to a new `## [X.Y.Z] - YYYY-MM-DD` section below it. The date follows a plain hyphen, and the empty `## [Unreleased]` heading stays. Add an `[X.Y.Z]` link comparing the previous version with `vX.Y.Z`, point the `[unreleased]` link at `vX.Y.Z...HEAD`, and commit.
|
|
132
|
+
2. Run `pnpm version <patch|minor|major>`, which makes the release commit and tag, and pushes both. If the changelog is not ready, [changelog-keeper](https://github.com/qqilihq/changelog-keeper) says which lines to write and the bump is undone. It checks after the version bump, the only point at which the new version is known, and never modifies the changelog.
|
|
133
|
+
3. The tag starts the publish workflow, which publishes to npm and creates the GitHub release.
|
|
134
|
+
|
|
135
|
+
## Authors
|
|
136
|
+
|
|
137
|
+
- **Etienne Martin** ([etiennemartin.ca](http://etiennemartin.ca/)): the original library
|
|
138
|
+
- **Philipp Katz** ([gitlab.com/qqilihq](https://gitlab.com/qqilihq)): this fork
|
|
139
|
+
|
|
140
|
+
## License
|
|
141
|
+
|
|
142
|
+
MIT, see [LICENSE](https://github.com/NodePit/svg-to-img/blob/master/LICENSE).
|
package/README.md
DELETED
|
@@ -1,195 +0,0 @@
|
|
|
1
|
-
# svg-to-img
|
|
2
|
-
|
|
3
|
-
#### A node.js library to convert SVGs to images built with [Puppeteer](https://github.com/GoogleChrome/puppeteer).
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
**NOTE:** This is a fork from Etienne Martin’s <a href="https://github.com/etienne-martin/svg-to-img">svg-to-img</a> which adds the possibility to connect to a Puppeteer endpoint (see <a href="https://github.com/etienne-martin/svg-to-img/pull/19">here</a>).
|
|
7
|
-
|
|
8
|
-
<!-- [](https://coveralls.io/github/etienne-martin/svg-to-img) -->
|
|
9
|
-
<!-- [](https://circleci.com/gh/etienne-martin/svg-to-img) -->
|
|
10
|
-
[](https://www.npmjs.com/package/%40nodepit%2Fsvg-to-img)
|
|
11
|
-
[](https://www.npmjs.com/package/%40nodepit%2Fsvg-to-img)
|
|
12
|
-
[](https://www.npmjs.com/package/%40nodepit%2Fsvg-to-img)
|
|
13
|
-
|
|
14
|
-
## Getting Started
|
|
15
|
-
|
|
16
|
-
### Installation
|
|
17
|
-
|
|
18
|
-
To use svg-to-img in your project, run:
|
|
19
|
-
|
|
20
|
-
```bash
|
|
21
|
-
npm install @nodepit/svg-to-img
|
|
22
|
-
```
|
|
23
|
-
|
|
24
|
-
Starting from v4.0.0, svg-to-img requires Node 22.12 or later and Puppeteer 25, which in turn needs a recent Chrome (it does not work with Chrome 78, as shipped in `browserless/chrome:1.x`; use e.g. `ghcr.io/browserless/chromium`).
|
|
25
|
-
|
|
26
|
-
Starting from v3.0.0, Chromium will **no longer** automatically be downloaded when installing this dependency (instead of depending on `puppetteer`, the library now depends on `puppeteer-core`; see [here](https://github.com/puppeteer/puppeteer/blob/main/docs/api.md#puppeteer-vs-puppeteer-core)). We assume that you either have an existing local or remote Chromium, or that you explicitly install `puppeteer` within your project to to have Chromium downloaded.
|
|
27
|
-
|
|
28
|
-
#### Debian
|
|
29
|
-
|
|
30
|
-
If you're planning on running svg-to-img on Debian, you will need to manually install the following dependencies:
|
|
31
|
-
|
|
32
|
-
```bash
|
|
33
|
-
#!/bin/bash
|
|
34
|
-
|
|
35
|
-
apt-get update
|
|
36
|
-
apt-get install -yq gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 \
|
|
37
|
-
libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 \
|
|
38
|
-
libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 \
|
|
39
|
-
libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 \
|
|
40
|
-
ca-certificates fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget
|
|
41
|
-
```
|
|
42
|
-
|
|
43
|
-
### Usage
|
|
44
|
-
|
|
45
|
-
**Example** - converting a `svg` to `png`:
|
|
46
|
-
|
|
47
|
-
```javascript
|
|
48
|
-
const svgToImg = require("svg-to-img");
|
|
49
|
-
|
|
50
|
-
(async () => {
|
|
51
|
-
const image = await svgToImg.from("<svg xmlns='http://www.w3.org/2000/svg'/>").toPng();
|
|
52
|
-
|
|
53
|
-
console.log(image);
|
|
54
|
-
})();
|
|
55
|
-
```
|
|
56
|
-
|
|
57
|
-
**Example** - converting a `svg` to `jpeg` and saving the image as *example.jpeg*:
|
|
58
|
-
|
|
59
|
-
```javascript
|
|
60
|
-
const svgToImg = require("svg-to-img");
|
|
61
|
-
|
|
62
|
-
(async () => {
|
|
63
|
-
await svgToImg.from("<svg xmlns='http://www.w3.org/2000/svg'/>").toJpeg({
|
|
64
|
-
path: "./example.jpeg"
|
|
65
|
-
});
|
|
66
|
-
})();
|
|
67
|
-
```
|
|
68
|
-
|
|
69
|
-
**Example** - resizing a `svg` proportionally and converting it to `webp`:
|
|
70
|
-
|
|
71
|
-
```javascript
|
|
72
|
-
const svgToImg = require("svg-to-img");
|
|
73
|
-
|
|
74
|
-
(async () => {
|
|
75
|
-
const image = await svgToImg.from("<svg xmlns='http://www.w3.org/2000/svg'/>").toWebp({
|
|
76
|
-
width: 300
|
|
77
|
-
});
|
|
78
|
-
|
|
79
|
-
console.log(image);
|
|
80
|
-
})();
|
|
81
|
-
```
|
|
82
|
-
|
|
83
|
-
**Example** - converting a `svg` to base64-encoded png:
|
|
84
|
-
|
|
85
|
-
```javascript
|
|
86
|
-
const svgToImg = require("svg-to-img");
|
|
87
|
-
|
|
88
|
-
(async () => {
|
|
89
|
-
const image = await svgToImg.from("<svg xmlns='http://www.w3.org/2000/svg'/>").toPng({
|
|
90
|
-
encoding: "base64"
|
|
91
|
-
});
|
|
92
|
-
|
|
93
|
-
console.log(image);
|
|
94
|
-
})();
|
|
95
|
-
```
|
|
96
|
-
|
|
97
|
-
**Example** - connect to Puppeteer `browserWSEndpoint`:
|
|
98
|
-
|
|
99
|
-
```javascript
|
|
100
|
-
const svgToImg = require("svg-to-img");
|
|
101
|
-
const convert = svgToImg.connect({
|
|
102
|
-
browserWSEndpoint: "ws://localhost:3000"
|
|
103
|
-
});
|
|
104
|
-
|
|
105
|
-
(async () => {
|
|
106
|
-
const image = await convert.from("<svg xmlns='http://www.w3.org/2000/svg'/>").toPng();
|
|
107
|
-
|
|
108
|
-
console.log(image);
|
|
109
|
-
})();
|
|
110
|
-
```
|
|
111
|
-
|
|
112
|
-
## API Documentation
|
|
113
|
-
|
|
114
|
-
### svgToImg.from(svg)
|
|
115
|
-
- `svg` <Buffer|string> SVG markup to be converted.
|
|
116
|
-
- returns: <[Svg]> a new Svg object.
|
|
117
|
-
|
|
118
|
-
The method returns a svg instance based on the given argument.
|
|
119
|
-
|
|
120
|
-
### svgToImg.connect(options)
|
|
121
|
-
- `options` <[Object]> Puppeteer [connect options](https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#puppeteerconnectoptions) object which will typically contain a `browserWSEndpoint` property.
|
|
122
|
-
- returns: <[SvgToImg]> an instance which is connected with the specified Puppeteer endpoint.
|
|
123
|
-
|
|
124
|
-
Use this method if you want to connect to a running Puppeteer endpoint (see [here](https://github.com/etienne-martin/svg-to-img/issues/9)). Note that the actual connection is established lazily; this means this method will always return, even when the given `browserWSEndpoint` cannot be reached -- in this case, errors will be thrown later when calling one of the `to` functions.
|
|
125
|
-
|
|
126
|
-
### svg.to([options])
|
|
127
|
-
- `options` <[Object]> Options object which might have the following properties:
|
|
128
|
-
- `path` <[string]> The file path to save the image to. The image type will be inferred from file extension. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). If no path is provided, the image won't be saved to the disk.
|
|
129
|
-
- `type` <[string]> Specify image type, can be either `png`, `jpeg` or `webp`. Defaults to `png`.
|
|
130
|
-
- `quality` <[number]> The quality of the image, between 0-1. Defaults to `1`. Not applicable to `png` images.
|
|
131
|
-
- `width` <[number]> width of the output image. Defaults to the natural width of the SVG.
|
|
132
|
-
- `height` <[number]> height of the output image. Defaults to the natural height of the SVG.
|
|
133
|
-
- `clip` <[Object]> An object which specifies clipping region of the output image. Should have the following fields:
|
|
134
|
-
- `x` <[number]> x-coordinate of top-left corner of clip area
|
|
135
|
-
- `y` <[number]> y-coordinate of top-left corner of clip area
|
|
136
|
-
- `width` <[number]> width of clipping area
|
|
137
|
-
- `height` <[number]> height of clipping area
|
|
138
|
-
- `background` <[string]> background color applied to the output image, must be a valid [CSS color value](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value).
|
|
139
|
-
- `encoding` <[string]> Specify encoding, can be either `base64`, `utf8`, `binary` or `hex`. Returns a `Buffer` if this option is omitted.
|
|
140
|
-
- returns: <[Promise]<Buffer|String>> Promise which resolves to the output image.
|
|
141
|
-
|
|
142
|
-
### svg.toPng([options])
|
|
143
|
-
- `options` <[Object]> Optional options object that can have the same properties as the `to` method except for the type property.
|
|
144
|
-
- returns: <[Promise]<Buffer|String>> Promise which resolves to the `png` image.
|
|
145
|
-
|
|
146
|
-
This method is simply a shorthand for the `to` method.
|
|
147
|
-
|
|
148
|
-
### svg.toJpeg([options])
|
|
149
|
-
- `options` <[Object]> Optional options object that can have the same properties as the `to` method except for the type property.
|
|
150
|
-
- returns: <[Promise]<Buffer|String>> Promise which resolves to the `jpeg` image.
|
|
151
|
-
|
|
152
|
-
This method is simply a shorthand for the `to` method.
|
|
153
|
-
|
|
154
|
-
### svg.toWebp([options])
|
|
155
|
-
- `options` <[Object]> Optional options object that can have the same properties as the `to` method except for the type property.
|
|
156
|
-
- returns: <[Promise]<Buffer|String>> Promise which resolves to the `webp` image.
|
|
157
|
-
|
|
158
|
-
This method is simply a shorthand for the `to` method.
|
|
159
|
-
|
|
160
|
-
### Errors
|
|
161
|
-
|
|
162
|
-
All conversion methods return a promise that rejects with an `Error` in these cases:
|
|
163
|
-
|
|
164
|
-
| Case | Error |
|
|
165
|
-
| --- | --- |
|
|
166
|
-
| The input is not a valid SVG | message `Malformed SVG` |
|
|
167
|
-
| The browser cannot be reached (`connect`) | message lists the refused addresses, `code` is `ECONNREFUSED`; the next call tries to connect again |
|
|
168
|
-
| `puppeteer` is not installed, and you use `from` (which launches a local browser) | message ``NPM module `puppeteer` is not available…`` |
|
|
169
|
-
| The `path` option cannot be written | the error of the file system, e.g. `ENOENT` |
|
|
170
|
-
|
|
171
|
-
Errors of the browser itself (e.g. the browser crashes during the conversion) are passed on unchanged.
|
|
172
|
-
|
|
173
|
-
## Built with
|
|
174
|
-
|
|
175
|
-
* [node.js](https://nodejs.org/en/) - Cross-platform JavaScript run-time environment for executing JavaScript code server-side.
|
|
176
|
-
* [Puppeteer](https://github.com/GoogleChrome/puppeteer/) - Headless Chrome Node API.
|
|
177
|
-
* [TypeScript](https://www.typescriptlang.org/) - Typed superset of JavaScript that compiles to plain JavaScript.
|
|
178
|
-
* [Jest](https://facebook.github.io/jest/) - Delightful JavaScript Testing.
|
|
179
|
-
|
|
180
|
-
## Contributing
|
|
181
|
-
|
|
182
|
-
When contributing to this project, please first discuss the change you wish to make via issue, email, or any other method with the owners of this repository before making a change.
|
|
183
|
-
|
|
184
|
-
Update the [README.md](https://github.com/etienne-martin/svg-to-img/blob/master/README.md) with details of changes to the library.
|
|
185
|
-
|
|
186
|
-
Execute `pnpm run test` and update the [tests](https://github.com/etienne-martin/svg-to-img/tree/master/src/tests) if needed.
|
|
187
|
-
|
|
188
|
-
## Authors
|
|
189
|
-
|
|
190
|
-
* **Etienne Martin** - *Initial work* - [etiennemartin.ca](http://etiennemartin.ca/)
|
|
191
|
-
* **Philipp Katz** - *Connect to browser endpoint* - [gitlab.com/qqilihq](https://gitlab.com/qqilihq)
|
|
192
|
-
|
|
193
|
-
## License
|
|
194
|
-
|
|
195
|
-
This project is licensed under the MIT License - see the [LICENSE](https://github.com/etienne-martin/svg-to-img/blob/master/LICENSE) file for details.
|