1 | 'use strict';
|
2 |
|
3 | const os = require('os');
|
4 | const fs = require('fs');
|
5 | const { pathToFileURL } = require('url');
|
6 | const path = require('path');
|
7 | const { optimize: optimizeAgnostic } = require('./svgo.js');
|
8 |
|
9 | const importConfig = async (configFile) => {
|
10 | let config;
|
11 |
|
12 |
|
13 |
|
14 | if (configFile.endsWith('.cjs')) {
|
15 | config = require(configFile);
|
16 | } else {
|
17 |
|
18 |
|
19 | const { default: imported } = await import(pathToFileURL(configFile));
|
20 | config = imported;
|
21 | }
|
22 | if (config == null || typeof config !== 'object' || Array.isArray(config)) {
|
23 | throw Error(`Invalid config file "${configFile}"`);
|
24 | }
|
25 | return config;
|
26 | };
|
27 |
|
28 | const isFile = async (file) => {
|
29 | try {
|
30 | const stats = await fs.promises.stat(file);
|
31 | return stats.isFile();
|
32 | } catch {
|
33 | return false;
|
34 | }
|
35 | };
|
36 |
|
37 | const loadConfig = async (configFile, cwd = process.cwd()) => {
|
38 | if (configFile != null) {
|
39 | if (path.isAbsolute(configFile)) {
|
40 | return await importConfig(configFile);
|
41 | } else {
|
42 | return await importConfig(path.join(cwd, configFile));
|
43 | }
|
44 | }
|
45 | let dir = cwd;
|
46 |
|
47 | while (true) {
|
48 | const js = path.join(dir, 'svgo.config.js');
|
49 | if (await isFile(js)) {
|
50 | return await importConfig(js);
|
51 | }
|
52 | const mjs = path.join(dir, 'svgo.config.mjs');
|
53 | if (await isFile(mjs)) {
|
54 | return await importConfig(mjs);
|
55 | }
|
56 | const cjs = path.join(dir, 'svgo.config.cjs');
|
57 | if (await isFile(cjs)) {
|
58 | return await importConfig(cjs);
|
59 | }
|
60 | const parent = path.dirname(dir);
|
61 | if (dir === parent) {
|
62 | return null;
|
63 | }
|
64 | dir = parent;
|
65 | }
|
66 | };
|
67 | exports.loadConfig = loadConfig;
|
68 |
|
69 | const optimize = (input, config) => {
|
70 | if (config == null) {
|
71 | config = {};
|
72 | }
|
73 | if (typeof config !== 'object') {
|
74 | throw Error('Config should be an object');
|
75 | }
|
76 | return optimizeAgnostic(input, {
|
77 | ...config,
|
78 | js2svg: {
|
79 |
|
80 | eol: os.EOL === '\r\n' ? 'crlf' : 'lf',
|
81 | ...config.js2svg,
|
82 | },
|
83 | });
|
84 | };
|
85 | exports.optimize = optimize;
|