image-optimizer-node 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/dist/index.cjs ADDED
@@ -0,0 +1,2899 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ CANDIDATE_ASSET_DIRS: () => CANDIDATE_ASSET_DIRS,
34
+ CONFIG_FILENAMES: () => CONFIG_FILENAMES,
35
+ DEFAULT_BACKUP_CONFIG: () => DEFAULT_BACKUP_CONFIG,
36
+ DEFAULT_BACKUP_DIR: () => DEFAULT_BACKUP_DIR,
37
+ DEFAULT_CLI_CONFIG: () => DEFAULT_CLI_CONFIG,
38
+ DEFAULT_CLI_REPO: () => DEFAULT_CLI_REPO,
39
+ DEFAULT_CLI_VERSION: () => DEFAULT_CLI_VERSION,
40
+ DEFAULT_CONFIG_FILENAME: () => DEFAULT_CONFIG_FILENAME,
41
+ DEFAULT_EXCLUDE_GLOBS: () => DEFAULT_EXCLUDE_GLOBS,
42
+ DEFAULT_INCLUDE_GLOBS: () => DEFAULT_INCLUDE_GLOBS,
43
+ DEFAULT_MANIFEST_PATH: () => DEFAULT_MANIFEST_PATH,
44
+ DEFAULT_OPTIMIZATION_OPTIONS: () => DEFAULT_OPTIMIZATION_OPTIONS,
45
+ DEFAULT_SCHEMA_REF: () => DEFAULT_SCHEMA_REF,
46
+ IGNORED_DIR_NAMES: () => IGNORED_DIR_NAMES,
47
+ LATEST_CACHE_TTL_MS: () => LATEST_CACHE_TTL_MS,
48
+ SUPPORTED_IMAGE_EXTENSIONS: () => SUPPORTED_IMAGE_EXTENSIONS,
49
+ buildManifestIndex: () => buildManifestIndex,
50
+ checkProject: () => checkProject,
51
+ cleanProject: () => cleanProject,
52
+ computeOptimizationConfigHash: () => computeOptimizationConfigHash,
53
+ createDefaultConfig: () => createDefaultConfig,
54
+ createEmptyManifest: () => createEmptyManifest,
55
+ detectProject: () => detectProject,
56
+ doctorProject: () => doctorProject,
57
+ downloadCliRelease: () => downloadCliRelease,
58
+ ensureCli: () => ensureCli,
59
+ ensureOriginalBackup: () => ensureOriginalBackup,
60
+ evaluateBudgets: () => evaluateBudgets,
61
+ fetchLatestReleaseTag: () => fetchLatestReleaseTag,
62
+ findConfigPath: () => findConfigPath,
63
+ findEntryForDiskPath: () => findEntryForDiskPath,
64
+ getBackupRelPath: () => getBackupRelPath,
65
+ getCliStatus: () => getCliStatus,
66
+ hasValidBackup: () => hasValidBackup,
67
+ initProject: () => initProject,
68
+ inspectProject: () => inspectProject,
69
+ listBackupFiles: () => listBackupFiles,
70
+ listCachedVersions: () => listCachedVersions,
71
+ loadConfig: () => loadConfig,
72
+ loadManifest: () => loadManifest,
73
+ normalizeConfig: () => normalizeConfig,
74
+ optimizeProject: () => optimizeProject,
75
+ probeBinaryVersion: () => probeBinaryVersion,
76
+ resolveCacheDir: () => resolveCacheDir,
77
+ resolveEffectiveOptimization: () => resolveEffectiveOptimization,
78
+ resolveReleaseAsset: () => resolveReleaseAsset,
79
+ restoreOriginals: () => restoreOriginals,
80
+ saveConfig: () => saveConfig,
81
+ saveManifest: () => saveManifest,
82
+ scanProjectImages: () => scanProjectImages,
83
+ sha256Buffer: () => sha256Buffer,
84
+ sha256File: () => sha256File
85
+ });
86
+ module.exports = __toCommonJS(src_exports);
87
+
88
+ // node_modules/.pnpm/tsup@8.5.1_postcss@8.5.34_typescript@5.9.3/node_modules/tsup/assets/cjs_shims.js
89
+ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
90
+ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
91
+
92
+ // src/constants.ts
93
+ var DEFAULT_CONFIG_FILENAME = "imgopt.config.json";
94
+ var CONFIG_FILENAMES = [
95
+ "imgopt.config.json",
96
+ ".imgoptrc.json"
97
+ ];
98
+ var DEFAULT_CLI_REPO = "xzsean666/Image-Optimizer-Cli";
99
+ var DEFAULT_CLI_VERSION = "latest";
100
+ var DEFAULT_BACKUP_DIR = ".imgopt/originals";
101
+ var DEFAULT_MANIFEST_PATH = ".imgopt/manifest.json";
102
+ var DEFAULT_INCLUDE_GLOBS = ["**/*.{png,jpg,jpeg,webp,avif,gif}"];
103
+ var DEFAULT_EXCLUDE_GLOBS = [
104
+ "**/favicon*.*",
105
+ "**/apple-touch-icon*.*"
106
+ ];
107
+ var SUPPORTED_IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([
108
+ ".png",
109
+ ".jpg",
110
+ ".jpeg",
111
+ ".webp",
112
+ ".avif",
113
+ ".gif"
114
+ ]);
115
+ var IGNORED_DIR_NAMES = /* @__PURE__ */ new Set([
116
+ "node_modules",
117
+ ".git",
118
+ ".hg",
119
+ ".svn",
120
+ ".imgopt",
121
+ "dist",
122
+ "build",
123
+ "out",
124
+ ".next",
125
+ ".nuxt",
126
+ ".output",
127
+ ".svelte-kit",
128
+ ".astro",
129
+ ".vitepress",
130
+ "coverage",
131
+ "target",
132
+ ".cache"
133
+ ]);
134
+ var DEFAULT_CLI_CONFIG = {
135
+ repo: DEFAULT_CLI_REPO,
136
+ version: DEFAULT_CLI_VERSION,
137
+ autoDownload: true,
138
+ autoUpdate: false
139
+ };
140
+ var DEFAULT_BACKUP_CONFIG = {
141
+ enabled: true,
142
+ dir: DEFAULT_BACKUP_DIR,
143
+ strategy: "preserve-first"
144
+ };
145
+ var DEFAULT_OPTIMIZATION_OPTIONS = {
146
+ preset: "balanced",
147
+ quality: 0.95,
148
+ effort: 5,
149
+ format: "preserve",
150
+ preserveMetadata: false,
151
+ preserveIcc: false,
152
+ convertToSrgb: true,
153
+ minBytes: 1024,
154
+ minSavingsPercent: 1,
155
+ removeSourceOnFormatChange: true
156
+ };
157
+ var DEFAULT_SCHEMA_REF = "https://raw.githubusercontent.com/xzsean666/image-optimizer-node/main/schemas/imgopt.config.schema.json";
158
+ function createDefaultConfig(targets) {
159
+ return {
160
+ $schema: DEFAULT_SCHEMA_REF,
161
+ version: 1,
162
+ cli: { ...DEFAULT_CLI_CONFIG },
163
+ targets,
164
+ backup: { ...DEFAULT_BACKUP_CONFIG },
165
+ manifest: DEFAULT_MANIFEST_PATH,
166
+ optimization: { ...DEFAULT_OPTIMIZATION_OPTIONS },
167
+ rules: []
168
+ };
169
+ }
170
+ var CANDIDATE_ASSET_DIRS = [
171
+ { dir: "src/assets", stacks: ["vite", "vue", "react", "svelte", "astro", "angular", "general"] },
172
+ { dir: "src/images", stacks: ["vite", "vue", "react", "general"] },
173
+ { dir: "src/img", stacks: ["vite", "vue", "react", "general"] },
174
+ { dir: "public", stacks: ["next", "nuxt", "vite", "astro", "svelte", "react", "vue", "general"] },
175
+ { dir: "public/images", stacks: ["next", "nuxt", "general"] },
176
+ { dir: "static", stacks: ["svelte", "docusaurus", "hugo", "hexo", "general"] },
177
+ { dir: "static/img", stacks: ["docusaurus", "hugo", "general"] },
178
+ { dir: "assets", stacks: ["react-native", "flutter", "electron", "general"] },
179
+ { dir: "assets/images", stacks: ["react-native", "flutter", "general"] },
180
+ { dir: "app/assets", stacks: ["remix", "rails", "general"] },
181
+ { dir: "docs/public", stacks: ["vitepress", "docs"] },
182
+ { dir: "docs/images", stacks: ["docs", "general"] },
183
+ { dir: "docs/assets", stacks: ["docs", "general"] },
184
+ { dir: "content/images", stacks: ["docs", "hugo", "astro", "general"] },
185
+ { dir: "resources/images", stacks: ["electron", "general"] },
186
+ { dir: "images", stacks: ["general"] },
187
+ { dir: "img", stacks: ["general"] },
188
+ { dir: "media", stacks: ["general"] }
189
+ ];
190
+ var LATEST_CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
191
+
192
+ // src/config/loader.ts
193
+ var import_node_crypto2 = __toESM(require("crypto"), 1);
194
+ var import_node_path3 = __toESM(require("path"), 1);
195
+ var import_picomatch = __toESM(require("picomatch"), 1);
196
+
197
+ // src/utils/fs.ts
198
+ var import_node_crypto = __toESM(require("crypto"), 1);
199
+ var import_promises = __toESM(require("fs/promises"), 1);
200
+ var import_node_path = __toESM(require("path"), 1);
201
+ async function fileExists(targetPath) {
202
+ try {
203
+ await import_promises.default.access(targetPath);
204
+ return true;
205
+ } catch {
206
+ return false;
207
+ }
208
+ }
209
+ async function isDirectory(targetPath) {
210
+ try {
211
+ const stat = await import_promises.default.stat(targetPath);
212
+ return stat.isDirectory();
213
+ } catch {
214
+ return false;
215
+ }
216
+ }
217
+ async function isFile(targetPath) {
218
+ try {
219
+ const stat = await import_promises.default.stat(targetPath);
220
+ return stat.isFile();
221
+ } catch {
222
+ return false;
223
+ }
224
+ }
225
+ async function atomicWriteFile(filePath, data) {
226
+ const dir = import_node_path.default.dirname(filePath);
227
+ await import_promises.default.mkdir(dir, { recursive: true });
228
+ const tempPath = import_node_path.default.join(
229
+ dir,
230
+ `.tmp-${import_node_path.default.basename(filePath)}-${process.pid}-${import_node_crypto.default.randomUUID()}`
231
+ );
232
+ try {
233
+ await import_promises.default.writeFile(tempPath, data);
234
+ await import_promises.default.rename(tempPath, filePath);
235
+ } catch (err) {
236
+ await import_promises.default.rm(tempPath, { force: true }).catch(() => {
237
+ });
238
+ throw err;
239
+ }
240
+ }
241
+ async function atomicCopyFile(srcPath, destPath) {
242
+ const dir = import_node_path.default.dirname(destPath);
243
+ await import_promises.default.mkdir(dir, { recursive: true });
244
+ const tempPath = import_node_path.default.join(
245
+ dir,
246
+ `.tmp-${import_node_path.default.basename(destPath)}-${process.pid}-${import_node_crypto.default.randomUUID()}`
247
+ );
248
+ try {
249
+ await import_promises.default.copyFile(srcPath, tempPath);
250
+ await import_promises.default.rename(tempPath, destPath);
251
+ } catch (err) {
252
+ await import_promises.default.rm(tempPath, { force: true }).catch(() => {
253
+ });
254
+ throw err;
255
+ }
256
+ }
257
+ async function writeJsonAtomic(filePath, value) {
258
+ await atomicWriteFile(filePath, `${JSON.stringify(value, null, 2)}
259
+ `);
260
+ }
261
+ async function readJsonFile(filePath) {
262
+ const raw = await import_promises.default.readFile(filePath, "utf8");
263
+ return JSON.parse(raw);
264
+ }
265
+
266
+ // src/utils/path.ts
267
+ var import_node_os = __toESM(require("os"), 1);
268
+ var import_node_path2 = __toESM(require("path"), 1);
269
+ function toPosixPath(inputPath) {
270
+ return inputPath.split(import_node_path2.default.sep).join("/");
271
+ }
272
+ function normalizeRelativePosix(rootDir, targetPath) {
273
+ const resolvedRoot = import_node_path2.default.resolve(rootDir);
274
+ const resolvedTarget = import_node_path2.default.resolve(rootDir, targetPath);
275
+ const rel = import_node_path2.default.relative(resolvedRoot, resolvedTarget);
276
+ if (rel === ".." || rel.startsWith(`..${import_node_path2.default.sep}`) || import_node_path2.default.isAbsolute(rel)) {
277
+ throw new Error(
278
+ `Path "${targetPath}" escapes project root "${resolvedRoot}"`
279
+ );
280
+ }
281
+ return toPosixPath(rel);
282
+ }
283
+ function resolveInsideRoot(rootDir, relPath) {
284
+ const resolvedRoot = import_node_path2.default.resolve(rootDir);
285
+ const resolvedTarget = import_node_path2.default.resolve(resolvedRoot, relPath);
286
+ const rel = import_node_path2.default.relative(resolvedRoot, resolvedTarget);
287
+ if (rel === ".." || rel.startsWith(`..${import_node_path2.default.sep}`) || import_node_path2.default.isAbsolute(rel)) {
288
+ throw new Error(
289
+ `Path "${relPath}" escapes project root "${resolvedRoot}"`
290
+ );
291
+ }
292
+ return resolvedTarget;
293
+ }
294
+ function expandHome(inputPath) {
295
+ if (inputPath === "~") {
296
+ return import_node_os.default.homedir();
297
+ }
298
+ if (inputPath.startsWith("~/") || inputPath.startsWith("~\\")) {
299
+ return import_node_path2.default.join(import_node_os.default.homedir(), inputPath.slice(2));
300
+ }
301
+ return inputPath;
302
+ }
303
+ function getDefaultCliCacheDir() {
304
+ if (process.env.IMGOPT_CACHE_DIR) {
305
+ return import_node_path2.default.resolve(expandHome(process.env.IMGOPT_CACHE_DIR));
306
+ }
307
+ if (process.env.XDG_CACHE_HOME) {
308
+ return import_node_path2.default.join(expandHome(process.env.XDG_CACHE_HOME), "imgopt-node", "bin");
309
+ }
310
+ if (process.platform === "win32" && process.env.LOCALAPPDATA) {
311
+ return import_node_path2.default.join(process.env.LOCALAPPDATA, "imgopt-node", "Cache", "bin");
312
+ }
313
+ return import_node_path2.default.join(import_node_os.default.homedir(), ".cache", "imgopt-node", "bin");
314
+ }
315
+
316
+ // src/config/loader.ts
317
+ var VALID_PRESETS = /* @__PURE__ */ new Set(["balanced", "maximum", "aggressive"]);
318
+ var VALID_FORMATS = /* @__PURE__ */ new Set([
319
+ "preserve",
320
+ "webp",
321
+ "avif",
322
+ "auto",
323
+ "jpeg",
324
+ "png",
325
+ "gif",
326
+ "force-webp",
327
+ "force-avif"
328
+ ]);
329
+ var VALID_RESIZE_MODES = /* @__PURE__ */ new Set([
330
+ "scale-down",
331
+ "contain",
332
+ "cover",
333
+ "exact"
334
+ ]);
335
+ var VALID_BACKUP_STRATEGIES = /* @__PURE__ */ new Set([
336
+ "preserve-first",
337
+ "keep-initial"
338
+ ]);
339
+ async function findConfigPath(projectRoot, explicitPath) {
340
+ if (explicitPath) {
341
+ const resolved = import_node_path3.default.resolve(projectRoot, explicitPath);
342
+ if (!await fileExists(resolved)) {
343
+ throw new Error(`Configuration file not found: ${resolved}`);
344
+ }
345
+ return resolved;
346
+ }
347
+ for (const candidate of CONFIG_FILENAMES) {
348
+ const resolved = import_node_path3.default.join(projectRoot, candidate);
349
+ if (await fileExists(resolved)) {
350
+ return resolved;
351
+ }
352
+ }
353
+ throw new Error(
354
+ `No configuration file found in ${projectRoot} (expected ${DEFAULT_CONFIG_FILENAME}). Run "imgopt-node init" first.`
355
+ );
356
+ }
357
+ function validateOptimizationFields(opt, label) {
358
+ if (opt.preset !== void 0 && !VALID_PRESETS.has(opt.preset)) {
359
+ throw new Error(
360
+ `Invalid ${label}.preset "${String(opt.preset)}"; expected balanced | maximum | aggressive`
361
+ );
362
+ }
363
+ if (opt.quality !== void 0 && (typeof opt.quality !== "number" || !Number.isFinite(opt.quality) || opt.quality < 0 || opt.quality > 1)) {
364
+ throw new Error(
365
+ `Invalid ${label}.quality "${String(opt.quality)}"; expected a number between 0.0 and 1.0`
366
+ );
367
+ }
368
+ if (opt.effort !== void 0 && (typeof opt.effort !== "number" || !Number.isInteger(opt.effort) || opt.effort < 1 || opt.effort > 6)) {
369
+ throw new Error(
370
+ `Invalid ${label}.effort "${String(opt.effort)}"; expected an integer between 1 and 6`
371
+ );
372
+ }
373
+ if (opt.format !== void 0 && !VALID_FORMATS.has(opt.format)) {
374
+ throw new Error(
375
+ `Invalid ${label}.format "${String(opt.format)}"; unsupported format policy`
376
+ );
377
+ }
378
+ if (opt.resize !== void 0) {
379
+ const { maxWidth, maxHeight, mode } = opt.resize;
380
+ if (maxWidth !== void 0 && (!Number.isInteger(maxWidth) || maxWidth <= 0)) {
381
+ throw new Error(
382
+ `Invalid ${label}.resize.maxWidth "${String(maxWidth)}"; expected positive integer`
383
+ );
384
+ }
385
+ if (maxHeight !== void 0 && (!Number.isInteger(maxHeight) || maxHeight <= 0)) {
386
+ throw new Error(
387
+ `Invalid ${label}.resize.maxHeight "${String(maxHeight)}"; expected positive integer`
388
+ );
389
+ }
390
+ if (mode !== void 0 && !VALID_RESIZE_MODES.has(mode)) {
391
+ throw new Error(
392
+ `Invalid ${label}.resize.mode "${String(mode)}"; expected scale-down | contain | cover | exact`
393
+ );
394
+ }
395
+ }
396
+ if (opt.minBytes !== void 0 && (typeof opt.minBytes !== "number" || opt.minBytes < 0)) {
397
+ throw new Error(
398
+ `Invalid ${label}.minBytes "${String(opt.minBytes)}"; expected >= 0`
399
+ );
400
+ }
401
+ if (opt.minSavingsPercent !== void 0 && (typeof opt.minSavingsPercent !== "number" || opt.minSavingsPercent < 0 || opt.minSavingsPercent > 100)) {
402
+ throw new Error(
403
+ `Invalid ${label}.minSavingsPercent "${String(opt.minSavingsPercent)}"; expected 0..100`
404
+ );
405
+ }
406
+ }
407
+ function normalizeConfig(raw, projectRoot) {
408
+ if (!raw || typeof raw !== "object") {
409
+ throw new Error("Configuration must be a JSON object");
410
+ }
411
+ if (raw.version !== void 0 && raw.version !== 1) {
412
+ throw new Error(`Unsupported configuration version: ${String(raw.version)}`);
413
+ }
414
+ if (!Array.isArray(raw.targets) || raw.targets.length === 0) {
415
+ throw new Error(
416
+ 'Configuration must include at least one directory in "targets"'
417
+ );
418
+ }
419
+ const normalizedTargets = raw.targets.map((target, index) => {
420
+ if (!target || typeof target.dir !== "string" || !target.dir.trim()) {
421
+ throw new Error(`targets[${index}].dir must be a non-empty string`);
422
+ }
423
+ const relDir = normalizeRelativePosix(projectRoot, target.dir.trim());
424
+ return {
425
+ dir: relDir || ".",
426
+ include: Array.isArray(target.include) && target.include.length > 0 ? target.include : [...DEFAULT_INCLUDE_GLOBS],
427
+ exclude: Array.isArray(target.exclude) ? target.exclude : [...DEFAULT_EXCLUDE_GLOBS]
428
+ };
429
+ });
430
+ const backupRaw = raw.backup ?? {};
431
+ const backupDirRaw = backupRaw.dir !== void 0 ? backupRaw.dir.trim() : DEFAULT_BACKUP_CONFIG.dir;
432
+ if (!backupDirRaw) {
433
+ throw new Error("backup.dir must not be empty");
434
+ }
435
+ const normalizedBackupDir = normalizeRelativePosix(projectRoot, backupDirRaw);
436
+ if (!normalizedBackupDir || normalizedBackupDir === ".") {
437
+ throw new Error("backup.dir must not be the project root directory");
438
+ }
439
+ const backupStrategy = backupRaw.strategy ?? DEFAULT_BACKUP_CONFIG.strategy;
440
+ if (!VALID_BACKUP_STRATEGIES.has(backupStrategy)) {
441
+ throw new Error(
442
+ `Invalid backup.strategy "${String(backupStrategy)}"; expected preserve-first | keep-initial`
443
+ );
444
+ }
445
+ const manifestRaw = raw.manifest !== void 0 ? raw.manifest.trim() : DEFAULT_MANIFEST_PATH;
446
+ if (!manifestRaw) {
447
+ throw new Error("manifest path must not be empty");
448
+ }
449
+ const normalizedManifest = normalizeRelativePosix(projectRoot, manifestRaw);
450
+ const userOpt = raw.optimization;
451
+ if (userOpt) {
452
+ validateOptimizationFields(userOpt, "optimization");
453
+ }
454
+ let optimization;
455
+ if (!userOpt) {
456
+ optimization = { ...DEFAULT_OPTIMIZATION_OPTIONS };
457
+ } else {
458
+ optimization = {
459
+ preset: userOpt.preset ?? DEFAULT_OPTIMIZATION_OPTIONS.preset,
460
+ quality: userOpt.quality !== void 0 ? userOpt.quality : userOpt.preset && userOpt.preset !== "balanced" ? void 0 : DEFAULT_OPTIMIZATION_OPTIONS.quality,
461
+ effort: userOpt.effort !== void 0 ? userOpt.effort : userOpt.preset && userOpt.preset !== "balanced" ? void 0 : DEFAULT_OPTIMIZATION_OPTIONS.effort,
462
+ format: userOpt.format ?? DEFAULT_OPTIMIZATION_OPTIONS.format,
463
+ preserveMetadata: userOpt.preserveMetadata ?? DEFAULT_OPTIMIZATION_OPTIONS.preserveMetadata,
464
+ preserveIcc: userOpt.preserveIcc ?? DEFAULT_OPTIMIZATION_OPTIONS.preserveIcc,
465
+ convertToSrgb: userOpt.convertToSrgb ?? DEFAULT_OPTIMIZATION_OPTIONS.convertToSrgb,
466
+ resize: userOpt.resize ? {
467
+ maxWidth: userOpt.resize.maxWidth,
468
+ maxHeight: userOpt.resize.maxHeight,
469
+ mode: userOpt.resize.mode ?? "scale-down"
470
+ } : void 0,
471
+ concurrency: userOpt.concurrency,
472
+ minBytes: userOpt.minBytes ?? DEFAULT_OPTIMIZATION_OPTIONS.minBytes,
473
+ minSavingsPercent: userOpt.minSavingsPercent ?? DEFAULT_OPTIMIZATION_OPTIONS.minSavingsPercent,
474
+ removeSourceOnFormatChange: userOpt.removeSourceOnFormatChange ?? DEFAULT_OPTIMIZATION_OPTIONS.removeSourceOnFormatChange
475
+ };
476
+ }
477
+ const rules = Array.isArray(raw.rules) ? raw.rules.map((rule, idx) => {
478
+ if (!rule || typeof rule.match !== "string" && !Array.isArray(rule.match) || !rule.optimization) {
479
+ throw new Error(`rules[${idx}] must define "match" and "optimization"`);
480
+ }
481
+ validateOptimizationFields(rule.optimization, `rules[${idx}].optimization`);
482
+ return rule;
483
+ }) : [];
484
+ return {
485
+ $schema: raw.$schema,
486
+ version: 1,
487
+ cli: {
488
+ ...DEFAULT_CLI_CONFIG,
489
+ ...raw.cli ?? {}
490
+ },
491
+ targets: normalizedTargets,
492
+ backup: {
493
+ enabled: backupRaw.enabled ?? DEFAULT_BACKUP_CONFIG.enabled,
494
+ dir: normalizedBackupDir,
495
+ strategy: backupStrategy
496
+ },
497
+ manifest: normalizedManifest,
498
+ optimization,
499
+ rules,
500
+ budgets: raw.budgets
501
+ };
502
+ }
503
+ async function loadConfig(projectRoot = process.cwd(), explicitConfigPath) {
504
+ const resolvedRoot = import_node_path3.default.resolve(projectRoot);
505
+ const configPath = await findConfigPath(resolvedRoot, explicitConfigPath);
506
+ const raw = await readJsonFile(configPath);
507
+ const config = normalizeConfig(raw, resolvedRoot);
508
+ return {
509
+ configPath,
510
+ projectRoot: resolvedRoot,
511
+ config
512
+ };
513
+ }
514
+ async function saveConfig(configPath, config) {
515
+ await writeJsonAtomic(configPath, config);
516
+ }
517
+ function resolveEffectiveOptimization(config, relPosixPath) {
518
+ const normalizedPath = toPosixPath(relPosixPath).replace(/^\.\//, "");
519
+ let effective = {
520
+ ...config.optimization,
521
+ resize: config.optimization.resize ? { ...config.optimization.resize } : void 0
522
+ };
523
+ for (const rule of config.rules) {
524
+ const patterns = Array.isArray(rule.match) ? rule.match : [rule.match];
525
+ const isMatch = import_picomatch.default.isMatch(normalizedPath, patterns, {
526
+ dot: true,
527
+ nocase: true
528
+ });
529
+ if (!isMatch) continue;
530
+ const patch = rule.optimization;
531
+ const presetChanged = patch.preset !== void 0 && patch.preset !== effective.preset;
532
+ effective = {
533
+ ...effective,
534
+ ...patch,
535
+ quality: patch.quality !== void 0 ? patch.quality : presetChanged ? void 0 : effective.quality,
536
+ effort: patch.effort !== void 0 ? patch.effort : presetChanged ? void 0 : effective.effort,
537
+ resize: patch.resize ? {
538
+ ...effective.resize ?? {},
539
+ ...patch.resize,
540
+ mode: patch.resize.mode ?? effective.resize?.mode ?? "scale-down"
541
+ } : effective.resize
542
+ };
543
+ }
544
+ return effective;
545
+ }
546
+ function computeOptimizationConfigHash(opt) {
547
+ const canonical = {
548
+ preset: opt.preset,
549
+ quality: opt.quality ?? null,
550
+ effort: opt.effort ?? null,
551
+ format: opt.format,
552
+ preserveMetadata: opt.preserveMetadata,
553
+ preserveIcc: opt.preserveIcc,
554
+ convertToSrgb: opt.convertToSrgb,
555
+ resize: opt.resize ? {
556
+ maxWidth: opt.resize.maxWidth ?? null,
557
+ maxHeight: opt.resize.maxHeight ?? null,
558
+ mode: opt.resize.mode ?? "scale-down"
559
+ } : null,
560
+ minBytes: opt.minBytes,
561
+ minSavingsPercent: opt.minSavingsPercent,
562
+ removeSourceOnFormatChange: opt.removeSourceOnFormatChange
563
+ };
564
+ return import_node_crypto2.default.createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
565
+ }
566
+
567
+ // src/config/detector.ts
568
+ var import_promises2 = __toESM(require("fs/promises"), 1);
569
+ var import_node_path4 = __toESM(require("path"), 1);
570
+ async function countImagesInDir(dirPath, maxDepth = 6) {
571
+ let count = 0;
572
+ async function walk(current, depth) {
573
+ if (depth > maxDepth) return;
574
+ let entries;
575
+ try {
576
+ entries = await import_promises2.default.readdir(current, { withFileTypes: true });
577
+ } catch {
578
+ return;
579
+ }
580
+ for (const entry of entries) {
581
+ if (entry.name.startsWith(".") || IGNORED_DIR_NAMES.has(entry.name)) {
582
+ continue;
583
+ }
584
+ const fullPath = import_node_path4.default.join(current, entry.name);
585
+ if (entry.isDirectory()) {
586
+ await walk(fullPath, depth + 1);
587
+ } else if (entry.isFile()) {
588
+ const ext = import_node_path4.default.extname(entry.name).toLowerCase();
589
+ if (SUPPORTED_IMAGE_EXTENSIONS.has(ext)) {
590
+ count += 1;
591
+ }
592
+ }
593
+ }
594
+ }
595
+ await walk(dirPath, 0);
596
+ return count;
597
+ }
598
+ async function detectStacks(projectRoot) {
599
+ const stacks = /* @__PURE__ */ new Set();
600
+ let isMonorepo = false;
601
+ const workspaceRoots = [];
602
+ const pkgPath = import_node_path4.default.join(projectRoot, "package.json");
603
+ if (await fileExists(pkgPath)) {
604
+ try {
605
+ const pkg = await readJsonFile(pkgPath);
606
+ const deps = {
607
+ ...pkg.dependencies ?? {},
608
+ ...pkg.devDependencies ?? {}
609
+ };
610
+ if ("next" in deps) stacks.add("next");
611
+ if ("nuxt" in deps) stacks.add("nuxt");
612
+ if ("vite" in deps) stacks.add("vite");
613
+ if ("astro" in deps) stacks.add("astro");
614
+ if ("vitepress" in deps) stacks.add("vitepress");
615
+ if ("@docusaurus/core" in deps) stacks.add("docusaurus");
616
+ if ("@remix-run/react" in deps || "react-router" in deps) stacks.add("remix");
617
+ if ("svelte" in deps || "@sveltejs/kit" in deps) stacks.add("svelte");
618
+ if ("vue" in deps) stacks.add("vue");
619
+ if ("react" in deps) stacks.add("react");
620
+ if ("react-native" in deps || "expo" in deps) stacks.add("react-native");
621
+ if ("electron" in deps) stacks.add("electron");
622
+ if ("@tauri-apps/api" in deps) stacks.add("tauri");
623
+ if (pkg.workspaces) {
624
+ isMonorepo = true;
625
+ const patterns = Array.isArray(pkg.workspaces) ? pkg.workspaces : pkg.workspaces.packages ?? [];
626
+ for (const p of patterns) {
627
+ if (typeof p === "string") workspaceRoots.push(p);
628
+ }
629
+ }
630
+ } catch {
631
+ }
632
+ }
633
+ if (await fileExists(import_node_path4.default.join(projectRoot, "pnpm-workspace.yaml"))) {
634
+ isMonorepo = true;
635
+ workspaceRoots.push("apps/*", "packages/*");
636
+ }
637
+ if (await fileExists(import_node_path4.default.join(projectRoot, "pubspec.yaml"))) {
638
+ stacks.add("flutter");
639
+ }
640
+ if (await fileExists(import_node_path4.default.join(projectRoot, "docs")) || await fileExists(import_node_path4.default.join(projectRoot, "mkdocs.yml"))) {
641
+ stacks.add("docs");
642
+ }
643
+ if (stacks.size === 0) {
644
+ stacks.add("general");
645
+ }
646
+ return {
647
+ stacks: [...stacks],
648
+ isMonorepo,
649
+ workspaceRoots
650
+ };
651
+ }
652
+ async function expandWorkspaceParents(projectRoot, patterns) {
653
+ const bases = /* @__PURE__ */ new Set();
654
+ const defaultGlobs = patterns.length > 0 ? patterns : ["apps/*", "packages/*"];
655
+ for (const rawPattern of defaultGlobs) {
656
+ const clean = rawPattern.replace(/\/\*+$/, "").replace(/^\.\//, "");
657
+ if (!clean || clean.includes("*") || clean.startsWith("!")) continue;
658
+ const baseAbs = import_node_path4.default.join(projectRoot, clean);
659
+ if (!await isDirectory(baseAbs)) continue;
660
+ try {
661
+ const entries = await import_promises2.default.readdir(baseAbs, { withFileTypes: true });
662
+ for (const entry of entries) {
663
+ if (entry.isDirectory() && !entry.name.startsWith(".")) {
664
+ bases.add(toPosixPath(import_node_path4.default.join(clean, entry.name)));
665
+ }
666
+ }
667
+ } catch {
668
+ }
669
+ }
670
+ return [...bases].sort();
671
+ }
672
+ function isNestedUnder(child, parent) {
673
+ if (child === parent) return true;
674
+ if (parent === ".") return true;
675
+ return child.startsWith(`${parent}/`);
676
+ }
677
+ async function detectProject(projectRoot = process.cwd(), customDirs = []) {
678
+ const resolvedRoot = import_node_path4.default.resolve(projectRoot);
679
+ const { stacks, isMonorepo, workspaceRoots } = await detectStacks(resolvedRoot);
680
+ const discovered = /* @__PURE__ */ new Map();
681
+ for (const rawDir of customDirs) {
682
+ const clean = toPosixPath(rawDir.trim()).replace(/^\.\//, "").replace(/\/+$/, "");
683
+ if (!clean) continue;
684
+ const abs = import_node_path4.default.join(resolvedRoot, clean);
685
+ const exists = await isDirectory(abs);
686
+ const imageCount = exists ? await countImagesInDir(abs) : 0;
687
+ discovered.set(clean, {
688
+ dir: clean,
689
+ imageCount,
690
+ source: "custom"
691
+ });
692
+ }
693
+ for (const candidate of CANDIDATE_ASSET_DIRS) {
694
+ const abs = import_node_path4.default.join(resolvedRoot, candidate.dir);
695
+ if (!await isDirectory(abs)) continue;
696
+ const imageCount = await countImagesInDir(abs);
697
+ if (imageCount === 0 && customDirs.length === 0) {
698
+ const isPrimaryRoot = candidate.dir === "src/assets" || candidate.dir === "public" || candidate.dir === "assets" || candidate.dir === "static";
699
+ if (!isPrimaryRoot) continue;
700
+ }
701
+ if (!discovered.has(candidate.dir)) {
702
+ discovered.set(candidate.dir, {
703
+ dir: candidate.dir,
704
+ imageCount,
705
+ source: "standard"
706
+ });
707
+ }
708
+ }
709
+ if (isMonorepo) {
710
+ const wsDirs = await expandWorkspaceParents(resolvedRoot, workspaceRoots);
711
+ const subCandidates = ["src/assets", "public", "static", "assets"];
712
+ for (const ws of wsDirs) {
713
+ for (const sub of subCandidates) {
714
+ const rel = `${ws}/${sub}`;
715
+ const abs = import_node_path4.default.join(resolvedRoot, rel);
716
+ if (!await isDirectory(abs)) continue;
717
+ const imageCount = await countImagesInDir(abs);
718
+ if (imageCount > 0 && !discovered.has(rel)) {
719
+ discovered.set(rel, {
720
+ dir: rel,
721
+ imageCount,
722
+ source: "monorepo"
723
+ });
724
+ }
725
+ }
726
+ }
727
+ }
728
+ const sortedAll = [...discovered.values()].sort(
729
+ (a, b) => a.dir.localeCompare(b.dir)
730
+ );
731
+ const deduplicated = [];
732
+ for (const item of sortedAll) {
733
+ const shadowedByParent = deduplicated.some(
734
+ (parent) => item.source !== "custom" && isNestedUnder(item.dir, parent.dir)
735
+ );
736
+ if (!shadowedByParent) {
737
+ deduplicated.push(item);
738
+ }
739
+ }
740
+ const suggestedTargets = deduplicated.length > 0 ? deduplicated.map((d) => ({
741
+ dir: d.dir,
742
+ include: [...DEFAULT_INCLUDE_GLOBS],
743
+ exclude: [...DEFAULT_EXCLUDE_GLOBS]
744
+ })) : [
745
+ {
746
+ dir: "assets",
747
+ include: [...DEFAULT_INCLUDE_GLOBS],
748
+ exclude: [...DEFAULT_EXCLUDE_GLOBS]
749
+ }
750
+ ];
751
+ return {
752
+ projectRoot: resolvedRoot,
753
+ stacks,
754
+ isMonorepo,
755
+ detectedDirs: deduplicated,
756
+ suggestedTargets
757
+ };
758
+ }
759
+
760
+ // src/cli-manager/downloader.ts
761
+ var import_node_child_process = require("child_process");
762
+ var import_node_crypto3 = __toESM(require("crypto"), 1);
763
+ var import_promises3 = __toESM(require("fs/promises"), 1);
764
+ var import_node_path5 = __toESM(require("path"), 1);
765
+ var import_node_util = require("util");
766
+ var import_adm_zip = __toESM(require("adm-zip"), 1);
767
+ var tar = __toESM(require("tar"), 1);
768
+
769
+ // src/utils/http.ts
770
+ var import_node_http = __toESM(require("http"), 1);
771
+ var import_node_https = __toESM(require("https"), 1);
772
+ var import_node_tls = __toESM(require("tls"), 1);
773
+ function isHttpProxyUrl(val) {
774
+ if (!val) return void 0;
775
+ return /^https?:\/\//i.test(val.trim()) ? val.trim() : void 0;
776
+ }
777
+ function isBypassedByNoProxy(hostname) {
778
+ const lower = hostname.toLowerCase();
779
+ if (lower === "127.0.0.1" || lower === "localhost" || lower === "::1" || lower === "[::1]") {
780
+ return true;
781
+ }
782
+ const noProxyRaw = process.env.NO_PROXY || process.env.no_proxy;
783
+ if (!noProxyRaw) return false;
784
+ const entries = noProxyRaw.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
785
+ for (const entry of entries) {
786
+ if (entry === "*") return true;
787
+ const clean = entry.replace(/^\./, "");
788
+ if (lower === clean || lower.endsWith(`.${clean}`)) {
789
+ return true;
790
+ }
791
+ }
792
+ return false;
793
+ }
794
+ function resolveProxyUrl(targetUrl) {
795
+ if (isBypassedByNoProxy(targetUrl.hostname)) {
796
+ return null;
797
+ }
798
+ const allProxy = isHttpProxyUrl(process.env.ALL_PROXY || process.env.all_proxy);
799
+ const raw = targetUrl.protocol === "https:" ? isHttpProxyUrl(process.env.HTTPS_PROXY || process.env.https_proxy) || allProxy : isHttpProxyUrl(process.env.HTTP_PROXY || process.env.http_proxy) || allProxy;
800
+ if (!raw) return null;
801
+ try {
802
+ return new URL(raw);
803
+ } catch {
804
+ return null;
805
+ }
806
+ }
807
+ function buildProxyAuthHeader(proxyUrl) {
808
+ if (!proxyUrl.username && !proxyUrl.password) return void 0;
809
+ const creds = `${decodeURIComponent(proxyUrl.username)}:${decodeURIComponent(proxyUrl.password)}`;
810
+ return `Basic ${Buffer.from(creds).toString("base64")}`;
811
+ }
812
+ function makeResponse(status, rawHeaders, body) {
813
+ return {
814
+ ok: status >= 200 && status < 300,
815
+ status,
816
+ headers: {
817
+ get(name) {
818
+ const val = rawHeaders[name.toLowerCase()];
819
+ if (val === void 0) return null;
820
+ return Array.isArray(val) ? val.join(", ") : val;
821
+ }
822
+ },
823
+ async arrayBuffer() {
824
+ return body.buffer.slice(
825
+ body.byteOffset,
826
+ body.byteOffset + body.byteLength
827
+ );
828
+ },
829
+ async json() {
830
+ return JSON.parse(body.toString("utf8"));
831
+ }
832
+ };
833
+ }
834
+ function singleRequest(targetUrl, method, headers) {
835
+ return new Promise((resolve, reject) => {
836
+ const proxyUrl = resolveProxyUrl(targetUrl);
837
+ const isHttps = targetUrl.protocol === "https:";
838
+ const targetPort = Number(targetUrl.port) || (isHttps ? 443 : 80);
839
+ const handleIncoming = (res) => {
840
+ const chunks = [];
841
+ res.on("data", (chunk) => chunks.push(chunk));
842
+ res.on("error", reject);
843
+ res.on("end", () => {
844
+ resolve(
845
+ makeResponse(
846
+ res.statusCode ?? 0,
847
+ res.headers,
848
+ Buffer.concat(chunks)
849
+ )
850
+ );
851
+ });
852
+ };
853
+ if (!proxyUrl) {
854
+ const transport = isHttps ? import_node_https.default : import_node_http.default;
855
+ const req = transport.request(
856
+ targetUrl,
857
+ { method, headers },
858
+ handleIncoming
859
+ );
860
+ req.setTimeout(3e4, () => {
861
+ req.destroy(new Error(`Request timed out: ${targetUrl.href}`));
862
+ });
863
+ req.on("error", reject);
864
+ req.end();
865
+ return;
866
+ }
867
+ const proxyPort = Number(proxyUrl.port) || (proxyUrl.protocol === "https:" ? 443 : 80);
868
+ const proxyAuth = buildProxyAuthHeader(proxyUrl);
869
+ if (!isHttps) {
870
+ const proxyHeaders = {
871
+ ...headers,
872
+ Host: targetUrl.host
873
+ };
874
+ if (proxyAuth) {
875
+ proxyHeaders["Proxy-Authorization"] = proxyAuth;
876
+ }
877
+ const proxyTransport2 = proxyUrl.protocol === "https:" ? import_node_https.default : import_node_http.default;
878
+ const req = proxyTransport2.request(
879
+ {
880
+ hostname: proxyUrl.hostname,
881
+ port: proxyPort,
882
+ method,
883
+ path: targetUrl.href,
884
+ headers: proxyHeaders
885
+ },
886
+ handleIncoming
887
+ );
888
+ req.setTimeout(3e4, () => {
889
+ req.destroy(new Error(`Proxy request timed out: ${targetUrl.href}`));
890
+ });
891
+ req.on("error", reject);
892
+ req.end();
893
+ return;
894
+ }
895
+ const connectHeaders = {
896
+ Host: `${targetUrl.hostname}:${targetPort}`
897
+ };
898
+ if (proxyAuth) {
899
+ connectHeaders["Proxy-Authorization"] = proxyAuth;
900
+ }
901
+ const proxyTransport = proxyUrl.protocol === "https:" ? import_node_https.default : import_node_http.default;
902
+ const connectReq = proxyTransport.request({
903
+ hostname: proxyUrl.hostname,
904
+ port: proxyPort,
905
+ method: "CONNECT",
906
+ path: `${targetUrl.hostname}:${targetPort}`,
907
+ headers: connectHeaders
908
+ });
909
+ connectReq.setTimeout(3e4, () => {
910
+ connectReq.destroy(
911
+ new Error(`Proxy CONNECT timed out for ${targetUrl.host}`)
912
+ );
913
+ });
914
+ connectReq.on("error", reject);
915
+ connectReq.on("connect", (connectRes, socket) => {
916
+ if (connectRes.statusCode !== 200) {
917
+ socket.destroy();
918
+ reject(
919
+ new Error(
920
+ `Proxy CONNECT failed with HTTP ${connectRes.statusCode ?? 0} for ${targetUrl.host}`
921
+ )
922
+ );
923
+ return;
924
+ }
925
+ const tlsSocket = import_node_tls.default.connect({
926
+ socket,
927
+ servername: targetUrl.hostname
928
+ });
929
+ const req = import_node_https.default.request(
930
+ {
931
+ hostname: targetUrl.hostname,
932
+ port: targetPort,
933
+ path: `${targetUrl.pathname}${targetUrl.search}`,
934
+ method,
935
+ headers,
936
+ agent: false,
937
+ createConnection: () => tlsSocket
938
+ },
939
+ handleIncoming
940
+ );
941
+ req.setTimeout(3e4, () => {
942
+ req.destroy(new Error(`Request timed out: ${targetUrl.href}`));
943
+ });
944
+ req.on("error", reject);
945
+ req.end();
946
+ });
947
+ connectReq.end();
948
+ });
949
+ }
950
+ async function proxyFetch(url, init = {}) {
951
+ const method = (init.method ?? "GET").toUpperCase();
952
+ const redirectMode = init.redirect ?? "follow";
953
+ const maxRedirects = init.maxRedirects ?? 10;
954
+ let currentUrl = new URL(url);
955
+ let currentHeaders = { ...init.headers ?? {} };
956
+ for (let hop = 0; hop <= maxRedirects; hop += 1) {
957
+ const res = await singleRequest(currentUrl, method, currentHeaders);
958
+ const isRedirect = res.status === 301 || res.status === 302 || res.status === 303 || res.status === 307 || res.status === 308;
959
+ if (!isRedirect || redirectMode === "manual") {
960
+ return res;
961
+ }
962
+ const location = res.headers.get("location");
963
+ if (!location) {
964
+ return res;
965
+ }
966
+ const nextUrl = new URL(location, currentUrl);
967
+ if (nextUrl.origin !== currentUrl.origin) {
968
+ delete currentHeaders.Authorization;
969
+ delete currentHeaders.authorization;
970
+ }
971
+ currentUrl = nextUrl;
972
+ }
973
+ throw new Error(`Exceeded maximum redirects (${maxRedirects}) for ${url}`);
974
+ }
975
+
976
+ // src/cli-manager/platform.ts
977
+ function resolveReleaseAsset(platform = process.platform, arch = process.arch) {
978
+ if (platform === "linux" && arch === "x64") {
979
+ return {
980
+ platformKey: "linux-x86_64",
981
+ assetName: "imgopt-linux-x86_64.tar.gz",
982
+ checksumAssetName: "imgopt-linux-x86_64.tar.gz.sha256",
983
+ archiveType: "tar.gz",
984
+ binaryName: "imgopt"
985
+ };
986
+ }
987
+ if (platform === "linux" && arch === "arm64") {
988
+ return {
989
+ platformKey: "linux-aarch64",
990
+ assetName: "imgopt-linux-aarch64.tar.gz",
991
+ checksumAssetName: "imgopt-linux-aarch64.tar.gz.sha256",
992
+ archiveType: "tar.gz",
993
+ binaryName: "imgopt"
994
+ };
995
+ }
996
+ if (platform === "darwin" && arch === "x64") {
997
+ return {
998
+ platformKey: "macos-x86_64",
999
+ assetName: "imgopt-macos-x86_64.tar.gz",
1000
+ checksumAssetName: "imgopt-macos-x86_64.tar.gz.sha256",
1001
+ archiveType: "tar.gz",
1002
+ binaryName: "imgopt"
1003
+ };
1004
+ }
1005
+ if (platform === "darwin" && arch === "arm64") {
1006
+ return {
1007
+ platformKey: "macos-aarch64",
1008
+ assetName: "imgopt-macos-aarch64.tar.gz",
1009
+ checksumAssetName: "imgopt-macos-aarch64.tar.gz.sha256",
1010
+ archiveType: "tar.gz",
1011
+ binaryName: "imgopt"
1012
+ };
1013
+ }
1014
+ if (platform === "win32" && arch === "x64") {
1015
+ return {
1016
+ platformKey: "windows-x86_64",
1017
+ assetName: "imgopt-windows-x86_64.zip",
1018
+ checksumAssetName: "imgopt-windows-x86_64.zip.sha256",
1019
+ archiveType: "zip",
1020
+ binaryName: "imgopt.exe"
1021
+ };
1022
+ }
1023
+ throw new Error(
1024
+ `Unsupported platform/arch "${platform}/${arch}" for prebuilt imgopt binaries. Set IMGOPT_BIN to a locally compiled imgopt binary.`
1025
+ );
1026
+ }
1027
+
1028
+ // src/cli-manager/downloader.ts
1029
+ var execFileAsync = (0, import_node_util.promisify)(import_node_child_process.execFile);
1030
+ function getAuthHeaders() {
1031
+ const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
1032
+ const headers = {
1033
+ "User-Agent": "image-optimizer-node",
1034
+ Accept: "application/vnd.github+json"
1035
+ };
1036
+ if (token) {
1037
+ headers.Authorization = `Bearer ${token}`;
1038
+ }
1039
+ return headers;
1040
+ }
1041
+ function resolveCacheDir(cliConfig) {
1042
+ if (cliConfig?.cacheDir) {
1043
+ return import_node_path5.default.resolve(expandHome(cliConfig.cacheDir));
1044
+ }
1045
+ return getDefaultCliCacheDir();
1046
+ }
1047
+ async function probeBinaryVersion(binPath) {
1048
+ const { stdout, stderr } = await execFileAsync(binPath, ["--version"], {
1049
+ timeout: 1e4
1050
+ });
1051
+ const text = `${stdout}
1052
+ ${stderr}`.trim();
1053
+ const match = text.match(/(\d+\.\d+\.\d+(?:[-+][\w.]+)?)/);
1054
+ return match ? `v${match[1]}` : text || "unknown";
1055
+ }
1056
+ async function findBinaryOnPath(binaryName) {
1057
+ const pathEnv = process.env.PATH ?? "";
1058
+ const dirs = pathEnv.split(import_node_path5.default.delimiter).filter(Boolean);
1059
+ for (const dir of dirs) {
1060
+ const candidate = import_node_path5.default.join(dir, binaryName);
1061
+ if (await isFile(candidate)) {
1062
+ return candidate;
1063
+ }
1064
+ }
1065
+ return null;
1066
+ }
1067
+ async function fetchLatestReleaseTag(repo) {
1068
+ const redirectUrl = `https://github.com/${repo}/releases/latest`;
1069
+ try {
1070
+ const res = await proxyFetch(redirectUrl, {
1071
+ method: "HEAD",
1072
+ redirect: "manual",
1073
+ headers: { "User-Agent": "image-optimizer-node" }
1074
+ });
1075
+ const location = res.headers.get("location");
1076
+ if (location) {
1077
+ const match = location.match(/\/releases\/tag\/([^/?#]+)/);
1078
+ if (match?.[1]) {
1079
+ return match[1];
1080
+ }
1081
+ }
1082
+ } catch {
1083
+ }
1084
+ const apiUrl = `https://api.github.com/repos/${repo}/releases/latest`;
1085
+ const apiRes = await proxyFetch(apiUrl, { headers: getAuthHeaders() });
1086
+ if (!apiRes.ok) {
1087
+ throw new Error(
1088
+ `Failed to query latest release for ${repo} (HTTP ${apiRes.status})`
1089
+ );
1090
+ }
1091
+ const data = await apiRes.json();
1092
+ if (!data.tag_name) {
1093
+ throw new Error(`No tag_name found in latest release response for ${repo}`);
1094
+ }
1095
+ return data.tag_name;
1096
+ }
1097
+ async function listCachedVersions(cacheDir) {
1098
+ try {
1099
+ const entries = await import_promises3.default.readdir(cacheDir, { withFileTypes: true });
1100
+ const spec = resolveReleaseAsset();
1101
+ const versions = [];
1102
+ for (const entry of entries) {
1103
+ if (!entry.isDirectory()) continue;
1104
+ const binCandidate = import_node_path5.default.join(cacheDir, entry.name, spec.binaryName);
1105
+ if (await isFile(binCandidate)) {
1106
+ versions.push(entry.name);
1107
+ }
1108
+ }
1109
+ return versions.sort();
1110
+ } catch {
1111
+ return [];
1112
+ }
1113
+ }
1114
+ function parseSha256Text(text) {
1115
+ const match = text.match(/\b([a-fA-F0-9]{64})\b/);
1116
+ if (!match?.[1]) {
1117
+ throw new Error(`Unable to parse SHA-256 checksum from: ${text.trim()}`);
1118
+ }
1119
+ return match[1].toLowerCase();
1120
+ }
1121
+ async function downloadBuffer(url) {
1122
+ const res = await proxyFetch(url, {
1123
+ redirect: "follow",
1124
+ headers: { "User-Agent": "image-optimizer-node" }
1125
+ });
1126
+ if (!res.ok) {
1127
+ throw new Error(`Download failed from ${url} (HTTP ${res.status})`);
1128
+ }
1129
+ const ab = await res.arrayBuffer();
1130
+ return Buffer.from(ab);
1131
+ }
1132
+ async function findExtractedBinary(rootDir, binaryName, depth = 0) {
1133
+ if (depth > 3) return null;
1134
+ const entries = await import_promises3.default.readdir(rootDir, { withFileTypes: true });
1135
+ for (const entry of entries) {
1136
+ const full = import_node_path5.default.join(rootDir, entry.name);
1137
+ if (entry.isFile() && entry.name === binaryName) {
1138
+ return full;
1139
+ }
1140
+ if (entry.isDirectory()) {
1141
+ const nested = await findExtractedBinary(full, binaryName, depth + 1);
1142
+ if (nested) return nested;
1143
+ }
1144
+ }
1145
+ return null;
1146
+ }
1147
+ async function downloadCliRelease(options) {
1148
+ const repo = options.repo ?? DEFAULT_CLI_REPO;
1149
+ const cacheDir = options.cacheDir ?? getDefaultCliCacheDir();
1150
+ const assetSpec = resolveReleaseAsset();
1151
+ const requestedVersion = options.version ?? "latest";
1152
+ const resolvedTag = requestedVersion === "latest" ? await fetchLatestReleaseTag(repo) : requestedVersion.startsWith("v") ? requestedVersion : `v${requestedVersion}`;
1153
+ const versionDir = import_node_path5.default.join(cacheDir, resolvedTag);
1154
+ const targetBinPath = import_node_path5.default.join(versionDir, assetSpec.binaryName);
1155
+ if (!options.force && await isFile(targetBinPath)) {
1156
+ const actualVer = await probeBinaryVersion(targetBinPath);
1157
+ if (requestedVersion === "latest") {
1158
+ await writeJsonAtomic(import_node_path5.default.join(cacheDir, "latest-meta.json"), {
1159
+ repo,
1160
+ tag: resolvedTag,
1161
+ checkedAt: Date.now()
1162
+ });
1163
+ }
1164
+ return {
1165
+ binPath: targetBinPath,
1166
+ tag: resolvedTag,
1167
+ version: actualVer,
1168
+ source: "cache",
1169
+ cacheDir
1170
+ };
1171
+ }
1172
+ const baseUrl = (options.downloadBaseUrl ?? process.env.IMGOPT_DOWNLOAD_BASE_URL ?? `https://github.com/${repo}/releases/download`).replace(/\/+$/, "");
1173
+ const archiveUrl = `${baseUrl}/${resolvedTag}/${assetSpec.assetName}`;
1174
+ const checksumUrl = `${baseUrl}/${resolvedTag}/${assetSpec.checksumAssetName}`;
1175
+ const [archiveBytes, checksumBytes] = await Promise.all([
1176
+ downloadBuffer(archiveUrl),
1177
+ downloadBuffer(checksumUrl)
1178
+ ]);
1179
+ const expectedHash = parseSha256Text(checksumBytes.toString("utf8"));
1180
+ const actualHash = import_node_crypto3.default.createHash("sha256").update(archiveBytes).digest("hex");
1181
+ if (actualHash !== expectedHash) {
1182
+ throw new Error(
1183
+ `SHA-256 verification failed for ${assetSpec.assetName}: expected ${expectedHash}, got ${actualHash}`
1184
+ );
1185
+ }
1186
+ const tempExtractDir = import_node_path5.default.join(
1187
+ cacheDir,
1188
+ `.tmp-extract-${resolvedTag}-${process.pid}-${import_node_crypto3.default.randomUUID()}`
1189
+ );
1190
+ await import_promises3.default.mkdir(tempExtractDir, { recursive: true });
1191
+ await import_promises3.default.mkdir(versionDir, { recursive: true });
1192
+ try {
1193
+ if (assetSpec.archiveType === "tar.gz") {
1194
+ const archivePath = import_node_path5.default.join(tempExtractDir, assetSpec.assetName);
1195
+ await import_promises3.default.writeFile(archivePath, archiveBytes);
1196
+ await tar.x({
1197
+ file: archivePath,
1198
+ cwd: tempExtractDir
1199
+ });
1200
+ } else {
1201
+ const zip = new import_adm_zip.default(archiveBytes);
1202
+ zip.extractAllTo(tempExtractDir, true);
1203
+ }
1204
+ const extractedBin = await findExtractedBinary(
1205
+ tempExtractDir,
1206
+ assetSpec.binaryName
1207
+ );
1208
+ if (!extractedBin) {
1209
+ throw new Error(
1210
+ `Archive ${assetSpec.assetName} did not contain expected binary "${assetSpec.binaryName}"`
1211
+ );
1212
+ }
1213
+ const tempTargetBin = `${targetBinPath}.tmp-${process.pid}`;
1214
+ await import_promises3.default.copyFile(extractedBin, tempTargetBin);
1215
+ if (process.platform !== "win32") {
1216
+ await import_promises3.default.chmod(tempTargetBin, 493);
1217
+ }
1218
+ await import_promises3.default.rename(tempTargetBin, targetBinPath);
1219
+ } finally {
1220
+ await import_promises3.default.rm(tempExtractDir, { recursive: true, force: true }).catch(() => {
1221
+ });
1222
+ }
1223
+ const verifiedVersion = await probeBinaryVersion(targetBinPath);
1224
+ if (requestedVersion === "latest") {
1225
+ await writeJsonAtomic(import_node_path5.default.join(cacheDir, "latest-meta.json"), {
1226
+ repo,
1227
+ tag: resolvedTag,
1228
+ checkedAt: Date.now()
1229
+ });
1230
+ }
1231
+ return {
1232
+ binPath: targetBinPath,
1233
+ tag: resolvedTag,
1234
+ version: verifiedVersion,
1235
+ source: "downloaded",
1236
+ cacheDir
1237
+ };
1238
+ }
1239
+ async function ensureCli(options = {}) {
1240
+ const cliConfig = {
1241
+ repo: options.cliConfig?.repo ?? DEFAULT_CLI_REPO,
1242
+ version: options.versionOverride ?? options.cliConfig?.version ?? "latest",
1243
+ autoDownload: options.cliConfig?.autoDownload ?? true,
1244
+ autoUpdate: options.cliConfig?.autoUpdate ?? false,
1245
+ cacheDir: options.cliConfig?.cacheDir,
1246
+ binPath: options.cliConfig?.binPath,
1247
+ downloadBaseUrl: options.cliConfig?.downloadBaseUrl
1248
+ };
1249
+ const cacheDir = resolveCacheDir(cliConfig);
1250
+ const assetSpec = resolveReleaseAsset();
1251
+ if (!options.forceUpdate && process.env.IMGOPT_BIN) {
1252
+ const envBin = import_node_path5.default.resolve(expandHome(process.env.IMGOPT_BIN));
1253
+ if (!await isFile(envBin)) {
1254
+ throw new Error(`IMGOPT_BIN points to a missing file: ${envBin}`);
1255
+ }
1256
+ const version = await probeBinaryVersion(envBin);
1257
+ return { binPath: envBin, tag: version, version, source: "env", cacheDir };
1258
+ }
1259
+ if (!options.forceUpdate && cliConfig.binPath) {
1260
+ const cfgBin = import_node_path5.default.resolve(expandHome(cliConfig.binPath));
1261
+ if (!await isFile(cfgBin)) {
1262
+ throw new Error(`cli.binPath points to a missing file: ${cfgBin}`);
1263
+ }
1264
+ const version = await probeBinaryVersion(cfgBin);
1265
+ return { binPath: cfgBin, tag: version, version, source: "config", cacheDir };
1266
+ }
1267
+ const shouldCheckRemote = options.forceUpdate || cliConfig.version === "latest" && cliConfig.autoUpdate;
1268
+ if (cliConfig.version !== "latest") {
1269
+ const tag = cliConfig.version.startsWith("v") ? cliConfig.version : `v${cliConfig.version}`;
1270
+ const cachedPath = import_node_path5.default.join(cacheDir, tag, assetSpec.binaryName);
1271
+ if (!options.forceUpdate && await isFile(cachedPath)) {
1272
+ const version = await probeBinaryVersion(cachedPath);
1273
+ return { binPath: cachedPath, tag, version, source: "cache", cacheDir };
1274
+ }
1275
+ if (cliConfig.autoDownload) {
1276
+ return downloadCliRelease({
1277
+ repo: cliConfig.repo,
1278
+ version: tag,
1279
+ cacheDir,
1280
+ downloadBaseUrl: cliConfig.downloadBaseUrl,
1281
+ force: options.forceUpdate
1282
+ });
1283
+ }
1284
+ } else {
1285
+ const metaPath = import_node_path5.default.join(cacheDir, "latest-meta.json");
1286
+ if (!shouldCheckRemote && await fileExists(metaPath)) {
1287
+ try {
1288
+ const meta = await readJsonFile(metaPath);
1289
+ if (meta.repo === cliConfig.repo && Date.now() - meta.checkedAt < LATEST_CACHE_TTL_MS) {
1290
+ const cachedPath = import_node_path5.default.join(
1291
+ cacheDir,
1292
+ meta.tag,
1293
+ assetSpec.binaryName
1294
+ );
1295
+ if (await isFile(cachedPath)) {
1296
+ const version = await probeBinaryVersion(cachedPath);
1297
+ return {
1298
+ binPath: cachedPath,
1299
+ tag: meta.tag,
1300
+ version,
1301
+ source: "cache",
1302
+ cacheDir
1303
+ };
1304
+ }
1305
+ }
1306
+ } catch {
1307
+ }
1308
+ }
1309
+ if (cliConfig.autoDownload || options.forceUpdate) {
1310
+ try {
1311
+ return await downloadCliRelease({
1312
+ repo: cliConfig.repo,
1313
+ version: "latest",
1314
+ cacheDir,
1315
+ downloadBaseUrl: cliConfig.downloadBaseUrl,
1316
+ force: options.forceUpdate
1317
+ });
1318
+ } catch (err) {
1319
+ const cachedVersions = await listCachedVersions(cacheDir);
1320
+ const latestCached = cachedVersions[cachedVersions.length - 1];
1321
+ if (latestCached && !options.forceUpdate) {
1322
+ const fallbackBin = import_node_path5.default.join(
1323
+ cacheDir,
1324
+ latestCached,
1325
+ assetSpec.binaryName
1326
+ );
1327
+ const version = await probeBinaryVersion(fallbackBin);
1328
+ return {
1329
+ binPath: fallbackBin,
1330
+ tag: latestCached,
1331
+ version,
1332
+ source: "cache",
1333
+ cacheDir
1334
+ };
1335
+ }
1336
+ throw err;
1337
+ }
1338
+ }
1339
+ }
1340
+ const pathBin = await findBinaryOnPath(assetSpec.binaryName);
1341
+ if (pathBin) {
1342
+ const version = await probeBinaryVersion(pathBin);
1343
+ return { binPath: pathBin, tag: version, version, source: "path", cacheDir };
1344
+ }
1345
+ throw new Error(
1346
+ `Unable to locate ${assetSpec.binaryName}. Run "imgopt-node cli update" or enable cli.autoDownload.`
1347
+ );
1348
+ }
1349
+ async function getCliStatus(cliConfig, checkRemote = true) {
1350
+ const repo = cliConfig?.repo ?? DEFAULT_CLI_REPO;
1351
+ const configuredVersion = cliConfig?.version ?? "latest";
1352
+ const cacheDir = resolveCacheDir(cliConfig);
1353
+ const cachedVersions = await listCachedVersions(cacheDir);
1354
+ const assetSpec = resolveReleaseAsset();
1355
+ let resolvedBinPath = null;
1356
+ let installedTag = null;
1357
+ let installedVersion = null;
1358
+ let source = "missing";
1359
+ if (process.env.IMGOPT_BIN && await isFile(process.env.IMGOPT_BIN)) {
1360
+ resolvedBinPath = import_node_path5.default.resolve(process.env.IMGOPT_BIN);
1361
+ installedVersion = await probeBinaryVersion(resolvedBinPath);
1362
+ installedTag = installedVersion;
1363
+ source = "env";
1364
+ } else if (cliConfig?.binPath && await isFile(cliConfig.binPath)) {
1365
+ resolvedBinPath = import_node_path5.default.resolve(expandHome(cliConfig.binPath));
1366
+ installedVersion = await probeBinaryVersion(resolvedBinPath);
1367
+ installedTag = installedVersion;
1368
+ source = "config";
1369
+ } else if (cachedVersions.length > 0) {
1370
+ const picked = configuredVersion !== "latest" && cachedVersions.includes(
1371
+ configuredVersion.startsWith("v") ? configuredVersion : `v${configuredVersion}`
1372
+ ) ? configuredVersion.startsWith("v") ? configuredVersion : `v${configuredVersion}` : cachedVersions[cachedVersions.length - 1];
1373
+ resolvedBinPath = import_node_path5.default.join(cacheDir, picked, assetSpec.binaryName);
1374
+ installedVersion = await probeBinaryVersion(resolvedBinPath);
1375
+ installedTag = picked;
1376
+ source = "cache";
1377
+ } else {
1378
+ const pathBin = await findBinaryOnPath(assetSpec.binaryName);
1379
+ if (pathBin) {
1380
+ resolvedBinPath = pathBin;
1381
+ installedVersion = await probeBinaryVersion(pathBin);
1382
+ installedTag = installedVersion;
1383
+ source = "path";
1384
+ }
1385
+ }
1386
+ let latestRemoteVersion = null;
1387
+ if (checkRemote) {
1388
+ try {
1389
+ latestRemoteVersion = await fetchLatestReleaseTag(repo);
1390
+ } catch {
1391
+ latestRemoteVersion = null;
1392
+ }
1393
+ }
1394
+ const comparedInstalled = installedTag ?? installedVersion;
1395
+ const updateAvailable = Boolean(
1396
+ latestRemoteVersion && comparedInstalled && latestRemoteVersion !== comparedInstalled
1397
+ );
1398
+ return {
1399
+ repo,
1400
+ configuredVersion,
1401
+ resolvedBinPath,
1402
+ installedTag,
1403
+ installedVersion,
1404
+ source,
1405
+ latestRemoteVersion,
1406
+ updateAvailable,
1407
+ cacheDir,
1408
+ cachedVersions
1409
+ };
1410
+ }
1411
+
1412
+ // src/core/scanner.ts
1413
+ var import_promises4 = __toESM(require("fs/promises"), 1);
1414
+ var import_node_path6 = __toESM(require("path"), 1);
1415
+ var import_picomatch2 = __toESM(require("picomatch"), 1);
1416
+ function isSameOrInside(candidatePosix, parentPosix) {
1417
+ const cleanParent = parentPosix.replace(/\/+$/, "");
1418
+ if (!cleanParent || cleanParent === ".") return false;
1419
+ return candidatePosix === cleanParent || candidatePosix.startsWith(`${cleanParent}/`);
1420
+ }
1421
+ async function scanProjectImages(projectRoot, config, onlyRelPaths) {
1422
+ const seen = /* @__PURE__ */ new Map();
1423
+ const backupDirPosix = toPosixPath(config.backup.dir).replace(/^\.\//, "");
1424
+ const manifestPosix = toPosixPath(config.manifest).replace(/^\.\//, "");
1425
+ for (const target of config.targets) {
1426
+ const targetDirAbs = resolveInsideRoot(projectRoot, target.dir);
1427
+ if (!await isDirectory(targetDirAbs)) {
1428
+ continue;
1429
+ }
1430
+ const includePatterns = target.include && target.include.length > 0 ? target.include : DEFAULT_INCLUDE_GLOBS;
1431
+ const excludePatterns = target.exclude !== void 0 ? target.exclude : DEFAULT_EXCLUDE_GLOBS;
1432
+ const isIncluded = (0, import_picomatch2.default)(includePatterns, { dot: false, nocase: true });
1433
+ const isExcluded = excludePatterns.length > 0 ? (0, import_picomatch2.default)(excludePatterns, { dot: true, nocase: true }) : () => false;
1434
+ async function walk(currentAbs) {
1435
+ let entries;
1436
+ try {
1437
+ entries = await import_promises4.default.readdir(currentAbs, { withFileTypes: true });
1438
+ } catch {
1439
+ return;
1440
+ }
1441
+ entries.sort((a, b) => a.name.localeCompare(b.name));
1442
+ for (const entry of entries) {
1443
+ if (entry.isSymbolicLink()) continue;
1444
+ if (entry.name.startsWith(".") || IGNORED_DIR_NAMES.has(entry.name)) {
1445
+ continue;
1446
+ }
1447
+ const absPath = import_node_path6.default.join(currentAbs, entry.name);
1448
+ const relToProject = toPosixPath(import_node_path6.default.relative(projectRoot, absPath));
1449
+ if (isSameOrInside(relToProject, backupDirPosix) || relToProject === manifestPosix) {
1450
+ continue;
1451
+ }
1452
+ if (entry.isDirectory()) {
1453
+ await walk(absPath);
1454
+ continue;
1455
+ }
1456
+ if (!entry.isFile()) continue;
1457
+ const ext = import_node_path6.default.extname(entry.name).toLowerCase();
1458
+ if (!SUPPORTED_IMAGE_EXTENSIONS.has(ext)) {
1459
+ continue;
1460
+ }
1461
+ const relToTarget = toPosixPath(import_node_path6.default.relative(targetDirAbs, absPath));
1462
+ if (!isIncluded(relToTarget) || isExcluded(relToTarget)) {
1463
+ continue;
1464
+ }
1465
+ if (onlyRelPaths && !onlyRelPaths.has(relToProject)) {
1466
+ continue;
1467
+ }
1468
+ if (!seen.has(relToProject)) {
1469
+ const stat = await import_promises4.default.stat(absPath);
1470
+ seen.set(relToProject, {
1471
+ relPath: relToProject,
1472
+ absPath,
1473
+ byteSize: stat.size,
1474
+ targetDir: target.dir
1475
+ });
1476
+ }
1477
+ }
1478
+ }
1479
+ await walk(targetDirAbs);
1480
+ }
1481
+ return [...seen.values()].sort((a, b) => a.relPath.localeCompare(b.relPath));
1482
+ }
1483
+
1484
+ // src/core/manifest.ts
1485
+ var import_node_path7 = __toESM(require("path"), 1);
1486
+ function createEmptyManifest() {
1487
+ return {
1488
+ version: 1,
1489
+ entries: {}
1490
+ };
1491
+ }
1492
+ async function loadManifest(projectRoot, manifestRelPath) {
1493
+ const absPath = resolveInsideRoot(projectRoot, manifestRelPath);
1494
+ if (!await fileExists(absPath)) {
1495
+ return createEmptyManifest();
1496
+ }
1497
+ const parsed = await readJsonFile(absPath);
1498
+ if (!parsed || typeof parsed !== "object" || parsed.version !== 1 || !parsed.entries) {
1499
+ throw new Error(`Invalid manifest schema in ${absPath}`);
1500
+ }
1501
+ return parsed;
1502
+ }
1503
+ async function saveManifest(projectRoot, manifestRelPath, manifest) {
1504
+ const absPath = resolveInsideRoot(projectRoot, manifestRelPath);
1505
+ const sortedEntries = {};
1506
+ for (const key of Object.keys(manifest.entries).sort()) {
1507
+ sortedEntries[key] = manifest.entries[key];
1508
+ }
1509
+ const ordered = {
1510
+ version: 1,
1511
+ entries: sortedEntries
1512
+ };
1513
+ await writeJsonAtomic(absPath, ordered);
1514
+ return import_node_path7.default.relative(projectRoot, absPath);
1515
+ }
1516
+ function buildManifestIndex(manifest) {
1517
+ const bySourcePath = /* @__PURE__ */ new Map();
1518
+ const byOutputPath = /* @__PURE__ */ new Map();
1519
+ for (const entry of Object.values(manifest.entries)) {
1520
+ bySourcePath.set(entry.sourcePath, entry);
1521
+ byOutputPath.set(entry.outputPath, entry);
1522
+ }
1523
+ return { bySourcePath, byOutputPath };
1524
+ }
1525
+ function findEntryForDiskPath(index, relPath) {
1526
+ return index.bySourcePath.get(relPath) ?? index.byOutputPath.get(relPath);
1527
+ }
1528
+
1529
+ // src/core/backup.ts
1530
+ var import_promises5 = __toESM(require("fs/promises"), 1);
1531
+ var import_node_path8 = __toESM(require("path"), 1);
1532
+
1533
+ // src/core/hash.ts
1534
+ var import_node_crypto4 = __toESM(require("crypto"), 1);
1535
+ var import_node_fs = __toESM(require("fs"), 1);
1536
+ async function sha256File(filePath) {
1537
+ return new Promise((resolve, reject) => {
1538
+ const hash = import_node_crypto4.default.createHash("sha256");
1539
+ const stream = import_node_fs.default.createReadStream(filePath);
1540
+ stream.on("data", (chunk) => hash.update(chunk));
1541
+ stream.on("error", reject);
1542
+ stream.on("end", () => resolve(hash.digest("hex")));
1543
+ });
1544
+ }
1545
+ function sha256Buffer(data) {
1546
+ return import_node_crypto4.default.createHash("sha256").update(data).digest("hex");
1547
+ }
1548
+
1549
+ // src/core/backup.ts
1550
+ function getBackupRelPath(backupDir, sourceRelPath) {
1551
+ const cleanDir = toPosixPath(backupDir).replace(/\/+$/, "");
1552
+ const cleanRel = toPosixPath(sourceRelPath).replace(/^\/+/, "");
1553
+ return `${cleanDir}/${cleanRel}`;
1554
+ }
1555
+ async function ensureOriginalBackup(options) {
1556
+ const {
1557
+ projectRoot,
1558
+ backupConfig,
1559
+ sourceRelPath,
1560
+ sourceAbsPath,
1561
+ isNewSourceVersion
1562
+ } = options;
1563
+ if (!backupConfig.enabled) {
1564
+ return void 0;
1565
+ }
1566
+ const backupRelPath = getBackupRelPath(backupConfig.dir, sourceRelPath);
1567
+ const backupAbsPath = resolveInsideRoot(projectRoot, backupRelPath);
1568
+ const exists = await fileExists(backupAbsPath);
1569
+ if (!exists) {
1570
+ await atomicCopyFile(sourceAbsPath, backupAbsPath);
1571
+ return backupRelPath;
1572
+ }
1573
+ if (backupConfig.strategy === "preserve-first" && isNewSourceVersion) {
1574
+ await atomicCopyFile(sourceAbsPath, backupAbsPath);
1575
+ }
1576
+ return backupRelPath;
1577
+ }
1578
+ async function hasValidBackup(options) {
1579
+ if (!options.backupRelPath) {
1580
+ return { exists: false };
1581
+ }
1582
+ const absPath = resolveInsideRoot(options.projectRoot, options.backupRelPath);
1583
+ if (!await isFile(absPath)) {
1584
+ return { exists: false };
1585
+ }
1586
+ if (options.expectedSha256) {
1587
+ const actual = await sha256File(absPath);
1588
+ if (actual !== options.expectedSha256) {
1589
+ return { exists: false };
1590
+ }
1591
+ }
1592
+ return { exists: true, absPath };
1593
+ }
1594
+ async function listBackupFiles(projectRoot, backupDir) {
1595
+ const backupRootAbs = resolveInsideRoot(projectRoot, backupDir);
1596
+ const results = [];
1597
+ async function walk(current) {
1598
+ let entries;
1599
+ try {
1600
+ entries = await import_promises5.default.readdir(current, { withFileTypes: true });
1601
+ } catch {
1602
+ return;
1603
+ }
1604
+ entries.sort((a, b) => a.name.localeCompare(b.name));
1605
+ for (const entry of entries) {
1606
+ if (entry.isSymbolicLink()) continue;
1607
+ const absPath = import_node_path8.default.join(current, entry.name);
1608
+ if (entry.isDirectory()) {
1609
+ await walk(absPath);
1610
+ } else if (entry.isFile()) {
1611
+ const sourceRelPath = toPosixPath(import_node_path8.default.relative(backupRootAbs, absPath));
1612
+ const backupRelPath = getBackupRelPath(backupDir, sourceRelPath);
1613
+ results.push({ backupRelPath, sourceRelPath, absPath });
1614
+ }
1615
+ }
1616
+ }
1617
+ await walk(backupRootAbs);
1618
+ return results;
1619
+ }
1620
+
1621
+ // src/commands/init.ts
1622
+ var import_promises6 = __toESM(require("fs/promises"), 1);
1623
+ var import_node_path9 = __toESM(require("path"), 1);
1624
+ var import_node_url = require("url");
1625
+ var import_node_fs2 = __toESM(require("fs"), 1);
1626
+ function getPackageRoot() {
1627
+ let dir = import_node_path9.default.dirname((0, import_node_url.fileURLToPath)(importMetaUrl));
1628
+ for (let i = 0; i < 6; i += 1) {
1629
+ const pkgPath = import_node_path9.default.join(dir, "package.json");
1630
+ if (import_node_fs2.default.existsSync(pkgPath)) {
1631
+ return dir;
1632
+ }
1633
+ const parent = import_node_path9.default.dirname(dir);
1634
+ if (parent === dir) break;
1635
+ dir = parent;
1636
+ }
1637
+ return import_node_path9.default.resolve(import_node_path9.default.dirname((0, import_node_url.fileURLToPath)(importMetaUrl)), "..", "..");
1638
+ }
1639
+ async function ensureGitignoreLines(projectRoot, linesToEnsure) {
1640
+ const gitignorePath = import_node_path9.default.join(projectRoot, ".gitignore");
1641
+ let content = "";
1642
+ if (await fileExists(gitignorePath)) {
1643
+ content = await import_promises6.default.readFile(gitignorePath, "utf8");
1644
+ }
1645
+ const existingLines = new Set(
1646
+ content.split(/\r?\n/).map((line) => line.trim())
1647
+ );
1648
+ const missing = linesToEnsure.filter((line) => !existingLines.has(line));
1649
+ if (missing.length === 0) {
1650
+ return false;
1651
+ }
1652
+ const suffix = (content.length > 0 && !content.endsWith("\n") ? "\n" : "") + `
1653
+ # image-optimizer-node
1654
+ ${missing.join("\n")}
1655
+ `;
1656
+ await atomicWriteFile(gitignorePath, content + suffix);
1657
+ return true;
1658
+ }
1659
+ async function initProject(options = {}) {
1660
+ const projectRoot = import_node_path9.default.resolve(options.projectRoot ?? process.cwd());
1661
+ const configPath = import_node_path9.default.resolve(
1662
+ projectRoot,
1663
+ options.configPath ?? DEFAULT_CONFIG_FILENAME
1664
+ );
1665
+ if (!options.force && await fileExists(configPath)) {
1666
+ throw new Error(
1667
+ `Configuration already exists at ${configPath}. Pass --force to overwrite.`
1668
+ );
1669
+ }
1670
+ const detection = await detectProject(projectRoot, options.dirs ?? []);
1671
+ const config = createDefaultConfig(detection.suggestedTargets);
1672
+ if (options.cliVersion) {
1673
+ config.cli.version = options.cliVersion;
1674
+ }
1675
+ if (options.backup !== void 0) {
1676
+ config.backup.enabled = options.backup;
1677
+ }
1678
+ if (options.backupDir) {
1679
+ config.backup.dir = options.backupDir;
1680
+ }
1681
+ if (options.preset) {
1682
+ config.optimization.preset = options.preset;
1683
+ if (options.preset !== "balanced") {
1684
+ if (options.quality === void 0) {
1685
+ delete config.optimization.quality;
1686
+ }
1687
+ if (options.effort === void 0) {
1688
+ delete config.optimization.effort;
1689
+ }
1690
+ }
1691
+ }
1692
+ if (options.quality !== void 0) {
1693
+ config.optimization.quality = options.quality;
1694
+ }
1695
+ if (options.effort !== void 0) {
1696
+ config.optimization.effort = options.effort;
1697
+ }
1698
+ if (options.format) {
1699
+ config.optimization.format = options.format;
1700
+ }
1701
+ if (options.template === "web") {
1702
+ config.optimization.resize = {
1703
+ maxWidth: 2560,
1704
+ maxHeight: 2560,
1705
+ mode: "scale-down"
1706
+ };
1707
+ }
1708
+ await saveConfig(configPath, config);
1709
+ let ciWorkflowPath;
1710
+ if (options.ci) {
1711
+ const templatePath = import_node_path9.default.join(
1712
+ getPackageRoot(),
1713
+ "templates",
1714
+ "workflows",
1715
+ "optimize-images.yml"
1716
+ );
1717
+ const workflowDest = import_node_path9.default.join(
1718
+ projectRoot,
1719
+ ".github",
1720
+ "workflows",
1721
+ "optimize-images.yml"
1722
+ );
1723
+ if (options.force || !await fileExists(workflowDest)) {
1724
+ const templateContent = await import_promises6.default.readFile(templatePath, "utf8");
1725
+ await atomicWriteFile(workflowDest, templateContent);
1726
+ }
1727
+ ciWorkflowPath = import_node_path9.default.relative(projectRoot, workflowDest);
1728
+ }
1729
+ let gitignoreUpdated = false;
1730
+ if (options.gitignore) {
1731
+ const backupEntry = `${(config.backup.dir || DEFAULT_BACKUP_DIR).replace(/\/+$/, "")}/`;
1732
+ gitignoreUpdated = await ensureGitignoreLines(projectRoot, [backupEntry]);
1733
+ }
1734
+ return {
1735
+ configPath,
1736
+ config,
1737
+ stacks: detection.stacks,
1738
+ detectedDirs: detection.detectedDirs,
1739
+ ciWorkflowPath,
1740
+ gitignoreUpdated
1741
+ };
1742
+ }
1743
+
1744
+ // src/commands/optimize.ts
1745
+ var import_promises8 = __toESM(require("fs/promises"), 1);
1746
+ var import_node_path11 = __toESM(require("path"), 1);
1747
+
1748
+ // src/core/git.ts
1749
+ var import_node_child_process2 = require("child_process");
1750
+ var import_node_util2 = require("util");
1751
+ var execFileAsync2 = (0, import_node_util2.promisify)(import_node_child_process2.execFile);
1752
+ async function isGitRepo(projectRoot) {
1753
+ try {
1754
+ await execFileAsync2("git", ["rev-parse", "--is-inside-work-tree"], {
1755
+ cwd: projectRoot
1756
+ });
1757
+ return true;
1758
+ } catch {
1759
+ return false;
1760
+ }
1761
+ }
1762
+ async function getStagedImagePaths(projectRoot) {
1763
+ const { stdout } = await execFileAsync2(
1764
+ "git",
1765
+ ["diff", "--cached", "--name-only", "--diff-filter=ACM", "-z"],
1766
+ { cwd: projectRoot }
1767
+ );
1768
+ const files = stdout.split("\0").map((p) => p.trim()).filter(Boolean).map((p) => toPosixPath(p));
1769
+ return new Set(files);
1770
+ }
1771
+ async function gitAddFiles(projectRoot, relPaths) {
1772
+ if (relPaths.length === 0) return;
1773
+ const nonIgnored = [];
1774
+ for (const rel of relPaths) {
1775
+ try {
1776
+ await execFileAsync2("git", ["check-ignore", "-q", rel], {
1777
+ cwd: projectRoot
1778
+ });
1779
+ } catch {
1780
+ nonIgnored.push(rel);
1781
+ }
1782
+ }
1783
+ if (nonIgnored.length > 0) {
1784
+ await execFileAsync2("git", ["add", "--", ...nonIgnored], {
1785
+ cwd: projectRoot
1786
+ });
1787
+ }
1788
+ }
1789
+
1790
+ // src/core/runner.ts
1791
+ var import_node_child_process3 = require("child_process");
1792
+ var import_node_crypto5 = __toESM(require("crypto"), 1);
1793
+ var import_promises7 = __toESM(require("fs/promises"), 1);
1794
+ var import_node_os2 = __toESM(require("os"), 1);
1795
+ var import_node_path10 = __toESM(require("path"), 1);
1796
+ var import_node_util3 = require("util");
1797
+ var execFileAsync3 = (0, import_node_util3.promisify)(import_node_child_process3.execFile);
1798
+ function buildOptimizeCliArgs(inputDir, outputDir, reportJsonPath, opt) {
1799
+ const args = [
1800
+ "optimize",
1801
+ inputDir,
1802
+ "--output",
1803
+ outputDir,
1804
+ "--format",
1805
+ opt.format,
1806
+ "--preset",
1807
+ opt.preset,
1808
+ "--json",
1809
+ reportJsonPath,
1810
+ "--quiet"
1811
+ ];
1812
+ if (opt.quality !== void 0) {
1813
+ args.push("--quality", String(opt.quality));
1814
+ }
1815
+ if (opt.effort !== void 0) {
1816
+ args.push("--effort", String(opt.effort));
1817
+ }
1818
+ if (opt.preserveMetadata) {
1819
+ args.push("--preserve-metadata");
1820
+ } else if (opt.preserveIcc) {
1821
+ args.push("--preserve-icc");
1822
+ }
1823
+ if (!opt.convertToSrgb) {
1824
+ args.push("--no-srgb-convert");
1825
+ }
1826
+ if (opt.resize) {
1827
+ if (opt.resize.maxWidth !== void 0) {
1828
+ args.push("--resize-width", String(opt.resize.maxWidth));
1829
+ }
1830
+ if (opt.resize.maxHeight !== void 0) {
1831
+ args.push("--resize-height", String(opt.resize.maxHeight));
1832
+ }
1833
+ if (opt.resize.mode) {
1834
+ args.push("--resize-mode", opt.resize.mode);
1835
+ }
1836
+ }
1837
+ if (opt.concurrency !== void 0) {
1838
+ args.push("--concurrency", String(opt.concurrency));
1839
+ }
1840
+ return args;
1841
+ }
1842
+ function formatToExtension(format, fallbackExt) {
1843
+ switch (format.toLowerCase()) {
1844
+ case "jpeg":
1845
+ case "jpg":
1846
+ return ".jpg";
1847
+ case "png":
1848
+ return ".png";
1849
+ case "webp":
1850
+ return ".webp";
1851
+ case "avif":
1852
+ return ".avif";
1853
+ case "gif":
1854
+ return ".gif";
1855
+ default:
1856
+ return fallbackExt;
1857
+ }
1858
+ }
1859
+ function extensionToCanonicalFormat(ext) {
1860
+ const lower = ext.toLowerCase();
1861
+ if (lower === ".jpg" || lower === ".jpeg") return "jpeg";
1862
+ if (lower === ".png") return "png";
1863
+ if (lower === ".webp") return "webp";
1864
+ if (lower === ".avif") return "avif";
1865
+ if (lower === ".gif") return "gif";
1866
+ return lower.replace(/^\./, "");
1867
+ }
1868
+ function partitionCollisionSafeBatches(tasks, formatPolicy) {
1869
+ if (formatPolicy === "preserve") {
1870
+ return tasks.length > 0 ? [tasks] : [];
1871
+ }
1872
+ const batches = [];
1873
+ const usedStemsPerBatch = [];
1874
+ for (const task of tasks) {
1875
+ const parsed = import_node_path10.default.posix.parse(task.relPath);
1876
+ const stemKey = `${parsed.dir}/${parsed.name}`.toLowerCase();
1877
+ let placed = false;
1878
+ for (let i = 0; i < batches.length; i += 1) {
1879
+ if (!usedStemsPerBatch[i].has(stemKey)) {
1880
+ usedStemsPerBatch[i].add(stemKey);
1881
+ batches[i].push(task);
1882
+ placed = true;
1883
+ break;
1884
+ }
1885
+ }
1886
+ if (!placed) {
1887
+ batches.push([task]);
1888
+ usedStemsPerBatch.push(/* @__PURE__ */ new Set([stemKey]));
1889
+ }
1890
+ }
1891
+ return batches;
1892
+ }
1893
+ async function runImgoptBatch(options) {
1894
+ const batches = partitionCollisionSafeBatches(
1895
+ options.tasks,
1896
+ options.optimization.format
1897
+ );
1898
+ for (const batch of batches) {
1899
+ const workDir = await import_promises7.default.mkdtemp(
1900
+ import_node_path10.default.join(import_node_os2.default.tmpdir(), `imgopt-node-${import_node_crypto5.default.randomUUID().slice(0, 8)}-`)
1901
+ );
1902
+ const inputDir = import_node_path10.default.join(workDir, "in");
1903
+ const outputDir = import_node_path10.default.join(workDir, "out");
1904
+ const reportPath = import_node_path10.default.join(workDir, "report.json");
1905
+ try {
1906
+ await import_promises7.default.mkdir(inputDir, { recursive: true });
1907
+ await import_promises7.default.mkdir(outputDir, { recursive: true });
1908
+ const stagedMap = /* @__PURE__ */ new Map();
1909
+ for (const task of batch) {
1910
+ const stagedIn = import_node_path10.default.join(inputDir, task.relPath);
1911
+ await import_promises7.default.mkdir(import_node_path10.default.dirname(stagedIn), { recursive: true });
1912
+ await import_promises7.default.copyFile(task.sourceFileToOptimize, stagedIn);
1913
+ stagedMap.set(toPosixPath(import_node_path10.default.resolve(stagedIn)), task);
1914
+ }
1915
+ const cliArgs = buildOptimizeCliArgs(
1916
+ inputDir,
1917
+ outputDir,
1918
+ reportPath,
1919
+ options.optimization
1920
+ );
1921
+ let cliError = null;
1922
+ try {
1923
+ await execFileAsync3(options.binPath, cliArgs, {
1924
+ maxBuffer: 20 * 1024 * 1024
1925
+ });
1926
+ } catch (err) {
1927
+ cliError = err instanceof Error ? err : new Error(String(err));
1928
+ }
1929
+ let parsedReport = null;
1930
+ try {
1931
+ const raw = await import_promises7.default.readFile(reportPath, "utf8");
1932
+ parsedReport = JSON.parse(raw);
1933
+ } catch {
1934
+ parsedReport = null;
1935
+ }
1936
+ if (!parsedReport) {
1937
+ throw cliError ?? new Error("imgopt did not produce a readable JSON report");
1938
+ }
1939
+ const outcomes = [];
1940
+ const resolvedInputDir = toPosixPath(import_node_path10.default.resolve(inputDir));
1941
+ for (const item of parsedReport.items) {
1942
+ const resolvedItemPath = toPosixPath(import_node_path10.default.resolve(item.path));
1943
+ const task = stagedMap.get(resolvedItemPath) ?? (() => {
1944
+ const relFromIn = toPosixPath(
1945
+ import_node_path10.default.relative(resolvedInputDir, resolvedItemPath)
1946
+ );
1947
+ return batch.find((b) => b.relPath === relFromIn);
1948
+ })();
1949
+ if (!task) continue;
1950
+ if (item.status === "failed" || !item.format) {
1951
+ outcomes.push({
1952
+ relPath: task.relPath,
1953
+ projectOutputRelPath: task.relPath,
1954
+ stagedOutputPath: "",
1955
+ format: item.format ?? "unknown",
1956
+ originalBytes: item.source_bytes,
1957
+ optimizedBytes: item.source_bytes,
1958
+ error: item.error ?? "Optimization failed"
1959
+ });
1960
+ continue;
1961
+ }
1962
+ const origParsed = import_node_path10.default.posix.parse(task.relPath);
1963
+ const imgoptExt = formatToExtension(item.format, origParsed.ext);
1964
+ const relStagedOut = import_node_path10.default.posix.join(
1965
+ origParsed.dir,
1966
+ `${origParsed.name}${imgoptExt}`
1967
+ );
1968
+ const stagedOutAbs = import_node_path10.default.join(outputDir, relStagedOut);
1969
+ const sameFormatAsSource = extensionToCanonicalFormat(origParsed.ext) === item.format.toLowerCase();
1970
+ const projectOutputRelPath = options.optimization.format === "preserve" || sameFormatAsSource ? task.relPath : relStagedOut;
1971
+ outcomes.push({
1972
+ relPath: task.relPath,
1973
+ projectOutputRelPath,
1974
+ stagedOutputPath: stagedOutAbs,
1975
+ format: item.format,
1976
+ originalBytes: item.source_bytes,
1977
+ optimizedBytes: item.optimized_bytes ?? item.source_bytes,
1978
+ qualityScore: item.quality_score
1979
+ });
1980
+ }
1981
+ await options.onEachStagedResult(outcomes);
1982
+ } finally {
1983
+ await import_promises7.default.rm(workDir, { recursive: true, force: true }).catch(() => {
1984
+ });
1985
+ }
1986
+ }
1987
+ }
1988
+ async function inspectImagesWithImgopt(binPath, absPaths) {
1989
+ const resultMap = /* @__PURE__ */ new Map();
1990
+ for (const absPath of absPaths) {
1991
+ try {
1992
+ const { stdout } = await execFileAsync3(
1993
+ binPath,
1994
+ ["inspect", absPath, "--json"],
1995
+ { maxBuffer: 5 * 1024 * 1024 }
1996
+ );
1997
+ const parsed = JSON.parse(stdout);
1998
+ if (Array.isArray(parsed)) {
1999
+ for (const entry of parsed) {
2000
+ if (entry?.path) {
2001
+ resultMap.set(import_node_path10.default.resolve(entry.path), entry);
2002
+ }
2003
+ }
2004
+ } else if (parsed?.path) {
2005
+ resultMap.set(import_node_path10.default.resolve(parsed.path), parsed);
2006
+ }
2007
+ } catch {
2008
+ }
2009
+ }
2010
+ return resultMap;
2011
+ }
2012
+
2013
+ // src/utils/format.ts
2014
+ function computeSavings(originalBytes, optimizedBytes) {
2015
+ const savedBytes = Math.max(0, originalBytes - optimizedBytes);
2016
+ const savedPercent = originalBytes > 0 ? savedBytes / originalBytes * 100 : 0;
2017
+ return { savedBytes, savedPercent };
2018
+ }
2019
+
2020
+ // src/commands/optimize.ts
2021
+ async function optimizeProject(options = {}) {
2022
+ const startMs = Date.now();
2023
+ const dryRun = Boolean(options.dryRun);
2024
+ const { projectRoot, config } = await loadConfig(
2025
+ options.projectRoot,
2026
+ options.configPath
2027
+ );
2028
+ let stagedFilter;
2029
+ if (options.staged) {
2030
+ if (!await isGitRepo(projectRoot)) {
2031
+ throw new Error("--staged requires running inside a Git repository");
2032
+ }
2033
+ stagedFilter = await getStagedImagePaths(projectRoot);
2034
+ if (stagedFilter.size === 0) {
2035
+ return {
2036
+ summary: {
2037
+ totalScanned: 0,
2038
+ optimized: 0,
2039
+ reoptimizedFromBackup: 0,
2040
+ skippedCached: 0,
2041
+ skippedSmall: 0,
2042
+ skippedNoSavings: 0,
2043
+ skippedConfigChangedNoBackup: 0,
2044
+ failed: 0,
2045
+ originalBytes: 0,
2046
+ optimizedBytes: 0,
2047
+ savedBytes: 0,
2048
+ savedPercent: 0,
2049
+ elapsedMs: Date.now() - startMs,
2050
+ dryRun,
2051
+ cliVersion: config.cli.version
2052
+ },
2053
+ items: [],
2054
+ budgetWarnings: []
2055
+ };
2056
+ }
2057
+ }
2058
+ const scannedFiles = await scanProjectImages(
2059
+ projectRoot,
2060
+ config,
2061
+ stagedFilter
2062
+ );
2063
+ const cliInfo = await ensureCli({
2064
+ cliConfig: config.cli,
2065
+ forceUpdate: options.updateCli,
2066
+ versionOverride: options.cliVersion
2067
+ });
2068
+ if (scannedFiles.length === 0) {
2069
+ return {
2070
+ summary: {
2071
+ totalScanned: 0,
2072
+ optimized: 0,
2073
+ reoptimizedFromBackup: 0,
2074
+ skippedCached: 0,
2075
+ skippedSmall: 0,
2076
+ skippedNoSavings: 0,
2077
+ skippedConfigChangedNoBackup: 0,
2078
+ failed: 0,
2079
+ originalBytes: 0,
2080
+ optimizedBytes: 0,
2081
+ savedBytes: 0,
2082
+ savedPercent: 0,
2083
+ elapsedMs: Date.now() - startMs,
2084
+ dryRun,
2085
+ cliVersion: cliInfo.tag
2086
+ },
2087
+ items: [],
2088
+ budgetWarnings: []
2089
+ };
2090
+ }
2091
+ const manifest = await loadManifest(projectRoot, config.manifest);
2092
+ const index = buildManifestIndex(manifest);
2093
+ const results = [];
2094
+ const pendingByConfigHash = /* @__PURE__ */ new Map();
2095
+ const finalDiskPathsForBudget = [];
2096
+ let manifestDirty = false;
2097
+ const filesToStage = [];
2098
+ for (const file of scannedFiles) {
2099
+ const diskSha256 = await sha256File(file.absPath);
2100
+ const existingEntry = findEntryForDiskPath(index, file.relPath);
2101
+ const effectiveOpt = resolveEffectiveOptimization(config, file.relPath);
2102
+ if (options.concurrency !== void 0) {
2103
+ effectiveOpt.concurrency = options.concurrency;
2104
+ }
2105
+ const configHash = computeOptimizationConfigHash(effectiveOpt);
2106
+ if (existingEntry && existingEntry.optimizedSha256 === diskSha256) {
2107
+ if (!options.force && existingEntry.configHash === configHash) {
2108
+ results.push({
2109
+ sourcePath: existingEntry.sourcePath,
2110
+ outputPath: existingEntry.outputPath,
2111
+ status: "skipped-cached",
2112
+ originalBytes: existingEntry.originalBytes,
2113
+ optimizedBytes: file.byteSize,
2114
+ savedBytes: Math.max(0, existingEntry.originalBytes - file.byteSize),
2115
+ savedPercent: existingEntry.originalBytes > 0 ? (existingEntry.originalBytes - file.byteSize) / existingEntry.originalBytes * 100 : 0,
2116
+ format: existingEntry.format,
2117
+ qualityScore: existingEntry.qualityScore,
2118
+ backupPath: existingEntry.backupPath
2119
+ });
2120
+ finalDiskPathsForBudget.push(file.absPath);
2121
+ continue;
2122
+ }
2123
+ const backupRel = existingEntry.backupPath ?? getBackupRelPath(config.backup.dir, existingEntry.sourcePath);
2124
+ const backupCheck = await hasValidBackup({
2125
+ projectRoot,
2126
+ backupRelPath: config.backup.enabled ? backupRel : void 0,
2127
+ expectedSha256: existingEntry.originalSha256
2128
+ });
2129
+ if (backupCheck.exists && backupCheck.absPath) {
2130
+ const backupStat = await import_promises8.default.stat(backupCheck.absPath);
2131
+ const group2 = pendingByConfigHash.get(configHash) ?? {
2132
+ opt: effectiveOpt,
2133
+ tasks: []
2134
+ };
2135
+ group2.tasks.push({
2136
+ scanned: file,
2137
+ diskSha256,
2138
+ effectiveOpt,
2139
+ configHash,
2140
+ existingEntry,
2141
+ sourceFileToOptimize: backupCheck.absPath,
2142
+ isReoptimizeFromBackup: true,
2143
+ originalSha256: existingEntry.originalSha256,
2144
+ originalBytes: backupStat.size,
2145
+ canonicalSourcePath: existingEntry.sourcePath
2146
+ });
2147
+ pendingByConfigHash.set(configHash, group2);
2148
+ continue;
2149
+ }
2150
+ if (!options.force && !options.reprocessOnConfigChange) {
2151
+ results.push({
2152
+ sourcePath: existingEntry.sourcePath,
2153
+ outputPath: existingEntry.outputPath,
2154
+ status: "skipped-config-changed-no-backup",
2155
+ originalBytes: existingEntry.originalBytes,
2156
+ optimizedBytes: file.byteSize,
2157
+ savedBytes: Math.max(0, existingEntry.originalBytes - file.byteSize),
2158
+ savedPercent: 0,
2159
+ format: existingEntry.format,
2160
+ qualityScore: existingEntry.qualityScore,
2161
+ backupPath: existingEntry.backupPath
2162
+ });
2163
+ finalDiskPathsForBudget.push(file.absPath);
2164
+ continue;
2165
+ }
2166
+ }
2167
+ if (file.byteSize < effectiveOpt.minBytes && !options.force) {
2168
+ results.push({
2169
+ sourcePath: file.relPath,
2170
+ outputPath: file.relPath,
2171
+ status: "skipped-small",
2172
+ originalBytes: file.byteSize,
2173
+ optimizedBytes: file.byteSize,
2174
+ savedBytes: 0,
2175
+ savedPercent: 0
2176
+ });
2177
+ finalDiskPathsForBudget.push(file.absPath);
2178
+ continue;
2179
+ }
2180
+ const group = pendingByConfigHash.get(configHash) ?? {
2181
+ opt: effectiveOpt,
2182
+ tasks: []
2183
+ };
2184
+ group.tasks.push({
2185
+ scanned: file,
2186
+ diskSha256,
2187
+ effectiveOpt,
2188
+ configHash,
2189
+ existingEntry,
2190
+ sourceFileToOptimize: file.absPath,
2191
+ isReoptimizeFromBackup: false,
2192
+ originalSha256: diskSha256,
2193
+ originalBytes: file.byteSize,
2194
+ canonicalSourcePath: file.relPath
2195
+ });
2196
+ pendingByConfigHash.set(configHash, group);
2197
+ }
2198
+ for (const [, group] of pendingByConfigHash) {
2199
+ const taskByRel = /* @__PURE__ */ new Map();
2200
+ const batchTasks = group.tasks.map((task) => {
2201
+ const batchRelPath = task.isReoptimizeFromBackup ? task.canonicalSourcePath : task.scanned.relPath;
2202
+ taskByRel.set(batchRelPath, task);
2203
+ return {
2204
+ relPath: batchRelPath,
2205
+ sourceFileToOptimize: task.sourceFileToOptimize
2206
+ };
2207
+ });
2208
+ await runImgoptBatch({
2209
+ binPath: cliInfo.binPath,
2210
+ tasks: batchTasks,
2211
+ optimization: group.opt,
2212
+ onEachStagedResult: async (outcomes) => {
2213
+ for (const outcome of outcomes) {
2214
+ const task = taskByRel.get(outcome.relPath);
2215
+ if (!task) continue;
2216
+ if (outcome.error || !outcome.stagedOutputPath) {
2217
+ results.push({
2218
+ sourcePath: task.canonicalSourcePath,
2219
+ outputPath: task.scanned.relPath,
2220
+ status: "failed",
2221
+ originalBytes: task.originalBytes,
2222
+ optimizedBytes: task.scanned.byteSize,
2223
+ savedBytes: 0,
2224
+ savedPercent: 0,
2225
+ error: outcome.error ?? "Unknown optimization error"
2226
+ });
2227
+ continue;
2228
+ }
2229
+ const stagedStat = await import_promises8.default.stat(outcome.stagedOutputPath);
2230
+ const optimizedBytes = stagedStat.size;
2231
+ const formatChanged = outcome.projectOutputRelPath !== task.scanned.relPath;
2232
+ const { savedBytes: savedBytes2, savedPercent: savedPercent2 } = computeSavings(
2233
+ task.originalBytes,
2234
+ optimizedBytes
2235
+ );
2236
+ const shouldRejectSmallSavings = !task.isReoptimizeFromBackup && !formatChanged && (optimizedBytes >= task.scanned.byteSize || savedPercent2 < task.effectiveOpt.minSavingsPercent);
2237
+ if (shouldRejectSmallSavings) {
2238
+ if (!dryRun) {
2239
+ manifest.entries[task.canonicalSourcePath] = {
2240
+ sourcePath: task.canonicalSourcePath,
2241
+ outputPath: task.scanned.relPath,
2242
+ originalSha256: task.originalSha256,
2243
+ optimizedSha256: task.diskSha256,
2244
+ configHash: task.configHash,
2245
+ originalBytes: task.originalBytes,
2246
+ optimizedBytes: task.scanned.byteSize,
2247
+ format: outcome.format,
2248
+ qualityScore: outcome.qualityScore,
2249
+ backupPath: task.existingEntry?.backupPath,
2250
+ status: "unchanged",
2251
+ cliVersion: cliInfo.tag,
2252
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2253
+ };
2254
+ manifestDirty = true;
2255
+ }
2256
+ results.push({
2257
+ sourcePath: task.canonicalSourcePath,
2258
+ outputPath: task.scanned.relPath,
2259
+ status: "skipped-no-savings",
2260
+ originalBytes: task.originalBytes,
2261
+ optimizedBytes: task.scanned.byteSize,
2262
+ savedBytes: 0,
2263
+ savedPercent: 0,
2264
+ format: outcome.format,
2265
+ qualityScore: outcome.qualityScore
2266
+ });
2267
+ finalDiskPathsForBudget.push(task.scanned.absPath);
2268
+ continue;
2269
+ }
2270
+ const destRelPath = outcome.projectOutputRelPath;
2271
+ const destAbsPath = resolveInsideRoot(projectRoot, destRelPath);
2272
+ let backupRelPath = task.existingEntry?.backupPath;
2273
+ if (!dryRun) {
2274
+ if (config.backup.enabled && !task.isReoptimizeFromBackup) {
2275
+ backupRelPath = await ensureOriginalBackup({
2276
+ projectRoot,
2277
+ backupConfig: config.backup,
2278
+ sourceRelPath: task.canonicalSourcePath,
2279
+ sourceAbsPath: task.scanned.absPath,
2280
+ isNewSourceVersion: true
2281
+ });
2282
+ if (backupRelPath) {
2283
+ filesToStage.push(backupRelPath);
2284
+ }
2285
+ }
2286
+ await atomicCopyFile(outcome.stagedOutputPath, destAbsPath);
2287
+ if (formatChanged && task.effectiveOpt.removeSourceOnFormatChange && task.scanned.absPath !== destAbsPath) {
2288
+ await import_promises8.default.rm(task.scanned.absPath, { force: true });
2289
+ filesToStage.push(task.scanned.relPath);
2290
+ }
2291
+ const optimizedSha256 = await sha256File(destAbsPath);
2292
+ if (task.existingEntry && task.existingEntry.sourcePath !== task.canonicalSourcePath) {
2293
+ delete manifest.entries[task.existingEntry.sourcePath];
2294
+ }
2295
+ manifest.entries[task.canonicalSourcePath] = {
2296
+ sourcePath: task.canonicalSourcePath,
2297
+ outputPath: destRelPath,
2298
+ originalSha256: task.originalSha256,
2299
+ optimizedSha256,
2300
+ configHash: task.configHash,
2301
+ originalBytes: task.originalBytes,
2302
+ optimizedBytes,
2303
+ format: outcome.format,
2304
+ qualityScore: outcome.qualityScore,
2305
+ backupPath: backupRelPath,
2306
+ status: "optimized",
2307
+ cliVersion: cliInfo.tag,
2308
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2309
+ };
2310
+ manifestDirty = true;
2311
+ filesToStage.push(destRelPath);
2312
+ finalDiskPathsForBudget.push(destAbsPath);
2313
+ }
2314
+ results.push({
2315
+ sourcePath: task.canonicalSourcePath,
2316
+ outputPath: destRelPath,
2317
+ status: task.isReoptimizeFromBackup ? "reoptimized-from-backup" : "optimized",
2318
+ originalBytes: task.originalBytes,
2319
+ optimizedBytes,
2320
+ savedBytes: savedBytes2,
2321
+ savedPercent: savedPercent2,
2322
+ format: outcome.format,
2323
+ qualityScore: outcome.qualityScore,
2324
+ backupPath: backupRelPath
2325
+ });
2326
+ }
2327
+ }
2328
+ });
2329
+ }
2330
+ if (manifestDirty && !dryRun) {
2331
+ await saveManifest(projectRoot, config.manifest, manifest);
2332
+ filesToStage.push(config.manifest);
2333
+ }
2334
+ if (options.staged && !dryRun && filesToStage.length > 0) {
2335
+ await gitAddFiles(projectRoot, [...new Set(filesToStage)]);
2336
+ }
2337
+ const budgetWarnings = await evaluateBudgets(
2338
+ config,
2339
+ cliInfo.binPath,
2340
+ projectRoot,
2341
+ dryRun ? [] : finalDiskPathsForBudget,
2342
+ results
2343
+ );
2344
+ results.sort((a, b) => a.sourcePath.localeCompare(b.sourcePath));
2345
+ let optimized = 0;
2346
+ let reoptimizedFromBackup = 0;
2347
+ let skippedCached = 0;
2348
+ let skippedSmall = 0;
2349
+ let skippedNoSavings = 0;
2350
+ let skippedConfigChangedNoBackup = 0;
2351
+ let failed = 0;
2352
+ let totalOriginalBytes = 0;
2353
+ let totalOptimizedBytes = 0;
2354
+ for (const item of results) {
2355
+ totalOriginalBytes += item.originalBytes;
2356
+ totalOptimizedBytes += item.optimizedBytes;
2357
+ switch (item.status) {
2358
+ case "optimized":
2359
+ optimized += 1;
2360
+ break;
2361
+ case "reoptimized-from-backup":
2362
+ reoptimizedFromBackup += 1;
2363
+ break;
2364
+ case "skipped-cached":
2365
+ skippedCached += 1;
2366
+ break;
2367
+ case "skipped-small":
2368
+ skippedSmall += 1;
2369
+ break;
2370
+ case "skipped-no-savings":
2371
+ skippedNoSavings += 1;
2372
+ break;
2373
+ case "skipped-config-changed-no-backup":
2374
+ skippedConfigChangedNoBackup += 1;
2375
+ break;
2376
+ case "failed":
2377
+ failed += 1;
2378
+ break;
2379
+ }
2380
+ }
2381
+ const { savedBytes, savedPercent } = computeSavings(
2382
+ totalOriginalBytes,
2383
+ totalOptimizedBytes
2384
+ );
2385
+ return {
2386
+ summary: {
2387
+ totalScanned: scannedFiles.length,
2388
+ optimized,
2389
+ reoptimizedFromBackup,
2390
+ skippedCached,
2391
+ skippedSmall,
2392
+ skippedNoSavings,
2393
+ skippedConfigChangedNoBackup,
2394
+ failed,
2395
+ originalBytes: totalOriginalBytes,
2396
+ optimizedBytes: totalOptimizedBytes,
2397
+ savedBytes,
2398
+ savedPercent,
2399
+ elapsedMs: Date.now() - startMs,
2400
+ dryRun,
2401
+ cliVersion: cliInfo.tag
2402
+ },
2403
+ items: results,
2404
+ budgetWarnings
2405
+ };
2406
+ }
2407
+ async function evaluateBudgets(config, binPath, projectRoot, diskAbsPaths, results) {
2408
+ const budgets = config.budgets;
2409
+ if (!budgets) return [];
2410
+ const violations = [];
2411
+ if (budgets.maxFileSizeKb !== void 0) {
2412
+ const limitBytes = budgets.maxFileSizeKb * 1024;
2413
+ if (results) {
2414
+ for (const item of results) {
2415
+ if (item.status !== "failed" && item.optimizedBytes > limitBytes) {
2416
+ violations.push({
2417
+ path: item.outputPath,
2418
+ rule: "maxFileSizeKb",
2419
+ actual: Number((item.optimizedBytes / 1024).toFixed(1)),
2420
+ limit: budgets.maxFileSizeKb
2421
+ });
2422
+ }
2423
+ }
2424
+ } else {
2425
+ for (const absPath of diskAbsPaths) {
2426
+ try {
2427
+ const stat = await import_promises8.default.stat(absPath);
2428
+ if (stat.size > limitBytes) {
2429
+ violations.push({
2430
+ path: import_node_path11.default.relative(projectRoot, absPath).split(import_node_path11.default.sep).join("/"),
2431
+ rule: "maxFileSizeKb",
2432
+ actual: Number((stat.size / 1024).toFixed(1)),
2433
+ limit: budgets.maxFileSizeKb
2434
+ });
2435
+ }
2436
+ } catch {
2437
+ }
2438
+ }
2439
+ }
2440
+ }
2441
+ if (binPath && (budgets.maxWidth !== void 0 || budgets.maxHeight !== void 0) && diskAbsPaths.length > 0) {
2442
+ const inspected = await inspectImagesWithImgopt(binPath, diskAbsPaths);
2443
+ for (const [absPath, info] of inspected) {
2444
+ const rel = import_node_path11.default.relative(projectRoot, absPath).split(import_node_path11.default.sep).join("/");
2445
+ if (budgets.maxWidth !== void 0 && info.dimensions && info.dimensions.width > budgets.maxWidth) {
2446
+ violations.push({
2447
+ path: rel,
2448
+ rule: "maxWidth",
2449
+ actual: info.dimensions.width,
2450
+ limit: budgets.maxWidth
2451
+ });
2452
+ }
2453
+ if (budgets.maxHeight !== void 0 && info.dimensions && info.dimensions.height > budgets.maxHeight) {
2454
+ violations.push({
2455
+ path: rel,
2456
+ rule: "maxHeight",
2457
+ actual: info.dimensions.height,
2458
+ limit: budgets.maxHeight
2459
+ });
2460
+ }
2461
+ }
2462
+ }
2463
+ return violations;
2464
+ }
2465
+
2466
+ // src/commands/check.ts
2467
+ async function checkProject(options = {}) {
2468
+ const { projectRoot, config } = await loadConfig(
2469
+ options.projectRoot,
2470
+ options.configPath
2471
+ );
2472
+ const scanned = await scanProjectImages(projectRoot, config);
2473
+ const manifest = await loadManifest(projectRoot, config.manifest);
2474
+ const index = buildManifestIndex(manifest);
2475
+ const pending = [];
2476
+ let upToDate = 0;
2477
+ for (const file of scanned) {
2478
+ const effectiveOpt = resolveEffectiveOptimization(config, file.relPath);
2479
+ if (file.byteSize < effectiveOpt.minBytes) {
2480
+ upToDate += 1;
2481
+ continue;
2482
+ }
2483
+ const diskSha = await sha256File(file.absPath);
2484
+ const entry = findEntryForDiskPath(index, file.relPath);
2485
+ const configHash = computeOptimizationConfigHash(effectiveOpt);
2486
+ if (entry && entry.optimizedSha256 === diskSha) {
2487
+ if (entry.configHash === configHash) {
2488
+ upToDate += 1;
2489
+ continue;
2490
+ }
2491
+ const backupCheck = await hasValidBackup({
2492
+ projectRoot,
2493
+ backupRelPath: config.backup.enabled ? entry.backupPath ?? getBackupRelPath(config.backup.dir, entry.sourcePath) : void 0,
2494
+ expectedSha256: entry.originalSha256
2495
+ });
2496
+ if (backupCheck.exists) {
2497
+ pending.push({
2498
+ path: file.relPath,
2499
+ reason: "config-changed-with-backup",
2500
+ bytes: file.byteSize
2501
+ });
2502
+ } else {
2503
+ upToDate += 1;
2504
+ }
2505
+ continue;
2506
+ }
2507
+ pending.push({
2508
+ path: file.relPath,
2509
+ reason: "new-or-modified",
2510
+ bytes: file.byteSize
2511
+ });
2512
+ }
2513
+ let binPath = null;
2514
+ const needsDimensionInspect = Boolean(
2515
+ config.budgets && (config.budgets.maxWidth !== void 0 || config.budgets.maxHeight !== void 0)
2516
+ );
2517
+ if (needsDimensionInspect || options.checkDimensions) {
2518
+ try {
2519
+ const cliInfo = await ensureCli({ cliConfig: config.cli });
2520
+ binPath = cliInfo.binPath;
2521
+ } catch {
2522
+ binPath = null;
2523
+ }
2524
+ }
2525
+ const budgetViolations = await evaluateBudgets(
2526
+ config,
2527
+ binPath,
2528
+ projectRoot,
2529
+ scanned.map((s) => s.absPath)
2530
+ );
2531
+ return {
2532
+ ok: pending.length === 0 && budgetViolations.length === 0,
2533
+ totalScanned: scanned.length,
2534
+ upToDate,
2535
+ pending,
2536
+ budgetViolations
2537
+ };
2538
+ }
2539
+
2540
+ // src/commands/restore.ts
2541
+ var import_promises9 = __toESM(require("fs/promises"), 1);
2542
+ var import_picomatch3 = __toESM(require("picomatch"), 1);
2543
+ async function restoreOriginals(options = {}) {
2544
+ const { projectRoot, config } = await loadConfig(
2545
+ options.projectRoot,
2546
+ options.configPath
2547
+ );
2548
+ const dryRun = Boolean(options.dryRun);
2549
+ const patterns = (options.patterns ?? []).map(
2550
+ (p) => toPosixPath(p.trim()).replace(/^\.\//, "")
2551
+ );
2552
+ if (!options.all && patterns.length === 0) {
2553
+ throw new Error(
2554
+ "Specify file path/glob patterns to restore, or pass --all to restore all backed-up originals."
2555
+ );
2556
+ }
2557
+ const manifest = await loadManifest(projectRoot, config.manifest);
2558
+ const backupFiles = await listBackupFiles(projectRoot, config.backup.dir);
2559
+ const candidateSourcePaths = /* @__PURE__ */ new Set([
2560
+ ...Object.keys(manifest.entries),
2561
+ ...backupFiles.map((b) => b.sourceRelPath)
2562
+ ]);
2563
+ const matcher = patterns.length > 0 ? (0, import_picomatch3.default)(patterns, { dot: true, nocase: true }) : () => true;
2564
+ const items = [];
2565
+ let manifestDirty = false;
2566
+ for (const sourcePath of [...candidateSourcePaths].sort()) {
2567
+ if (!options.all && !matcher(sourcePath)) {
2568
+ continue;
2569
+ }
2570
+ const entry = manifest.entries[sourcePath];
2571
+ const backupRelPath = entry?.backupPath ?? getBackupRelPath(config.backup.dir, sourcePath);
2572
+ const backupAbsPath = resolveInsideRoot(projectRoot, backupRelPath);
2573
+ if (!await isFile(backupAbsPath)) {
2574
+ items.push({
2575
+ sourcePath,
2576
+ backupPath: backupRelPath,
2577
+ restoredBytes: 0,
2578
+ status: "missing-backup"
2579
+ });
2580
+ continue;
2581
+ }
2582
+ const backupStat = await import_promises9.default.stat(backupAbsPath);
2583
+ const destAbsPath = resolveInsideRoot(projectRoot, sourcePath);
2584
+ let removedOutputPath;
2585
+ if (entry && entry.outputPath !== sourcePath) {
2586
+ const convertedAbsPath = resolveInsideRoot(projectRoot, entry.outputPath);
2587
+ if (await fileExists(convertedAbsPath)) {
2588
+ removedOutputPath = entry.outputPath;
2589
+ }
2590
+ }
2591
+ if (!dryRun) {
2592
+ await atomicCopyFile(backupAbsPath, destAbsPath);
2593
+ if (removedOutputPath) {
2594
+ await import_promises9.default.rm(resolveInsideRoot(projectRoot, removedOutputPath), {
2595
+ force: true
2596
+ });
2597
+ }
2598
+ if (options.deleteBackup) {
2599
+ await import_promises9.default.rm(backupAbsPath, { force: true });
2600
+ }
2601
+ if (entry) {
2602
+ delete manifest.entries[sourcePath];
2603
+ manifestDirty = true;
2604
+ }
2605
+ }
2606
+ items.push({
2607
+ sourcePath,
2608
+ backupPath: backupRelPath,
2609
+ removedOutputPath,
2610
+ restoredBytes: backupStat.size,
2611
+ status: "restored"
2612
+ });
2613
+ }
2614
+ if (manifestDirty && !dryRun) {
2615
+ await saveManifest(projectRoot, config.manifest, manifest);
2616
+ }
2617
+ return {
2618
+ dryRun,
2619
+ restoredCount: items.filter((i) => i.status === "restored").length,
2620
+ missingCount: items.filter((i) => i.status === "missing-backup").length,
2621
+ items
2622
+ };
2623
+ }
2624
+
2625
+ // src/commands/clean.ts
2626
+ var import_promises10 = __toESM(require("fs/promises"), 1);
2627
+ var import_node_path12 = __toESM(require("path"), 1);
2628
+ async function cleanProject(options = {}) {
2629
+ const { projectRoot, config } = await loadConfig(
2630
+ options.projectRoot,
2631
+ options.configPath
2632
+ );
2633
+ const dryRun = Boolean(options.dryRun);
2634
+ const manifest = await loadManifest(projectRoot, config.manifest);
2635
+ const backups = await listBackupFiles(projectRoot, config.backup.dir);
2636
+ const removedBackups = [];
2637
+ const removedManifestEntries = [];
2638
+ const removedCacheVersions = [];
2639
+ let reclaimedBytes = 0;
2640
+ for (const backup of backups) {
2641
+ const sourceAbs = resolveInsideRoot(projectRoot, backup.sourceRelPath);
2642
+ const entry = manifest.entries[backup.sourceRelPath];
2643
+ const outputExists = entry ? await fileExists(resolveInsideRoot(projectRoot, entry.outputPath)) : false;
2644
+ const sourceExists = await fileExists(sourceAbs);
2645
+ if (!sourceExists && !outputExists) {
2646
+ const stat = await import_promises10.default.stat(backup.absPath);
2647
+ reclaimedBytes += stat.size;
2648
+ removedBackups.push(backup.backupRelPath);
2649
+ if (!dryRun) {
2650
+ await import_promises10.default.rm(backup.absPath, { force: true });
2651
+ }
2652
+ }
2653
+ }
2654
+ let manifestDirty = false;
2655
+ for (const [key, entry] of Object.entries(manifest.entries)) {
2656
+ const sourceExists = await fileExists(
2657
+ resolveInsideRoot(projectRoot, entry.sourcePath)
2658
+ );
2659
+ const outputExists = await fileExists(
2660
+ resolveInsideRoot(projectRoot, entry.outputPath)
2661
+ );
2662
+ if (!sourceExists && !outputExists) {
2663
+ removedManifestEntries.push(key);
2664
+ if (!dryRun) {
2665
+ delete manifest.entries[key];
2666
+ manifestDirty = true;
2667
+ }
2668
+ }
2669
+ }
2670
+ if (manifestDirty && !dryRun) {
2671
+ await saveManifest(projectRoot, config.manifest, manifest);
2672
+ }
2673
+ if (options.cache) {
2674
+ const cacheDir = resolveCacheDir(config.cli);
2675
+ const cachedVersions = await listCachedVersions(cacheDir);
2676
+ const status = await getCliStatus(config.cli, false);
2677
+ const keepVersion = status.installedTag ?? status.installedVersion;
2678
+ for (const ver of cachedVersions) {
2679
+ if (keepVersion && ver === keepVersion) continue;
2680
+ const verDir = import_node_path12.default.join(cacheDir, ver);
2681
+ removedCacheVersions.push(ver);
2682
+ if (!dryRun) {
2683
+ await import_promises10.default.rm(verDir, { recursive: true, force: true });
2684
+ }
2685
+ }
2686
+ }
2687
+ return {
2688
+ dryRun,
2689
+ removedBackups,
2690
+ removedManifestEntries,
2691
+ removedCacheVersions,
2692
+ reclaimedBytes
2693
+ };
2694
+ }
2695
+
2696
+ // src/commands/doctor.ts
2697
+ var import_promises11 = __toESM(require("fs/promises"), 1);
2698
+ var import_node_path13 = __toESM(require("path"), 1);
2699
+ async function doctorProject(options = {}) {
2700
+ const checks = [];
2701
+ const projectRoot = import_node_path13.default.resolve(options.projectRoot ?? process.cwd());
2702
+ let loaded;
2703
+ try {
2704
+ loaded = await loadConfig(projectRoot, options.configPath);
2705
+ checks.push({
2706
+ name: "config",
2707
+ status: "ok",
2708
+ message: `Valid config loaded from ${import_node_path13.default.relative(projectRoot, loaded.configPath) || loaded.configPath}`
2709
+ });
2710
+ } catch (err) {
2711
+ checks.push({
2712
+ name: "config",
2713
+ status: "error",
2714
+ message: err instanceof Error ? err.message : String(err)
2715
+ });
2716
+ return { ok: false, checks };
2717
+ }
2718
+ const { config } = loaded;
2719
+ let existingTargetCount = 0;
2720
+ for (const target of config.targets) {
2721
+ const abs = resolveInsideRoot(projectRoot, target.dir);
2722
+ if (await isDirectory(abs)) {
2723
+ existingTargetCount += 1;
2724
+ } else {
2725
+ checks.push({
2726
+ name: `target:${target.dir}`,
2727
+ status: "warn",
2728
+ message: `Target directory "${target.dir}" does not exist on disk`
2729
+ });
2730
+ }
2731
+ }
2732
+ if (existingTargetCount > 0) {
2733
+ checks.push({
2734
+ name: "targets",
2735
+ status: "ok",
2736
+ message: `${existingTargetCount}/${config.targets.length} target directory(ies) present`
2737
+ });
2738
+ }
2739
+ const cliStatus = await getCliStatus(config.cli, options.checkRemote ?? true);
2740
+ if (cliStatus.resolvedBinPath && cliStatus.installedVersion) {
2741
+ const displayTag = cliStatus.installedTag ?? cliStatus.installedVersion;
2742
+ if (cliStatus.updateAvailable && cliStatus.latestRemoteVersion) {
2743
+ checks.push({
2744
+ name: "cli-binary",
2745
+ status: "warn",
2746
+ message: `Installed imgopt ${displayTag} (${cliStatus.source}); newer release ${cliStatus.latestRemoteVersion} available`
2747
+ });
2748
+ } else {
2749
+ checks.push({
2750
+ name: "cli-binary",
2751
+ status: "ok",
2752
+ message: `imgopt ${displayTag} ready (${cliStatus.source}: ${cliStatus.resolvedBinPath})`
2753
+ });
2754
+ }
2755
+ } else {
2756
+ checks.push({
2757
+ name: "cli-binary",
2758
+ status: config.cli.autoDownload ? "warn" : "error",
2759
+ message: config.cli.autoDownload ? `imgopt not downloaded yet; will auto-download ${cliStatus.configuredVersion} on first optimize run` : "imgopt binary not found and cli.autoDownload is false"
2760
+ });
2761
+ }
2762
+ try {
2763
+ const manifest = await loadManifest(projectRoot, config.manifest);
2764
+ const entryCount = Object.keys(manifest.entries).length;
2765
+ checks.push({
2766
+ name: "manifest",
2767
+ status: "ok",
2768
+ message: `Manifest valid (${entryCount} tracked asset(s))`
2769
+ });
2770
+ if (config.backup.enabled) {
2771
+ const backups = await listBackupFiles(projectRoot, config.backup.dir);
2772
+ let orphanCount = 0;
2773
+ for (const b of backups) {
2774
+ const entry = manifest.entries[b.sourceRelPath];
2775
+ const srcExists = await fileExists(
2776
+ resolveInsideRoot(projectRoot, b.sourceRelPath)
2777
+ );
2778
+ const outExists = entry ? await fileExists(resolveInsideRoot(projectRoot, entry.outputPath)) : false;
2779
+ if (!srcExists && !outExists) orphanCount += 1;
2780
+ }
2781
+ if (orphanCount > 0) {
2782
+ checks.push({
2783
+ name: "backups",
2784
+ status: "warn",
2785
+ message: `${backups.length} backup(s) in ${config.backup.dir}; ${orphanCount} orphan(s) can be cleaned via "imgopt-node clean"`
2786
+ });
2787
+ } else {
2788
+ checks.push({
2789
+ name: "backups",
2790
+ status: "ok",
2791
+ message: `Originals backup enabled (${config.backup.dir}, ${backups.length} file(s))`
2792
+ });
2793
+ }
2794
+ } else {
2795
+ checks.push({
2796
+ name: "backups",
2797
+ status: "warn",
2798
+ message: "Original image backup is disabled (backup.enabled = false)"
2799
+ });
2800
+ }
2801
+ } catch (err) {
2802
+ checks.push({
2803
+ name: "manifest",
2804
+ status: "error",
2805
+ message: err instanceof Error ? err.message : String(err)
2806
+ });
2807
+ }
2808
+ const gitignorePath = import_node_path13.default.join(projectRoot, ".gitignore");
2809
+ if (await fileExists(gitignorePath)) {
2810
+ const content = await import_promises11.default.readFile(gitignorePath, "utf8");
2811
+ const dirNorm = config.backup.dir.replace(/\/+$/, "");
2812
+ const ignored = content.includes(dirNorm) || content.includes(".imgopt/");
2813
+ checks.push({
2814
+ name: "gitignore",
2815
+ status: "ok",
2816
+ message: ignored ? `Backup directory (${dirNorm}) is listed in .gitignore` : `Backup directory (${dirNorm}) is tracked by Git (team-shared backups)`
2817
+ });
2818
+ }
2819
+ return {
2820
+ ok: checks.every((c) => c.status !== "error"),
2821
+ checks
2822
+ };
2823
+ }
2824
+
2825
+ // src/commands/inspect.ts
2826
+ async function inspectProject(options = {}) {
2827
+ const { projectRoot, config } = await loadConfig(
2828
+ options.projectRoot,
2829
+ options.configPath
2830
+ );
2831
+ const cliInfo = await ensureCli({ cliConfig: config.cli });
2832
+ let pathsToInspect;
2833
+ if (options.targetPath) {
2834
+ pathsToInspect = [resolveInsideRoot(projectRoot, options.targetPath)];
2835
+ } else {
2836
+ const scanned = await scanProjectImages(projectRoot, config);
2837
+ pathsToInspect = scanned.map((s) => s.absPath);
2838
+ }
2839
+ const inspected = await inspectImagesWithImgopt(
2840
+ cliInfo.binPath,
2841
+ pathsToInspect
2842
+ );
2843
+ return [...inspected.values()];
2844
+ }
2845
+ // Annotate the CommonJS export names for ESM import in node:
2846
+ 0 && (module.exports = {
2847
+ CANDIDATE_ASSET_DIRS,
2848
+ CONFIG_FILENAMES,
2849
+ DEFAULT_BACKUP_CONFIG,
2850
+ DEFAULT_BACKUP_DIR,
2851
+ DEFAULT_CLI_CONFIG,
2852
+ DEFAULT_CLI_REPO,
2853
+ DEFAULT_CLI_VERSION,
2854
+ DEFAULT_CONFIG_FILENAME,
2855
+ DEFAULT_EXCLUDE_GLOBS,
2856
+ DEFAULT_INCLUDE_GLOBS,
2857
+ DEFAULT_MANIFEST_PATH,
2858
+ DEFAULT_OPTIMIZATION_OPTIONS,
2859
+ DEFAULT_SCHEMA_REF,
2860
+ IGNORED_DIR_NAMES,
2861
+ LATEST_CACHE_TTL_MS,
2862
+ SUPPORTED_IMAGE_EXTENSIONS,
2863
+ buildManifestIndex,
2864
+ checkProject,
2865
+ cleanProject,
2866
+ computeOptimizationConfigHash,
2867
+ createDefaultConfig,
2868
+ createEmptyManifest,
2869
+ detectProject,
2870
+ doctorProject,
2871
+ downloadCliRelease,
2872
+ ensureCli,
2873
+ ensureOriginalBackup,
2874
+ evaluateBudgets,
2875
+ fetchLatestReleaseTag,
2876
+ findConfigPath,
2877
+ findEntryForDiskPath,
2878
+ getBackupRelPath,
2879
+ getCliStatus,
2880
+ hasValidBackup,
2881
+ initProject,
2882
+ inspectProject,
2883
+ listBackupFiles,
2884
+ listCachedVersions,
2885
+ loadConfig,
2886
+ loadManifest,
2887
+ normalizeConfig,
2888
+ optimizeProject,
2889
+ probeBinaryVersion,
2890
+ resolveCacheDir,
2891
+ resolveEffectiveOptimization,
2892
+ resolveReleaseAsset,
2893
+ restoreOriginals,
2894
+ saveConfig,
2895
+ saveManifest,
2896
+ scanProjectImages,
2897
+ sha256Buffer,
2898
+ sha256File
2899
+ });