create-freeholder 0.2.0-beta.5 → 0.2.0-beta.6
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/template/.changeset/blog-playground-content.md +4 -0
- package/dist/template/.changeset/blog-wordpress-structure.md +6 -0
- package/dist/template/.changeset/managed-preview-assistant.md +4 -0
- package/dist/template/.changeset/public-beta-6.md +4 -0
- package/dist/template/.github/ISSUE_TEMPLATE/bug_report.yml +1 -1
- package/dist/template/MASTER.md +81 -8
- package/dist/template/README.md +1 -1
- package/dist/template/app/(admin)/admin/assistant/page.tsx +9 -1
- package/dist/template/app/(admin)/admin/blog/PostSettings.tsx +26 -0
- package/dist/template/app/(admin)/admin/blog/[kind]/page.tsx +53 -0
- package/dist/template/app/(admin)/admin/blog/actions.ts +186 -6
- package/dist/template/app/(admin)/admin/blog/comments/page.tsx +25 -0
- package/dist/template/app/(admin)/admin/blog/page.tsx +21 -5
- package/dist/template/app/(admin)/admin/imports/[id]/page.tsx +2 -0
- package/dist/template/app/(admin)/admin/pages/[id]/page.tsx +3 -0
- package/dist/template/app/(admin)/assistant-actions.ts +13 -6
- package/dist/template/app/(public)/[[...slug]]/ReaderComments.tsx +25 -0
- package/dist/template/app/(public)/[[...slug]]/blog-parts.tsx +153 -0
- package/dist/template/app/(public)/[[...slug]]/comment-actions.ts +16 -0
- package/dist/template/app/(public)/[[...slug]]/page.tsx +182 -18
- package/dist/template/app/api/chat/assistant/call/route.ts +35 -0
- package/dist/template/db/migrations/0061_blog_structure.sql +89 -0
- package/dist/template/db/migrations/0062_blog_reader_comments.sql +24 -0
- package/dist/template/db/migrations/meta/_journal.json +14 -0
- package/dist/template/deploy/blog-wordpress-2026-11-07.md +146 -0
- package/dist/template/deploy/docker-selfhost/.env.example +1 -1
- package/dist/template/deploy/docker-selfhost/README.md +3 -2
- package/dist/template/deploy/docker-selfhost/infra/compose.https.yml +1 -1
- package/dist/template/deploy/docker-selfhost/infra/compose.yml +1 -1
- package/dist/template/deploy/f-criteria-matrix.md +74 -0
- package/dist/template/deploy/linux/README.md +1 -1
- package/dist/template/deploy/linux/install.sh +1 -1
- package/dist/template/deploy/managed-preview-assistant.md +99 -0
- package/dist/template/eslint.config.mjs +3 -1
- package/dist/template/locales/ar.json +85 -6
- package/dist/template/locales/en.json +83 -4
- package/dist/template/locales/es.json +83 -4
- package/dist/template/locales/fr.json +85 -6
- package/dist/template/next.config.ts +2 -0
- package/dist/template/package.json +1 -1
- package/dist/template/packages/cli/package.json +1 -1
- package/dist/template/packages/create-freeholder/package.json +1 -1
- package/dist/template/packages/freeholder-app/package.json +1 -1
- package/dist/template/packages/mobile-app/package.json +1 -1
- package/dist/template/packages/plugin-kit/package.json +1 -1
- package/dist/template/packages/sdk/package.json +1 -1
- package/dist/template/packages/sdk/src/generated.ts +177 -9
- package/dist/template/packages/sdk/src/version.ts +1 -1
- package/dist/template/packages/templates/package.json +1 -1
- package/dist/template/proxy.ts +18 -1
- package/dist/template/public/managed-assistant/0.1.10/duplex-codec/NOTICE.txt +117 -0
- package/dist/template/public/managed-assistant/0.1.10/duplex-codec/audio-output-processor.js +267 -0
- package/dist/template/public/managed-assistant/0.1.10/duplex-codec/decoderWorker.min.js +847 -0
- package/dist/template/public/managed-assistant/0.1.10/duplex-codec/decoderWorker.min.wasm +0 -0
- package/dist/template/public/managed-assistant/0.1.10/duplex-codec/encoderWorker.min.js +1 -0
- package/dist/template/public/managed-assistant/0.1.10/manifest.json +12 -0
- package/dist/template/public/managed-assistant/0.1.10/pm-ai-duplex-client.js +1376 -0
- package/dist/template/scripts/license-headers.mjs +3 -0
- package/dist/template/scripts/verify-wordpress-migration.d.mts +8 -0
- package/dist/template/scripts/verify-wordpress-migration.mjs +105 -0
- package/dist/template/security/adversarial-audit-2026-10-08.md +1 -1
- package/dist/template/src/adapters/ai/types.ts +5 -0
- package/dist/template/src/adapters/paradise/assistant.ts +37 -0
- package/dist/template/src/adapters/paradise/http.ts +4 -3
- package/dist/template/src/core/contract/json-schema.ts +8 -0
- package/dist/template/src/core/demo/playground-inserts.ts +29 -0
- package/dist/template/src/core/demo/playground-policy.ts +9 -0
- package/dist/template/src/core/env.ts +2 -0
- package/dist/template/src/core/http/csp.ts +10 -2
- package/dist/template/src/core/http/csrf-client.ts +10 -0
- package/dist/template/src/core/import/service.ts +217 -12
- package/dist/template/src/core/import/wordpress.ts +80 -15
- package/dist/template/src/core/notifications/service.ts +1 -0
- package/dist/template/src/core/retention/registry.ts +2 -0
- package/dist/template/src/core/search/registry.ts +2 -0
- package/dist/template/src/core/seo/feeds.ts +2 -0
- package/dist/template/src/core/seo/jsonld.ts +46 -2
- package/dist/template/src/core/seo/legacy-proxy.ts +53 -0
- package/dist/template/src/core/seo/meta.ts +10 -7
- package/dist/template/src/core/seo/service.ts +14 -1
- package/dist/template/src/core/update/release-declaration.json +1 -1
- package/dist/template/src/modules/assistant/contract.ts +1 -1
- package/dist/template/src/modules/assistant/limits.ts +3 -0
- package/dist/template/src/modules/assistant/preview.ts +124 -0
- package/dist/template/src/modules/assistant/provider.ts +7 -0
- package/dist/template/src/modules/assistant/service.ts +21 -5
- package/dist/template/src/modules/cms/blocks/PreviewAssistantCall.tsx +176 -0
- package/dist/template/src/modules/cms/blocks/SiteChatClient.tsx +10 -4
- package/dist/template/src/modules/cms/blocks/surfaces.tsx +10 -0
- package/dist/template/src/modules/cms/blog-comments-schema.ts +27 -0
- package/dist/template/src/modules/cms/blog-comments.ts +111 -0
- package/dist/template/src/modules/cms/blog-schema.ts +146 -0
- package/dist/template/src/modules/cms/blog-service.ts +999 -0
- package/dist/template/src/modules/cms/blog.tsx +245 -25
- package/dist/template/src/modules/cms/manifest.ts +7 -1
- package/dist/template/src/modules/cms/read.ts +18 -0
- package/dist/template/src/modules/cms/service.ts +22 -4
- package/dist/template/src/modules/cms/tables.ts +2 -0
- package/dist/template/src/modules/seed/launch.ts +31 -3
- package/dist/template/tests/browser/blog-structure.spec.ts +69 -0
- package/dist/template/tests/core/analytics-consent.test.ts +1 -1
- package/dist/template/tests/core/blog-playground.test.ts +106 -0
- package/dist/template/tests/core/blog-structure-comments.test.ts +166 -0
- package/dist/template/tests/core/csp.test.ts +1 -1
- package/dist/template/tests/core/internal-services.test.ts +4 -0
- package/dist/template/tests/core/legacy-redirect-proxy.test.ts +59 -0
- package/dist/template/tests/core/locale-routing.test.ts +1 -1
- package/dist/template/tests/core/playground-cache.test.ts +1 -1
- package/dist/template/tests/core/playground.test.ts +3 -3
- package/dist/template/tests/core/preview-assistant-call.test.ts +88 -0
- package/dist/template/tests/core/private-preview-webhooks.test.ts +1 -1
- package/dist/template/tests/core/private-preview.test.ts +1 -1
- package/dist/template/tests/core/proxy-locale.test.ts +1 -1
- package/dist/template/tests/core/sdk-schema.test.ts +20 -0
- package/dist/template/tests/core/seo.test.ts +1 -1
- package/dist/template/tests/core/site-chat-client.test.ts +50 -0
- package/dist/template/tests/core/wordpress-import-flow.test.ts +81 -18
- package/dist/template/tests/core/wordpress-import.test.ts +25 -12
- package/dist/template/tests/core/wordpress-migration-verification.test.ts +37 -0
- package/dist/template/tests/modules/preview-assistant.test.ts +164 -0
- package/dist/template-manifest.json +349 -139
- package/package.json +1 -1
|
@@ -0,0 +1,999 @@
|
|
|
1
|
+
// Copyright (C) 2026 Tony Aly
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
// Blog structure services: categories, tags, authors and post metadata
|
|
4
|
+
// (C2.27, C2.28). UI, HTTP and MCP all reach the blog through these.
|
|
5
|
+
//
|
|
6
|
+
// Archive paths are addresses people and search engines keep. Changing a
|
|
7
|
+
// slug, a parent or deleting a term moves an archive, so the service that
|
|
8
|
+
// moves it records the redirect (MASTER.md §5: "slugs never silently break"),
|
|
9
|
+
// the same way `cms.updatePage` does for a renamed page.
|
|
10
|
+
import { and, asc, desc, eq, inArray, isNull, isNotNull, like, notInArray, or, sql } from "drizzle-orm";
|
|
11
|
+
import { z } from "zod";
|
|
12
|
+
import { checkPlaygroundInsert } from "@/core/demo/playground-inserts";
|
|
13
|
+
import { listed, okResult, row, timestamp, uuid } from "@/core/contract";
|
|
14
|
+
import { defineService, getService, ServiceError, type ServiceContext, type Tx } from "@/core/service";
|
|
15
|
+
import { isUniqueViolation } from "@/core/db";
|
|
16
|
+
import { users } from "@/core/auth/schema";
|
|
17
|
+
import { businessProfile } from "@/core/settings/schema";
|
|
18
|
+
import { pages } from "./schema";
|
|
19
|
+
import {
|
|
20
|
+
BLOG_TAXONOMIES,
|
|
21
|
+
blogAuthors,
|
|
22
|
+
blogPosts,
|
|
23
|
+
blogPostTerms,
|
|
24
|
+
blogSettings,
|
|
25
|
+
blogTerms,
|
|
26
|
+
type BlogTaxonomy,
|
|
27
|
+
} from "./blog-schema";
|
|
28
|
+
|
|
29
|
+
/* ---------------------------------------------------------------- shapes */
|
|
30
|
+
|
|
31
|
+
const slugPart = z
|
|
32
|
+
.string()
|
|
33
|
+
.trim()
|
|
34
|
+
.toLowerCase()
|
|
35
|
+
.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "use lowercase words separated by hyphens");
|
|
36
|
+
|
|
37
|
+
/** A site path, no leading or trailing slash: "category/glazes". */
|
|
38
|
+
const archivePath = z
|
|
39
|
+
.string()
|
|
40
|
+
.trim()
|
|
41
|
+
.transform((value) => value.replace(/^\/+|\/+$/g, "").toLowerCase())
|
|
42
|
+
.refine((value) => /^[a-z0-9]+(?:[-/][a-z0-9]+)*$/.test(value) && !value.includes("//"), "use lowercase words separated by hyphens or slashes");
|
|
43
|
+
|
|
44
|
+
const archiveSeo = z
|
|
45
|
+
.object({
|
|
46
|
+
title: z.string().trim().max(200).optional(),
|
|
47
|
+
description: z.string().trim().max(320).optional(),
|
|
48
|
+
noindex: z.boolean().optional(),
|
|
49
|
+
})
|
|
50
|
+
.default({});
|
|
51
|
+
export type ArchiveSeo = z.infer<typeof archiveSeo>;
|
|
52
|
+
|
|
53
|
+
const termRow = row({
|
|
54
|
+
id: uuid,
|
|
55
|
+
taxonomy: z.enum(BLOG_TAXONOMIES),
|
|
56
|
+
slug: z.string(),
|
|
57
|
+
path: z.string(),
|
|
58
|
+
name: z.string(),
|
|
59
|
+
description: z.string().nullable(),
|
|
60
|
+
parentId: uuid.nullable(),
|
|
61
|
+
position: z.number().int(),
|
|
62
|
+
seo: z.unknown(),
|
|
63
|
+
source: z.string(),
|
|
64
|
+
createdAt: timestamp,
|
|
65
|
+
updatedAt: timestamp,
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
const authorRow = row({
|
|
69
|
+
id: uuid,
|
|
70
|
+
slug: z.string(),
|
|
71
|
+
path: z.string(),
|
|
72
|
+
name: z.string(),
|
|
73
|
+
bio: z.string().nullable(),
|
|
74
|
+
email: z.string().nullable(),
|
|
75
|
+
userId: uuid.nullable(),
|
|
76
|
+
seo: z.unknown(),
|
|
77
|
+
source: z.string(),
|
|
78
|
+
createdAt: timestamp,
|
|
79
|
+
updatedAt: timestamp,
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
const settingsRow = z.object({
|
|
83
|
+
categoryBase: z.string(),
|
|
84
|
+
tagBase: z.string(),
|
|
85
|
+
authorBase: z.string(),
|
|
86
|
+
postsPerPage: z.number().int(),
|
|
87
|
+
commentsEnabled: z.boolean(),
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
export type BlogSettings = z.infer<typeof settingsRow>;
|
|
91
|
+
|
|
92
|
+
export const DEFAULT_BLOG_SETTINGS: BlogSettings = {
|
|
93
|
+
categoryBase: "blog/category",
|
|
94
|
+
tagBase: "blog/tag",
|
|
95
|
+
authorBase: "blog/author",
|
|
96
|
+
postsPerPage: 12,
|
|
97
|
+
commentsEnabled: true,
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
/* --------------------------------------------------------------- helpers */
|
|
101
|
+
|
|
102
|
+
/** A slug lookup must authorize this exact row, including legacy locale duplicates. */
|
|
103
|
+
export async function isPublicPage(ctx: ServiceContext, page: { id: string; slug: string; locale?: string }): Promise<boolean> {
|
|
104
|
+
const resolved = z.object({ id: uuid }).nullable().parse(await ctx.call(getService("cms.resolvePage"), { slug: page.slug, ...(page.locale ? { locale: page.locale } : {}) }));
|
|
105
|
+
return resolved?.id === page.id;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export async function loadBlogSettings(tx: Tx): Promise<BlogSettings> {
|
|
109
|
+
const [found] = await tx.select().from(blogSettings).where(eq(blogSettings.key, "site")).limit(1);
|
|
110
|
+
return found
|
|
111
|
+
? {
|
|
112
|
+
categoryBase: found.categoryBase,
|
|
113
|
+
tagBase: found.tagBase,
|
|
114
|
+
authorBase: found.authorBase,
|
|
115
|
+
postsPerPage: found.postsPerPage,
|
|
116
|
+
commentsEnabled: found.commentsEnabled,
|
|
117
|
+
}
|
|
118
|
+
: DEFAULT_BLOG_SETTINGS;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** An archive path may not be a page's, or another archive's. */
|
|
122
|
+
async function assertPathFree(
|
|
123
|
+
tx: Tx,
|
|
124
|
+
path: string,
|
|
125
|
+
own: { termId?: string; authorId?: string },
|
|
126
|
+
): Promise<void> {
|
|
127
|
+
const [page] = await tx
|
|
128
|
+
.select({ id: pages.id })
|
|
129
|
+
.from(pages)
|
|
130
|
+
.where(and(eq(pages.slug, path), isNull(pages.trashedAt)))
|
|
131
|
+
.limit(1);
|
|
132
|
+
if (page) throw new ServiceError("conflict", `A page already lives at /${path}.`);
|
|
133
|
+
const [term] = await tx.select({ id: blogTerms.id }).from(blogTerms).where(eq(blogTerms.path, path)).limit(1);
|
|
134
|
+
if (term && term.id !== own.termId) throw new ServiceError("conflict", `Another archive already lives at /${path}.`);
|
|
135
|
+
const [author] = await tx
|
|
136
|
+
.select({ id: blogAuthors.id })
|
|
137
|
+
.from(blogAuthors)
|
|
138
|
+
.where(eq(blogAuthors.path, path))
|
|
139
|
+
.limit(1);
|
|
140
|
+
if (author && author.id !== own.authorId) throw new ServiceError("conflict", `Another archive already lives at /${path}.`);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function moved(ctx: ServiceContext, fromPath: string, toPath: string): Promise<void> {
|
|
144
|
+
if (fromPath === toPath) return;
|
|
145
|
+
await ctx.callAsSystem(getService("seo.recordRedirect"), {
|
|
146
|
+
fromPath,
|
|
147
|
+
toPath,
|
|
148
|
+
source: "slug-change",
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
type TermRecord = typeof blogTerms.$inferSelect;
|
|
153
|
+
|
|
154
|
+
async function allTerms(tx: Tx, taxonomy?: BlogTaxonomy): Promise<TermRecord[]> {
|
|
155
|
+
return tx
|
|
156
|
+
.select()
|
|
157
|
+
.from(blogTerms)
|
|
158
|
+
.where(taxonomy ? eq(blogTerms.taxonomy, taxonomy) : undefined)
|
|
159
|
+
.orderBy(asc(blogTerms.position), asc(blogTerms.name));
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function categoryPath(base: string, chain: string[]): string {
|
|
163
|
+
return [base, ...chain].filter(Boolean).join("/");
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Slugs from the root down to `id`, inclusive. */
|
|
167
|
+
function chainOf(terms: Map<string, TermRecord>, id: string | null, own?: { id: string; slug: string; parentId: string | null }): string[] {
|
|
168
|
+
const chain: string[] = [];
|
|
169
|
+
const seen = new Set<string>();
|
|
170
|
+
let cursor: string | null = id;
|
|
171
|
+
while (cursor) {
|
|
172
|
+
if (seen.has(cursor)) throw new ServiceError("validation", "A category cannot be inside itself.");
|
|
173
|
+
seen.add(cursor);
|
|
174
|
+
const term = own && cursor === own.id ? { ...terms.get(cursor)!, ...own } : terms.get(cursor);
|
|
175
|
+
if (!term) break;
|
|
176
|
+
chain.unshift(term.slug);
|
|
177
|
+
cursor = term.parentId;
|
|
178
|
+
}
|
|
179
|
+
return chain;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Every descendant of a category, for archives that include subcategories. */
|
|
183
|
+
export function descendantIds(terms: Array<{ id: string; parentId: string | null }>, rootId: string): string[] {
|
|
184
|
+
const out = [rootId];
|
|
185
|
+
for (let index = 0; index < out.length; index += 1) {
|
|
186
|
+
for (const term of terms) if (term.parentId === out[index] && !out.includes(term.id)) out.push(term.id);
|
|
187
|
+
}
|
|
188
|
+
return out;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Re-path a category and everything under it after its slug or parent
|
|
193
|
+
* changed, recording a redirect for every archive that moved. A path set
|
|
194
|
+
* explicitly (an imported WordPress archive) keeps its own base.
|
|
195
|
+
*/
|
|
196
|
+
async function repathCategorySubtree(ctx: ServiceContext, rootId: string): Promise<void> {
|
|
197
|
+
const terms = await allTerms(ctx.tx, "category");
|
|
198
|
+
const byId = new Map(terms.map((term) => [term.id, term]));
|
|
199
|
+
for (const id of descendantIds(terms, rootId)) {
|
|
200
|
+
const term = byId.get(id)!;
|
|
201
|
+
const parent = term.parentId ? byId.get(term.parentId) : undefined;
|
|
202
|
+
const next = parent ? `${parent.path}/${term.slug}` : term.path.replace(/[^/]+$/, term.slug);
|
|
203
|
+
if (next === term.path) continue;
|
|
204
|
+
await assertPathFree(ctx.tx, next, { termId: term.id });
|
|
205
|
+
await ctx.tx.update(blogTerms).set({ path: next }).where(eq(blogTerms.id, term.id));
|
|
206
|
+
await moved(ctx, term.path, next);
|
|
207
|
+
byId.set(id, { ...term, path: next });
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/* -------------------------------------------------------------- settings */
|
|
212
|
+
|
|
213
|
+
export const getBlogSettings = defineService({
|
|
214
|
+
name: "cms.blogSettings",
|
|
215
|
+
summary: "Where new blog archives live and how many posts an archive page lists.",
|
|
216
|
+
kind: "query",
|
|
217
|
+
permission: "public",
|
|
218
|
+
input: z.object({}),
|
|
219
|
+
output: settingsRow,
|
|
220
|
+
handler: (_input, ctx) => loadBlogSettings(ctx.tx),
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
export const updateBlogSettings = defineService({
|
|
224
|
+
name: "cms.updateBlogSettings",
|
|
225
|
+
summary:
|
|
226
|
+
"Change where new category, tag and author archives live and how many posts an archive page lists. Existing archives keep their addresses.",
|
|
227
|
+
kind: "mutation",
|
|
228
|
+
permission: "scoped",
|
|
229
|
+
input: z.object({
|
|
230
|
+
categoryBase: archivePath.optional(),
|
|
231
|
+
tagBase: archivePath.optional(),
|
|
232
|
+
authorBase: archivePath.optional(),
|
|
233
|
+
postsPerPage: z.number().int().min(1).max(50).optional(),
|
|
234
|
+
commentsEnabled: z.boolean().optional(),
|
|
235
|
+
}),
|
|
236
|
+
output: settingsRow,
|
|
237
|
+
handler: async (input, ctx) => {
|
|
238
|
+
const current = await loadBlogSettings(ctx.tx);
|
|
239
|
+
const next = { ...current, ...Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined)) };
|
|
240
|
+
await ctx.tx
|
|
241
|
+
.insert(blogSettings)
|
|
242
|
+
.values({ key: "site", ...next })
|
|
243
|
+
.onConflictDoUpdate({ target: blogSettings.key, set: { ...next, updatedAt: new Date() } });
|
|
244
|
+
ctx.setSubject("blog_settings", "site");
|
|
245
|
+
return next;
|
|
246
|
+
},
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
/* ----------------------------------------------------------------- terms */
|
|
250
|
+
|
|
251
|
+
export const listTerms = defineService({
|
|
252
|
+
name: "cms.listTerms",
|
|
253
|
+
summary: "Blog categories and tags, with how many published posts each has.",
|
|
254
|
+
kind: "query",
|
|
255
|
+
permission: "scoped",
|
|
256
|
+
input: z.object({ taxonomy: z.enum(BLOG_TAXONOMIES).optional() }),
|
|
257
|
+
output: listed(termRow.extend({ posts: z.number().int() })),
|
|
258
|
+
handler: async (input, ctx) => {
|
|
259
|
+
const terms = await allTerms(ctx.tx, input.taxonomy);
|
|
260
|
+
const counts = await ctx.tx
|
|
261
|
+
.select({ termId: blogPostTerms.termId, posts: sql<number>`count(*)::int` })
|
|
262
|
+
.from(blogPostTerms)
|
|
263
|
+
.innerJoin(pages, eq(pages.id, blogPostTerms.pageId))
|
|
264
|
+
.where(and(eq(pages.status, "published"), isNull(pages.trashedAt)))
|
|
265
|
+
.groupBy(blogPostTerms.termId);
|
|
266
|
+
const byTerm = new Map(counts.map((count) => [count.termId, Number(count.posts)]));
|
|
267
|
+
return terms.map((term) => ({ ...term, posts: byTerm.get(term.id) ?? 0 }));
|
|
268
|
+
},
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
export const publicBlogCategories = defineService({
|
|
272
|
+
name: "cms.publicBlogCategories", summary: "Public category links with published posts, without draft taxonomy or import metadata.",
|
|
273
|
+
kind: "query", permission: "public", input: z.object({}),
|
|
274
|
+
output: listed(z.object({ slug: z.string(), name: z.string(), path: z.string(), posts: z.number().int() })),
|
|
275
|
+
handler: async (_input, ctx) => {
|
|
276
|
+
const out = [];
|
|
277
|
+
for (const category of await allTerms(ctx.tx, "category")) {
|
|
278
|
+
if (category.parentId) continue;
|
|
279
|
+
const dated = await publishedPostDates(ctx, await postIdsMatching(ctx.tx, { category: category.id }));
|
|
280
|
+
if (dated.length) out.push({ slug: category.slug, name: category.name, path: category.path, posts: dated.length });
|
|
281
|
+
}
|
|
282
|
+
return out;
|
|
283
|
+
},
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
export const saveTerm = defineService({
|
|
287
|
+
name: "cms.saveTerm",
|
|
288
|
+
summary:
|
|
289
|
+
"Create or change a blog category or tag. Changing its slug or parent moves its archive and records a redirect from the old address.",
|
|
290
|
+
kind: "mutation",
|
|
291
|
+
permission: "scoped",
|
|
292
|
+
input: z.object({
|
|
293
|
+
id: z.string().uuid().optional(),
|
|
294
|
+
taxonomy: z.enum(BLOG_TAXONOMIES),
|
|
295
|
+
name: z.string().trim().min(1).max(200),
|
|
296
|
+
slug: slugPart.optional(),
|
|
297
|
+
description: z.string().trim().max(2_000).nullable().optional(),
|
|
298
|
+
parentId: z.string().uuid().nullable().optional(),
|
|
299
|
+
position: z.number().int().min(0).max(100_000).optional(),
|
|
300
|
+
seo: archiveSeo.optional(),
|
|
301
|
+
/** An explicit archive address (an imported site keeps its own). */
|
|
302
|
+
path: archivePath.optional(),
|
|
303
|
+
source: z.string().max(100).optional(),
|
|
304
|
+
}),
|
|
305
|
+
output: termRow,
|
|
306
|
+
handler: async (input, ctx) => {
|
|
307
|
+
const settings = await loadBlogSettings(ctx.tx);
|
|
308
|
+
const slug = input.slug ?? slugFromName(input.name);
|
|
309
|
+
if (input.taxonomy === "tag" && input.parentId) {
|
|
310
|
+
throw new ServiceError("validation", "Tags are flat; only categories have parents.");
|
|
311
|
+
}
|
|
312
|
+
const terms = await allTerms(ctx.tx, input.taxonomy);
|
|
313
|
+
const byId = new Map(terms.map((term) => [term.id, term]));
|
|
314
|
+
const before = input.id ? byId.get(input.id) : undefined;
|
|
315
|
+
if (input.id && !before) throw new ServiceError("not_found", "That category or tag is gone.");
|
|
316
|
+
const parentId = input.parentId === undefined ? (before?.parentId ?? null) : input.parentId;
|
|
317
|
+
if (parentId && !byId.has(parentId)) throw new ServiceError("validation", "That parent category does not exist.");
|
|
318
|
+
|
|
319
|
+
let path: string;
|
|
320
|
+
if (input.path) {
|
|
321
|
+
path = input.path;
|
|
322
|
+
} else if (input.taxonomy === "category") {
|
|
323
|
+
const parent = parentId ? byId.get(parentId)! : undefined;
|
|
324
|
+
if (parent && before) chainOf(byId, parentId, { id: before.id, slug, parentId });
|
|
325
|
+
path = parent ? `${parent.path}/${slug}` : before ? before.path.replace(/[^/]+$/, slug) : categoryPath(settings.categoryBase, [slug]);
|
|
326
|
+
} else {
|
|
327
|
+
path = before ? before.path.replace(/[^/]+$/, slug) : `${settings.tagBase}/${slug}`;
|
|
328
|
+
}
|
|
329
|
+
if (before && parentId && descendantIds(terms, before.id).includes(parentId)) {
|
|
330
|
+
throw new ServiceError("validation", "A category cannot be inside itself.");
|
|
331
|
+
}
|
|
332
|
+
await assertPathFree(ctx.tx, path, { termId: before?.id });
|
|
333
|
+
|
|
334
|
+
const values = {
|
|
335
|
+
taxonomy: input.taxonomy,
|
|
336
|
+
name: input.name,
|
|
337
|
+
slug,
|
|
338
|
+
path,
|
|
339
|
+
description: input.description === undefined ? (before?.description ?? null) : input.description,
|
|
340
|
+
parentId,
|
|
341
|
+
position: input.position ?? before?.position ?? 0,
|
|
342
|
+
seo: input.seo ?? (before?.seo as ArchiveSeo | undefined) ?? {},
|
|
343
|
+
source: before?.source ?? input.source ?? "admin",
|
|
344
|
+
};
|
|
345
|
+
let saved: TermRecord;
|
|
346
|
+
if (!before) await checkPlaygroundInsert(ctx.tx, ctx.actor, "cms.saveTerm");
|
|
347
|
+
try {
|
|
348
|
+
if (before) {
|
|
349
|
+
[saved] = (await ctx.tx.update(blogTerms).set(values).where(eq(blogTerms.id, before.id)).returning()) as [TermRecord];
|
|
350
|
+
} else {
|
|
351
|
+
[saved] = (await ctx.tx.insert(blogTerms).values(values).returning()) as [TermRecord];
|
|
352
|
+
}
|
|
353
|
+
} catch (error) {
|
|
354
|
+
if (isUniqueViolation(error)) {
|
|
355
|
+
throw new ServiceError("conflict", `Another ${input.taxonomy} already uses the slug "${slug}".`);
|
|
356
|
+
}
|
|
357
|
+
throw error;
|
|
358
|
+
}
|
|
359
|
+
if (before && before.path !== saved.path) {
|
|
360
|
+
await moved(ctx, before.path, saved.path);
|
|
361
|
+
if (saved.taxonomy === "category") await repathCategorySubtree(ctx, saved.id);
|
|
362
|
+
}
|
|
363
|
+
ctx.setSubject("blog_term", saved.id);
|
|
364
|
+
ctx.queueEvent(before ? "cms.termUpdated" : "cms.termCreated", { id: saved.id, taxonomy: saved.taxonomy });
|
|
365
|
+
return saved;
|
|
366
|
+
},
|
|
367
|
+
});
|
|
368
|
+
|
|
369
|
+
export const deleteTerm = defineService({
|
|
370
|
+
name: "cms.deleteTerm",
|
|
371
|
+
writeClass: "destructive",
|
|
372
|
+
summary:
|
|
373
|
+
"Delete a blog category or tag. Its posts stay; subcategories move up a level; its archive redirects to its parent's archive or the blog.",
|
|
374
|
+
kind: "mutation",
|
|
375
|
+
permission: "scoped",
|
|
376
|
+
input: z.object({ id: z.string().uuid() }),
|
|
377
|
+
output: okResult,
|
|
378
|
+
handler: async (input, ctx) => {
|
|
379
|
+
const [term] = await ctx.tx.select().from(blogTerms).where(eq(blogTerms.id, input.id)).limit(1);
|
|
380
|
+
if (!term) throw new ServiceError("not_found", "That category or tag is gone.");
|
|
381
|
+
const parent = term.parentId
|
|
382
|
+
? (await ctx.tx.select().from(blogTerms).where(eq(blogTerms.id, term.parentId)).limit(1))[0]
|
|
383
|
+
: undefined;
|
|
384
|
+
const children = await ctx.tx.select().from(blogTerms).where(eq(blogTerms.parentId, term.id));
|
|
385
|
+
await ctx.tx.delete(blogTerms).where(eq(blogTerms.id, term.id));
|
|
386
|
+
for (const childTerm of children) {
|
|
387
|
+
await ctx.tx.update(blogTerms).set({ parentId: parent?.id ?? null }).where(eq(blogTerms.id, childTerm.id));
|
|
388
|
+
}
|
|
389
|
+
for (const childTerm of children) {
|
|
390
|
+
const next = parent ? `${parent.path}/${childTerm.slug}` : term.path.replace(/[^/]+$/, childTerm.slug);
|
|
391
|
+
if (next !== childTerm.path) {
|
|
392
|
+
await assertPathFree(ctx.tx, next, { termId: childTerm.id });
|
|
393
|
+
await ctx.tx.update(blogTerms).set({ path: next }).where(eq(blogTerms.id, childTerm.id));
|
|
394
|
+
await moved(ctx, childTerm.path, next);
|
|
395
|
+
await repathCategorySubtree(ctx, childTerm.id);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
await moved(ctx, term.path, parent?.path ?? "blog");
|
|
399
|
+
ctx.setSubject("blog_term", term.id);
|
|
400
|
+
ctx.queueEvent("cms.termDeleted", { id: term.id, taxonomy: term.taxonomy });
|
|
401
|
+
return { ok: true as const };
|
|
402
|
+
},
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
/* --------------------------------------------------------------- authors */
|
|
406
|
+
|
|
407
|
+
export function slugFromName(name: string): string {
|
|
408
|
+
return (
|
|
409
|
+
name
|
|
410
|
+
.normalize("NFKD")
|
|
411
|
+
.replace(/[̀-ͯ]/g, "")
|
|
412
|
+
.toLowerCase()
|
|
413
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
414
|
+
.replace(/^-+|-+$/g, "")
|
|
415
|
+
.slice(0, 80) || "item"
|
|
416
|
+
);
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
export const listAuthors = defineService({
|
|
420
|
+
name: "cms.listAuthors",
|
|
421
|
+
summary: "Blog authors, including private matching email and linked account.",
|
|
422
|
+
kind: "query",
|
|
423
|
+
permission: "scoped",
|
|
424
|
+
input: z.object({}),
|
|
425
|
+
output: listed(authorRow.extend({ posts: z.number().int() })),
|
|
426
|
+
handler: async (_input, ctx) => {
|
|
427
|
+
const authors = await ctx.tx.select().from(blogAuthors).orderBy(asc(blogAuthors.name));
|
|
428
|
+
const counts = await ctx.tx
|
|
429
|
+
.select({ authorId: blogPosts.authorId, posts: sql<number>`count(*)::int` })
|
|
430
|
+
.from(blogPosts)
|
|
431
|
+
.groupBy(blogPosts.authorId);
|
|
432
|
+
const byAuthor = new Map(counts.map((count) => [count.authorId, Number(count.posts)]));
|
|
433
|
+
return authors.map((author) => ({ ...author, posts: byAuthor.get(author.id) ?? 0 }));
|
|
434
|
+
},
|
|
435
|
+
});
|
|
436
|
+
|
|
437
|
+
export const saveAuthor = defineService({
|
|
438
|
+
name: "cms.saveAuthor",
|
|
439
|
+
summary:
|
|
440
|
+
"Create or change a blog author: a site account, or a profile that cannot sign in. Changing the slug moves the archive and records a redirect.",
|
|
441
|
+
kind: "mutation",
|
|
442
|
+
permission: "scoped",
|
|
443
|
+
input: z.object({
|
|
444
|
+
id: z.string().uuid().optional(),
|
|
445
|
+
name: z.string().trim().min(1).max(200),
|
|
446
|
+
slug: slugPart.optional(),
|
|
447
|
+
bio: z.string().trim().max(4_000).nullable().optional(),
|
|
448
|
+
email: z.string().trim().toLowerCase().email().max(320).nullable().optional(),
|
|
449
|
+
userId: z.string().uuid().nullable().optional(),
|
|
450
|
+
seo: archiveSeo.optional(),
|
|
451
|
+
path: archivePath.optional(),
|
|
452
|
+
source: z.string().max(100).optional(),
|
|
453
|
+
}),
|
|
454
|
+
output: authorRow,
|
|
455
|
+
handler: async (input, ctx) => {
|
|
456
|
+
const settings = await loadBlogSettings(ctx.tx);
|
|
457
|
+
const [before] = input.id
|
|
458
|
+
? await ctx.tx.select().from(blogAuthors).where(eq(blogAuthors.id, input.id)).limit(1)
|
|
459
|
+
: [];
|
|
460
|
+
if (input.id && !before) throw new ServiceError("not_found", "That author is gone.");
|
|
461
|
+
if (input.userId) {
|
|
462
|
+
const [account] = await ctx.tx.select({ id: users.id }).from(users).where(eq(users.id, input.userId)).limit(1);
|
|
463
|
+
if (!account) throw new ServiceError("validation", "That account does not exist.");
|
|
464
|
+
}
|
|
465
|
+
const slug = input.slug ?? before?.slug ?? slugFromName(input.name);
|
|
466
|
+
const path = input.path ?? (before ? before.path.replace(/[^/]+$/, slug) : `${settings.authorBase}/${slug}`);
|
|
467
|
+
await assertPathFree(ctx.tx, path, { authorId: before?.id });
|
|
468
|
+
const values = {
|
|
469
|
+
name: input.name,
|
|
470
|
+
slug,
|
|
471
|
+
path,
|
|
472
|
+
bio: input.bio === undefined ? (before?.bio ?? null) : input.bio,
|
|
473
|
+
email: input.email === undefined ? (before?.email ?? null) : input.email,
|
|
474
|
+
userId: input.userId === undefined ? (before?.userId ?? null) : input.userId,
|
|
475
|
+
seo: input.seo ?? (before?.seo as ArchiveSeo | undefined) ?? {},
|
|
476
|
+
source: before?.source ?? input.source ?? "admin",
|
|
477
|
+
};
|
|
478
|
+
let saved: typeof blogAuthors.$inferSelect;
|
|
479
|
+
if (!before) await checkPlaygroundInsert(ctx.tx, ctx.actor, "cms.saveAuthor");
|
|
480
|
+
try {
|
|
481
|
+
[saved] = before
|
|
482
|
+
? ((await ctx.tx.update(blogAuthors).set(values).where(eq(blogAuthors.id, before.id)).returning()) as [typeof saved])
|
|
483
|
+
: ((await ctx.tx.insert(blogAuthors).values(values).returning()) as [typeof saved]);
|
|
484
|
+
} catch (error) {
|
|
485
|
+
if (isUniqueViolation(error)) {
|
|
486
|
+
throw new ServiceError("conflict", "Another author already uses that slug or account.");
|
|
487
|
+
}
|
|
488
|
+
throw error;
|
|
489
|
+
}
|
|
490
|
+
if (before && before.path !== saved.path) await moved(ctx, before.path, saved.path);
|
|
491
|
+
ctx.setSubject("blog_author", saved.id);
|
|
492
|
+
return saved;
|
|
493
|
+
},
|
|
494
|
+
});
|
|
495
|
+
|
|
496
|
+
export const deleteAuthor = defineService({
|
|
497
|
+
name: "cms.deleteAuthor",
|
|
498
|
+
writeClass: "destructive",
|
|
499
|
+
summary: "Delete a blog author profile. Their posts stay, without a byline; the archive redirects to the blog.",
|
|
500
|
+
kind: "mutation",
|
|
501
|
+
permission: "scoped",
|
|
502
|
+
input: z.object({ id: z.string().uuid() }),
|
|
503
|
+
output: okResult,
|
|
504
|
+
handler: async (input, ctx) => {
|
|
505
|
+
const [author] = await ctx.tx.delete(blogAuthors).where(eq(blogAuthors.id, input.id)).returning();
|
|
506
|
+
if (!author) throw new ServiceError("not_found", "That author is gone.");
|
|
507
|
+
await moved(ctx, author.path, "blog");
|
|
508
|
+
ctx.setSubject("blog_author", author.id);
|
|
509
|
+
return { ok: true as const };
|
|
510
|
+
},
|
|
511
|
+
});
|
|
512
|
+
|
|
513
|
+
/* ------------------------------------------------------------ post meta */
|
|
514
|
+
|
|
515
|
+
const postMetaRow = z.object({
|
|
516
|
+
pageId: uuid,
|
|
517
|
+
isPost: z.boolean(),
|
|
518
|
+
authorId: uuid.nullable(),
|
|
519
|
+
categoryIds: z.array(uuid),
|
|
520
|
+
tagIds: z.array(uuid),
|
|
521
|
+
commentsEnabled: z.boolean(),
|
|
522
|
+
sourceModifiedAt: timestamp.nullable(),
|
|
523
|
+
});
|
|
524
|
+
|
|
525
|
+
async function readPostMeta(tx: Tx, pageId: string): Promise<z.infer<typeof postMetaRow>> {
|
|
526
|
+
const [post] = await tx.select().from(blogPosts).where(eq(blogPosts.pageId, pageId)).limit(1);
|
|
527
|
+
if (!post) {
|
|
528
|
+
return { pageId, isPost: false, authorId: null, categoryIds: [], tagIds: [], commentsEnabled: true, sourceModifiedAt: null };
|
|
529
|
+
}
|
|
530
|
+
const terms = await tx
|
|
531
|
+
.select({ id: blogTerms.id, taxonomy: blogTerms.taxonomy })
|
|
532
|
+
.from(blogPostTerms)
|
|
533
|
+
.innerJoin(blogTerms, eq(blogTerms.id, blogPostTerms.termId))
|
|
534
|
+
.where(eq(blogPostTerms.pageId, pageId))
|
|
535
|
+
.orderBy(asc(blogPostTerms.position));
|
|
536
|
+
return {
|
|
537
|
+
pageId,
|
|
538
|
+
isPost: true,
|
|
539
|
+
authorId: post.authorId,
|
|
540
|
+
categoryIds: terms.filter((term) => term.taxonomy === "category").map((term) => term.id),
|
|
541
|
+
tagIds: terms.filter((term) => term.taxonomy === "tag").map((term) => term.id),
|
|
542
|
+
commentsEnabled: post.commentsEnabled,
|
|
543
|
+
sourceModifiedAt: post.sourceModifiedAt,
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
export const getPostMeta = defineService({
|
|
548
|
+
name: "cms.getPostMeta",
|
|
549
|
+
summary: "Whether a page is a blog post, and its author, categories, tags and comment switch.",
|
|
550
|
+
kind: "query",
|
|
551
|
+
permission: "scoped",
|
|
552
|
+
input: z.object({ pageId: z.string().uuid() }),
|
|
553
|
+
output: postMetaRow,
|
|
554
|
+
handler: (input, ctx) => readPostMeta(ctx.tx, input.pageId),
|
|
555
|
+
});
|
|
556
|
+
|
|
557
|
+
export const setPostMeta = defineService({
|
|
558
|
+
name: "cms.setPostMeta",
|
|
559
|
+
summary:
|
|
560
|
+
"Make a page a blog post (or not), and set its author, categories, tags and whether it takes comments. Tags named but not yet created are created.",
|
|
561
|
+
kind: "mutation",
|
|
562
|
+
permission: "scoped",
|
|
563
|
+
writeClass: "blocks",
|
|
564
|
+
input: z.object({
|
|
565
|
+
pageId: z.string().uuid(),
|
|
566
|
+
isPost: z.boolean().default(true),
|
|
567
|
+
authorId: z.string().uuid().nullable().optional(),
|
|
568
|
+
categoryIds: z.array(z.string().uuid()).max(50).optional(),
|
|
569
|
+
tagIds: z.array(z.string().uuid()).max(200).optional(),
|
|
570
|
+
tagNames: z.array(z.string().trim().min(1).max(200)).max(200).optional(),
|
|
571
|
+
commentsEnabled: z.boolean().optional(),
|
|
572
|
+
sourceModifiedAt: z.iso.datetime({ offset: true }).nullable().optional(),
|
|
573
|
+
source: z.string().max(100).optional(),
|
|
574
|
+
}),
|
|
575
|
+
output: postMetaRow,
|
|
576
|
+
handler: async (input, ctx) => {
|
|
577
|
+
const [page] = await ctx.tx.select({ id: pages.id }).from(pages).where(eq(pages.id, input.pageId)).limit(1);
|
|
578
|
+
if (!page) throw new ServiceError("not_found", "That page is gone.");
|
|
579
|
+
if (!input.isPost) {
|
|
580
|
+
await ctx.tx.delete(blogPosts).where(eq(blogPosts.pageId, input.pageId));
|
|
581
|
+
ctx.setSubject("page", input.pageId);
|
|
582
|
+
return readPostMeta(ctx.tx, input.pageId);
|
|
583
|
+
}
|
|
584
|
+
if (input.authorId) {
|
|
585
|
+
const [author] = await ctx.tx.select({ id: blogAuthors.id }).from(blogAuthors).where(eq(blogAuthors.id, input.authorId)).limit(1);
|
|
586
|
+
if (!author) throw new ServiceError("validation", "That author does not exist.");
|
|
587
|
+
}
|
|
588
|
+
const before = await readPostMeta(ctx.tx, input.pageId);
|
|
589
|
+
const values = {
|
|
590
|
+
authorId: input.authorId === undefined ? before.authorId : input.authorId,
|
|
591
|
+
commentsEnabled: input.commentsEnabled ?? before.commentsEnabled,
|
|
592
|
+
sourceModifiedAt:
|
|
593
|
+
input.sourceModifiedAt === undefined
|
|
594
|
+
? before.sourceModifiedAt
|
|
595
|
+
: input.sourceModifiedAt
|
|
596
|
+
? new Date(input.sourceModifiedAt)
|
|
597
|
+
: null,
|
|
598
|
+
};
|
|
599
|
+
await ctx.tx
|
|
600
|
+
.insert(blogPosts)
|
|
601
|
+
.values({ pageId: input.pageId, ...values, source: input.source ?? "admin" })
|
|
602
|
+
.onConflictDoUpdate({ target: blogPosts.pageId, set: { ...values, updatedAt: new Date() } });
|
|
603
|
+
|
|
604
|
+
if (input.categoryIds || input.tagIds || input.tagNames) {
|
|
605
|
+
let tagIds = input.tagIds ?? (input.tagNames ? [] : before.tagIds);
|
|
606
|
+
if (input.tagNames?.length) {
|
|
607
|
+
const settings = await loadBlogSettings(ctx.tx);
|
|
608
|
+
for (const name of input.tagNames) {
|
|
609
|
+
const slug = slugFromName(name);
|
|
610
|
+
const [existing] = await ctx.tx
|
|
611
|
+
.select({ id: blogTerms.id })
|
|
612
|
+
.from(blogTerms)
|
|
613
|
+
.where(and(eq(blogTerms.taxonomy, "tag"), eq(blogTerms.slug, slug)))
|
|
614
|
+
.limit(1);
|
|
615
|
+
if (existing) {
|
|
616
|
+
tagIds = [...tagIds, existing.id];
|
|
617
|
+
continue;
|
|
618
|
+
}
|
|
619
|
+
const path = `${settings.tagBase}/${slug}`;
|
|
620
|
+
await assertPathFree(ctx.tx, path, {});
|
|
621
|
+
await checkPlaygroundInsert(ctx.tx, ctx.actor, "cms.saveTerm");
|
|
622
|
+
const [created] = await ctx.tx
|
|
623
|
+
.insert(blogTerms)
|
|
624
|
+
.values({ taxonomy: "tag", name, slug, path, source: input.source ?? "admin" })
|
|
625
|
+
.returning({ id: blogTerms.id });
|
|
626
|
+
tagIds = [...tagIds, created!.id];
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
const categoryIds = input.categoryIds ?? before.categoryIds;
|
|
630
|
+
const wanted = [...new Set([...categoryIds, ...tagIds])];
|
|
631
|
+
if (wanted.length) {
|
|
632
|
+
const found = await ctx.tx
|
|
633
|
+
.select({ id: blogTerms.id, taxonomy: blogTerms.taxonomy })
|
|
634
|
+
.from(blogTerms)
|
|
635
|
+
.where(inArray(blogTerms.id, wanted));
|
|
636
|
+
const kinds = new Map(found.map((term) => [term.id, term.taxonomy]));
|
|
637
|
+
if (categoryIds.some((id) => kinds.get(id) !== "category") || tagIds.some((id) => kinds.get(id) !== "tag")) {
|
|
638
|
+
throw new ServiceError("validation", "One of those categories or tags does not exist.");
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
await ctx.tx.delete(blogPostTerms).where(eq(blogPostTerms.pageId, input.pageId));
|
|
642
|
+
const ordered = [...new Set([...categoryIds, ...tagIds])];
|
|
643
|
+
if (ordered.length) {
|
|
644
|
+
await ctx.tx
|
|
645
|
+
.insert(blogPostTerms)
|
|
646
|
+
.values(ordered.map((termId, position) => ({ pageId: input.pageId, termId, position })));
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
ctx.setSubject("page", input.pageId);
|
|
650
|
+
ctx.queueEvent("cms.postMetaChanged", { pageId: input.pageId });
|
|
651
|
+
return readPostMeta(ctx.tx, input.pageId);
|
|
652
|
+
},
|
|
653
|
+
});
|
|
654
|
+
|
|
655
|
+
/* ------------------------------------------------------------ public reads */
|
|
656
|
+
|
|
657
|
+
const publicLink = z.object({ name: z.string(), path: z.string() });
|
|
658
|
+
|
|
659
|
+
const publicPostMeta = z
|
|
660
|
+
.object({
|
|
661
|
+
pageId: uuid,
|
|
662
|
+
author: publicLink.extend({ bio: z.string().nullable() }).nullable(),
|
|
663
|
+
categories: z.array(publicLink),
|
|
664
|
+
tags: z.array(publicLink),
|
|
665
|
+
commentsEnabled: z.boolean(),
|
|
666
|
+
publishedAt: timestamp.nullable(),
|
|
667
|
+
modifiedAt: timestamp.nullable(),
|
|
668
|
+
})
|
|
669
|
+
.nullable();
|
|
670
|
+
|
|
671
|
+
/** What a published post shows around its body. Null for anything else. */
|
|
672
|
+
export const postMetaAt = defineService({
|
|
673
|
+
name: "cms.postMetaAt",
|
|
674
|
+
summary: "The byline, categories, tags and dates of a published blog post.",
|
|
675
|
+
kind: "query",
|
|
676
|
+
permission: "public",
|
|
677
|
+
input: z.object({ slug: z.string() }),
|
|
678
|
+
output: publicPostMeta,
|
|
679
|
+
handler: async (input, ctx) => {
|
|
680
|
+
const slug = input.slug.replace(/^\/+|\/+$/g, "");
|
|
681
|
+
const resolved = z.object({ id: uuid }).nullable().parse(await ctx.call(getService("cms.resolvePage"), { slug }));
|
|
682
|
+
if (!resolved) return null;
|
|
683
|
+
const [found] = await ctx.tx
|
|
684
|
+
.select({ page: pages, post: blogPosts })
|
|
685
|
+
.from(pages)
|
|
686
|
+
.innerJoin(blogPosts, eq(blogPosts.pageId, pages.id))
|
|
687
|
+
.where(and(eq(pages.id, resolved.id), eq(pages.slug, slug), eq(pages.status, "published"), isNull(pages.trashedAt)))
|
|
688
|
+
.limit(1);
|
|
689
|
+
if (!found) return null;
|
|
690
|
+
const [author] = found.post.authorId
|
|
691
|
+
? await ctx.tx
|
|
692
|
+
.select({ name: blogAuthors.name, path: blogAuthors.path, bio: blogAuthors.bio })
|
|
693
|
+
.from(blogAuthors)
|
|
694
|
+
.where(eq(blogAuthors.id, found.post.authorId))
|
|
695
|
+
.limit(1)
|
|
696
|
+
: [];
|
|
697
|
+
const terms = await ctx.tx
|
|
698
|
+
.select({ name: blogTerms.name, path: blogTerms.path, taxonomy: blogTerms.taxonomy })
|
|
699
|
+
.from(blogPostTerms)
|
|
700
|
+
.innerJoin(blogTerms, eq(blogTerms.id, blogPostTerms.termId))
|
|
701
|
+
.where(eq(blogPostTerms.pageId, found.page.id))
|
|
702
|
+
.orderBy(asc(blogPostTerms.position));
|
|
703
|
+
return {
|
|
704
|
+
pageId: found.page.id,
|
|
705
|
+
author: author ?? null,
|
|
706
|
+
categories: terms.filter((term) => term.taxonomy === "category").map(({ name, path }) => ({ name, path })),
|
|
707
|
+
tags: terms.filter((term) => term.taxonomy === "tag").map(({ name, path }) => ({ name, path })),
|
|
708
|
+
commentsEnabled: found.post.commentsEnabled,
|
|
709
|
+
publishedAt: found.page.publishedAt,
|
|
710
|
+
modifiedAt: found.post.sourceModifiedAt && found.page.publishedAt && found.post.sourceModifiedAt > found.page.publishedAt
|
|
711
|
+
? found.post.sourceModifiedAt
|
|
712
|
+
: found.page.publishedAt,
|
|
713
|
+
};
|
|
714
|
+
},
|
|
715
|
+
});
|
|
716
|
+
|
|
717
|
+
/** Published post ids under a category (and its subcategories), tag or author. */
|
|
718
|
+
export async function postIdsMatching(
|
|
719
|
+
tx: Tx,
|
|
720
|
+
filter: { category?: string; tag?: string; author?: string },
|
|
721
|
+
): Promise<Set<string> | null> {
|
|
722
|
+
let ids: Set<string> | null = null;
|
|
723
|
+
const intersect = (next: string[]) => {
|
|
724
|
+
ids = ids === null ? new Set(next) : new Set(next.filter((id) => ids!.has(id)));
|
|
725
|
+
};
|
|
726
|
+
if (filter.category) {
|
|
727
|
+
const categories = await allTerms(tx, "category");
|
|
728
|
+
const root = categories.find((term) => term.id === filter.category || term.slug === filter.category);
|
|
729
|
+
if (!root) return new Set();
|
|
730
|
+
const rows = await tx
|
|
731
|
+
.select({ pageId: blogPostTerms.pageId })
|
|
732
|
+
.from(blogPostTerms)
|
|
733
|
+
.where(inArray(blogPostTerms.termId, descendantIds(categories, root.id)));
|
|
734
|
+
intersect(rows.map((one) => one.pageId));
|
|
735
|
+
}
|
|
736
|
+
if (filter.tag) {
|
|
737
|
+
const [tag] = await tx
|
|
738
|
+
.select({ id: blogTerms.id })
|
|
739
|
+
.from(blogTerms)
|
|
740
|
+
.where(and(eq(blogTerms.taxonomy, "tag"), sql`(${blogTerms.slug} = ${filter.tag} or ${blogTerms.id}::text = ${filter.tag})`))
|
|
741
|
+
.limit(1);
|
|
742
|
+
if (!tag) return new Set();
|
|
743
|
+
const rows = await tx.select({ pageId: blogPostTerms.pageId }).from(blogPostTerms).where(eq(blogPostTerms.termId, tag.id));
|
|
744
|
+
intersect(rows.map((one) => one.pageId));
|
|
745
|
+
}
|
|
746
|
+
if (filter.author) {
|
|
747
|
+
const [author] = await tx
|
|
748
|
+
.select({ id: blogAuthors.id })
|
|
749
|
+
.from(blogAuthors)
|
|
750
|
+
.where(sql`(${blogAuthors.slug} = ${filter.author} or ${blogAuthors.id}::text = ${filter.author})`)
|
|
751
|
+
.limit(1);
|
|
752
|
+
if (!author) return new Set();
|
|
753
|
+
const rows = await tx.select({ pageId: blogPosts.pageId }).from(blogPosts).where(eq(blogPosts.authorId, author.id));
|
|
754
|
+
intersect(rows.map((one) => one.pageId));
|
|
755
|
+
}
|
|
756
|
+
return ids;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
const archiveShape = z
|
|
760
|
+
.object({
|
|
761
|
+
kind: z.enum(["category", "tag", "author", "date"]),
|
|
762
|
+
id: z.string(),
|
|
763
|
+
slug: z.string(),
|
|
764
|
+
path: z.string(),
|
|
765
|
+
name: z.string(),
|
|
766
|
+
description: z.string().nullable(),
|
|
767
|
+
seo: z.object({ title: z.string().optional(), description: z.string().optional(), noindex: z.boolean().optional() }),
|
|
768
|
+
/** Ancestors, root first, for a category's breadcrumb. */
|
|
769
|
+
trail: z.array(publicLink),
|
|
770
|
+
posts: z.number().int(),
|
|
771
|
+
updatedAt: timestamp.nullable(),
|
|
772
|
+
})
|
|
773
|
+
.nullable();
|
|
774
|
+
|
|
775
|
+
async function publishedPostDates(ctx: ServiceContext, ids: Set<string> | null): Promise<Array<{ id: string; publishedAt: Date | null }>> {
|
|
776
|
+
if (ids !== null && ids.size === 0) return [];
|
|
777
|
+
const found = await ctx.tx
|
|
778
|
+
.select({ id: pages.id, slug: pages.slug, locale: pages.locale, publishedAt: pages.publishedAt })
|
|
779
|
+
.from(pages)
|
|
780
|
+
.innerJoin(blogPosts, eq(blogPosts.pageId, pages.id))
|
|
781
|
+
.where(
|
|
782
|
+
and(
|
|
783
|
+
eq(pages.status, "published"),
|
|
784
|
+
isNull(pages.trashedAt),
|
|
785
|
+
ids === null ? undefined : inArray(pages.id, [...ids]),
|
|
786
|
+
),
|
|
787
|
+
);
|
|
788
|
+
const visible = [];
|
|
789
|
+
for (const post of found) if (await isPublicPage(ctx, post)) visible.push(post);
|
|
790
|
+
return visible;
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
/** A category, tag or author archive at a path, while it has a published post. */
|
|
794
|
+
export const resolveBlogArchive = defineService({
|
|
795
|
+
name: "cms.resolveBlogArchive",
|
|
796
|
+
summary: "The blog category, tag or author archive at a path, if it has published posts.",
|
|
797
|
+
kind: "query",
|
|
798
|
+
permission: "public",
|
|
799
|
+
input: z.object({ path: z.string() }),
|
|
800
|
+
output: archiveShape,
|
|
801
|
+
handler: async (input, ctx) => {
|
|
802
|
+
const path = input.path.replace(/^\/+|\/+$/g, "").toLowerCase();
|
|
803
|
+
if (!path) return null;
|
|
804
|
+
const date = /^(\d{4})(?:\/(0[1-9]|1[0-2]))?(?:\/(0[1-9]|[12]\d|3[01]))?$/.exec(path);
|
|
805
|
+
if (date) {
|
|
806
|
+
const dated = (await publishedPostDates(ctx, null)).filter(post => post.publishedAt?.toISOString().startsWith(path.replaceAll("/", "-")));
|
|
807
|
+
if (!dated.length) return null;
|
|
808
|
+
return { kind: "date" as const, id: `date:${path}`, slug: path, path, name: path.replaceAll("/", "-"), description: null, seo: {}, trail: [], posts: dated.length, updatedAt: latest(dated) };
|
|
809
|
+
}
|
|
810
|
+
const [term] = await ctx.tx.select().from(blogTerms).where(eq(blogTerms.path, path)).limit(1);
|
|
811
|
+
if (term) {
|
|
812
|
+
const ids = await postIdsMatching(ctx.tx, term.taxonomy === "category" ? { category: term.id } : { tag: term.id });
|
|
813
|
+
const dated = await publishedPostDates(ctx, ids);
|
|
814
|
+
if (dated.length === 0) return null;
|
|
815
|
+
const trail: Array<{ name: string; path: string }> = [];
|
|
816
|
+
if (term.taxonomy === "category") {
|
|
817
|
+
const categories = new Map((await allTerms(ctx.tx, "category")).map((one) => [one.id, one]));
|
|
818
|
+
let cursor = term.parentId ? categories.get(term.parentId) : undefined;
|
|
819
|
+
while (cursor && trail.length < 20) {
|
|
820
|
+
trail.unshift({ name: cursor.name, path: cursor.path });
|
|
821
|
+
cursor = cursor.parentId ? categories.get(cursor.parentId) : undefined;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
return {
|
|
825
|
+
kind: term.taxonomy,
|
|
826
|
+
id: term.id,
|
|
827
|
+
slug: term.slug,
|
|
828
|
+
path: term.path,
|
|
829
|
+
name: term.name,
|
|
830
|
+
description: term.description,
|
|
831
|
+
seo: archiveSeo.parse(term.seo ?? {}),
|
|
832
|
+
trail,
|
|
833
|
+
posts: dated.length,
|
|
834
|
+
updatedAt: latest(dated),
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
const [author] = await ctx.tx.select().from(blogAuthors).where(eq(blogAuthors.path, path)).limit(1);
|
|
838
|
+
if (!author) return null;
|
|
839
|
+
const dated = await publishedPostDates(ctx, await postIdsMatching(ctx.tx, { author: author.id }));
|
|
840
|
+
if (dated.length === 0) return null;
|
|
841
|
+
return {
|
|
842
|
+
kind: "author" as const,
|
|
843
|
+
id: author.id,
|
|
844
|
+
slug: author.slug,
|
|
845
|
+
path: author.path,
|
|
846
|
+
name: author.name,
|
|
847
|
+
description: author.bio,
|
|
848
|
+
seo: archiveSeo.parse(author.seo ?? {}),
|
|
849
|
+
trail: [],
|
|
850
|
+
posts: dated.length,
|
|
851
|
+
updatedAt: latest(dated),
|
|
852
|
+
};
|
|
853
|
+
},
|
|
854
|
+
});
|
|
855
|
+
|
|
856
|
+
function latest(rows: Array<{ publishedAt: Date | null }>): Date | null {
|
|
857
|
+
return rows.reduce<Date | null>((best, one) => (one.publishedAt && (!best || one.publishedAt > best) ? one.publishedAt : best), null);
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
/**
|
|
861
|
+
* Archives for the sitemap (§5): only the ones with a published post, and not
|
|
862
|
+
* the ones an owner (or the imported site) marked noindex.
|
|
863
|
+
*/
|
|
864
|
+
export const blogArchivePaths = defineService({
|
|
865
|
+
name: "cms.blogArchivePaths",
|
|
866
|
+
summary: "Every blog category, tag and author archive that has a published post, for the sitemap.",
|
|
867
|
+
kind: "query",
|
|
868
|
+
permission: "public",
|
|
869
|
+
input: z.object({ locale: z.string().default("en") }),
|
|
870
|
+
output: listed(
|
|
871
|
+
z.object({
|
|
872
|
+
slug: z.string(),
|
|
873
|
+
title: z.string(),
|
|
874
|
+
description: z.string().optional(),
|
|
875
|
+
kind: z.string(),
|
|
876
|
+
priority: z.number(),
|
|
877
|
+
updatedAt: timestamp.optional(),
|
|
878
|
+
}),
|
|
879
|
+
),
|
|
880
|
+
handler: async (input, ctx) => {
|
|
881
|
+
// Archives are listed once, in the site's own language: their names and
|
|
882
|
+
// descriptions are not translated, so a /fr/ copy would be a duplicate.
|
|
883
|
+
const [business] = await ctx.tx.select({ defaultLocale: businessProfile.defaultLocale }).from(businessProfile).limit(1);
|
|
884
|
+
if (business && input.locale !== business.defaultLocale) return [];
|
|
885
|
+
const out: Array<{ slug: string; title: string; description?: string; kind: string; priority: number; updatedAt?: Date }> = [];
|
|
886
|
+
for (const term of await allTerms(ctx.tx)) {
|
|
887
|
+
if (archiveSeo.parse(term.seo ?? {}).noindex) continue;
|
|
888
|
+
const ids = await postIdsMatching(ctx.tx, term.taxonomy === "category" ? { category: term.id } : { tag: term.id });
|
|
889
|
+
const dated = await publishedPostDates(ctx, ids);
|
|
890
|
+
if (dated.length === 0) continue;
|
|
891
|
+
out.push({
|
|
892
|
+
slug: term.path,
|
|
893
|
+
title: term.name,
|
|
894
|
+
description: term.description ?? undefined,
|
|
895
|
+
kind: "collection",
|
|
896
|
+
priority: term.taxonomy === "category" ? 0.5 : 0.3,
|
|
897
|
+
updatedAt: latest(dated) ?? undefined,
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
for (const author of await ctx.tx.select().from(blogAuthors)) {
|
|
901
|
+
if (archiveSeo.parse(author.seo ?? {}).noindex) continue;
|
|
902
|
+
const dated = await publishedPostDates(ctx, await postIdsMatching(ctx.tx, { author: author.id }));
|
|
903
|
+
if (dated.length === 0) continue;
|
|
904
|
+
out.push({
|
|
905
|
+
slug: author.path,
|
|
906
|
+
title: author.name,
|
|
907
|
+
description: author.bio ?? undefined,
|
|
908
|
+
kind: "collection",
|
|
909
|
+
priority: 0.3,
|
|
910
|
+
updatedAt: latest(dated) ?? undefined,
|
|
911
|
+
});
|
|
912
|
+
}
|
|
913
|
+
return out;
|
|
914
|
+
},
|
|
915
|
+
});
|
|
916
|
+
|
|
917
|
+
export const listPostPages = defineService({
|
|
918
|
+
name: "cms.listPostPages",
|
|
919
|
+
summary: "Blog posts for the owner, including drafts and imported posts at their original addresses.",
|
|
920
|
+
kind: "query",
|
|
921
|
+
permission: "scoped",
|
|
922
|
+
input: z.object({}),
|
|
923
|
+
output: listed(z.object({ id: uuid, title: z.string(), slug: z.string(), status: z.string() })),
|
|
924
|
+
handler: (_input, ctx) => ctx.tx.select({ id: pages.id, title: pages.title, slug: pages.slug, status: pages.status })
|
|
925
|
+
.from(pages).leftJoin(blogPosts, eq(blogPosts.pageId, pages.id))
|
|
926
|
+
.where(and(isNull(pages.trashedAt), or(isNotNull(blogPosts.pageId), like(pages.slug, "blog/%"))))
|
|
927
|
+
.orderBy(desc(pages.createdAt)),
|
|
928
|
+
});
|
|
929
|
+
|
|
930
|
+
export const createPost = defineService({
|
|
931
|
+
name: "cms.createPost",
|
|
932
|
+
summary: "Create a draft blog post and its post metadata atomically.",
|
|
933
|
+
kind: "mutation",
|
|
934
|
+
permission: "scoped",
|
|
935
|
+
writeClass: "blocks",
|
|
936
|
+
input: z.object({ title: z.string().trim().min(1).max(200), slug: slugPart, locale: z.string().default("en") }),
|
|
937
|
+
output: z.object({ id: uuid }),
|
|
938
|
+
handler: async (input, ctx) => {
|
|
939
|
+
const page = z.object({ id: uuid }).parse(await ctx.call(getService("cms.createPage"), {
|
|
940
|
+
title: input.title, slug: `blog/${input.slug}`, locale: input.locale,
|
|
941
|
+
blocks: [{ id: "post-title", type: "heading", props: { text: input.title, level: 1 } }, { id: "post-body", type: "text", props: { body: "" } }],
|
|
942
|
+
}));
|
|
943
|
+
const [author] = ctx.actor.kind === "user"
|
|
944
|
+
? await ctx.tx.select({ id: blogAuthors.id }).from(blogAuthors).where(eq(blogAuthors.userId, ctx.actor.userId)).limit(1)
|
|
945
|
+
: [];
|
|
946
|
+
await ctx.call(setPostMeta, { pageId: page.id, isPost: true, authorId: author?.id ?? null });
|
|
947
|
+
ctx.setSubject("page", page.id);
|
|
948
|
+
return { id: page.id };
|
|
949
|
+
},
|
|
950
|
+
});
|
|
951
|
+
|
|
952
|
+
export const authorAccounts = defineService({
|
|
953
|
+
name: "cms.authorAccounts", summary: "Owner and staff accounts available to link to a blog author; this is a private administration directory.",
|
|
954
|
+
kind: "query", permission: "scoped", input: z.object({}), output: listed(z.object({ id: uuid, email: z.string() })),
|
|
955
|
+
handler: (_input, ctx) => ctx.tx.select({ id: users.id, email: users.email }).from(users).where(inArray(users.role, ["owner", "staff"])).orderBy(asc(users.email)),
|
|
956
|
+
});
|
|
957
|
+
|
|
958
|
+
export const rollbackImportedBlogProfiles = defineService({
|
|
959
|
+
name: "cms.rollbackImportedBlogProfiles",
|
|
960
|
+
summary: "Remove unused blog profiles created by one rolled-back import; profiles used by other posts are retained.",
|
|
961
|
+
kind: "mutation", permission: "scoped", writeClass: "destructive",
|
|
962
|
+
input: z.object({ runId: uuid }), output: okResult,
|
|
963
|
+
handler: async (input, ctx) => {
|
|
964
|
+
const source = `import:${input.runId}`;
|
|
965
|
+
const terms = await allTerms(ctx.tx);
|
|
966
|
+
const referenced = new Set((await ctx.tx.select({ id: blogPostTerms.termId }).from(blogPostTerms)).map(row => row.id));
|
|
967
|
+
const retained = new Set(terms.filter(term => term.source !== source || referenced.has(term.id)).map(term => term.id));
|
|
968
|
+
const byId = new Map(terms.map(term => [term.id, term]));
|
|
969
|
+
for (const id of [...retained]) {
|
|
970
|
+
let parent = byId.get(id)?.parentId;
|
|
971
|
+
while (parent && !retained.has(parent)) { retained.add(parent); parent = byId.get(parent)?.parentId; }
|
|
972
|
+
}
|
|
973
|
+
await ctx.tx.delete(blogTerms).where(and(eq(blogTerms.source, source), retained.size ? notInArray(blogTerms.id, [...retained]) : undefined));
|
|
974
|
+
await ctx.tx.delete(blogAuthors).where(and(eq(blogAuthors.source, source), sql`not exists (select 1 from ${blogPosts} where ${blogPosts.authorId} = ${blogAuthors.id})`));
|
|
975
|
+
ctx.setSubject("import_run", input.runId);
|
|
976
|
+
return { ok: true as const };
|
|
977
|
+
},
|
|
978
|
+
});
|
|
979
|
+
|
|
980
|
+
export default [
|
|
981
|
+
authorAccounts,
|
|
982
|
+
publicBlogCategories,
|
|
983
|
+
listPostPages,
|
|
984
|
+
createPost,
|
|
985
|
+
rollbackImportedBlogProfiles,
|
|
986
|
+
getBlogSettings,
|
|
987
|
+
updateBlogSettings,
|
|
988
|
+
listTerms,
|
|
989
|
+
saveTerm,
|
|
990
|
+
deleteTerm,
|
|
991
|
+
listAuthors,
|
|
992
|
+
saveAuthor,
|
|
993
|
+
deleteAuthor,
|
|
994
|
+
getPostMeta,
|
|
995
|
+
setPostMeta,
|
|
996
|
+
postMetaAt,
|
|
997
|
+
resolveBlogArchive,
|
|
998
|
+
blogArchivePaths,
|
|
999
|
+
];
|