Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/collection-index-page.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@cloudhal/core-ts": patch
---

A collection's template may now sit on top of a page at its prefix: `set_collection_permalink` with `posts` → `/blog/{slug}` no longer fails with `path_conflict` because a page lives at `/blog`. That page is the collection's index page (RFC-0038), so only pages strictly under the prefix conflict, in the template check, its SQL race guard (`noPageUnder`) and the reverse check on page writes. Studio's "Create listing page" now works for a collection with its own permalink too.
2 changes: 1 addition & 1 deletion apps/studio/test/collection-settings.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ describe("Collection settings", () => {
status: 409,
body: {
error: "path_conflict",
message: 'collection "posts" at /about would cover page /about',
message: 'collection "posts" at /about would cover page /about/team',
},
});
render(wrap(<CollectionSettingsSection siteId="site_1" />));
Expand Down
6 changes: 3 additions & 3 deletions docs/rfcs/0038-collection-permalinks.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ When tokens other than `{slug}` arrive, a prefix no longer describes the change.

### 4. Invariants

1. A template never overlaps another collection's template, a taxonomy archive's `basePath`, a page path, or a reserved path (`checkReservedPath`, `pathsOverlap`, and `entryAt` for the reverse check). A conflicting `updateSite` fails with `path_conflict`, the way Eleventy refuses duplicate URLs.
1. A template never overlaps another collection's template, a taxonomy archive's `basePath`, a page path under its prefix (the page at the prefix itself is the collection's index page, open question 3), or a reserved path (`checkReservedPath`, `pathsOverlap`, and `entryAt` for the reverse check). A conflicting `updateSite` fails with `path_conflict`, the way Eleventy refuses duplicate URLs.
2. The default is `/<collection>/{slug}`: a site without `collections` renders exactly as before.
3. The collection key is never derived from the URL. Filters, templates, MCP tools and `ContentEntry.collection` keep using the key.
4. Changing a template never breaks a published URL: the old URL answers with a 301 to the new one.
Expand Down Expand Up @@ -145,8 +145,8 @@ No new scopes: changing a template is a site update (`site:write`). In Studio a
- **Redirects in the site's batch.** `SiteEngine.update` (`store/sites.ts`) compares `collectionPermalink(stored, key)` with `collectionPermalink(next, key)` for every key in either site (`changedPermalinks` in `permalinks.ts`). `store/site-permalinks.ts` plans one `RedirectPlan.move(oldPrefix, newPrefix, { match: "prefix", reason: "slug-change" })` per changed collection, as `updateTaxonomy` does for `archive.basePath`, and always moves (taxonomy archives do not check for published entries either). The plan's writes go into an `OpBatch` anchored on the site's new hash (`OpBatch.anchorOn(hashIs(site, hash))`), and its statements, `op_guards` assertions included, join the site CAS's batch. A failed assertion is treated as a missed CAS, so a stale or raced site write raises `ConflictError` and leaves no redirect.
- **Every locale.** Redirects are per locale (RFC-0033) and entries in every locale share the v1 template, so the move is made for the default locale (untagged) and for each other site locale. `updateTaxonomy` moves only the default locale's redirects; that difference is deliberate here, since entries exist in every locale.
- **Chains and loops** are `RedirectPlan`'s: moving again repoints the older redirects onto the new prefix, and moving back to the default drops the redirect that would point at itself.
- **Overlaps.** A changed template is checked against the effective prefixes of the other collections (configured ones, and the default `/<collection>` of collections with entries), every taxonomy archive base path (`pathsOverlap`), and, for a configured template, every page at or under its prefix, media URLs, `/search` and locale prefixes (`reserved_path`). A collection moved back to its default prefix keeps today's rule that a page under it wins. The site CAS carries race guards (`noArchiveOverlapping`, `noPageWithin` in `permalink-paths.ts`); a miss at the same rev re-runs the check for the `path_conflict` message.
- **The reverse.** Page writes (`checkPagePath`/`pageGuard` in `store/site-permalinks.ts`) and taxonomy writes (`#checkTaxonomy`/`#archiveGuard`) refuse a path in a configured prefix; their SQL guards read the site row's `collections` (`configuredPrefixFree`).
- **Overlaps.** A changed template is checked against the effective prefixes of the other collections (configured ones, and the default `/<collection>` of collections with entries), every taxonomy archive base path (`pathsOverlap`), and, for a configured template, every page under its prefix (a page at the prefix itself is the collection's index page, open question 3, and stays), media URLs, `/search` and locale prefixes (`reserved_path`). A collection moved back to its default prefix keeps today's rule that a page under it wins. The site CAS carries race guards (`noArchiveOverlapping`, `noPageUnder` in `permalink-paths.ts`); a miss at the same rev re-runs the check for the `path_conflict` message.
- **The reverse.** Page writes (`checkPagePath`/`pageGuard` in `store/site-permalinks.ts`) and taxonomy writes (`#checkTaxonomy`/`#archiveGuard`) refuse a path under a configured prefix (pages may sit at it); their SQL guards read the site row's `collections` (`configuredPrefixFree`).
- **Search.** `planSearch` rewrites every entry row when the live site node's templates differ from the indexed snapshot's, so hrefs follow the move on the next publish.
- **Rollback** restores the template with the site node; redirects stay, as invariant 5 says.

Expand Down
11 changes: 10 additions & 1 deletion packages/api/src/testing-permalinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,23 @@ export function describePermalinkApi(label: string, factory: ApiStoreFactory): v
});

it("refuses an overlap with a page (409 path_conflict) and a reserved prefix (409 reserved_path)", async () => {
// A page at the prefix (/about) would be the collection's index page; one under it is not.
await store.createPage((await store.getSite(siteId)) as Site, {
siteId,
path: "/about/team",
title: "Team",
locale: "en",
status: "draft",
sections: [],
});
const current = await site();
const clash = await putSite({
...current,
collections: { posts: { permalink: "/about/{slug}" } },
});
expect(clash.status).toBe(409);
expect(clash.body.error).toBe("path_conflict");
expect(clash.body.message).toContain("/about");
expect(clash.body.message).toContain("/about/team");

const archive = await putSite({
...current,
Expand Down
30 changes: 16 additions & 14 deletions packages/core-ts/src/permalink-paths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ export function pathsOverlap(a: string, b: string): boolean {
return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
}

/** `path` equals `base` or lies under it. */
export function pathWithin(path: string, base: string): boolean {
return path === base || path.startsWith(`${base}/`);
/** `path` lies strictly under `base` (`/blog/x` under `/blog`, but not `/blog` itself). */
export function pathUnder(path: string, base: string): boolean {
return path.startsWith(`${base}/`);
}

export interface CollectionPrefix {
Expand Down Expand Up @@ -51,29 +51,31 @@ const PERMALINK = "json_extract(c.value, '$.permalink')";
const PREFIX = `substr(${PERMALINK}, 1, length(${PERMALINK}) - 7)`;

/**
* Holds while no configured collection prefix in the site row's `collections` contains `path`
* (`within`: a page path) or overlaps it either way (`overlap`: an archive base path).
* Holds while no configured collection prefix in the site row's `collections` has `path` strictly
* under it (`under`: a page path; the page at the prefix itself is the collection's index page,
* RFC-0038) or overlaps it either way (`overlap`: an archive base path).
*/
export function configuredPrefixFree(
siteId: string,
path: string,
mode: "within" | "overlap",
mode: "under" | "overlap",
): Cond {
const within = `${PREFIX} = ? OR substr(?, 1, length(${PREFIX}) + 1) = ${PREFIX} || '/'`;
const cond = mode === "within" ? within : `${within} OR substr(${PREFIX}, 1, ?) = ?`;
const extra = mode === "within" ? [] : [path.length + 1, `${path}/`];
const under = `substr(?, 1, length(${PREFIX}) + 1) = ${PREFIX} || '/'`;
const cond =
mode === "under" ? under : `${PREFIX} = ? OR ${under} OR substr(${PREFIX}, 1, ?) = ?`;
const params = mode === "under" ? [path] : [path, path, path.length + 1, `${path}/`];
return {
sql: `NOT EXISTS (SELECT 1 FROM nodes s, json_each(s.body, '$.collections') c WHERE s.id = ? AND s.kind = 'site' AND ${PERMALINK} IS NOT NULL AND (${cond}))`,
params: [siteId, path, path, ...extra],
params: [siteId, ...params],
};
}

/** Holds while no page of the site sits at `base` or under it. */
export function noPageWithin(siteId: string, base: string): Cond {
/** Holds while no page of the site sits strictly under `base` (a page at `base` may stay). */
export function noPageUnder(siteId: string, base: string): Cond {
const path = "json_extract(body, '$.path')";
return {
sql: `NOT EXISTS (SELECT 1 FROM nodes WHERE site_id = ? AND kind = 'page' AND (${path} = ? OR substr(${path}, 1, ?) = ?))`,
params: [siteId, base, base.length + 1, `${base}/`],
sql: `NOT EXISTS (SELECT 1 FROM nodes WHERE site_id = ? AND kind = 'page' AND substr(${path}, 1, ?) = ?)`,
params: [siteId, base.length + 1, `${base}/`],
};
}

Expand Down
17 changes: 9 additions & 8 deletions packages/core-ts/src/store/site-permalinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ import {
collectionPrefixes,
configuredPrefixFree,
noArchiveOverlapping,
noPageWithin,
noPageUnder,
pathsOverlap,
pathWithin,
pathUnder,
} from "../permalink-paths.ts";
import { changedPermalinks, type PermalinkChange } from "../permalinks.ts";
import { RedirectPlan, redirectLocale } from "../redirects.ts";
Expand Down Expand Up @@ -64,7 +64,7 @@ export async function planPermalinks(
guard: and(
...changes.flatMap((c) => [
noArchiveOverlapping(next.id, c.to),
...(c.configured ? [noPageWithin(next.id, c.to)] : []),
...(c.configured ? [noPageUnder(next.id, c.to)] : []),
]),
),
async statements(hash) {
Expand Down Expand Up @@ -103,9 +103,10 @@ async function checkPermalinks(
for (const tax of taxonomies)
if (pathsOverlap(tax.archive.basePath, c.to))
conflict(`${at} collides with the ${tax.key} archive ${tax.archive.basePath}`);
// A default `/<collection>` keeps today's rule: a page there wins over an entry.
// A default `/<collection>` keeps today's rule: a page there wins over an entry. A page at
// the prefix itself is the collection's index page (RFC-0038 §"Out of scope" 3).
if (!c.configured) continue;
const page = pages.find((p) => pathWithin(p.path, c.to));
const page = pages.find((p) => pathUnder(p.path, c.to));
if (page) conflict(`${at} would cover page ${page.path}`, { pageId: page.id });
}
}
Expand All @@ -126,12 +127,12 @@ function conflict(message: string, details?: Record<string, unknown>): never {
throw new InvariantError("path_conflict", message, details);
}

/** The reverse of invariant 1 for page writes: no page at or under a configured prefix. */
/** The reverse of invariant 1 for page writes: no page under a configured prefix, only at it. */
export async function checkPagePath(ctx: StoreContext, page: Page, site?: Site): Promise<void> {
await ctx.tax.checkPagePath(page);
const s = site ?? (await ctx.graph.getSite(page.siteId));
for (const { collection, prefix } of collectionPrefixes(s, []))
if (pathWithin(page.path, prefix))
if (pathUnder(page.path, prefix))
conflict(`page path ${page.path} lies in collection "${collection}" at ${prefix}`, {
collection,
});
Expand All @@ -141,6 +142,6 @@ export async function checkPagePath(ctx: StoreContext, page: Page, site?: Site):
export function pageGuard(ctx: StoreContext, page: Page): Cond {
return and(
ctx.tax.pageGuard(page),
configuredPrefixFree(page.siteId, page.path, "within"),
configuredPrefixFree(page.siteId, page.path, "under"),
) as Cond;
}
27 changes: 24 additions & 3 deletions packages/core-ts/src/testing-permalinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ export function permalinksSuite(ctx: SuiteContext): void {
expect(dry).toMatchObject({ rev: s.rev + 1, collections: next.collections });
expect((await fresh(site)).rev).toBe(s.rev);
expect(await redirects(site)).toEqual([]);
const clash = { ...s, collections: { posts: { permalink: "/about/{slug}" } } };
const clash = { ...s, collections: { posts: { permalink: "/tag/{slug}" } } };
expect(await code(ctx.store().updateSite(clash, { dryRun: true }))).toBe("path_conflict");
});

Expand Down Expand Up @@ -157,7 +157,6 @@ export function permalinksSuite(ctx: SuiteContext): void {
tags: [],
author: person,
} as never);
expect(await code(move(site, "/about/{slug}"))).toBe("path_conflict");
expect(await code(move(site, "/work/{slug}"))).toBe("path_conflict");
expect(await code(move(site, "/category/{slug}"))).toBe("path_conflict");
expect(await code(move(site, "/tag/posts/{slug}"))).toBe("path_conflict");
Expand Down Expand Up @@ -188,7 +187,6 @@ export function permalinksSuite(ctx: SuiteContext): void {
({ site } = await page("/posts/landing"));
// A page in the way is refused when the template moves there, not afterwards.
site = await move(site, "/blog/{slug}");
expect(await code(page("/blog"))).toBe("path_conflict");
expect(await code(page("/blog/about"))).toBe("path_conflict");
const about = (await store.listPages(site.id)).find((p) => p.path === "/about");
expect(about).toBeDefined();
Expand All @@ -213,6 +211,29 @@ export function permalinksSuite(ctx: SuiteContext): void {
expect((await page("/posts/new")).page.path).toBe("/posts/new");
});

it("§4.1: the page at a template's prefix is the collection's index page, not a conflict", async () => {
let site = await setup();
const store = ctx.store();
const page = (path: string) =>
store.createPage(site, {
siteId: site.id,
path,
title: "P",
locale: "en",
status: "draft",
sections: [],
});
// The listing page exists first; entries then move under it. Both writes run their SQL race
// guards (`noPageUnder`, `configuredPrefixFree`) in the batch, so those pass too.
({ site } = await page("/blog"));
site = await move(site, "/blog/{slug}");
expect(site.collections?.posts?.permalink).toBe("/blog/{slug}");
// …or the template is there first and the listing page comes after.
site = await move(site, "/notes/{slug}");
({ site } = await page("/notes"));
expect((await store.listPages(site.id)).map((p) => p.path)).toContain("/notes");
});

it("§3: a stale site rev raises ConflictError and writes no redirect", async () => {
const site = await setup();
const stale = await fresh(site);
Expand Down
11 changes: 10 additions & 1 deletion packages/mcp-server/test/permalinks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,18 @@ describe("set_collection_permalink (RFC-0038 §5)", () => {

it("an overlap or a no-op is refused before a person is asked", async () => {
const run = direct(w, "edits");
// The page at /about would be the collection's index page; one under it is in the way.
await w.store.createPage(w.site, {
siteId: w.site.id,
path: "/about/team",
title: "Team",
locale: w.site.defaultLocale,
status: "draft",
sections: [],
});
await expect(run({ permalink: "/about/{slug}" })).rejects.toMatchObject({
code: "path_conflict",
message: expect.stringContaining("would cover page /about"),
message: expect.stringContaining("would cover page /about/team"),
});
await expect(run({ permalink: "/tag/{slug}" })).rejects.toMatchObject({
code: "path_conflict",
Expand Down
Loading