picgo-plugin-tinify 0.0.0-stage → 0.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/License ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2019 - present Molunerfinn
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,88 @@
1
- # Temporary Holding Version
1
+ # picgo-plugin-tinify
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [中文说明](./README_CN.md)
4
+
5
+ Compress images before [PicGo](https://picgo.app) uploads them, and optionally convert them to AVIF, WebP, JPEG or PNG. The plugin also adds a `picgo tinify` command for compressing local files.
6
+
7
+ The first engine is the [TinyPNG API](https://tinypng.com/developers). More engines are planned; the engine is a setting, so they will appear there without changing anything else.
8
+
9
+ ## Requirements
10
+
11
+ - PicGo 3.0.0 or later (GUI), or PicGo-Core 3.0.0 or later (CLI), on Node.js 20.19 or later.
12
+ - A TinyPNG API key. Get one free at [tinypng.com/developers](https://tinypng.com/developers); the free plan covers 500 compressions a month.
13
+
14
+ ## Install
15
+
16
+ GUI: open PicGo → Plugins, search for `tinify` and install it.
17
+
18
+ CLI:
19
+
20
+ ```bash
21
+ picgo install tinify
22
+ ```
23
+
24
+ ## Configure
25
+
26
+ GUI: Plugins → tinify → Config plugin. CLI: `picgo set plugin tinify`.
27
+
28
+ | Field | Meaning |
29
+ | --- | --- |
30
+ | Compression engine | Only TinyPNG for now. |
31
+ | TinyPNG API key | Required. Stored in PicGo's config file. The `TINYPNG_API_KEY` environment variable wins over the saved value. |
32
+ | Convert to | Keep format (default), AVIF, WEBP, JPEG or PNG. A converted image gets the new extension, so `photo.png` uploads as `photo.webp`. TinyPNG counts a conversion as one extra compression. |
33
+ | JPEG background | Fill for transparent areas when converting to JPEG: `white` (default), `black` or `#RRGGBB`. |
34
+ | Keep metadata | Any of copyright, creation time and location. TinyPNG drops all metadata by default. Location is not kept in PNG. |
35
+ | Minimum size (KB) | Images smaller than this are uploaded as they are, which saves compressions. `0` (default) compresses every image. |
36
+
37
+ ## Upload
38
+
39
+ Once configured, every upload is compressed first. The plugin reads the real format from the file content, so a wrong extension doesn't matter. It skips:
40
+
41
+ - files that are not images (PDF, zip, …) and images TinyPNG can't compress (GIF, SVG, or a file TinyPNG rejects): uploaded as they are, with no error or notification, even when no API key is set;
42
+ - images smaller than the minimum size;
43
+ - images TinyPNG can't make smaller without a conversion: the original is kept.
44
+
45
+ In a terminal (`picgo upload`, `picgo tinify`), a spinner shows how many images are done while they are compressed. It stays off in the GUI, in silent mode and when the output is piped.
46
+
47
+ If compression fails (no key, wrong key, monthly limit reached, network error), the original image is uploaded and the GUI shows a notification. After a wrong key or a reached limit the plugin stops calling TinyPNG for the rest of the batch.
48
+
49
+ ## Command line
50
+
51
+ ```bash
52
+ picgo tinify a.png b.jpg # compress in place
53
+ picgo tinify *.png --convert webp # write a.webp next to a.png, keep a.png
54
+ picgo tinify *.png -o dist/ # write results into dist/, leave inputs alone
55
+ picgo tinify a.jpg --convert none # ignore the configured conversion for this run
56
+ picgo tinify a.jpg --preserve copyright,creation
57
+ ```
58
+
59
+ | Option | Meaning |
60
+ | --- | --- |
61
+ | `-o, --out-dir <dir>` | Write results to this folder (created if missing) instead of next to the inputs. |
62
+ | `--convert <format>` | `avif`, `webp`, `jpeg`, `png`, or `none` to keep the format. Default: the plugin config. |
63
+ | `--preserve <keys>` | Comma separated: `copyright`, `creation`, `location`. An empty value keeps none. Default: the plugin config. |
64
+
65
+ Without `--out-dir`, a file whose format doesn't change is overwritten; a converted file is written next to it with the new extension and the original stays. The command uses the API key, conversion, background and metadata settings from the config; the minimum size only applies to uploads. It exits with code 1 if any file failed.
66
+
67
+ ## Development
68
+
69
+ ```bash
70
+ pnpm install
71
+ pnpm build # TypeScript → dist/ (CommonJS, loaded by PicGo with require)
72
+ pnpm lint # eslint + type check
73
+ pnpm test # build, then unit and end-to-end tests
74
+ ```
75
+
76
+ The end-to-end test loads `dist/index.js` into a real PicGo-Core instance and runs uploads and the CLI against a local mock TinyPNG server. `TINIFY_API_URL` points the plugin at that server and is not meant for normal use.
77
+
78
+ Engines live in `src/engines/`. A new engine implements `CompressionEngine` (`src/engines/types.ts`), gets a case in `createEngine` and a value in the `engine` config field; the upload hook and the CLI only use the interface.
79
+
80
+ ### Commits and releases
81
+
82
+ The repo follows the PicGo commit convention through [@picgo/bump-version](https://github.com/PicGo/bump-version): use `pnpm cz` to write a commit message, and the commit-msg hook checks it with commitlint.
83
+
84
+ To release, run `pnpm release` (patch by default, `-t minor` or `-t major` for bigger bumps). It bumps `package.json`, updates `CHANGELOG.md`, commits, and creates a `v<version>` tag. Push both with `git push --follow-tags origin main`; the tag starts the release workflow, which lints, tests, builds and publishes to npm with provenance through npm trusted publishing, so no npm token is stored in the repo.
85
+
86
+ ## License
87
+
88
+ MIT
package/README_CN.md ADDED
@@ -0,0 +1,73 @@
1
+ # picgo-plugin-tinify
2
+
3
+ [English](./README.md)
4
+
5
+ 在 [PicGo](https://picgo.app) 上传前压缩图片,也可以顺便转成 AVIF、WebP、JPEG 或 PNG。插件还提供 `picgo tinify` 命令,用来压缩本地文件。
6
+
7
+ 第一个压缩引擎是 [TinyPNG API](https://tinypng.com/developers)。以后会加入更多引擎,引擎是一个配置项,新引擎会直接出现在那里。
8
+
9
+ ## 要求
10
+
11
+ - PicGo 3.0.0 及以上(GUI),或 PicGo-Core 3.0.0 及以上(CLI),Node.js 20.19 及以上。
12
+ - TinyPNG API Key。在 [tinypng.com/developers](https://tinypng.com/developers) 免费申请,免费额度每月 500 次压缩。
13
+
14
+ ## 安装
15
+
16
+ GUI:打开 PicGo → 插件设置,搜索 `tinify` 安装。
17
+
18
+ CLI:
19
+
20
+ ```bash
21
+ picgo install tinify
22
+ ```
23
+
24
+ ## 配置
25
+
26
+ GUI:插件设置 → tinify → 配置插件。CLI:`picgo set plugin tinify`。
27
+
28
+ | 配置项 | 说明 |
29
+ | --- | --- |
30
+ | 压缩引擎 | 目前只有 TinyPNG。 |
31
+ | TinyPNG API Key | 必填,保存在 PicGo 的配置文件里。设置了环境变量 `TINYPNG_API_KEY` 时优先用环境变量。 |
32
+ | 转换格式 | 不转换(默认)、AVIF、WEBP、JPEG、PNG。转换后文件扩展名跟着变,`photo.png` 会以 `photo.webp` 上传。TinyPNG 把转换额外算一次压缩。 |
33
+ | JPEG 背景色 | 转成 JPEG 时填充透明区域:`white`(默认)、`black` 或 `#RRGGBB`。 |
34
+ | 保留元数据 | 可多选版权、创建时间、位置。TinyPNG 默认去掉所有元数据。PNG 不保留位置信息。 |
35
+ | 最小体积(KB) | 小于这个大小的图片不压缩直接上传,可以省额度。`0`(默认)表示全部压缩。 |
36
+
37
+ ## 上传
38
+
39
+ 配置好之后,每次上传都会先压缩。插件按文件内容判断真实格式,扩展名写错也没关系。以下情况跳过:
40
+
41
+ - 不是图片的文件(PDF、zip 等)和 TinyPNG 压缩不了的图片(GIF、SVG,或被 TinyPNG 拒绝的文件):原样上传,不报错也不弹通知,没填 API Key 也一样;
42
+ - 小于最小体积的图片;
43
+ - 不转换格式时 TinyPNG 压不小的图片:保留原图。
44
+
45
+ 在终端里(`picgo upload`、`picgo tinify`)压缩时会显示转圈和已完成张数。GUI、静默模式和输出被管道接走时不显示。
46
+
47
+ 压缩失败(没填 Key、Key 错误、本月额度用完、网络错误)时上传原图,GUI 弹出通知。Key 错误或额度用完后,这一批剩下的图片不再请求 TinyPNG。
48
+
49
+ ## 命令行
50
+
51
+ ```bash
52
+ picgo tinify a.png b.jpg # 原地压缩
53
+ picgo tinify *.png --convert webp # 在 a.png 旁边写 a.webp,保留 a.png
54
+ picgo tinify *.png -o dist/ # 结果写到 dist/,不动原文件
55
+ picgo tinify a.jpg --convert none # 这次忽略配置里的格式转换
56
+ picgo tinify a.jpg --preserve copyright,creation
57
+ ```
58
+
59
+ | 选项 | 说明 |
60
+ | --- | --- |
61
+ | `-o, --out-dir <dir>` | 结果写到这个目录(不存在会创建),不写在原文件旁边。 |
62
+ | `--convert <format>` | `avif`、`webp`、`jpeg`、`png`,`none` 表示不转换。默认用插件配置。 |
63
+ | `--preserve <keys>` | 逗号分隔:`copyright`、`creation`、`location`,传空值表示都不保留。默认用插件配置。 |
64
+
65
+ 不传 `--out-dir` 时,格式不变的文件直接覆盖;转换了格式的文件写在原文件旁边,用新扩展名,原文件保留。命令使用配置里的 API Key、转换格式、背景色和元数据设置;最小体积只对上传生效。有文件失败时退出码为 1。
66
+
67
+ ## 开发
68
+
69
+ 见 [README](./README.md#development)。
70
+
71
+ ## License
72
+
73
+ MIT
@@ -0,0 +1,9 @@
1
+ import type { IPicGo, IPlugin } from 'picgo';
2
+ /**
3
+ * Compresses every image in `ctx.output` before the uploader runs. Files that are not images, or
4
+ * images the engine can't compress, pass through untouched without touching the config, so a
5
+ * missing key never gets in the way of uploading other files. Any failure (no key, bad key, quota,
6
+ * network) leaves that image as it was, so the upload still goes through with the original.
7
+ */
8
+ export declare const handleBeforeUpload: (ctx: IPicGo) => Promise<IPicGo>;
9
+ export declare const beforeUploadPlugin: IPlugin;
@@ -0,0 +1,157 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.beforeUploadPlugin = exports.handleBeforeUpload = void 0;
4
+ const compress_1 = require("./compress");
5
+ const config_1 = require("./config");
6
+ const engines_1 = require("./engines");
7
+ const format_1 = require("./format");
8
+ const i18n_1 = require("./i18n");
9
+ const spinner_1 = require("./spinner");
10
+ const CONCURRENCY = 3;
11
+ const readBuffer = (item) => {
12
+ if (item.buffer) {
13
+ return item.buffer;
14
+ }
15
+ if (item.base64Image) {
16
+ return Buffer.from(item.base64Image, 'base64');
17
+ }
18
+ return undefined;
19
+ };
20
+ /** Puts the compressed bytes into the upload item and renames it when the format changed. */
21
+ const applyResult = (item, buffer, format, inputFormat) => {
22
+ item.buffer = buffer;
23
+ item.base64Image &&= buffer.toString('base64');
24
+ item.size = buffer.length;
25
+ if (format !== inputFormat) {
26
+ const extname = (0, format_1.extnameFor)(format);
27
+ item.fileName &&= (0, format_1.replaceExtname)(item.fileName, extname);
28
+ item.extname = extname;
29
+ item.contentType = format_1.MIME_TYPES[format];
30
+ }
31
+ else if (item.fileName && !item.extname) {
32
+ item.extname = (0, format_1.currentExtname)(item.fileName);
33
+ }
34
+ };
35
+ /**
36
+ * Compresses every image in `ctx.output` before the uploader runs. Files that are not images, or
37
+ * images the engine can't compress, pass through untouched without touching the config, so a
38
+ * missing key never gets in the way of uploading other files. Any failure (no key, bad key, quota,
39
+ * network) leaves that image as it was, so the upload still goes through with the original.
40
+ */
41
+ const handleBeforeUpload = async (ctx) => {
42
+ const $T = (0, i18n_1.T)(ctx);
43
+ const engineId = (0, config_1.configuredEngine)((0, config_1.getUserConfig)(ctx));
44
+ const accepted = engineId ? engines_1.ENGINE_INPUT_FORMATS[engineId] : undefined;
45
+ const candidates = [];
46
+ for (const item of ctx.output) {
47
+ const input = readBuffer(item);
48
+ if (!input) {
49
+ continue;
50
+ }
51
+ const format = (0, format_1.detectFormat)(input);
52
+ // With an unknown engine every image stays a candidate, so getSettings reports the bad config below.
53
+ if (!format || (accepted && !accepted.includes(format))) {
54
+ ctx.log.info($T('TINIFY_SKIP_UNSUPPORTED', { name: item.fileName ?? '' }));
55
+ continue;
56
+ }
57
+ candidates.push({ item, input });
58
+ }
59
+ if (candidates.length === 0) {
60
+ return ctx;
61
+ }
62
+ const failures = [];
63
+ const notifyFailure = (count) => {
64
+ ctx.log.warn($T('TINIFY_UPLOAD_ORIGINAL'));
65
+ ctx.emit('notification', {
66
+ title: $T('TINIFY_NOTIFY_FAILED_TITLE'),
67
+ body: $T('TINIFY_NOTIFY_FAILED_BODY', { count: String(count), message: failures[0] ?? '' })
68
+ });
69
+ };
70
+ let settings;
71
+ try {
72
+ settings = (0, config_1.getSettings)(ctx, $T);
73
+ }
74
+ catch (e) {
75
+ failures.push(e.message);
76
+ ctx.log.warn(e.message);
77
+ notifyFailure(candidates.length);
78
+ return ctx;
79
+ }
80
+ const engine = (0, engines_1.createEngine)(ctx, settings, $T);
81
+ let failed = 0;
82
+ let stopped = false;
83
+ const spinner = (0, spinner_1.createSpinner)(ctx);
84
+ const log = (0, spinner_1.spinnerLogger)(ctx, spinner);
85
+ let done = 0;
86
+ const progress = () => {
87
+ spinner.update($T('TINIFY_PROGRESS', { engine: engine.name, done: String(done), total: String(candidates.length) }));
88
+ };
89
+ progress();
90
+ const compressOne = async ({ item, input }) => {
91
+ const name = item.fileName ?? '';
92
+ if (stopped) {
93
+ failed++;
94
+ return;
95
+ }
96
+ if (input.length < settings.minSizeBytes) {
97
+ log.info($T('TINIFY_SKIP_SMALL', { name, size: (0, format_1.formatBytes)(settings.minSizeBytes) }));
98
+ return;
99
+ }
100
+ try {
101
+ const outcome = await (0, compress_1.compressImage)(engine, input, {
102
+ convert: settings.convert,
103
+ background: settings.background,
104
+ preserve: settings.preserve
105
+ });
106
+ if (outcome.status === 'unsupported') {
107
+ log.info($T('TINIFY_SKIP_UNSUPPORTED', { name }));
108
+ return;
109
+ }
110
+ if (outcome.status === 'notSmaller') {
111
+ log.info($T('TINIFY_SKIP_NOT_SMALLER', { name }));
112
+ return;
113
+ }
114
+ applyResult(item, outcome.buffer, outcome.format, outcome.inputFormat);
115
+ log.success($T('TINIFY_COMPRESSED', {
116
+ name: item.fileName ?? name,
117
+ before: (0, format_1.formatBytes)(outcome.before),
118
+ after: (0, format_1.formatBytes)(outcome.after),
119
+ ratio: (0, format_1.formatRatio)(outcome.before, outcome.after)
120
+ }));
121
+ }
122
+ catch (e) {
123
+ failed++;
124
+ const message = e instanceof Error ? e.message : String(e);
125
+ failures.push(message);
126
+ log.warn($T('TINIFY_FAILED_ITEM', { name, message }));
127
+ // A bad key or a used-up quota fails every image the same way; don't spend more requests.
128
+ if (e instanceof engines_1.EngineError && e.fatal) {
129
+ stopped = true;
130
+ }
131
+ if (!(e instanceof engines_1.EngineError)) {
132
+ log.error(e);
133
+ }
134
+ }
135
+ };
136
+ await (0, compress_1.mapLimit)(candidates, CONCURRENCY, async (candidate) => {
137
+ try {
138
+ await compressOne(candidate);
139
+ }
140
+ finally {
141
+ done++;
142
+ progress();
143
+ }
144
+ }).finally(() => { spinner.stop(); });
145
+ const usage = engine.usage?.();
146
+ if (usage) {
147
+ ctx.log.info(usage);
148
+ }
149
+ if (failed > 0) {
150
+ notifyFailure(failed);
151
+ }
152
+ return ctx;
153
+ };
154
+ exports.handleBeforeUpload = handleBeforeUpload;
155
+ exports.beforeUploadPlugin = {
156
+ handle: exports.handleBeforeUpload
157
+ };
package/dist/cli.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import type { IPicGo } from 'picgo';
2
+ interface TinifyFlags {
3
+ outDir?: string;
4
+ convert?: string;
5
+ preserve?: string;
6
+ }
7
+ /**
8
+ * Where a compressed file goes: next to the input (same name when the format is unchanged, so the
9
+ * input is overwritten; new extension otherwise), or into `outDir`.
10
+ */
11
+ export declare const outputPath: (input: string, extname: string, outDir?: string) => string;
12
+ export declare const tinifyCommand: (ctx: IPicGo, files: string[], flags: TinifyFlags) => Promise<void>;
13
+ export declare const registerCli: (ctx: IPicGo) => void;
14
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,161 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.registerCli = exports.tinifyCommand = exports.outputPath = void 0;
7
+ const node_fs_1 = __importDefault(require("node:fs"));
8
+ const node_path_1 = __importDefault(require("node:path"));
9
+ const compress_1 = require("./compress");
10
+ const config_1 = require("./config");
11
+ const engines_1 = require("./engines");
12
+ const format_1 = require("./format");
13
+ const i18n_1 = require("./i18n");
14
+ const spinner_1 = require("./spinner");
15
+ const CONCURRENCY = 3;
16
+ /**
17
+ * Where a compressed file goes: next to the input (same name when the format is unchanged, so the
18
+ * input is overwritten; new extension otherwise), or into `outDir`.
19
+ */
20
+ const outputPath = (input, extname, outDir) => {
21
+ const fileName = (0, format_1.replaceExtname)(node_path_1.default.basename(input), extname);
22
+ return node_path_1.default.join(outDir ? node_path_1.default.resolve(outDir) : node_path_1.default.dirname(input), fileName);
23
+ };
24
+ exports.outputPath = outputPath;
25
+ const resolveSettings = (ctx, $T, flags) => {
26
+ const settings = (0, config_1.getSettings)(ctx, $T);
27
+ if (flags.convert !== undefined) {
28
+ settings.convert = (0, config_1.parseConvert)($T, flags.convert);
29
+ }
30
+ if (flags.preserve !== undefined) {
31
+ settings.preserve = (0, config_1.parsePreserve)($T, flags.preserve);
32
+ }
33
+ return settings;
34
+ };
35
+ const tinifyCommand = async (ctx, files, flags) => {
36
+ const $T = (0, i18n_1.T)(ctx);
37
+ let settings;
38
+ try {
39
+ settings = resolveSettings(ctx, $T, flags);
40
+ }
41
+ catch (e) {
42
+ if (e instanceof config_1.ConfigError) {
43
+ ctx.log.error(e.message);
44
+ process.exitCode = 1;
45
+ return;
46
+ }
47
+ throw e;
48
+ }
49
+ const engine = (0, engines_1.createEngine)(ctx, settings, $T);
50
+ if (flags.outDir) {
51
+ node_fs_1.default.mkdirSync(node_path_1.default.resolve(flags.outDir), { recursive: true });
52
+ }
53
+ const counts = { done: 0, skipped: 0, failed: 0, before: 0, after: 0 };
54
+ let stopped;
55
+ const spinner = (0, spinner_1.createSpinner)(ctx);
56
+ const log = (0, spinner_1.spinnerLogger)(ctx, spinner);
57
+ let finished = 0;
58
+ const progress = () => {
59
+ spinner.update($T('TINIFY_PROGRESS', { engine: engine.name, done: String(finished), total: String(files.length) }));
60
+ };
61
+ progress();
62
+ const tinifyOne = async (file) => {
63
+ const input = node_path_1.default.resolve(file);
64
+ const name = node_path_1.default.basename(input);
65
+ if (stopped) {
66
+ counts.failed++;
67
+ return;
68
+ }
69
+ if (!node_fs_1.default.existsSync(input) || !node_fs_1.default.statSync(input).isFile()) {
70
+ log.error($T('TINIFY_CLI_NOT_FILE', { path: file }));
71
+ counts.failed++;
72
+ return;
73
+ }
74
+ try {
75
+ const buffer = await node_fs_1.default.promises.readFile(input);
76
+ const outcome = await (0, compress_1.compressImage)(engine, buffer, {
77
+ convert: settings.convert,
78
+ background: settings.background,
79
+ preserve: settings.preserve
80
+ });
81
+ if (outcome.status !== 'compressed') {
82
+ log.info($T(outcome.status === 'unsupported' ? 'TINIFY_SKIP_UNSUPPORTED' : 'TINIFY_SKIP_NOT_SMALLER', { name }));
83
+ counts.skipped++;
84
+ if (outcome.status === 'notSmaller' && flags.outDir) {
85
+ // Still deliver the file to the output folder so it holds the full set.
86
+ await node_fs_1.default.promises.writeFile((0, exports.outputPath)(input, (0, format_1.currentExtname)(name), flags.outDir), buffer);
87
+ }
88
+ return;
89
+ }
90
+ const extname = outcome.format === outcome.inputFormat ? (0, format_1.currentExtname)(name) || (0, format_1.extnameFor)(outcome.format) : (0, format_1.extnameFor)(outcome.format);
91
+ const target = (0, exports.outputPath)(input, extname, flags.outDir);
92
+ await node_fs_1.default.promises.writeFile(target, outcome.buffer);
93
+ counts.done++;
94
+ counts.before += outcome.before;
95
+ counts.after += outcome.after;
96
+ log.success($T('TINIFY_CLI_WROTE', {
97
+ name,
98
+ before: (0, format_1.formatBytes)(outcome.before),
99
+ after: (0, format_1.formatBytes)(outcome.after),
100
+ ratio: (0, format_1.formatRatio)(outcome.before, outcome.after),
101
+ path: node_path_1.default.relative(process.cwd(), target) || target
102
+ }));
103
+ }
104
+ catch (e) {
105
+ counts.failed++;
106
+ const message = e instanceof Error ? e.message : String(e);
107
+ log.error($T('TINIFY_FAILED_ITEM', { name, message }));
108
+ if (e instanceof engines_1.EngineError && e.fatal) {
109
+ stopped = message;
110
+ }
111
+ }
112
+ };
113
+ await (0, compress_1.mapLimit)(files, CONCURRENCY, async (file) => {
114
+ try {
115
+ await tinifyOne(file);
116
+ }
117
+ finally {
118
+ finished++;
119
+ progress();
120
+ }
121
+ }).finally(() => { spinner.stop(); });
122
+ if (stopped) {
123
+ ctx.log.error($T('TINIFY_CLI_STOPPED', { message: stopped }));
124
+ }
125
+ const summary = $T('TINIFY_CLI_SUMMARY', {
126
+ done: String(counts.done),
127
+ skipped: String(counts.skipped),
128
+ failed: String(counts.failed),
129
+ before: (0, format_1.formatBytes)(counts.before),
130
+ after: (0, format_1.formatBytes)(counts.after)
131
+ });
132
+ if (counts.failed > 0) {
133
+ ctx.log.warn(summary);
134
+ process.exitCode = 1;
135
+ }
136
+ else {
137
+ ctx.log.success(summary);
138
+ }
139
+ const usage = engine.usage?.();
140
+ if (usage) {
141
+ ctx.log.info(usage);
142
+ }
143
+ };
144
+ exports.tinifyCommand = tinifyCommand;
145
+ const registerCli = (ctx) => {
146
+ ctx.cmd.register('tinify', {
147
+ handle(ctx) {
148
+ const program = ctx.cmd.program;
149
+ program
150
+ .command('tinify <files...>')
151
+ .description('compress (and optionally convert) local images with the configured engine')
152
+ .option('-o, --out-dir <dir>', 'write results to this folder instead of next to the inputs')
153
+ .option('--convert <format>', 'convert to avif, webp, jpeg or png; none keeps the format (default: plugin config)')
154
+ .option('--preserve <keys>', 'metadata to keep, comma separated: copyright,creation,location (default: plugin config)')
155
+ .action(async (files, flags) => {
156
+ await (0, exports.tinifyCommand)(ctx, files, flags);
157
+ });
158
+ }
159
+ });
160
+ };
161
+ exports.registerCli = registerCli;
@@ -0,0 +1,22 @@
1
+ import { type CompressionEngine, type CompressOptions } from './engines';
2
+ import { type ImageFormat } from './format';
3
+ export type CompressOutcome = {
4
+ status: 'compressed';
5
+ buffer: Buffer;
6
+ format: ImageFormat;
7
+ inputFormat: ImageFormat;
8
+ before: number;
9
+ after: number;
10
+ } | {
11
+ status: 'unsupported';
12
+ } | {
13
+ status: 'notSmaller';
14
+ };
15
+ /**
16
+ * Compresses one image. Files the engine cannot read, by magic bytes or by its own answer, come back
17
+ * as `unsupported` instead of an error. Without a format conversion, a result that is not smaller than the input
18
+ * is dropped (`notSmaller`), so the original stays untouched.
19
+ */
20
+ export declare const compressImage: (engine: CompressionEngine, input: Buffer, options: CompressOptions) => Promise<CompressOutcome>;
21
+ /** Runs `fn` over `items` with at most `limit` in flight. */
22
+ export declare const mapLimit: <T>(items: T[], limit: number, fn: (item: T, index: number) => Promise<void>) => Promise<void>;
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.mapLimit = exports.compressImage = void 0;
4
+ const engines_1 = require("./engines");
5
+ const format_1 = require("./format");
6
+ /**
7
+ * Compresses one image. Files the engine cannot read, by magic bytes or by its own answer, come back
8
+ * as `unsupported` instead of an error. Without a format conversion, a result that is not smaller than the input
9
+ * is dropped (`notSmaller`), so the original stays untouched.
10
+ */
11
+ const compressImage = async (engine, input, options) => {
12
+ const inputFormat = (0, format_1.detectFormat)(input);
13
+ if (!inputFormat || !engine.inputFormats.includes(inputFormat)) {
14
+ return { status: 'unsupported' };
15
+ }
16
+ let result;
17
+ try {
18
+ result = await engine.compress(input, options);
19
+ }
20
+ catch (e) {
21
+ if (e instanceof engines_1.EngineError && e.unsupported) {
22
+ return { status: 'unsupported' };
23
+ }
24
+ throw e;
25
+ }
26
+ if (result.format === inputFormat && result.buffer.length >= input.length) {
27
+ return { status: 'notSmaller' };
28
+ }
29
+ return { status: 'compressed', buffer: result.buffer, format: result.format, inputFormat, before: input.length, after: result.buffer.length };
30
+ };
31
+ exports.compressImage = compressImage;
32
+ /** Runs `fn` over `items` with at most `limit` in flight. */
33
+ const mapLimit = async (items, limit, fn) => {
34
+ let next = 0;
35
+ const worker = async () => {
36
+ while (next < items.length) {
37
+ const index = next++;
38
+ await fn(items[index], index);
39
+ }
40
+ };
41
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
42
+ };
43
+ exports.mapLimit = mapLimit;
@@ -0,0 +1,43 @@
1
+ import type { IPicGo, IPluginConfig } from 'picgo';
2
+ import type { ConvertFormat, PreserveKey } from './engines/types';
3
+ import type { Translate } from './i18n';
4
+ export declare const PLUGIN_NAME = "picgo-plugin-tinify";
5
+ export declare const CONFIG_KEY = "picgo-plugin-tinify";
6
+ export declare const ENGINES: readonly ["tinypng"];
7
+ export type EngineId = typeof ENGINES[number];
8
+ export declare const CONVERT_CHOICES: readonly ["none", "avif", "webp", "jpeg", "png"];
9
+ export declare const PRESERVE_KEYS: readonly PreserveKey[];
10
+ /** What PicGo stores under `picgo-plugin-tinify`. Values from the CLI prompt are strings. */
11
+ export interface UserConfig {
12
+ engine?: string;
13
+ tinypngApiKey?: string;
14
+ convert?: string;
15
+ background?: string;
16
+ preserve?: string[] | string;
17
+ minSize?: string | number;
18
+ }
19
+ export interface Settings {
20
+ engine: EngineId;
21
+ tinypngApiKey: string;
22
+ convert?: ConvertFormat;
23
+ background: string;
24
+ preserve: PreserveKey[];
25
+ minSizeBytes: number;
26
+ }
27
+ export declare class ConfigError extends Error {
28
+ constructor(message: string);
29
+ }
30
+ export declare const getUserConfig: (ctx: IPicGo) => UserConfig;
31
+ export declare const parseConvert: ($T: Translate, value: string | undefined) => ConvertFormat | undefined;
32
+ export declare const parseBackground: ($T: Translate, value: string | undefined) => string;
33
+ export declare const parsePreserve: ($T: Translate, value: string[] | string | undefined) => PreserveKey[];
34
+ export declare const parseMinSize: ($T: Translate, value: string | number | undefined) => number;
35
+ /** The configured engine id, `tinypng` when unset; undefined when it names no known engine. */
36
+ export declare const configuredEngine: (config: UserConfig) => EngineId | undefined;
37
+ /** `TINYPNG_API_KEY` when set, else the saved key. */
38
+ export declare const tinypngApiKey: (config: UserConfig, env?: NodeJS.ProcessEnv) => string;
39
+ /** Reads and validates the plugin config. Throws ConfigError with a message meant for the user. */
40
+ export declare const getSettings: (ctx: IPicGo, $T: Translate, env?: NodeJS.ProcessEnv) => Settings;
41
+ /** Test hook, not shown in the UI: point the TinyPNG engine at a mock server. */
42
+ export declare const apiOverride: (env?: NodeJS.ProcessEnv) => string | undefined;
43
+ export declare const pluginConfig: (ctx: IPicGo, $T: Translate) => IPluginConfig[];