image-optimizer-node 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 +224 -2
- package/action.yml +257 -0
- package/dist/cli.cjs +3158 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +3131 -0
- package/dist/index.cjs +2902 -0
- package/dist/index.d.cts +414 -0
- package/dist/index.d.ts +414 -0
- package/dist/index.js +2810 -0
- package/docs/AI/SKILL.md +73 -0
- package/package.json +83 -4
- package/schemas/imgopt.config.schema.json +236 -0
- package/templates/workflows/optimize-images.yml +64 -0
package/README.md
CHANGED
|
@@ -1,3 +1,225 @@
|
|
|
1
|
-
#
|
|
1
|
+
# image-optimizer-node (`imgopt-node`)
|
|
2
|
+
|
|
3
|
+
一个基于高性能 Rust 引擎 [`imgopt` (`Image-Optimizer-Cli`)](https://github.com/xzsean666/Image-Optimizer-Cli) 的通用 Node.js 图像优化 CLI、TypeScript SDK 与 GitHub Action 工具,面向前端项目、文档站点、移动端与静态资源仓库。
|
|
4
|
+
|
|
5
|
+
## 核心特性
|
|
6
|
+
|
|
7
|
+
- **一命令自动探测与初始化(`init`)**:自动识别项目技术栈(Vite / Next.js / Nuxt / Astro / VitePress / Docusaurus / React Native / Monorepo / 通用项目),探测 `src/assets`、`public`、`static`、`assets`、`docs/images` 等目录并写入 [`imgopt.config.json`](schemas/imgopt.config.schema.json)。
|
|
8
|
+
- **绝不重复处理(双哈希增量状态机)**:在 `.imgopt/manifest.json` 中同时记录**原图 SHA-256(`originalSha256`)**、**优化后 SHA-256(`optimizedSha256`)**与**参数签名(`configHash`)**。再次运行时命中缓存 0 开销跳过,绝不对已优化图片二次有损压缩。
|
|
9
|
+
- **默认保留原图备份(`.imgopt/originals`)**:默认开启 `backup.enabled: true`,将原图按相对路径镜像备份到 `.imgopt/originals/`(可在 JSON 中关闭或改路径):
|
|
10
|
+
- 当你调优配置参数(例如调高画质或增加缩放限制)时,直接从**无损原图备份**重压,避免画质代际劣化;
|
|
11
|
+
- 支持 `imgopt-node restore` 一键还原单张或全部原图。
|
|
12
|
+
- **可控的 CLI 二进制自动下载与 Action 集成**:
|
|
13
|
+
- 无需在项目或 CI 安装 Rust/Cargo,自动按系统平台(Linux/macOS/Windows, x64/arm64)从 `xzsean666/Image-Optimizer-Cli` Releases 拉取预编译 `imgopt` 并校验 `.sha256`;
|
|
14
|
+
- 提供 `imgopt-node cli status / update / path` 与仓库级 Composite GitHub Action([`action.yml`](action.yml)),可在 GitHub Actions 中精确控制下载 `latest` 或指定版本 CLI。
|
|
15
|
+
- **面向工程工作流的实用能力**:
|
|
16
|
+
- `check` 模式(CI 门禁:不修改文件,存在未优化图片或体积超预算即失败);
|
|
17
|
+
- `--staged`(只处理 Git 暂存区图片并自动 re-stage,完美配合 `husky` / `lint-staged`);
|
|
18
|
+
- `rules` 分目录覆写规则(例如首页大图转 WebP,小图标保持原格式高画质);
|
|
19
|
+
- `budgets` 体积/尺寸预算告警、`--dry-run` 演练、`clean` 清理孤儿备份、`doctor` 健康诊断。
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## 快速开始
|
|
24
|
+
|
|
25
|
+
### 1. 安装(支持 npm 与 GitHub 直接安装)
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
# 从 npm 安装(推荐)
|
|
29
|
+
pnpm add -D image-optimizer-node
|
|
30
|
+
# 或全局安装 / 免安装运行
|
|
31
|
+
npm install -g image-optimizer-node
|
|
32
|
+
pnpm dlx image-optimizer-node init
|
|
33
|
+
|
|
34
|
+
# 或从 GitHub 安装(遵循内部 git+commit hash 规范)
|
|
35
|
+
pnpm add -D git+https://github.com/xzsean666/image-optimizer-node.git
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### 2. 初始化配置
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
# 自动探测项目目录并生成 imgopt.config.json
|
|
42
|
+
imgopt-node init
|
|
43
|
+
|
|
44
|
+
# 同时生成 GitHub Actions 工作流并将备份目录加入 .gitignore
|
|
45
|
+
imgopt-node init --ci --gitignore
|
|
46
|
+
|
|
47
|
+
# 指定目录 / Web 大图模板(默认开启 maxWidth: 2560 等比缩减)
|
|
48
|
+
imgopt-node init --dir src/assets public --template web
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### 3. 执行增量优化
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
# 预览将优化哪些图片(不落盘修改)
|
|
55
|
+
imgopt-node optimize --dry-run
|
|
56
|
+
|
|
57
|
+
# 执行优化(首次运行会自动下载最新版 imgopt CLI 并校验 SHA-256)
|
|
58
|
+
imgopt-node optimize
|
|
59
|
+
|
|
60
|
+
# 仅优化 Git 暂存区图片(用于 pre-commit hook)
|
|
61
|
+
imgopt-node optimize --staged
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### 4. 其他常用命令
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
# CI 门禁检查(不改文件,有未优化图片或超出 budgets 则返回非 0 退出码)
|
|
68
|
+
imgopt-node check
|
|
69
|
+
|
|
70
|
+
# 还原某张或全部原图
|
|
71
|
+
imgopt-node restore src/assets/hero.png
|
|
72
|
+
imgopt-node restore --all
|
|
73
|
+
|
|
74
|
+
# 清理项目已删除图片对应的孤儿备份与无效 manifest 记录(--cache 顺带清理旧 CLI 缓存)
|
|
75
|
+
imgopt-node clean --cache
|
|
76
|
+
|
|
77
|
+
# 查看与更新底层 imgopt CLI 二进制
|
|
78
|
+
imgopt-node cli status
|
|
79
|
+
imgopt-node cli update --cli-version latest --force
|
|
80
|
+
|
|
81
|
+
# 项目与环境健康诊断
|
|
82
|
+
imgopt-node doctor
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
---
|
|
86
|
+
|
|
87
|
+
## `imgopt.config.json` 配置说明
|
|
88
|
+
|
|
89
|
+
`imgopt-node init` 默认生成的结构如下:
|
|
90
|
+
|
|
91
|
+
```json
|
|
92
|
+
{
|
|
93
|
+
"$schema": "https://raw.githubusercontent.com/xzsean666/image-optimizer-node/main/schemas/imgopt.config.schema.json",
|
|
94
|
+
"version": 1,
|
|
95
|
+
"cli": {
|
|
96
|
+
"repo": "xzsean666/Image-Optimizer-Cli",
|
|
97
|
+
"version": "latest",
|
|
98
|
+
"autoDownload": true,
|
|
99
|
+
"autoUpdate": false
|
|
100
|
+
},
|
|
101
|
+
"targets": [
|
|
102
|
+
{
|
|
103
|
+
"dir": "src/assets",
|
|
104
|
+
"include": ["**/*.{png,jpg,jpeg,webp,avif,gif}"],
|
|
105
|
+
"exclude": ["**/favicon*.*", "**/apple-touch-icon*.*"]
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
"dir": "public",
|
|
109
|
+
"include": ["**/*.{png,jpg,jpeg,webp,avif,gif}"],
|
|
110
|
+
"exclude": ["**/favicon*.*", "**/apple-touch-icon*.*"]
|
|
111
|
+
}
|
|
112
|
+
],
|
|
113
|
+
"backup": {
|
|
114
|
+
"enabled": true,
|
|
115
|
+
"dir": ".imgopt/originals",
|
|
116
|
+
"strategy": "preserve-first"
|
|
117
|
+
},
|
|
118
|
+
"manifest": ".imgopt/manifest.json",
|
|
119
|
+
"optimization": {
|
|
120
|
+
"preset": "balanced",
|
|
121
|
+
"quality": 0.95,
|
|
122
|
+
"effort": 5,
|
|
123
|
+
"format": "preserve",
|
|
124
|
+
"preserveMetadata": false,
|
|
125
|
+
"preserveIcc": false,
|
|
126
|
+
"convertToSrgb": true,
|
|
127
|
+
"minBytes": 1024,
|
|
128
|
+
"minSavingsPercent": 1,
|
|
129
|
+
"removeSourceOnFormatChange": true
|
|
130
|
+
},
|
|
131
|
+
"rules": []
|
|
132
|
+
}
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### 关键配置项
|
|
136
|
+
|
|
137
|
+
- **`backup.enabled`**(默认 `true`):是否在优化前备份原图。设为 `false` 即可关闭原图保留。
|
|
138
|
+
- **`backup.dir`**(默认 `".imgopt/originals"`):原图备份目录,隐藏目录不会被 Vite/Next/Webpack 或 `imgopt` 自身扫描打包。
|
|
139
|
+
- **`backup.strategy`**:
|
|
140
|
+
- `"preserve-first"`(默认):首次优化写入备份;当你主动替换了新的图片源文件时更新该备份;
|
|
141
|
+
- `"keep-initial"`:永远只保留最初第一版原图备份。
|
|
142
|
+
- **`optimization.format`**(默认 `"preserve"`):保持原文件扩展名(`.png`/`.jpg`/`.webp`/`.gif`),避免破坏前端代码 `import` 与 `<img src>`;也可设为 `"auto"` / `"webp"` / `"avif"`,或通过 `rules` 仅对特定目录生效。
|
|
143
|
+
- **`optimization.quality` / `preset` / `effort`**:默认 `balanced + quality: 0.95 + effort: 5`,在肉眼几乎不可辨识画质下降的前提下大幅压缩体积(支持 `0.0 ~ 1.0` SSIM 目标)。
|
|
144
|
+
- **`rules`**:按 glob 路径局部覆盖参数,例如:
|
|
145
|
+
```json
|
|
146
|
+
"rules": [
|
|
147
|
+
{
|
|
148
|
+
"match": "public/banners/**",
|
|
149
|
+
"optimization": {
|
|
150
|
+
"format": "webp",
|
|
151
|
+
"resize": { "maxWidth": 1920, "mode": "scale-down" }
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
]
|
|
155
|
+
```
|
|
156
|
+
- **`budgets`**:可选体积/分辨率预算门禁:
|
|
157
|
+
```json
|
|
158
|
+
"budgets": {
|
|
159
|
+
"maxFileSizeKb": 500,
|
|
160
|
+
"maxWidth": 2560,
|
|
161
|
+
"maxHeight": 2560
|
|
162
|
+
}
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
---
|
|
166
|
+
|
|
167
|
+
## GitHub Actions 集成(可控下载最新 CLI)
|
|
168
|
+
|
|
169
|
+
在任意项目的 `.github/workflows/optimize-images.yml` 中直接引用本仓库 Composite Action(或运行 `imgopt-node init --ci` 自动生成):
|
|
170
|
+
|
|
171
|
+
```yaml
|
|
172
|
+
- uses: xzsean666/image-optimizer-node@main
|
|
173
|
+
with:
|
|
174
|
+
cli-version: latest # 'latest' 会解析最新 tag 并自动更新缓存;也可固定如 'v0.1.2'
|
|
175
|
+
force-download-cli: false # 设为 'true' 强制跳过缓存重新拉取 CLI
|
|
176
|
+
mode: optimize # 'optimize' 或 'check'
|
|
177
|
+
commit: true # 自动提交优化后的图片与 .imgopt/manifest.json
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
---
|
|
181
|
+
|
|
182
|
+
## 作为 Node.js / TypeScript SDK 调用
|
|
183
|
+
|
|
184
|
+
```typescript
|
|
185
|
+
import {
|
|
186
|
+
initProject,
|
|
187
|
+
optimizeProject,
|
|
188
|
+
checkProject,
|
|
189
|
+
restoreOriginals,
|
|
190
|
+
ensureCli,
|
|
191
|
+
} from 'image-optimizer-node';
|
|
192
|
+
|
|
193
|
+
await initProject({ projectRoot: './my-app', template: 'web' });
|
|
194
|
+
const report = await optimizeProject({ projectRoot: './my-app' });
|
|
195
|
+
console.log(`Saved ${report.summary.savedBytes} bytes`);
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
---
|
|
199
|
+
|
|
200
|
+
## 环境变量覆盖
|
|
201
|
+
|
|
202
|
+
| 变量 | 说明 |
|
|
203
|
+
|---|---|
|
|
204
|
+
| `IMGOPT_BIN` | 强制使用本地指定的 `imgopt` 可执行文件路径 |
|
|
205
|
+
| `IMGOPT_CACHE_DIR` | 自定义 CLI 二进制缓存目录 |
|
|
206
|
+
| `IMGOPT_DOWNLOAD_BASE_URL` | 自定义 Releases 下载镜像/代理地址 |
|
|
207
|
+
| `GITHUB_TOKEN` / `GH_TOKEN` | 提高 GitHub Releases API 查询限额 |
|
|
208
|
+
|
|
209
|
+
---
|
|
210
|
+
|
|
211
|
+
## 发布 npm 包与 GitHub Release
|
|
212
|
+
|
|
213
|
+
仓库内置 [`.github/workflows/release.yml`](.github/workflows/release.yml),通过 Repository Secret `NPM_TOKEN` 自动完成校验、测试、npm 发布与 GitHub Release 创建:
|
|
214
|
+
|
|
215
|
+
- **手动触发**:在 GitHub 仓库进入 **Actions -> Release & Publish npm -> Run workflow**,选择 `version`(`current` / `patch` / `minor` / `major` 或指定版本号)与 `dry_run`。
|
|
216
|
+
- **CLI 触发**:
|
|
217
|
+
```bash
|
|
218
|
+
# 先演练验证(不真正发布)
|
|
219
|
+
gh workflow run release.yml -f version=current -f dry_run=true
|
|
220
|
+
|
|
221
|
+
# 正式发布当前版本
|
|
222
|
+
gh workflow run release.yml -f version=current -f dry_run=false
|
|
223
|
+
```
|
|
224
|
+
- **Tag 触发**:推送与 `package.json` 版本一致的 `v*` 标签(如 `git tag v0.1.0 && git push origin v0.1.0`)同样自动触发发布。
|
|
2
225
|
|
|
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.
|
package/action.yml
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
name: "Image Optimizer Node Action"
|
|
2
|
+
description: "Download latest or pinned imgopt CLI release and incrementally optimize or check repository images without reprocessing."
|
|
3
|
+
|
|
4
|
+
inputs:
|
|
5
|
+
cli-version:
|
|
6
|
+
description: "imgopt CLI release tag to download ('latest' or e.g. 'v0.1.2')"
|
|
7
|
+
required: false
|
|
8
|
+
default: "latest"
|
|
9
|
+
cli-repo:
|
|
10
|
+
description: "GitHub repository hosting imgopt CLI releases"
|
|
11
|
+
required: false
|
|
12
|
+
default: "xzsean666/Image-Optimizer-Cli"
|
|
13
|
+
force-download-cli:
|
|
14
|
+
description: "Bypass cache and force downloading the target imgopt CLI release"
|
|
15
|
+
required: false
|
|
16
|
+
default: "false"
|
|
17
|
+
config:
|
|
18
|
+
description: "Path to imgopt.config.json relative to working-directory"
|
|
19
|
+
required: false
|
|
20
|
+
default: "imgopt.config.json"
|
|
21
|
+
mode:
|
|
22
|
+
description: "Execution mode: 'optimize' or 'check'"
|
|
23
|
+
required: false
|
|
24
|
+
default: "optimize"
|
|
25
|
+
dry-run:
|
|
26
|
+
description: "Preview optimize run without modifying repository files"
|
|
27
|
+
required: false
|
|
28
|
+
default: "false"
|
|
29
|
+
fail-on-budget:
|
|
30
|
+
description: "Fail the step when any configured size or dimension budget is exceeded"
|
|
31
|
+
required: false
|
|
32
|
+
default: "false"
|
|
33
|
+
commit:
|
|
34
|
+
description: "Commit optimized images, manifest, and backups back to the current branch (only in optimize mode)"
|
|
35
|
+
required: false
|
|
36
|
+
default: "false"
|
|
37
|
+
commit-message:
|
|
38
|
+
description: "Git commit message used when commit is true"
|
|
39
|
+
required: false
|
|
40
|
+
default: "chore(images): optimize assets with imgopt-node [skip ci]"
|
|
41
|
+
working-directory:
|
|
42
|
+
description: "Directory containing the project and imgopt.config.json"
|
|
43
|
+
required: false
|
|
44
|
+
default: "."
|
|
45
|
+
node-version:
|
|
46
|
+
description: "Node.js version to setup if not already configured"
|
|
47
|
+
required: false
|
|
48
|
+
default: "22"
|
|
49
|
+
github-token:
|
|
50
|
+
description: "GitHub token used to resolve releases and push commits"
|
|
51
|
+
required: false
|
|
52
|
+
default: ${{ github.token }}
|
|
53
|
+
|
|
54
|
+
outputs:
|
|
55
|
+
cli-version-resolved:
|
|
56
|
+
description: "Resolved imgopt CLI version actually executed"
|
|
57
|
+
value: ${{ steps.run_tool.outputs.cli_version }}
|
|
58
|
+
optimized-count:
|
|
59
|
+
description: "Number of images newly optimized or reoptimized"
|
|
60
|
+
value: ${{ steps.run_tool.outputs.optimized_count }}
|
|
61
|
+
saved-bytes:
|
|
62
|
+
description: "Total bytes saved across scanned images"
|
|
63
|
+
value: ${{ steps.run_tool.outputs.saved_bytes }}
|
|
64
|
+
saved-percent:
|
|
65
|
+
description: "Percentage of bytes saved"
|
|
66
|
+
value: ${{ steps.run_tool.outputs.saved_percent }}
|
|
67
|
+
report-json:
|
|
68
|
+
description: "Path to machine-readable JSON report file"
|
|
69
|
+
value: ${{ steps.run_tool.outputs.report_json }}
|
|
70
|
+
|
|
71
|
+
runs:
|
|
72
|
+
using: "composite"
|
|
73
|
+
steps:
|
|
74
|
+
- name: Setup Node.js
|
|
75
|
+
uses: actions/setup-node@v4
|
|
76
|
+
with:
|
|
77
|
+
node-version: ${{ inputs.node-version }}
|
|
78
|
+
|
|
79
|
+
- name: Install image-optimizer-node Action runtime
|
|
80
|
+
shell: bash
|
|
81
|
+
env:
|
|
82
|
+
ACTION_PATH: ${{ github.action_path }}
|
|
83
|
+
run: |
|
|
84
|
+
cd "${ACTION_PATH}"
|
|
85
|
+
if [ -f "dist/cli.js" ]; then
|
|
86
|
+
npm install --omit=dev --no-audit --no-fund --ignore-scripts
|
|
87
|
+
else
|
|
88
|
+
npm install --no-audit --no-fund --ignore-scripts
|
|
89
|
+
npm run build
|
|
90
|
+
fi
|
|
91
|
+
|
|
92
|
+
- name: Resolve target imgopt CLI release tag
|
|
93
|
+
id: resolve_tag
|
|
94
|
+
shell: bash
|
|
95
|
+
env:
|
|
96
|
+
INPUT_CLI_VERSION: ${{ inputs.cli-version }}
|
|
97
|
+
INPUT_CLI_REPO: ${{ inputs.cli-repo }}
|
|
98
|
+
GITHUB_TOKEN: ${{ inputs.github-token }}
|
|
99
|
+
run: |
|
|
100
|
+
TAG=$(node -e '
|
|
101
|
+
const req = process.env.INPUT_CLI_VERSION || "latest";
|
|
102
|
+
const repo = process.env.INPUT_CLI_REPO || "xzsean666/Image-Optimizer-Cli";
|
|
103
|
+
async function main() {
|
|
104
|
+
if (req !== "latest") {
|
|
105
|
+
console.log(req.startsWith("v") ? req : "v" + req);
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
const res = await fetch(`https://github.com/${repo}/releases/latest`, {
|
|
109
|
+
method: "HEAD",
|
|
110
|
+
redirect: "manual",
|
|
111
|
+
headers: { "User-Agent": "image-optimizer-node-action" },
|
|
112
|
+
});
|
|
113
|
+
const loc = res.headers.get("location") || "";
|
|
114
|
+
const m = loc.match(/\/releases\/tag\/([^/?#]+)/);
|
|
115
|
+
if (m && m[1]) {
|
|
116
|
+
console.log(m[1]);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
const headers = { "User-Agent": "image-optimizer-node-action", Accept: "application/vnd.github+json" };
|
|
120
|
+
if (process.env.GITHUB_TOKEN) headers.Authorization = `Bearer ${process.env.GITHUB_TOKEN}`;
|
|
121
|
+
const apiRes = await fetch(`https://api.github.com/repos/${repo}/releases/latest`, { headers });
|
|
122
|
+
if (!apiRes.ok) throw new Error(`Failed to resolve latest release: HTTP ${apiRes.status}`);
|
|
123
|
+
const data = await apiRes.json();
|
|
124
|
+
console.log(data.tag_name);
|
|
125
|
+
}
|
|
126
|
+
main().catch((err) => { console.error(err); process.exit(1); });
|
|
127
|
+
')
|
|
128
|
+
echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
|
|
129
|
+
echo "Resolved imgopt CLI target tag: ${TAG}"
|
|
130
|
+
|
|
131
|
+
- name: Restore cached imgopt CLI binary
|
|
132
|
+
if: ${{ inputs.force-download-cli != 'true' }}
|
|
133
|
+
uses: actions/cache@v4
|
|
134
|
+
with:
|
|
135
|
+
path: ~/.cache/imgopt-node/bin
|
|
136
|
+
key: imgopt-bin-${{ runner.os }}-${{ runner.arch }}-${{ steps.resolve_tag.outputs.tag }}
|
|
137
|
+
|
|
138
|
+
- name: Download / verify imgopt CLI binary
|
|
139
|
+
shell: bash
|
|
140
|
+
working-directory: ${{ inputs.working-directory }}
|
|
141
|
+
env:
|
|
142
|
+
ACTION_PATH: ${{ github.action_path }}
|
|
143
|
+
TARGET_TAG: ${{ steps.resolve_tag.outputs.tag }}
|
|
144
|
+
FORCE_DL: ${{ inputs.force-download-cli }}
|
|
145
|
+
CONFIG_PATH: ${{ inputs.config }}
|
|
146
|
+
GITHUB_TOKEN: ${{ inputs.github-token }}
|
|
147
|
+
IMGOPT_CACHE_DIR: ~/.cache/imgopt-node/bin
|
|
148
|
+
run: |
|
|
149
|
+
ARGS=(cli update --cli-version "${TARGET_TAG}")
|
|
150
|
+
if [ "${FORCE_DL}" = "true" ]; then
|
|
151
|
+
ARGS+=(--force)
|
|
152
|
+
fi
|
|
153
|
+
if [ -f "${CONFIG_PATH}" ]; then
|
|
154
|
+
ARGS+=(--config "${CONFIG_PATH}")
|
|
155
|
+
fi
|
|
156
|
+
node "${ACTION_PATH}/dist/cli.js" "${ARGS[@]}"
|
|
157
|
+
|
|
158
|
+
- name: Run imgopt-node (${{ inputs.mode }})
|
|
159
|
+
id: run_tool
|
|
160
|
+
shell: bash
|
|
161
|
+
working-directory: ${{ inputs.working-directory }}
|
|
162
|
+
env:
|
|
163
|
+
ACTION_PATH: ${{ github.action_path }}
|
|
164
|
+
MODE: ${{ inputs.mode }}
|
|
165
|
+
CONFIG_PATH: ${{ inputs.config }}
|
|
166
|
+
DRY_RUN: ${{ inputs.dry-run }}
|
|
167
|
+
FAIL_ON_BUDGET: ${{ inputs.fail-on-budget }}
|
|
168
|
+
TARGET_TAG: ${{ steps.resolve_tag.outputs.tag }}
|
|
169
|
+
IMGOPT_CACHE_DIR: ~/.cache/imgopt-node/bin
|
|
170
|
+
run: |
|
|
171
|
+
REPORT_FILE="${RUNNER_TEMP}/imgopt-node-report.json"
|
|
172
|
+
if [ "${MODE}" = "check" ]; then
|
|
173
|
+
set +e
|
|
174
|
+
node "${ACTION_PATH}/dist/cli.js" check --config "${CONFIG_PATH}" --json > "${REPORT_FILE}"
|
|
175
|
+
STATUS=$?
|
|
176
|
+
set -e
|
|
177
|
+
else
|
|
178
|
+
ARGS=(optimize --config "${CONFIG_PATH}" --cli-version "${TARGET_TAG}" --json)
|
|
179
|
+
if [ "${DRY_RUN}" = "true" ]; then
|
|
180
|
+
ARGS+=(--dry-run)
|
|
181
|
+
fi
|
|
182
|
+
if [ "${FAIL_ON_BUDGET}" = "true" ]; then
|
|
183
|
+
ARGS+=(--fail-on-budget)
|
|
184
|
+
fi
|
|
185
|
+
set +e
|
|
186
|
+
node "${ACTION_PATH}/dist/cli.js" "${ARGS[@]}" > "${REPORT_FILE}"
|
|
187
|
+
STATUS=$?
|
|
188
|
+
set -e
|
|
189
|
+
fi
|
|
190
|
+
|
|
191
|
+
node -e '
|
|
192
|
+
const fs = require("fs");
|
|
193
|
+
const reportPath = process.env.REPORT_FILE;
|
|
194
|
+
const mode = process.env.MODE;
|
|
195
|
+
const outFile = process.env.GITHUB_OUTPUT;
|
|
196
|
+
const summaryFile = process.env.GITHUB_STEP_SUMMARY;
|
|
197
|
+
if (!fs.existsSync(reportPath)) process.exit(0);
|
|
198
|
+
const raw = fs.readFileSync(reportPath, "utf8").trim();
|
|
199
|
+
if (!raw) process.exit(0);
|
|
200
|
+
let data;
|
|
201
|
+
try {
|
|
202
|
+
data = JSON.parse(raw);
|
|
203
|
+
} catch {
|
|
204
|
+
process.exit(0);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
if (mode === "check") {
|
|
208
|
+
fs.appendFileSync(outFile, `cli_version=${process.env.TARGET_TAG}\noptimized_count=0\nsaved_bytes=0\nsaved_percent=0\nreport_json=${reportPath}\n`);
|
|
209
|
+
const lines = [
|
|
210
|
+
"### Image Optimizer Check",
|
|
211
|
+
"",
|
|
212
|
+
`- **Status**: ${data.ok ? "PASS" : "FAIL"}`,
|
|
213
|
+
`- **Scanned**: ${data.totalScanned} | **Up-to-date**: ${data.upToDate} | **Pending**: ${data.pending.length} | **Budget violations**: ${data.budgetViolations.length}`,
|
|
214
|
+
];
|
|
215
|
+
if (data.pending.length > 0) {
|
|
216
|
+
lines.push("", "| Pending File | Reason | Size (B) |", "|---|---|---|");
|
|
217
|
+
for (const p of data.pending) lines.push(`| \`${p.path}\` | ${p.reason} | ${p.bytes} |`);
|
|
218
|
+
}
|
|
219
|
+
fs.appendFileSync(summaryFile, lines.join("\n") + "\n");
|
|
220
|
+
} else {
|
|
221
|
+
const s = data.summary;
|
|
222
|
+
fs.appendFileSync(outFile, `cli_version=${s.cliVersion}\noptimized_count=${s.optimized + s.reoptimizedFromBackup}\nsaved_bytes=${s.savedBytes}\nsaved_percent=${s.savedPercent.toFixed(2)}\nreport_json=${reportPath}\n`);
|
|
223
|
+
const lines = [
|
|
224
|
+
`### Image Optimizer Summary (imgopt ${s.cliVersion})`,
|
|
225
|
+
"",
|
|
226
|
+
`- **Scanned**: ${s.totalScanned} | **Optimized**: ${s.optimized} | **Reoptimized from backup**: ${s.reoptimizedFromBackup} | **Skipped (cached)**: ${s.skippedCached}`,
|
|
227
|
+
`- **Total Size**: ${s.originalBytes} B -> ${s.optimizedBytes} B (**saved ${s.savedBytes} B / ${s.savedPercent.toFixed(2)}%**)`,
|
|
228
|
+
];
|
|
229
|
+
const changed = (data.items || []).filter(i => i.status === "optimized" || i.status === "reoptimized-from-backup" || i.status === "failed");
|
|
230
|
+
if (changed.length > 0) {
|
|
231
|
+
lines.push("", "| File | Status | Original | Optimized | Saved | SSIM |", "|---|---|---|---|---|---|");
|
|
232
|
+
for (const item of changed) {
|
|
233
|
+
lines.push(`| \`${item.outputPath}\` | ${item.status} | ${item.originalBytes} B | ${item.optimizedBytes} B | ${item.savedPercent.toFixed(1)}% | ${item.qualityScore !== undefined ? item.qualityScore.toFixed(4) : "-"} |`);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
fs.appendFileSync(summaryFile, lines.join("\n") + "\n");
|
|
237
|
+
}
|
|
238
|
+
' REPORT_FILE="${REPORT_FILE}"
|
|
239
|
+
|
|
240
|
+
exit "${STATUS}"
|
|
241
|
+
|
|
242
|
+
- name: Commit and push optimized assets
|
|
243
|
+
if: ${{ inputs.mode == 'optimize' && inputs.commit == 'true' && inputs.dry-run != 'true' }}
|
|
244
|
+
shell: bash
|
|
245
|
+
working-directory: ${{ inputs.working-directory }}
|
|
246
|
+
env:
|
|
247
|
+
COMMIT_MESSAGE: ${{ inputs.commit-message }}
|
|
248
|
+
run: |
|
|
249
|
+
git config user.name "github-actions[bot]"
|
|
250
|
+
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
|
251
|
+
git add -A
|
|
252
|
+
if ! git diff --cached --quiet; then
|
|
253
|
+
git commit -m "${COMMIT_MESSAGE}"
|
|
254
|
+
git push
|
|
255
|
+
else
|
|
256
|
+
echo "No changes to commit."
|
|
257
|
+
fi
|