@kidecms/core 0.1.11 → 0.14.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/LICENSE +21 -0
- package/admin/components/AssetsGrid.tsx +366 -173
- package/admin/components/BlockEditor.tsx +260 -679
- package/admin/components/CheckboxField.tsx +2 -2
- package/admin/components/CollaborationReviewBar.tsx +384 -0
- package/admin/components/ColorField.tsx +87 -0
- package/admin/components/CommandPalette.tsx +169 -0
- package/admin/components/ContentEditor.tsx +687 -0
- package/admin/components/DocumentActions.tsx +4 -2
- package/admin/components/DocumentsDataTable.tsx +91 -10
- package/admin/components/FieldControl.astro +151 -26
- package/admin/components/FocalPointSelector.tsx +27 -1
- package/admin/components/InternalLinkPicker.tsx +4 -3
- package/admin/components/LinkField.tsx +126 -0
- package/admin/components/RelationField.tsx +105 -26
- package/admin/components/RepeaterInput.tsx +46 -0
- package/admin/components/RichTextEditor.tsx +44 -9
- package/admin/components/SharedSectionBlockField.tsx +93 -0
- package/admin/components/SidebarUserMenu.tsx +1 -1
- package/admin/components/Toast.astro +1 -1
- package/admin/components/TreeItemsEditor.tsx +20 -19
- package/admin/components/TreeSelect.tsx +2 -2
- package/admin/components/YoutubeField.tsx +48 -0
- package/admin/components/block-fields.tsx +777 -0
- package/admin/components/content-block-spec.ts +114 -0
- package/admin/components/slash-command.tsx +242 -0
- package/admin/components/tree-utils.ts +14 -2
- package/admin/components/ui/badge.tsx +2 -3
- package/admin/components/ui/button.tsx +5 -4
- package/admin/components/ui/checkbox.tsx +1 -1
- package/admin/components/ui/input.tsx +1 -1
- package/admin/components/ui/select.tsx +1 -1
- package/admin/components/ui/table.tsx +1 -1
- package/admin/components/ui/textarea.tsx +1 -1
- package/admin/layouts/AdminLayout.astro +323 -123
- package/admin/lib/access.ts +54 -0
- package/admin/lib/collaboration.ts +178 -0
- package/admin/lib/edit-data.ts +448 -0
- package/admin/views/AccessDeniedView.astro +8 -0
- package/admin/views/EditView.astro +706 -0
- package/admin/views/ListView.astro +202 -0
- package/admin/views/RecentView.astro +76 -0
- package/admin/views/SinglesView.astro +65 -0
- package/admin/views/edit/EditScripts.astro +145 -0
- package/admin/views/edit/ReverseReferencesList.astro +68 -0
- package/core/admin.ts +193 -0
- package/core/ai.ts +87 -0
- package/core/api.ts +1392 -0
- package/core/assets.ts +336 -0
- package/core/audit.ts +86 -0
- package/core/auth-config.ts +44 -0
- package/core/auth.ts +303 -0
- package/core/collaboration.ts +276 -0
- package/core/content.ts +27 -0
- package/core/create-admin.ts +28 -0
- package/core/define.ts +623 -0
- package/core/field-model.ts +172 -0
- package/core/generator.ts +519 -0
- package/core/http.ts +42 -0
- package/core/image.ts +219 -0
- package/core/index.ts +211 -0
- package/core/locks.ts +52 -0
- package/core/log.ts +37 -0
- package/core/migrate.ts +278 -0
- package/core/rate-limit.ts +110 -0
- package/core/request-scope.ts +33 -0
- package/core/richtext.ts +1 -0
- package/core/runtime.ts +63 -0
- package/core/schema.ts +32 -0
- package/core/search.ts +489 -0
- package/core/seed.ts +101 -0
- package/core/shared-sections.ts +96 -0
- package/core/tasks.ts +176 -0
- package/core/values.ts +433 -0
- package/core/webhooks.ts +85 -0
- package/core/youtube.ts +39 -0
- package/internals/cli.mjs +34 -0
- package/internals/context.ts +67 -0
- package/internals/create-admin.ts +40 -0
- package/internals/describe.ts +25 -0
- package/internals/eject.ts +144 -0
- package/internals/generator.ts +11 -0
- package/internals/integration.ts +481 -0
- package/internals/mcp.ts +397 -0
- package/internals/project.ts +31 -0
- package/internals/push.ts +160 -0
- package/internals/reindex.ts +11 -0
- package/internals/restore.ts +257 -0
- package/internals/seed.ts +15 -0
- package/internals/upgrade.ts +785 -0
- package/{virtual.d.ts → internals/virtual.d.ts} +39 -5
- package/middleware/auth.ts +130 -17
- package/middleware/push.ts +121 -0
- package/package.json +55 -67
- package/platform/cloudflare/cf-env.ts +60 -0
- package/platform/cloudflare/database.ts +28 -0
- package/platform/cloudflare/globals.d.ts +5 -0
- package/platform/cloudflare/storage.ts +33 -0
- package/platform/cloudflare/uploads-route.ts +37 -0
- package/platform/node/database.ts +39 -0
- package/platform/node/storage.ts +52 -0
- package/routes/admin/[...path].astro +71 -0
- package/routes/{pages/admin → admin}/assets/[id].astro +25 -19
- package/routes/admin/assets/index.astro +90 -0
- package/routes/{pages/admin/login.astro → admin/forgot-password.astro} +21 -19
- package/routes/{pages/admin → admin}/invite.astro +13 -6
- package/routes/admin/login.astro +103 -0
- package/routes/admin/reset-password.astro +73 -0
- package/routes/{pages/admin → admin}/setup.astro +32 -8
- package/routes/api/{cms/[collection] → [collection]}/[...path].ts +67 -15
- package/routes/api/admin/search.ts +89 -0
- package/routes/api/{cms/assets → assets}/[id].ts +24 -14
- package/routes/api/{cms/assets → assets}/index.ts +4 -2
- package/routes/api/assets/upload.ts +147 -0
- package/routes/api/auth/forgot-password.ts +77 -0
- package/routes/api/{cms/auth → auth}/invite.ts +41 -9
- package/routes/api/auth/login.ts +167 -0
- package/routes/api/{cms/auth → auth}/logout.ts +11 -2
- package/routes/api/auth/reset-password.ts +85 -0
- package/routes/api/auth/setup.ts +110 -0
- package/routes/api/auth/sso/[provider]/start.ts +34 -0
- package/routes/api/collaboration/index.ts +106 -0
- package/routes/api/cron/_authorize.ts +25 -0
- package/routes/api/{cms/cron → cron}/publish.ts +3 -9
- package/routes/api/cron/tasks.ts +34 -0
- package/routes/api/forms/submit/[slug].ts +143 -0
- package/routes/api/img/[...path].ts +65 -0
- package/routes/api/{cms/preview → preview}/render.ts +8 -3
- package/routes/api/{cms/references → references}/[collection]/[id].ts +31 -1
- package/routes/api/webhooks/[provider].ts +54 -0
- package/README.md +0 -28
- package/dist/admin.d.ts +0 -33
- package/dist/admin.js +0 -92
- package/dist/ai.d.ts +0 -15
- package/dist/ai.js +0 -70
- package/dist/api.d.ts +0 -14
- package/dist/api.js +0 -833
- package/dist/assets.d.ts +0 -51
- package/dist/assets.js +0 -163
- package/dist/auth.d.ts +0 -30
- package/dist/auth.js +0 -132
- package/dist/content.d.ts +0 -3
- package/dist/content.js +0 -29
- package/dist/create-admin.d.ts +0 -5
- package/dist/create-admin.js +0 -23
- package/dist/define.d.ts +0 -254
- package/dist/define.js +0 -36
- package/dist/generator.d.ts +0 -9
- package/dist/generator.js +0 -370
- package/dist/image.d.ts +0 -9
- package/dist/image.js +0 -69
- package/dist/index.d.ts +0 -28
- package/dist/index.js +0 -16
- package/dist/integration.d.ts +0 -14
- package/dist/integration.js +0 -327
- package/dist/locks.d.ts +0 -7
- package/dist/locks.js +0 -37
- package/dist/richtext.d.ts +0 -1
- package/dist/richtext.js +0 -1
- package/dist/runtime.d.ts +0 -24
- package/dist/runtime.js +0 -26
- package/dist/schema.d.ts +0 -17
- package/dist/schema.js +0 -13
- package/dist/seed.d.ts +0 -2
- package/dist/seed.js +0 -84
- package/dist/values.d.ts +0 -8
- package/dist/values.js +0 -102
- package/dist/webhooks.d.ts +0 -2
- package/dist/webhooks.js +0 -73
- package/routes/api/cms/assets/upload.ts +0 -112
- package/routes/api/cms/auth/login.ts +0 -124
- package/routes/api/cms/auth/setup.ts +0 -77
- package/routes/api/cms/img/[...path].ts +0 -24
- package/routes/pages/admin/[...path].astro +0 -1107
- package/routes/pages/admin/assets/index.astro +0 -63
- /package/routes/api/{cms/ai → ai}/alt-text.ts +0 -0
- /package/routes/api/{cms/ai → ai}/seo.ts +0 -0
- /package/routes/api/{cms/ai → ai}/translate.ts +0 -0
- /package/routes/api/{cms/assets → assets}/folders.ts +0 -0
- /package/routes/api/{cms/locks → locks}/[...path].ts +0 -0
package/core/tasks.ts
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { and, desc, eq, inArray, lte } from "drizzle-orm";
|
|
2
|
+
import { nanoid } from "nanoid";
|
|
3
|
+
|
|
4
|
+
import type { CMSConfig } from "./define";
|
|
5
|
+
import { getDb } from "./runtime";
|
|
6
|
+
import { getSchema } from "./schema";
|
|
7
|
+
|
|
8
|
+
// Durable background tasks ("the database is the queue"): enqueue is a plain
|
|
9
|
+
// insert into cms_outbox, drainTasks claims due rows with an optimistic lease
|
|
10
|
+
// and runs the handler registered in config.integrations.tasks. Handlers throw
|
|
11
|
+
// to retry with exponential backoff and return to complete — delivery is
|
|
12
|
+
// at-least-once, so handlers must tolerate re-runs.
|
|
13
|
+
|
|
14
|
+
const BASE_BACKOFF_MS = 30_000;
|
|
15
|
+
const CLAIM_LEASE_MS = 5 * 60_000;
|
|
16
|
+
const DEFAULT_MAX_ATTEMPTS = 5;
|
|
17
|
+
const DEFAULT_PRUNE_AFTER_MS = 7 * 24 * 60 * 60 * 1000;
|
|
18
|
+
|
|
19
|
+
export type EnqueueTaskOptions = {
|
|
20
|
+
/** Delay before the first attempt (default: due on the next drain). */
|
|
21
|
+
delayMs?: number;
|
|
22
|
+
/** Attempts before the task is marked failed (default 5). */
|
|
23
|
+
maxAttempts?: number;
|
|
24
|
+
/** Skip enqueueing when a pending task with the same key already exists. */
|
|
25
|
+
dedupeKey?: string;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export type DrainResult = { processed: number; succeeded: number; failed: number };
|
|
29
|
+
|
|
30
|
+
// Core-provided task handlers. Dynamic imports avoid a static import cycle.
|
|
31
|
+
const BUILTIN_TASK_HANDLERS: Record<string, (payload: any, ctx: { config: CMSConfig }) => Promise<void>> = {
|
|
32
|
+
"webhook.deliver": async (payload, ctx) => {
|
|
33
|
+
const { deliverWebhookTask } = await import("./webhooks");
|
|
34
|
+
await deliverWebhookTask(payload, ctx);
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const outboxTable = () => getSchema().cmsOutbox;
|
|
39
|
+
|
|
40
|
+
/** Durably enqueue a background task. Returns the task id, or null when deduped. */
|
|
41
|
+
export const enqueueTask = async (
|
|
42
|
+
type: string,
|
|
43
|
+
payload?: unknown,
|
|
44
|
+
options: EnqueueTaskOptions = {},
|
|
45
|
+
): Promise<string | null> => {
|
|
46
|
+
const db = await getDb();
|
|
47
|
+
const outbox = outboxTable();
|
|
48
|
+
|
|
49
|
+
if (options.dedupeKey) {
|
|
50
|
+
const existing = await db
|
|
51
|
+
.select({ _id: outbox._id })
|
|
52
|
+
.from(outbox)
|
|
53
|
+
.where(and(eq(outbox.dedupeKey, options.dedupeKey), eq(outbox.status, "pending")))
|
|
54
|
+
.limit(1);
|
|
55
|
+
if (existing.length > 0) return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const id = nanoid();
|
|
59
|
+
const timestamp = Date.now();
|
|
60
|
+
await db.insert(outbox).values({
|
|
61
|
+
_id: id,
|
|
62
|
+
type,
|
|
63
|
+
payload: payload === undefined ? null : JSON.stringify(payload),
|
|
64
|
+
status: "pending",
|
|
65
|
+
attempts: 0,
|
|
66
|
+
maxAttempts: options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS,
|
|
67
|
+
nextAttemptAt: timestamp + (options.delayMs ?? 0),
|
|
68
|
+
dedupeKey: options.dedupeKey ?? null,
|
|
69
|
+
createdAt: timestamp,
|
|
70
|
+
updatedAt: timestamp,
|
|
71
|
+
});
|
|
72
|
+
return id;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
/** Run due tasks: claim with a lease, execute the registered handler, retry with backoff. */
|
|
76
|
+
export const drainTasks = async (config: CMSConfig, limit = 25): Promise<DrainResult> => {
|
|
77
|
+
const db = await getDb();
|
|
78
|
+
const outbox = outboxTable();
|
|
79
|
+
const handlers = config.integrations?.tasks ?? {};
|
|
80
|
+
|
|
81
|
+
const due = await db
|
|
82
|
+
.select()
|
|
83
|
+
.from(outbox)
|
|
84
|
+
.where(and(eq(outbox.status, "pending"), lte(outbox.nextAttemptAt, Date.now())))
|
|
85
|
+
.orderBy(outbox.nextAttemptAt)
|
|
86
|
+
.limit(limit);
|
|
87
|
+
|
|
88
|
+
const result: DrainResult = { processed: 0, succeeded: 0, failed: 0 };
|
|
89
|
+
|
|
90
|
+
for (const task of due) {
|
|
91
|
+
// Optimistic claim: bump attempts and lease the row so a concurrent drain skips it.
|
|
92
|
+
const claimed = await db
|
|
93
|
+
.update(outbox)
|
|
94
|
+
.set({
|
|
95
|
+
attempts: task.attempts + 1,
|
|
96
|
+
nextAttemptAt: Date.now() + CLAIM_LEASE_MS,
|
|
97
|
+
updatedAt: Date.now(),
|
|
98
|
+
})
|
|
99
|
+
.where(and(eq(outbox._id, task._id), eq(outbox.status, "pending"), eq(outbox.attempts, task.attempts)))
|
|
100
|
+
.returning({ _id: outbox._id });
|
|
101
|
+
if (claimed.length === 0) continue;
|
|
102
|
+
|
|
103
|
+
result.processed++;
|
|
104
|
+
const attempt = task.attempts + 1;
|
|
105
|
+
const handler = handlers[String(task.type)] ?? BUILTIN_TASK_HANDLERS[String(task.type)];
|
|
106
|
+
|
|
107
|
+
try {
|
|
108
|
+
if (!handler) throw new Error(`No task handler registered for "${task.type}"`);
|
|
109
|
+
const payload = task.payload == null ? undefined : JSON.parse(String(task.payload));
|
|
110
|
+
await handler(payload, { config });
|
|
111
|
+
await db
|
|
112
|
+
.update(outbox)
|
|
113
|
+
.set({ status: "done", lastError: null, updatedAt: Date.now() })
|
|
114
|
+
.where(eq(outbox._id, task._id));
|
|
115
|
+
result.succeeded++;
|
|
116
|
+
} catch (error) {
|
|
117
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
118
|
+
const exhausted = attempt >= task.maxAttempts;
|
|
119
|
+
await db
|
|
120
|
+
.update(outbox)
|
|
121
|
+
.set({
|
|
122
|
+
status: exhausted ? "failed" : "pending",
|
|
123
|
+
lastError: message,
|
|
124
|
+
nextAttemptAt: Date.now() + BASE_BACKOFF_MS * 2 ** (attempt - 1),
|
|
125
|
+
updatedAt: Date.now(),
|
|
126
|
+
})
|
|
127
|
+
.where(eq(outbox._id, task._id));
|
|
128
|
+
if (exhausted) result.failed++;
|
|
129
|
+
console.error(`[tasks] ${task.type} attempt ${attempt}/${task.maxAttempts} failed: ${message}`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
return result;
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const scheduleDedupeKey = (schedule: { task: string; payload?: unknown }) =>
|
|
137
|
+
schedule.payload === undefined
|
|
138
|
+
? `schedule:${schedule.task}`
|
|
139
|
+
: `schedule:${schedule.task}:${JSON.stringify(schedule.payload)}`;
|
|
140
|
+
|
|
141
|
+
/** Enqueue configured recurring tasks whose interval has elapsed since their last run. */
|
|
142
|
+
export const tickSchedules = async (config: CMSConfig): Promise<number> => {
|
|
143
|
+
const schedules = config.integrations?.schedules ?? [];
|
|
144
|
+
if (schedules.length === 0) return 0;
|
|
145
|
+
|
|
146
|
+
const db = await getDb();
|
|
147
|
+
const outbox = outboxTable();
|
|
148
|
+
let scheduled = 0;
|
|
149
|
+
|
|
150
|
+
for (const schedule of schedules) {
|
|
151
|
+
const dedupeKey = scheduleDedupeKey(schedule);
|
|
152
|
+
const latest = await db
|
|
153
|
+
.select({ createdAt: outbox.createdAt })
|
|
154
|
+
.from(outbox)
|
|
155
|
+
.where(eq(outbox.dedupeKey, dedupeKey))
|
|
156
|
+
.orderBy(desc(outbox.createdAt))
|
|
157
|
+
.limit(1);
|
|
158
|
+
|
|
159
|
+
const dueSince = Date.now() - schedule.everyMinutes * 60_000;
|
|
160
|
+
if (latest.length > 0 && Number(latest[0].createdAt) > dueSince) continue;
|
|
161
|
+
|
|
162
|
+
const id = await enqueueTask(schedule.task, schedule.payload, { dedupeKey });
|
|
163
|
+
if (id) scheduled++;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
return scheduled;
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
/** Delete completed AND failed tasks older than the cutoff (default 7 days). */
|
|
170
|
+
export const pruneTasks = async (olderThanMs = DEFAULT_PRUNE_AFTER_MS): Promise<void> => {
|
|
171
|
+
const db = await getDb();
|
|
172
|
+
const outbox = outboxTable();
|
|
173
|
+
await db
|
|
174
|
+
.delete(outbox)
|
|
175
|
+
.where(and(inArray(outbox.status, ["done", "failed"]), lte(outbox.updatedAt, Date.now() - olderThanMs)));
|
|
176
|
+
};
|
package/core/values.ts
ADDED
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ContentBlockNode,
|
|
3
|
+
ContentDocument,
|
|
4
|
+
ContentNode,
|
|
5
|
+
FieldConfig,
|
|
6
|
+
RichTextDocument,
|
|
7
|
+
RichTextNode,
|
|
8
|
+
} from "./define";
|
|
9
|
+
import { cmsImage, cmsSrcset } from "./image";
|
|
10
|
+
|
|
11
|
+
export const cloneValue = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T;
|
|
12
|
+
|
|
13
|
+
export const slugify = (value: string) =>
|
|
14
|
+
value
|
|
15
|
+
.normalize("NFKD")
|
|
16
|
+
.replace(/[^\w\s-]/g, "")
|
|
17
|
+
.trim()
|
|
18
|
+
.toLowerCase()
|
|
19
|
+
.replace(/[\s_-]+/g, "-")
|
|
20
|
+
.replace(/^-+|-+$/g, "");
|
|
21
|
+
|
|
22
|
+
export const escapeHtml = (value: string) =>
|
|
23
|
+
value
|
|
24
|
+
.replaceAll("&", "&")
|
|
25
|
+
.replaceAll("<", "<")
|
|
26
|
+
.replaceAll(">", ">")
|
|
27
|
+
.replaceAll('"', """)
|
|
28
|
+
.replaceAll("'", "'");
|
|
29
|
+
|
|
30
|
+
export const createRichTextFromPlainText = (text: string): RichTextDocument => ({
|
|
31
|
+
type: "root",
|
|
32
|
+
children: text
|
|
33
|
+
.split(/\n{2,}/)
|
|
34
|
+
.map((paragraph) => paragraph.trim())
|
|
35
|
+
.filter(Boolean)
|
|
36
|
+
.map((paragraph) => ({
|
|
37
|
+
type: "paragraph",
|
|
38
|
+
children: paragraph
|
|
39
|
+
.split("\n")
|
|
40
|
+
.map((line, index, lines) => `${line}${index < lines.length - 1 ? "\n" : ""}`)
|
|
41
|
+
.filter(Boolean)
|
|
42
|
+
.map((line) => ({ type: "text", value: line })),
|
|
43
|
+
})),
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
// --- HTML → rich-text AST --------------------------------------------------
|
|
47
|
+
// A small, dependency-free converter so migrations/imports from any HTML source
|
|
48
|
+
// are a one-liner. Maps to the same node shapes renderNode emits below
|
|
49
|
+
// (paragraph | heading | list/list-item | quote | image; inline text carries
|
|
50
|
+
// bold/italic/href). Unknown/unsupported tags are unwrapped, not errored on.
|
|
51
|
+
|
|
52
|
+
const NAMED_ENTITIES: Record<string, string> = {
|
|
53
|
+
amp: "&",
|
|
54
|
+
lt: "<",
|
|
55
|
+
gt: ">",
|
|
56
|
+
quot: '"',
|
|
57
|
+
apos: "'",
|
|
58
|
+
nbsp: " ",
|
|
59
|
+
copy: "©",
|
|
60
|
+
reg: "®",
|
|
61
|
+
trade: "™",
|
|
62
|
+
hellip: "…",
|
|
63
|
+
mdash: "—",
|
|
64
|
+
ndash: "–",
|
|
65
|
+
lsquo: "‘",
|
|
66
|
+
rsquo: "’",
|
|
67
|
+
ldquo: "“",
|
|
68
|
+
rdquo: "”",
|
|
69
|
+
deg: "°",
|
|
70
|
+
times: "×",
|
|
71
|
+
middot: "·",
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const decodeEntities = (text: string): string =>
|
|
75
|
+
text.replace(/&(#x?[0-9a-f]+|[a-z][a-z0-9]*);/gi, (whole, code: string) => {
|
|
76
|
+
if (code[0] === "#") {
|
|
77
|
+
const n = code[1] === "x" || code[1] === "X" ? parseInt(code.slice(2), 16) : parseInt(code.slice(1), 10);
|
|
78
|
+
return Number.isFinite(n) ? String.fromCodePoint(n) : whole;
|
|
79
|
+
}
|
|
80
|
+
return NAMED_ENTITIES[code] ?? NAMED_ENTITIES[code.toLowerCase()] ?? whole;
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
type HtmlEl = { tag: string; attrs: Record<string, string>; children: HtmlChild[] };
|
|
84
|
+
type HtmlChild = HtmlEl | { text: string };
|
|
85
|
+
const isText = (n: HtmlChild): n is { text: string } => "text" in n;
|
|
86
|
+
|
|
87
|
+
const VOID_TAGS = new Set([
|
|
88
|
+
"br",
|
|
89
|
+
"hr",
|
|
90
|
+
"img",
|
|
91
|
+
"input",
|
|
92
|
+
"source",
|
|
93
|
+
"meta",
|
|
94
|
+
"link",
|
|
95
|
+
"col",
|
|
96
|
+
"area",
|
|
97
|
+
"base",
|
|
98
|
+
"embed",
|
|
99
|
+
"wbr",
|
|
100
|
+
]);
|
|
101
|
+
const BLOCK_OR_CONTAINER = new Set([
|
|
102
|
+
"p",
|
|
103
|
+
"pre",
|
|
104
|
+
"ul",
|
|
105
|
+
"ol",
|
|
106
|
+
"li",
|
|
107
|
+
"blockquote",
|
|
108
|
+
"div",
|
|
109
|
+
"section",
|
|
110
|
+
"article",
|
|
111
|
+
"main",
|
|
112
|
+
"header",
|
|
113
|
+
"footer",
|
|
114
|
+
"aside",
|
|
115
|
+
"figure",
|
|
116
|
+
"figcaption",
|
|
117
|
+
"table",
|
|
118
|
+
"img",
|
|
119
|
+
"h1",
|
|
120
|
+
"h2",
|
|
121
|
+
"h3",
|
|
122
|
+
"h4",
|
|
123
|
+
"h5",
|
|
124
|
+
"h6",
|
|
125
|
+
]);
|
|
126
|
+
|
|
127
|
+
const parseAttrs = (raw: string): Record<string, string> => {
|
|
128
|
+
const attrs: Record<string, string> = {};
|
|
129
|
+
const re = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g;
|
|
130
|
+
let m: RegExpExecArray | null;
|
|
131
|
+
while ((m = re.exec(raw))) {
|
|
132
|
+
attrs[m[1].toLowerCase()] = decodeEntities(m[2] ?? m[3] ?? m[4] ?? "");
|
|
133
|
+
}
|
|
134
|
+
return attrs;
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
const buildHtmlTree = (html: string): HtmlEl => {
|
|
138
|
+
const root: HtmlEl = { tag: "#root", attrs: {}, children: [] };
|
|
139
|
+
const stack: HtmlEl[] = [root];
|
|
140
|
+
const re =
|
|
141
|
+
/<!--[\s\S]*?-->|<\/([a-zA-Z][a-zA-Z0-9-]*)\s*>|<([a-zA-Z][a-zA-Z0-9-]*)((?:[^>"']|"[^"]*"|'[^']*')*?)\/?>/g;
|
|
142
|
+
let last = 0;
|
|
143
|
+
let m: RegExpExecArray | null;
|
|
144
|
+
const pushText = (text: string) => {
|
|
145
|
+
if (text) stack[stack.length - 1].children.push({ text });
|
|
146
|
+
};
|
|
147
|
+
while ((m = re.exec(html))) {
|
|
148
|
+
pushText(html.slice(last, m.index));
|
|
149
|
+
last = m.index + m[0].length;
|
|
150
|
+
if (m[0].startsWith("<!--")) continue;
|
|
151
|
+
if (m[1]) {
|
|
152
|
+
const tag = m[1].toLowerCase();
|
|
153
|
+
for (let i = stack.length - 1; i > 0; i--) {
|
|
154
|
+
if (stack[i].tag === tag) {
|
|
155
|
+
stack.length = i;
|
|
156
|
+
break;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
} else if (m[2]) {
|
|
160
|
+
const tag = m[2].toLowerCase();
|
|
161
|
+
const el: HtmlEl = { tag, attrs: parseAttrs(m[3] ?? ""), children: [] };
|
|
162
|
+
stack[stack.length - 1].children.push(el);
|
|
163
|
+
if (!(m[0].endsWith("/>") || VOID_TAGS.has(tag))) stack.push(el);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
pushText(html.slice(last));
|
|
167
|
+
return root;
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
type Marks = { bold?: boolean; italic?: boolean; href?: string };
|
|
171
|
+
|
|
172
|
+
const collectInline = (children: HtmlChild[], marks: Marks = {}, out: RichTextNode[] = []): RichTextNode[] => {
|
|
173
|
+
for (const child of children) {
|
|
174
|
+
if (isText(child)) {
|
|
175
|
+
const value = decodeEntities(child.text).replace(/\s+/g, " ");
|
|
176
|
+
if (value) out.push({ type: "text", value, ...marks });
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
const { tag } = child;
|
|
180
|
+
if (tag === "br") {
|
|
181
|
+
if (out.length) out[out.length - 1].value = `${out[out.length - 1].value ?? ""}\n`;
|
|
182
|
+
} else if (tag === "strong" || tag === "b") {
|
|
183
|
+
collectInline(child.children, { ...marks, bold: true }, out);
|
|
184
|
+
} else if (tag === "em" || tag === "i") {
|
|
185
|
+
collectInline(child.children, { ...marks, italic: true }, out);
|
|
186
|
+
} else if (tag === "a") {
|
|
187
|
+
collectInline(child.children, { ...marks, href: child.attrs.href || marks.href }, out);
|
|
188
|
+
} else if (tag !== "img") {
|
|
189
|
+
collectInline(child.children, marks, out); // span, code, mark, … — unwrap
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return out;
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
const inlineChildren = (children: HtmlChild[]): RichTextNode[] =>
|
|
196
|
+
collectInline(children).filter((leaf) => ((leaf.value as string) ?? "").length > 0);
|
|
197
|
+
|
|
198
|
+
// True when leaves carry real content, not just whitespace between block tags.
|
|
199
|
+
const meaningful = (leaves: RichTextNode[]): boolean =>
|
|
200
|
+
leaves.some((leaf) => String(leaf.value ?? "").trim().length > 0);
|
|
201
|
+
|
|
202
|
+
const walkBlocks = (el: HtmlEl, out: RichTextNode[]): void => {
|
|
203
|
+
for (const child of el.children) {
|
|
204
|
+
if (isText(child)) {
|
|
205
|
+
const leaves = inlineChildren([child]);
|
|
206
|
+
if (meaningful(leaves)) out.push({ type: "paragraph", children: leaves });
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
const { tag } = child;
|
|
210
|
+
if (tag === "p" || tag === "pre") {
|
|
211
|
+
const leaves = inlineChildren(child.children);
|
|
212
|
+
if (meaningful(leaves)) out.push({ type: "paragraph", children: leaves });
|
|
213
|
+
} else if (/^h[1-6]$/.test(tag)) {
|
|
214
|
+
const leaves = inlineChildren(child.children);
|
|
215
|
+
if (meaningful(leaves)) out.push({ type: "heading", level: Number(tag[1]), children: leaves });
|
|
216
|
+
} else if (tag === "ul" || tag === "ol") {
|
|
217
|
+
const items = child.children
|
|
218
|
+
.filter((c): c is HtmlEl => !isText(c) && c.tag === "li")
|
|
219
|
+
.map((li) => ({ type: "list-item", children: inlineChildren(li.children) }))
|
|
220
|
+
.filter((item) => meaningful(item.children));
|
|
221
|
+
if (items.length) out.push({ type: "list", ordered: tag === "ol", children: items });
|
|
222
|
+
} else if (tag === "blockquote") {
|
|
223
|
+
const leaves = inlineChildren(child.children);
|
|
224
|
+
if (meaningful(leaves)) out.push({ type: "quote", children: leaves });
|
|
225
|
+
} else if (tag === "img") {
|
|
226
|
+
if (child.attrs.src) out.push({ type: "image", src: child.attrs.src, alt: child.attrs.alt ?? "" });
|
|
227
|
+
} else if (tag === "hr" || tag === "br") {
|
|
228
|
+
// no structural equivalent — skip
|
|
229
|
+
} else {
|
|
230
|
+
// div/section/figure/table/… — descend for block descendants, else treat as a paragraph
|
|
231
|
+
const hasBlockChild = child.children.some((c) => !isText(c) && BLOCK_OR_CONTAINER.has((c as HtmlEl).tag));
|
|
232
|
+
if (hasBlockChild) {
|
|
233
|
+
walkBlocks(child, out);
|
|
234
|
+
} else {
|
|
235
|
+
const leaves = inlineChildren(child.children);
|
|
236
|
+
if (meaningful(leaves)) out.push({ type: "paragraph", children: leaves });
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Convert an HTML string into the CMS rich-text AST. Forgiving by design — it
|
|
244
|
+
* tolerates malformed markup, unwraps unsupported inline tags, and falls back to
|
|
245
|
+
* plain text when no structure is found. Returns an empty document for empty
|
|
246
|
+
* input. Pair with createRichTextFromPlainText for non-HTML sources.
|
|
247
|
+
*/
|
|
248
|
+
export const htmlToRichText = (html: string | null | undefined): RichTextDocument => {
|
|
249
|
+
if (!html || !html.trim()) return { type: "root", children: [] };
|
|
250
|
+
const children: RichTextNode[] = [];
|
|
251
|
+
walkBlocks(buildHtmlTree(html), children);
|
|
252
|
+
if (!children.length) return createRichTextFromPlainText(decodeEntities(html.replace(/<[^>]+>/g, " ")));
|
|
253
|
+
return { type: "root", children };
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
const SAFE_URL_SCHEMES = new Set(["http:", "https:", "mailto:", "tel:"]);
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Rich text is authored data, so a stored `javascript:` href would execute in every
|
|
260
|
+
* visitor's browser — and in the admin's own preview. Escaping doesn't help: the payload
|
|
261
|
+
* contains no HTML-special characters. Allow only known-safe schemes; relative URLs
|
|
262
|
+
* (`/path`, `#anchor`, `?q=`) carry no scheme and are always fine.
|
|
263
|
+
*/
|
|
264
|
+
export const safeUrl = (value: string): string | null => {
|
|
265
|
+
const trimmed = value.trim();
|
|
266
|
+
if (!trimmed) return null;
|
|
267
|
+
if (/^[/#?]/.test(trimmed)) return trimmed;
|
|
268
|
+
try {
|
|
269
|
+
const { protocol } = new URL(trimmed, "https://example.invalid");
|
|
270
|
+
return SAFE_URL_SCHEMES.has(protocol) ? trimmed : null;
|
|
271
|
+
} catch {
|
|
272
|
+
return null;
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
const renderNode = (node: RichTextNode): string => {
|
|
277
|
+
if (node.type === "text") {
|
|
278
|
+
let content = escapeHtml(String(node.value ?? ""));
|
|
279
|
+
if (node.bold) content = `<strong>${content}</strong>`;
|
|
280
|
+
if (node.italic) content = `<em>${content}</em>`;
|
|
281
|
+
if (node.href) {
|
|
282
|
+
const safeHref = safeUrl(String(node.href));
|
|
283
|
+
if (safeHref) {
|
|
284
|
+
const href = escapeHtml(safeHref);
|
|
285
|
+
const isExternal = safeHref.startsWith("http://") || safeHref.startsWith("https://");
|
|
286
|
+
const target = isExternal ? ' target="_blank" rel="noopener noreferrer"' : "";
|
|
287
|
+
content = `<a href="${href}"${target}>${content}</a>`;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
return content;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
if (node.type === "paragraph") {
|
|
294
|
+
return `<p>${(node.children ?? []).map(renderNode).join("")}</p>`;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
if (node.type === "heading") {
|
|
298
|
+
const level = Math.min(Math.max(Number(node.level ?? 2), 1), 6);
|
|
299
|
+
return `<h${level}>${(node.children ?? []).map(renderNode).join("")}</h${level}>`;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
if (node.type === "list") {
|
|
303
|
+
const tag = node.ordered ? "ol" : "ul";
|
|
304
|
+
return `<${tag}>${(node.children ?? []).map(renderNode).join("")}</${tag}>`;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
if (node.type === "list-item") {
|
|
308
|
+
return `<li>${(node.children ?? []).map(renderNode).join("")}</li>`;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
if (node.type === "quote") {
|
|
312
|
+
return `<blockquote>${(node.children ?? []).map(renderNode).join("")}</blockquote>`;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
if (node.type === "image") {
|
|
316
|
+
const src = String(node.src ?? "");
|
|
317
|
+
const alt = escapeHtml(String(node.alt ?? ""));
|
|
318
|
+
const isLocal = src.startsWith("/uploads/");
|
|
319
|
+
if (isLocal) {
|
|
320
|
+
const sizes = "(max-width: 768px) 100vw, 768px";
|
|
321
|
+
const avif = escapeHtml(cmsSrcset(src, undefined, "avif"));
|
|
322
|
+
const webp = escapeHtml(cmsSrcset(src, undefined, "webp"));
|
|
323
|
+
const fallback = escapeHtml(cmsImage(src, 1024));
|
|
324
|
+
return `<picture><source type="image/avif" srcset="${avif}" sizes="${sizes}" /><source type="image/webp" srcset="${webp}" sizes="${sizes}" /><img src="${fallback}" alt="${alt}" loading="lazy" class="h-auto max-w-full rounded-lg" /></picture>`;
|
|
325
|
+
}
|
|
326
|
+
const safeSrc = safeUrl(src);
|
|
327
|
+
if (!safeSrc) return "";
|
|
328
|
+
return `<img src="${escapeHtml(safeSrc)}" alt="${alt}" loading="lazy" class="max-w-full rounded-lg" />`;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
return "";
|
|
332
|
+
};
|
|
333
|
+
|
|
334
|
+
export const renderRichText = (document?: RichTextDocument | null) => {
|
|
335
|
+
if (!document || document.type !== "root") return "";
|
|
336
|
+
return document.children.map(renderNode).join("");
|
|
337
|
+
};
|
|
338
|
+
|
|
339
|
+
// --- content (mixed rich-text + inline blocks) -----------------------------
|
|
340
|
+
|
|
341
|
+
export type ContentSegment = { kind: "richText"; doc: RichTextDocument } | { kind: "block"; block: ContentBlockNode };
|
|
342
|
+
|
|
343
|
+
const isBlockNode = (node: ContentNode): node is ContentBlockNode => node.type === "block";
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Split a `content` document into an ordered list of segments: runs of prose
|
|
347
|
+
* (grouped into a RichTextDocument so the existing rich-text renderer can handle
|
|
348
|
+
* them) interleaved with inline component blocks. Used by ContentRenderer and the
|
|
349
|
+
* preview route to render mixed content while keeping block rendering in Astro.
|
|
350
|
+
*/
|
|
351
|
+
export const contentSegments = (document?: ContentDocument | null): ContentSegment[] => {
|
|
352
|
+
if (!document || document.type !== "root") return [];
|
|
353
|
+
const segments: ContentSegment[] = [];
|
|
354
|
+
let buffer: RichTextNode[] = [];
|
|
355
|
+
const flush = () => {
|
|
356
|
+
if (buffer.length > 0) {
|
|
357
|
+
segments.push({ kind: "richText", doc: { type: "root", children: buffer } });
|
|
358
|
+
buffer = [];
|
|
359
|
+
}
|
|
360
|
+
};
|
|
361
|
+
for (const node of document.children) {
|
|
362
|
+
if (isBlockNode(node)) {
|
|
363
|
+
flush();
|
|
364
|
+
segments.push({ kind: "block", block: node });
|
|
365
|
+
} else {
|
|
366
|
+
buffer.push(node as RichTextNode);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
flush();
|
|
370
|
+
return segments;
|
|
371
|
+
};
|
|
372
|
+
|
|
373
|
+
/** Extract the inline component blocks from a content document, in order. */
|
|
374
|
+
export const contentBlocks = (document?: ContentDocument | null): ContentBlockNode[] =>
|
|
375
|
+
document?.type === "root" ? document.children.filter(isBlockNode) : [];
|
|
376
|
+
|
|
377
|
+
export const richTextToPlainText = (document?: RichTextDocument | null): string => {
|
|
378
|
+
if (!document?.children) return "";
|
|
379
|
+
|
|
380
|
+
const flatten = (node: RichTextNode): string => {
|
|
381
|
+
if (node.type === "text") {
|
|
382
|
+
return String(node.value ?? "");
|
|
383
|
+
}
|
|
384
|
+
return (node.children ?? []).map(flatten).join("");
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
return document.children.map(flatten).join("\n\n").trim();
|
|
388
|
+
};
|
|
389
|
+
|
|
390
|
+
// Pull readable strings out of a block's `fields` object (text values, nested arrays,
|
|
391
|
+
// rich-text/json sub-fields) so block-only content still yields a usable plain-text summary.
|
|
392
|
+
const extractFieldStrings = (value: unknown): string => {
|
|
393
|
+
if (value == null) return "";
|
|
394
|
+
if (typeof value === "string") return value;
|
|
395
|
+
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
396
|
+
if (Array.isArray(value)) return value.map(extractFieldStrings).filter(Boolean).join(" ");
|
|
397
|
+
if (typeof value === "object") {
|
|
398
|
+
return Object.entries(value as Record<string, unknown>)
|
|
399
|
+
.filter(([key]) => key !== "type")
|
|
400
|
+
.map(([, v]) => extractFieldStrings(v))
|
|
401
|
+
.filter(Boolean)
|
|
402
|
+
.join(" ");
|
|
403
|
+
}
|
|
404
|
+
return "";
|
|
405
|
+
};
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* Plain-text rendering of a `content` document: prose nodes flatten like rich text, and
|
|
409
|
+
* inline component blocks contribute the text of their fields (which richTextToPlainText
|
|
410
|
+
* would otherwise skip). Used for list previews and auto-excerpts.
|
|
411
|
+
*/
|
|
412
|
+
export const contentToPlainText = (document?: ContentDocument | null): string => {
|
|
413
|
+
if (!document?.children) return "";
|
|
414
|
+
return document.children
|
|
415
|
+
.map((node) =>
|
|
416
|
+
node.type === "block"
|
|
417
|
+
? extractFieldStrings((node as ContentBlockNode).fields)
|
|
418
|
+
: richTextToPlainText({ type: "root", children: [node as RichTextNode] }),
|
|
419
|
+
)
|
|
420
|
+
.filter(Boolean)
|
|
421
|
+
.join("\n\n")
|
|
422
|
+
.trim();
|
|
423
|
+
};
|
|
424
|
+
|
|
425
|
+
export const serializeFieldValue = (field: FieldConfig, value: unknown): string => {
|
|
426
|
+
if (value === null || value === undefined) return "";
|
|
427
|
+
if (field.type === "richText") return richTextToPlainText(value as RichTextDocument);
|
|
428
|
+
if (field.type === "content") return contentToPlainText(value as ContentDocument);
|
|
429
|
+
if (field.type === "array") return Array.isArray(value) ? value.map((item) => String(item ?? "")).join(", ") : "";
|
|
430
|
+
if (field.type === "json" || field.type === "blocks") return JSON.stringify(value, null, 2);
|
|
431
|
+
if (field.type === "boolean") return value ? "true" : "false";
|
|
432
|
+
return String(value);
|
|
433
|
+
};
|
package/core/webhooks.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { CMSConfig, WebhookConfig, WebhookContext, WebhookEvent } from "./define";
|
|
2
|
+
import { trackTask } from "./request-scope";
|
|
3
|
+
import { enqueueTask } from "./tasks";
|
|
4
|
+
|
|
5
|
+
const TIMEOUT_MS = 5000;
|
|
6
|
+
|
|
7
|
+
export type WebhookDeliveryRef = {
|
|
8
|
+
webhookName: string;
|
|
9
|
+
event: WebhookEvent;
|
|
10
|
+
collection: string;
|
|
11
|
+
doc: Record<string, unknown>;
|
|
12
|
+
user: WebhookContext["user"];
|
|
13
|
+
timestamp: string;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const buildPayload = (webhook: WebhookConfig, ref: WebhookDeliveryRef) => {
|
|
17
|
+
const context: WebhookContext = {
|
|
18
|
+
user: ref.user,
|
|
19
|
+
event: ref.event,
|
|
20
|
+
collection: ref.collection,
|
|
21
|
+
timestamp: ref.timestamp,
|
|
22
|
+
};
|
|
23
|
+
return webhook.payload
|
|
24
|
+
? webhook.payload(ref.doc, context)
|
|
25
|
+
: { event: ref.event, collection: ref.collection, doc: ref.doc, user: ref.user, timestamp: ref.timestamp };
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/** One delivery attempt as a durable outbox task. URL/headers resolve from live config, never stored. */
|
|
29
|
+
export async function deliverWebhookTask(ref: WebhookDeliveryRef, ctx: { config: CMSConfig }): Promise<void> {
|
|
30
|
+
const webhook = ctx.config.admin?.webhooks?.find((w) => w.name === ref.webhookName);
|
|
31
|
+
if (!webhook) {
|
|
32
|
+
// Config no longer defines this webhook (renamed/removed) — nothing to retry.
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const controller = new AbortController();
|
|
37
|
+
const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
|
38
|
+
try {
|
|
39
|
+
const response = await fetch(webhook.url, {
|
|
40
|
+
method: webhook.method ?? "POST",
|
|
41
|
+
headers: { "Content-Type": "application/json", ...webhook.headers },
|
|
42
|
+
body: JSON.stringify(buildPayload(webhook, ref)),
|
|
43
|
+
signal: controller.signal,
|
|
44
|
+
});
|
|
45
|
+
if (!response.ok) throw new Error(`webhook ${webhook.name} → HTTP ${response.status}`);
|
|
46
|
+
} finally {
|
|
47
|
+
clearTimeout(timeout);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Durably enqueue a delivery reference for every webhook matching this event. */
|
|
52
|
+
export function dispatchWebhooks(
|
|
53
|
+
config: CMSConfig,
|
|
54
|
+
event: WebhookEvent,
|
|
55
|
+
collectionSlug: string,
|
|
56
|
+
doc: Record<string, unknown>,
|
|
57
|
+
user: WebhookContext["user"],
|
|
58
|
+
): void {
|
|
59
|
+
const webhooks = config.admin?.webhooks;
|
|
60
|
+
if (!webhooks || webhooks.length === 0) return;
|
|
61
|
+
|
|
62
|
+
const matching = webhooks.filter(
|
|
63
|
+
(webhook: WebhookConfig) =>
|
|
64
|
+
webhook.events.includes(event) && (!webhook.collections || webhook.collections.includes(collectionSlug)),
|
|
65
|
+
);
|
|
66
|
+
if (matching.length === 0) return;
|
|
67
|
+
|
|
68
|
+
const timestamp = new Date().toISOString();
|
|
69
|
+
for (const webhook of matching) {
|
|
70
|
+
const ref: WebhookDeliveryRef = {
|
|
71
|
+
webhookName: webhook.name,
|
|
72
|
+
event,
|
|
73
|
+
collection: collectionSlug,
|
|
74
|
+
doc,
|
|
75
|
+
user: user ?? null,
|
|
76
|
+
timestamp,
|
|
77
|
+
};
|
|
78
|
+
// If the enqueue itself fails, the event is lost — log loudly rather than swallow it.
|
|
79
|
+
trackTask(
|
|
80
|
+
enqueueTask("webhook.deliver", ref).catch((error) => {
|
|
81
|
+
console.error(`[webhook] failed to enqueue "${webhook.name}" for ${event}/${collectionSlug}:`, error);
|
|
82
|
+
}),
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
}
|