@bieberkit/plugin-pages 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1571 @@
1
+ import { definePlugin } from "@bieberkit/core";
2
+ import { defineEntity, f } from "@bieberkit/data";
3
+ import { ContentError, contentFieldOptions } from "@bieberkit/content";
4
+ import { HttpError, SITE_SITEMAP_TAG, defineFragment, defineRoute, purgeSite } from "@bieberkit/http";
5
+ import { DEFAULT_TENANT, expectVersion, recordAudit, runInTransaction, runInUnitOfWork } from "@bieberkit/data/orm";
6
+ import { previewToken, readPreviewToken, slugify, uniqueSlug } from "@bieberkit/site-kit";
7
+ // package.json
8
+ var version = "0.6.0";
9
+ // src/entities/publication.ts
10
+ /**
11
+ * BieberKit
12
+ *
13
+ * @file plugins/pages/src/entities/publication.ts
14
+ * @description Defines an editorial identity shared by its published locales.
15
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
16
+ * @copyright Copyright (c) 2026 Bieber Kieu
17
+ * @license Apache-2.0
18
+ *
19
+ * Licensed under the Apache License, Version 2.0 (the "License");
20
+ * you may not use this file except in compliance with the License.
21
+ * You may obtain a copy of the License at
22
+ *
23
+ * http://www.apache.org/licenses/LICENSE-2.0
24
+ *
25
+ * Unless required by applicable law or agreed to in writing, software
26
+ * distributed under the License is distributed on an "AS IS" BASIS,
27
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
28
+ * See the License for the specific language governing permissions and
29
+ * limitations under the License.
30
+ *
31
+ * SPDX-License-Identifier: Apache-2.0
32
+ */
33
+ const Publication = defineEntity({
34
+ name: "pages.Publication",
35
+ table: "bk_site_publications",
36
+ fields: {
37
+ id: f.id(),
38
+ kind: f.oneOf(["page", "article"]),
39
+ createdAt: f.createdAt()
40
+ }
41
+ });
42
+ // src/entities/translation.ts
43
+ /**
44
+ * BieberKit
45
+ *
46
+ * @file plugins/pages/src/entities/translation.ts
47
+ * @description Stores locale-specific draft and published page snapshots.
48
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
49
+ * @copyright Copyright (c) 2026 Bieber Kieu
50
+ * @license Apache-2.0
51
+ *
52
+ * Licensed under the Apache License, Version 2.0 (the "License");
53
+ * you may not use this file except in compliance with the License.
54
+ * You may obtain a copy of the License at
55
+ *
56
+ * http://www.apache.org/licenses/LICENSE-2.0
57
+ *
58
+ * Unless required by applicable law or agreed to in writing, software
59
+ * distributed under the License is distributed on an "AS IS" BASIS,
60
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
61
+ * See the License for the specific language governing permissions and
62
+ * limitations under the License.
63
+ *
64
+ * SPDX-License-Identifier: Apache-2.0
65
+ */
66
+ const Translation = defineEntity({
67
+ name: "pages.Translation",
68
+ table: "bk_site_publication_locales",
69
+ fields: {
70
+ id: f.id(),
71
+ publication: f.belongsTo(() => Publication),
72
+ locale: f.string({
73
+ min: 1,
74
+ max: 32
75
+ }),
76
+ draftTitle: f.string({
77
+ min: 1,
78
+ max: 240
79
+ }),
80
+ draftSlug: f.string({
81
+ min: 1,
82
+ max: 80
83
+ }),
84
+ draftExcerpt: f.text({ max: 1e3 }).optional(),
85
+ draftDocument: f.custom(contentFieldOptions()),
86
+ publishedTitle: f.string({
87
+ min: 1,
88
+ max: 240
89
+ }).optional(),
90
+ publishedSlug: f.string({
91
+ min: 1,
92
+ max: 120
93
+ }).optional(),
94
+ publishedExcerpt: f.text({ max: 1e3 }).optional(),
95
+ publishedDocument: f.custom(contentFieldOptions()).optional(),
96
+ firstPublishedAt: f.dateTime().optional(),
97
+ publishedAt: f.dateTime().optional(),
98
+ updatedAt: f.updatedAt()
99
+ },
100
+ orm: { uniques: [{
101
+ properties: ["publication", "locale"],
102
+ name: "bk_site_pub_locale_uq"
103
+ }, {
104
+ properties: ["locale", "publishedSlug"],
105
+ name: "bk_site_pub_slug_uq"
106
+ }] }
107
+ });
108
+ // src/entities/public-comment.ts
109
+ /**
110
+ * BieberKit
111
+ *
112
+ * @file plugins/pages/src/entities/public-comment.ts
113
+ * @description Stores text explicitly approved for the public article comment feed.
114
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
115
+ * @copyright Copyright (c) 2026 Bieber Kieu
116
+ * @license Apache-2.0
117
+ *
118
+ * Licensed under the Apache License, Version 2.0 (the "License");
119
+ * you may not use this file except in compliance with the License.
120
+ * You may obtain a copy of the License at
121
+ *
122
+ * http://www.apache.org/licenses/LICENSE-2.0
123
+ *
124
+ * Unless required by applicable law or agreed to in writing, software
125
+ * distributed under the License is distributed on an "AS IS" BASIS,
126
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
127
+ * See the License for the specific language governing permissions and
128
+ * limitations under the License.
129
+ *
130
+ * SPDX-License-Identifier: Apache-2.0
131
+ */
132
+ const PublicComment = defineEntity({
133
+ name: "pages.PublicComment",
134
+ table: "bk_site_public_comments",
135
+ fields: {
136
+ id: f.id(),
137
+ translation: f.belongsTo(() => Translation).index(),
138
+ name: f.string({
139
+ min: 1,
140
+ max: 80
141
+ }).optional(),
142
+ body: f.text({ max: 2e3 }),
143
+ createdAt: f.createdAt()
144
+ }
145
+ });
146
+ // src/services/publication.ts
147
+ /**
148
+ * BieberKit
149
+ *
150
+ * @file plugins/pages/src/services/publication.ts
151
+ * @description Saves and publishes locale-specific content and canonical paths.
152
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
153
+ * @copyright Copyright (c) 2026 Bieber Kieu
154
+ * @license Apache-2.0
155
+ *
156
+ * Licensed under the Apache License, Version 2.0 (the "License");
157
+ * you may not use this file except in compliance with the License.
158
+ * You may obtain a copy of the License at
159
+ *
160
+ * http://www.apache.org/licenses/LICENSE-2.0
161
+ *
162
+ * Unless required by applicable law or agreed to in writing, software
163
+ * distributed under the License is distributed on an "AS IS" BASIS,
164
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
165
+ * See the License for the specific language governing permissions and
166
+ * limitations under the License.
167
+ *
168
+ * SPDX-License-Identifier: Apache-2.0
169
+ */
170
+ const PAGES_TAG = "pages:content";
171
+ const publicationOf = (em) => em.getMetadata().getByClassName(Publication.name).class;
172
+ const translationsOf = (em) => em.getMetadata().getByClassName(Translation.name).class;
173
+ const property = (row, key) => typeof row === "object" && row !== null ? Reflect.get(row, key) : void 0;
174
+ const textOf = (value) => typeof value === "string" ? value : void 0;
175
+ const publishedPath = (locale, slug) => "/" + locale + "/" + (slug === "home" ? "" : encodeURIComponent(slug));
176
+ function localeOf(value) {
177
+ if (typeof value !== "string" || value.length > 32) return void 0;
178
+ try {
179
+ const [locale] = Intl.getCanonicalLocales(value);
180
+ return locale;
181
+ } catch {
182
+ return;
183
+ }
184
+ }
185
+ function invalid$1(message) {
186
+ throw new HttpError("PUBLICATION_INVALID", 400, message, "Check the locale, title, slug and content.");
187
+ }
188
+ function absent$1() {
189
+ throw new HttpError("PUBLICATION_NOT_FOUND", 404, "There is no publication here.", "Check the publication and locale.");
190
+ }
191
+ function readDocument(content, input) {
192
+ try {
193
+ return content.parse(input);
194
+ } catch (error) {
195
+ if (error instanceof ContentError) return invalid$1("Enter a valid block content document.");
196
+ throw error;
197
+ }
198
+ }
199
+ function draftOf(content, input) {
200
+ const title = textOf(property(input, "title"))?.trim();
201
+ if (title === void 0 || title === "" || title.length > 240) return invalid$1("Enter a title.");
202
+ const wanted = textOf(property(input, "slug"));
203
+ const slug = slugify(wanted ?? title);
204
+ if (slug === "") return invalid$1("Enter a slug with a letter or number.");
205
+ const excerpt = textOf(property(input, "excerpt"))?.trim();
206
+ return {
207
+ title,
208
+ slug,
209
+ document: readDocument(content, property(input, "document")),
210
+ ...excerpt === void 0 || excerpt === "" ? {} : { excerpt }
211
+ };
212
+ }
213
+ async function createPublication(db, kind) {
214
+ if (kind !== "page" && kind !== "article") return invalid$1("Choose page or article.");
215
+ return runInTransaction(db, async (em) => {
216
+ const record = em.create(publicationOf(em), { kind });
217
+ await em.flush();
218
+ const id = textOf(property(record, "id"));
219
+ if (id === void 0) throw new HttpError("PUBLICATION_ID", 500, "The publication has no identifier.", "Try again.");
220
+ return { id };
221
+ });
222
+ }
223
+ async function listPublications(db, page) {
224
+ return runInUnitOfWork(db, async (em) => {
225
+ const [rows, total] = await em.findAndCount(publicationOf(em), {}, {
226
+ orderBy: {
227
+ createdAt: "desc",
228
+ id: "desc"
229
+ },
230
+ offset: (page - 1) * 50,
231
+ limit: 50
232
+ });
233
+ return {
234
+ data: await summarizePublications(em, rows),
235
+ total
236
+ };
237
+ });
238
+ }
239
+ async function summarizePublications(em, rows) {
240
+ const base = rows.flatMap((row) => {
241
+ const id = textOf(property(row, "id"));
242
+ const kind = property(row, "kind");
243
+ return id === void 0 || kind !== "page" && kind !== "article" ? [] : [{
244
+ id,
245
+ kind
246
+ }];
247
+ });
248
+ const translations = await em.find(translationsOf(em), { publication: { $in: base.map(({ id }) => id) } }, { orderBy: {
249
+ updatedAt: "desc",
250
+ id: "desc"
251
+ } });
252
+ const titles = /* @__PURE__ */ new Map();
253
+ for (const row of translations) {
254
+ const publication = property(row, "publication");
255
+ const id = textOf(publication) ?? textOf(property(publication, "id"));
256
+ const title = textOf(property(row, "draftTitle"));
257
+ if (id !== void 0 && title !== void 0 && !titles.has(id)) titles.set(id, title);
258
+ }
259
+ return base.map((row) => {
260
+ const title = titles.get(row.id);
261
+ return title === void 0 ? row : {
262
+ ...row,
263
+ title
264
+ };
265
+ });
266
+ }
267
+ async function saveDraft(db, id, language, value, content) {
268
+ const locale = localeOf(language);
269
+ if (locale === void 0) return invalid$1("Enter a supported language tag.");
270
+ const draft = draftOf(content, value);
271
+ return runInTransaction(db, async (em) => {
272
+ const publication = await em.findOne(publicationOf(em), { id });
273
+ if (typeof publication !== "object" || publication === null) return absent$1();
274
+ const entity = translationsOf(em);
275
+ const existing = await em.findOne(entity, {
276
+ publication: id,
277
+ locale
278
+ });
279
+ const fields = {
280
+ draftTitle: draft.title,
281
+ draftSlug: draft.slug,
282
+ draftExcerpt: draft.excerpt ?? null,
283
+ draftDocument: draft.document
284
+ };
285
+ if (typeof existing === "object" && existing !== null) for (const [key, field] of Object.entries(fields)) Reflect.set(existing, key, field);
286
+ else em.create(entity, {
287
+ publication,
288
+ locale,
289
+ ...fields
290
+ });
291
+ await em.flush();
292
+ return draft;
293
+ });
294
+ }
295
+ async function readDraft(db, id, language, content) {
296
+ const locale = localeOf(language);
297
+ if (locale === void 0) return invalid$1("Enter a supported language tag.");
298
+ return runInUnitOfWork(db, async (em) => {
299
+ const row = await em.findOne(translationsOf(em), {
300
+ publication: id,
301
+ locale
302
+ });
303
+ if (row == null) return absent$1();
304
+ return storedDraft(content, row);
305
+ });
306
+ }
307
+ function storedDraft(content, row) {
308
+ const excerpt = textOf(property(row, "draftExcerpt"));
309
+ return {
310
+ title: textOf(property(row, "draftTitle")) ?? absent$1(),
311
+ slug: textOf(property(row, "draftSlug")) ?? absent$1(),
312
+ document: readDocument(content, property(row, "draftDocument")),
313
+ ...excerpt === void 0 ? {} : { excerpt }
314
+ };
315
+ }
316
+ async function freeSlug(em, redirects, locale, proposed, old) {
317
+ const rows = await em.find(translationsOf(em), {
318
+ locale,
319
+ publishedSlug: { $like: proposed + "%" }
320
+ });
321
+ const taken = new Set(rows.flatMap((row) => {
322
+ const slug = textOf(property(row, "publishedSlug"));
323
+ return slug === void 0 || slug === old ? [] : [slug];
324
+ }));
325
+ let slug = uniqueSlug(proposed, taken);
326
+ while (slug !== old && await redirects.isReserved(publishedPath(locale, slug))) {
327
+ taken.add(slug);
328
+ slug = uniqueSlug(proposed, taken);
329
+ }
330
+ return slug;
331
+ }
332
+ async function publishDraft(db, redirects, id, language, content) {
333
+ const locale = localeOf(language);
334
+ if (locale === void 0) return invalid$1("Enter a supported language tag.");
335
+ return runInTransaction(db, async (em) => {
336
+ const row = await em.findOne(translationsOf(em), {
337
+ publication: id,
338
+ locale
339
+ });
340
+ if (typeof row !== "object" || row === null) return absent$1();
341
+ const draft = storedDraft(content, row);
342
+ const old = textOf(property(row, "publishedSlug"));
343
+ const slug = await freeSlug(em, redirects, locale, draft.slug, old);
344
+ const now = /* @__PURE__ */ new Date();
345
+ const snapshot = {
346
+ publishedTitle: draft.title,
347
+ publishedSlug: slug,
348
+ publishedExcerpt: draft.excerpt ?? null,
349
+ publishedDocument: draft.document,
350
+ publishedAt: now,
351
+ firstPublishedAt: property(row, "firstPublishedAt") ?? now
352
+ };
353
+ for (const [key, field] of Object.entries(snapshot)) Reflect.set(row, key, field);
354
+ if (old !== void 0 && old !== slug) await redirects.recordMove(publishedPath(locale, old), publishedPath(locale, slug));
355
+ purgeSite(em, [PAGES_TAG, SITE_SITEMAP_TAG]);
356
+ await em.flush();
357
+ return { slug };
358
+ });
359
+ }
360
+ /** Installs a starter publication without overwriting a draft, published page or reserved path. */
361
+ async function seedPublication(services, input) {
362
+ const locale = localeOf(input.locale);
363
+ if (locale === void 0) return invalid$1("Enter a supported language tag.");
364
+ const draft = draftOf(services.content, input);
365
+ await runInTransaction(services.database, async (em) => {
366
+ const translations = translationsOf(em);
367
+ if (await em.findOne(translations, {
368
+ locale,
369
+ $or: [{ publishedSlug: draft.slug }, { draftSlug: draft.slug }]
370
+ }) != null || await services.publicationRedirects.isReserved(publishedPath(locale, draft.slug))) return;
371
+ const publication = em.create(publicationOf(em), { kind: input.kind });
372
+ const now = /* @__PURE__ */ new Date();
373
+ em.create(translations, {
374
+ publication,
375
+ locale,
376
+ draftTitle: draft.title,
377
+ draftSlug: draft.slug,
378
+ draftExcerpt: draft.excerpt ?? null,
379
+ draftDocument: draft.document,
380
+ publishedTitle: draft.title,
381
+ publishedSlug: draft.slug,
382
+ publishedExcerpt: draft.excerpt ?? null,
383
+ publishedDocument: draft.document,
384
+ publishedAt: now,
385
+ firstPublishedAt: now
386
+ });
387
+ purgeSite(em, [PAGES_TAG, SITE_SITEMAP_TAG]);
388
+ await em.flush();
389
+ });
390
+ }
391
+ // src/services/preview.ts
392
+ /**
393
+ * BieberKit
394
+ *
395
+ * @file plugins/pages/src/services/preview.ts
396
+ * @description Issues and reads short-lived signed publication previews.
397
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
398
+ * @copyright Copyright (c) 2026 Bieber Kieu
399
+ * @license Apache-2.0
400
+ *
401
+ * Licensed under the Apache License, Version 2.0 (the "License");
402
+ * you may not use this file except in compliance with the License.
403
+ * You may obtain a copy of the License at
404
+ *
405
+ * http://www.apache.org/licenses/LICENSE-2.0
406
+ *
407
+ * Unless required by applicable law or agreed to in writing, software
408
+ * distributed under the License is distributed on an "AS IS" BASIS,
409
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
410
+ * See the License for the specific language governing permissions and
411
+ * limitations under the License.
412
+ *
413
+ * SPDX-License-Identifier: Apache-2.0
414
+ */
415
+ function unavailable() {
416
+ throw new HttpError("PUBLICATION_PREVIEW_NOT_FOUND", 404, "The preview is unavailable or expired.", "Open a new preview from the admin.");
417
+ }
418
+ async function issuePreview(db, config, id, language, content) {
419
+ const origin = config.SITE_URL;
420
+ const secret = config.SITE_REVALIDATE_SECRET;
421
+ if (origin === void 0 || secret === void 0) throw new HttpError("PUBLICATION_PREVIEW_CONFIG", 503, "Draft preview is not configured.", "Configure the public site URL and signing key.");
422
+ const locale = localeOf(language);
423
+ if (locale === void 0) return unavailable();
424
+ await readDraft(db, id, locale, content);
425
+ const token = await previewToken({
426
+ secret,
427
+ subject: {
428
+ entity: Publication.name,
429
+ id,
430
+ locale
431
+ }
432
+ });
433
+ const url = new URL("/preview", origin);
434
+ url.searchParams.set("token", token);
435
+ return url.href;
436
+ }
437
+ async function readPreview(db, secret, token, content) {
438
+ if (secret === void 0 || typeof token !== "string") return unavailable();
439
+ const subject = await readPreviewToken({
440
+ secret,
441
+ token
442
+ });
443
+ if (subject?.entity !== Publication.name || subject.locale === void 0) return unavailable();
444
+ return {
445
+ ...await readDraft(db, subject.id, subject.locale, content),
446
+ locale: subject.locale
447
+ };
448
+ }
449
+ // src/routes/shared.ts
450
+ /**
451
+ * BieberKit
452
+ *
453
+ * @file plugins/pages/src/routes/shared.ts
454
+ * @description Applies the public site administration scope to editorial routes.
455
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
456
+ * @copyright Copyright (c) 2026 Bieber Kieu
457
+ * @license Apache-2.0
458
+ *
459
+ * Licensed under the Apache License, Version 2.0 (the "License");
460
+ * you may not use this file except in compliance with the License.
461
+ * You may obtain a copy of the License at
462
+ *
463
+ * http://www.apache.org/licenses/LICENSE-2.0
464
+ *
465
+ * Unless required by applicable law or agreed to in writing, software
466
+ * distributed under the License is distributed on an "AS IS" BASIS,
467
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
468
+ * See the License for the specific language governing permissions and
469
+ * limitations under the License.
470
+ *
471
+ * SPDX-License-Identifier: Apache-2.0
472
+ */
473
+ function siteScope(ctx) {
474
+ if (ctx.tenantId !== void 0 && ctx.tenantId !== DEFAULT_TENANT) throw new HttpError("PUBLICATION_SCOPE", 403, "Publications belong to the whole public site.", "Manage publications outside a tenant.");
475
+ ctx.header("cache-control", "private, no-store");
476
+ }
477
+ // src/services/sections.ts
478
+ /**
479
+ * BieberKit
480
+ *
481
+ * @file plugins/pages/src/services/sections.ts
482
+ * @description Loads related articles and manages the public comment feed.
483
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
484
+ * @copyright Copyright (c) 2026 Bieber Kieu
485
+ * @license Apache-2.0
486
+ *
487
+ * Licensed under the Apache License, Version 2.0 (the "License");
488
+ * you may not use this file except in compliance with the License.
489
+ * You may obtain a copy of the License at
490
+ *
491
+ * http://www.apache.org/licenses/LICENSE-2.0
492
+ *
493
+ * Unless required by applicable law or agreed to in writing, software
494
+ * distributed under the License is distributed on an "AS IS" BASIS,
495
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
496
+ * See the License for the specific language governing permissions and
497
+ * limitations under the License.
498
+ *
499
+ * SPDX-License-Identifier: Apache-2.0
500
+ */
501
+ const commentsOf = (em) => em.getMetadata().getByClassName(PublicComment.name).class;
502
+ function absent() {
503
+ throw new HttpError("ARTICLE_NOT_PUBLISHED", 404, "There is no published article at this locale.", "Open a published article.");
504
+ }
505
+ function languageOf(value) {
506
+ return localeOf(value) ?? absent();
507
+ }
508
+ async function articleId(em, where) {
509
+ const { locale, publication, publishedSlug } = where;
510
+ const row = await em.findOne(translationsOf(em), {
511
+ locale,
512
+ publishedSlug: publishedSlug ?? { $ne: null },
513
+ publication: {
514
+ kind: "article",
515
+ ...publication === void 0 ? {} : { id: publication }
516
+ }
517
+ });
518
+ return textOf(property(row, "id")) ?? absent();
519
+ }
520
+ function readComment(row) {
521
+ const id = textOf(property(row, "id"));
522
+ const name = textOf(property(row, "name"));
523
+ const body = textOf(property(row, "body"));
524
+ const at = property(row, "createdAt");
525
+ if (id === void 0 || body === void 0 || !(at instanceof Date)) return void 0;
526
+ return {
527
+ id,
528
+ body,
529
+ createdAt: at.toISOString(),
530
+ ...name === void 0 ? {} : { name }
531
+ };
532
+ }
533
+ async function commentList(em, translation) {
534
+ return (await em.find(commentsOf(em), { translation }, {
535
+ orderBy: {
536
+ createdAt: "desc",
537
+ id: "desc"
538
+ },
539
+ limit: 50
540
+ })).map(readComment).filter((item) => item !== void 0);
541
+ }
542
+ async function readArticleSection(db, slug, language, kind) {
543
+ const locale = languageOf(language);
544
+ return runInUnitOfWork(db, async (em) => {
545
+ const id = await articleId(em, {
546
+ locale,
547
+ publishedSlug: slug
548
+ });
549
+ if (kind === "comments") return (await commentList(em, id)).map(({ id: _id, ...comment }) => comment);
550
+ return (await em.find(translationsOf(em), {
551
+ id: { $ne: id },
552
+ locale,
553
+ publishedSlug: { $ne: null },
554
+ publication: { kind: "article" }
555
+ }, {
556
+ orderBy: {
557
+ publishedAt: "desc",
558
+ id: "desc"
559
+ },
560
+ limit: 3
561
+ })).flatMap((row) => {
562
+ const title = textOf(property(row, "publishedTitle"));
563
+ const address = textOf(property(row, "publishedSlug"));
564
+ return title === void 0 || address === void 0 ? [] : [{
565
+ title,
566
+ path: publishedPath(locale, address)
567
+ }];
568
+ });
569
+ });
570
+ }
571
+ async function listPublicComments(db, publication, language) {
572
+ const locale = languageOf(language);
573
+ return runInUnitOfWork(db, async (em) => commentList(em, await articleId(em, {
574
+ locale,
575
+ publication
576
+ })));
577
+ }
578
+ async function addPublicComment(db, publication, language, input) {
579
+ const locale = languageOf(language);
580
+ const body = textOf(property(input, "body"))?.trim();
581
+ const name = textOf(property(input, "name"))?.trim();
582
+ if (body === void 0 || body === "" || body.length > 2e3 || name !== void 0 && name.length > 80) throw new HttpError("PUBLIC_COMMENT_INVALID", 400, "The public comment is invalid.", "Enter text and an optional name.");
583
+ return runInTransaction(db, async (em) => {
584
+ const translation = await articleId(em, {
585
+ locale,
586
+ publication
587
+ });
588
+ const row = em.create(commentsOf(em), {
589
+ translation,
590
+ body,
591
+ ...name ? { name } : {}
592
+ });
593
+ purgeSite(em, [PAGES_TAG]);
594
+ await em.flush();
595
+ const id = textOf(property(row, "id"));
596
+ if (id === void 0) throw new HttpError("PUBLIC_COMMENT_ID", 500, "The comment has no identifier.", "Try again.");
597
+ return { id };
598
+ });
599
+ }
600
+ async function removePublicComment(db, publication, language, comment) {
601
+ const locale = languageOf(language);
602
+ await runInTransaction(db, async (em) => {
603
+ const translation = await articleId(em, {
604
+ locale,
605
+ publication
606
+ });
607
+ if (await em.nativeDelete(commentsOf(em), {
608
+ id: comment,
609
+ translation
610
+ }) > 0) {
611
+ purgeSite(em, [PAGES_TAG]);
612
+ await em.flush();
613
+ }
614
+ });
615
+ }
616
+ // src/routes/sections.ts
617
+ /**
618
+ * BieberKit
619
+ *
620
+ * @file plugins/pages/src/routes/sections.ts
621
+ * @description Declares the public and editorial routes for article sections.
622
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
623
+ * @copyright Copyright (c) 2026 Bieber Kieu
624
+ * @license Apache-2.0
625
+ *
626
+ * Licensed under the Apache License, Version 2.0 (the "License");
627
+ * you may not use this file except in compliance with the License.
628
+ * You may obtain a copy of the License at
629
+ *
630
+ * http://www.apache.org/licenses/LICENSE-2.0
631
+ *
632
+ * Unless required by applicable law or agreed to in writing, software
633
+ * distributed under the License is distributed on an "AS IS" BASIS,
634
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
635
+ * See the License for the specific language governing permissions and
636
+ * limitations under the License.
637
+ *
638
+ * SPDX-License-Identifier: Apache-2.0
639
+ */
640
+ const comments = "/api/v1/pages/publications/:id/comments/:locale";
641
+ const id$2 = {
642
+ type: "string",
643
+ format: "uuid"
644
+ };
645
+ const locale$1 = {
646
+ type: "string",
647
+ minLength: 1,
648
+ maxLength: 32
649
+ };
650
+ const body$1 = {
651
+ type: "string",
652
+ minLength: 1,
653
+ maxLength: 2e3
654
+ };
655
+ const name$1 = {
656
+ type: "string",
657
+ maxLength: 80
658
+ };
659
+ const publicComment = {
660
+ type: "object",
661
+ properties: {
662
+ body: body$1,
663
+ name: name$1,
664
+ createdAt: {
665
+ type: "string",
666
+ format: "date-time"
667
+ }
668
+ },
669
+ required: ["body", "createdAt"]
670
+ };
671
+ const params$1 = {
672
+ type: "object",
673
+ properties: {
674
+ id: id$2,
675
+ locale: locale$1
676
+ },
677
+ required: ["id", "locale"]
678
+ };
679
+ const array = (items) => ({
680
+ type: "object",
681
+ properties: { data: {
682
+ type: "array",
683
+ items
684
+ } },
685
+ required: ["data"]
686
+ });
687
+ const sectionRoutes = [
688
+ defineRoute({
689
+ method: "GET",
690
+ url: "/api/v1/pages/sections/:slug",
691
+ public: true,
692
+ cache: {
693
+ sMaxAge: 60,
694
+ staleWhileRevalidate: 300,
695
+ tags: [PAGES_TAG]
696
+ },
697
+ schema: {
698
+ params: {
699
+ type: "object",
700
+ properties: { slug: {
701
+ type: "string",
702
+ minLength: 1,
703
+ maxLength: 120
704
+ } },
705
+ required: ["slug"]
706
+ },
707
+ query: {
708
+ type: "object",
709
+ properties: {
710
+ locale: locale$1,
711
+ kind: {
712
+ type: "string",
713
+ enum: ["related", "comments"]
714
+ }
715
+ },
716
+ required: ["locale", "kind"]
717
+ },
718
+ response: { 200: array({ anyOf: [publicComment, {
719
+ type: "object",
720
+ properties: {
721
+ title: { type: "string" },
722
+ path: { type: "string" }
723
+ },
724
+ required: ["title", "path"]
725
+ }] }) }
726
+ },
727
+ handler: async (ctx) => ({ data: await readArticleSection(ctx.services.database, textOf(ctx.params["slug"]) ?? "", ctx.query["locale"], ctx.query["kind"] === "comments" ? "comments" : "related") })
728
+ }),
729
+ defineRoute({
730
+ method: "GET",
731
+ url: comments,
732
+ permission: "pages.publish",
733
+ schema: {
734
+ params: params$1,
735
+ response: { 200: array({
736
+ ...publicComment,
737
+ properties: {
738
+ ...publicComment.properties,
739
+ id: id$2
740
+ },
741
+ required: [...publicComment.required, "id"]
742
+ }) }
743
+ },
744
+ handler: async (ctx) => {
745
+ siteScope(ctx);
746
+ return { data: await listPublicComments(ctx.services.database, textOf(ctx.params["id"]) ?? "", ctx.params["locale"]) };
747
+ }
748
+ }),
749
+ defineRoute({
750
+ method: "POST",
751
+ url: comments,
752
+ permission: "pages.publish",
753
+ schema: {
754
+ params: params$1,
755
+ body: {
756
+ type: "object",
757
+ additionalProperties: false,
758
+ properties: {
759
+ body: body$1,
760
+ name: name$1
761
+ },
762
+ required: ["body"]
763
+ },
764
+ response: { 201: {
765
+ type: "object",
766
+ properties: { data: {
767
+ type: "object",
768
+ properties: { id: id$2 },
769
+ required: ["id"]
770
+ } },
771
+ required: ["data"]
772
+ } }
773
+ },
774
+ handler: async (ctx) => {
775
+ siteScope(ctx);
776
+ const data = await addPublicComment(ctx.services.database, textOf(ctx.params["id"]) ?? "", ctx.params["locale"], ctx.body);
777
+ ctx.status(201);
778
+ return { data };
779
+ }
780
+ }),
781
+ defineRoute({
782
+ method: "DELETE",
783
+ url: comments + "/:comment",
784
+ permission: "pages.publish",
785
+ schema: {
786
+ params: {
787
+ ...params$1,
788
+ properties: {
789
+ ...params$1.properties,
790
+ comment: id$2
791
+ },
792
+ required: [...params$1.required, "comment"]
793
+ },
794
+ response: { 204: { type: "null" } }
795
+ },
796
+ handler: async (ctx) => {
797
+ siteScope(ctx);
798
+ await removePublicComment(ctx.services.database, textOf(ctx.params["id"]) ?? "", ctx.params["locale"], textOf(ctx.params["comment"]) ?? "");
799
+ ctx.status(204);
800
+ return null;
801
+ }
802
+ })
803
+ ];
804
+ // src/routes/index.ts
805
+ /**
806
+ * BieberKit
807
+ *
808
+ * @file plugins/pages/src/routes/index.ts
809
+ * @description Declares editorial routes for localized pages and articles.
810
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
811
+ * @copyright Copyright (c) 2026 Bieber Kieu
812
+ * @license Apache-2.0
813
+ *
814
+ * Licensed under the Apache License, Version 2.0 (the "License");
815
+ * you may not use this file except in compliance with the License.
816
+ * You may obtain a copy of the License at
817
+ *
818
+ * http://www.apache.org/licenses/LICENSE-2.0
819
+ *
820
+ * Unless required by applicable law or agreed to in writing, software
821
+ * distributed under the License is distributed on an "AS IS" BASIS,
822
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
823
+ * See the License for the specific language governing permissions and
824
+ * limitations under the License.
825
+ *
826
+ * SPDX-License-Identifier: Apache-2.0
827
+ */
828
+ const root = "/api/v1/pages/publications";
829
+ const id$1 = {
830
+ type: "string",
831
+ format: "uuid"
832
+ };
833
+ const locale = {
834
+ type: "string",
835
+ minLength: 1,
836
+ maxLength: 32
837
+ };
838
+ const idAndLocale = {
839
+ type: "object",
840
+ properties: {
841
+ id: id$1,
842
+ locale
843
+ },
844
+ required: ["id", "locale"]
845
+ };
846
+ const title = {
847
+ type: "string",
848
+ minLength: 1,
849
+ maxLength: 240
850
+ };
851
+ const slug$1 = {
852
+ type: "string",
853
+ minLength: 1,
854
+ maxLength: 120
855
+ };
856
+ const kind = {
857
+ type: "string",
858
+ enum: ["page", "article"]
859
+ };
860
+ const draft = {
861
+ type: "object",
862
+ additionalProperties: false,
863
+ properties: {
864
+ title,
865
+ slug: slug$1,
866
+ excerpt: {
867
+ type: "string",
868
+ maxLength: 1e3
869
+ },
870
+ document: contentFieldOptions().jsonSchema
871
+ },
872
+ required: ["title", "document"]
873
+ };
874
+ function dataOf(data) {
875
+ return {
876
+ type: "object",
877
+ properties: { data },
878
+ required: ["data"]
879
+ };
880
+ }
881
+ const routes = [
882
+ ...sectionRoutes,
883
+ defineRoute({
884
+ method: "GET",
885
+ url: root,
886
+ permission: "pages.read",
887
+ schema: {
888
+ query: {
889
+ type: "object",
890
+ properties: { page: {
891
+ type: "integer",
892
+ minimum: 1,
893
+ maximum: 1e6
894
+ } }
895
+ },
896
+ response: { 200: {
897
+ type: "object",
898
+ properties: {
899
+ data: {
900
+ type: "array",
901
+ items: {
902
+ type: "object",
903
+ properties: {
904
+ id: id$1,
905
+ kind,
906
+ title
907
+ },
908
+ required: ["id", "kind"]
909
+ }
910
+ },
911
+ total: { type: "integer" }
912
+ },
913
+ required: ["data", "total"]
914
+ } }
915
+ },
916
+ handler: (ctx) => {
917
+ siteScope(ctx);
918
+ const page = ctx.query["page"];
919
+ return listPublications(ctx.services.database, typeof page === "number" ? page : 1);
920
+ }
921
+ }),
922
+ defineRoute({
923
+ method: "POST",
924
+ url: root,
925
+ permission: "pages.manage",
926
+ schema: {
927
+ body: {
928
+ type: "object",
929
+ additionalProperties: false,
930
+ properties: { kind },
931
+ required: ["kind"]
932
+ },
933
+ response: { 201: dataOf({
934
+ type: "object",
935
+ properties: { id: id$1 },
936
+ required: ["id"]
937
+ }) }
938
+ },
939
+ handler: async (ctx) => {
940
+ siteScope(ctx);
941
+ const publicationKind = typeof ctx.body === "object" && ctx.body !== null ? Reflect.get(ctx.body, "kind") : void 0;
942
+ const data = await createPublication(ctx.services.database, publicationKind);
943
+ ctx.status(201);
944
+ return { data };
945
+ }
946
+ }),
947
+ defineRoute({
948
+ method: "GET",
949
+ url: root + "/:id/drafts/:locale",
950
+ permission: "pages.read",
951
+ schema: {
952
+ params: idAndLocale,
953
+ response: { 200: dataOf(draft) }
954
+ },
955
+ handler: async (ctx) => {
956
+ siteScope(ctx);
957
+ return { data: await readDraft(ctx.services.database, textOf(ctx.params["id"]) ?? "", ctx.params["locale"], ctx.services.content) };
958
+ }
959
+ }),
960
+ defineRoute({
961
+ method: "PUT",
962
+ url: root + "/:id/drafts/:locale",
963
+ permission: "pages.manage",
964
+ schema: {
965
+ params: idAndLocale,
966
+ body: draft,
967
+ response: { 200: dataOf(draft) }
968
+ },
969
+ handler: async (ctx) => {
970
+ siteScope(ctx);
971
+ return { data: await saveDraft(ctx.services.database, textOf(ctx.params["id"]) ?? "", ctx.params["locale"], ctx.body, ctx.services.content) };
972
+ }
973
+ }),
974
+ defineRoute({
975
+ method: "POST",
976
+ url: root + "/:id/publish/:locale",
977
+ permission: "pages.publish",
978
+ schema: {
979
+ params: idAndLocale,
980
+ response: { 200: dataOf({
981
+ type: "object",
982
+ properties: { slug: slug$1 },
983
+ required: ["slug"]
984
+ }) }
985
+ },
986
+ handler: async (ctx) => {
987
+ siteScope(ctx);
988
+ return { data: await publishDraft(ctx.services.database, ctx.services.publicationRedirects, textOf(ctx.params["id"]) ?? "", ctx.params["locale"], ctx.services.content) };
989
+ }
990
+ }),
991
+ defineRoute({
992
+ method: "POST",
993
+ url: root + "/:id/preview/:locale",
994
+ permission: "pages.read",
995
+ schema: {
996
+ params: idAndLocale,
997
+ response: { 200: dataOf({
998
+ type: "object",
999
+ properties: { url: {
1000
+ type: "string",
1001
+ format: "uri"
1002
+ } },
1003
+ required: ["url"]
1004
+ }) }
1005
+ },
1006
+ handler: async (ctx) => {
1007
+ siteScope(ctx);
1008
+ return { data: { url: await issuePreview(ctx.services.database, ctx.services.config, textOf(ctx.params["id"]) ?? "", ctx.params["locale"], ctx.services.content) } };
1009
+ }
1010
+ }),
1011
+ defineRoute({
1012
+ method: "GET",
1013
+ url: "/api/v1/pages/preview",
1014
+ public: true,
1015
+ schema: {
1016
+ query: {
1017
+ type: "object",
1018
+ properties: { token: {
1019
+ type: "string",
1020
+ minLength: 1,
1021
+ maxLength: 4096
1022
+ } },
1023
+ required: ["token"]
1024
+ },
1025
+ response: { 200: dataOf({
1026
+ type: "object",
1027
+ properties: {
1028
+ ...draft.properties,
1029
+ locale
1030
+ },
1031
+ required: [
1032
+ "title",
1033
+ "document",
1034
+ "locale"
1035
+ ]
1036
+ }) }
1037
+ },
1038
+ handler: async (ctx) => {
1039
+ ctx.header("cache-control", "private, no-store");
1040
+ ctx.header("x-robots-tag", "noindex, nofollow");
1041
+ return { data: await readPreview(ctx.services.database, ctx.services.config.SITE_REVALIDATE_SECRET, ctx.query["token"], ctx.services.content) };
1042
+ }
1043
+ })
1044
+ ];
1045
+ // src/services/composition.ts
1046
+ /**
1047
+ * BieberKit
1048
+ *
1049
+ * @file plugins/pages/src/services/composition.ts
1050
+ * @description Reads only published translations for site composition and sitemaps.
1051
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
1052
+ * @copyright Copyright (c) 2026 Bieber Kieu
1053
+ * @license Apache-2.0
1054
+ *
1055
+ * Licensed under the Apache License, Version 2.0 (the "License");
1056
+ * you may not use this file except in compliance with the License.
1057
+ * You may obtain a copy of the License at
1058
+ *
1059
+ * http://www.apache.org/licenses/LICENSE-2.0
1060
+ *
1061
+ * Unless required by applicable law or agreed to in writing, software
1062
+ * distributed under the License is distributed on an "AS IS" BASIS,
1063
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1064
+ * See the License for the specific language governing permissions and
1065
+ * limitations under the License.
1066
+ *
1067
+ * SPDX-License-Identifier: Apache-2.0
1068
+ */
1069
+ const tags = () => [PAGES_TAG];
1070
+ function jsonValue(value) {
1071
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
1072
+ if (Array.isArray(value)) return value.map(jsonValue);
1073
+ if (typeof value !== "object") return null;
1074
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, jsonValue(child)]));
1075
+ }
1076
+ const publicationId = (row) => {
1077
+ const ref = property(row, "publication");
1078
+ return textOf(ref) ?? textOf(property(ref, "id"));
1079
+ };
1080
+ const isoDate = (value) => value instanceof Date ? value.toISOString() : void 0;
1081
+ function sitemapFragment(kind) {
1082
+ return defineFragment({
1083
+ name: kind === "page" ? "pages.sitemap" : "articles.sitemap",
1084
+ on: "sitemap",
1085
+ tags: () => [SITE_SITEMAP_TAG, PAGES_TAG],
1086
+ load: async (_input, services) => runInUnitOfWork(services.database, async (em) => {
1087
+ return (await em.find(translationsOf(em), {
1088
+ publication: { kind },
1089
+ publishedSlug: { $ne: null }
1090
+ }, {
1091
+ orderBy: {
1092
+ locale: "asc",
1093
+ publishedSlug: "asc"
1094
+ },
1095
+ limit: 5e4
1096
+ })).flatMap((row) => {
1097
+ const locale = textOf(property(row, "locale"));
1098
+ const slug = textOf(property(row, "publishedSlug"));
1099
+ const lastmod = isoDate(property(row, "publishedAt"));
1100
+ return locale === void 0 || slug === void 0 ? [] : [{
1101
+ path: publishedPath(locale, slug),
1102
+ ...lastmod === void 0 ? {} : { lastmod }
1103
+ }];
1104
+ });
1105
+ })
1106
+ });
1107
+ }
1108
+ const fragments = [
1109
+ defineFragment({
1110
+ name: "pages.content",
1111
+ on: "page",
1112
+ primary: true,
1113
+ tags,
1114
+ load: async ({ slug, locale }, services) => {
1115
+ const language = locale === void 0 ? "en" : localeOf(locale);
1116
+ if (slug === void 0 || language === void 0) return void 0;
1117
+ return runInUnitOfWork(services.database, async (em) => {
1118
+ const rows = translationsOf(em);
1119
+ const row = await em.findOne(rows, {
1120
+ locale: language,
1121
+ publishedSlug: slug
1122
+ });
1123
+ const id = publicationId(row);
1124
+ const title = textOf(property(row, "publishedTitle"));
1125
+ if (id === void 0 || title === void 0) return void 0;
1126
+ const translations = await em.find(rows, {
1127
+ publication: id,
1128
+ publishedSlug: { $ne: null }
1129
+ });
1130
+ const paths = Object.fromEntries(translations.flatMap((entry) => {
1131
+ const tag = textOf(property(entry, "locale"));
1132
+ const url = textOf(property(entry, "publishedSlug"));
1133
+ return tag === void 0 || url === void 0 ? [] : [[tag, url === "home" ? "" : url]];
1134
+ }));
1135
+ const excerpt = textOf(property(row, "publishedExcerpt"));
1136
+ const record = await em.findOne(publicationOf(em), { id });
1137
+ const datePublished = isoDate(property(row, "firstPublishedAt"));
1138
+ const dateModified = isoDate(property(row, "publishedAt"));
1139
+ const seo = property(record, "kind") === "article" ? {
1140
+ type: "article",
1141
+ structured: { article: {
1142
+ ...datePublished === void 0 ? {} : { datePublished },
1143
+ ...dateModified === void 0 ? {} : { dateModified }
1144
+ } }
1145
+ } : void 0;
1146
+ return {
1147
+ title,
1148
+ paths,
1149
+ document: jsonValue(property(row, "publishedDocument")),
1150
+ ...excerpt === void 0 ? {} : { excerpt },
1151
+ ...seo === void 0 ? {} : {
1152
+ seo,
1153
+ article: true
1154
+ }
1155
+ };
1156
+ });
1157
+ }
1158
+ }),
1159
+ sitemapFragment("page"),
1160
+ sitemapFragment("article")
1161
+ ];
1162
+ // src/services/taxonomy.ts
1163
+ /**
1164
+ * BieberKit
1165
+ *
1166
+ * @file plugins/pages/src/services/taxonomy.ts
1167
+ * @description Stores taxonomy terms and their links to publication identities.
1168
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
1169
+ * @copyright Copyright (c) 2026 Bieber Kieu
1170
+ * @license Apache-2.0
1171
+ *
1172
+ * Licensed under the Apache License, Version 2.0 (the "License");
1173
+ * you may not use this file except in compliance with the License.
1174
+ * You may obtain a copy of the License at
1175
+ *
1176
+ * http://www.apache.org/licenses/LICENSE-2.0
1177
+ *
1178
+ * Unless required by applicable law or agreed to in writing, software
1179
+ * distributed under the License is distributed on an "AS IS" BASIS,
1180
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1181
+ * See the License for the specific language governing permissions and
1182
+ * limitations under the License.
1183
+ *
1184
+ * SPDX-License-Identifier: Apache-2.0
1185
+ */
1186
+ const TERM_PAGE_SIZE = 50;
1187
+ const classOf = (em, def) => em.getMetadata().getByClassName(def.name).class;
1188
+ function invalid() {
1189
+ throw new HttpError("TAXONOMY_INVALID", 400, "Enter a name and slug.", "Use a name and a lowercase URL slug.");
1190
+ }
1191
+ function missing() {
1192
+ throw new HttpError("TAXONOMY_NOT_FOUND", 404, "The term is no longer available.", "Reload the list of terms.");
1193
+ }
1194
+ function stale() {
1195
+ throw new HttpError("DATA_VERSION_STALE", 412, "The term changed since it was read.", "Reload the term and apply the change again.");
1196
+ }
1197
+ function shape(row) {
1198
+ return {
1199
+ id: String(row["id"]),
1200
+ name: String(row["name"]),
1201
+ slug: String(row["slug"]),
1202
+ version: Number(row["version"])
1203
+ };
1204
+ }
1205
+ async function assigned(em, taxonomy, id) {
1206
+ const rows = await em.find(classOf(em, taxonomy.assignment), { term: id });
1207
+ if (rows.length === 0) return [];
1208
+ const ids = rows.map((row) => String(property(row["publication"], "id")));
1209
+ return (await summarizePublications(em, await em.find(publicationOf(em), { id: { $in: ids } }, { orderBy: {
1210
+ createdAt: "desc",
1211
+ id: "desc"
1212
+ } }))).map(({ id: publicationId, ...summary }) => ({
1213
+ publicationId,
1214
+ ...summary
1215
+ }));
1216
+ }
1217
+ async function replaceAssignments(em, taxonomy, id, input) {
1218
+ const ids = input.map(({ publicationId }) => publicationId.toLowerCase());
1219
+ if (new Set(ids).size !== ids.length) throw new HttpError("TAXONOMY_DUPLICATE_ASSIGNMENT", 409, "A publication is listed more than once.", "Choose each publication once.");
1220
+ const link = classOf(em, taxonomy.assignment);
1221
+ await em.nativeDelete(link, { term: id });
1222
+ for (const publication of ids) em.create(link, {
1223
+ term: id,
1224
+ publication
1225
+ });
1226
+ await em.flush();
1227
+ }
1228
+ function taxonomyStore(db, taxonomy) {
1229
+ async function read(em, id, seePublications) {
1230
+ const row = await em.findOne(classOf(em, taxonomy.term), { id }, { refresh: true });
1231
+ if (row === null) return missing();
1232
+ return {
1233
+ ...shape(row),
1234
+ ...seePublications ? { publications: await assigned(em, taxonomy, id) } : {}
1235
+ };
1236
+ }
1237
+ const audit = (em, action, id) => recordAudit(em, {
1238
+ action: taxonomy.term.name + "." + action,
1239
+ entity: taxonomy.term.name,
1240
+ recordId: id
1241
+ });
1242
+ return {
1243
+ list: (page) => runInUnitOfWork(db, async (em) => {
1244
+ const [rows, total] = await em.findAndCount(classOf(em, taxonomy.term), {}, {
1245
+ orderBy: {
1246
+ name: "asc",
1247
+ id: "asc"
1248
+ },
1249
+ offset: (page - 1) * TERM_PAGE_SIZE,
1250
+ limit: TERM_PAGE_SIZE
1251
+ });
1252
+ return {
1253
+ data: rows.map(shape),
1254
+ total
1255
+ };
1256
+ }),
1257
+ get: (id, seePublications) => runInUnitOfWork(db, (em) => read(em, id, seePublications)),
1258
+ create: (input, seePublications) => runInTransaction(db, async (em) => {
1259
+ const name = input.name?.trim();
1260
+ if (name === void 0 || name === "" || input.slug === void 0) return invalid();
1261
+ const row = em.create(classOf(em, taxonomy.term), {
1262
+ name,
1263
+ slug: input.slug
1264
+ });
1265
+ const id = String(row["id"]);
1266
+ audit(em, "create", id);
1267
+ await em.flush();
1268
+ if (input.publications !== void 0) await replaceAssignments(em, taxonomy, id, input.publications);
1269
+ return read(em, id, seePublications);
1270
+ }),
1271
+ update: (id, version, input, seePublications) => runInTransaction(db, async (em) => {
1272
+ const term = classOf(em, taxonomy.term);
1273
+ const row = await em.findOne(term, { id });
1274
+ if (row === null) return missing();
1275
+ expectVersion(row, version);
1276
+ const name = input.name?.trim();
1277
+ if (name === "") return invalid();
1278
+ const current = Number(row["version"]);
1279
+ if (await em.nativeUpdate(term, {
1280
+ id,
1281
+ version: current
1282
+ }, {
1283
+ ...name === void 0 ? {} : { name },
1284
+ ...input.slug === void 0 ? {} : { slug: input.slug },
1285
+ updatedAt: /* @__PURE__ */ new Date(),
1286
+ version: current + 1
1287
+ }) === 0) return stale();
1288
+ if (input.publications !== void 0) await replaceAssignments(em, taxonomy, id, input.publications);
1289
+ audit(em, "update", id);
1290
+ return read(em, id, seePublications);
1291
+ }),
1292
+ remove: (id, version) => runInTransaction(db, async (em) => {
1293
+ const term = classOf(em, taxonomy.term);
1294
+ const row = await em.findOne(term, { id });
1295
+ if (row === null) missing();
1296
+ expectVersion(row, version);
1297
+ if (await em.nativeDelete(term, {
1298
+ id,
1299
+ version: row["version"]
1300
+ }) === 0) stale();
1301
+ audit(em, "delete", id);
1302
+ })
1303
+ };
1304
+ }
1305
+ // src/routes/taxonomy.ts
1306
+ /**
1307
+ * BieberKit
1308
+ *
1309
+ * @file plugins/pages/src/routes/taxonomy.ts
1310
+ * @description Builds scoped CRUD routes shared by categories and tags.
1311
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
1312
+ * @copyright Copyright (c) 2026 Bieber Kieu
1313
+ * @license Apache-2.0
1314
+ *
1315
+ * Licensed under the Apache License, Version 2.0 (the "License");
1316
+ * you may not use this file except in compliance with the License.
1317
+ * You may obtain a copy of the License at
1318
+ *
1319
+ * http://www.apache.org/licenses/LICENSE-2.0
1320
+ *
1321
+ * Unless required by applicable law or agreed to in writing, software
1322
+ * distributed under the License is distributed on an "AS IS" BASIS,
1323
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1324
+ * See the License for the specific language governing permissions and
1325
+ * limitations under the License.
1326
+ *
1327
+ * SPDX-License-Identifier: Apache-2.0
1328
+ */
1329
+ const id = {
1330
+ type: "string",
1331
+ format: "uuid"
1332
+ };
1333
+ const name = {
1334
+ type: "string",
1335
+ minLength: 1,
1336
+ maxLength: 120
1337
+ };
1338
+ const slug = {
1339
+ type: "string",
1340
+ minLength: 1,
1341
+ maxLength: 80,
1342
+ pattern: "^[a-z0-9]+(?:-[a-z0-9]+)*$"
1343
+ };
1344
+ const params = {
1345
+ type: "object",
1346
+ properties: { id },
1347
+ required: ["id"]
1348
+ };
1349
+ const body = {
1350
+ type: "object",
1351
+ additionalProperties: false,
1352
+ properties: {
1353
+ name,
1354
+ slug,
1355
+ publications: {
1356
+ type: "array",
1357
+ maxItems: 200,
1358
+ items: {
1359
+ type: "object",
1360
+ properties: { publicationId: id },
1361
+ required: ["publicationId"],
1362
+ additionalProperties: false
1363
+ }
1364
+ }
1365
+ }
1366
+ };
1367
+ const record = {
1368
+ type: "object",
1369
+ properties: {
1370
+ id,
1371
+ name,
1372
+ slug,
1373
+ version: { type: "integer" },
1374
+ publications: {
1375
+ type: "array",
1376
+ items: {
1377
+ type: "object",
1378
+ properties: {
1379
+ publicationId: id,
1380
+ kind: { enum: ["page", "article"] },
1381
+ title: { type: "string" }
1382
+ },
1383
+ required: ["publicationId", "kind"]
1384
+ }
1385
+ }
1386
+ },
1387
+ required: [
1388
+ "id",
1389
+ "name",
1390
+ "slug",
1391
+ "version"
1392
+ ]
1393
+ };
1394
+ const result = {
1395
+ type: "object",
1396
+ properties: { data: record },
1397
+ required: ["data"]
1398
+ };
1399
+ function match(ctx) {
1400
+ const value = ctx.headers["if-match"];
1401
+ if (typeof value !== "string") throw new HttpError("HTTP_PRECONDITION_REQUIRED", 428, "Send the version of the term in If-Match.", "Reload the term and send its current version.");
1402
+ return value;
1403
+ }
1404
+ function inputOf(ctx) {
1405
+ return ctx.body;
1406
+ }
1407
+ async function readPublications(ctx, input) {
1408
+ const canRead = await ctx.can("pages.read");
1409
+ if (input?.publications !== void 0 && !canRead) throw new HttpError("TAXONOMY_PUBLICATIONS_DENIED", 403, "You may not assign publications.", "Ask for the permission to read publications.");
1410
+ return canRead;
1411
+ }
1412
+ /** Builds the first-party taxonomy API with the editorial site's scope and independent plugin permissions. */
1413
+ function taxonomyRoutes(module, term, assignmentEntity) {
1414
+ const url = `/api/v1/${module}/${module}`;
1415
+ const read = module + ".read";
1416
+ const manage = module + ".manage";
1417
+ const store = (ctx) => taxonomyStore(ctx.services.database, {
1418
+ term,
1419
+ assignment: assignmentEntity
1420
+ });
1421
+ return [
1422
+ defineRoute({
1423
+ method: "GET",
1424
+ url,
1425
+ permission: read,
1426
+ schema: {
1427
+ query: {
1428
+ type: "object",
1429
+ properties: { page: {
1430
+ type: "integer",
1431
+ minimum: 1,
1432
+ maximum: 1e6
1433
+ } }
1434
+ },
1435
+ response: { 200: {
1436
+ type: "object",
1437
+ properties: {
1438
+ data: {
1439
+ type: "array",
1440
+ items: record
1441
+ },
1442
+ total: { type: "integer" }
1443
+ },
1444
+ required: ["data", "total"]
1445
+ } }
1446
+ },
1447
+ handler: (ctx) => {
1448
+ siteScope(ctx);
1449
+ const page = ctx.query["page"];
1450
+ return store(ctx).list(typeof page === "number" ? page : 1);
1451
+ }
1452
+ }),
1453
+ defineRoute({
1454
+ method: "GET",
1455
+ url: url + "/:id",
1456
+ permission: read,
1457
+ schema: {
1458
+ params,
1459
+ response: { 200: result }
1460
+ },
1461
+ handler: async (ctx) => {
1462
+ siteScope(ctx);
1463
+ return { data: await store(ctx).get(String(ctx.params["id"]), await readPublications(ctx)) };
1464
+ }
1465
+ }),
1466
+ defineRoute({
1467
+ method: "POST",
1468
+ url,
1469
+ permission: manage,
1470
+ idempotent: true,
1471
+ schema: {
1472
+ body: {
1473
+ ...body,
1474
+ required: ["name", "slug"]
1475
+ },
1476
+ response: { 201: result }
1477
+ },
1478
+ handler: async (ctx) => {
1479
+ siteScope(ctx);
1480
+ const input = inputOf(ctx);
1481
+ const data = await store(ctx).create(input, await readPublications(ctx, input));
1482
+ ctx.status(201);
1483
+ ctx.header("location", url + "/" + data.id);
1484
+ return { data };
1485
+ }
1486
+ }),
1487
+ defineRoute({
1488
+ method: "PATCH",
1489
+ url: url + "/:id",
1490
+ permission: manage,
1491
+ requiresIfMatch: true,
1492
+ schema: {
1493
+ params,
1494
+ body: {
1495
+ ...body,
1496
+ minProperties: 1
1497
+ },
1498
+ response: { 200: result }
1499
+ },
1500
+ handler: async (ctx) => {
1501
+ siteScope(ctx);
1502
+ const input = inputOf(ctx);
1503
+ return { data: await store(ctx).update(String(ctx.params["id"]), match(ctx), input, await readPublications(ctx, input)) };
1504
+ }
1505
+ }),
1506
+ defineRoute({
1507
+ method: "DELETE",
1508
+ url: url + "/:id",
1509
+ permission: manage,
1510
+ requiresIfMatch: true,
1511
+ schema: {
1512
+ params,
1513
+ response: { 204: { type: "null" } }
1514
+ },
1515
+ handler: async (ctx) => {
1516
+ siteScope(ctx);
1517
+ await store(ctx).remove(String(ctx.params["id"]), match(ctx));
1518
+ ctx.status(204);
1519
+ return null;
1520
+ }
1521
+ })
1522
+ ];
1523
+ }
1524
+ // src/index.ts
1525
+ /**
1526
+ * BieberKit
1527
+ *
1528
+ * @file plugins/pages/src/index.ts
1529
+ * @description Declares the pages plugin with editorial and public composition routes.
1530
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
1531
+ * @copyright Copyright (c) 2026 Bieber Kieu
1532
+ * @license Apache-2.0
1533
+ *
1534
+ * Licensed under the Apache License, Version 2.0 (the "License");
1535
+ * you may not use this file except in compliance with the License.
1536
+ * You may obtain a copy of the License at
1537
+ *
1538
+ * http://www.apache.org/licenses/LICENSE-2.0
1539
+ *
1540
+ * Unless required by applicable law or agreed to in writing, software
1541
+ * distributed under the License is distributed on an "AS IS" BASIS,
1542
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1543
+ * See the License for the specific language governing permissions and
1544
+ * limitations under the License.
1545
+ *
1546
+ * SPDX-License-Identifier: Apache-2.0
1547
+ */
1548
+ const plugin = definePlugin({
1549
+ name: "@bieberkit/plugin-pages",
1550
+ version,
1551
+ core: "*",
1552
+ dialects: [
1553
+ "postgres",
1554
+ "mysql",
1555
+ "sqlite"
1556
+ ],
1557
+ requires: { "@bieberkit/plugin-redirects": "*" },
1558
+ permissions: [
1559
+ "pages.read",
1560
+ "pages.manage",
1561
+ "pages.publish"
1562
+ ],
1563
+ entities: [
1564
+ Publication,
1565
+ Translation,
1566
+ PublicComment
1567
+ ],
1568
+ routes,
1569
+ fragments
1570
+ });
1571
+ export { Publication, plugin as default, seedPublication, taxonomyRoutes };