qarpeo 0.2.1 → 0.3.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/chunks/tools.mjs +993 -31
- package/dist/cli/index.mjs +1071 -31
- package/dist/fate/index.d.ts +9 -1
- package/dist/fate/index.mjs +20 -3
- package/dist/module.mjs +292 -748
- package/dist/runtime/browser.mjs +2 -2
- package/dist/runtime/comments-server.d.ts +3 -0
- package/dist/runtime/comments-server.mjs +2 -0
- package/dist/runtime/comments.d.ts +0 -2
- package/dist/runtime/comments.mjs +0 -2
- package/dist/runtime/db.d.ts +10 -9
- package/dist/runtime/db.mjs +79 -8
- package/dist/runtime/drizzle.mjs +21 -6
- package/dist/runtime/index.d.ts +4 -0
- package/dist/runtime/realtime-server.d.ts +4 -0
- package/dist/runtime/realtime-server.mjs +13 -0
- package/dist/runtime/realtime.d.ts +1 -4
- package/dist/runtime/realtime.mjs +0 -13
- package/dist/runtime/replica.d.ts +27 -0
- package/dist/runtime/replica.mjs +229 -0
- package/dist/runtime/server/durable-objects/agent.mjs +14 -2
- package/dist/runtime/server/durable-objects/room.d.ts +10 -0
- package/dist/runtime/server/durable-objects/room.mjs +119 -28
- package/dist/runtime/server/middleware/devtools.mjs +1 -1
- package/dist/runtime/server/middleware/tenancy.mjs +7 -4
- package/dist/runtime/server/plugins/store.mjs +1 -1
- package/dist/runtime/server/routes/__qarpeo/mail/track/click/[id].get.mjs +57 -17
- package/dist/runtime/server/routes/agents/[agent]/chat.post.mjs +19 -12
- package/dist/runtime/server/routes/agents/[agent]/clear.post.mjs +8 -9
- package/dist/runtime/server/routes/agents/[agent]/history.get.mjs +8 -9
- package/dist/runtime/server/routes/analytics/events.get.mjs +12 -2
- package/dist/runtime/server/routes/analytics/pageviews.get.mjs +10 -1
- package/dist/runtime/server/routes/analytics/summary.get.mjs +10 -1
- package/dist/runtime/server/routes/auth/2fa/disable.post.mjs +11 -2
- package/dist/runtime/server/routes/auth/2fa/setup.post.mjs +7 -0
- package/dist/runtime/server/routes/auth/2fa/verify.post.mjs +11 -2
- package/dist/runtime/server/routes/auth/account.delete.mjs +7 -0
- package/dist/runtime/server/routes/auth/magic-link/verify.get.mjs +5 -3
- package/dist/runtime/server/routes/auth/organization/sso/index.post.mjs +10 -0
- package/dist/runtime/server/routes/auth/otp/verify.post.mjs +5 -3
- package/dist/runtime/server/routes/auth/sso/saml/acs.post.mjs +18 -0
- package/dist/runtime/server/routes/auth/webauthn/login/options.post.d.ts +1 -1
- package/dist/runtime/server/routes/auth/webauthn/login/options.post.mjs +11 -2
- package/dist/runtime/server/routes/auth/webauthn/login/verify.post.mjs +10 -1
- package/dist/runtime/server/routes/auth/webauthn/register/options.post.d.ts +1 -1
- package/dist/runtime/server/routes/auth/webauthn/register/options.post.mjs +10 -1
- package/dist/runtime/server/routes/auth/webauthn/register/verify.post.mjs +10 -1
- package/dist/runtime/server/routes/browser/crawl.post.mjs +13 -0
- package/dist/runtime/server/routes/browser/invoice.post.mjs +15 -1
- package/dist/runtime/server/routes/browser/og-image.post.mjs +13 -0
- package/dist/runtime/server/routes/browser/pdf.post.mjs +15 -1
- package/dist/runtime/server/routes/browser/screenshot.post.mjs +13 -0
- package/dist/runtime/server/routes/cms/[collection]/[id]/preview-token.post.mjs +23 -8
- package/dist/runtime/server/routes/cms/[collection]/[id]/publish.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/[collection]/[id]/review.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/[collection]/[id]/revisions/[revId]/restore.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/[collection]/[id].delete.mjs +2 -1
- package/dist/runtime/server/routes/cms/[collection]/[id].put.mjs +2 -1
- package/dist/runtime/server/routes/cms/[collection]/index.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/categories/[id].delete.mjs +2 -1
- package/dist/runtime/server/routes/cms/categories/[id].put.mjs +2 -1
- package/dist/runtime/server/routes/cms/categories.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/collections/[id].delete.mjs +2 -1
- package/dist/runtime/server/routes/cms/collections/[id].put.mjs +2 -1
- package/dist/runtime/server/routes/cms/collections/index.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/export.post.mjs +1 -1
- package/dist/runtime/server/routes/cms/subscribers/[id].delete.mjs +2 -1
- package/dist/runtime/server/routes/cms/subscribers/[id].patch.mjs +2 -1
- package/dist/runtime/server/routes/cms/tags/[id].delete.mjs +2 -1
- package/dist/runtime/server/routes/cms/tags.post.mjs +2 -1
- package/dist/runtime/server/routes/comments/[id]/react.post.mjs +7 -3
- package/dist/runtime/server/routes/comments/[id]/report.post.mjs +3 -0
- package/dist/runtime/server/routes/comments/[id].delete.mjs +1 -1
- package/dist/runtime/server/routes/comments/[id].get.mjs +13 -0
- package/dist/runtime/server/routes/comments/[id].patch.mjs +1 -1
- package/dist/runtime/server/routes/fate.d.ts +6 -0
- package/dist/runtime/server/routes/fate.mjs +32 -3
- package/dist/runtime/server/routes/mail/bounce.post.mjs +14 -2
- package/dist/runtime/server/routes/mail/unsubscribe.mjs +2 -1
- package/dist/runtime/server/routes/mail/webhooks.post.mjs +18 -4
- package/dist/runtime/server/routes/notifications/[id].get.mjs +3 -4
- package/dist/runtime/server/routes/notifications/index.get.mjs +4 -2
- package/dist/runtime/server/routes/notifications/push/subscribe.post.mjs +3 -1
- package/dist/runtime/server/routes/notifications/push/unsubscribe.post.mjs +5 -3
- package/dist/runtime/server/routes/notifications/read-all.post.mjs +6 -2
- package/dist/runtime/server/routes/notifications/send.post.mjs +13 -2
- package/dist/runtime/server/routes/payments/cancel.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/change-plan.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/checkout.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/pause.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/portal.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/subscription.get.mjs +1 -1
- package/dist/runtime/server/routes/payments/usage.get.mjs +1 -1
- package/dist/runtime/server/routes/payments/usage.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/webhook.post.mjs +8 -1
- package/dist/runtime/server/routes/realtime/broadcast.post.mjs +3 -2
- package/dist/runtime/server/routes/realtime/history.delete.mjs +2 -2
- package/dist/runtime/server/routes/realtime/history.get.mjs +2 -2
- package/dist/runtime/server/routes/realtime/presence.get.mjs +3 -3
- package/dist/runtime/server/routes/realtime/state.get.mjs +3 -3
- package/dist/runtime/server/routes/realtime/state.post.mjs +13 -4
- package/dist/runtime/server/routes/realtime/ws.get.mjs +2 -2
- package/dist/runtime/server/routes/storage/file/[...key].delete.mjs +1 -1
- package/dist/runtime/server/routes/storage/file/[...key].get.mjs +7 -0
- package/dist/runtime/server/routes/storage/files.get.d.ts +1 -1
- package/dist/runtime/server/routes/storage/files.get.mjs +24 -4
- package/dist/runtime/server/routes/storage/multipart/abort.post.mjs +16 -1
- package/dist/runtime/server/routes/storage/multipart/complete.post.d.ts +1 -1
- package/dist/runtime/server/routes/storage/multipart/complete.post.mjs +15 -1
- package/dist/runtime/server/routes/storage/multipart/create.post.mjs +7 -0
- package/dist/runtime/server/routes/storage/multipart/part.put.mjs +15 -1
- package/dist/runtime/server/routes/storage/presigned-r2.post.mjs +8 -1
- package/dist/runtime/server/routes/storage/presigned.post.d.ts +1 -1
- package/dist/runtime/server/routes/storage/presigned.post.mjs +8 -1
- package/dist/runtime/server/routes/storage/sign.post.mjs +7 -0
- package/dist/runtime/server/routes/storage/upload.post.d.ts +2 -2
- package/dist/runtime/server/routes/store/cart/index.delete.mjs +3 -4
- package/dist/runtime/server/routes/store/cart/index.get.mjs +3 -10
- package/dist/runtime/server/routes/store/cart/items/[id].delete.mjs +6 -4
- package/dist/runtime/server/routes/store/cart/items/[id].patch.mjs +12 -4
- package/dist/runtime/server/routes/store/cart/items.post.mjs +9 -10
- package/dist/runtime/server/routes/store/categories/index.get.mjs +4 -2
- package/dist/runtime/server/routes/store/checkout.post.mjs +13 -3
- package/dist/runtime/server/routes/store/coupons/apply.post.mjs +6 -5
- package/dist/runtime/server/routes/store/orders/[id].get.mjs +2 -2
- package/dist/runtime/server/routes/store/orders/download/[token].get.mjs +6 -3
- package/dist/runtime/server/routes/store/orders/index.get.mjs +1 -1
- package/dist/runtime/server/routes/store/products/[slug].get.mjs +2 -2
- package/dist/runtime/server/routes/store/products/index.get.mjs +1 -1
- package/dist/runtime/server/routes/store/tax/calculate.post.mjs +10 -0
- package/dist/runtime/server/routes/tenants/[tenant]/domains/[domain]/index.delete.mjs +26 -25
- package/dist/runtime/server/routes/tenants/[tenant]/domains/[domain]/verify.post.mjs +26 -25
- package/dist/runtime/server/utils/ai.d.ts +6 -0
- package/dist/runtime/server/utils/ai.mjs +12 -2
- package/dist/runtime/server/utils/analytics-query.mjs +8 -4
- package/dist/runtime/server/utils/browser-utils.d.ts +9 -0
- package/dist/runtime/server/utils/browser-utils.mjs +135 -0
- package/dist/runtime/server/utils/cms/cache.d.ts +13 -0
- package/dist/runtime/server/utils/cms/cache.mjs +95 -0
- package/dist/runtime/server/utils/cms/common.mjs +1 -1
- package/dist/runtime/server/utils/cms/markdown.mjs +38 -8
- package/dist/runtime/server/utils/cms/mutations.d.ts +26 -0
- package/dist/runtime/server/utils/cms/mutations.mjs +569 -0
- package/dist/runtime/server/utils/cms/path.d.ts +8 -0
- package/dist/runtime/server/utils/cms/path.mjs +23 -0
- package/dist/runtime/server/utils/cms/queries.d.ts +27 -0
- package/dist/runtime/server/utils/cms/queries.mjs +366 -0
- package/dist/runtime/server/utils/cms/references.d.ts +48 -0
- package/dist/runtime/server/utils/cms/references.mjs +309 -0
- package/dist/runtime/server/utils/cms/revisions.d.ts +7 -0
- package/dist/runtime/server/utils/cms/revisions.mjs +60 -0
- package/dist/runtime/server/utils/cms/sync.mjs +3 -3
- package/dist/runtime/server/utils/cms.d.ts +5 -82
- package/dist/runtime/server/utils/cms.mjs +28 -1367
- package/dist/runtime/server/utils/comments.d.ts +11 -0
- package/dist/runtime/server/utils/comments.mjs +65 -17
- package/dist/runtime/server/utils/crypto.mjs +1 -1
- package/dist/runtime/server/utils/domains.mjs +9 -0
- package/dist/runtime/server/utils/drizzle.d.ts +26 -1
- package/dist/runtime/server/utils/drizzle.mjs +78 -19
- package/dist/runtime/server/utils/email-inbound.mjs +9 -1
- package/dist/runtime/server/utils/impersonation.mjs +58 -1
- package/dist/runtime/server/utils/lock.d.ts +11 -0
- package/dist/runtime/server/utils/lock.mjs +4 -0
- package/dist/runtime/server/utils/mail-suppression.mjs +48 -13
- package/dist/runtime/server/utils/mail.d.ts +2 -1
- package/dist/runtime/server/utils/mail.mjs +17 -11
- package/dist/runtime/server/utils/notifications.d.ts +13 -4
- package/dist/runtime/server/utils/notifications.mjs +20 -4
- package/dist/runtime/server/utils/organization.mjs +36 -1
- package/dist/runtime/server/utils/passwordless.mjs +8 -0
- package/dist/runtime/server/utils/payments/checkout.d.ts +34 -0
- package/dist/runtime/server/utils/payments/checkout.mjs +158 -0
- package/dist/runtime/server/utils/payments/common.d.ts +45 -0
- package/dist/runtime/server/utils/payments/common.mjs +234 -0
- package/dist/runtime/server/utils/payments/index.d.ts +9 -0
- package/dist/runtime/server/utils/payments/index.mjs +21 -0
- package/dist/runtime/server/utils/payments/lemonsqueezy.d.ts +7 -0
- package/dist/runtime/server/utils/payments/lemonsqueezy.mjs +55 -0
- package/dist/runtime/server/utils/payments/paddle.d.ts +7 -0
- package/dist/runtime/server/utils/payments/paddle.mjs +92 -0
- package/dist/runtime/server/utils/payments/polar.d.ts +11 -0
- package/dist/runtime/server/utils/payments/polar.mjs +66 -0
- package/dist/runtime/server/utils/payments/stripe.d.ts +7 -0
- package/dist/runtime/server/utils/payments/stripe.mjs +159 -0
- package/dist/runtime/server/utils/payments/subscriptions.d.ts +89 -0
- package/dist/runtime/server/utils/payments/subscriptions.mjs +236 -0
- package/dist/runtime/server/utils/payments/usage.d.ts +12 -0
- package/dist/runtime/server/utils/payments/usage.mjs +143 -0
- package/dist/runtime/server/utils/payments/webhooks.d.ts +10 -0
- package/dist/runtime/server/utils/payments/webhooks.mjs +200 -0
- package/dist/runtime/server/utils/payments.d.ts +1 -158
- package/dist/runtime/server/utils/payments.mjs +1 -1289
- package/dist/runtime/server/utils/queue.d.ts +2 -0
- package/dist/runtime/server/utils/queue.mjs +34 -21
- package/dist/runtime/server/utils/rag.mjs +30 -17
- package/dist/runtime/server/utils/realtime.d.ts +5 -1
- package/dist/runtime/server/utils/realtime.mjs +43 -7
- package/dist/runtime/server/utils/session.mjs +16 -3
- package/dist/runtime/server/utils/sso.d.ts +3 -0
- package/dist/runtime/server/utils/sso.mjs +43 -0
- package/dist/runtime/server/utils/storage.mjs +12 -1
- package/dist/runtime/server/utils/store/cart.d.ts +63 -0
- package/dist/runtime/server/utils/store/cart.mjs +542 -0
- package/dist/runtime/server/utils/store/checkout.d.ts +14 -0
- package/dist/runtime/server/utils/store/checkout.mjs +118 -0
- package/dist/runtime/server/utils/store/common.d.ts +29 -0
- package/dist/runtime/server/utils/store/common.mjs +479 -0
- package/dist/runtime/server/utils/store/index.d.ts +7 -0
- package/dist/runtime/server/utils/store/index.mjs +30 -0
- package/dist/runtime/server/utils/store/inventory.d.ts +25 -0
- package/dist/runtime/server/utils/store/inventory.mjs +190 -0
- package/dist/runtime/server/utils/store/orders.d.ts +60 -0
- package/dist/runtime/server/utils/store/orders.mjs +590 -0
- package/dist/runtime/server/utils/store/products.d.ts +35 -0
- package/dist/runtime/server/utils/store/products.mjs +461 -0
- package/dist/runtime/server/utils/store/vendor.d.ts +18 -0
- package/dist/runtime/server/utils/store/vendor.mjs +68 -0
- package/dist/runtime/server/utils/store.d.ts +1 -207
- package/dist/runtime/server/utils/store.mjs +1 -2227
- package/dist/runtime/server/utils/string.d.ts +1 -1
- package/dist/runtime/server/utils/string.mjs +12 -4
- package/dist/runtime/server/utils/tenant.mjs +19 -5
- package/dist/runtime/server/utils/tracker.mjs +2 -0
- package/dist/runtime/server.d.ts +3 -3
- package/dist/runtime/server.mjs +4 -4
- package/dist/runtime/storage-server.d.ts +2 -0
- package/dist/runtime/storage-server.mjs +1 -0
- package/dist/runtime/storage.d.ts +1 -1
- package/dist/runtime/storage.mjs +0 -1
- package/dist/runtime/store.d.ts +0 -1
- package/dist/runtime/store.mjs +0 -1
- package/dist/runtime/test-utils.d.ts +4 -0
- package/dist/runtime/test-utils.mjs +54 -0
- package/dist/runtime/types/d1.d.ts +43 -0
- package/dist/runtime/types/drizzle.d.ts +6 -0
- package/dist/runtime/types/store.d.ts +1 -1
- package/dist/types/analytics.d.ts +80 -0
- package/dist/types/auth.d.ts +282 -0
- package/dist/types/cache.d.ts +55 -0
- package/dist/types/comments.d.ts +130 -0
- package/dist/types/db.d.ts +29 -0
- package/dist/types/email.d.ts +182 -0
- package/dist/types/index.d.ts +22 -0
- package/dist/types/jobs.d.ts +58 -0
- package/dist/types/notifications.d.ts +77 -0
- package/dist/types/options.d.ts +363 -0
- package/dist/types/payments.d.ts +145 -0
- package/dist/types/ratelimit.d.ts +71 -0
- package/dist/types/realtime.d.ts +136 -0
- package/dist/types/site.d.ts +121 -0
- package/dist/types/storage.d.ts +164 -0
- package/dist/types/store-options.d.ts +199 -0
- package/dist/types/tenant.d.ts +100 -0
- package/dist/types.d.ts +1 -2174
- package/dist/utils/migration-lock.d.ts +139 -0
- package/dist/utils/pkg.d.ts +14 -1
- package/dist/utils/schema-diff.d.ts +39 -0
- package/package.json +55 -17
- package/dist/chunks/auth-schema.mjs +0 -364
|
@@ -0,0 +1,569 @@
|
|
|
1
|
+
import { createError } from "nuxt/server";
|
|
2
|
+
import { fireCMSWebhooks, fireCMSDeployTrigger } from "../cms-events.mjs";
|
|
3
|
+
import { getAuthContext } from "../context.mjs";
|
|
4
|
+
import { invalidateCMSEntryCache } from "./cache.mjs";
|
|
5
|
+
import {
|
|
6
|
+
getCMSDb,
|
|
7
|
+
nanoid,
|
|
8
|
+
getCMSConfig,
|
|
9
|
+
resolveCollectionApproval,
|
|
10
|
+
getCMSTenantId,
|
|
11
|
+
cmsEntryTbl,
|
|
12
|
+
cmsRevisionTbl
|
|
13
|
+
} from "./common.mjs";
|
|
14
|
+
import { syncEntryToGit } from "./git.mjs";
|
|
15
|
+
import { processMarkdown } from "./markdown.mjs";
|
|
16
|
+
import { assertSafeCmsSlug } from "./path.mjs";
|
|
17
|
+
import { rowToEntry } from "./queries.mjs";
|
|
18
|
+
import {
|
|
19
|
+
isReferenceValue,
|
|
20
|
+
validateAndNormalizeReferenceFields,
|
|
21
|
+
validateAndNormalizeComponentFields
|
|
22
|
+
} from "./references.mjs";
|
|
23
|
+
import { pruneRevisions } from "./revisions.mjs";
|
|
24
|
+
import { syncCMSEntryTags } from "./taxonomy.mjs";
|
|
25
|
+
export async function createCMSEntry(event, collectionId, data) {
|
|
26
|
+
const db = getCMSDb(event);
|
|
27
|
+
const cmsConfig = getCMSConfig(event);
|
|
28
|
+
const isSingleton = cmsConfig.collections?.[collectionId]?.singleton;
|
|
29
|
+
if (isSingleton) {
|
|
30
|
+
const existing = await db.prepare(`SELECT COUNT(*) as total FROM ${cmsEntryTbl(event)} WHERE collection_id = ?`).bind(collectionId).first();
|
|
31
|
+
if (existing && existing.total > 0) {
|
|
32
|
+
throw createError({
|
|
33
|
+
statusCode: 409,
|
|
34
|
+
message: `Collection '${collectionId}' is a singleton and already has an entry.`
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
const id = data.id || nanoid();
|
|
39
|
+
const slug = assertSafeCmsSlug(data.slug);
|
|
40
|
+
const now = Date.now();
|
|
41
|
+
const rawContent = data.contentMd ?? data.content ?? "";
|
|
42
|
+
const { ast, html: contentHtml } = await processMarkdown(rawContent);
|
|
43
|
+
const metadata = data.metadata || {};
|
|
44
|
+
await validateAndNormalizeReferenceFields(event, collectionId, metadata);
|
|
45
|
+
await validateAndNormalizeComponentFields(event, collectionId, metadata);
|
|
46
|
+
const metadataJson = JSON.stringify(metadata);
|
|
47
|
+
const publishedAt = data.status === "published" ? data.publishedAt ?? now : data.status === "scheduled" && data.publishedAt ? data.publishedAt : data.publishedAt ?? null;
|
|
48
|
+
const tenantId = getCMSTenantId(event);
|
|
49
|
+
const existingSlug = await db.prepare(
|
|
50
|
+
`SELECT id FROM ${cmsEntryTbl(event)} WHERE collection_id = ? AND slug = ? ${tenantId ? "AND (tenant_id = ? OR tenant_id IS NULL)" : ""} LIMIT 1`
|
|
51
|
+
).bind(...tenantId ? [collectionId, slug, tenantId] : [collectionId, slug]).first();
|
|
52
|
+
if (existingSlug?.id) {
|
|
53
|
+
throw createError({
|
|
54
|
+
statusCode: 409,
|
|
55
|
+
message: `An entry with slug '${slug}' already exists in collection '${collectionId}'.`
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
const words = rawContent.trim() ? rawContent.trim().split(/\s+/).length : 0;
|
|
59
|
+
const calculatedReadingTime = Math.max(1, Math.ceil(words / 200));
|
|
60
|
+
const readingTime = data.readingTime ?? metadata.readingTime ?? calculatedReadingTime;
|
|
61
|
+
try {
|
|
62
|
+
await db.prepare(
|
|
63
|
+
`INSERT INTO ${cmsEntryTbl(event)}
|
|
64
|
+
(id, collection_id, slug, title, description, cover_image, tags, "order", content_md, content_html, metadata_json, status, source, author_id, category_id, sub_category_id, featured, view_count, reading_time, published_at, created_at, updated_at, tenant_id)
|
|
65
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
|
66
|
+
).bind(
|
|
67
|
+
id,
|
|
68
|
+
collectionId,
|
|
69
|
+
slug,
|
|
70
|
+
data.title,
|
|
71
|
+
data.description ?? null,
|
|
72
|
+
data.coverImage ?? null,
|
|
73
|
+
data.tags ?? null,
|
|
74
|
+
data.order ?? 0,
|
|
75
|
+
rawContent,
|
|
76
|
+
contentHtml,
|
|
77
|
+
metadataJson,
|
|
78
|
+
data.status || "draft",
|
|
79
|
+
data.source || "db",
|
|
80
|
+
data.authorId ?? null,
|
|
81
|
+
data.categoryId ?? null,
|
|
82
|
+
data.subCategoryId ?? null,
|
|
83
|
+
data.featured ? 1 : 0,
|
|
84
|
+
data.viewCount ?? 0,
|
|
85
|
+
readingTime,
|
|
86
|
+
publishedAt,
|
|
87
|
+
now,
|
|
88
|
+
now,
|
|
89
|
+
tenantId
|
|
90
|
+
).run();
|
|
91
|
+
} catch (err) {
|
|
92
|
+
if (err?.message?.includes("UNIQUE constraint failed")) {
|
|
93
|
+
throw createError({
|
|
94
|
+
statusCode: 409,
|
|
95
|
+
message: `An entry with slug "${data.slug}" already exists in collection "${collectionId}".`
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
throw err;
|
|
99
|
+
}
|
|
100
|
+
const entry = {
|
|
101
|
+
id,
|
|
102
|
+
collectionId,
|
|
103
|
+
slug,
|
|
104
|
+
title: data.title,
|
|
105
|
+
description: data.description ?? null,
|
|
106
|
+
coverImage: data.coverImage ?? null,
|
|
107
|
+
tags: data.tags ?? null,
|
|
108
|
+
order: data.order ?? 0,
|
|
109
|
+
contentMd: rawContent,
|
|
110
|
+
contentHtml,
|
|
111
|
+
metadataJson,
|
|
112
|
+
metadata,
|
|
113
|
+
body: ast ? { ...ast, value: rawContent, content: rawContent } : void 0,
|
|
114
|
+
status: data.status || "draft",
|
|
115
|
+
source: "db",
|
|
116
|
+
filePath: null,
|
|
117
|
+
contentHash: null,
|
|
118
|
+
authorId: data.authorId ?? null,
|
|
119
|
+
categoryId: data.categoryId ?? void 0,
|
|
120
|
+
subCategoryId: data.subCategoryId ?? void 0,
|
|
121
|
+
featured: Boolean(data.featured),
|
|
122
|
+
viewCount: data.viewCount ?? 0,
|
|
123
|
+
readingTime,
|
|
124
|
+
publishedAt,
|
|
125
|
+
tenantId: tenantId ?? null,
|
|
126
|
+
createdAt: now,
|
|
127
|
+
updatedAt: now
|
|
128
|
+
};
|
|
129
|
+
const gitResult = await syncEntryToGit(event, collectionId, entry, "create");
|
|
130
|
+
if (gitResult?.filePath) {
|
|
131
|
+
entry.filePath = gitResult.filePath;
|
|
132
|
+
entry.contentHash = gitResult.contentHash || null;
|
|
133
|
+
entry.source = "file";
|
|
134
|
+
}
|
|
135
|
+
await invalidateCMSEntryCache(
|
|
136
|
+
event,
|
|
137
|
+
collectionId,
|
|
138
|
+
[slug, entry.id].filter(Boolean)
|
|
139
|
+
);
|
|
140
|
+
await syncCMSEntryTags(event, null, data.tags ?? null).catch(() => {
|
|
141
|
+
});
|
|
142
|
+
fireCMSWebhooks(getCMSConfig(event), collectionId, "create", entry).catch(console.warn);
|
|
143
|
+
return entry;
|
|
144
|
+
}
|
|
145
|
+
export async function updateCMSEntry(event, entryId, data) {
|
|
146
|
+
const db = getCMSDb(event);
|
|
147
|
+
const now = Date.now();
|
|
148
|
+
const existing = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
|
|
149
|
+
if (!existing) throw createError({ statusCode: 404, message: "Entry not found" });
|
|
150
|
+
const tenantId = getCMSTenantId(event);
|
|
151
|
+
if (tenantId && existing.tenant_id !== tenantId) {
|
|
152
|
+
throw createError({
|
|
153
|
+
statusCode: 403,
|
|
154
|
+
message: "Forbidden: Cannot modify an entry belonging to another tenant"
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
const updatedSlug = data.slug !== void 0 ? assertSafeCmsSlug(data.slug) : void 0;
|
|
158
|
+
if (updatedSlug && updatedSlug !== existing.slug) {
|
|
159
|
+
const slugCollision = await db.prepare(
|
|
160
|
+
`SELECT id FROM ${cmsEntryTbl(event)} WHERE collection_id = ? AND slug = ? AND id != ? ${tenantId ? "AND (tenant_id = ? OR tenant_id IS NULL)" : ""} LIMIT 1`
|
|
161
|
+
).bind(
|
|
162
|
+
...tenantId ? [existing.collection_id, updatedSlug, entryId, tenantId] : [existing.collection_id, updatedSlug, entryId]
|
|
163
|
+
).first();
|
|
164
|
+
if (slugCollision?.id) {
|
|
165
|
+
throw createError({
|
|
166
|
+
statusCode: 409,
|
|
167
|
+
message: `An entry with slug '${updatedSlug}' already exists in collection '${existing.collection_id}'.`
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
const contentMd = data.contentMd ?? data.content ?? existing.content_md;
|
|
172
|
+
let contentHtml = existing.content_html;
|
|
173
|
+
if (data.contentMd !== void 0 || data.content !== void 0) {
|
|
174
|
+
const res = await processMarkdown(contentMd);
|
|
175
|
+
contentHtml = res.html;
|
|
176
|
+
}
|
|
177
|
+
let metadataObj = data.metadata;
|
|
178
|
+
if (!metadataObj && existing.metadata_json) {
|
|
179
|
+
try {
|
|
180
|
+
metadataObj = JSON.parse(existing.metadata_json);
|
|
181
|
+
} catch {
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
if (metadataObj && (data.metadata || data.status === "published")) {
|
|
185
|
+
await validateAndNormalizeReferenceFields(event, existing.collection_id, metadataObj);
|
|
186
|
+
await validateAndNormalizeComponentFields(event, existing.collection_id, metadataObj);
|
|
187
|
+
}
|
|
188
|
+
const metadataJson = metadataObj ? JSON.stringify(metadataObj) : existing.metadata_json;
|
|
189
|
+
const status = data.status ?? existing.status;
|
|
190
|
+
let publishedAt;
|
|
191
|
+
if (data.publishedAt !== void 0) {
|
|
192
|
+
publishedAt = data.publishedAt;
|
|
193
|
+
} else if (status === "published") {
|
|
194
|
+
publishedAt = existing.published_at ?? now;
|
|
195
|
+
} else if (status === "scheduled") {
|
|
196
|
+
publishedAt = existing.published_at ?? now;
|
|
197
|
+
} else {
|
|
198
|
+
publishedAt = existing.published_at;
|
|
199
|
+
}
|
|
200
|
+
const words = contentMd.trim() ? contentMd.trim().split(/\s+/).length : 0;
|
|
201
|
+
const calculatedReadingTime = Math.max(1, Math.ceil(words / 200));
|
|
202
|
+
const readingTime = data.readingTime !== void 0 ? data.readingTime : data.contentMd !== void 0 || data.content !== void 0 ? calculatedReadingTime : existing.reading_time || calculatedReadingTime;
|
|
203
|
+
await db.prepare(
|
|
204
|
+
`INSERT INTO ${cmsRevisionTbl(event)} (id, entry_id, title, content_md, metadata_json, author_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)`
|
|
205
|
+
).bind(
|
|
206
|
+
nanoid(),
|
|
207
|
+
entryId,
|
|
208
|
+
existing.title,
|
|
209
|
+
existing.content_md,
|
|
210
|
+
existing.metadata_json,
|
|
211
|
+
existing.author_id,
|
|
212
|
+
now
|
|
213
|
+
).run();
|
|
214
|
+
await db.prepare(
|
|
215
|
+
`UPDATE ${cmsEntryTbl(event)} SET
|
|
216
|
+
slug = COALESCE(?, slug), title = COALESCE(?, title),
|
|
217
|
+
description = COALESCE(?, description), cover_image = COALESCE(?, cover_image),
|
|
218
|
+
tags = COALESCE(?, tags), "order" = COALESCE(?, "order"),
|
|
219
|
+
content_md = ?, content_html = ?, metadata_json = ?,
|
|
220
|
+
status = ?, source = COALESCE(?, source),
|
|
221
|
+
category_id = COALESCE(?, category_id),
|
|
222
|
+
sub_category_id = COALESCE(?, sub_category_id),
|
|
223
|
+
featured = COALESCE(?, featured),
|
|
224
|
+
view_count = COALESCE(?, view_count),
|
|
225
|
+
reading_time = COALESCE(?, reading_time),
|
|
226
|
+
published_at = ?, updated_at = ?
|
|
227
|
+
WHERE id = ?`
|
|
228
|
+
).bind(
|
|
229
|
+
updatedSlug ?? null,
|
|
230
|
+
data.title ?? null,
|
|
231
|
+
data.description ?? null,
|
|
232
|
+
data.coverImage ?? null,
|
|
233
|
+
data.tags ?? null,
|
|
234
|
+
data.order ?? null,
|
|
235
|
+
contentMd,
|
|
236
|
+
contentHtml,
|
|
237
|
+
metadataJson,
|
|
238
|
+
status,
|
|
239
|
+
data.source ?? null,
|
|
240
|
+
data.categoryId !== void 0 ? data.categoryId : null,
|
|
241
|
+
data.subCategoryId !== void 0 ? data.subCategoryId : null,
|
|
242
|
+
data.featured !== void 0 ? data.featured ? 1 : 0 : null,
|
|
243
|
+
data.viewCount !== void 0 ? data.viewCount : null,
|
|
244
|
+
readingTime ?? null,
|
|
245
|
+
publishedAt,
|
|
246
|
+
now,
|
|
247
|
+
entryId
|
|
248
|
+
).run();
|
|
249
|
+
const config = getCMSConfig(event);
|
|
250
|
+
const maxRevisions = typeof config.revisions === "object" ? config.revisions.max ?? 10 : 10;
|
|
251
|
+
await pruneRevisions(event, entryId, maxRevisions);
|
|
252
|
+
const updated = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
|
|
253
|
+
const updatedEntry = rowToEntry(updated);
|
|
254
|
+
const gitResult = await syncEntryToGit(event, updatedEntry.collectionId, updatedEntry, "update");
|
|
255
|
+
if (gitResult?.filePath) {
|
|
256
|
+
updatedEntry.filePath = gitResult.filePath;
|
|
257
|
+
updatedEntry.contentHash = gitResult.contentHash || null;
|
|
258
|
+
updatedEntry.source = "file";
|
|
259
|
+
}
|
|
260
|
+
await invalidateCMSEntryCache(
|
|
261
|
+
event,
|
|
262
|
+
updatedEntry.collectionId,
|
|
263
|
+
[
|
|
264
|
+
updatedEntry.slug,
|
|
265
|
+
updatedEntry.id,
|
|
266
|
+
existing.slug,
|
|
267
|
+
existing.id
|
|
268
|
+
].filter(Boolean)
|
|
269
|
+
);
|
|
270
|
+
await syncCMSEntryTags(
|
|
271
|
+
event,
|
|
272
|
+
existing.tags,
|
|
273
|
+
data.tags !== void 0 ? data.tags : existing.tags
|
|
274
|
+
).catch(() => {
|
|
275
|
+
});
|
|
276
|
+
fireCMSWebhooks(getCMSConfig(event), updatedEntry.collectionId, "update", updatedEntry).catch(
|
|
277
|
+
console.warn
|
|
278
|
+
);
|
|
279
|
+
return updatedEntry;
|
|
280
|
+
}
|
|
281
|
+
async function nullifyOrphanedReferences(event, deletedEntryId) {
|
|
282
|
+
const db = getCMSDb(event);
|
|
283
|
+
try {
|
|
284
|
+
const tenantId = getCMSTenantId(event);
|
|
285
|
+
const tenantClause = tenantId ? " AND (tenant_id = ? OR tenant_id IS NULL)" : "";
|
|
286
|
+
const searchPattern = `%"${deletedEntryId}"%`;
|
|
287
|
+
const binds = tenantId ? [searchPattern, tenantId] : [searchPattern];
|
|
288
|
+
const rows = (await db.prepare(
|
|
289
|
+
`SELECT id, collection_id, slug, metadata_json FROM ${cmsEntryTbl(event)}
|
|
290
|
+
WHERE json_extract(metadata_json, '$') IS NOT NULL
|
|
291
|
+
AND metadata_json LIKE ?${tenantClause}`
|
|
292
|
+
).bind(...binds).all()).results;
|
|
293
|
+
for (const row of rows) {
|
|
294
|
+
let meta;
|
|
295
|
+
try {
|
|
296
|
+
meta = JSON.parse(row.metadata_json);
|
|
297
|
+
} catch {
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
let changed = false;
|
|
301
|
+
for (const [key, value] of Object.entries(meta)) {
|
|
302
|
+
if (isReferenceValue(value) && value.id === deletedEntryId) {
|
|
303
|
+
meta[key] = null;
|
|
304
|
+
changed = true;
|
|
305
|
+
} else if (Array.isArray(value)) {
|
|
306
|
+
const filtered = value.filter(
|
|
307
|
+
(item) => !(isReferenceValue(item) && item.id === deletedEntryId)
|
|
308
|
+
);
|
|
309
|
+
if (filtered.length !== value.length) {
|
|
310
|
+
meta[key] = filtered;
|
|
311
|
+
changed = true;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
if (changed) {
|
|
316
|
+
await db.prepare(`UPDATE ${cmsEntryTbl(event)} SET metadata_json = ? WHERE id = ?`).bind(JSON.stringify(meta), row.id).run();
|
|
317
|
+
await invalidateCMSEntryCache(event, row.collection_id, row.slug);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
} catch (err) {
|
|
321
|
+
console.warn("[qarpeo:cms] nullifyOrphanedReferences failed:", err);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
export async function deleteCMSEntry(event, entryId) {
|
|
325
|
+
const db = getCMSDb(event);
|
|
326
|
+
const existing = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
|
|
327
|
+
if (!existing) throw createError({ statusCode: 404, message: "Entry not found" });
|
|
328
|
+
const tenantId = getCMSTenantId(event);
|
|
329
|
+
if (tenantId && existing.tenant_id !== tenantId) {
|
|
330
|
+
throw createError({
|
|
331
|
+
statusCode: 403,
|
|
332
|
+
message: "Forbidden: Cannot delete an entry belonging to another tenant"
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
await db.batch([
|
|
336
|
+
db.prepare(`DELETE FROM ${cmsRevisionTbl(event)} WHERE entry_id = ?`).bind(entryId),
|
|
337
|
+
db.prepare(`DELETE FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId)
|
|
338
|
+
]);
|
|
339
|
+
if (existing) {
|
|
340
|
+
await nullifyOrphanedReferences(event, entryId);
|
|
341
|
+
await syncCMSEntryTags(event, existing.tags, null).catch(() => {
|
|
342
|
+
});
|
|
343
|
+
await invalidateCMSEntryCache(
|
|
344
|
+
event,
|
|
345
|
+
existing.collection_id,
|
|
346
|
+
[existing.slug, existing.id].filter(Boolean)
|
|
347
|
+
);
|
|
348
|
+
await syncEntryToGit(
|
|
349
|
+
event,
|
|
350
|
+
existing.collection_id,
|
|
351
|
+
rowToEntry(existing),
|
|
352
|
+
"delete"
|
|
353
|
+
).catch((err) => console.warn("[qarpeo:cms] Git sync on delete failed:", err));
|
|
354
|
+
fireCMSWebhooks(
|
|
355
|
+
getCMSConfig(event),
|
|
356
|
+
existing.collection_id,
|
|
357
|
+
"delete",
|
|
358
|
+
rowToEntry(existing)
|
|
359
|
+
).catch(console.warn);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
export async function publishCMSEntry(event, entryId, targetStatus, targetPublishedAt) {
|
|
363
|
+
const db = getCMSDb(event);
|
|
364
|
+
const now = Date.now();
|
|
365
|
+
const existing = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
|
|
366
|
+
if (!existing) {
|
|
367
|
+
throw createError({ statusCode: 404, message: "Entry not found" });
|
|
368
|
+
}
|
|
369
|
+
const tenantId = getCMSTenantId(event);
|
|
370
|
+
if (tenantId && existing.tenant_id !== tenantId) {
|
|
371
|
+
throw createError({
|
|
372
|
+
statusCode: 403,
|
|
373
|
+
message: "Forbidden: Cannot publish an entry belonging to another tenant"
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
const publishedAt = targetStatus === "published" ? targetPublishedAt ?? existing.published_at ?? now : targetStatus === "scheduled" ? targetPublishedAt ?? existing.published_at ?? now : null;
|
|
377
|
+
const collectionId = existing.collection_id;
|
|
378
|
+
const config = getCMSConfig(event);
|
|
379
|
+
const colConfig = config.collections[collectionId] || {};
|
|
380
|
+
const approval = resolveCollectionApproval(colConfig, config.approval);
|
|
381
|
+
let metadataJson = existing.metadata_json || "{}";
|
|
382
|
+
if ((targetStatus === "published" || targetStatus === "scheduled") && approval) {
|
|
383
|
+
const auth = await getAuthContext(event);
|
|
384
|
+
const userRole = auth?.role || "user";
|
|
385
|
+
const isAuthorized = auth?.isAdmin || approval.roles?.includes(userRole);
|
|
386
|
+
if (!isAuthorized) {
|
|
387
|
+
throw createError({
|
|
388
|
+
statusCode: 403,
|
|
389
|
+
message: `${targetStatus === "scheduled" ? "Scheduling" : "Publishing"} in "${collectionId}" requires one of the following approver roles: ${approval.roles?.join(", ")}.`
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
if (!approval.allowSelfApproval && existing.author_id && auth?.user?.id === existing.author_id) {
|
|
393
|
+
throw createError({
|
|
394
|
+
statusCode: 403,
|
|
395
|
+
message: `Self-approval is disabled for "${collectionId}". Another team member must approve this entry.`
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
let metaObj = {};
|
|
399
|
+
try {
|
|
400
|
+
metaObj = JSON.parse(metadataJson);
|
|
401
|
+
} catch {
|
|
402
|
+
}
|
|
403
|
+
metaObj._approval = {
|
|
404
|
+
...metaObj._approval,
|
|
405
|
+
approvedBy: auth?.user?.id || null,
|
|
406
|
+
approvedByName: auth?.user?.name || auth?.user?.email || "Admin",
|
|
407
|
+
approvedAt: now
|
|
408
|
+
};
|
|
409
|
+
metadataJson = JSON.stringify(metaObj);
|
|
410
|
+
}
|
|
411
|
+
await db.prepare(
|
|
412
|
+
`UPDATE ${cmsEntryTbl(event)} SET status = ?, published_at = ?, metadata_json = ?, updated_at = ? WHERE id = ?`
|
|
413
|
+
).bind(targetStatus, publishedAt, metadataJson, now, entryId).run();
|
|
414
|
+
const updatedRow = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
|
|
415
|
+
if (updatedRow) {
|
|
416
|
+
const updated = rowToEntry(updatedRow);
|
|
417
|
+
await invalidateCMSEntryCache(
|
|
418
|
+
event,
|
|
419
|
+
collectionId,
|
|
420
|
+
[
|
|
421
|
+
updated.slug,
|
|
422
|
+
updated.id,
|
|
423
|
+
existing.slug,
|
|
424
|
+
existing.id
|
|
425
|
+
].filter(Boolean)
|
|
426
|
+
);
|
|
427
|
+
await syncEntryToGit(
|
|
428
|
+
event,
|
|
429
|
+
updated.collectionId,
|
|
430
|
+
updated,
|
|
431
|
+
targetStatus === "published" ? "publish" : "update"
|
|
432
|
+
);
|
|
433
|
+
const webhookEvent = targetStatus === "published" ? "publish" : targetStatus === "scheduled" ? "update" : "unpublish";
|
|
434
|
+
fireCMSWebhooks(config, updated.collectionId, webhookEvent, updated).catch(console.warn);
|
|
435
|
+
if (targetStatus === "published" || targetStatus === "draft") {
|
|
436
|
+
fireCMSDeployTrigger(
|
|
437
|
+
config,
|
|
438
|
+
updated.collectionId,
|
|
439
|
+
targetStatus === "published" ? "publish" : "unpublish"
|
|
440
|
+
).catch(console.warn);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
export async function publishDueScheduledEntries(event) {
|
|
445
|
+
const db = getCMSDb(event);
|
|
446
|
+
if (!db) {
|
|
447
|
+
return [];
|
|
448
|
+
}
|
|
449
|
+
const now = Date.now();
|
|
450
|
+
const config = getCMSConfig(event);
|
|
451
|
+
const rows = await db.prepare(
|
|
452
|
+
`SELECT * FROM ${cmsEntryTbl(event)} WHERE status = 'scheduled' AND published_at IS NOT NULL AND published_at <= ?`
|
|
453
|
+
).bind(now).all();
|
|
454
|
+
const entriesToPublish = rows.results || [];
|
|
455
|
+
const publishedEntries = [];
|
|
456
|
+
for (const row of entriesToPublish) {
|
|
457
|
+
const entryId = row.id;
|
|
458
|
+
const collectionId = row.collection_id;
|
|
459
|
+
await db.prepare(`UPDATE ${cmsEntryTbl(event)} SET status = 'published', updated_at = ? WHERE id = ?`).bind(now, entryId).run();
|
|
460
|
+
const updatedRow = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
|
|
461
|
+
if (updatedRow) {
|
|
462
|
+
const entry = rowToEntry(updatedRow);
|
|
463
|
+
publishedEntries.push(entry);
|
|
464
|
+
await invalidateCMSEntryCache(
|
|
465
|
+
event,
|
|
466
|
+
collectionId,
|
|
467
|
+
[
|
|
468
|
+
entry.slug,
|
|
469
|
+
entry.id,
|
|
470
|
+
row.slug,
|
|
471
|
+
row.id
|
|
472
|
+
].filter(Boolean)
|
|
473
|
+
);
|
|
474
|
+
await syncEntryToGit(event, collectionId, entry, "publish").catch(console.warn);
|
|
475
|
+
fireCMSWebhooks(config, collectionId, "publish", entry).catch(console.warn);
|
|
476
|
+
fireCMSDeployTrigger(config, collectionId, "publish").catch(console.warn);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
return publishedEntries;
|
|
480
|
+
}
|
|
481
|
+
export async function submitCMSEntryForReview(event, entryId, note) {
|
|
482
|
+
const db = getCMSDb(event);
|
|
483
|
+
const now = Date.now();
|
|
484
|
+
const existing = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
|
|
485
|
+
if (!existing) throw createError({ statusCode: 404, message: "Entry not found" });
|
|
486
|
+
const tenantId = getCMSTenantId(event);
|
|
487
|
+
if (tenantId && existing.tenant_id !== tenantId) {
|
|
488
|
+
throw createError({
|
|
489
|
+
statusCode: 403,
|
|
490
|
+
message: "Forbidden: Cannot modify an entry belonging to another tenant"
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
const auth = await getAuthContext(event);
|
|
494
|
+
let metaObj = {};
|
|
495
|
+
try {
|
|
496
|
+
metaObj = JSON.parse(existing.metadata_json || "{}");
|
|
497
|
+
} catch {
|
|
498
|
+
}
|
|
499
|
+
metaObj._approval = {
|
|
500
|
+
...metaObj._approval,
|
|
501
|
+
submittedBy: auth?.user?.id || null,
|
|
502
|
+
submittedByName: auth?.user?.name || auth?.user?.email || "Editor",
|
|
503
|
+
submittedAt: now,
|
|
504
|
+
submissionNote: note || null
|
|
505
|
+
};
|
|
506
|
+
const metadataJson = JSON.stringify(metaObj);
|
|
507
|
+
await db.prepare(
|
|
508
|
+
`INSERT INTO ${cmsRevisionTbl(event)} (id, entry_id, title, content_md, metadata_json, author_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)`
|
|
509
|
+
).bind(
|
|
510
|
+
nanoid(),
|
|
511
|
+
entryId,
|
|
512
|
+
existing.title,
|
|
513
|
+
existing.content_md,
|
|
514
|
+
metadataJson,
|
|
515
|
+
auth?.user?.id || existing.author_id,
|
|
516
|
+
now
|
|
517
|
+
).run();
|
|
518
|
+
await db.prepare(
|
|
519
|
+
`UPDATE ${cmsEntryTbl(event)} SET status = 'pending_review', metadata_json = ?, updated_at = ? WHERE id = ?`
|
|
520
|
+
).bind(metadataJson, now, entryId).run();
|
|
521
|
+
const updated = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
|
|
522
|
+
return rowToEntry(updated);
|
|
523
|
+
}
|
|
524
|
+
export async function rejectCMSEntryReview(event, entryId, reason) {
|
|
525
|
+
const db = getCMSDb(event);
|
|
526
|
+
const now = Date.now();
|
|
527
|
+
const existing = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
|
|
528
|
+
if (!existing) throw createError({ statusCode: 404, message: "Entry not found" });
|
|
529
|
+
const tenantId = getCMSTenantId(event);
|
|
530
|
+
if (tenantId && existing.tenant_id !== tenantId) {
|
|
531
|
+
throw createError({
|
|
532
|
+
statusCode: 403,
|
|
533
|
+
message: "Forbidden: Cannot modify an entry belonging to another tenant"
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
const collectionId = existing.collection_id;
|
|
537
|
+
const config = getCMSConfig(event);
|
|
538
|
+
const colConfig = config.collections[collectionId] || {};
|
|
539
|
+
const approval = resolveCollectionApproval(colConfig, config.approval);
|
|
540
|
+
const auth = await getAuthContext(event);
|
|
541
|
+
if (approval) {
|
|
542
|
+
const userRole = auth?.role || "user";
|
|
543
|
+
const isAuthorized = auth?.isAdmin || approval.roles?.includes(userRole);
|
|
544
|
+
if (!isAuthorized) {
|
|
545
|
+
throw createError({
|
|
546
|
+
statusCode: 403,
|
|
547
|
+
message: `Only reviewers with roles [${approval.roles?.join(", ")}] can request changes on entries in "${collectionId}".`
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
let metaObj = {};
|
|
552
|
+
try {
|
|
553
|
+
metaObj = JSON.parse(existing.metadata_json || "{}");
|
|
554
|
+
} catch {
|
|
555
|
+
}
|
|
556
|
+
metaObj._approval = {
|
|
557
|
+
...metaObj._approval,
|
|
558
|
+
rejectedBy: auth?.user?.id || null,
|
|
559
|
+
rejectedByName: auth?.user?.name || auth?.user?.email || "Reviewer",
|
|
560
|
+
rejectedAt: now,
|
|
561
|
+
rejectionReason: reason || null
|
|
562
|
+
};
|
|
563
|
+
const metadataJson = JSON.stringify(metaObj);
|
|
564
|
+
await db.prepare(
|
|
565
|
+
`UPDATE ${cmsEntryTbl(event)} SET status = 'draft', metadata_json = ?, updated_at = ? WHERE id = ?`
|
|
566
|
+
).bind(metadataJson, now, entryId).run();
|
|
567
|
+
const updated = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
|
|
568
|
+
return rowToEntry(updated);
|
|
569
|
+
}
|
|
@@ -1,4 +1,12 @@
|
|
|
1
1
|
import type { CMSHeadingLink } from "../../../../types";
|
|
2
|
+
/**
|
|
3
|
+
* Asserts that a CMS slug is safe and valid:
|
|
4
|
+
* - Must be a non-empty string <= 256 chars
|
|
5
|
+
* - Cannot start or end with slash or dot
|
|
6
|
+
* - Cannot contain backslashes, directory traversal (".."), or control characters
|
|
7
|
+
* - Each segment between slashes must match URL-safe characters: [a-zA-Z0-9_.-]
|
|
8
|
+
*/
|
|
9
|
+
export declare function assertSafeCmsSlug(slug: unknown): string;
|
|
2
10
|
/** Converts a heading text to a URL-safe slug ID. e.g. "Getting Started" → "getting-started" */
|
|
3
11
|
export declare function slugifyHeading(text: string): string;
|
|
4
12
|
/**
|
|
@@ -1,3 +1,26 @@
|
|
|
1
|
+
import { createError } from "nuxt/server";
|
|
2
|
+
export function assertSafeCmsSlug(slug) {
|
|
3
|
+
if (typeof slug !== "string" || !slug.trim()) {
|
|
4
|
+
throw createError({ statusCode: 400, message: "Slug is required and must be a non-empty string" });
|
|
5
|
+
}
|
|
6
|
+
const trimmed = slug.trim();
|
|
7
|
+
if (trimmed.length > 256) {
|
|
8
|
+
throw createError({ statusCode: 400, message: "Slug exceeds maximum length of 256 characters" });
|
|
9
|
+
}
|
|
10
|
+
if (trimmed.includes("\\") || trimmed.includes("..") || /[\x00-\x1f\x7f]/.test(trimmed)) {
|
|
11
|
+
throw createError({ statusCode: 400, message: "Slug contains invalid characters or path traversal sequences" });
|
|
12
|
+
}
|
|
13
|
+
if (trimmed.startsWith("/") || trimmed.endsWith("/") || trimmed.startsWith(".") || trimmed.endsWith(".")) {
|
|
14
|
+
throw createError({ statusCode: 400, message: "Slug cannot start or end with slashes or dots" });
|
|
15
|
+
}
|
|
16
|
+
const segments = trimmed.split("/");
|
|
17
|
+
for (const seg of segments) {
|
|
18
|
+
if (!seg || seg === "." || seg === ".." || !/^[a-zA-Z0-9_.-]+$/.test(seg)) {
|
|
19
|
+
throw createError({ statusCode: 400, message: `Invalid slug segment: "${seg}"` });
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return trimmed;
|
|
23
|
+
}
|
|
1
24
|
export function slugifyHeading(text) {
|
|
2
25
|
return text.toLowerCase().replace(/[^\w\s-]/g, "").replace(/[\s_]+/g, "-").replace(/^-+|-+$/g, "");
|
|
3
26
|
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type RequestEvent } from "nuxt/server";
|
|
2
|
+
import type { CMSEntry, CMSQueryOptions } from "../../../../types";
|
|
3
|
+
/**
|
|
4
|
+
* Formats a CMSEntry into standard markdown with YAML frontmatter. Omits internal system fields
|
|
5
|
+
* starting with `_`.
|
|
6
|
+
*/
|
|
7
|
+
export declare function formatEntryAsMarkdown(entry: CMSEntry | Record<string, any>): string;
|
|
8
|
+
export declare function projectCMSEntry(entry: CMSEntry | null, fields?: string[] | string): any;
|
|
9
|
+
export declare function rowToEntry(row: Record<string, unknown>): CMSEntry;
|
|
10
|
+
/** Queries entries for a collection with filtering, pagination, and sorting. */
|
|
11
|
+
export declare function queryCMSEntries(event: RequestEvent, collectionId: string, opts?: CMSQueryOptions): Promise<{
|
|
12
|
+
entries: CMSEntry[];
|
|
13
|
+
total: number;
|
|
14
|
+
page: number;
|
|
15
|
+
limit: number;
|
|
16
|
+
}>;
|
|
17
|
+
/**
|
|
18
|
+
* Fetches a single entry by slug or ID. Supports draft preview via authenticated session or HMAC
|
|
19
|
+
* preview token.
|
|
20
|
+
*/
|
|
21
|
+
export declare function getCMSEntry(event: RequestEvent, collectionId: string, slugOrId: string, opts?: {
|
|
22
|
+
preview?: boolean;
|
|
23
|
+
previewToken?: string;
|
|
24
|
+
previewExpires?: string;
|
|
25
|
+
populate?: boolean | string[];
|
|
26
|
+
fields?: string[] | string;
|
|
27
|
+
}): Promise<CMSEntry | null>;
|