@fleox/agentphoto 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +177 -72
  2. package/changelog.json +18 -0
  3. package/dist/agent/agentphoto.mjs +64 -17
  4. package/dist/agent/chunks/{assets-CDQo3VqD.mjs → assets-BZVUUHjg.mjs} +3 -3
  5. package/dist/agent/chunks/{context-DoLoLF9f.mjs → context-CNpRboiC.mjs} +1 -1
  6. package/dist/agent/chunks/{doc-BjY_j4Su.mjs → doc-D_v_yE07.mjs} +25 -286
  7. package/dist/agent/chunks/{export-CLmpFART.mjs → export-aNJcPNbJ.mjs} +1 -1
  8. package/dist/agent/chunks/geometry-BKIhUO9x.mjs +315 -0
  9. package/dist/agent/chunks/{models-C4i_hicr.mjs → models-CxrjmA0W.mjs} +1 -1
  10. package/dist/agent/chunks/{package-DSmAxrla.mjs → package-Cu1GyvKL.mjs} +2 -2
  11. package/dist/agent/chunks/{project-CUykGysG.mjs → project-o1DH2nOw.mjs} +12 -10
  12. package/dist/agent/chunks/{templates--YGpGuHh.mjs → templates-BJ2me4XZ.mjs} +24 -3
  13. package/dist/agent/chunks/{tools-Dnh8g6F9.mjs → tools-DKaAPEV5.mjs} +92 -27
  14. package/dist/agent/chunks/{tree-DO7N0UDV.mjs → tree-D8qZKPAb.mjs} +2 -2
  15. package/dist/engine/agentphoto-engine.js +408 -352
  16. package/dist/studio/assets/index-CmOzzoXv.css +1 -0
  17. package/dist/studio/assets/index-D3Iw5q8v.js +28 -0
  18. package/dist/studio/assets/{transformers.web-DgnCIB_X.js → transformers.web-osEqoMhg.js} +1 -1
  19. package/dist/studio/index.html +2 -2
  20. package/dist/studio/templates/index.json +1 -1
  21. package/dist/studio/templates/product-white/photo.json +2 -2
  22. package/dist/studio/templates/product-white/preview.jpg +0 -0
  23. package/dist/studio/templates/product-white/template.json +1 -1
  24. package/package.json +2 -2
  25. package/plugin/.claude-plugin/plugin.json +1 -1
  26. package/plugin/skills/agentphoto-cutout/SKILL.md +30 -25
  27. package/plugin/skills/agentphoto-design/SKILL.md +24 -24
  28. package/plugin/skills/agentphoto-publish/SKILL.md +10 -10
  29. package/plugin/skills/agentphoto-retouch/SKILL.md +26 -26
  30. package/plugin/skills/agentphoto-retouch/references/filters.md +1 -1
  31. package/plugin/skills/agentphoto-retouch/references/patch-ops.md +14 -13
  32. package/plugin/skills/agentphoto-retouch/references/recipes.md +3 -3
  33. package/templates/product-white/photo.json +2 -2
  34. package/templates/product-white/preview.jpg +0 -0
  35. package/templates/product-white/template.json +1 -1
  36. package/dist/studio/assets/index-Be8JnaFy.js +0 -28
  37. package/dist/studio/assets/index-DwPms2S5.css +0 -1
@@ -7,11 +7,11 @@ const __filename = __apPath(import.meta.url);
7
7
  __apDirname(__filename);
8
8
  import { t as __exportAll } from "./chunks/rolldown-runtime-CMQPkI6i.mjs";
9
9
  import { a as routeConsoleToStderr, i as printResult, n as createIo, o as toCliError, r as printError, t as CliError } from "./chunks/output-3F12IR9O.mjs";
10
- import { _ as packageRoot, a as mimeOf, b as templatesDir, c as sendJson, d as distRoot, f as engineBuilt, g as modelsDir, h as libraryDir, l as sendText, m as isBundled, n as modelCacheDir, o as readBody, p as engineDir, r as modelsRoute, s as resolveUnder, t as listCachedModels, u as startLocalServer, v as readVersionInfo, y as studioDir } from "./chunks/models-C4i_hicr.mjs";
11
- import { d as normalizePath, u as FsError } from "./chunks/context-DoLoLF9f.mjs";
10
+ import { _ as packageRoot, a as mimeOf, b as templatesDir, c as sendJson, d as distRoot, f as engineBuilt, g as modelsDir, h as libraryDir, l as sendText, m as isBundled, n as modelCacheDir, o as readBody, p as engineDir, r as modelsRoute, s as resolveUnder, t as listCachedModels, u as startLocalServer, v as readVersionInfo, y as studioDir } from "./chunks/models-CxrjmA0W.mjs";
11
+ import { d as normalizePath, u as FsError } from "./chunks/context-CNpRboiC.mjs";
12
12
  import { o as MODELS, t as CATALOG, u as modelDef } from "./chunks/catalog-DIZ5dnH5.mjs";
13
- import { r as parseTemplateInfo } from "./chunks/templates--YGpGuHh.mjs";
14
- import { s as referencedFiles } from "./chunks/tree-DO7N0UDV.mjs";
13
+ import { r as parseTemplateInfo } from "./chunks/templates-BJ2me4XZ.mjs";
14
+ import { s as referencedFiles } from "./chunks/tree-D8qZKPAb.mjs";
15
15
  import { parseArgs } from "node:util";
16
16
  import { existsSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, watch } from "node:fs";
17
17
  import { homedir, tmpdir } from "node:os";
@@ -327,6 +327,14 @@ async function runMutation(io, options, fs, name, input, human, opts = {}) {
327
327
  if (r.status === "refused") throw refused(r);
328
328
  printResult(io, r, () => `${human}: ${r.plan.summary}\n${issuesLine(r.issues)}`);
329
329
  }
330
+ function shownDir(dir, typed, cwd = process.cwd()) {
331
+ let p = typed?.trim();
332
+ if (!p) {
333
+ const rel = relative(cwd, dir);
334
+ p = rel === "" ? "." : !rel.startsWith("..") && !isAbsolute(rel) ? rel : dir;
335
+ }
336
+ return /\s/.test(p) ? JSON.stringify(p) : p;
337
+ }
330
338
  function absPath(fs, path) {
331
339
  return resolve(fs.root, path);
332
340
  }
@@ -656,7 +664,7 @@ var templatesCommand = {
656
664
  if (!meta || !raw) throw new CliError("notFound", `Template "${id}" has no photo.json.`, "`agentphoto templates list` lists the templates.");
657
665
  let summary = null;
658
666
  try {
659
- const { summarizeDoc } = await import("./chunks/doc-BjY_j4Su.mjs").then((n) => n.r);
667
+ const { summarizeDoc } = await import("./chunks/doc-D_v_yE07.mjs").then((n) => n.r);
660
668
  const { normalizeDoc } = await import("./chunks/validate-CXPFB-i6.mjs").then((n) => n.a);
661
669
  summary = summarizeDoc(normalizeDoc(JSON.parse(new TextDecoder().decode(raw))));
662
670
  } catch {
@@ -909,7 +917,7 @@ var layerCommand = {
909
917
  if (action === "get") {
910
918
  const id = positional(positionals, 1, "layer id", "layer get <id>");
911
919
  const doc = await tool(fs, "doc_get", {});
912
- const { findLayer } = await import("./chunks/tree-DO7N0UDV.mjs").then((n) => n.c);
920
+ const { findLayer } = await import("./chunks/tree-D8qZKPAb.mjs").then((n) => n.c);
913
921
  const hit = findLayer(doc.layers, id);
914
922
  if (!hit) throw new CliError("notFound", `No layer "${id}".`, "`agentphoto layer list` lists the layer ids.");
915
923
  return printResult(io, {
@@ -1190,7 +1198,7 @@ var maskCommand = {
1190
1198
  return printResult(io, {
1191
1199
  ...r,
1192
1200
  maskFile: `${fs.root}/${r.mask}`
1193
- }, () => `Mask ${r.mask} (${String(r.size)}) set on "${r.layer ?? id}". ${r.plan.summary}\nLook at it: agentphoto render --project ${fs.root}`);
1201
+ }, () => `Mask ${r.mask} (${String(r.size)}) set on "${r.layer ?? id}". ${r.plan.summary}\nLook at it: agentphoto render --project ${shownDir(fs.root, strOpt(options, "project"))}`);
1194
1202
  }
1195
1203
  usage(`Unknown mask action "${action}".`, "Use set, clear or generate.");
1196
1204
  }
@@ -1199,7 +1207,7 @@ var maskCommand = {
1199
1207
  var log$1 = (m) => void process.stderr.write(`${m}\n`);
1200
1208
  var removeBgCommand = {
1201
1209
  name: "remove-bg",
1202
- usage: "remove-bg <layer> [--model rmbg-1.4|modnet] [--background <paint>] [--shadow] [--feather <px>] [--threshold <0-255>]",
1210
+ usage: "remove-bg <layer> [--model rmbg-1.4|modnet] [--background <paint>] [--shadow] [--feather <px>] [--threshold <0-255>] [--fit x,y,w,h|none] [--anchor center|bottom|…]",
1203
1211
  summary: "Remove the background of a photo layer with local AI (nothing is uploaded; the model downloads once): writes a mask to assets/masks/ and sets it on the layer — non-destructive (`mask clear` restores). --background adds a colour / gradient under the cut-out, --shadow a soft drop shadow.",
1204
1212
  writes: true,
1205
1213
  options: [
@@ -1228,6 +1236,16 @@ var removeBgCommand = {
1228
1236
  name: "threshold",
1229
1237
  type: "string",
1230
1238
  description: "Hard edge: keep pixels with confidence ≥ threshold (0..255). Default: soft alpha (best for hair)."
1239
+ },
1240
+ {
1241
+ name: "fit",
1242
+ type: "string",
1243
+ description: "Scale and move the layer so the subject fits this canvas box \"x,y,width,height\"; \"none\" leaves it in place. Default: the template's subject area on its photo slot (first cut-out after `new --template … --image`)."
1244
+ },
1245
+ {
1246
+ name: "anchor",
1247
+ type: "string",
1248
+ description: "With --fit: where the subject sits in the box — center (default), bottom (on a floor line), top, left, right, top-left…"
1231
1249
  }
1232
1250
  ],
1233
1251
  async run({ io, options, positionals }) {
@@ -1239,12 +1257,27 @@ var removeBgCommand = {
1239
1257
  if (boolOpt(options, "shadow")) input.shadow = true;
1240
1258
  if (numOpt(options, "feather") !== void 0) input.feather = numOpt(options, "feather");
1241
1259
  if (numOpt(options, "threshold") !== void 0) input.threshold = numOpt(options, "threshold");
1260
+ const fit = strOpt(options, "fit");
1261
+ if (fit !== void 0) {
1262
+ if (fit === "none" || fit === "false") input.fit = false;
1263
+ else {
1264
+ const v = fit.split(",").map((x) => Number(x.trim()));
1265
+ if (v.length !== 4 || !v.every(Number.isFinite)) usage(`Invalid --fit "${fit}".`, "Pass the canvas box \"x,y,width,height\" (e.g. --fit 500,400,1000,850 --anchor bottom) or \"none\".");
1266
+ input.fit = {
1267
+ x: v[0],
1268
+ y: v[1],
1269
+ width: v[2],
1270
+ height: v[3],
1271
+ ...strOpt(options, "anchor") ? { anchor: strOpt(options, "anchor") } : {}
1272
+ };
1273
+ }
1274
+ } else if (strOpt(options, "anchor")) usage("--anchor needs --fit.", "e.g. remove-bg photo --fit 500,400,1000,850 --anchor bottom");
1242
1275
  const r = await tool(fs, "remove_background", input);
1243
1276
  if (r.status === "refused") throw new CliError("validation", "The cut-out could not be applied.", "See details.issues.", 2, { issues: r.issues });
1244
1277
  printResult(io, {
1245
1278
  ...r,
1246
1279
  maskFile: absPath(fs, r.mask)
1247
- }, () => `Background removed from "${id}" (${r.model}): mask ${r.mask} (${r.size}). ${r.plan.summary}\nLook at it: agentphoto render --project ${fs.root}`);
1280
+ }, () => `Background removed from "${id}" (${r.model}): mask ${r.mask} (${r.size}). ${r.plan.summary}${r.fitted ? `\nSubject fitted into ${r.fitted.box.x},${r.fitted.box.y},${r.fitted.box.width},${r.fitted.box.height} (${r.fitted.anchor}); --fit none keeps the layer in place.` : ""}\nLook at it: agentphoto render --project ${shownDir(fs.root, strOpt(options, "project"))}`);
1248
1281
  }
1249
1282
  };
1250
1283
  var analyzeCommand = {
@@ -1418,7 +1451,7 @@ var exportCommand = {
1418
1451
  if (!Array.isArray(variants) || !variants.length || variants.some((v) => !v || typeof v !== "object" || Array.isArray(v))) usage("--variants must be a JSON array of objects.", `e.g. --variants '[{"preset":"og"},{"preset":"square","format":"jpeg"}]'`);
1419
1452
  input.variants = variants;
1420
1453
  }
1421
- const [{ getDoc }, { planExport }] = await Promise.all([import("./chunks/doc-BjY_j4Su.mjs").then((n) => n.r), import("./chunks/export-CLmpFART.mjs").then((n) => n.n)]);
1454
+ const [{ getDoc }, { planExport }] = await Promise.all([import("./chunks/doc-D_v_yE07.mjs").then((n) => n.r), import("./chunks/export-aNJcPNbJ.mjs").then((n) => n.n)]);
1422
1455
  const doc = await getDoc(fs);
1423
1456
  const { variants: _v, ...base } = input;
1424
1457
  const jobs = (Array.isArray(variants) ? variants.map((v) => ({
@@ -1592,7 +1625,7 @@ var doctorCommand = {
1592
1625
  optional: true,
1593
1626
  message: tpl ? `Templates found (${templatesDir()})` : `Templates folder missing (${templatesDir()})`
1594
1627
  });
1595
- const { listCachedModels } = await import("./chunks/models-C4i_hicr.mjs").then((n) => n.i);
1628
+ const { listCachedModels } = await import("./chunks/models-CxrjmA0W.mjs").then((n) => n.i);
1596
1629
  const cached = listCachedModels().filter((m) => m.cached);
1597
1630
  checks.push({
1598
1631
  id: "models",
@@ -1844,7 +1877,8 @@ var newCommand = {
1844
1877
  }
1845
1878
  ],
1846
1879
  async run({ io, options, positionals }) {
1847
- const dir = resolve(positional(positionals, 0, "project folder", "new <dir> [--image <photo>]"));
1880
+ const typed = positional(positionals, 0, "project folder", "new <dir> [--image <photo>]");
1881
+ const dir = resolve(typed);
1848
1882
  const force = boolOpt(options, "force");
1849
1883
  if (!force && existsSync(resolve(dir, "photo.json"))) throw new CliError("conflict", `${dir} is already an AgentPhoto project (photo.json exists).`, "Work on it with `--project <dir>` (`agentphoto info --project …`), pick another folder, or pass --force to overwrite it.");
1850
1884
  if (!force && existsSync(dir) && readdirSync(dir).filter((f) => !f.startsWith(".")).length) throw new CliError("conflict", `${dir} exists and is not empty.`, "Pick a new or empty folder for the project (or --force).");
@@ -1871,7 +1905,7 @@ var newCommand = {
1871
1905
  layers,
1872
1906
  files,
1873
1907
  issues: r.issues
1874
- }, () => [`Created ${dir} (${canvas.width}×${canvas.height}${strOpt(options, "template") ? `, template ${strOpt(options, "template")}` : ""}; layers: ${layers.map((l) => l.id).join(", ") || "none"}).`, `Next: agentphoto render --project ${dir} · agentphoto analyze --project ${dir}`].join("\n"));
1908
+ }, () => [`Created ${shownDir(dir, typed)} (${canvas.width}×${canvas.height}${strOpt(options, "template") ? `, template ${strOpt(options, "template")}` : ""}; layers: ${layers.map((l) => l.id).join(", ") || "none"}).`, `Next: agentphoto render --project ${shownDir(dir, typed)} · agentphoto analyze --project ${shownDir(dir, typed)}`].join("\n"));
1875
1909
  }
1876
1910
  };
1877
1911
  var infoCommand = {
@@ -2604,7 +2638,7 @@ function toolContext(fs) {
2604
2638
  };
2605
2639
  }
2606
2640
  async function listTools(opts = {}) {
2607
- const { listAiTools } = await import("./chunks/tools-Dnh8g6F9.mjs");
2641
+ const { listAiTools } = await import("./chunks/tools-DKaAPEV5.mjs");
2608
2642
  return listAiTools(nodeHost(null), opts).map((t) => ({
2609
2643
  name: t.name,
2610
2644
  description: t.description,
@@ -2614,11 +2648,11 @@ async function listTools(opts = {}) {
2614
2648
  }));
2615
2649
  }
2616
2650
  async function callTool(fs, name, input) {
2617
- const { callAiTool } = await import("./chunks/tools-Dnh8g6F9.mjs");
2651
+ const { callAiTool } = await import("./chunks/tools-DKaAPEV5.mjs");
2618
2652
  return callAiTool(toolContext(fs), name, input);
2619
2653
  }
2620
2654
  async function previewImages(name, result, root) {
2621
- const { resultImages } = await import("./chunks/tools-Dnh8g6F9.mjs");
2655
+ const { resultImages } = await import("./chunks/tools-DKaAPEV5.mjs");
2622
2656
  const out = [];
2623
2657
  for (const file of resultImages(name, result)) try {
2624
2658
  const mimeType = /\.jpe?g$/i.test(file) ? "image/jpeg" : /\.webp$/i.test(file) ? "image/webp" : "image/png";
@@ -2826,6 +2860,19 @@ async function startStudioServer(opts) {
2826
2860
  });
2827
2861
  return true;
2828
2862
  }
2863
+ if (url.pathname === "/api/models" && method === "GET") {
2864
+ const models = listCachedModels().map((m) => ({
2865
+ id: m.id,
2866
+ task: m.task,
2867
+ sizeMb: m.sizeMb,
2868
+ cached: m.cached,
2869
+ cachedMb: m.cachedMb
2870
+ }));
2871
+ return sendJson(res, 200, {
2872
+ ok: true,
2873
+ data: { models }
2874
+ }), true;
2875
+ }
2829
2876
  if (url.pathname === "/api/catalog" && method === "GET") return sendJson(res, 200, {
2830
2877
  ok: true,
2831
2878
  data: CATALOG
@@ -3146,7 +3193,7 @@ function mcpOptions(fs, readOnly, tools) {
3146
3193
  description: "Compact outline: canvas, layers top → bottom with type, box, filters, masks, effects.",
3147
3194
  mimeType: "application/json",
3148
3195
  read: async () => {
3149
- const { getDoc, summarizeDoc } = await import("./chunks/doc-BjY_j4Su.mjs").then((n) => n.r);
3196
+ const { getDoc, summarizeDoc } = await import("./chunks/doc-D_v_yE07.mjs").then((n) => n.r);
3150
3197
  return summarizeDoc(await getDoc(fs));
3151
3198
  }
3152
3199
  },
@@ -8,9 +8,9 @@ import { t as __exportAll } from "./rolldown-runtime-CMQPkI6i.mjs";
8
8
  import { r as slugify } from "./ids-DAmiNwd9.mjs";
9
9
  import { n as imageInfo, t as IMAGE_EXTENSIONS } from "./imageInfo-QxAfu8R6.mjs";
10
10
  import { n as isLibraryRef } from "./library-C_EXiphj.mjs";
11
- import { a as nowIso, l as writeJson, n as KB, r as OpsError, s as readJsonOr } from "./context-DoLoLF9f.mjs";
12
- import { n as DOC_FILE, t as ASSET_MANIFEST_FILE } from "./project-CUykGysG.mjs";
13
- import { s as referencedFiles } from "./tree-DO7N0UDV.mjs";
11
+ import { a as nowIso, l as writeJson, n as KB, r as OpsError, s as readJsonOr } from "./context-CNpRboiC.mjs";
12
+ import { n as DOC_FILE, t as ASSET_MANIFEST_FILE } from "./project-o1DH2nOw.mjs";
13
+ import { s as referencedFiles } from "./tree-D8qZKPAb.mjs";
14
14
  // src/ops/assets.ts
15
15
  var assets_exports = /* @__PURE__ */ __exportAll({
16
16
  addAsset: () => addAsset,
@@ -4,7 +4,7 @@ import { dirname as __apDirname } from "node:path";
4
4
  __apRequire(import.meta.url);
5
5
  const __filename = __apPath(import.meta.url);
6
6
  __apDirname(__filename);
7
- import { n as version } from "./package-DSmAxrla.mjs";
7
+ import { n as version } from "./package-Cu1GyvKL.mjs";
8
8
  // src/core/fs.ts
9
9
  var FsError = class extends Error {
10
10
  code;
@@ -6,285 +6,14 @@ const __filename = __apPath(import.meta.url);
6
6
  __apDirname(__filename);
7
7
  import { t as __exportAll } from "./rolldown-runtime-CMQPkI6i.mjs";
8
8
  import { i as uniqueId, n as isValidId } from "./ids-DAmiNwd9.mjs";
9
- import { c as setAt, i as getAt, n as clone$1, o as mergePatch, r as deepEqual, s as removeAt, t as PathError } from "./jsonPath-B7vAPXsi.mjs";
9
+ import { c as setAt, i as getAt, n as clone, o as mergePatch, r as deepEqual, s as removeAt, t as PathError } from "./jsonPath-B7vAPXsi.mjs";
10
10
  import { n as isLibraryRef } from "./library-C_EXiphj.mjs";
11
11
  import { i as validateDoc, l as didYouMean, r as normalizeDoc } from "./validate-CXPFB-i6.mjs";
12
- import { a as isShapeMask, n as hasBox, r as isGradientMask } from "./types-DOK7tAAu.mjs";
13
- import { i as hasErrors, o as readJson, r as OpsError } from "./context-DoLoLF9f.mjs";
14
- import { c as filterDef, i as EFFECTS } from "./catalog-DIZ5dnH5.mjs";
15
- import { a as layerDetail, i as isDescendant, l as walkLayers, n as findLayer, o as maskKind, r as flattenLayers, t as allLayerIds } from "./tree-DO7N0UDV.mjs";
16
- import { a as saveDoc, n as DOC_FILE } from "./project-CUykGysG.mjs";
17
- // src/ops/geometry.ts
18
- var geometry_exports = /* @__PURE__ */ __exportAll({ cropDoc: () => cropDoc });
19
- var ANCHORS = [
20
- "top-left",
21
- "top",
22
- "top-right",
23
- "left",
24
- "center",
25
- "right",
26
- "bottom-left",
27
- "bottom",
28
- "bottom-right"
29
- ];
30
- var clone = (v) => JSON.parse(JSON.stringify(v));
31
- var r2 = (v) => Math.round(v * 100) / 100;
32
- function estimateTextBox(l) {
33
- const size = l.size ?? 64;
34
- const lines = String(l.text ?? "").split("\n");
35
- const longest = Math.max(1, ...lines.map((s) => s.length));
36
- return {
37
- width: l.width ?? longest * size * .55 + Math.max(0, longest - 1) * (l.letterSpacing ?? 0),
38
- height: l.height ?? lines.length * size * (l.lineHeight ?? 1.2)
39
- };
40
- }
41
- function layerBox(l, sizes = {}) {
42
- if (!hasBox(l)) return null;
43
- const x = l.x ?? 0;
44
- const y = l.y ?? 0;
45
- if (l.type === "text") return {
46
- x,
47
- y,
48
- ...estimateTextBox(l)
49
- };
50
- let w = l.width;
51
- let h = l.height;
52
- if (l.type === "image" && (w === void 0 || h === void 0)) {
53
- const nat = sizes[l.src];
54
- const src = l.crop ? {
55
- width: l.crop.width,
56
- height: l.crop.height
57
- } : nat;
58
- if (src) {
59
- if (w === void 0 && h === void 0) [w, h] = [src.width, src.height];
60
- else if (w === void 0) w = h * src.width / src.height;
61
- else h = w * src.height / src.width;
62
- }
63
- }
64
- if (w === void 0 || h === void 0) return null;
65
- return {
66
- x,
67
- y,
68
- width: w,
69
- height: h
70
- };
71
- }
72
- function pinSize(l, sizes) {
73
- if (l.type !== "image" || l.width !== void 0 && l.height !== void 0) return;
74
- const b = layerBox(l, sizes);
75
- if (!b) throw new OpsError("invalid", `The size of image layer "${l.id}" is unknown (its source ${l.src} could not be read).`, "Give the layer an explicit width and height, or fix its src (assets_list).");
76
- l.width = r2(b.width);
77
- l.height = r2(b.height);
78
- }
79
- function eachLayer(layers, fn) {
80
- for (const l of layers) {
81
- fn(l);
82
- if (l.type === "group") eachLayer(l.children ?? [], fn);
83
- }
84
- }
85
- function translateMask(m, dx, dy) {
86
- if (m && isShapeMask(m)) {
87
- m.x = r2(m.x + dx);
88
- m.y = r2(m.y + dy);
89
- }
90
- }
91
- function translateAll(layers, dx, dy) {
92
- eachLayer(layers, (l) => {
93
- if (hasBox(l)) {
94
- l.x = r2((l.x ?? 0) + dx);
95
- l.y = r2((l.y ?? 0) + dy);
96
- } else translateMask(l.mask, dx, dy);
97
- });
98
- }
99
- function cropDoc(doc, rect) {
100
- const { x, y, width, height } = rect;
101
- if (![
102
- x,
103
- y,
104
- width,
105
- height
106
- ].every(Number.isFinite) || width < 1 || height < 1) throw new OpsError("invalid", "crop needs x, y, width ≥ 1, height ≥ 1 (canvas pixels).");
107
- const out = clone(doc);
108
- translateAll(out.layers, -x, -y);
109
- out.canvas = {
110
- ...out.canvas,
111
- width: Math.round(width),
112
- height: Math.round(height)
113
- };
114
- return out;
115
- }
116
- function anchorOffset(anchor, dw, dh) {
117
- const ax = anchor.endsWith("left") ? 0 : anchor.endsWith("right") ? 1 : .5;
118
- const ay = anchor.startsWith("top") ? 0 : anchor.startsWith("bottom") ? 1 : .5;
119
- return [dw * ax, dh * ay];
120
- }
121
- function resizeCanvasDoc(doc, width, height, anchor = "center") {
122
- if (!ANCHORS.includes(anchor)) throw new OpsError("invalid", `Unknown anchor "${anchor}".`, `Anchors: ${ANCHORS.join(", ")}.`);
123
- const [ox, oy] = anchorOffset(anchor, width - doc.canvas.width, height - doc.canvas.height);
124
- return cropDoc(doc, {
125
- x: -ox,
126
- y: -oy,
127
- width,
128
- height
129
- });
130
- }
131
- function scalePx(obj, keys, k) {
132
- if (!obj) return;
133
- for (const key of keys) if (typeof obj[key] === "number") obj[key] = r2(obj[key] * k);
134
- }
135
- function scaleFilters(filters, k) {
136
- for (const f of filters ?? []) scalePx(f, (filterDef(f.type)?.params ?? []).filter((p) => p.px).map((p) => p.name), k);
137
- }
138
- function scaleDoc(doc, sx, sy, sizes = {}) {
139
- if (!(sx > 0) || !(sy > 0)) throw new OpsError("invalid", "The scale must be > 0.");
140
- const out = clone(doc);
141
- const k = Math.sqrt(sx * sy);
142
- eachLayer(out.layers, (l) => {
143
- pinSize(l, sizes);
144
- if (hasBox(l)) {
145
- l.x = r2((l.x ?? 0) * sx);
146
- l.y = r2((l.y ?? 0) * sy);
147
- if (l.width !== void 0) l.width = r2(l.width * sx);
148
- if (l.height !== void 0) l.height = r2(l.height * sy);
149
- } else if (l.mask && isShapeMask(l.mask)) {
150
- const m = l.mask;
151
- m.x = r2(m.x * sx);
152
- m.y = r2(m.y * sy);
153
- m.width = r2(m.width * sx);
154
- m.height = r2(m.height * sy);
155
- }
156
- if (l.mask) {
157
- if (hasBox(l) && isShapeMask(l.mask)) {
158
- const m = l.mask;
159
- m.x = r2(m.x * sx);
160
- m.y = r2(m.y * sy);
161
- m.width = r2(m.width * sx);
162
- m.height = r2(m.height * sy);
163
- }
164
- scalePx(l.mask, ["feather", "radius"], k);
165
- }
166
- if (l.type === "text") {
167
- scalePx(l, ["size", "letterSpacing"], k);
168
- if (l.background) {
169
- const p = l.background.padding;
170
- l.background.padding = Array.isArray(p) ? [r2(p[0] * k), r2(p[1] * k)] : typeof p === "number" ? r2(p * k) : p;
171
- scalePx(l.background, ["radius"], k);
172
- }
173
- }
174
- if (l.type === "shape") {
175
- scalePx(l, ["radius"], k);
176
- if (l.stroke) scalePx(l.stroke, ["width"], k);
177
- }
178
- scaleFilters(l.filters, k);
179
- if (l.effects) for (const def of EFFECTS) {
180
- const fx = l.effects[def.id];
181
- scalePx(fx, def.params.filter((p) => p.px).map((p) => p.name), k);
182
- }
183
- });
184
- out.canvas = {
185
- ...out.canvas,
186
- width: Math.max(1, Math.round(doc.canvas.width * sx)),
187
- height: Math.max(1, Math.round(doc.canvas.height * sy))
188
- };
189
- return out;
190
- }
191
- var normAngle = (deg) => {
192
- const a = ((deg + 180) % 360 + 360) % 360 - 180;
193
- return a === -180 ? 180 : a;
194
- };
195
- function transformPaint(p, fn) {
196
- if (!p || typeof p !== "object") return;
197
- if (p.type === "linear") p.angle = r2(normAngle(fn.angle(p.angle ?? 90)));
198
- else if (p.type === "radial") {
199
- const [cx, cy] = fn.point(p.cx ?? .5, p.cy ?? .5);
200
- p.cx = r2(cx);
201
- p.cy = r2(cy);
202
- }
203
- }
204
- function transformCanvasPaints(doc, fn) {
205
- transformPaint(doc.canvas.background, fn);
206
- eachLayer(doc.layers, (l) => {
207
- if (hasBox(l)) return;
208
- if (l.type === "fill") transformPaint(l.fill, fn);
209
- if (l.mask && isGradientMask(l.mask)) transformPaint(l.mask.gradient, fn);
210
- });
211
- }
212
- function rotateDoc(doc, angle, sizes = {}) {
213
- const a = (Math.round(angle / 90) * 90 % 360 + 360) % 360;
214
- if (angle % 90 !== 0) throw new OpsError("invalid", `Canvas rotation must be a multiple of 90°, got ${angle}.`, "To straighten a photo by a few degrees, set the image layer's rotation instead (and crop).");
215
- if (a === 0) return clone(doc);
216
- const out = clone(doc);
217
- const W = doc.canvas.width;
218
- const H = doc.canvas.height;
219
- const map = (x, y) => a === 90 ? [H - y, x] : a === 180 ? [W - x, H - y] : [y, W - x];
220
- eachLayer(out.layers, (l) => {
221
- pinSize(l, sizes);
222
- const box = layerBox(l, sizes);
223
- if (box) {
224
- const [cx, cy] = map(box.x + box.width / 2, box.y + box.height / 2);
225
- const bl = l;
226
- bl.x = r2(cx - box.width / 2);
227
- bl.y = r2(cy - box.height / 2);
228
- bl.rotation = normAngle((bl.rotation ?? 0) + a);
229
- if (bl.rotation === 0) delete bl.rotation;
230
- } else if (l.mask && isShapeMask(l.mask)) {
231
- const m = l.mask;
232
- const [cx, cy] = map(m.x + m.width / 2, m.y + m.height / 2);
233
- const [w, h] = a === 180 ? [m.width, m.height] : [m.height, m.width];
234
- Object.assign(m, {
235
- x: r2(cx - w / 2),
236
- y: r2(cy - h / 2),
237
- width: w,
238
- height: h
239
- });
240
- }
241
- });
242
- transformCanvasPaints(out, {
243
- angle: (deg) => deg + a,
244
- point: (fx, fy) => a === 90 ? [1 - fy, fx] : a === 180 ? [1 - fx, 1 - fy] : [fy, 1 - fx]
245
- });
246
- if (a !== 180) out.canvas = {
247
- ...out.canvas,
248
- width: H,
249
- height: W
250
- };
251
- return out;
252
- }
253
- function flipDoc(doc, axis, sizes = {}) {
254
- if (axis !== "horizontal" && axis !== "vertical") throw new OpsError("invalid", `axis must be "horizontal" or "vertical".`);
255
- const out = clone(doc);
256
- const W = doc.canvas.width;
257
- const H = doc.canvas.height;
258
- eachLayer(out.layers, (l) => {
259
- pinSize(l, sizes);
260
- const box = layerBox(l, sizes);
261
- if (box) {
262
- const bl = l;
263
- if (axis === "horizontal") {
264
- bl.x = r2(W - box.x - box.width);
265
- if (l.type !== "text") bl.flipX = !bl.flipX || void 0;
266
- } else {
267
- bl.y = r2(H - box.y - box.height);
268
- if (l.type !== "text") bl.flipY = !bl.flipY || void 0;
269
- }
270
- if (bl.rotation) bl.rotation = -bl.rotation;
271
- if (!bl.flipX) delete bl.flipX;
272
- if (!bl.flipY) delete bl.flipY;
273
- } else if (l.mask && isShapeMask(l.mask)) {
274
- const m = l.mask;
275
- if (axis === "horizontal") m.x = r2(W - m.x - m.width);
276
- else m.y = r2(H - m.y - m.height);
277
- }
278
- });
279
- transformCanvasPaints(out, axis === "horizontal" ? {
280
- angle: (deg) => 180 - deg,
281
- point: (fx, fy) => [1 - fx, fy]
282
- } : {
283
- angle: (deg) => -deg,
284
- point: (fx, fy) => [fx, 1 - fy]
285
- });
286
- return out;
287
- }
12
+ import { a as isShapeMask, n as hasBox } from "./types-DOK7tAAu.mjs";
13
+ import { i as hasErrors, o as readJson, r as OpsError } from "./context-CNpRboiC.mjs";
14
+ import { c as rotateDoc, i as flipDoc, l as scaleDoc, n as cropDoc, r as fitLayerDoc, s as resizeCanvasDoc, t as ANCHORS } from "./geometry-BKIhUO9x.mjs";
15
+ import { a as layerDetail, i as isDescendant, l as walkLayers, n as findLayer, o as maskKind, r as flattenLayers, t as allLayerIds } from "./tree-D8qZKPAb.mjs";
16
+ import { n as DOC_FILE, o as saveDoc } from "./project-o1DH2nOw.mjs";
288
17
  // src/ops/doc.ts
289
18
  var doc_exports = /* @__PURE__ */ __exportAll({
290
19
  DOC_FILE: () => DOC_FILE,
@@ -493,12 +222,14 @@ var PATCH_OPS = [
493
222
  "resizeCanvas",
494
223
  "resizeImage",
495
224
  "rotateCanvas",
496
- "flipCanvas"
225
+ "flipCanvas",
226
+ "fitLayer"
497
227
  ];
498
228
  var GEOMETRY_OPS = /* @__PURE__ */ new Set([
499
229
  "resizeImage",
500
230
  "rotateCanvas",
501
- "flipCanvas"
231
+ "flipCanvas",
232
+ "fitLayer"
502
233
  ]);
503
234
  var isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
504
235
  function opError(i, code, message, hint) {
@@ -545,7 +276,7 @@ function checkNewIds(doc, layer, i) {
545
276
  visit(layer);
546
277
  }
547
278
  function renameTree(l, taken, rootId) {
548
- const copy = clone$1(l);
279
+ const copy = clone(l);
549
280
  const visit = (x, isRoot) => {
550
281
  x.id = isRoot && rootId ? rootId : uniqueId(`${x.id}-copy`, taken);
551
282
  taken.add(x.id);
@@ -565,14 +296,14 @@ function filterIndex(list, index, i, id) {
565
296
  }
566
297
  function applyPatchOps(doc, ops, sizes = {}) {
567
298
  if (!Array.isArray(ops)) throw new OpsError("invalid", "ops must be an array of patch operations.");
568
- let d = clone$1(doc);
299
+ let d = clone(doc);
569
300
  ops.forEach((op, i) => {
570
301
  if (!isObj(op) || typeof op.op !== "string") throw opError(i, "invalid", "Each op is an object with an \"op\" field.", `Ops: ${PATCH_OPS.join(", ")}.`);
571
302
  try {
572
303
  switch (op.op) {
573
304
  case "set":
574
305
  if (typeof op.path !== "string") throw opError(i, "invalid", "\"path\" is required.");
575
- setAt(d, op.path, clone$1(op.value));
306
+ setAt(d, op.path, clone(op.value));
576
307
  break;
577
308
  case "merge": {
578
309
  if (typeof op.path !== "string") throw opError(i, "invalid", "\"path\" is required.");
@@ -593,7 +324,7 @@ function applyPatchOps(doc, ops, sizes = {}) {
593
324
  if (!isObj(op.layer)) throw opError(i, "invalid", "\"layer\" (a layer object) is required.");
594
325
  checkNewIds(d, op.layer, i);
595
326
  const t = target(d, op, i);
596
- t.container.splice(t.index, 0, clone$1(op.layer));
327
+ t.container.splice(t.index, 0, clone(op.layer));
597
328
  break;
598
329
  }
599
330
  case "updateLayer": {
@@ -673,7 +404,7 @@ function applyPatchOps(doc, ops, sizes = {}) {
673
404
  if (!isObj(op.filter) || typeof op.filter.type !== "string") throw opError(i, "invalid", "\"filter\" ({ type, ...params }) is required.", "e.g. { \"type\": \"brightnessContrast\", \"contrast\": 20 } — catalog_get section \"filters\".");
674
405
  const list = filtersOf(loc, i);
675
406
  const at = op.index === void 0 ? list.length : Math.max(0, Math.min(list.length, op.index));
676
- list.splice(at, 0, clone$1(op.filter));
407
+ list.splice(at, 0, clone(op.filter));
677
408
  break;
678
409
  }
679
410
  case "updateFilter": {
@@ -691,7 +422,7 @@ function applyPatchOps(doc, ops, sizes = {}) {
691
422
  case "setMask": {
692
423
  const loc = need(d, op.id, i);
693
424
  if (op.mask === null || op.mask === void 0) delete loc.layer.mask;
694
- else loc.layer.mask = clone$1(op.mask);
425
+ else loc.layer.mask = clone(op.mask);
695
426
  break;
696
427
  }
697
428
  case "crop":
@@ -721,6 +452,14 @@ function applyPatchOps(doc, ops, sizes = {}) {
721
452
  case "flipCanvas":
722
453
  d = flipDoc(d, op.axis, sizes);
723
454
  break;
455
+ case "fitLayer":
456
+ need(d, op.id, i);
457
+ d = fitLayerDoc(d, op.id, op.box, {
458
+ subject: op.subject,
459
+ anchor: op.anchor,
460
+ sizes
461
+ });
462
+ break;
724
463
  default: throw opError(i, "invalid", `Unknown op "${op.op}".`, `${didYouMean(op.op, PATCH_OPS)}Ops: ${PATCH_OPS.join(", ")}.`);
725
464
  }
726
465
  } catch (e) {
@@ -770,4 +509,4 @@ async function patchDoc(fs, ops, opts = {}) {
770
509
  doc
771
510
  };
772
511
  }
773
- export { patchDoc as a, layerBox as c, getDoc as i, applyDoc as n, summarizeDoc as o, doc_exports as r, geometry_exports as s, PATCH_OPS as t };
512
+ export { patchDoc as a, getDoc as i, applyDoc as n, summarizeDoc as o, doc_exports as r, PATCH_OPS as t };
@@ -7,7 +7,7 @@ __apDirname(__filename);
7
7
  import { t as __exportAll } from "./rolldown-runtime-CMQPkI6i.mjs";
8
8
  import { d as sizePreset, s as SIZE_PRESETS } from "./catalog-DIZ5dnH5.mjs";
9
9
  import { l as didYouMean, o as isValidColor, s as parseColor, t as MAX_CANVAS } from "./validate-CXPFB-i6.mjs";
10
- import { r as OpsError } from "./context-DoLoLF9f.mjs";
10
+ import { r as OpsError } from "./context-CNpRboiC.mjs";
11
11
  // src/ops/export.ts
12
12
  var export_exports = /* @__PURE__ */ __exportAll({
13
13
  DEFAULT_QUALITY: () => DEFAULT_QUALITY,