@mainsoft/agent-cms 0.10.1 → 0.11.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.
Files changed (87) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +98 -2
  3. package/TODO.md +6 -6
  4. package/UPGRADE-0.11.md +43 -0
  5. package/dist/agent.d.cts +1 -1
  6. package/dist/agent.d.ts +1 -1
  7. package/dist/agent.js +7 -7
  8. package/dist/bin.js +236 -23
  9. package/dist/{chunk-IU2SMWAM.js → chunk-42PW3HQ3.js} +15 -1
  10. package/dist/{chunk-6PB4ZCHH.js → chunk-CIMW73L3.js} +58 -1
  11. package/dist/{chunk-7Y6TU2UA.js → chunk-HY4ED7LT.js} +2 -2
  12. package/dist/{chunk-DSJETZT4.js → chunk-I3DF6DMI.js} +15 -10
  13. package/dist/{chunk-KAO3Z3CF.js → chunk-I5UHTAAW.js} +3 -1
  14. package/dist/{chunk-7SCYDG2G.js → chunk-J25IKU7C.js} +164 -28
  15. package/dist/{chunk-BFVBHIHV.js → chunk-J5DW3RFQ.js} +4 -1
  16. package/dist/{chunk-7WJIIJCI.js → chunk-LELPCGDX.js} +8 -5
  17. package/dist/{chunk-QMPSOLLH.js → chunk-NO6S7KOL.js} +1 -1
  18. package/dist/{chunk-ZCUJ4MPT.js → chunk-OLHLSSTD.js} +3 -3
  19. package/dist/{chunk-3OPKTBEI.js → chunk-SV3ZA6XP.js} +1 -1
  20. package/dist/{chunk-PEQY4N73.js → chunk-TKKTEGHL.js} +1 -0
  21. package/dist/{chunk-PGV2QPIL.js → chunk-WWG7XDIZ.js} +2 -0
  22. package/dist/cli.cjs +236 -23
  23. package/dist/cli.d.cts +2 -2
  24. package/dist/cli.d.ts +2 -2
  25. package/dist/cli.js +18 -16
  26. package/dist/client.cjs +4 -1
  27. package/dist/client.d.cts +14 -2
  28. package/dist/client.d.ts +14 -2
  29. package/dist/client.js +1 -1
  30. package/dist/{cms-pqJyowu1.d.ts → cms-A9tmLmTP.d.ts} +100 -5
  31. package/dist/{cms-C_vkAxYV.d.cts → cms-CaB81PPX.d.cts} +100 -5
  32. package/dist/config.d.cts +1 -1
  33. package/dist/config.d.ts +1 -1
  34. package/dist/{drizzle-repo-DWLD0rWe.d.ts → drizzle-repo-BXV-hFkE.d.ts} +1 -1
  35. package/dist/{drizzle-repo-CviH3EX7.d.cts → drizzle-repo-CblPVYnK.d.cts} +1 -1
  36. package/dist/errors.cjs +4 -0
  37. package/dist/errors.d.cts +3 -1
  38. package/dist/errors.d.ts +3 -1
  39. package/dist/errors.js +2 -2
  40. package/dist/frontmatter.d.cts +1 -1
  41. package/dist/frontmatter.d.ts +1 -1
  42. package/dist/http.cjs +32 -12
  43. package/dist/http.d.cts +18 -4
  44. package/dist/http.d.ts +18 -4
  45. package/dist/http.js +30 -20
  46. package/dist/image-sharp.cjs +104 -0
  47. package/dist/image-sharp.d.cts +47 -0
  48. package/dist/image-sharp.d.ts +47 -0
  49. package/dist/image-sharp.js +70 -0
  50. package/dist/index.cjs +244 -27
  51. package/dist/index.d.cts +3 -3
  52. package/dist/index.d.ts +3 -3
  53. package/dist/index.js +21 -21
  54. package/dist/mcp.cjs +9 -4
  55. package/dist/mcp.d.cts +1 -1
  56. package/dist/mcp.d.ts +1 -1
  57. package/dist/mcp.js +11 -11
  58. package/dist/messages/en.cjs +2 -0
  59. package/dist/messages/en.js +1 -1
  60. package/dist/messages/ko.cjs +2 -0
  61. package/dist/messages/ko.js +2 -0
  62. package/dist/registry/cms-doc-editor.json +6 -1
  63. package/dist/registry/cms-lib.json +2 -2
  64. package/dist/registry/cms-media-picker.json +2 -2
  65. package/dist/registry/cms-media.json +1 -1
  66. package/dist/registry/registry.json +4 -0
  67. package/dist/storage-vercel-blob.cjs +199 -0
  68. package/dist/storage-vercel-blob.d.cts +98 -0
  69. package/dist/storage-vercel-blob.d.ts +98 -0
  70. package/dist/storage-vercel-blob.js +165 -0
  71. package/dist/storage.cjs +63 -3
  72. package/dist/storage.d.cts +27 -2
  73. package/dist/storage.d.ts +27 -2
  74. package/dist/storage.js +9 -3
  75. package/dist/tables.cjs +15 -1
  76. package/dist/tables.d.cts +154 -1
  77. package/dist/tables.d.ts +154 -1
  78. package/dist/tables.js +2 -2
  79. package/dist/tools.cjs +8 -3
  80. package/dist/tools.d.cts +1 -1
  81. package/dist/tools.d.ts +1 -1
  82. package/dist/tools.js +9 -9
  83. package/dist/types.cjs +5 -0
  84. package/dist/types.d.cts +6 -1
  85. package/dist/types.d.ts +6 -1
  86. package/dist/types.js +3 -3
  87. package/package.json +36 -2
package/dist/bin.js CHANGED
@@ -452,6 +452,60 @@ var DEFAULT_MAX_FILE_SIZE = 5 * 1024 ** 3;
452
452
  var PART_SIZE = 16 * 1024 * 1024;
453
453
  var THUMB_PREFIX = "_cms/thumbs/";
454
454
  var RESERVED_FOLDER = "_cms";
455
+ var DERIVED_PREFIX = "_cms/derived/";
456
+ var REPLACE_PREFIX = "_cms/replace/";
457
+ function stripJpegMetadata(b) {
458
+ if (b.length < 4 || b[0] !== 255 || b[1] !== 216) return b;
459
+ const keep = [];
460
+ let orientation = 1;
461
+ let dropped = false;
462
+ let i = 2;
463
+ while (i + 4 <= b.length && b[i] === 255) {
464
+ const m = b[i + 1];
465
+ if (m === 218 || m === 217) break;
466
+ if (m === 255) {
467
+ i++;
468
+ continue;
469
+ }
470
+ if (m >= 208 && m <= 215 || m === 1) {
471
+ keep.push([i, i + 2]);
472
+ i += 2;
473
+ continue;
474
+ }
475
+ const end = i + 2 + (b[i + 2] << 8 | b[i + 3]);
476
+ if (end < i + 4 || end > b.length) return b;
477
+ if (m === 225 || m === 237 || m === 254) {
478
+ dropped = true;
479
+ if (m === 225 && end - i >= 18 && b[i + 4] === 69 && b[i + 5] === 120 && b[i + 6] === 105 && b[i + 7] === 102) orientation = exifOrientation(b.subarray(i + 10, end)) ?? orientation;
480
+ } else keep.push([i, end]);
481
+ i = end;
482
+ }
483
+ if (!dropped) return b;
484
+ const turn = orientation >= 2 && orientation <= 8 ? Uint8Array.of(255, 225, 0, 34, 69, 120, 105, 102, 0, 0, 77, 77, 0, 42, 0, 0, 0, 8, 0, 1, 1, 18, 0, 3, 0, 0, 0, 1, 0, orientation, 0, 0, 0, 0, 0, 0) : new Uint8Array();
485
+ const out = new Uint8Array(2 + turn.length + keep.reduce((n, [a, z2]) => n + z2 - a, 0) + b.length - i);
486
+ out.set(b.subarray(0, 2));
487
+ out.set(turn, 2);
488
+ let at = 2 + turn.length;
489
+ for (const [a, z2] of keep) {
490
+ out.set(b.subarray(a, z2), at);
491
+ at += z2 - a;
492
+ }
493
+ out.set(b.subarray(i), at);
494
+ return out;
495
+ }
496
+ function exifOrientation(t) {
497
+ if (t.length < 14) return null;
498
+ const le = t[0] === 73;
499
+ const u16 = (o) => le ? t[o] | t[o + 1] << 8 : t[o] << 8 | t[o + 1];
500
+ const ifd = le ? t[4] | t[5] << 8 | t[6] << 16 | t[7] << 24 : (t[4] << 24 | t[5] << 16 | t[6] << 8 | t[7]) >>> 0;
501
+ if (ifd < 8 || ifd + 2 > t.length) return null;
502
+ const n = u16(ifd);
503
+ for (let k = 0; k < n && ifd + 2 + (k + 1) * 12 <= t.length; k++) {
504
+ const e = ifd + 2 + k * 12;
505
+ if (u16(e) === 274) return u16(e + 8);
506
+ }
507
+ return null;
508
+ }
455
509
  var extOf = (name) => {
456
510
  const m = /\.([a-z0-9]{1,10})$/i.exec(name);
457
511
  return m ? m[1].toLowerCase() : "";
@@ -592,6 +646,16 @@ var ASSET_ID_RE = /^[a-z0-9]{12}$/;
592
646
  var SIGN_SECONDS = 3600;
593
647
  var MAX_THUMB_BYTES = 512 * 1024;
594
648
  var TAG_MAX = 30;
649
+ var IMAGE_EXT = { webp: "webp", avif: "avif", jpeg: "jpg", png: "png" };
650
+ var FOREVER = "public, max-age=31536000, immutable";
651
+ function stamp(v) {
652
+ let h = 2166136261;
653
+ for (const c of JSON.stringify(v)) h = Math.imul(h ^ c.charCodeAt(0), 16777619);
654
+ return (h >>> 0).toString(36);
655
+ }
656
+ var withRev = (url, rev) => rev > 0 ? `${url}${url.includes("?") ? "&" : "?"}v=${rev}` : url;
657
+ var focalOf = (a) => a.focalX !== null && a.focalY !== null ? { x: a.focalX, y: a.focalY } : null;
658
+ var resizable = (a) => a.kind === "image" && a.mime !== "image/svg+xml" && a.mime !== "image/gif";
595
659
  function humanSize(bytes) {
596
660
  const units = ["B", "KB", "MB", "GB", "TB"];
597
661
  let n = bytes;
@@ -612,6 +676,7 @@ function createAssets(ctx) {
612
676
  const names2 = Object.keys(media?.stores ?? {});
613
677
  const filesUrl = (media?.filesUrl ?? "/api/cms/files").replace(/\/+$/, "");
614
678
  const ttl = media?.linkTtlSeconds ?? 300;
679
+ const transforms = media?.transforms ?? null;
615
680
  for (const n of names2) {
616
681
  const s = media.stores[n];
617
682
  const rules = s.accept ?? media.accept ?? DEFAULT_ACCEPT;
@@ -644,11 +709,12 @@ function createAssets(ctx) {
644
709
  function view(a) {
645
710
  const cfg = media?.stores[a.store];
646
711
  const href = `${filesUrl}/${a.id}/${encodeURIComponent(a.name)}`;
647
- return { ...a, visibility: cfg?.visibility ?? "private", href, publicUrl: cfg?.visibility === "public" ? cfg.adapter.publicUrl(a.key) : null, thumbHref: a.thumbKey ? `${href}?thumb=1` : null };
712
+ const direct = cfg?.visibility === "public" ? cfg.adapter.publicUrl(a.key) : null;
713
+ return { ...a, visibility: cfg?.visibility ?? "private", href, publicUrl: direct ? withRev(direct, a.rev) : null, thumbHref: a.thumbKey ? `${href}?thumb=1${a.rev ? `&v=${a.rev}` : ""}` : null };
648
714
  }
649
715
  const info = (a) => {
650
716
  const v = view(a);
651
- return { id: a.id, name: a.name, kind: a.kind, mime: a.mime, size: a.size, width: a.width, height: a.height, duration: a.duration, alt: a.alt, url: v.publicUrl ?? v.href, visibility: v.visibility };
717
+ return { id: a.id, name: a.name, kind: a.kind, mime: a.mime, size: a.size, width: a.width, height: a.height, duration: a.duration, alt: a.alt, url: v.publicUrl ?? v.href, visibility: v.visibility, focal: focalOf(a) };
652
718
  };
653
719
  async function load(id, o = {}) {
654
720
  const a = ASSET_ID_RE.test(id) ? await repo.findAsset(id) : null;
@@ -691,23 +757,25 @@ function createAssets(ctx) {
691
757
  }
692
758
  async function requestUpload(actor, input) {
693
759
  await ctx.ready();
694
- const store = storeOf(input.store);
760
+ const target = input.replace ? await replaceable(actor, input.replace, input) : null;
761
+ const store = storeOf(target ? target.store : input.store);
695
762
  need(actor, store.name, "write");
696
- const a = admit(store, input);
697
- const free = await freeKey(store, a.folder, a.name);
763
+ const a = target ? admit(store, { name: target.name, mime: target.mime, size: input.size, folder: target.folder }) : admit(store, input);
764
+ const id = newAssetId();
765
+ const free = target ? { key: `${REPLACE_PREFIX}${target.id}/${id}${extOf(target.name) ? `.${extOf(target.name)}` : ""}`, name: target.name } : await freeKey(store, a.folder, a.name);
698
766
  const put2 = { mime: a.mime, disposition: dispositionFor(free.name, a.mime) };
699
767
  const who = ctx.actorRef(actor);
700
768
  let upload;
701
769
  let uploadId = null;
702
- if (input.size <= PART_SIZE) {
703
- const signed = await store.cfg.adapter.presignPut(free.key, { ...put2, expires: SIGN_SECONDS });
770
+ if (input.size <= PART_SIZE || store.cfg.adapter.multipart === false) {
771
+ const signed = await store.cfg.adapter.presignPut(free.key, { ...put2, expires: SIGN_SECONDS, size: input.size });
704
772
  upload = { kind: "single", url: signed.url, headers: signed.headers };
705
773
  } else {
706
774
  uploadId = await store.cfg.adapter.createMultipart(free.key, put2);
707
775
  upload = { kind: "multipart", partSize: PART_SIZE, partCount: Math.ceil(input.size / PART_SIZE) };
708
776
  }
709
777
  const row = await repo.insertAsset({
710
- id: newAssetId(),
778
+ id,
711
779
  store: store.name,
712
780
  key: free.key,
713
781
  folder: a.folder,
@@ -755,9 +823,107 @@ function createAssets(ctx) {
755
823
  });
756
824
  if (a.thumbKey) await adapter.delete(a.thumbKey).catch(() => {
757
825
  });
826
+ await dropDerived(a);
758
827
  }
759
828
  await repo.deleteAsset(a.id);
760
829
  }
830
+ async function replaceable(actor, id, input) {
831
+ const t = await load(id);
832
+ need(actor, t.store, "delete");
833
+ if (t.kind === "folder" || mimeOf(cleanName(input.name), input.mime) !== t.mime) throw fail("asset_replace_type", { name: input.name, mime: t.mime });
834
+ return t;
835
+ }
836
+ async function replaced(actor, t, now) {
837
+ const adapter = storeOf(t.store).cfg.adapter;
838
+ if (t.thumbKey) await adapter.delete(t.thumbKey).catch(() => {
839
+ });
840
+ await dropDerived(t);
841
+ const row = await repo.updateAsset(t.id, { ...now, thumbKey: null, rev: t.rev + 1, updatedAt: ctx.nowIso() });
842
+ ctx.audit(actor, "asset.replace", { detail: { id: t.id, store: t.store, key: t.key, size: now.size, was: t.size } });
843
+ return row;
844
+ }
845
+ async function replace(actor, id, input) {
846
+ await ctx.ready();
847
+ const t = await replaceable(actor, id, { name: (await load(id)).name, mime: input.mime });
848
+ const store = storeOf(t.store);
849
+ const bytes = media?.stripMetadata && t.mime === "image/jpeg" ? stripJpegMetadata(input.bytes) : input.bytes;
850
+ admit(store, { name: t.name, mime: t.mime, size: bytes.length, folder: t.folder });
851
+ if (!contentMatches(t.mime, bytes.subarray(0, 4096))) throw fail("asset_type_mismatch", { name: t.name, mime: t.mime });
852
+ await scanned(actor, { store: t.store, key: t.key, name: t.name, mime: t.mime, size: bytes.length, bytes }, null);
853
+ await store.cfg.adapter.put(t.key, bytes, { mime: t.mime, disposition: dispositionFor(t.name, t.mime) });
854
+ const given = dims(input);
855
+ const read = t.kind === "image" && !given.width ? imageSize(bytes) : null;
856
+ return view(await serverThumb(await replaced(actor, t, { size: bytes.length, width: given.width ?? read?.width ?? null, height: given.height ?? read?.height ?? null, duration: given.duration }), bytes));
857
+ }
858
+ const made = /* @__PURE__ */ new Set();
859
+ const making = /* @__PURE__ */ new Map();
860
+ const waiting = [];
861
+ let active = 0;
862
+ const jobOf = (a, p) => ({ width: p.width ?? null, height: p.height ?? null, fit: p.fit ?? "inside", format: p.format ?? transforms.format, quality: p.quality ?? null, focal: focalOf(a) });
863
+ async function sized(a, size) {
864
+ const preset = transforms?.presets[size];
865
+ if (!transforms || !preset) throw fail("unknown_image_size", { size });
866
+ if (!resizable(a) || a.size > (transforms.maxInputBytes ?? 40 * 1024 * 1024)) return null;
867
+ const job = jobOf(a, preset);
868
+ const key = `${DERIVED_PREFIX}${a.id}/${size}-${stamp([a.rev, a.size, job])}.${IMAGE_EXT[job.format]}`;
869
+ if (made.has(key)) return key;
870
+ let work = making.get(key);
871
+ if (!work) {
872
+ work = (async () => {
873
+ const adapter = storeOf(a.store).cfg.adapter;
874
+ if (await adapter.head(key)) return key;
875
+ if (active >= (transforms.concurrency ?? 4)) await new Promise((go) => waiting.push(go));
876
+ else active++;
877
+ try {
878
+ const bytes = await adapter.readStart(a.key, a.size);
879
+ if (!bytes) return null;
880
+ const out = await transforms.make(bytes, job);
881
+ await adapter.put(key, out.bytes, { mime: `image/${job.format}`, cacheControl: FOREVER });
882
+ return key;
883
+ } finally {
884
+ const next = waiting.shift();
885
+ if (next) next();
886
+ else active--;
887
+ }
888
+ })().then((k) => (k && made.add(k), k)).catch((e) => (ctx.warn(`image-size-${a.id}-${size}`, `could not make size "${size}" of ${a.key}: ${e instanceof Error ? e.message : String(e)}`), null)).finally(() => making.delete(key));
889
+ making.set(key, work);
890
+ }
891
+ let timer;
892
+ const late = new Promise((r) => timer = setTimeout(() => r(null), transforms.timeoutMs ?? 1e4));
893
+ try {
894
+ return await Promise.race([work, late]);
895
+ } finally {
896
+ clearTimeout(timer);
897
+ }
898
+ }
899
+ async function dropDerived(a) {
900
+ const adapter = media?.stores[a.store]?.adapter;
901
+ if (!adapter || !transforms) return;
902
+ try {
903
+ let cursor = null;
904
+ do {
905
+ const page = await adapter.list({ prefix: `${DERIVED_PREFIX}${a.id}/`, cursor, limit: 200 });
906
+ for (const o of page.objects) {
907
+ await adapter.delete(o.key).catch(() => {
908
+ });
909
+ made.delete(o.key);
910
+ }
911
+ cursor = page.cursor;
912
+ } while (cursor);
913
+ } catch {
914
+ }
915
+ }
916
+ async function serverThumb(row, bytes) {
917
+ if (!transforms || !resizable(row) || bytes.length > (transforms.maxInputBytes ?? 40 * 1024 * 1024)) return row;
918
+ try {
919
+ const out = await transforms.make(bytes, { width: 480, height: 480, fit: "inside", format: "webp", quality: null, focal: null });
920
+ const key = `${THUMB_PREFIX}${row.id}.webp`;
921
+ await storeOf(row.store).cfg.adapter.put(key, out.bytes, { mime: "image/webp", cacheControl: FOREVER });
922
+ return await repo.updateAsset(row.id, { thumbKey: key }) ?? row;
923
+ } catch {
924
+ return row;
925
+ }
926
+ }
761
927
  const dims = (o) => {
762
928
  const int = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 && v < 1e5 ? Math.round(v) : null;
763
929
  return { width: int(o.width), height: int(o.height), duration: typeof o.duration === "number" && Number.isFinite(o.duration) && o.duration >= 0 ? o.duration : null };
@@ -792,6 +958,19 @@ function createAssets(ctx) {
792
958
  });
793
959
  const given = dims(meta);
794
960
  const read = a.kind === "image" && !given.width ? imageSize(start) : null;
961
+ const settle = (key, name) => adapter.settle?.(key, { mime: a.mime, disposition: dispositionFor(name, a.mime) });
962
+ if (a.key.startsWith(REPLACE_PREFIX)) {
963
+ const t = await repo.findAsset(a.key.slice(REPLACE_PREFIX.length).split("/")[0]);
964
+ if (!t || t.status !== "ready" || !canAsset(actor, t.store, "delete")) {
965
+ await discard({ ...a, uploadId: null });
966
+ throw fail("asset_not_found", { id });
967
+ }
968
+ await adapter.copy(a.key, t.key);
969
+ await settle(t.key, t.name);
970
+ await discard({ ...a, uploadId: null });
971
+ return view(await replaced(actor, t, { size: head.size, width: given.width ?? read?.width ?? null, height: given.height ?? read?.height ?? null, duration: given.duration }));
972
+ }
973
+ await settle(a.key, a.name);
795
974
  const row = await repo.updateAsset(a.id, { status: "ready", uploadId: null, width: given.width ?? read?.width ?? null, height: given.height ?? read?.height ?? null, duration: given.duration, updatedAt: ctx.nowIso() });
796
975
  ctx.audit(actor, "asset.upload", { detail: { id: a.id, store: a.store, key: a.key, size: a.size } });
797
976
  return view(row);
@@ -817,6 +996,7 @@ function createAssets(ctx) {
817
996
  await ctx.ready();
818
997
  const store = storeOf(input.store);
819
998
  need(actor, store.name, "write");
999
+ if (media?.stripMetadata && mimeOf(cleanName(input.name), input.mime) === "image/jpeg") input = { ...input, bytes: stripJpegMetadata(input.bytes) };
820
1000
  const a = admit(store, { ...input, size: input.bytes.length });
821
1001
  if (!contentMatches(a.mime, input.bytes.subarray(0, 4096))) throw fail("asset_type_mismatch", { name: a.name, mime: a.mime });
822
1002
  const free = await freeKey(store, a.folder, a.name);
@@ -850,7 +1030,7 @@ function createAssets(ctx) {
850
1030
  updatedAt: ctx.nowIso()
851
1031
  });
852
1032
  ctx.audit(actor, "asset.upload", { detail: { id: row.id, store: row.store, key: row.key, size: row.size } });
853
- return view(row);
1033
+ return view(await serverThumb(row, input.bytes));
854
1034
  }
855
1035
  async function importFromUrl(actor, input) {
856
1036
  const store = storeOf(input.store);
@@ -961,7 +1141,10 @@ function createAssets(ctx) {
961
1141
  async function update(actor, id, patch) {
962
1142
  const a = await load(id);
963
1143
  need(actor, a.store, "write");
964
- const row = await repo.updateAsset(a.id, { ...patch.alt !== void 0 ? { alt: String(patch.alt).trim().slice(0, 500) } : {}, ...patch.tags !== void 0 ? { tags: cleanTags(patch.tags) } : {}, updatedAt: ctx.nowIso() });
1144
+ const unit = (v) => Math.round(Math.min(1, Math.max(0, Number(v) || 0)) * 1e3) / 1e3;
1145
+ const focal = patch.focal === void 0 ? {} : patch.focal === null || a.kind !== "image" ? { focalX: null, focalY: null } : { focalX: unit(patch.focal.x), focalY: unit(patch.focal.y) };
1146
+ const row = await repo.updateAsset(a.id, { ...patch.alt !== void 0 ? { alt: String(patch.alt).trim().slice(0, 500) } : {}, ...patch.tags !== void 0 ? { tags: cleanTags(patch.tags) } : {}, ...focal, updatedAt: ctx.nowIso() });
1147
+ if ("focalX" in focal && (focal.focalX !== a.focalX || focal.focalY !== a.focalY)) await dropDerived(a);
965
1148
  return view(row);
966
1149
  }
967
1150
  async function move(actor, id, to) {
@@ -1031,8 +1214,9 @@ function createAssets(ctx) {
1031
1214
  const a = await load(id);
1032
1215
  const store = storeOf(a.store);
1033
1216
  if (store.cfg.visibility === "private" || store.cfg.access?.read) need(actor, a.store, "read");
1034
- const key = o.thumb && a.thumbKey ? a.thumbKey : a.key;
1035
- const direct = store.cfg.visibility === "public" && !o.download ? store.cfg.adapter.publicUrl(key) : null;
1217
+ const key = o.thumb && a.thumbKey ? a.thumbKey : o.size && !o.thumb ? await sized(a, o.size) ?? a.key : a.key;
1218
+ const plain = store.cfg.visibility === "public" && !o.download ? store.cfg.adapter.publicUrl(key) : null;
1219
+ const direct = plain && !key.startsWith(DERIVED_PREFIX) ? withRev(plain, a.rev) : plain;
1036
1220
  return { url: direct ?? await store.cfg.adapter.presignGet(key, { expires: ttl, download: o.download ? a.name : null }), visibility: store.cfg.visibility, ttl };
1037
1221
  }
1038
1222
  async function cleanup(o = {}) {
@@ -1112,7 +1296,9 @@ function createAssets(ctx) {
1112
1296
  return Object.fromEntries(rows.filter((a) => a.status === "ready" && media.stores[a.store]).map((a) => [a.id, info(a)]));
1113
1297
  }
1114
1298
  function imageUrl(asset, o) {
1115
- return media?.imageUrl && asset.kind === "image" && asset.mime !== "image/svg+xml" ? media.imageUrl({ url: asset.url, width: o.width, asset }) : asset.url;
1299
+ if (asset.kind !== "image" || asset.mime === "image/svg+xml") return asset.url;
1300
+ if (o.size && transforms?.presets[o.size] && asset.mime !== "image/gif") return `${filesUrl}/${asset.id}/${encodeURIComponent(asset.name)}?size=${encodeURIComponent(o.size)}`;
1301
+ return media?.imageUrl && o.width ? media.imageUrl({ url: asset.url, width: o.width, asset }) : asset.url;
1116
1302
  }
1117
1303
  async function scanned(actor, f, adapter) {
1118
1304
  if (!media?.scan) return;
@@ -1323,9 +1509,9 @@ function createAssets(ctx) {
1323
1509
  if (!media) return null;
1324
1510
  const stores = names2.filter((n) => canAsset(actor, n, "read")).map((n) => {
1325
1511
  const cfg = media.stores[n];
1326
- return { name: n, label: cfg.label ?? n, visibility: cfg.visibility, ...rulesOf(cfg), can: { write: canAsset(actor, n, "write"), delete: canAsset(actor, n, "delete"), browse: canBrowse(actor, n) } };
1512
+ return { name: n, label: cfg.label ?? n, visibility: cfg.visibility, ...rulesOf(cfg), parts: cfg.adapter.multipart !== false, can: { write: canAsset(actor, n, "write"), delete: canAsset(actor, n, "delete"), browse: canBrowse(actor, n) } };
1327
1513
  });
1328
- return stores.length ? { stores, partSize: PART_SIZE } : null;
1514
+ return stores.length ? { stores, partSize: PART_SIZE, stripMetadata: !!media.stripMetadata, sizes: Object.keys(transforms?.presets ?? {}) } : null;
1329
1515
  }
1330
1516
  return {
1331
1517
  enabled: !!media && names2.length > 0,
@@ -1339,6 +1525,7 @@ function createAssets(ctx) {
1339
1525
  abortUpload,
1340
1526
  setThumb,
1341
1527
  put,
1528
+ replace,
1342
1529
  import: importFromUrl,
1343
1530
  list,
1344
1531
  folders,
@@ -1588,7 +1775,10 @@ function createRestClient(opts) {
1588
1775
  /** Address of a file by its key (files the CMS has no row for). */
1589
1776
  storeFileUrl: (store, key, o = {}) => `${base}/stores/${enc(store)}/files/_open?key=${enc(key)}${o.download ? "&download=1" : ""}`,
1590
1777
  /** Address of a file through the CMS route (`thumb`: its small picture). */
1591
- fileUrl: (a, o = {}) => `${base}/files/${enc(a.id)}/${enc(a.name)}${o.thumb ? "?thumb=1" : o.download ? "?download=1" : ""}`,
1778
+ fileUrl: (a, o = {}) => {
1779
+ const query = [o.thumb ? "thumb=1" : o.download ? "download=1" : o.size ? `size=${enc(o.size)}` : "", a.rev ? `v=${a.rev}` : ""].filter(Boolean).join("&");
1780
+ return `${base}/files/${enc(a.id)}/${enc(a.name)}${query ? `?${query}` : ""}`;
1781
+ },
1592
1782
  audit: (q = {}) => req("GET", "/audit", { query: q })
1593
1783
  };
1594
1784
  }
@@ -1650,6 +1840,8 @@ var en = {
1650
1840
  import_blocked: "That address cannot be fetched",
1651
1841
  import_failed: "Could not fetch the file ({reason})",
1652
1842
  asset_rejected: "This file did not pass the check",
1843
+ asset_replace_type: "A file can only be replaced by one of the same type ({mime})",
1844
+ unknown_image_size: "There is no image size named \u201C{size}\u201D",
1653
1845
  asset_missing: "The file {id} does not exist",
1654
1846
  asset_wrong_kind: "The file {id} is not a kind this field takes",
1655
1847
  asset_alt_missing: "The image on line {line} has no alt text",
@@ -1739,6 +1931,8 @@ var ERROR_CODES = {
1739
1931
  import_blocked: "invalid",
1740
1932
  import_failed: "invalid",
1741
1933
  asset_rejected: "invalid",
1934
+ asset_replace_type: "invalid",
1935
+ unknown_image_size: "not_found",
1742
1936
  asset_missing: "invalid",
1743
1937
  asset_wrong_kind: "invalid",
1744
1938
  asset_alt_missing: "invalid",
@@ -2583,7 +2777,7 @@ function displayPrefix(raw) {
2583
2777
  }
2584
2778
 
2585
2779
  // src/schema-version.ts
2586
- var SCHEMA_VERSION = 4;
2780
+ var SCHEMA_VERSION = 5;
2587
2781
 
2588
2782
  // src/search.ts
2589
2783
  var HANGUL = /[\uac00-\ud7a3]/;
@@ -3622,17 +3816,17 @@ ${h.added.join("\n")}`).digest("hex").slice(0, 12);
3622
3816
  const t = Date.now();
3623
3817
  if (index2.built && !index2.dirty && t - index2.checkedAt > refreshMs) {
3624
3818
  index2.checkedAt = t;
3625
- const stamp = await repo.changeStamp().catch(() => index2.stamp);
3626
- if (stamp !== index2.stamp) index2.dirty = true;
3819
+ const stamp2 = await repo.changeStamp().catch(() => index2.stamp);
3820
+ if (stamp2 !== index2.stamp) index2.dirty = true;
3627
3821
  }
3628
3822
  if (index2.built && !index2.dirty) return index2.built;
3629
3823
  if (!index2.building) {
3630
3824
  index2.dirty = false;
3631
3825
  index2.building = (async () => {
3632
- const stamp = await repo.changeStamp();
3826
+ const stamp2 = await repo.changeStamp();
3633
3827
  const built = await buildIndex();
3634
3828
  index2.built = built;
3635
- index2.stamp = stamp;
3829
+ index2.stamp = stamp2;
3636
3830
  index2.checkedAt = Date.now();
3637
3831
  return built;
3638
3832
  })().catch((err) => {
@@ -4050,6 +4244,9 @@ function cmsTables(o = {}) {
4050
4244
  alt: text("alt").notNull().default(""),
4051
4245
  tags: jsonb("tags").$type().notNull().default([]),
4052
4246
  thumbKey: text("thumb_key"),
4247
+ focalX: real("focal_x"),
4248
+ focalY: real("focal_y"),
4249
+ rev: integer("rev").notNull().default(0),
4053
4250
  status: text("status").notNull().default("pending"),
4054
4251
  uploadId: text("upload_id"),
4055
4252
  createdBy: text("created_by"),
@@ -4226,6 +4423,9 @@ CREATE TABLE IF NOT EXISTS ${tbl("assets")} (
4226
4423
  "alt" text NOT NULL DEFAULT '',
4227
4424
  "tags" jsonb NOT NULL DEFAULT '[]'::jsonb,
4228
4425
  "thumb_key" text,
4426
+ "focal_x" real,
4427
+ "focal_y" real,
4428
+ "rev" integer NOT NULL DEFAULT 0,
4229
4429
  "status" text NOT NULL DEFAULT 'pending',
4230
4430
  "upload_id" text,
4231
4431
  "created_by" text,
@@ -4315,6 +4515,14 @@ CREATE TABLE IF NOT EXISTS ${tbl("presence")} (
4315
4515
  PRIMARY KEY ("document_id", "actor_id")
4316
4516
  );
4317
4517
  CREATE INDEX IF NOT EXISTS ${idx("presence_seen_idx")} ON ${tbl("presence")} ("seen_at");`.trim()
4518
+ },
4519
+ {
4520
+ version: 5,
4521
+ name: "agent-cms 0.11.0: an image's focal point, replacing a file at the same address",
4522
+ sql: `
4523
+ ALTER TABLE ${tbl("assets")} ADD COLUMN IF NOT EXISTS "focal_x" real;
4524
+ ALTER TABLE ${tbl("assets")} ADD COLUMN IF NOT EXISTS "focal_y" real;
4525
+ ALTER TABLE ${tbl("assets")} ADD COLUMN IF NOT EXISTS "rev" integer NOT NULL DEFAULT 0;`.trim()
4318
4526
  }
4319
4527
  ];
4320
4528
  }
@@ -4547,6 +4755,9 @@ var DrizzleRepo = class _DrizzleRepo {
4547
4755
  alt: r.alt,
4548
4756
  tags: r.tags ?? [],
4549
4757
  thumbKey: r.thumbKey,
4758
+ focalX: r.focalX ?? null,
4759
+ focalY: r.focalY ?? null,
4760
+ rev: r.rev ?? 0,
4550
4761
  status: r.status,
4551
4762
  uploadId: r.uploadId,
4552
4763
  createdBy: r.createdBy,
@@ -5057,7 +5268,7 @@ import { basename, dirname, join, relative, resolve } from "path";
5057
5268
  import { fileURLToPath } from "url";
5058
5269
 
5059
5270
  // src/version.ts
5060
- var VERSION = "0.10.1";
5271
+ var VERSION = "0.11.0";
5061
5272
 
5062
5273
  // src/registry.ts
5063
5274
  var sha = (s) => createHash3("sha256").update(s).digest("hex");
@@ -5544,7 +5755,8 @@ async function storageCheck(media, origin, io) {
5544
5755
  expect(res.ok, `PUT answered ${res.status}`);
5545
5756
  expect((await a.head(`${run}/b.txt`))?.size === text2.length, "the file did not arrive");
5546
5757
  });
5547
- await step("large files in parts", async () => {
5758
+ if (a.multipart === false) io.out("skip large files in parts: not supported on this store (a file goes up in one request, and a failed upload starts again)");
5759
+ else await step("large files in parts", async () => {
5548
5760
  const id = await a.createMultipart(`${run}/c.bin`, { mime: "application/octet-stream" });
5549
5761
  const sizes = [5 * 1024 * 1024, 1024];
5550
5762
  for (const n of [1, 2]) {
@@ -5597,6 +5809,7 @@ async function storageCheck(media, origin, io) {
5597
5809
  for (const k of ["a.txt", "b.txt", "c.bin", "d.txt"]) await a.delete(`${run}/${k}`).catch(() => {
5598
5810
  });
5599
5811
  }
5812
+ if (Object.values(media.stores).every((s) => s.adapter.multipart === false)) return bad ? 1 : 0;
5600
5813
  io.out("");
5601
5814
  io.out("CORS rule the bucket needs (replace the origin with your site):");
5602
5815
  io.out(JSON.stringify([{ AllowedOrigins: [origin ?? "https://your-site.example"], AllowedMethods: ["GET", "HEAD", "PUT"], AllowedHeaders: ["*"], ExposeHeaders: ["ETag"], MaxAgeSeconds: 3600 }], null, 2));
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  SCHEMA_VERSION
3
- } from "./chunk-3OPKTBEI.js";
3
+ } from "./chunk-SV3ZA6XP.js";
4
4
 
5
5
  // src/tables.ts
6
6
  import { bigint, boolean, date, index, integer, jsonb, pgSchema, pgTable, primaryKey, real, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
@@ -139,6 +139,9 @@ function cmsTables(o = {}) {
139
139
  alt: text("alt").notNull().default(""),
140
140
  tags: jsonb("tags").$type().notNull().default([]),
141
141
  thumbKey: text("thumb_key"),
142
+ focalX: real("focal_x"),
143
+ focalY: real("focal_y"),
144
+ rev: integer("rev").notNull().default(0),
142
145
  status: text("status").notNull().default("pending"),
143
146
  uploadId: text("upload_id"),
144
147
  createdBy: text("created_by"),
@@ -315,6 +318,9 @@ CREATE TABLE IF NOT EXISTS ${tbl("assets")} (
315
318
  "alt" text NOT NULL DEFAULT '',
316
319
  "tags" jsonb NOT NULL DEFAULT '[]'::jsonb,
317
320
  "thumb_key" text,
321
+ "focal_x" real,
322
+ "focal_y" real,
323
+ "rev" integer NOT NULL DEFAULT 0,
318
324
  "status" text NOT NULL DEFAULT 'pending',
319
325
  "upload_id" text,
320
326
  "created_by" text,
@@ -404,6 +410,14 @@ CREATE TABLE IF NOT EXISTS ${tbl("presence")} (
404
410
  PRIMARY KEY ("document_id", "actor_id")
405
411
  );
406
412
  CREATE INDEX IF NOT EXISTS ${idx("presence_seen_idx")} ON ${tbl("presence")} ("seen_at");`.trim()
413
+ },
414
+ {
415
+ version: 5,
416
+ name: "agent-cms 0.11.0: an image's focal point, replacing a file at the same address",
417
+ sql: `
418
+ ALTER TABLE ${tbl("assets")} ADD COLUMN IF NOT EXISTS "focal_x" real;
419
+ ALTER TABLE ${tbl("assets")} ADD COLUMN IF NOT EXISTS "focal_y" real;
420
+ ALTER TABLE ${tbl("assets")} ADD COLUMN IF NOT EXISTS "rev" integer NOT NULL DEFAULT 0;`.trim()
407
421
  }
408
422
  ];
409
423
  }
@@ -56,6 +56,60 @@ var DEFAULT_MAX_FILE_SIZE = 5 * 1024 ** 3;
56
56
  var PART_SIZE = 16 * 1024 * 1024;
57
57
  var THUMB_PREFIX = "_cms/thumbs/";
58
58
  var RESERVED_FOLDER = "_cms";
59
+ var DERIVED_PREFIX = "_cms/derived/";
60
+ var REPLACE_PREFIX = "_cms/replace/";
61
+ function stripJpegMetadata(b) {
62
+ if (b.length < 4 || b[0] !== 255 || b[1] !== 216) return b;
63
+ const keep = [];
64
+ let orientation = 1;
65
+ let dropped = false;
66
+ let i = 2;
67
+ while (i + 4 <= b.length && b[i] === 255) {
68
+ const m = b[i + 1];
69
+ if (m === 218 || m === 217) break;
70
+ if (m === 255) {
71
+ i++;
72
+ continue;
73
+ }
74
+ if (m >= 208 && m <= 215 || m === 1) {
75
+ keep.push([i, i + 2]);
76
+ i += 2;
77
+ continue;
78
+ }
79
+ const end = i + 2 + (b[i + 2] << 8 | b[i + 3]);
80
+ if (end < i + 4 || end > b.length) return b;
81
+ if (m === 225 || m === 237 || m === 254) {
82
+ dropped = true;
83
+ if (m === 225 && end - i >= 18 && b[i + 4] === 69 && b[i + 5] === 120 && b[i + 6] === 105 && b[i + 7] === 102) orientation = exifOrientation(b.subarray(i + 10, end)) ?? orientation;
84
+ } else keep.push([i, end]);
85
+ i = end;
86
+ }
87
+ if (!dropped) return b;
88
+ const turn = orientation >= 2 && orientation <= 8 ? Uint8Array.of(255, 225, 0, 34, 69, 120, 105, 102, 0, 0, 77, 77, 0, 42, 0, 0, 0, 8, 0, 1, 1, 18, 0, 3, 0, 0, 0, 1, 0, orientation, 0, 0, 0, 0, 0, 0) : new Uint8Array();
89
+ const out = new Uint8Array(2 + turn.length + keep.reduce((n, [a, z]) => n + z - a, 0) + b.length - i);
90
+ out.set(b.subarray(0, 2));
91
+ out.set(turn, 2);
92
+ let at = 2 + turn.length;
93
+ for (const [a, z] of keep) {
94
+ out.set(b.subarray(a, z), at);
95
+ at += z - a;
96
+ }
97
+ out.set(b.subarray(i), at);
98
+ return out;
99
+ }
100
+ function exifOrientation(t) {
101
+ if (t.length < 14) return null;
102
+ const le = t[0] === 73;
103
+ const u16 = (o) => le ? t[o] | t[o + 1] << 8 : t[o] << 8 | t[o + 1];
104
+ const ifd = le ? t[4] | t[5] << 8 | t[6] << 16 | t[7] << 24 : (t[4] << 24 | t[5] << 16 | t[6] << 8 | t[7]) >>> 0;
105
+ if (ifd < 8 || ifd + 2 > t.length) return null;
106
+ const n = u16(ifd);
107
+ for (let k = 0; k < n && ifd + 2 + (k + 1) * 12 <= t.length; k++) {
108
+ const e = ifd + 2 + k * 12;
109
+ if (u16(e) === 274) return u16(e + 8);
110
+ }
111
+ return null;
112
+ }
59
113
  var extOf = (name) => {
60
114
  const m = /\.([a-z0-9]{1,10})$/i.exec(name);
61
115
  return m ? m[1].toLowerCase() : "";
@@ -204,7 +258,7 @@ var MemoryStorage = class {
204
258
  return `memory://${this.o.name ?? "store"}/`;
205
259
  }
206
260
  store(key, body, o) {
207
- this.objects.set(key, { body, mime: o.mime, disposition: o.disposition ?? null, at: (/* @__PURE__ */ new Date()).toISOString() });
261
+ this.objects.set(key, { body, mime: o.mime, disposition: o.disposition ?? null, cacheControl: o.cacheControl ?? null, at: (/* @__PURE__ */ new Date()).toISOString() });
208
262
  }
209
263
  meta(key, v) {
210
264
  return { key, size: v.body.length, mime: v.mime, etag: `"m${v.body.length}"`, lastModified: v.at };
@@ -309,6 +363,9 @@ export {
309
363
  PART_SIZE,
310
364
  THUMB_PREFIX,
311
365
  RESERVED_FOLDER,
366
+ DERIVED_PREFIX,
367
+ REPLACE_PREFIX,
368
+ stripJpegMetadata,
312
369
  extOf,
313
370
  mimeOf,
314
371
  declaredMatches,
@@ -1,13 +1,13 @@
1
1
  import {
2
2
  coreOf
3
- } from "./chunk-7SCYDG2G.js";
3
+ } from "./chunk-J25IKU7C.js";
4
4
  import {
5
5
  APP_LINK_RE,
6
6
  splitSections
7
7
  } from "./chunk-MA6VKJ3F.js";
8
8
  import {
9
9
  isCmsError
10
- } from "./chunk-KAO3Z3CF.js";
10
+ } from "./chunk-I5UHTAAW.js";
11
11
 
12
12
  // src/agent.ts
13
13
  var MAX_SECTION_CHARS = 1400;
@@ -1,20 +1,20 @@
1
- import {
2
- isCmsRemoteError
3
- } from "./chunk-BFVBHIHV.js";
4
1
  import {
5
2
  lookupForAgent
6
- } from "./chunk-7Y6TU2UA.js";
3
+ } from "./chunk-HY4ED7LT.js";
7
4
  import {
8
5
  BULK_ACTIONS,
9
6
  coreOf
10
- } from "./chunk-7SCYDG2G.js";
7
+ } from "./chunk-J25IKU7C.js";
11
8
  import {
12
9
  ASSET_KINDS,
13
10
  DOC_STATUSES
14
- } from "./chunk-PEQY4N73.js";
11
+ } from "./chunk-TKKTEGHL.js";
15
12
  import {
16
13
  isCmsError
17
- } from "./chunk-KAO3Z3CF.js";
14
+ } from "./chunk-I5UHTAAW.js";
15
+ import {
16
+ isCmsRemoteError
17
+ } from "./chunk-J5DW3RFQ.js";
18
18
 
19
19
  // src/tools.ts
20
20
  import { z } from "zod";
@@ -395,9 +395,14 @@ var CMS_TOOLS = [
395
395
  {
396
396
  name: "update_asset",
397
397
  media: "write",
398
- description: "Change a file's alt text or tags. Documents that use the file without their own alt text show the new one.",
399
- input: z.object({ id: assetId, alt: z.string().optional(), tags: z.array(z.string()).optional() }),
400
- run: async (cms, actor, a) => assetOut(await cms.assets.update(actor, a.id, { alt: a.alt, tags: a.tags }))
398
+ description: "Change a file's alt text, tags or focal point. Documents that use the file without their own alt text show the new one.",
399
+ input: z.object({
400
+ id: assetId,
401
+ alt: z.string().optional(),
402
+ tags: z.array(z.string()).optional(),
403
+ focal: z.object({ x: z.number().min(0).max(1), y: z.number().min(0).max(1) }).nullable().optional().describe("Images: the point that stays in view when the picture is cropped, from the left and from the top (0..1). null clears it.")
404
+ }),
405
+ run: async (cms, actor, a) => assetOut(await cms.assets.update(actor, a.id, { alt: a.alt, tags: a.tags, focal: a.focal }))
401
406
  },
402
407
  {
403
408
  name: "move_asset",
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  en
3
- } from "./chunk-PGV2QPIL.js";
3
+ } from "./chunk-WWG7XDIZ.js";
4
4
 
5
5
  // src/errors.ts
6
6
  var ERROR_KINDS = ["not_found", "unknown_collection", "forbidden", "unauthorized", "invalid", "conflict", "precondition", "internal"];
@@ -60,6 +60,8 @@ var ERROR_CODES = {
60
60
  import_blocked: "invalid",
61
61
  import_failed: "invalid",
62
62
  asset_rejected: "invalid",
63
+ asset_replace_type: "invalid",
64
+ unknown_image_size: "not_found",
63
65
  asset_missing: "invalid",
64
66
  asset_wrong_kind: "invalid",
65
67
  asset_alt_missing: "invalid",