@pramen/cms 0.0.60 → 0.0.63

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
@@ -603,6 +603,18 @@ export const cmsSchema = {
603
603
  // Hierarchical vocabularies allow `parentId` on their terms; flat ones reject it on
604
604
  // write. Enforced in the handler, not the schema — one term table serves both.
605
605
  hierarchical: defaultTo(t.bool(), false),
606
+ // What this vocabulary classifies — a subset of `TAXONOMY_TARGETS`. NULL means EVERYTHING,
607
+ // which is both the backward-compatible reading for rows written before this column and a
608
+ // legitimate authored value ("Topics classifies whatever there is"). Without it a site with
609
+ // "Categories" for articles and tags for images offers both on both, so a photo can be
610
+ // filed under "Local news" and `getTermTree("category")` fills up with terms like "hero"
611
+ // that no page listing will ever use.
612
+ //
613
+ // A `t.json()` array rather than two booleans: the set of things a CMS classifies grows
614
+ // (collections are the obvious next one), and a column per target would need a migration
615
+ // each time. It is not queryable — JSON in a TEXT cell — but nothing pages by taxonomy:
616
+ // `listTaxonomies` reads them all and narrows in memory.
617
+ appliesTo: t.json(),
606
618
  createdAt: defaultTo(t.text(), expr.now()),
607
619
  })),
608
620
  cms_terms: Entity((t) => ({
@@ -622,6 +634,7 @@ export const cmsSchema = {
622
634
  taxonomy: r.belongsTo("cms_taxonomies", "taxonomyId", { onDelete: "cascade" }),
623
635
  parent: r.belongsTo("cms_terms", "parentId", { onDelete: "setNull" }),
624
636
  pages: r.hasMany("cms_page_terms", "termId"),
637
+ media: r.hasMany("cms_media_terms", "termId"),
625
638
  }),
626
639
  // A slug identifies a term WITHIN its vocabulary — `/category/news` and `/tag/news`
627
640
  // are two different terms, and both are legitimate.
@@ -640,6 +653,23 @@ export const cmsSchema = {
640
653
  // One assignment per (page, term). Without it a double-submit leaves a page tagged
641
654
  // twice and every `with: { terms: true }` renders the term twice.
642
655
  { unique: [["pageId", "termId"]] }),
656
+ // The same junction for media. A SECOND table rather than one polymorphic
657
+ // `cms_object_terms(objectType, objectId, termId)`: a polymorphic key cannot carry a real
658
+ // foreign key, and the FKs are what does the work here — purging a media row or deleting a
659
+ // term takes its assignments with it, with no handler remembering to. A `where` traversal
660
+ // also needs a typed column to join on; `objectId` would have to be filtered by a
661
+ // discriminator the read engine has no way to require, so one forgotten `objectType`
662
+ // clause silently mixes a page's tags into a media query.
663
+ cms_media_terms: Entity((t) => ({
664
+ id: primaryKey(generated(t.uuid())),
665
+ mediaId: indexed(notNull(t.uuid())),
666
+ termId: indexed(notNull(t.uuid())),
667
+ }), (r) => ({
668
+ // `cascade` on both ends, as on the page junction. Note this fires on PURGE, not on
669
+ // trashing: `deleteMedia` only stamps `deletedAt`, so a restored file keeps its tags.
670
+ media: r.belongsTo("cms_media", "mediaId", { onDelete: "cascade" }),
671
+ term: r.belongsTo("cms_terms", "termId", { onDelete: "cascade" }),
672
+ }), { unique: [["mediaId", "termId"]] }),
643
673
  // A named template region an admin fills without touching code — the sidebar, the footer
644
674
  // column, the pre-footer strip.
645
675
  //
@@ -665,13 +695,160 @@ export const cmsSchema = {
665
695
  cms_media: Entity((t) => ({
666
696
  id: primaryKey(generated(t.uuid())),
667
697
  file: t.fileRef(),
698
+ // The three fields the library SORTS and FILTERS by, projected out of `file` into real
699
+ // columns. `file` is a `t.fileRef()` — JSON in a TEXT cell — so its `filename`,
700
+ // `contentType` and `size` are invisible to `orderBy` and `where`, and sorting a library
701
+ // after the page has been fetched sorts one page, which is not sorting.
702
+ //
703
+ // A duplicate, deliberately, and the cost is named: they are written where a media row is
704
+ // CREATED and nowhere else (`updateMedia` never touches the file), so there is one writer
705
+ // and `file` stays the source of truth for serving. SQLite generated columns would remove
706
+ // the duplication outright — `GENERATED ALWAYS AS (json_extract(file,'$.filename'))` — but
707
+ // the schema DSL has no way to declare one, and `generated()` here means something else
708
+ // entirely (auto-mint a uuid on insert).
709
+ //
710
+ // Nullable, so adding them is a plain `ADD COLUMN` on an existing store rather than a
711
+ // gated table rebuild; `cmsMigrations` backfills what is already there.
712
+ filename: indexed(t.text()),
713
+ contentType: indexed(t.text()),
714
+ size: t.int(),
668
715
  alt: t.text(),
669
716
  // Soft delete, as on cms_pages. The R2 OBJECT is deliberately kept while a media row
670
717
  // is trashed — deleting the bytes would make restore a lie. `purgeMedia` drops both.
671
718
  deletedAt: indexed(t.text()),
672
719
  createdAt: defaultTo(t.text(), expr.now()),
720
+ }), (r) => ({
721
+ // Media is classified by the SAME vocabularies pages are, through the same `cms_terms`
722
+ // table — a deployment that declares "Topics" gets to tag a photo with one without
723
+ // declaring it twice, and the terms screen stays the one place a vocabulary is edited.
724
+ //
725
+ // The traversal is what makes tagging worth having: `where: { terms: { id } }` compiles
726
+ // to a subquery through the junction, so the library filters by term IN SQL like it
727
+ // filters by kind. A tag you cannot filter a paged library by is decoration.
728
+ terms: r.manyToMany("cms_terms", { through: "cms_media_terms", sourceColumn: "mediaId", targetColumn: "termId" }),
673
729
  })),
674
730
  };
731
+ /** …resolved to the order the read engine takes. `createdAt` is ISO-8601 TEXT (`expr.now()`),
732
+ * so a lexicographic sort on it IS chronological. */
733
+ const MEDIA_SORTS = {
734
+ newest: { column: "createdAt", dir: "desc" },
735
+ oldest: { column: "createdAt", dir: "asc" },
736
+ name: { column: "filename", dir: "asc" },
737
+ name_desc: { column: "filename", dir: "desc" },
738
+ largest: { column: "size", dir: "desc" },
739
+ smallest: { column: "size", dir: "asc" },
740
+ };
741
+ /** The coarse type buckets the library filters by — the first segment of a MIME type, which
742
+ * is the distinction someone browsing a library actually makes ("show me the images"). */
743
+ export const MEDIA_KINDS = ["image", "video", "audio", "document", "other"];
744
+ /** MIME prefixes for the buckets that have one. `document` is a LIST rather than a prefix
745
+ * because the useful documents share no MIME family — a PDF is `application/pdf` and a Word
746
+ * file is `application/vnd.openxmlformats-…`. */
747
+ const DOCUMENT_PREFIXES = ["application/pdf", "text/", "application/msword", "application/vnd."];
748
+ /** Trim and cap a search needle. Capped because it lands in a `LIKE` pattern: the engine
749
+ * escapes `%` and `_` for us, so this is not an injection guard — it is a bound on work a
750
+ * caller can ask the database to do per row. */
751
+ function mediaQuery(raw) {
752
+ const q = typeof raw === "string" ? raw.trim().slice(0, 120) : "";
753
+ return q === "" ? undefined : q;
754
+ }
755
+ /** Match a needle against the two fields that NAME a file: what it was uploaded as, and what
756
+ * an editor wrote about it. `alt` is included because it is the only human description a
757
+ * media row carries, and searching a library for "logo" should find the file somebody
758
+ * described as a logo even when the upload was called `IMG_2831.png`. */
759
+ function mediaSearchWhere(q) {
760
+ return { OR: [{ filename: { contains: q } }, { alt: { contains: q } }] };
761
+ }
762
+ /** The `where` clause for one bucket, or `undefined` for "everything".
763
+ *
764
+ * `other` is the interesting one: it is defined as NOT any of the buckets that have a
765
+ * definition, so a file type nobody anticipated still has exactly one home rather than
766
+ * disappearing from every filter. A row whose `contentType` is NULL — uploaded before the
767
+ * projection columns existed and never backfilled — lands there too, which is the honest
768
+ * place for it.
769
+ *
770
+ * That NULL case needs its OWN clause, and did not have one. SQL is three-valued: against a
771
+ * NULL column every `LIKE` is NULL, so the `OR` is NULL and `NOT NULL` is NULL — which is not
772
+ * TRUE, so the row is excluded. `other` therefore matched everything except the rows it
773
+ * documents as belonging there, and a legacy row was invisible under ALL FIVE chips, with only
774
+ * "clear the filter" to find it and nothing on screen saying why. Exactly the deployment that
775
+ * upgraded and did not spread `cmsMigrations`. */
776
+ function mediaKindWhere(kind) {
777
+ if (kind === undefined)
778
+ return undefined;
779
+ if (kind === "image" || kind === "video" || kind === "audio")
780
+ return { contentType: { startsWith: `${kind}/` } };
781
+ const documents = { OR: DOCUMENT_PREFIXES.map((p) => ({ contentType: { startsWith: p } })) };
782
+ if (kind === "document")
783
+ return documents;
784
+ const known = { OR: [{ contentType: { startsWith: "image/" } }, { contentType: { startsWith: "video/" } }, { contentType: { startsWith: "audio/" } }, documents] };
785
+ return { OR: [{ contentType: { isNull: true } }, { NOT: known }] };
786
+ }
787
+ // --- taxonomies: what a vocabulary classifies ---------------------------------------------
788
+ /** The object types a vocabulary can be applied to. A CLOSED vocabulary, like `MEDIA_KINDS`:
789
+ * it decides which panels offer a taxonomy AND which assignments are accepted, so an unknown
790
+ * value must not be storable. */
791
+ export const TAXONOMY_TARGETS = ["page", "media"];
792
+ /** Whether a vocabulary applies to `target`.
793
+ *
794
+ * The permissive readings all collapse to TRUE, deliberately: NULL (never narrowed, or written
795
+ * before the column existed), a non-array, an array of things that are not targets. A stored
796
+ * value nobody can interpret must not silently stop a vocabulary from working — the failure
797
+ * would be a taxonomy that has quietly vanished from every panel, with the row still there. */
798
+ export function taxonomyApplies(row, target) {
799
+ const list = row.appliesTo;
800
+ if (!Array.isArray(list))
801
+ return true;
802
+ const targets = list.filter((v) => TAXONOMY_TARGETS.includes(v));
803
+ return targets.length === 0 || targets.includes(target);
804
+ }
805
+ /** Parse an `appliesTo` input. `undefined` stays undefined (the field was not sent); `null`
806
+ * clears the narrowing back to "everything". An unknown target is a 400 rather than a silent
807
+ * drop — dropping it would store a NARROWER set than the caller asked for, which is the one
808
+ * direction that loses assignments. */
809
+ function parseAppliesTo(raw) {
810
+ if (raw === undefined)
811
+ return undefined;
812
+ if (raw === null)
813
+ return null;
814
+ if (!Array.isArray(raw))
815
+ throw new BadRequest("appliesTo must be a list or null");
816
+ const out = [];
817
+ for (const v of raw) {
818
+ if (typeof v !== "string" || !TAXONOMY_TARGETS.includes(v)) {
819
+ throw new BadRequest(`appliesTo must contain only ${TAXONOMY_TARGETS.join(", ")}`);
820
+ }
821
+ if (!out.includes(v))
822
+ out.push(v);
823
+ }
824
+ // A vocabulary that classifies nothing is not a narrowing, it is a vocabulary nobody can
825
+ // reach — and it reads identically to NULL in storage, which means the opposite.
826
+ if (out.length === 0)
827
+ throw new BadRequest("appliesTo must name at least one of " + TAXONOMY_TARGETS.join(", "));
828
+ return out;
829
+ }
830
+ /** Refuse term ids from a vocabulary that does not classify `target`.
831
+ *
832
+ * The write side, not just the UI. Hiding a vocabulary from a panel without changing what the
833
+ * server accepts is the `hideI18n` mistake this package already retired once: the control
834
+ * disappears, the request does not, and `appliesTo` becomes a hint rather than a rule. It also
835
+ * has to be here for the assignments the panel never made — a script, a migration, an older
836
+ * editor build that has not learned the capability.
837
+ *
838
+ * Reads the terms' taxonomies through `ctx.db`, so an unreadable vocabulary refuses the
839
+ * assignment rather than being waved through. */
840
+ async function assertTermsApplyTo(db, termIds, target) {
841
+ if (termIds.length === 0)
842
+ return;
843
+ const terms = await db.find({ from: "cms_terms", where: { id: { in: [...termIds] } }, select: ["id", "taxonomyId"], limit: termIds.length });
844
+ const taxIds = [...new Set(terms.map((t) => String(t.taxonomyId)))];
845
+ if (taxIds.length === 0)
846
+ return;
847
+ const taxa = await db.find({ from: "cms_taxonomies", where: { id: { in: taxIds } }, select: ["id", "slug", "appliesTo"], limit: taxIds.length });
848
+ const bad = taxa.filter((t) => !taxonomyApplies(t, target));
849
+ if (bad[0])
850
+ throw new BadRequest(`vocabulary '${String(bad[0].slug)}' does not apply to ${target}`);
851
+ }
675
852
  /** Block Kit — custom admin pages, described as JSON and rendered by the editor. See
676
853
  * `./blockkit`. Re-exported so a host imports `adminPage` beside `collection`. */
677
854
  export { adminPage, createAdminPageHandlers, normalizeAdminResponse, validateAdminPages, MAX_ADMIN_BLOCK_DEPTH, } from "./blockkit";
@@ -2503,9 +2680,35 @@ export function createCmsHandlers(opts = {}) {
2503
2680
  // same way it creates its content types. A vocabulary that is hierarchical allows
2504
2681
  // `parentId` on its terms; a flat one refuses it rather than storing something no
2505
2682
  // listing renders.
2506
- /** Every vocabulary. PUBLIC like content types, a taxonomy's slug is structural (it
2507
- * is a URL segment) and a front end routes on it. */
2508
- listTaxonomies: query((ctx) => cdb(ctx).find({ from: "cms_taxonomies", orderBy: { column: "label" }, limit: PAGE_LIST_MAX_LIMIT })),
2683
+ /** Every vocabulary, or just the ones that classify `target`. PUBLIC like content
2684
+ * types, a taxonomy's slug is structural (it is a URL segment) and a front end routes on
2685
+ * it.
2686
+ *
2687
+ * Narrowed HERE rather than in each caller, so the page panel, the media panel and the
2688
+ * write-side guard cannot disagree about what a vocabulary applies to. In memory, because
2689
+ * `appliesTo` is a `t.json()` column that `where` cannot see into — which costs nothing:
2690
+ * this handler already reads every taxonomy, and nothing pages by them.
2691
+ *
2692
+ * No `target` means EVERY vocabulary, which is what the Taxonomies screen needs: the one
2693
+ * place that edits `appliesTo` must be able to see a vocabulary it has narrowed away. */
2694
+ listTaxonomies: query(async (ctx, input) => {
2695
+ const rows = await cdb(ctx).find({ from: "cms_taxonomies", orderBy: { column: "label" }, limit: PAGE_LIST_MAX_LIMIT });
2696
+ const target = input?.target;
2697
+ return target === undefined ? rows : rows.filter((r) => taxonomyApplies(r, target));
2698
+ }, {
2699
+ input: (raw) => {
2700
+ const t = asObj(raw).target;
2701
+ // Unrecognised narrows to nothing rather than falling back to everything: this one
2702
+ // decides what a panel OFFERS, and answering "all of them" to a question the server
2703
+ // did not understand is how a media panel ends up listing page-only vocabularies.
2704
+ if (t === undefined || t === null)
2705
+ return {};
2706
+ if (typeof t !== "string" || !TAXONOMY_TARGETS.includes(t)) {
2707
+ throw new BadRequest(`target must be one of ${TAXONOMY_TARGETS.join(", ")}`);
2708
+ }
2709
+ return { target: t };
2710
+ },
2711
+ }),
2509
2712
  createTaxonomy: mutation(async (ctx, input) => {
2510
2713
  const db = cdb(ctx);
2511
2714
  const clash = await db.find({ from: "cms_taxonomies", where: { slug: input.slug }, select: ["id"], limit: 1 });
@@ -2517,6 +2720,9 @@ export function createCmsHandlers(opts = {}) {
2517
2720
  pluralLabel: input.pluralLabel ?? null,
2518
2721
  description: input.description ?? null,
2519
2722
  hierarchical: input.hierarchical ?? false,
2723
+ // Unsent means EVERY target, which is what a vocabulary created before this existed
2724
+ // means too — one reading of NULL, so an old row and a new one behave alike.
2725
+ appliesTo: input.appliesTo ?? null,
2520
2726
  });
2521
2727
  }, {
2522
2728
  ...editor,
@@ -2528,6 +2734,7 @@ export function createCmsHandlers(opts = {}) {
2528
2734
  pluralLabel: typeof o.pluralLabel === "string" ? o.pluralLabel : undefined,
2529
2735
  description: typeof o.description === "string" ? o.description : undefined,
2530
2736
  hierarchical: typeof o.hierarchical === "boolean" ? o.hierarchical : undefined,
2737
+ appliesTo: parseAppliesTo(o.appliesTo),
2531
2738
  };
2532
2739
  },
2533
2740
  }),
@@ -2536,7 +2743,14 @@ export function createCmsHandlers(opts = {}) {
2536
2743
  *
2537
2744
  * Turning `hierarchical` OFF is refused while any term still has a parent. Allowing it
2538
2745
  * would leave a stored hierarchy that no reader renders and no writer can clear, and
2539
- * flattening the terms silently is a destructive edit behind a checkbox. */
2746
+ * flattening the terms silently is a destructive edit behind a checkbox.
2747
+ *
2748
+ * NARROWING `appliesTo` is refused on exactly the same grounds, and it is the same bug:
2749
+ * dropping a target this vocabulary is already used for would strand those assignments —
2750
+ * still stored, still returned by `listPageTerms`/`listMediaTerms`, but invisible in the
2751
+ * panel that could remove them, because the panel only renders vocabularies that apply.
2752
+ * Unassign them first; then the narrowing is a settings change rather than a silent
2753
+ * orphaning. WIDENING is always fine — it strands nothing. */
2540
2754
  updateTaxonomy: mutation(async (ctx, input) => {
2541
2755
  const db = cdb(ctx);
2542
2756
  const rows = await db.find({ from: "cms_taxonomies", where: { id: input.id }, limit: 1 });
@@ -2548,8 +2762,20 @@ export function createCmsHandlers(opts = {}) {
2548
2762
  if (nested[0])
2549
2763
  throw new BadRequest("this vocabulary still has nested terms — move them to the top level before making it flat");
2550
2764
  }
2765
+ if (input.appliesTo !== undefined && input.appliesTo !== null) {
2766
+ const next = input.appliesTo;
2767
+ for (const target of TAXONOMY_TARGETS) {
2768
+ // Only a target this vocabulary applies to TODAY and would not after the patch.
2769
+ if (next.includes(target) || !taxonomyApplies(row, target))
2770
+ continue;
2771
+ const junction = target === "page" ? "cms_page_terms" : "cms_media_terms";
2772
+ const used = await db.find({ from: junction, where: { term: { taxonomyId: input.id } }, select: ["id"], limit: 1 });
2773
+ if (used[0])
2774
+ throw new BadRequest(`this vocabulary is still assigned to ${target === "page" ? "pages" : "media"} — remove those assignments before narrowing it`);
2775
+ }
2776
+ }
2551
2777
  const patch = {};
2552
- for (const k of ["label", "pluralLabel", "description", "hierarchical"]) {
2778
+ for (const k of ["label", "pluralLabel", "description", "hierarchical", "appliesTo"]) {
2553
2779
  if (input[k] !== undefined)
2554
2780
  patch[k] = input[k];
2555
2781
  }
@@ -2569,6 +2795,9 @@ export function createCmsHandlers(opts = {}) {
2569
2795
  out.description = typeof o.description === "string" ? o.description : null;
2570
2796
  if (typeof o.hierarchical === "boolean")
2571
2797
  out.hierarchical = o.hierarchical;
2798
+ const appliesTo = parseAppliesTo(o.appliesTo);
2799
+ if (appliesTo !== undefined)
2800
+ out.appliesTo = appliesTo;
2572
2801
  return out;
2573
2802
  },
2574
2803
  }),
@@ -2752,6 +2981,7 @@ export function createCmsHandlers(opts = {}) {
2752
2981
  const found = await db.find({ from: "cms_terms", where: { id: { in: [...wanted] } }, select: ["id"], limit: wanted.size });
2753
2982
  if (found.length !== wanted.size)
2754
2983
  throw new BadRequest("one or more termIds are not terms");
2984
+ await assertTermsApplyTo(db, [...wanted], "page");
2755
2985
  }
2756
2986
  const existing = await db.find({ from: "cms_page_terms", where: { pageId: input.pageId }, select: ["id", "termId"], limit: MAX_TERMS });
2757
2987
  const have = new Map(existing.map((l) => [String(l.termId), String(l.id)]));
@@ -2951,7 +3181,15 @@ export function createCmsHandlers(opts = {}) {
2951
3181
  filename: input.ref.filename,
2952
3182
  uploadedAt: Date.now(),
2953
3183
  };
2954
- return cdb(ctx).insert("cms_media", { file, alt: input.alt ?? null });
3184
+ // The projection columns go in beside `file`, from the SAME resolved values — never
3185
+ // from `input`, which is the client's claim about a blob it has just uploaded.
3186
+ return cdb(ctx).insert("cms_media", {
3187
+ file,
3188
+ filename: file.filename ?? null,
3189
+ contentType: file.contentType ?? null,
3190
+ size: file.size ?? null,
3191
+ alt: input.alt ?? null,
3192
+ });
2955
3193
  }, {
2956
3194
  ...editor,
2957
3195
  input: (raw) => {
@@ -2973,8 +3211,40 @@ export function createCmsHandlers(opts = {}) {
2973
3211
  listMedia: query((ctx, input) => {
2974
3212
  const limit = Math.min(Math.max(Math.trunc(Number(input?.limit ?? 50)) || 50, 1), 200);
2975
3213
  const offset = Math.max(Math.trunc(Number(input?.offset ?? 0)) || 0, 0);
2976
- return cdb(ctx).find({ from: "cms_media", orderBy: { column: "createdAt", dir: "desc" }, limit, offset });
2977
- }, viewer),
3214
+ // The narrowings AND together a search inside a type filter inside a tag is all
3215
+ // three. Built as a list so none has to know whether the others are present.
3216
+ const clauses = [
3217
+ mediaKindWhere(input?.kind),
3218
+ input?.q ? mediaSearchWhere(input.q) : undefined,
3219
+ // A relation traversal, compiled to a subquery through `cms_media_terms`. Filtering
3220
+ // by term therefore costs the same page of rows as filtering by kind — the whole
3221
+ // reason the assignments are a junction rather than a JSON array on the media row.
3222
+ input?.term ? { terms: { id: input.term } } : undefined,
3223
+ ].filter((c) => c !== undefined);
3224
+ const where = clauses.length === 0 ? undefined : clauses.length === 1 ? clauses[0] : { AND: clauses };
3225
+ return cdb(ctx).find({ from: "cms_media", where, orderBy: MEDIA_SORTS[input?.sort ?? "newest"], limit, offset });
3226
+ }, {
3227
+ ...viewer,
3228
+ // Parsed, not cast: `sort` names an ORDER BY and `kind` a WHERE, and both arrive from a
3229
+ // browser. Anything unrecognised falls back to the default rather than erroring — a
3230
+ // stale bookmark carrying a sort this build dropped should show the library, not a 400.
3231
+ input: (raw) => {
3232
+ const o = asObj(raw);
3233
+ const sort = typeof o.sort === "string" && o.sort in MEDIA_SORTS ? o.sort : undefined;
3234
+ const kind = typeof o.kind === "string" && MEDIA_KINDS.includes(o.kind) ? o.kind : undefined;
3235
+ return {
3236
+ limit: typeof o.limit === "number" ? o.limit : undefined,
3237
+ offset: typeof o.offset === "number" ? o.offset : undefined,
3238
+ sort,
3239
+ kind,
3240
+ q: mediaQuery(o.q),
3241
+ // An id, not a slug: a slug identifies a term only within its vocabulary, and the
3242
+ // filter has no vocabulary to resolve it against. An id that is not a term matches
3243
+ // nothing, which is the same answer as a term with no files.
3244
+ term: typeof o.term === "string" && o.term !== "" ? o.term : undefined,
3245
+ };
3246
+ },
3247
+ }),
2978
3248
  getMedia: query(async (ctx, input) => {
2979
3249
  const rows = await cdb(ctx).find({ from: "cms_media", where: { id: input.id }, limit: 1 });
2980
3250
  return rows[0] ?? null;
@@ -3002,6 +3272,74 @@ export function createCmsHandlers(opts = {}) {
3002
3272
  return { id: o.id, alt: typeof o.alt === "string" ? o.alt : null };
3003
3273
  },
3004
3274
  }),
3275
+ /** A media asset's assigned terms.
3276
+ *
3277
+ * The media row is read FIRST, through `ctx.db`, so the caller's own scope decides
3278
+ * whether this answers — the junction and `cms_terms` are granted unscoped, so without
3279
+ * it anyone holding an id could read a TRASHED file's tags and the non-empty answer
3280
+ * would confirm the file exists. Same rule as `listPageTerms`, for the same reason. */
3281
+ listMediaTerms: query(async (ctx, input) => {
3282
+ const db = cdb(ctx);
3283
+ const media = await db.find({ from: "cms_media", where: { id: input.mediaId }, select: ["id"], limit: 1 });
3284
+ if (!media[0])
3285
+ return [];
3286
+ const links = await db.find({ from: "cms_media_terms", where: { mediaId: input.mediaId }, select: ["termId"], limit: MAX_TERMS });
3287
+ const ids = links.map((l) => String(l.termId));
3288
+ if (ids.length === 0)
3289
+ return [];
3290
+ const rows = await db.find({ from: "cms_terms", where: { id: { in: ids } }, orderBy: [{ column: "position" }, { column: "label" }], limit: ids.length });
3291
+ return rows;
3292
+ }, {
3293
+ ...viewer,
3294
+ input: (raw) => {
3295
+ const id = asObj(raw).mediaId;
3296
+ if (typeof id !== "string" || id === "")
3297
+ throw new BadRequest("mediaId is required");
3298
+ return { mediaId: id };
3299
+ },
3300
+ }),
3301
+ /** Replace a media asset's term assignments wholesale — set semantics, like
3302
+ * `setPageTerms`, and for the same reason: the panel holds the whole selection, and two
3303
+ * calls each patching one end of it race into a state neither asked for. */
3304
+ setMediaTerms: mutation(async (ctx, input) => {
3305
+ const db = cdb(ctx);
3306
+ const media = await db.find({ from: "cms_media", where: { id: input.mediaId }, select: ["id"], limit: 1 });
3307
+ if (!media[0])
3308
+ throw notFound("media");
3309
+ const wanted = new Set(input.termIds);
3310
+ if (wanted.size > 0) {
3311
+ const found = await db.find({ from: "cms_terms", where: { id: { in: [...wanted] } }, select: ["id"], limit: wanted.size });
3312
+ if (found.length !== wanted.size)
3313
+ throw new BadRequest("one or more termIds are not terms");
3314
+ await assertTermsApplyTo(db, [...wanted], "media");
3315
+ }
3316
+ const existing = await db.find({ from: "cms_media_terms", where: { mediaId: input.mediaId }, select: ["id", "termId"], limit: MAX_TERMS });
3317
+ const have = new Map(existing.map((l) => [String(l.termId), String(l.id)]));
3318
+ for (const [termId, linkId] of have)
3319
+ if (!wanted.has(termId))
3320
+ await db.delete("cms_media_terms", linkId);
3321
+ for (const termId of wanted)
3322
+ if (!have.has(termId))
3323
+ await db.insert("cms_media_terms", { mediaId: input.mediaId, termId });
3324
+ return { ok: true, count: wanted.size };
3325
+ }, {
3326
+ ...editor,
3327
+ input: (raw) => {
3328
+ const o = asObj(raw);
3329
+ if (typeof o.mediaId !== "string" || o.mediaId === "")
3330
+ throw new BadRequest("mediaId is required");
3331
+ if (!Array.isArray(o.termIds))
3332
+ throw new BadRequest("termIds must be a list");
3333
+ const ids = o.termIds.map((v) => {
3334
+ if (typeof v !== "string" || v === "")
3335
+ throw new BadRequest("termIds must be a list of ids");
3336
+ return v;
3337
+ });
3338
+ if (ids.length > MAX_TERMS)
3339
+ throw new BadRequest(`a file may carry at most ${MAX_TERMS} terms`);
3340
+ return { mediaId: o.mediaId, termIds: ids };
3341
+ },
3342
+ }),
3005
3343
  /** Trash a media row. The R2 OBJECT IS KEPT — deleting the bytes here would make
3006
3344
  * `restoreMedia` a lie, and a block still referencing the id would render a dead url
3007
3345
  * with no way back. `purgeMedia` is what drops both — and `listTrash` is how you find
@@ -3420,6 +3758,11 @@ export function createCmsHandlers(opts = {}) {
3420
3758
  // the next cold start. That is GitHub #48 in the deployment that upgraded the editor to
3421
3759
  // fix it. Absent ⇒ the editor treats no type as code-defined, which is correct there.
3422
3760
  codeDefinedTypes: true,
3761
+ // Media carries taxonomy terms, and `listMedia` understands `term`. Declared for the
3762
+ // usual reason: an older server has neither handler, so the detail panel's Tags
3763
+ // section would 404 on open and the library's tag filter would send an argument that
3764
+ // is ignored — a filter that visibly does nothing. Absent ⇒ neither is drawn.
3765
+ mediaTerms: true,
3423
3766
  // PER-CALLER, unlike everything else here. `viewer` is `editorRoles ∪ reviewerRoles`,
3424
3767
  // so a reviewer-only session reaches this handler and every read handler — but every
3425
3768
  // WRITE is `editorRoles`. Without this the editor renders the authoring surfaces
@@ -3799,10 +4142,11 @@ export function createCmsHandlers(opts = {}) {
3799
4142
  const secret = previewSecret(ctx.env);
3800
4143
  if (!secret)
3801
4144
  throw previewUnconfigured(); // fail closed — never mint a forgeable link
3802
- // The redeem route always reaches a Durable Object (callPrivileged -> PRAMEN.get); it
3803
- // has no notion of `x-pramen-store`. Minting on the D1 store therefore produces a
3804
- // link that 404s forever while the editor reports success refuse instead of
3805
- // handing out a token that cannot work.
4145
+ // This used to refuse on the D1 store: redemption goes through `ctx.callPrivileged`,
4146
+ // which only forwarded to a DO, so a link minted on D1 would have 404'd forever while
4147
+ // the editor reported success. `callPrivileged` now dispatches locally in the Worker
4148
+ // on D1, so both stores mint. The redeem route is a BROWSER request carrying no
4149
+ // `x-pramen-store`, so a D1 deployment still needs `PRAMEN_STORE=d1` to route it.
3806
4150
  const db = cdb(ctx);
3807
4151
  // Read the page through the ACL first: minting a link is granting access to it, so a
3808
4152
  // caller who cannot read the page must not be able to mint a link that can.
@@ -4034,7 +4378,7 @@ export function cmsPolicies(opts = {}) {
4034
4378
  "cms_content_types", "cms_block_types", "cms_blocks", "cms_pages", "cms_page_blocks", "cms_page_revisions", "cms_media", "cms_audit",
4035
4379
  // Site furniture. Full CRUD for an editor, like every other cms_ table — the per-handler
4036
4380
  // `auth` gate is what separates editor from reviewer; this is the row scope.
4037
- "cms_menus", "cms_redirects", "cms_taxonomies", "cms_terms", "cms_page_terms", "cms_widget_areas",
4381
+ "cms_menus", "cms_redirects", "cms_taxonomies", "cms_terms", "cms_page_terms", "cms_media_terms", "cms_widget_areas",
4038
4382
  ];
4039
4383
  // Soft-deleted rows are filtered in the ACL, not in each handler. A read scope is
4040
4384
  // AND-merged into every `ctx.db` read, so one policy hides a trashed row from the public
@@ -4091,6 +4435,10 @@ export function cmsPolicies(opts = {}) {
4091
4435
  policy(`${p}:public:taxonomies:read`, "cms_taxonomies", "read", allow()),
4092
4436
  policy(`${p}:public:terms:read`, "cms_terms", "read", allow()),
4093
4437
  policy(`${p}:public:page-terms:read`, "cms_page_terms", "read", allow()),
4438
+ // The media junction, for the same reason as the page one: `where: { terms: … }` on a
4439
+ // media row compiles to a subquery THROUGH it, so without the grant the library's tag
4440
+ // filter matches nothing and reads as "no files carry this tag".
4441
+ policy(`${p}:public:media-terms:read`, "cms_media_terms", "read", allow()),
4094
4442
  policy(`${p}:public:widget-areas:read`, "cms_widget_areas", "read", allow()),
4095
4443
  ],
4096
4444
  editor: editorPolicies,
@@ -4919,7 +5267,7 @@ export function createCollectionHandlers(collections, opts = {}) {
4919
5267
  }),
4920
5268
  // ---- preview ------------------------------------------------------------
4921
5269
  /** Mint a signed link that shows ONE row's unpublished state, to whoever holds it.
4922
- * Mirrors `signPagePreview` — same secret, same TTL clamp, same D1 refusal, and the
5270
+ * Mirrors `signPagePreview` — same secret, same TTL clamp, works on both stores, and the
4923
5271
  * same rule that the row is read through the ACL FIRST: minting a link is granting
4924
5272
  * access to the row, so a caller who cannot read it must not be able to mint one. */
4925
5273
  signCollectionPreview: query(async (ctx, input) => {
@@ -5164,6 +5512,61 @@ export function createCollectionTasks(collections) {
5164
5512
  * between the revision insert and the page update leaves the page unpublished with an orphan
5165
5513
  * revision until the next at-least-once redelivery re-runs (the token still matches, so it
5166
5514
  * completes). Acceptable for a scheduled job; the interactive path is atomic. */
5515
+ /**
5516
+ * The CMS's own data migrations — spread into `app.migrations`.
5517
+ *
5518
+ * migrations: [...cmsMigrations]
5519
+ *
5520
+ * Opt-in like every other fragment this package ships (`cmsHandlers`, `cmsPolicies`,
5521
+ * `cmsTasks`), and with the same consequence for forgetting it: nothing breaks loudly. Media
5522
+ * rows written before the projection columns existed keep NULL `filename`/`contentType`, so
5523
+ * they sort together under a name sort and answer only the `other` type filter. New uploads
5524
+ * are unaffected — `createMedia` writes the columns itself.
5525
+ */
5526
+ export const cmsMigrations = [
5527
+ {
5528
+ // Fill the columns `cms_media` grew for sorting and filtering, out of the `file` JSON that
5529
+ // has always held the same three values.
5530
+ id: "cms:2026-09-04-media-projection-columns",
5531
+ // `MigrationContext<typeof cmsSchema>` is what types `db` here — the `DataMigration`
5532
+ // contract is schema-agnostic, so an unparameterized ctx hands back untyped rows.
5533
+ async up({ db, driver }) {
5534
+ const d = driver.dialect;
5535
+ const t = d.id("cms_media");
5536
+ const set = (c, path) => `${d.id(c)} = json_extract(${d.id("file")}, '$.${path}')`;
5537
+ try {
5538
+ // One statement for the whole table. `WHERE filename IS NULL` makes it cheap on a
5539
+ // store that has nothing to do, and keeps it off rows a later upload already filled.
5540
+ await driver.exec(`UPDATE ${t} SET ${set("filename", "filename")}, ${set("contentType", "contentType")}, ${set("size", "size")} ` +
5541
+ `WHERE ${d.id("filename")} IS NULL AND ${d.id("contentType")} IS NULL`, []);
5542
+ return;
5543
+ }
5544
+ catch {
5545
+ // `json_extract` is a JSON1 function. It is present in D1 and in every ordinary SQLite
5546
+ // build, but nothing in this repo has depended on it before and DO SQLite is
5547
+ // Cloudflare's own engine — so a missing function must not brick a tenant's boot,
5548
+ // which is exactly what a data migration's fail-closed contract would otherwise do.
5549
+ // The fallback walks the rows through the ORM, where the fileRef codec has already
5550
+ // parsed the same JSON for us. Slower, and bounded by how many media a tenant has.
5551
+ }
5552
+ // No chunking: this runs inside `blockConcurrencyWhile` on a tenant's first fetch, so a
5553
+ // very large library will stall that one request — which is still the right trade
5554
+ // against leaving half the table unsorted forever, since a migration runs ONCE.
5555
+ const rows = await db.find({ from: "cms_media", where: { filename: { isNull: true }, contentType: { isNull: true } } });
5556
+ for (const row of rows) {
5557
+ const file = row.file;
5558
+ if (!file || typeof file !== "object" || Array.isArray(file))
5559
+ continue;
5560
+ const ref = file;
5561
+ await db.update("cms_media", String(row.id), {
5562
+ filename: typeof ref.filename === "string" ? ref.filename : null,
5563
+ contentType: typeof ref.contentType === "string" ? ref.contentType : null,
5564
+ size: typeof ref.size === "number" ? ref.size : null,
5565
+ });
5566
+ }
5567
+ },
5568
+ },
5569
+ ];
5167
5570
  export const cmsTasks = {
5168
5571
  "cms:publish": async (ctx, payload) => {
5169
5572
  const { pageId, token } = asObj(payload);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pramen/cms",
3
- "version": "0.0.60",
3
+ "version": "0.0.63",
4
4
  "description": "Optional block/page builder for pramen — Drupal-Paragraphs-style typed blocks in named regions, reusable blocks, scheduled publishing, built entirely from pramen primitives.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -41,7 +41,7 @@
41
41
  "access": "public"
42
42
  },
43
43
  "dependencies": {
44
- "@pramen/server": "0.0.60"
44
+ "@pramen/server": "0.0.63"
45
45
  },
46
46
  "peerDependencies": {
47
47
  "react": ">=18"