@kitschpatrol/aphex 0.1.6 → 0.3.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.js CHANGED
@@ -6,8 +6,8 @@ import { spawn } from "node:child_process";
6
6
  import { ExifTool } from "exiftool-vendored";
7
7
  import { createLogger, injectionHelper } from "lognow";
8
8
  import os from "node:os";
9
- import { slug } from "github-slugger";
10
9
  import { fileURLToPath } from "node:url";
10
+ import { slug } from "github-slugger";
11
11
  import { createDefu } from "defu";
12
12
  import { imageSizeFromFile } from "image-size/fromFile";
13
13
  import { lookup, mimes } from "mrmime";
@@ -36,10 +36,13 @@ function setLogger(logger) {
36
36
  * management to prevent hanging processes. The exiftool-vendored library spawns
37
37
  * persistent Perl processes that must be explicitly ended.
38
38
  */
39
- const exiftoolInstance = new ExifTool({
40
- maxProcs: 4,
41
- onIdleIntervalMillis: 1e3
42
- });
39
+ function createExiftool() {
40
+ return new ExifTool({
41
+ maxProcs: 4,
42
+ onIdleIntervalMillis: 1e3
43
+ });
44
+ }
45
+ let exiftoolInstance = createExiftool();
43
46
  let cleanupScheduled = false;
44
47
  let processExitHandlerInstalled = false;
45
48
  /**
@@ -47,13 +50,15 @@ let processExitHandlerInstalled = false;
47
50
  */
48
51
  function getExiftool() {
49
52
  scheduleProcessCleanup();
53
+ if (exiftoolInstance.ended) exiftoolInstance = createExiftool();
50
54
  return exiftoolInstance;
51
55
  }
52
56
  /**
53
57
  * End the exiftool process gracefully
54
58
  *
55
59
  * This should be called when you're done using exiftool to prevent hanging
56
- * processes. It's safe to call multiple times.
60
+ * processes. It's safe to call multiple times, and exiftool starts again the
61
+ * next time it's needed.
57
62
  */
58
63
  async function endExiftool() {
59
64
  if (exiftoolInstance.pids.length === 0) return;
@@ -193,7 +198,7 @@ function ensureArray(value) {
193
198
  return Array.isArray(value) ? value : [value];
194
199
  }
195
200
  /**
196
- * Ensure the length has a single item
201
+ * Assert that the array has exactly one element
197
202
  */
198
203
  function assertSingleElement(array) {
199
204
  if (array.length !== 1) throw new Error(`Expected array of length 1, got ${array.length}`);
@@ -216,7 +221,7 @@ function getPackageAssetsPath(meta) {
216
221
  return path.basename(dirname) === "dist" ? path.join(dirname, "assets") : path.join("src", "assets");
217
222
  }
218
223
  /**
219
- * Asset directory path of package or distribution folder (Copied by tsdown)
224
+ * Workers directory path of package or distribution folder (Copied by tsdown)
220
225
  */
221
226
  function getPackageWorkersPath(meta) {
222
227
  const dirname = getDirname(meta);
@@ -231,58 +236,80 @@ function getPackageBinPath(meta) {
231
236
  return path.basename(dirname) === "dist" ? path.join(dirname) : path.join("dist");
232
237
  }
233
238
  // src/aphex-swift/cli-bridge.ts
234
- const SHELL_SPECIAL_CHARS_REGEX = /[\s'"\\]/v;
239
+ const SHELL_SAFE_REGEX = /^[\w\-.\/:=+,%@]+$/v;
240
+ const SESSION_RESTART_EXIT_CODE = 75;
235
241
  let interactiveProcess;
236
242
  let currentRequest;
243
+ let commandQueue = [];
244
+ const stoppedProcesses = /* @__PURE__ */ new WeakSet();
237
245
  /**
238
246
  * Start an interactive session with aphex-swift. Commands will be sent to this
239
247
  * persistent process instead of spawning new ones.
240
248
  *
249
+ * If the process ends on its own after it has answered a command, or to get rid
250
+ * of a render that timed out, another one takes its place and carries on with
251
+ * the commands that were waiting.
252
+ *
241
253
  * @throws {Error} If the session is already active or fails to start
242
254
  */
243
255
  async function interactiveSessionStart() {
244
256
  if (interactiveProcess !== void 0) throw new Error("Interactive session is already active");
245
- const binPath = getPackageBinPath(import.meta);
246
- interactiveProcess = spawn("./aphex-swift", ["interactive"], {
247
- cwd: binPath,
257
+ spawnInteractiveProcess();
258
+ await new Promise((resolve) => {
259
+ setTimeout(resolve, 100);
260
+ });
261
+ }
262
+ function spawnInteractiveProcess() {
263
+ const child = spawn("./aphex-swift", ["interactive"], {
264
+ cwd: getPackageBinPath(import.meta),
248
265
  stdio: [
249
266
  "pipe",
250
267
  "pipe",
251
268
  "pipe"
252
269
  ]
253
270
  });
254
- interactiveProcess.stdout?.on("data", (data) => {
255
- if (currentRequest === void 0) return;
271
+ interactiveProcess = child;
272
+ let hasResponded = false;
273
+ child.stdin.on("error", () => void 0);
274
+ child.stdout.on("data", (data) => {
275
+ if (interactiveProcess !== child || currentRequest === void 0) return;
256
276
  currentRequest.buffer += data.toString();
257
277
  try {
258
278
  JSON.parse(currentRequest.buffer);
259
279
  const response = currentRequest.buffer;
260
280
  const request = currentRequest;
261
281
  currentRequest = void 0;
282
+ hasResponded = true;
262
283
  request.resolve(response);
263
284
  processNextCommand();
264
285
  } catch {}
265
286
  });
266
- interactiveProcess.stderr?.on("data", (data) => {
267
- if (currentRequest === void 0) return;
287
+ child.stderr.on("data", (data) => {
288
+ if (interactiveProcess !== child || currentRequest === void 0) return;
268
289
  const error = new Error(data.toString().trim());
269
290
  const request = currentRequest;
270
291
  currentRequest = void 0;
271
292
  request.reject(error);
272
293
  processNextCommand();
273
294
  });
274
- interactiveProcess.on("close", (code) => {
295
+ child.on("close", (code) => {
296
+ if (interactiveProcess !== child) return;
297
+ interactiveProcess = void 0;
298
+ const interrupted = currentRequest;
299
+ currentRequest = void 0;
275
300
  const error = /* @__PURE__ */ new Error(`Interactive session exited with code ${code}`);
276
- if (currentRequest !== void 0) {
277
- currentRequest.reject(error);
278
- currentRequest = void 0;
301
+ const restart = !stoppedProcesses.has(child) && (hasResponded || code === SESSION_RESTART_EXIT_CODE);
302
+ if (interrupted !== void 0) {
303
+ if (restart && code === SESSION_RESTART_EXIT_CODE) commandQueue.unshift(interrupted);
304
+ else interrupted.reject(error);
305
+ }
306
+ if (restart) {
307
+ spawnInteractiveProcess();
308
+ processNextCommand();
309
+ return;
279
310
  }
280
311
  for (const queued of commandQueue) queued.reject(error);
281
312
  commandQueue = [];
282
- interactiveProcess = void 0;
283
- });
284
- await new Promise((resolve) => {
285
- setTimeout(resolve, 100);
286
313
  });
287
314
  }
288
315
  /**
@@ -291,6 +318,7 @@ async function interactiveSessionStart() {
291
318
  async function interactiveSessionStop() {
292
319
  if (interactiveProcess === void 0) return;
293
320
  const processToStop = interactiveProcess;
321
+ stoppedProcesses.add(processToStop);
294
322
  processToStop.stdin?.write("exit\n");
295
323
  processToStop.stdin?.end();
296
324
  await new Promise((resolve) => {
@@ -313,14 +341,12 @@ async function interactiveSessionStop() {
313
341
  function isInteractiveSessionActive() {
314
342
  return interactiveProcess !== void 0;
315
343
  }
316
- let commandQueue = [];
317
344
  function processNextCommand() {
318
345
  if (currentRequest !== void 0 || interactiveProcess === void 0 || commandQueue.length === 0) return;
319
346
  const next = commandQueue.shift();
320
347
  currentRequest = {
321
- buffer: "",
322
- reject: next.reject,
323
- resolve: next.resolve
348
+ ...next,
349
+ buffer: ""
324
350
  };
325
351
  interactiveProcess.stdin?.write(next.command + "\n");
326
352
  }
@@ -340,10 +366,11 @@ async function executeInteractiveCommand(command) {
340
366
  }
341
367
  /**
342
368
  * Escape and join arguments into a single command string for interactive mode.
343
- * Arguments with spaces or special characters are quoted.
369
+ * Any argument that isn't plainly safe is wrapped in single quotes, which a
370
+ * shell takes literally.
344
371
  */
345
372
  function escapeCommand(args) {
346
- return args.map((arg) => SHELL_SPECIAL_CHARS_REGEX.test(arg) ? `'${arg.replaceAll("'", String.raw`'\''`)}'` : arg).join(" ");
373
+ return args.map((arg) => SHELL_SAFE_REGEX.test(arg) ? arg : `'${arg.replaceAll("'", String.raw`'\''`)}'`).join(" ");
347
374
  }
348
375
  /**
349
376
  * Runtime type guard for ResourceInfo
@@ -398,10 +425,16 @@ function assertAlbumInfoArray(value) {
398
425
  if (!isAlbumInfoArray(value)) throw new Error("Invalid AlbumInfo array");
399
426
  }
400
427
  /**
401
- * Get photo asset information for given identifiers (ID, filename, album name,
402
- * or photo path)
428
+ * Look up photos in the Photos.app library.
429
+ *
430
+ * @param identifiers Photo UUIDs, paths like `Album/Title` or
431
+ * `Album/IMG_1234.jpeg`, or album UUIDs and paths, which stand for every
432
+ * photo in the album.
433
+ * @param caseSensitive Whether titles, file names, and album paths have to
434
+ * match exactly.
403
435
  *
404
- * @throws {Error} If the command fails
436
+ * @returns One entry per photo found. Empty if no identifiers are passed.
437
+ * @throws {Error} If nothing matches, or the command fails.
405
438
  */
406
439
  async function aphexPhotoInfo(identifiers, caseSensitive = false) {
407
440
  const identifiersArray = ensureArray(identifiers);
@@ -423,9 +456,13 @@ async function aphexPhotoInfo(identifiers, caseSensitive = false) {
423
456
  }
424
457
  }
425
458
  /**
426
- * Get album info
459
+ * Look up albums in the Photos.app library.
427
460
  *
428
- * @throws {Error} If the command fails
461
+ * @param identifiers Album UUIDs, or paths like `Album` or `Folder/Album`.
462
+ * @param caseSensitive Whether album paths have to match exactly.
463
+ *
464
+ * @returns One entry per album found. Empty if no identifiers are passed.
465
+ * @throws {Error} If nothing matches, or the command fails.
429
466
  */
430
467
  async function aphexAlbumInfo(identifiers, caseSensitive = false) {
431
468
  const identifiersArray = ensureArray(identifiers);
@@ -446,12 +483,38 @@ async function aphexAlbumInfo(identifiers, caseSensitive = false) {
446
483
  throw new Error(`Error fetching album info: ${stdout}`);
447
484
  }
448
485
  }
486
+ const LEADING_HASH_REGEX = /^#/v;
487
+ function getRenderArguments(options) {
488
+ const { background, bitDepth, colorProfile, format, includeLocation, includeMetadata, maxHeight, maxWidth, preserveAlpha, quality } = options;
489
+ const canHoldAlpha = format === "png" || format === "tiff";
490
+ return [
491
+ "--format",
492
+ format,
493
+ ...colorProfile === void 0 ? [] : ["--color-profile", colorProfile],
494
+ ...quality !== void 0 && format === "jpeg" ? ["--quality", String(quality)] : [],
495
+ ...bitDepth !== void 0 && format === "tiff" ? ["--bit-depth", String(bitDepth)] : [],
496
+ ...maxWidth === void 0 ? [] : ["--max-width", String(Math.floor(maxWidth))],
497
+ ...maxHeight === void 0 ? [] : ["--max-height", String(Math.floor(maxHeight))],
498
+ ...includeMetadata === true ? ["--include-metadata"] : [],
499
+ ...includeLocation === true ? ["--include-location"] : [],
500
+ ...background === void 0 ? [] : ["--background", background.replace(LEADING_HASH_REGEX, "")],
501
+ ...preserveAlpha === true && background === void 0 && canHoldAlpha ? ["--preserve-alpha"] : []
502
+ ];
503
+ }
449
504
  /**
450
- * Export photos for given identifiers to a destination directory
505
+ * Export photos from the Photos.app library to a directory with aphex-swift.
506
+ *
507
+ * By default this copies the image stored in the library: the original, or for
508
+ * an edited photo, the edited image Photos.app saved.
509
+ *
510
+ * @param identifiers Photo or album identifiers, see `aphexPhotoInfo`.
511
+ * @param destination An existing directory.
451
512
  *
452
- * @throws {Error} If the command fails
513
+ * @returns The paths of the exported files.
514
+ * @throws {Error} If nothing could be exported, or the command fails.
453
515
  */
454
- async function aphexExport(identifiers, destination, caseSensitive = false, originals = false) {
516
+ async function aphexExport(identifiers, destination, options = {}) {
517
+ const { caseSensitive = false, originals = false, render } = options;
455
518
  const identifiersArray = ensureArray(identifiers);
456
519
  if (identifiersArray.length === 0) return [];
457
520
  const args = [
@@ -460,7 +523,8 @@ async function aphexExport(identifiers, destination, caseSensitive = false, orig
460
523
  "--destination",
461
524
  destination,
462
525
  ...caseSensitive ? ["--case-sensitive"] : [],
463
- ...originals ? ["--originals"] : []
526
+ ...originals ? ["--originals"] : [],
527
+ ...render === void 0 ? [] : getRenderArguments(render)
464
528
  ];
465
529
  let stdout;
466
530
  if (isInteractiveSessionActive()) stdout = await executeInteractiveCommand(escapeCommand(args));
@@ -872,12 +936,22 @@ async function getImageDimensions(imagePath) {
872
936
  height
873
937
  };
874
938
  }
939
+ const RAW_MIME_TYPES = /* @__PURE__ */ new Set([
940
+ "arw",
941
+ "cr2",
942
+ "cr3",
943
+ "crw",
944
+ "dng",
945
+ "nef",
946
+ "pef"
947
+ ]);
875
948
  /**
876
- * Check if an image has an alpha channel
949
+ * Check if an image has transparency: an alpha channel in which at least one
950
+ * pixel is not fully opaque
877
951
  */
878
952
  async function hasAlpha(imagePath) {
879
953
  const mime = lookupImageMimeType(imagePath, true);
880
- if (mime === "jpeg") return false;
954
+ if (mime === "jpeg" || RAW_MIME_TYPES.has(mime)) return false;
881
955
  if (mime !== "psd" && mime !== "tiff") {
882
956
  const { stdout: channelOutput } = await execa("identify", [
883
957
  "-format",
@@ -911,16 +985,21 @@ function escapeForAppleScript(text) {
911
985
  return text.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"");
912
986
  }
913
987
  /**
914
- * Export a photo via AppleScript using the Photos app's scripting dictionary
988
+ * Export a photo with the `export` command of the Photos.app AppleScript
989
+ * dictionary.
990
+ *
991
+ * Photos.app decides what comes out: a JPEG it renders from the photo and its
992
+ * edits, or with `forceOriginal`, the original file as it was imported.
915
993
  *
916
994
  * @param photoUuid - UUID of the photo to export
917
- * @param forceOriginal - Whether to force export of original version
995
+ * @param forceOriginal - Whether to export the original file, ignoring edits
918
996
  *
919
- * @returns Promise<string> - Path to the exported file
997
+ * @returns The path of the exported file, in a new temporary directory. Move it
998
+ * and remove the directory afterwards.
920
999
  */
921
1000
  async function exportViaAppleScript(photoUuid, forceOriginal = false) {
922
1001
  const tempDirectory = await getTempDirectory("engine", "applescript");
923
- const exportFlag = forceOriginal ? "with originals" : "without originals";
1002
+ const exportFlag = forceOriginal ? "with using originals" : "without using originals";
924
1003
  const appleScript = `
925
1004
  tell application "Photos"
926
1005
  -- Find the media item by UUID
@@ -928,22 +1007,19 @@ async function exportViaAppleScript(photoUuid, forceOriginal = false) {
928
1007
 
929
1008
  -- Export the photo to temp directory
930
1009
  export {targetPhoto} to POSIX file "${escapeForAppleScript(tempDirectory)}" ${exportFlag}
931
-
932
- -- Get the exported file name
933
- set photoFilename to filename of targetPhoto
934
-
935
- -- Return the filename for path construction
936
- return photoFilename
937
1010
  end tell
938
1011
  `;
939
1012
  try {
940
- const { stdout } = await execa("osascript", ["-e", appleScript]);
941
- const exportedFileName = stdout.trim();
942
- return path.join(tempDirectory, exportedFileName);
1013
+ await execa("osascript", ["-e", appleScript]);
943
1014
  } catch (error) {
944
1015
  const errorMessage = error instanceof Error ? error.message : String(error);
945
1016
  throw new Error(`Failed to export photo via AppleScript: ${errorMessage}`, { cause: error });
946
1017
  }
1018
+ const entries = await fse.readdir(tempDirectory);
1019
+ const images = entries.filter((name) => lookupImageMimeType(name) !== void 0);
1020
+ const [exportedFileName] = images;
1021
+ if (exportedFileName === void 0 || images.length > 1) throw new Error(`Expected the AppleScript export of photo "${photoUuid}" to produce one image, but found ${String(images.length)}: ${JSON.stringify(entries)}`);
1022
+ return path.join(tempDirectory, exportedFileName);
947
1023
  }
948
1024
  // src/pipeline/engines/applescript-gui.ts
949
1025
  /** Apple's defaults, but these are overridden by Aphex by default */
@@ -962,40 +1038,50 @@ const defaultExportViaAppleScriptGuiOptions = {
962
1038
  tiffBitDepth: 8
963
1039
  };
964
1040
  /**
965
- * Export a photo via the Photos.app GUI to a temporary directory Clean up and
966
- * move the file as needed afterwards
1041
+ * Export a photo, or every photo in an album, through the Photos.app export
1042
+ * sheet, by automating its GUI with AppleScript.
1043
+ *
1044
+ * @returns The paths of the exported files, in a new temporary directory. Move
1045
+ * them and remove the directory afterwards.
967
1046
  */
968
1047
  async function exportViaAppleScriptGui(uuid, options) {
969
1048
  const tempDirectory = await getTempDirectory("engine", "applescript-gui");
970
1049
  const { colorProfile, fileName, includeLocation, includeMetadata, jpegQuality, maxSizeType, maxSizeValue, photoKind, photoSize, sequentialPrefix, subfolderFormat, tiffBitDepth } = mergeDefaults(options, defaultExportViaAppleScriptGuiOptions);
971
1050
  const appleScriptPath = path.join(getPackageAssetsPath(import.meta), "applescript-gui.applescript");
972
- const { failed, stderr } = await execa("osascript", [
973
- appleScriptPath,
974
- uuid,
975
- tempDirectory,
976
- photoKind,
977
- jpegQuality,
978
- tiffBitDepth.toString(),
979
- colorProfile,
980
- photoSize,
981
- maxSizeType,
982
- maxSizeValue.toString(),
983
- includeMetadata.toString(),
984
- includeLocation.toString(),
985
- fileName,
986
- sequentialPrefix,
987
- subfolderFormat
988
- ]);
989
- if (failed) throw new Error(`Error exporting album "${uuid}": ${stderr}`);
990
- const results = stderr.split("\n").filter((line) => line.trim() !== "");
991
- if (results.length === 0) throw new Error(`No photos exported for album "${uuid}"`);
992
- if (typeof results[0] !== "string") throw new TypeError(`Unexpected export results for album "${uuid}": ${JSON.stringify(results)}`);
1051
+ let stderr;
1052
+ try {
1053
+ stderr = (await execa("osascript", [
1054
+ appleScriptPath,
1055
+ uuid,
1056
+ tempDirectory,
1057
+ photoKind,
1058
+ jpegQuality,
1059
+ tiffBitDepth.toString(),
1060
+ colorProfile,
1061
+ photoSize,
1062
+ maxSizeType,
1063
+ maxSizeValue.toString(),
1064
+ includeMetadata.toString(),
1065
+ includeLocation.toString(),
1066
+ fileName,
1067
+ sequentialPrefix,
1068
+ subfolderFormat
1069
+ ])).stderr;
1070
+ } catch (error) {
1071
+ const errorMessage = error instanceof Error ? error.message : String(error);
1072
+ throw new Error(`Failed to export "${uuid}" via the Photos GUI: ${errorMessage}`, { cause: error });
1073
+ }
1074
+ const results = stderr.split("\n").filter((line) => line.startsWith(`${tempDirectory}/`));
1075
+ if (results.length === 0) throw new Error(`No files exported for "${uuid}" via the Photos GUI. Output: ${stderr}`);
993
1076
  return results;
994
1077
  }
995
1078
  // src/pipeline/engines/file-system.ts
996
1079
  /**
997
- * Export a photo via direct file system copy of the original or edited file to
998
- * a temporary directory Clean up and move the file as needed afterwards
1080
+ * Export a photo by copying its file straight out of the Photos.app library
1081
+ * folder: the edited image if the photo has edits, the original otherwise.
1082
+ *
1083
+ * @returns The path of the copy, in a new temporary directory. Move it and
1084
+ * remove the directory afterwards.
999
1085
  */
1000
1086
  async function exportViaFileSystem(photoUuid, forceOriginal = false) {
1001
1087
  const [photoInfo] = isPhotoInfo(photoUuid) ? [photoUuid] : await aphexPhotoInfo(photoUuid);
@@ -1013,13 +1099,80 @@ async function exportViaFileSystem(photoUuid, forceOriginal = false) {
1013
1099
  }
1014
1100
  // src/pipeline/engines/swift-photokit.ts
1015
1101
  /**
1016
- * Export a photo via aphex-swift command line tool using PhotoKit
1102
+ * Export a photo by asking PhotoKit for the image stored in the library, via
1103
+ * the aphex-swift command line tool. That is the untouched original, or for an
1104
+ * edited photo, the compressed image Photos.app saved with the edit.
1105
+ *
1106
+ * @returns The path of the file, in a new temporary directory. Move it and
1107
+ * remove the directory afterwards.
1017
1108
  */
1018
1109
  async function exportViaSwiftPhotoKit(photoUuid) {
1019
1110
  const [result] = await aphexExport(photoUuid, await getTempDirectory("engine", "swift-photokit"));
1020
1111
  if (result === void 0) throw new Error(`Export via PhotoKit returned no files for photo "${photoUuid}"`);
1021
1112
  return result;
1022
1113
  }
1114
+ // src/pipeline/engines/swift-render.ts
1115
+ /** Equivalent to what the Photos.app export sheet starts out with */
1116
+ const defaultExportViaSwiftRenderOptions = {
1117
+ background: void 0,
1118
+ bitDepth: 8,
1119
+ colorProfile: "most-compatible",
1120
+ format: "jpeg",
1121
+ includeLocation: true,
1122
+ includeMetadata: true,
1123
+ maxHeight: void 0,
1124
+ maxWidth: void 0,
1125
+ preserveAlpha: false,
1126
+ quality: .75
1127
+ };
1128
+ const HEX_COLOR_REGEX = /^#?[\da-f]{6}$/iv;
1129
+ /**
1130
+ * Check render options before anything is exported with them. A bad value would
1131
+ * otherwise only show up as a failed render, one photo at a time.
1132
+ *
1133
+ * @throws {TypeError} Naming the option that is wrong
1134
+ */
1135
+ function assertValidSwiftRenderOptions(options) {
1136
+ const { background, maxHeight, maxWidth, quality } = options;
1137
+ if (!(quality >= 0) || !(quality <= 1)) throw new TypeError(`swiftRenderOptions.quality must be from 0 to 1, got ${String(quality)}`);
1138
+ for (const [name, value] of [["maxWidth", maxWidth], ["maxHeight", maxHeight]]) if (value !== void 0 && !(value >= 1)) throw new TypeError(`swiftRenderOptions.${name} must be at least 1, got ${String(value)}`);
1139
+ if (background !== void 0 && !HEX_COLOR_REGEX.test(background)) throw new TypeError(`swiftRenderOptions.background must be six hexadecimal digits like "ff8800", got "${background}"`);
1140
+ }
1141
+ /**
1142
+ * Export a photo by re-rendering it, and any edits made to it in Photos.app, at
1143
+ * full quality via the aphex-swift command line tool.
1144
+ *
1145
+ * This produces the same pixels as File → Export in Photos.app without
1146
+ * automating its GUI, where the other engines return the compressed image that
1147
+ * Photos.app saved when the photo was edited. It can also keep transparency,
1148
+ * which Photos.app flattens onto white. It relies on private Photos APIs, so it
1149
+ * can stop working after a macOS update.
1150
+ *
1151
+ * @returns The path of the rendered file, in a new temporary directory. Move it
1152
+ * and remove the directory afterwards.
1153
+ */
1154
+ async function exportViaSwiftRender(photoUuid, options) {
1155
+ const resolvedOptions = mergeDefaults(options, defaultExportViaSwiftRenderOptions);
1156
+ assertValidSwiftRenderOptions(resolvedOptions);
1157
+ const { background, maxHeight, maxWidth, ...rest } = resolvedOptions;
1158
+ const tempDirectory = await getTempDirectory("engine", "swift-render");
1159
+ try {
1160
+ const [result] = await aphexExport(photoUuid, tempDirectory, { render: {
1161
+ ...rest,
1162
+ background,
1163
+ maxHeight,
1164
+ maxWidth
1165
+ } });
1166
+ if (result === void 0) throw new Error(`Export via render returned no files for photo "${photoUuid}"`);
1167
+ return result;
1168
+ } catch (error) {
1169
+ await fse.rm(tempDirectory, {
1170
+ force: true,
1171
+ recursive: true
1172
+ });
1173
+ throw error;
1174
+ }
1175
+ }
1023
1176
  // src/pipeline/image-export.ts
1024
1177
  const defaultExportApplePhotoOptions = {
1025
1178
  appleScriptGuiOptions: {
@@ -1036,24 +1189,24 @@ const defaultExportApplePhotoOptions = {
1036
1189
  subfolderFormat: "None",
1037
1190
  tiffBitDepth: 8
1038
1191
  },
1039
- engineEdited: "photos-gui",
1040
- engineEditedAlpha: "swift-photokit",
1192
+ engineEdited: "swift-render",
1193
+ engineEditedAlpha: "swift-render",
1041
1194
  engineOriginal: {
1042
- arw: "photos-gui",
1195
+ arw: "swift-render",
1043
1196
  avif: "swift-photokit",
1044
- cr2: "photos-gui",
1045
- cr3: "photos-gui",
1046
- crw: "photos-gui",
1047
- dng: "photos-gui",
1197
+ cr2: "swift-render",
1198
+ cr3: "swift-render",
1199
+ crw: "swift-render",
1200
+ dng: "swift-render",
1048
1201
  gif: "swift-photokit",
1049
1202
  heic: "swift-photokit",
1050
1203
  heif: "swift-photokit",
1051
1204
  jpeg: "swift-photokit",
1052
- nef: "photos-gui",
1053
- pef: "photos-gui",
1054
- png: "photos-gui",
1055
- psd: "photos-gui",
1056
- tiff: "photos-gui",
1205
+ nef: "swift-render",
1206
+ pef: "swift-render",
1207
+ png: "swift-render",
1208
+ psd: "swift-render",
1209
+ tiff: "swift-render",
1057
1210
  webp: "swift-photokit"
1058
1211
  },
1059
1212
  engineOriginalAlpha: "swift-photokit",
@@ -1064,13 +1217,28 @@ const defaultExportApplePhotoOptions = {
1064
1217
  "fileName",
1065
1218
  "uuid"
1066
1219
  ],
1067
- fileNameSluggify: true
1220
+ fileNameSluggify: true,
1221
+ swiftRenderOptions: {
1222
+ background: void 0,
1223
+ bitDepth: 8,
1224
+ colorProfile: "srgb",
1225
+ format: "png",
1226
+ includeLocation: false,
1227
+ includeMetadata: false,
1228
+ maxHeight: void 0,
1229
+ maxWidth: void 0,
1230
+ preserveAlpha: true,
1231
+ quality: 1
1232
+ }
1068
1233
  };
1069
1234
  /**
1070
- * Export a batch of photos
1235
+ * Export photos and albums from the Photos.app library to a directory, each
1236
+ * photo through the engine the options pick for it. No processing, metadata, or
1237
+ * sync.
1071
1238
  */
1072
1239
  async function exportApplePhotos(identifiers, destinationDirectory, options) {
1073
1240
  const resolvedOptions = mergeDefaults(options, defaultExportApplePhotoOptions);
1241
+ assertValidSwiftRenderOptions(resolvedOptions.swiftRenderOptions);
1074
1242
  const photoInfos = await resolveIdentifiers(identifiers);
1075
1243
  const exportedPhotos = [];
1076
1244
  for (const photoInfo of photoInfos) {
@@ -1094,19 +1262,35 @@ async function exportApplePhotos(identifiers, destinationDirectory, options) {
1094
1262
  }
1095
1263
  return exportedPhotos;
1096
1264
  }
1265
+ /**
1266
+ * Export a photo through one engine.
1267
+ *
1268
+ * @returns The path of the exported file, in a new temporary directory.
1269
+ * @throws {Error} If the engine fails. No other engine is tried instead.
1270
+ */
1097
1271
  async function exportPhotoWithEngine(photoInfo, engine, options) {
1098
1272
  switch (engine) {
1099
1273
  case "applescript": return exportViaAppleScript(photoInfo.uuid);
1100
1274
  case "file-system": return exportViaFileSystem(photoInfo);
1101
- case "photos-gui": {
1102
- const [exportedPath] = await exportViaAppleScriptGui(photoInfo.uuid, options.appleScriptGuiOptions);
1103
- if (exportedPath === void 0) throw new Error(`Photos GUI export returned no files for photo "${photoInfo.uuid}"`);
1104
- return exportedPath;
1105
- }
1275
+ case "photos-gui": return exportViaPhotosGui(photoInfo, options.appleScriptGuiOptions);
1106
1276
  case "swift-photokit": return exportViaSwiftPhotoKit(photoInfo.uuid);
1277
+ case "swift-render": try {
1278
+ return await exportViaSwiftRender(photoInfo.uuid, options.swiftRenderOptions);
1279
+ } catch (error) {
1280
+ throw new Error(`Rendering photo "${photoInfo.title ?? photoInfo.uuid}" failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
1281
+ }
1107
1282
  }
1108
1283
  }
1109
- /** Also normalizes */
1284
+ async function exportViaPhotosGui(photoInfo, guiOptions) {
1285
+ const [exportedPath] = await exportViaAppleScriptGui(photoInfo.uuid, guiOptions);
1286
+ if (exportedPath === void 0) throw new Error(`Photos GUI export returned no files for photo "${photoInfo.uuid}"`);
1287
+ return exportedPath;
1288
+ }
1289
+ /**
1290
+ * Work out the path an exported photo should end up at: the directory and
1291
+ * extension of `filePath`, with a file name chosen by the first naming strategy
1292
+ * the photo has a value for.
1293
+ */
1110
1294
  function getImagePathWithFileName(photoInfo, filePath, sluggify = true, fileNameAppendUuidFragment = false, normalizeExtensions = true, namingStrategyPrecedence = [
1111
1295
  "title",
1112
1296
  "fileName",
@@ -1147,14 +1331,35 @@ async function getEngineForPhoto(photoInfo, options) {
1147
1331
  if (engine === void 0) throw new Error(`No export engine found for original photo "${photoInfo.title}" of type "${type}"${alpha ? " with alpha channel" : ""}`);
1148
1332
  return engine;
1149
1333
  }
1150
- const alpha = await hasAlpha(photoInfo.edited.filePath);
1151
- if (alpha) log.warn(`Edited photo "${photoInfo.title}" has true transparency, it probably won't export correctly. Only un-edited files preserve transparency on export.`);
1334
+ const alpha = await originalHasTransparency(photoInfo);
1152
1335
  const type = lookupImageMimeType(photoInfo.edited.filePath, true);
1153
1336
  const engine = alpha ? typeof engineEditedAlpha === "string" ? engineEditedAlpha : engineEditedAlpha[type] : typeof engineEdited === "string" ? engineEdited : engineEdited[type];
1337
+ if (alpha && (engine !== "swift-render" || !rendersTransparency(options.swiftRenderOptions))) log.warn(`Edited photo "${photoInfo.title ?? photoInfo.uuid}" has transparency, which the "${String(engine)}" engine will flatten onto white. Only swift-render can keep it, with "preserveAlpha" and a "png" or "tiff" format.`);
1154
1338
  if (engine === void 0) throw new Error(`No export engine found for edited photo "${photoInfo.title}" of type "${type}"${alpha ? " with alpha channel" : ""}`);
1155
1339
  return engine;
1156
1340
  }
1157
1341
  /**
1342
+ * Whether a photo's original has transparency. An original that can't be
1343
+ * inspected, such as a camera raw format ImageMagick doesn't know, is taken to
1344
+ * have none, so that it doesn't stop the export.
1345
+ */
1346
+ async function originalHasTransparency(photoInfo) {
1347
+ try {
1348
+ return await hasAlpha(photoInfo.original.filePath);
1349
+ } catch (error) {
1350
+ log.debug(`Could not check "${photoInfo.original.fileName}" for transparency, assuming it has none: ${error instanceof Error ? error.message : String(error)}`);
1351
+ return false;
1352
+ }
1353
+ }
1354
+ /**
1355
+ * Whether swift-render will deal with transparency itself, by keeping it or by
1356
+ * flattening it onto a chosen color, instead of leaving it to be flattened onto
1357
+ * white
1358
+ */
1359
+ function rendersTransparency(options) {
1360
+ return options.background !== void 0 || options.preserveAlpha && (options.format === "png" || options.format === "tiff");
1361
+ }
1362
+ /**
1158
1363
  * Export a single album to a folder Optionally sync the output directory with
1159
1364
  * the album, deleting any images that are no longer in the album Optionally
1160
1365
  * audit the album for duplicate titles Does NOT further process the images
@@ -1176,19 +1381,23 @@ const defaultManageMetadataOptions = {
1176
1381
  /**
1177
1382
  * Manage metadata for a batch of photos
1178
1383
  */
1179
- async function manageMetadataBatch(identifiers, targetFilePaths, options, exportOptions) {
1384
+ async function manageMetadataBatch(identifiers, targetFilePaths, { exportOptions, exportResults, options } = {}) {
1180
1385
  const photoInfos = await resolveIdentifiers(identifiers);
1181
1386
  if (photoInfos.length !== targetFilePaths.length) throw new Error("Photo infos and target files length mismatch");
1182
1387
  return Promise.all(photoInfos.map(async (photoInfo, index) => {
1183
1388
  const targetFilePath = targetFilePaths[index];
1184
1389
  if (targetFilePath === void 0) throw new Error(`Missing target file path for photo "${photoInfo.uuid}"`);
1185
- return manageMetadata(photoInfo, targetFilePath, options, exportOptions);
1390
+ return manageMetadata(photoInfo, targetFilePath, {
1391
+ exportOptions,
1392
+ exportResult: exportResults?.[index],
1393
+ options
1394
+ });
1186
1395
  }));
1187
1396
  }
1188
1397
  /**
1189
- * Manage metadata...
1398
+ * Carry metadata over to one exported photo, as configured in `options`
1190
1399
  */
1191
- async function manageMetadata(identifier, targetFilePath, options, exportOptions) {
1400
+ async function manageMetadata(identifier, targetFilePath, { exportOptions, exportResult, options } = {}) {
1192
1401
  const resolvedOptions = mergeDefaults(options, defaultManageMetadataOptions);
1193
1402
  const photoInfo = await resolvePhotoIdentifier(identifier);
1194
1403
  let tagsToTarget;
@@ -1196,6 +1405,7 @@ async function manageMetadata(identifier, targetFilePath, options, exportOptions
1196
1405
  let tagsToEdited;
1197
1406
  if (photoInfo.edited && resolvedOptions.syncToEdited) tagsToEdited = await cloneTags(photoInfo.original.filePath, photoInfo.edited.filePath, resolvedOptions.tagsToSync);
1198
1407
  if (exportOptions !== void 0 && resolvedOptions.writeAphexMetadata) await setTags(targetFilePath, { aphexMetadata: {
1408
+ ...exportResult,
1199
1409
  exportOptions,
1200
1410
  photoInfo
1201
1411
  } });
@@ -1249,9 +1459,9 @@ async function resizePngToFit(imagePath, destinationDirectory, maxWidth, maxHeig
1249
1459
  return destinationImagePath;
1250
1460
  }
1251
1461
  /**
1252
- * Resize a PNG image to fit within a maximum width and height
1462
+ * Convert an image to a JPEG with mozjpeg, at a quality from 0 to 1
1253
1463
  */
1254
- async function convertToJpeg(sourceImagePath, destinationDirectory, quality, force = false, engine = "mozjpeg") {
1464
+ async function convertToJpeg(sourceImagePath, destinationDirectory, quality, force = false) {
1255
1465
  const mime = lookupImageMimeType(sourceImagePath, [
1256
1466
  "bmp",
1257
1467
  "jpeg",
@@ -1262,49 +1472,31 @@ async function convertToJpeg(sourceImagePath, destinationDirectory, quality, for
1262
1472
  const destinationImagePath = path.join(destinationDirectory, path.basename(sourceImagePath, path.extname(sourceImagePath)) + ".jpeg");
1263
1473
  if (!force && mime === "jpeg") await fse.copy(sourceImagePath, destinationImagePath);
1264
1474
  else {
1265
- const jpegQuality = quality === "lossless" ? "lossless" : Math.round(quality * 100);
1266
- switch (engine) {
1267
- case "guetzli":
1268
- if (jpegQuality === "lossless") throw new Error("Lossless JPEG conversion not supported with guetzli");
1269
- await execa("guetzli", [
1270
- "--quality",
1271
- jpegQuality.toString(),
1272
- sourceImagePath,
1273
- destinationImagePath
1274
- ]);
1275
- break;
1276
- case "mozjpeg": {
1277
- const tgaTempDirectory = await fse.mkdtemp(path.join(os.tmpdir(), `com.kitschpatrol.aphex.${getSlugFilename(sourceImagePath)}.${engine}.`));
1278
- const tgaImagePath = await convertToTga(sourceImagePath, tgaTempDirectory);
1279
- await execa("cjpeg", [
1280
- ...jpegQuality === "lossless" ? ["--lossless"] : ["-quality", jpegQuality.toString()],
1281
- "-optimize",
1282
- "-progressive",
1283
- "-outfile",
1284
- destinationImagePath,
1285
- tgaImagePath
1286
- ]);
1287
- await fse.rm(tgaTempDirectory, { recursive: true });
1288
- break;
1289
- }
1290
- case "sips":
1291
- if (jpegQuality === "lossless") throw new Error("Lossless JPEG conversion not supported with sips");
1292
- await execa("sips", [
1293
- "-s",
1294
- "format",
1295
- "jpeg",
1296
- "-s",
1297
- "formatOptions",
1298
- jpegQuality.toString(),
1299
- sourceImagePath,
1300
- "--out",
1301
- destinationImagePath
1302
- ]);
1303
- }
1475
+ const cjpegPath = getMozjpegCjpegPath();
1476
+ if (!await fse.pathExists(cjpegPath)) throw new Error(`JPEG encoding needs mozjpeg, which was not found at "${cjpegPath}". Install it with "brew install mozjpeg".`);
1477
+ const tgaTempDirectory = await fse.mkdtemp(path.join(os.tmpdir(), `com.kitschpatrol.aphex.${getSlugFilename(sourceImagePath)}.mozjpeg.`));
1478
+ const tgaImagePath = await convertToTga(sourceImagePath, tgaTempDirectory);
1479
+ await execa(cjpegPath, [
1480
+ "-quality",
1481
+ Math.round(quality * 100).toString(),
1482
+ "-optimize",
1483
+ "-progressive",
1484
+ "-outfile",
1485
+ destinationImagePath,
1486
+ tgaImagePath
1487
+ ]);
1488
+ await fse.rm(tgaTempDirectory, { recursive: true });
1304
1489
  }
1305
1490
  return destinationImagePath;
1306
1491
  }
1307
1492
  /**
1493
+ * Homebrew installs mozjpeg keg-only, so its `cjpeg` is not on the PATH. The
1494
+ * `cjpeg` that is comes from libjpeg-turbo, which ImageMagick depends on.
1495
+ */
1496
+ function getMozjpegCjpegPath() {
1497
+ return path.join(process.env.HOMEBREW_PREFIX ?? "/opt/homebrew", "opt/mozjpeg/bin/cjpeg");
1498
+ }
1499
+ /**
1308
1500
  * Convert an image to a WebP
1309
1501
  */
1310
1502
  async function convertToWebp(sourceImagePath, destinationDirectory, quality, force = false) {
@@ -1478,7 +1670,7 @@ async function compressImage(sourceImagePath, destinationDirectory, options) {
1478
1670
  workingImagePath = await convertToAvif(sourceImagePath, tempDirectory, lossyQuality, true);
1479
1671
  break;
1480
1672
  case "jpeg":
1481
- workingImagePath = await convertToJpeg(sourceImagePath, tempDirectory, lossyQuality, true, "mozjpeg");
1673
+ workingImagePath = await convertToJpeg(sourceImagePath, tempDirectory, lossyQuality, true);
1482
1674
  break;
1483
1675
  case "none":
1484
1676
  workingImagePath = sourceImagePath;
@@ -1774,7 +1966,7 @@ async function getDestinationFiles(destinationDirectory) {
1774
1966
  *
1775
1967
  * TODO how to handle non-image files?
1776
1968
  */
1777
- async function getSyncPlanForImages(identifiers, destinationDirectory, options, exportOptions) {
1969
+ async function getSyncPlanForImages(identifiers, destinationDirectory, { exportOptions, options } = {}) {
1778
1970
  const resolvedOptions = mergeDefaults(options, defaultSyncOptions);
1779
1971
  const resolvedExportOptions = mergeDefaults(exportOptions, defaultExportOptions);
1780
1972
  const photoInfos = await resolveIdentifiers(identifiers);
@@ -1818,9 +2010,17 @@ async function getSyncPlanForImages(identifiers, destinationDirectory, options,
1818
2010
  return syncResult;
1819
2011
  }
1820
2012
  /**
2013
+ * The options an export was made with are kept as JSON in the exported file.
2014
+ * JSON drops options that are `undefined`, so current options only compare
2015
+ * equal to stored ones after the same round trip.
2016
+ */
2017
+ function asStored(options) {
2018
+ return JSON.parse(JSON.stringify(options));
2019
+ }
2020
+ /**
1821
2021
  * See if there's a difference between the source image and the target image
1822
2022
  *
1823
- * @returns Undefined if the, or the reason for the difference if found
2023
+ * @returns The first strategy that found a difference, or false if none did
1824
2024
  */
1825
2025
  async function isDifferent(diffStrategies, sourcePhotoInfo, sourcePhotoFileBaseName, matchPhotoFilePath, matchPhotoTags, exportOptions, forceUpdate) {
1826
2026
  if (forceUpdate) return "force-update";
@@ -1830,14 +2030,14 @@ async function isDifferent(diffStrategies, sourcePhotoInfo, sourcePhotoFileBaseN
1830
2030
  case "exif-tags":
1831
2031
  sourceTags ??= await getTags(sourcePhotoInfo.original.filePath);
1832
2032
  return matchPhotoTags === void 0 || sourceTags.credit !== matchPhotoTags.credit || sourceTags.creator !== matchPhotoTags.creator || sourceTags.description !== matchPhotoTags.description || sourceTags.preservedFileName !== matchPhotoTags.preservedFileName || sourceTags.label !== matchPhotoTags.label;
1833
- case "export-options": return matchPhotoTags === void 0 || !deepEqual(exportOptions.exportOptions, matchPhotoTags.aphexMetadata?.exportOptions.exportOptions);
2033
+ case "export-options": return matchPhotoTags === void 0 || !deepEqual(asStored(exportOptions.exportOptions), matchPhotoTags.aphexMetadata?.exportOptions.exportOptions);
1834
2034
  case "file-name": return stripExtension(path.basename(matchPhotoFilePath)) !== sourcePhotoFileBaseName;
1835
2035
  case "force-update": return true;
1836
2036
  case "metadata-options":
1837
2037
  sourceTags ??= await getTags(sourcePhotoInfo.original.filePath);
1838
- return matchPhotoTags === void 0 || !deepEqual(exportOptions.metadataOptions, matchPhotoTags.aphexMetadata?.exportOptions.metadataOptions);
2038
+ return matchPhotoTags === void 0 || !deepEqual(asStored(exportOptions.metadataOptions), matchPhotoTags.aphexMetadata?.exportOptions.metadataOptions);
1839
2039
  case "photo-info": return matchPhotoTags === void 0 || !deepEqual(sourcePhotoInfo, matchPhotoTags.aphexMetadata?.photoInfo);
1840
- case "process-options": return matchPhotoTags === void 0 || !deepEqual(exportOptions.processOptions, matchPhotoTags.aphexMetadata?.exportOptions.processOptions);
2040
+ case "process-options": return matchPhotoTags === void 0 || !deepEqual(asStored(exportOptions.processOptions), matchPhotoTags.aphexMetadata?.exportOptions.processOptions);
1841
2041
  }
1842
2042
  }
1843
2043
  for (const diffStrategy of diffStrategies) if (await strategyFindsDifference(diffStrategy)) return diffStrategy;
@@ -1845,8 +2045,8 @@ async function isDifferent(diffStrategies, sourcePhotoInfo, sourcePhotoFileBaseN
1845
2045
  }
1846
2046
  // src/index.ts
1847
2047
  /**
1848
- * Helper for deep merging ExportOptions object against library defaults.
1849
- * Exported for unplugin-aphex.
2048
+ * Fill in everything a partial `ExportOptions` object leaves out with the
2049
+ * library defaults. Exported for unplugin-aphex.
1850
2050
  */
1851
2051
  function mergeDefaultExportOptions(options) {
1852
2052
  return mergeDefaults(options, defaultExportOptions);
@@ -1871,7 +2071,14 @@ const defaultExportOptions = {
1871
2071
  syncOptions: defaultSyncOptions
1872
2072
  };
1873
2073
  /**
1874
- * Export a single photo
2074
+ * Export a single photo from the Photos.app library to a directory.
2075
+ *
2076
+ * @param identifier A photo's UUID, a path like `Album/Title` or
2077
+ * `Folder/Album/IMG_1234.jpeg`, or a `PhotoInfo` from `getPhotoInfo`.
2078
+ * @param destinationDirectory Created if it doesn't exist. A leading `~` is
2079
+ * expanded.
2080
+ * @param options Anything left out falls back to the library defaults.
2081
+ * @throws {Error} If the identifier matches no photo, or more than one.
1875
2082
  */
1876
2083
  async function exportPhoto(identifier, destinationDirectory, options) {
1877
2084
  const result = await exportPhotos([await resolvePhotoIdentifier(identifier)], destinationDirectory, options);
@@ -1879,7 +2086,23 @@ async function exportPhoto(identifier, destinationDirectory, options) {
1879
2086
  return result[0];
1880
2087
  }
1881
2088
  /**
1882
- * Export photos
2089
+ * Export any number of photos and albums from the Photos.app library to a
2090
+ * directory.
2091
+ *
2092
+ * Each photo goes through the stages that are enabled in `options`: checking
2093
+ * whether an up-to-date export already exists, exporting from Photos.app,
2094
+ * processing, and writing metadata.
2095
+ *
2096
+ * @param identifiers Any mix of photo and album identifiers: UUIDs, paths like
2097
+ * `Album/Title` or `Folder/Album`, and `PhotoInfo` or `AlbumInfo` objects. An
2098
+ * album stands for every photo in it.
2099
+ * @param destinationDirectory Created if it doesn't exist. A leading `~` is
2100
+ * expanded.
2101
+ * @param options Anything left out falls back to the library defaults.
2102
+ *
2103
+ * @returns One result per photo, in a flat list. A photo that is identified
2104
+ * more than once is exported once.
2105
+ * @throws {Error} If the identifiers match no photos.
1883
2106
  */
1884
2107
  async function exportPhotos(identifiers, destinationDirectory, options) {
1885
2108
  const resolvedOptions = mergeDefaultExportOptions(options);
@@ -1888,8 +2111,10 @@ async function exportPhotos(identifiers, destinationDirectory, options) {
1888
2111
  const photoInfos = await resolveIdentifiers(identifiers);
1889
2112
  let syncResult;
1890
2113
  if (syncOptions !== "disabled") {
1891
- syncResult = await getSyncPlanForImages(photoInfos, resolvedDestinationDirectory, syncOptions, resolvedOptions);
1892
- await Promise.all(syncResult.toDelete.map(async (file) => fse.rm(file, { force: true })));
2114
+ syncResult = await getSyncPlanForImages(photoInfos, resolvedDestinationDirectory, {
2115
+ exportOptions: resolvedOptions,
2116
+ options: syncOptions
2117
+ });
1893
2118
  if (syncResult.plan.length !== photoInfos.length) throw new Error("Sync plan length does not match photos length");
1894
2119
  }
1895
2120
  const exportResults = photoInfos.map((photoInfo, index) => {
@@ -1906,7 +2131,10 @@ async function exportPhotos(identifiers, destinationDirectory, options) {
1906
2131
  }
1907
2132
  };
1908
2133
  });
1909
- if (exportResults.every((exportResult) => exportResult.results.syncResult?.status === "unchanged")) return exportResults;
2134
+ if (exportResults.every((exportResult) => exportResult.results.syncResult?.status === "unchanged")) {
2135
+ await deleteStaleFiles(syncResult?.toDelete, exportResults);
2136
+ return exportResults;
2137
+ }
1910
2138
  const seenBaseNames = /* @__PURE__ */ new Set();
1911
2139
  let hasCollision = false;
1912
2140
  for (const exportResult of exportResults) {
@@ -1949,14 +2177,53 @@ async function exportPhotos(identifiers, destinationDirectory, options) {
1949
2177
  }
1950
2178
  if (metadataOptions !== "disabled") {
1951
2179
  const targetPhotos = exportResults.filter((exportResult) => exportResult.results.syncResult?.status !== "unchanged");
1952
- const metadataResults = await manageMetadataBatch(targetPhotos.map((exportResult) => exportResult.photoInfo), targetPhotos.map((exportResult) => exportResult.path), metadataOptions, resolvedOptions);
2180
+ const metadataResults = await manageMetadataBatch(targetPhotos.map((exportResult) => exportResult.photoInfo), targetPhotos.map((exportResult) => exportResult.path), {
2181
+ exportOptions: resolvedOptions,
2182
+ exportResults: targetPhotos.map((exportResult) => exportResult.results.exportResult),
2183
+ options: metadataOptions
2184
+ });
1953
2185
  for (const exportResult of exportResults) {
1954
2186
  const matchingMetadataResult = metadataResults.find((photoExportResult) => photoExportResult.photoInfo.uuid === exportResult.photoInfo.uuid);
1955
2187
  if (matchingMetadataResult) exportResult.results.metadataResult = cleanMetadataResults(matchingMetadataResult);
1956
2188
  }
1957
2189
  }
2190
+ await deleteStaleFiles(syncResult?.toDelete, exportResults);
1958
2191
  return exportResults;
1959
2192
  }
2193
+ /**
2194
+ * Delete the files a sync plan marked for deletion, now that the export has
2195
+ * gone through.
2196
+ *
2197
+ * A file that a result points to stays, since a new export can take the place
2198
+ * of an old one under the same name. So does an out-of-date export that nothing
2199
+ * took the place of.
2200
+ */
2201
+ async function deleteStaleFiles(toDelete, exportResults) {
2202
+ if (toDelete === void 0 || toDelete.length === 0) return;
2203
+ const keep = /* @__PURE__ */ new Set();
2204
+ for (const { path: resultPath, results } of exportResults) {
2205
+ const identity = resultPath === "" ? void 0 : await getFileIdentity(resultPath);
2206
+ const staleIdentity = identity === void 0 && results.syncResult?.matchFilePath !== void 0 ? await getFileIdentity(results.syncResult.matchFilePath) : void 0;
2207
+ for (const kept of [identity, staleIdentity]) if (kept !== void 0) keep.add(kept);
2208
+ }
2209
+ for (const file of toDelete) {
2210
+ const identity = await getFileIdentity(file);
2211
+ if (identity !== void 0 && !keep.has(identity)) await fse.rm(file, { force: true });
2212
+ }
2213
+ }
2214
+ /**
2215
+ * A string that is the same for every path that leads to one file
2216
+ *
2217
+ * @returns Undefined if there is no file at the path
2218
+ */
2219
+ async function getFileIdentity(filePath) {
2220
+ try {
2221
+ const { dev, ino } = await fse.stat(filePath, { bigint: true });
2222
+ return `${dev}:${ino}`;
2223
+ } catch {
2224
+ return;
2225
+ }
2226
+ }
1960
2227
  function cleanExportResults(result) {
1961
2228
  return { exportEngine: result.exportEngine };
1962
2229
  }