@dyrected/core 2.7.1 → 2.8.1

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.
Files changed (53) hide show
  1. package/dist/app-config-7G-3tF_I.d.cts +2259 -0
  2. package/dist/app-config-7G-3tF_I.d.ts +2259 -0
  3. package/dist/app-config-B3ByBjCN.d.cts +2222 -0
  4. package/dist/app-config-B3ByBjCN.d.ts +2222 -0
  5. package/dist/app-config-B5tYsZaH.d.cts +2404 -0
  6. package/dist/app-config-B5tYsZaH.d.ts +2404 -0
  7. package/dist/app-config-BEuyPktb.d.cts +2556 -0
  8. package/dist/app-config-BEuyPktb.d.ts +2556 -0
  9. package/dist/app-config-BIkjQWzU.d.cts +2218 -0
  10. package/dist/app-config-BIkjQWzU.d.ts +2218 -0
  11. package/dist/app-config-BfpeE3bF.d.cts +2100 -0
  12. package/dist/app-config-BfpeE3bF.d.ts +2100 -0
  13. package/dist/app-config-CCe-yq9q.d.cts +2222 -0
  14. package/dist/app-config-CCe-yq9q.d.ts +2222 -0
  15. package/dist/app-config-CPOs7THF.d.cts +2217 -0
  16. package/dist/app-config-CPOs7THF.d.ts +2217 -0
  17. package/dist/app-config-Ctp454zB.d.cts +2214 -0
  18. package/dist/app-config-Ctp454zB.d.ts +2214 -0
  19. package/dist/app-config-DJmNYgYh.d.cts +2305 -0
  20. package/dist/app-config-DJmNYgYh.d.ts +2305 -0
  21. package/dist/app-config-DO3laV58.d.cts +2397 -0
  22. package/dist/app-config-DO3laV58.d.ts +2397 -0
  23. package/dist/app-config-DZf_mmi9.d.cts +2211 -0
  24. package/dist/app-config-DZf_mmi9.d.ts +2211 -0
  25. package/dist/app-config-SkUoN5JU.d.cts +2192 -0
  26. package/dist/app-config-SkUoN5JU.d.ts +2192 -0
  27. package/dist/app-config-WzqpuZMr.d.cts +2566 -0
  28. package/dist/app-config-WzqpuZMr.d.ts +2566 -0
  29. package/dist/app-config-fEjRm1o9.d.cts +2402 -0
  30. package/dist/app-config-fEjRm1o9.d.ts +2402 -0
  31. package/dist/app-config-oz8H_MOX.d.cts +2224 -0
  32. package/dist/app-config-oz8H_MOX.d.ts +2224 -0
  33. package/dist/chunk-3TRRTN6U.js +3441 -0
  34. package/dist/chunk-5ZIA5COH.js +3414 -0
  35. package/dist/chunk-6TWQ6GTD.js +3480 -0
  36. package/dist/chunk-AQO4HI2Y.js +3204 -0
  37. package/dist/chunk-DFBLNYUH.js +3402 -0
  38. package/dist/chunk-GFFGDHST.js +3543 -0
  39. package/dist/chunk-KEKOEAX6.js +3139 -0
  40. package/dist/chunk-PRQ2RF5C.js +3485 -0
  41. package/dist/chunk-PZMDK3MH.js +3203 -0
  42. package/dist/chunk-SM32ND5M.js +3472 -0
  43. package/dist/chunk-XX7N64NL.js +3550 -0
  44. package/dist/chunk-ZISFMAEL.js +3550 -0
  45. package/dist/index.cjs +439 -9
  46. package/dist/index.d.cts +166 -3
  47. package/dist/index.d.ts +166 -3
  48. package/dist/index.js +53 -1
  49. package/dist/server.cjs +623 -367
  50. package/dist/server.d.cts +26 -7
  51. package/dist/server.d.ts +26 -7
  52. package/dist/server.js +420 -359
  53. package/package.json +1 -1
@@ -0,0 +1,3204 @@
1
+ // src/workflows.ts
2
+ var WORKFLOW_HISTORY_COLLECTION = "__workflow_history";
3
+ var LIFECYCLE_EVENTS_COLLECTION = "__lifecycle_events";
4
+ var EDITOR_CAPABILITIES = ["entry.edit", "entry.submit"];
5
+ var PUBLISHER_CAPABILITIES = ["entry.edit", "entry.submit", "entry.publish", "entry.unpublish"];
6
+ function definePublishingWorkflow(options = {}) {
7
+ const editors = options.editors ?? ["editor"];
8
+ const publishers = options.publishers ?? ["publisher", "admin"];
9
+ return {
10
+ initialState: "draft",
11
+ draftState: "draft",
12
+ states: [
13
+ { name: "draft", label: "Draft", color: "neutral" },
14
+ { name: "in_review", label: "In review", color: "warning" },
15
+ { name: "published", label: "Published", color: "success", published: true }
16
+ ],
17
+ transitions: [
18
+ {
19
+ name: "submit",
20
+ label: "Submit for review",
21
+ from: "draft",
22
+ to: "in_review",
23
+ requiredCapabilities: ["entry.submit"]
24
+ },
25
+ {
26
+ name: "publish",
27
+ label: "Publish",
28
+ from: "in_review",
29
+ to: "published",
30
+ requiredCapabilities: ["entry.publish"]
31
+ },
32
+ {
33
+ name: "reject",
34
+ label: "Request changes",
35
+ from: "in_review",
36
+ to: "draft",
37
+ requiredCapabilities: ["entry.publish"],
38
+ requireComment: true
39
+ },
40
+ {
41
+ name: "unpublish",
42
+ label: "Unpublish",
43
+ from: "published",
44
+ to: "draft",
45
+ requiredCapabilities: ["entry.unpublish"],
46
+ unpublish: true
47
+ }
48
+ ],
49
+ roles: [
50
+ ...editors.map((role) => ({ role, capabilities: [...EDITOR_CAPABILITIES] })),
51
+ ...publishers.map((role) => ({ role, capabilities: [...PUBLISHER_CAPABILITIES] }))
52
+ ]
53
+ };
54
+ }
55
+ function publishingWorkflow() {
56
+ return definePublishingWorkflow();
57
+ }
58
+ function simplePublishingWorkflow() {
59
+ return {
60
+ initialState: "draft",
61
+ draftState: "draft",
62
+ states: [
63
+ { name: "draft", label: "Draft", color: "neutral" },
64
+ { name: "published", label: "Published", color: "success", published: true }
65
+ ],
66
+ transitions: [
67
+ { name: "publish", label: "Publish", from: ["draft", "published"], to: "published" },
68
+ { name: "unpublish", label: "Unpublish", from: "published", to: "draft", unpublish: true }
69
+ ]
70
+ // Intentionally no `roles`: this lightweight workflow (synthesized from
71
+ // `drafts: true`) does no capability-based gating. Draft visibility for a
72
+ // no-roles workflow is handled in `canViewWorkflowDraft`.
73
+ };
74
+ }
75
+ function publicMetadata(meta) {
76
+ const { availableTransitions: _availableTransitions, ...safe } = meta;
77
+ return safe;
78
+ }
79
+ function workflowCapabilities(workflow, user) {
80
+ const capabilities = new Set(Array.isArray(user?.capabilities) ? user.capabilities : []);
81
+ const roles = Array.isArray(user?.roles) ? user.roles : [];
82
+ for (const mapping of workflow.roles ?? []) {
83
+ if (roles.includes(mapping.role)) mapping.capabilities.forEach((capability) => capabilities.add(capability));
84
+ }
85
+ return capabilities;
86
+ }
87
+ function canViewWorkflowDraft(workflow, user) {
88
+ if (!user) return false;
89
+ const capabilities = workflowCapabilities(workflow, user);
90
+ if (capabilities.has("entry.edit")) return true;
91
+ if (workflow.transitions.some(
92
+ (transition) => (transition.requiredCapabilities ?? []).some((capability) => capabilities.has(capability))
93
+ )) {
94
+ return true;
95
+ }
96
+ if (!workflow.roles || workflow.roles.length === 0) return true;
97
+ return false;
98
+ }
99
+ function availableWorkflowTransitions(workflow, state, user) {
100
+ const capabilities = workflowCapabilities(workflow, user);
101
+ return workflow.transitions.filter((transition) => {
102
+ const from = Array.isArray(transition.from) ? transition.from : [transition.from];
103
+ return from.includes(state) && (transition.requiredCapabilities ?? []).every((item) => capabilities.has(item));
104
+ });
105
+ }
106
+ function initializeWorkflowDocument(data, workflow) {
107
+ return {
108
+ ...data,
109
+ __workflow: { state: workflow.initialState, revision: 1 }
110
+ };
111
+ }
112
+ function publishedStateName(workflow) {
113
+ return workflow.states.find((state) => state.published)?.name ?? workflow.states[workflow.states.length - 1]?.name ?? workflow.initialState;
114
+ }
115
+ function materializeWorkflowDocument(doc, workflow, user) {
116
+ const meta = doc.__workflow;
117
+ const publishedState = publishedStateName(workflow);
118
+ if (!meta) {
119
+ const { __published: _legacyPublished, __workflow: _legacyWorkflow, ...working2 } = doc;
120
+ const state = publishedStateName(workflow);
121
+ return {
122
+ ...working2,
123
+ _workflow: {
124
+ state,
125
+ revision: 1,
126
+ availableTransitions: availableWorkflowTransitions(workflow, state, user).map((item) => item.name)
127
+ }
128
+ };
129
+ }
130
+ const { __published, __workflow, ...working } = doc;
131
+ if (!canViewWorkflowDraft(workflow, user)) {
132
+ if (!__published || typeof __published !== "object") {
133
+ if (meta.state === publishedState) {
134
+ return { ...working, _workflow: publicMetadata(meta) };
135
+ }
136
+ return null;
137
+ }
138
+ return { id: doc.id, ...__published, _workflow: publicMetadata(meta) };
139
+ }
140
+ return {
141
+ ...working,
142
+ _workflow: {
143
+ ...meta,
144
+ availableTransitions: availableWorkflowTransitions(workflow, meta.state, user).map((item) => item.name)
145
+ }
146
+ };
147
+ }
148
+ function eventId() {
149
+ return globalThis.crypto?.randomUUID?.() ?? `evt_${Date.now()}_${Math.random().toString(36).slice(2)}`;
150
+ }
151
+ function createLifecycleEvent(args) {
152
+ return {
153
+ id: eventId(),
154
+ name: args.name,
155
+ collection: args.collection,
156
+ documentId: args.documentId,
157
+ occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
158
+ actorId: args.actorId,
159
+ payload: args.payload,
160
+ attempts: 0,
161
+ status: "pending"
162
+ };
163
+ }
164
+ async function persistEvent(db, event) {
165
+ await db.create({ collection: LIFECYCLE_EVENTS_COLLECTION, data: event });
166
+ }
167
+ async function dispatchLifecycleEvent(config, event) {
168
+ const db = config.db;
169
+ if (!db || !config.events?.handlers.length) return;
170
+ const maxAttempts = config.events.maxAttempts ?? 8;
171
+ const retryDelayMs = config.events.retryDelayMs ?? 1e3;
172
+ const attempts = event.attempts + 1;
173
+ try {
174
+ await db.update({
175
+ collection: LIFECYCLE_EVENTS_COLLECTION,
176
+ id: event.id,
177
+ data: { status: "processing", attempts }
178
+ });
179
+ for (const handler of config.events.handlers) await handler({ ...event, status: "processing", attempts });
180
+ await db.update({
181
+ collection: LIFECYCLE_EVENTS_COLLECTION,
182
+ id: event.id,
183
+ data: { status: "delivered", attempts, deliveredAt: (/* @__PURE__ */ new Date()).toISOString(), lastError: null }
184
+ });
185
+ } catch (error) {
186
+ const exhausted = attempts >= maxAttempts;
187
+ await db.update({
188
+ collection: LIFECYCLE_EVENTS_COLLECTION,
189
+ id: event.id,
190
+ data: {
191
+ status: "failed",
192
+ attempts,
193
+ lastError: error instanceof Error ? error.message : String(error),
194
+ nextAttemptAt: exhausted ? null : new Date(Date.now() + retryDelayMs * 2 ** (attempts - 1)).toISOString()
195
+ }
196
+ });
197
+ }
198
+ }
199
+ async function dispatchPendingLifecycleEvents(config, limit = 50) {
200
+ if (!config.db || !config.events?.handlers.length) return 0;
201
+ const maxAttempts = config.events.maxAttempts ?? 8;
202
+ const result = await config.db.find({
203
+ collection: LIFECYCLE_EVENTS_COLLECTION,
204
+ where: { status: { in: ["pending", "failed"] } },
205
+ sort: "occurredAt",
206
+ limit
207
+ });
208
+ const now2 = Date.now();
209
+ const due = result.docs.filter(
210
+ (doc) => Number(doc.attempts ?? 0) < maxAttempts && (!doc.nextAttemptAt || new Date(doc.nextAttemptAt).getTime() <= now2)
211
+ );
212
+ for (const event of due) await dispatchLifecycleEvent(config, event);
213
+ return due.length;
214
+ }
215
+ async function saveWorkflowDraft(args) {
216
+ const { config, collection, id, originalDoc, data, user } = args;
217
+ const db = config.db;
218
+ const workflow = collection.workflow;
219
+ if (!db.transaction) throw new Error(`The configured database adapter does not support workflow transactions.`);
220
+ const previous = originalDoc.__workflow;
221
+ const isLegacyPublishedDoc = !previous;
222
+ const baselineRevision = previous?.revision ?? 1;
223
+ const event = createLifecycleEvent({
224
+ name: "revision.created",
225
+ collection: collection.slug,
226
+ documentId: id,
227
+ actorId: user?.sub,
228
+ payload: {
229
+ revision: baselineRevision + 1,
230
+ previousRevision: isLegacyPublishedDoc ? baselineRevision : previous?.revision ?? null
231
+ }
232
+ });
233
+ const doc = await db.transaction(async (tx) => {
234
+ const nextMeta = {
235
+ ...previous ?? {},
236
+ state: isLegacyPublishedDoc ? workflow.draftState ?? workflow.initialState : originalDoc.__published ? workflow.draftState ?? workflow.initialState : previous.state,
237
+ revision: baselineRevision + 1,
238
+ ...isLegacyPublishedDoc ? { publishedRevision: baselineRevision } : {}
239
+ };
240
+ const updateData = {
241
+ ...data,
242
+ __workflow: nextMeta
243
+ };
244
+ if (isLegacyPublishedDoc) {
245
+ const { __workflow: _legacyWorkflow, __published: _legacyPublished, ...publishedSnapshot } = originalDoc;
246
+ updateData.__published = publishedSnapshot;
247
+ }
248
+ const updated = await tx.update({ collection: collection.slug, id, data: updateData });
249
+ await persistEvent(tx, event);
250
+ return updated;
251
+ });
252
+ void dispatchLifecycleEvent(config, event);
253
+ return { doc, event };
254
+ }
255
+ async function createWorkflowDocument(args) {
256
+ const { config, collection, data, user } = args;
257
+ const db = config.db;
258
+ if (!db.transaction) throw new Error(`The configured database adapter does not support workflow transactions.`);
259
+ let event;
260
+ const doc = await db.transaction(async (tx) => {
261
+ const created = await tx.create({ collection: collection.slug, data });
262
+ event = createLifecycleEvent({
263
+ name: "revision.created",
264
+ collection: collection.slug,
265
+ documentId: created.id,
266
+ actorId: user?.sub,
267
+ payload: { revision: 1, previousRevision: null }
268
+ });
269
+ await persistEvent(tx, event);
270
+ return created;
271
+ });
272
+ void dispatchLifecycleEvent(config, event);
273
+ return { doc, event };
274
+ }
275
+ async function transitionWorkflow(args) {
276
+ const { config, collection, id, transitionName, expectedRevision, comment, user, req } = args;
277
+ const db = config.db;
278
+ const workflow = collection.workflow;
279
+ if (!db.transaction) throw new Error(`The configured database adapter does not support workflow transactions.`);
280
+ const original = await db.findOne({ collection: collection.slug, id });
281
+ if (!original) throw Object.assign(new Error("Not Found"), { statusCode: 404 });
282
+ const meta = original.__workflow;
283
+ if (!meta) throw Object.assign(new Error("Entry has no workflow metadata"), { statusCode: 409 });
284
+ if (expectedRevision !== void 0 && expectedRevision !== meta.revision) {
285
+ throw Object.assign(new Error("This entry changed since it was loaded. Refresh before transitioning it."), {
286
+ statusCode: 409
287
+ });
288
+ }
289
+ const transition = workflow.transitions.find((item) => item.name === transitionName);
290
+ const fromStates = transition ? Array.isArray(transition.from) ? transition.from : [transition.from] : [];
291
+ if (!transition || !fromStates.includes(meta.state)) {
292
+ throw Object.assign(new Error(`Transition "${transitionName}" is not valid from "${meta.state}".`), {
293
+ statusCode: 409
294
+ });
295
+ }
296
+ if (!availableWorkflowTransitions(workflow, meta.state, user).some((item) => item.name === transition.name)) {
297
+ throw Object.assign(new Error(`You do not have permission to perform "${transition.label}".`), { statusCode: 403 });
298
+ }
299
+ if (transition.requireComment && !comment?.trim()) {
300
+ throw Object.assign(new Error(`A comment is required for "${transition.label}".`), { statusCode: 400 });
301
+ }
302
+ const hookContext = { transition, from: meta.state, to: transition.to, doc: original, user, comment, req, db };
303
+ for (const hook of workflow.hooks?.beforeTransition ?? []) await hook(hookContext);
304
+ const events = [
305
+ createLifecycleEvent({
306
+ name: "workflow.transitioned",
307
+ collection: collection.slug,
308
+ documentId: id,
309
+ actorId: user?.sub,
310
+ payload: { transition: transition.name, from: meta.state, to: transition.to, revision: meta.revision, comment }
311
+ })
312
+ ];
313
+ const targetState = workflow.states.find((state) => state.name === transition.to);
314
+ if (targetState.published) {
315
+ events.push(
316
+ createLifecycleEvent({
317
+ name: "entry.published",
318
+ collection: collection.slug,
319
+ documentId: id,
320
+ actorId: user?.sub,
321
+ payload: { revision: meta.revision }
322
+ })
323
+ );
324
+ } else if (transition.unpublish) {
325
+ events.push(
326
+ createLifecycleEvent({
327
+ name: "entry.unpublished",
328
+ collection: collection.slug,
329
+ documentId: id,
330
+ actorId: user?.sub,
331
+ payload: { revision: meta.publishedRevision }
332
+ })
333
+ );
334
+ }
335
+ const updated = await db.transaction(async (tx) => {
336
+ const locked = await tx.findOne({ collection: collection.slug, id });
337
+ if (!locked) throw Object.assign(new Error("Not Found"), { statusCode: 404 });
338
+ const lockedMeta = locked.__workflow;
339
+ if (lockedMeta.revision !== meta.revision || lockedMeta.state !== meta.state || expectedRevision !== void 0 && lockedMeta.revision !== expectedRevision) {
340
+ throw Object.assign(new Error("This entry changed since it was loaded. Refresh before transitioning it."), {
341
+ statusCode: 409
342
+ });
343
+ }
344
+ const now2 = (/* @__PURE__ */ new Date()).toISOString();
345
+ const { __published: _published, __workflow: _workflow, id: _id, ...working } = locked;
346
+ const nextMeta = {
347
+ ...lockedMeta,
348
+ state: transition.to,
349
+ ...targetState.published ? { publishedRevision: lockedMeta.revision, publishedAt: now2, publishedBy: user?.sub } : {},
350
+ ...transition.unpublish ? { publishedRevision: void 0, publishedAt: void 0, publishedBy: void 0 } : {}
351
+ };
352
+ const data = { __workflow: nextMeta };
353
+ if (targetState.published) data.__published = working;
354
+ if (transition.unpublish) data.__published = null;
355
+ const next = await tx.update({ collection: collection.slug, id, data });
356
+ await tx.create({
357
+ collection: WORKFLOW_HISTORY_COLLECTION,
358
+ data: {
359
+ collection: collection.slug,
360
+ documentId: id,
361
+ transition: transition.name,
362
+ from: lockedMeta.state,
363
+ to: transition.to,
364
+ revision: lockedMeta.revision,
365
+ comment: comment ?? null,
366
+ actorId: user?.sub ?? null,
367
+ createdAt: now2
368
+ }
369
+ });
370
+ for (const event of events) await persistEvent(tx, event);
371
+ if (collection.audit) {
372
+ await tx.create({
373
+ collection: "__audit",
374
+ data: {
375
+ collection: collection.slug,
376
+ documentId: id,
377
+ operation: "workflow.transition",
378
+ user: user?.sub ?? null,
379
+ timestamp: now2,
380
+ changes: JSON.stringify({
381
+ transition: transition.name,
382
+ from: lockedMeta.state,
383
+ to: transition.to,
384
+ revision: lockedMeta.revision
385
+ })
386
+ }
387
+ });
388
+ }
389
+ return next;
390
+ });
391
+ for (const event of events) void dispatchLifecycleEvent(config, event);
392
+ for (const hook of workflow.hooks?.afterTransition ?? []) {
393
+ try {
394
+ await hook({ ...hookContext, doc: updated, event: events[0] });
395
+ } catch (error) {
396
+ try {
397
+ const { getConfigLogger, getObservabilityRuntime } = await import("./observability-KCMTV7GO.js");
398
+ getObservabilityRuntime(config)?.recordWorkflowHookFailure({
399
+ collection: collection.slug,
400
+ transition: transition.name
401
+ });
402
+ getConfigLogger(config, "workflow").error({
403
+ err: error,
404
+ msg: "afterTransition hook failed",
405
+ collection: collection.slug,
406
+ transition: transition.name,
407
+ documentId: id
408
+ });
409
+ } catch {
410
+ console.error("afterTransition hook failed:", error);
411
+ }
412
+ }
413
+ }
414
+ return updated;
415
+ }
416
+
417
+ // src/utils/admin-auth.ts
418
+ function getAdminAuthCollection(config) {
419
+ const adminCollection = resolveAdminAuthCollection(config.collections, config.adminAuth?.collectionSlug);
420
+ return adminCollection ?? null;
421
+ }
422
+ function resolveAdminAuthCollection(collections, collectionSlug) {
423
+ const adminsCollection = collections.find((collection) => collection.slug === "__admins");
424
+ if (adminsCollection) return adminsCollection;
425
+ if (collectionSlug) {
426
+ const requestedCollection = collections.find((collection) => collection.slug === collectionSlug);
427
+ if (requestedCollection) return requestedCollection;
428
+ }
429
+ return collections.find((collection) => collection.auth);
430
+ }
431
+ function getPublicAdminAuthConfig(adminAuth, collections) {
432
+ const providers = (adminAuth?.providers ?? []).map((provider) => ({
433
+ id: provider.id,
434
+ type: provider.type,
435
+ displayName: provider.displayName || humanizeProviderName(provider.id, provider.type),
436
+ autoRedirect: provider.autoRedirect
437
+ }));
438
+ const resolvedCollectionSlug = collections ? resolveAdminAuthCollection(collections, adminAuth?.collectionSlug)?.slug : adminAuth?.collectionSlug;
439
+ return {
440
+ mode: adminAuth?.mode ?? "local",
441
+ collectionSlug: resolvedCollectionSlug,
442
+ provisioningMode: adminAuth?.provisioningMode,
443
+ providers
444
+ };
445
+ }
446
+ function humanizeProviderName(id, type) {
447
+ const cleaned = id.replace(/[-_]+/g, " ").trim();
448
+ if (!cleaned) return type.toUpperCase();
449
+ return cleaned.replace(/\b\w/g, (char) => char.toUpperCase());
450
+ }
451
+
452
+ // src/utils/jexl-helpers.ts
453
+ import jexl from "jexl";
454
+ function slugify(val) {
455
+ if (val === void 0 || val === null) return "";
456
+ return String(val).normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim().replace(/[^a-z0-9\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
457
+ }
458
+ function lower(val) {
459
+ if (val === void 0 || val === null) return "";
460
+ return String(val).toLowerCase();
461
+ }
462
+ function upper(val) {
463
+ if (val === void 0 || val === null) return "";
464
+ return String(val).toUpperCase();
465
+ }
466
+ function trim(val) {
467
+ if (val === void 0 || val === null) return "";
468
+ return String(val).trim();
469
+ }
470
+ function capitalize(val) {
471
+ if (val === void 0 || val === null) return "";
472
+ const str = String(val).trim();
473
+ if (!str) return "";
474
+ return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
475
+ }
476
+ function truncate(val, length2, ellipsis = "...") {
477
+ if (val === void 0 || val === null) return "";
478
+ const str = String(val);
479
+ const maxLen = typeof length2 === "number" && length2 > 0 ? length2 : 100;
480
+ if (str.length <= maxLen) return str;
481
+ return str.slice(0, maxLen).trim() + String(ellipsis ?? "...");
482
+ }
483
+ function readingTime(val, wpm = 200) {
484
+ if (val === void 0 || val === null) return 1;
485
+ const str = String(val).trim();
486
+ if (!str) return 1;
487
+ const words = str.split(/\s+/).filter(Boolean).length;
488
+ return Math.max(1, Math.ceil(words / (typeof wpm === "number" && wpm > 0 ? wpm : 200)));
489
+ }
490
+ function wordCount(val) {
491
+ if (val === void 0 || val === null) return 0;
492
+ const str = String(val).trim();
493
+ if (!str) return 0;
494
+ return str.split(/\s+/).filter(Boolean).length;
495
+ }
496
+ function replace(val, search, replacement) {
497
+ if (val === void 0 || val === null) return "";
498
+ return String(val).replace(new RegExp(String(search || ""), "g"), String(replacement ?? ""));
499
+ }
500
+ function startsWith(str, prefix) {
501
+ if (str === void 0 || str === null) return false;
502
+ return String(str).startsWith(String(prefix ?? ""));
503
+ }
504
+ function endsWith(str, suffix) {
505
+ if (str === void 0 || str === null) return false;
506
+ return String(str).endsWith(String(suffix ?? ""));
507
+ }
508
+ function now() {
509
+ return (/* @__PURE__ */ new Date()).toISOString();
510
+ }
511
+ function today() {
512
+ return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
513
+ }
514
+ function formatDate(val, style = "short") {
515
+ if (!val) return "";
516
+ const d = new Date(val);
517
+ if (Number.isNaN(d.getTime())) return "";
518
+ const styleStr = String(style).toLowerCase();
519
+ if (styleStr === "iso" || styleStr === "date") return d.toISOString().slice(0, 10);
520
+ if (styleStr === "datetime" || styleStr === "full") return d.toISOString();
521
+ return d.toLocaleDateString("en-US", {
522
+ year: "numeric",
523
+ month: "short",
524
+ day: "numeric"
525
+ });
526
+ }
527
+ function addDays(val, days) {
528
+ const d = val ? new Date(val) : /* @__PURE__ */ new Date();
529
+ if (Number.isNaN(d.getTime())) return "";
530
+ const daysNum = typeof days === "number" ? days : Number(days) || 0;
531
+ d.setDate(d.getDate() + daysNum);
532
+ return d.toISOString();
533
+ }
534
+ function diffDays(dateA, dateB) {
535
+ const dA = dateA ? new Date(dateA) : /* @__PURE__ */ new Date();
536
+ const dB = dateB ? new Date(dateB) : /* @__PURE__ */ new Date();
537
+ if (Number.isNaN(dA.getTime()) || Number.isNaN(dB.getTime())) return 0;
538
+ const diffMs = Math.abs(dA.getTime() - dB.getTime());
539
+ return Math.floor(diffMs / (1e3 * 60 * 60 * 24));
540
+ }
541
+ function isPast(val) {
542
+ if (!val) return false;
543
+ const d = new Date(val);
544
+ if (Number.isNaN(d.getTime())) return false;
545
+ return d.getTime() < Date.now();
546
+ }
547
+ function isFuture(val) {
548
+ if (!val) return false;
549
+ const d = new Date(val);
550
+ if (Number.isNaN(d.getTime())) return false;
551
+ return d.getTime() > Date.now();
552
+ }
553
+ function includes(arrOrStr, item) {
554
+ if (Array.isArray(arrOrStr)) {
555
+ return arrOrStr.includes(item);
556
+ }
557
+ if (typeof arrOrStr === "string") {
558
+ return arrOrStr.includes(String(item ?? ""));
559
+ }
560
+ return false;
561
+ }
562
+ function join(arr, separator = ", ") {
563
+ if (!Array.isArray(arr)) return "";
564
+ return arr.filter((item) => item !== void 0 && item !== null).join(String(separator));
565
+ }
566
+ function first(arr) {
567
+ if (Array.isArray(arr)) return arr[0] ?? null;
568
+ return null;
569
+ }
570
+ function last(arr) {
571
+ if (Array.isArray(arr)) return arr[arr.length - 1] ?? null;
572
+ return null;
573
+ }
574
+ function compact(arr) {
575
+ if (!Array.isArray(arr)) return [];
576
+ return arr.filter((item) => item !== void 0 && item !== null && item !== "");
577
+ }
578
+ function unique(arr) {
579
+ if (!Array.isArray(arr)) return [];
580
+ return Array.from(new Set(arr));
581
+ }
582
+ function length(val) {
583
+ if (Array.isArray(val) || typeof val === "string") return val.length;
584
+ if (val && typeof val === "object") return Object.keys(val).length;
585
+ return 0;
586
+ }
587
+ function round(val, decimals = 0) {
588
+ const num = Number(val);
589
+ if (Number.isNaN(num)) return 0;
590
+ const dec = typeof decimals === "number" ? decimals : Number(decimals) || 0;
591
+ const factor = Math.pow(10, dec);
592
+ return Math.round(num * factor) / factor;
593
+ }
594
+ function clamp(val, minVal, maxVal) {
595
+ const num = Number(val) || 0;
596
+ const min = Number(minVal) || 0;
597
+ const max = Number(maxVal) || 0;
598
+ return Math.min(Math.max(num, min), max);
599
+ }
600
+ function defaultValue(val, fallback) {
601
+ if (val === void 0 || val === null || val === "") return fallback;
602
+ return val;
603
+ }
604
+ function coalesce(...args) {
605
+ for (const arg of args) {
606
+ if (arg !== void 0 && arg !== null && arg !== "") return arg;
607
+ }
608
+ return null;
609
+ }
610
+ function isEmpty(val) {
611
+ if (val === void 0 || val === null || val === "") return true;
612
+ if (Array.isArray(val)) return val.length === 0;
613
+ if (typeof val === "object") return Object.keys(val).length === 0;
614
+ return false;
615
+ }
616
+ function get(obj, path, fallback = null) {
617
+ if (!obj || typeof obj !== "object") return fallback;
618
+ const pathStr = String(path || "").trim();
619
+ if (!pathStr) return fallback;
620
+ const parts = pathStr.split(".");
621
+ let curr = obj;
622
+ for (const part of parts) {
623
+ if (curr === void 0 || curr === null) return fallback;
624
+ curr = curr[part];
625
+ }
626
+ return curr === void 0 || curr === null ? fallback : curr;
627
+ }
628
+ function registerJexlHelpers(jexlInstance = jexl) {
629
+ const helpers = {
630
+ // Strings
631
+ slugify,
632
+ lower,
633
+ upper,
634
+ trim,
635
+ capitalize,
636
+ truncate,
637
+ readingTime,
638
+ wordCount,
639
+ replace,
640
+ startsWith,
641
+ endsWith,
642
+ // Dates
643
+ now,
644
+ today,
645
+ formatDate,
646
+ addDays,
647
+ diffDays,
648
+ isPast,
649
+ isFuture,
650
+ // Arrays
651
+ includes,
652
+ join,
653
+ first,
654
+ last,
655
+ compact,
656
+ unique,
657
+ length,
658
+ // Math
659
+ round,
660
+ clamp,
661
+ // Objects & Logical
662
+ default: defaultValue,
663
+ coalesce,
664
+ isEmpty,
665
+ get
666
+ };
667
+ for (const [name, fn] of Object.entries(helpers)) {
668
+ try {
669
+ jexlInstance.addFunction(name, fn);
670
+ } catch {
671
+ }
672
+ }
673
+ }
674
+ registerJexlHelpers(jexl);
675
+ var BUILTIN_JEXL_HELPERS = [
676
+ // Strings
677
+ "slugify",
678
+ "lower",
679
+ "upper",
680
+ "trim",
681
+ "capitalize",
682
+ "truncate",
683
+ "readingTime",
684
+ "wordCount",
685
+ "replace",
686
+ "startsWith",
687
+ "endsWith",
688
+ // Dates
689
+ "now",
690
+ "today",
691
+ "formatDate",
692
+ "addDays",
693
+ "diffDays",
694
+ "isPast",
695
+ "isFuture",
696
+ // Arrays
697
+ "includes",
698
+ "join",
699
+ "first",
700
+ "last",
701
+ "compact",
702
+ "unique",
703
+ "length",
704
+ // Math
705
+ "round",
706
+ "clamp",
707
+ // Objects & Logical
708
+ "default",
709
+ "coalesce",
710
+ "isEmpty",
711
+ "get"
712
+ ];
713
+
714
+ // src/utils/declarative-hooks.ts
715
+ import jexl2 from "jexl";
716
+ registerJexlHelpers(jexl2);
717
+ var SURFACE_ROOTS = {
718
+ "collection.beforeRead": ["req", "user", "query", ...BUILTIN_JEXL_HELPERS],
719
+ "collection.afterRead": ["req", "user", "doc", ...BUILTIN_JEXL_HELPERS],
720
+ "collection.beforeChange": ["req", "user", "data", "doc", "operation", ...BUILTIN_JEXL_HELPERS],
721
+ "global.beforeRead": ["req", "user", "query", ...BUILTIN_JEXL_HELPERS],
722
+ "global.afterRead": ["req", "user", "doc", ...BUILTIN_JEXL_HELPERS],
723
+ "global.beforeChange": ["req", "user", "data", "doc", "operation", ...BUILTIN_JEXL_HELPERS],
724
+ "field.beforeChange": ["value", "data", "originalDoc", "user", ...BUILTIN_JEXL_HELPERS],
725
+ "field.admin.onChange": ["value", "siblingData", "data", ...BUILTIN_JEXL_HELPERS]
726
+ };
727
+ var ACCESS_ROOTS = ["user", "req", "doc", "data", "id", "config", ...BUILTIN_JEXL_HELPERS];
728
+ var ADMIN_CONDITION_RESERVED_ROOTS = ["data", "siblingData", "user", "id", ...BUILTIN_JEXL_HELPERS];
729
+ var PREVIEW_URL_RESERVED_ROOTS = ["siteUrl", "id", ...BUILTIN_JEXL_HELPERS];
730
+ var COMPILE_CACHE = /* @__PURE__ */ new Map();
731
+ function compileExpression(expression) {
732
+ const cached = COMPILE_CACHE.get(expression);
733
+ if (cached) return cached;
734
+ const compiled = jexl2.compile(expression);
735
+ const next = { ast: compiled._ast };
736
+ COMPILE_CACHE.set(expression, next);
737
+ return next;
738
+ }
739
+ function isPlainObject(value) {
740
+ return !!value && typeof value === "object" && !Array.isArray(value);
741
+ }
742
+ function quoteSegment(value) {
743
+ return `["${value.replace(/"/g, '\\"')}"]`;
744
+ }
745
+ function fieldSegment(field, index) {
746
+ return typeof field.name === "string" && field.name.length > 0 ? `fields${quoteSegment(field.name)}` : `fields[${index}]`;
747
+ }
748
+ function blockSegment(block, index) {
749
+ return typeof block.slug === "string" && block.slug.length > 0 ? `blocks${quoteSegment(block.slug)}` : `blocks[${index}]`;
750
+ }
751
+ function collectionSegment(collection, index) {
752
+ return typeof collection.slug === "string" && collection.slug.length > 0 ? `collections${quoteSegment(collection.slug)}` : `collections[${index}]`;
753
+ }
754
+ function globalSegment(global, index) {
755
+ return typeof global.slug === "string" && global.slug.length > 0 ? `globals${quoteSegment(global.slug)}` : `globals[${index}]`;
756
+ }
757
+ function colorize(value, code, enabled) {
758
+ return enabled ? `\x1B[${code}m${value}\x1B[0m` : value;
759
+ }
760
+ function collectRootIdentifiers(node, roots, seen) {
761
+ if (!node || typeof node !== "object" || seen.has(node)) return;
762
+ seen.add(node);
763
+ const candidate = node;
764
+ if (candidate.type === "Identifier") {
765
+ if (candidate.from) {
766
+ collectRootIdentifiers(candidate.from, roots, seen);
767
+ return;
768
+ }
769
+ if (typeof candidate.value === "string" && candidate.value !== "null") {
770
+ roots.add(candidate.value);
771
+ }
772
+ return;
773
+ }
774
+ if (Array.isArray(node)) {
775
+ for (const entry of node) collectRootIdentifiers(entry, roots, seen);
776
+ return;
777
+ }
778
+ for (const value of Object.values(node)) {
779
+ if (Array.isArray(value)) {
780
+ for (const entry of value) collectRootIdentifiers(entry, roots, seen);
781
+ continue;
782
+ }
783
+ if (value && typeof value === "object") {
784
+ collectRootIdentifiers(value, roots, seen);
785
+ }
786
+ }
787
+ }
788
+ function getInvalidRoots(expression, allowedRoots) {
789
+ const { ast } = compileExpression(expression);
790
+ const roots = /* @__PURE__ */ new Set();
791
+ collectRootIdentifiers(ast, roots, /* @__PURE__ */ new Set());
792
+ const allowed = new Set(allowedRoots);
793
+ return [...roots].filter((root) => !allowed.has(root));
794
+ }
795
+ function validateDeclarativeHookExpression(expression, surface, path) {
796
+ try {
797
+ const invalidRoots = getInvalidRoots(expression, SURFACE_ROOTS[surface]);
798
+ if (invalidRoots.length === 0) return [];
799
+ return [
800
+ {
801
+ path,
802
+ surface,
803
+ expression,
804
+ message: `uses unsupported context ${invalidRoots.map((root) => `"${root}"`).join(", ")}. Allowed context: ${SURFACE_ROOTS[surface].map((root) => `"${root}"`).join(", ")}`
805
+ }
806
+ ];
807
+ } catch (error) {
808
+ return [
809
+ {
810
+ path,
811
+ surface,
812
+ expression,
813
+ message: `has invalid syntax: ${error.message}`
814
+ }
815
+ ];
816
+ }
817
+ }
818
+ function validateDeclarativeAccessExpression(expression, surface, path) {
819
+ try {
820
+ const invalidRoots = getInvalidRoots(expression, ACCESS_ROOTS);
821
+ if (invalidRoots.length === 0) return [];
822
+ return [
823
+ {
824
+ path,
825
+ surface,
826
+ expression,
827
+ message: `uses unsupported context ${invalidRoots.map((root) => `"${root}"`).join(", ")}. Allowed context: ${ACCESS_ROOTS.map((root) => `"${root}"`).join(", ")}`
828
+ }
829
+ ];
830
+ } catch (error) {
831
+ return [
832
+ {
833
+ path,
834
+ surface,
835
+ expression,
836
+ message: `has invalid syntax: ${error.message}`
837
+ }
838
+ ];
839
+ }
840
+ }
841
+ function validateAdminConditionExpression(expression, path, allowedRoots) {
842
+ try {
843
+ const invalidRoots = getInvalidRoots(expression, allowedRoots);
844
+ if (invalidRoots.length === 0) return [];
845
+ return [
846
+ {
847
+ path,
848
+ surface: "field.admin.condition",
849
+ expression,
850
+ message: `uses unsupported context ${invalidRoots.map((root) => `"${root}"`).join(", ")}. Allowed context: ${allowedRoots.map((root) => `"${root}"`).join(", ")}`
851
+ }
852
+ ];
853
+ } catch (error) {
854
+ return [
855
+ {
856
+ path,
857
+ surface: "field.admin.condition",
858
+ expression,
859
+ message: `has invalid syntax: ${error.message}`
860
+ }
861
+ ];
862
+ }
863
+ }
864
+ function validatePreviewUrlExpression(expression, path, allowedRoots) {
865
+ try {
866
+ const invalidRoots = getInvalidRoots(expression, allowedRoots);
867
+ if (invalidRoots.length === 0) return [];
868
+ return [
869
+ {
870
+ path,
871
+ surface: "collection.admin.previewUrl",
872
+ expression,
873
+ message: `uses unsupported context ${invalidRoots.map((root) => `"${root}"`).join(", ")}. Allowed context: ${allowedRoots.map((root) => `"${root}"`).join(", ")}`
874
+ }
875
+ ];
876
+ } catch (error) {
877
+ return [
878
+ {
879
+ path,
880
+ surface: "collection.admin.previewUrl",
881
+ expression,
882
+ message: `has invalid syntax: ${error.message}`
883
+ }
884
+ ];
885
+ }
886
+ }
887
+ function assertValidDeclarativeHookExpression(expression, surface, path) {
888
+ const issues = validateDeclarativeHookExpression(expression, surface, path);
889
+ if (issues.length === 0) return;
890
+ throw new Error(`Invalid declarative hook at ${path}: ${issues[0].message}`);
891
+ }
892
+ function assertValidDeclarativeHookResult(result, surface, path) {
893
+ if (isPlainObject(result)) return;
894
+ throw new Error(`Invalid declarative hook result at ${path}: ${surface} expressions must return an object`);
895
+ }
896
+ function collectFieldIssues(fields, path, issues) {
897
+ fields.forEach((field, index) => {
898
+ const fieldPath = `${path}.${fieldSegment(field, index)}`;
899
+ field.hooks?.beforeChange?.forEach((hook, hookIndex) => {
900
+ if (typeof hook !== "string") return;
901
+ issues.push(
902
+ ...validateDeclarativeHookExpression(
903
+ hook,
904
+ "field.beforeChange",
905
+ `${fieldPath}.hooks.beforeChange[${hookIndex}]`
906
+ )
907
+ );
908
+ });
909
+ field.hooks?.afterRead?.forEach((hook, hookIndex) => {
910
+ if (typeof hook !== "string") return;
911
+ issues.push({
912
+ path: `${fieldPath}.hooks.afterRead[${hookIndex}]`,
913
+ surface: "unsupported",
914
+ expression: hook,
915
+ message: "declarative strings are not supported on field hooks.afterRead"
916
+ });
917
+ });
918
+ if (typeof field.admin?.hooks?.onChange === "string") {
919
+ issues.push(
920
+ ...validateDeclarativeHookExpression(
921
+ field.admin.hooks.onChange,
922
+ "field.admin.onChange",
923
+ `${fieldPath}.admin.hooks.onChange`
924
+ )
925
+ );
926
+ }
927
+ if (typeof field.admin?.hooks?.options === "string") {
928
+ issues.push({
929
+ path: `${fieldPath}.admin.hooks.options`,
930
+ surface: "unsupported",
931
+ expression: field.admin.hooks.options,
932
+ message: "declarative strings are not supported on field admin.hooks.options"
933
+ });
934
+ }
935
+ if (Array.isArray(field.fields)) {
936
+ collectFieldIssues(field.fields, fieldPath, issues);
937
+ }
938
+ if (Array.isArray(field.blocks)) {
939
+ field.blocks.forEach((block, blockIndex) => {
940
+ if (!Array.isArray(block.fields)) return;
941
+ collectFieldIssues(block.fields, `${fieldPath}.${blockSegment(block, blockIndex)}`, issues);
942
+ });
943
+ }
944
+ });
945
+ }
946
+ function collectFieldNames(fields) {
947
+ return fields.flatMap(
948
+ (field) => typeof field.name === "string" && field.name.length > 0 ? [field.name] : []
949
+ );
950
+ }
951
+ function collectAdminConditionIssues(fields, path, rootFieldNames, issues) {
952
+ const scopeFieldNames = collectFieldNames(fields);
953
+ const allowedRoots = [.../* @__PURE__ */ new Set([...ADMIN_CONDITION_RESERVED_ROOTS, ...rootFieldNames, ...scopeFieldNames])];
954
+ fields.forEach((field, index) => {
955
+ const fieldPath = `${path}.${fieldSegment(field, index)}`;
956
+ if (typeof field.admin?.condition === "string") {
957
+ issues.push(
958
+ ...validateAdminConditionExpression(
959
+ field.admin.condition,
960
+ `${fieldPath}.admin.condition`,
961
+ allowedRoots
962
+ )
963
+ );
964
+ }
965
+ if (Array.isArray(field.fields)) {
966
+ collectAdminConditionIssues(field.fields, fieldPath, rootFieldNames, issues);
967
+ }
968
+ if (Array.isArray(field.blocks)) {
969
+ field.blocks.forEach((block, blockIndex) => {
970
+ if (!Array.isArray(block.fields)) return;
971
+ collectAdminConditionIssues(
972
+ block.fields,
973
+ `${fieldPath}.${blockSegment(block, blockIndex)}`,
974
+ rootFieldNames,
975
+ issues
976
+ );
977
+ });
978
+ }
979
+ });
980
+ }
981
+ function collectFieldAccessIssues(fields, path, issues) {
982
+ fields.forEach((field, index) => {
983
+ const fieldPath = `${path}.${fieldSegment(field, index)}`;
984
+ if (typeof field.access?.read === "string") {
985
+ issues.push(...validateDeclarativeAccessExpression(field.access.read, "field.access", `${fieldPath}.access.read`));
986
+ }
987
+ if (typeof field.access?.create === "string") {
988
+ issues.push(
989
+ ...validateDeclarativeAccessExpression(field.access.create, "field.access", `${fieldPath}.access.create`)
990
+ );
991
+ }
992
+ if (typeof field.access?.update === "string") {
993
+ issues.push(
994
+ ...validateDeclarativeAccessExpression(field.access.update, "field.access", `${fieldPath}.access.update`)
995
+ );
996
+ }
997
+ if (Array.isArray(field.fields)) {
998
+ collectFieldAccessIssues(field.fields, fieldPath, issues);
999
+ }
1000
+ if (Array.isArray(field.blocks)) {
1001
+ field.blocks.forEach((block, blockIndex) => {
1002
+ if (!Array.isArray(block.fields)) return;
1003
+ collectFieldAccessIssues(
1004
+ block.fields,
1005
+ `${fieldPath}.${blockSegment(block, blockIndex)}`,
1006
+ issues
1007
+ );
1008
+ });
1009
+ }
1010
+ });
1011
+ }
1012
+ function collectHookIssues(hooks, scope, path, issues) {
1013
+ if (!hooks) return;
1014
+ const supported = {
1015
+ beforeRead: `${scope}.beforeRead`,
1016
+ afterRead: `${scope}.afterRead`,
1017
+ beforeChange: `${scope}.beforeChange`
1018
+ };
1019
+ for (const [key, value] of Object.entries(hooks)) {
1020
+ if (!Array.isArray(value)) continue;
1021
+ value.forEach((hook, index) => {
1022
+ if (typeof hook !== "string") return;
1023
+ const surface = supported[key];
1024
+ if (!surface) {
1025
+ issues.push({
1026
+ path: `${path}.${key}[${index}]`,
1027
+ surface: "unsupported",
1028
+ expression: hook,
1029
+ message: `declarative strings are not supported on ${scope} hooks.${key}`
1030
+ });
1031
+ return;
1032
+ }
1033
+ issues.push(...validateDeclarativeHookExpression(hook, surface, `${path}.${key}[${index}]`));
1034
+ });
1035
+ }
1036
+ }
1037
+ function collectDeclarativeHookValidationIssues(config) {
1038
+ const issues = [];
1039
+ config.blocks?.forEach((block, blockIndex) => {
1040
+ if (!Array.isArray(block.fields)) return;
1041
+ collectFieldIssues(
1042
+ block.fields,
1043
+ blockSegment(block, blockIndex),
1044
+ issues
1045
+ );
1046
+ });
1047
+ config.collections.forEach((collection, collectionIndex) => {
1048
+ const collectionPath = collectionSegment(collection, collectionIndex);
1049
+ collectHookIssues(
1050
+ collection.hooks,
1051
+ "collection",
1052
+ `${collectionPath}.hooks`,
1053
+ issues
1054
+ );
1055
+ collectFieldIssues(collection.fields, collectionPath, issues);
1056
+ });
1057
+ config.globals?.forEach((global, globalIndex) => {
1058
+ const globalPath = globalSegment(global, globalIndex);
1059
+ collectHookIssues(
1060
+ global.hooks,
1061
+ "global",
1062
+ `${globalPath}.hooks`,
1063
+ issues
1064
+ );
1065
+ collectFieldIssues(global.fields, globalPath, issues);
1066
+ });
1067
+ return issues;
1068
+ }
1069
+ function collectDeclarativeAccessValidationIssues(config) {
1070
+ const issues = [];
1071
+ Object.entries(config.accessPolicies ?? {}).forEach(([name, value]) => {
1072
+ if (typeof value !== "string") return;
1073
+ issues.push(
1074
+ ...validateDeclarativeAccessExpression(value, "config.accessPolicy", `accessPolicies.${name}`)
1075
+ );
1076
+ });
1077
+ config.blocks?.forEach((block, blockIndex) => {
1078
+ if (!Array.isArray(block.fields)) return;
1079
+ collectFieldAccessIssues(
1080
+ block.fields,
1081
+ blockSegment(block, blockIndex),
1082
+ issues
1083
+ );
1084
+ });
1085
+ config.collections.forEach((collection, collectionIndex) => {
1086
+ const collectionPath = collectionSegment(collection, collectionIndex);
1087
+ if (typeof collection.access?.read === "string") {
1088
+ issues.push(
1089
+ ...validateDeclarativeAccessExpression(
1090
+ collection.access.read,
1091
+ "collection.access",
1092
+ `${collectionPath}.access.read`
1093
+ )
1094
+ );
1095
+ }
1096
+ if (typeof collection.access?.create === "string") {
1097
+ issues.push(
1098
+ ...validateDeclarativeAccessExpression(
1099
+ collection.access.create,
1100
+ "collection.access",
1101
+ `${collectionPath}.access.create`
1102
+ )
1103
+ );
1104
+ }
1105
+ if (typeof collection.access?.update === "string") {
1106
+ issues.push(
1107
+ ...validateDeclarativeAccessExpression(
1108
+ collection.access.update,
1109
+ "collection.access",
1110
+ `${collectionPath}.access.update`
1111
+ )
1112
+ );
1113
+ }
1114
+ if (typeof collection.access?.delete === "string") {
1115
+ issues.push(
1116
+ ...validateDeclarativeAccessExpression(
1117
+ collection.access.delete,
1118
+ "collection.access",
1119
+ `${collectionPath}.access.delete`
1120
+ )
1121
+ );
1122
+ }
1123
+ if (typeof collection.access?.readAudit === "string") {
1124
+ issues.push(
1125
+ ...validateDeclarativeAccessExpression(
1126
+ collection.access.readAudit,
1127
+ "collection.access",
1128
+ `${collectionPath}.access.readAudit`
1129
+ )
1130
+ );
1131
+ }
1132
+ collectFieldAccessIssues(collection.fields, collectionPath, issues);
1133
+ });
1134
+ config.globals?.forEach((global, globalIndex) => {
1135
+ const globalPath = globalSegment(global, globalIndex);
1136
+ if (typeof global.access?.read === "string") {
1137
+ issues.push(
1138
+ ...validateDeclarativeAccessExpression(global.access.read, "global.access", `${globalPath}.access.read`)
1139
+ );
1140
+ }
1141
+ if (typeof global.access?.update === "string") {
1142
+ issues.push(
1143
+ ...validateDeclarativeAccessExpression(
1144
+ global.access.update,
1145
+ "global.access",
1146
+ `${globalPath}.access.update`
1147
+ )
1148
+ );
1149
+ }
1150
+ collectFieldAccessIssues(global.fields, globalPath, issues);
1151
+ });
1152
+ return issues;
1153
+ }
1154
+ function collectAdminConditionValidationIssues(config) {
1155
+ const issues = [];
1156
+ config.blocks?.forEach((block, blockIndex) => {
1157
+ if (!Array.isArray(block.fields)) return;
1158
+ collectAdminConditionIssues(
1159
+ block.fields,
1160
+ blockSegment(block, blockIndex),
1161
+ collectFieldNames(block.fields),
1162
+ issues
1163
+ );
1164
+ });
1165
+ config.collections.forEach((collection, collectionIndex) => {
1166
+ const collectionPath = collectionSegment(collection, collectionIndex);
1167
+ const rootFieldNames = collectFieldNames(collection.fields);
1168
+ collectAdminConditionIssues(collection.fields, collectionPath, rootFieldNames, issues);
1169
+ });
1170
+ config.globals?.forEach((global, globalIndex) => {
1171
+ const globalPath = globalSegment(global, globalIndex);
1172
+ const rootFieldNames = collectFieldNames(global.fields);
1173
+ collectAdminConditionIssues(global.fields, globalPath, rootFieldNames, issues);
1174
+ });
1175
+ return issues;
1176
+ }
1177
+ function collectPreviewUrlValidationIssues(config) {
1178
+ const issues = [];
1179
+ config.collections.forEach((collection, collectionIndex) => {
1180
+ if (typeof collection.admin?.previewUrl !== "string") return;
1181
+ const collectionPath = collectionSegment(collection, collectionIndex);
1182
+ const allowedRoots = [
1183
+ .../* @__PURE__ */ new Set([...PREVIEW_URL_RESERVED_ROOTS, ...collectFieldNames(collection.fields)])
1184
+ ];
1185
+ issues.push(
1186
+ ...validatePreviewUrlExpression(
1187
+ collection.admin.previewUrl,
1188
+ `${collectionPath}.admin.previewUrl`,
1189
+ allowedRoots
1190
+ )
1191
+ );
1192
+ });
1193
+ return issues;
1194
+ }
1195
+ function assertValidAdminConditionsInConfig(config, source = "config") {
1196
+ const diagnostics = collectAdminConditionValidationIssues(config).map((issue) => ({
1197
+ severity: "error",
1198
+ source: "adminCondition",
1199
+ path: issue.path,
1200
+ surface: issue.surface,
1201
+ message: issue.message,
1202
+ expression: issue.expression
1203
+ }));
1204
+ if (diagnostics.length === 0) return;
1205
+ throw new ConfigValidationError(source, diagnostics);
1206
+ }
1207
+ function assertValidPreviewUrlsInConfig(config, source = "config") {
1208
+ const diagnostics = collectPreviewUrlValidationIssues(config).map((issue) => ({
1209
+ severity: "error",
1210
+ source: "previewUrl",
1211
+ path: issue.path,
1212
+ surface: issue.surface,
1213
+ message: issue.message,
1214
+ expression: issue.expression
1215
+ }));
1216
+ if (diagnostics.length === 0) return;
1217
+ throw new ConfigValidationError(source, diagnostics);
1218
+ }
1219
+ function collectConfigDiagnostics(config) {
1220
+ const hookIssues = collectDeclarativeHookValidationIssues(config).map((issue) => ({
1221
+ severity: "error",
1222
+ source: "declarativeHook",
1223
+ path: issue.path,
1224
+ surface: issue.surface,
1225
+ message: issue.message,
1226
+ expression: issue.expression
1227
+ }));
1228
+ const accessIssues = collectDeclarativeAccessValidationIssues(config).map((issue) => ({
1229
+ severity: "error",
1230
+ source: "declarativeAccess",
1231
+ path: issue.path,
1232
+ surface: issue.surface,
1233
+ message: issue.message,
1234
+ expression: issue.expression
1235
+ }));
1236
+ const adminConditionIssues = collectAdminConditionValidationIssues(config).map((issue) => ({
1237
+ severity: "error",
1238
+ source: "adminCondition",
1239
+ path: issue.path,
1240
+ surface: issue.surface,
1241
+ message: issue.message,
1242
+ expression: issue.expression
1243
+ }));
1244
+ const previewUrlIssues = collectPreviewUrlValidationIssues(config).map((issue) => ({
1245
+ severity: "error",
1246
+ source: "previewUrl",
1247
+ path: issue.path,
1248
+ surface: issue.surface,
1249
+ message: issue.message,
1250
+ expression: issue.expression
1251
+ }));
1252
+ return [...hookIssues, ...accessIssues, ...adminConditionIssues, ...previewUrlIssues];
1253
+ }
1254
+ function formatConfigDiagnostics(source, diagnostics, options = {}) {
1255
+ const color = options.color ?? false;
1256
+ const header = `${colorize("Config validation failed", 31, color)} in ${colorize(source, 36, color)}`;
1257
+ const docLink = `${colorize(" Learn how to write declarative rules:", 90, color)} ${colorize("https://docs.dyrected.com/docs/editor-experience/form-and-field-hooks", 34, color)}`;
1258
+ const lines = diagnostics.flatMap((issue, index) => [
1259
+ `${colorize(`${index + 1}.`, 31, color)} ${colorize(issue.path, 1, color)}`,
1260
+ ` ${issue.message}`,
1261
+ ` ${colorize("surface:", 90, color)} ${issue.surface}`
1262
+ ]);
1263
+ return `${header}
1264
+ ${lines.join("\n")}
1265
+
1266
+ ${docLink}`;
1267
+ }
1268
+ var ConfigValidationError = class extends Error {
1269
+ diagnostics;
1270
+ source;
1271
+ constructor(source, diagnostics) {
1272
+ super(formatConfigDiagnostics(source, diagnostics));
1273
+ this.name = "ConfigValidationError";
1274
+ this.source = source;
1275
+ this.diagnostics = diagnostics;
1276
+ }
1277
+ };
1278
+ function isConfigValidationError(error) {
1279
+ return error instanceof ConfigValidationError;
1280
+ }
1281
+ function assertValidDeclarativeHooksInConfig(config, source = "config") {
1282
+ const diagnostics = collectDeclarativeHookValidationIssues(config).map((issue) => ({
1283
+ severity: "error",
1284
+ source: "declarativeHook",
1285
+ path: issue.path,
1286
+ surface: issue.surface,
1287
+ message: issue.message,
1288
+ expression: issue.expression
1289
+ }));
1290
+ if (diagnostics.length === 0) return;
1291
+ throw new ConfigValidationError(source, diagnostics);
1292
+ }
1293
+ function assertValidDeclarativeAccessInConfig(config, source = "config") {
1294
+ const diagnostics = collectDeclarativeAccessValidationIssues(config).map((issue) => ({
1295
+ severity: "error",
1296
+ source: "declarativeAccess",
1297
+ path: issue.path,
1298
+ surface: issue.surface,
1299
+ message: issue.message,
1300
+ expression: issue.expression
1301
+ }));
1302
+ if (diagnostics.length === 0) return;
1303
+ throw new ConfigValidationError(source, diagnostics);
1304
+ }
1305
+
1306
+ // src/auth/token.ts
1307
+ import { SignJWT, jwtVerify, decodeJwt } from "jose";
1308
+ function getSecret() {
1309
+ const secret = process.env.DYRECTED_JWT_SECRET;
1310
+ if (!secret) {
1311
+ throw new Error(
1312
+ "[dyrected/core] DYRECTED_JWT_SECRET is not set. Add it to your environment variables to enable auth collections."
1313
+ );
1314
+ }
1315
+ return new TextEncoder().encode(secret);
1316
+ }
1317
+ var DEFAULT_EXPIRY = "7d";
1318
+ async function signCollectionToken(payload, expiresIn = DEFAULT_EXPIRY) {
1319
+ return new SignJWT({ ...payload }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(expiresIn).sign(getSecret());
1320
+ }
1321
+ async function verifyCollectionToken(token) {
1322
+ const { payload } = await jwtVerify(token, getSecret());
1323
+ return payload;
1324
+ }
1325
+ function decodeCollectionToken(token) {
1326
+ try {
1327
+ return decodeJwt(token);
1328
+ } catch {
1329
+ return null;
1330
+ }
1331
+ }
1332
+
1333
+ // src/auth/sessions.ts
1334
+ var AUTH_SESSIONS_COLLECTION = "__auth_sessions";
1335
+ async function issueAuthSessionToken(args) {
1336
+ const sessionId = createSessionId();
1337
+ const now2 = (/* @__PURE__ */ new Date()).toISOString();
1338
+ const db = args.config.db;
1339
+ if (db) {
1340
+ await db.create({
1341
+ collection: AUTH_SESSIONS_COLLECTION,
1342
+ data: {
1343
+ id: sessionId,
1344
+ userId: args.userId,
1345
+ email: args.email,
1346
+ collection: args.collection,
1347
+ authSource: args.authSource ?? "local",
1348
+ providerId: args.providerId,
1349
+ lastIp: args.ip,
1350
+ lastSeenAt: now2,
1351
+ revokedAt: null,
1352
+ expiresAt: null
1353
+ }
1354
+ });
1355
+ }
1356
+ const token = await signCollectionToken(
1357
+ {
1358
+ sub: args.userId,
1359
+ email: args.email,
1360
+ collection: args.collection,
1361
+ authSource: args.authSource,
1362
+ providerId: args.providerId,
1363
+ sid: sessionId
1364
+ },
1365
+ args.expiresIn
1366
+ );
1367
+ const payload = decodeCollectionToken(token);
1368
+ const expiresAt = payload?.exp != null ? new Date(payload.exp * 1e3).toISOString() : null;
1369
+ if (db && expiresAt) {
1370
+ await db.update({
1371
+ collection: AUTH_SESSIONS_COLLECTION,
1372
+ id: sessionId,
1373
+ data: {
1374
+ expiresAt,
1375
+ lastSeenAt: now2,
1376
+ lastIp: args.ip
1377
+ }
1378
+ });
1379
+ }
1380
+ return token;
1381
+ }
1382
+ async function getAuthSession(config, sessionId) {
1383
+ const db = config.db;
1384
+ if (!db) return null;
1385
+ return await db.findOne({
1386
+ collection: AUTH_SESSIONS_COLLECTION,
1387
+ id: sessionId
1388
+ });
1389
+ }
1390
+ function isAuthSessionActive(session) {
1391
+ if (!session) return false;
1392
+ if (session.revokedAt) return false;
1393
+ if (session.expiresAt && new Date(session.expiresAt).getTime() <= Date.now()) {
1394
+ return false;
1395
+ }
1396
+ return true;
1397
+ }
1398
+ async function touchAuthSession(config, sessionId, args) {
1399
+ const db = config.db;
1400
+ if (!db) return;
1401
+ await db.update({
1402
+ collection: AUTH_SESSIONS_COLLECTION,
1403
+ id: sessionId,
1404
+ data: {
1405
+ lastSeenAt: (/* @__PURE__ */ new Date()).toISOString(),
1406
+ ...args.ip ? { lastIp: args.ip } : {}
1407
+ }
1408
+ });
1409
+ }
1410
+ async function revokeAuthSession(config, sessionId) {
1411
+ const db = config.db;
1412
+ if (!db) return;
1413
+ await db.update({
1414
+ collection: AUTH_SESSIONS_COLLECTION,
1415
+ id: sessionId,
1416
+ data: {
1417
+ revokedAt: (/* @__PURE__ */ new Date()).toISOString()
1418
+ }
1419
+ });
1420
+ }
1421
+ async function revokeAllAuthSessions(config, args) {
1422
+ const db = config.db;
1423
+ if (!db) return 0;
1424
+ let page = 1;
1425
+ let revoked = 0;
1426
+ while (true) {
1427
+ const result = await db.find({
1428
+ collection: AUTH_SESSIONS_COLLECTION,
1429
+ where: {
1430
+ userId: { equals: args.userId },
1431
+ collection: { equals: args.collection }
1432
+ },
1433
+ page,
1434
+ limit: 100
1435
+ });
1436
+ for (const session of result.docs) {
1437
+ if (session.revokedAt) continue;
1438
+ await revokeAuthSession(config, session.id);
1439
+ revoked += 1;
1440
+ }
1441
+ if (!result.hasNextPage) break;
1442
+ page += 1;
1443
+ }
1444
+ return revoked;
1445
+ }
1446
+ function createSessionId() {
1447
+ return globalThis.crypto?.randomUUID?.() ? globalThis.crypto.randomUUID() : `sess_${Date.now()}_${Math.random().toString(36).slice(2)}`;
1448
+ }
1449
+
1450
+ // src/utils/block-references.ts
1451
+ function mergeUniqueBlocks(blocks) {
1452
+ const seen = /* @__PURE__ */ new Map();
1453
+ for (const block of blocks) {
1454
+ const existing = seen.get(block.slug);
1455
+ if (existing && existing !== block) {
1456
+ throw new Error(
1457
+ `Duplicate block slug "${block.slug}" found in the reusable block registry. Block slugs must be unique.`
1458
+ );
1459
+ }
1460
+ if (!existing) seen.set(block.slug, block);
1461
+ }
1462
+ return Array.from(seen.values());
1463
+ }
1464
+ function buildRegistry(blocks) {
1465
+ return new Map(blocks.map((block) => [block.slug, block]));
1466
+ }
1467
+ function resolveField(field, registry, blockCache) {
1468
+ const next = { ...field };
1469
+ if (next.fields) {
1470
+ next.fields = next.fields.map(
1471
+ (child) => resolveField(child, registry, blockCache)
1472
+ );
1473
+ }
1474
+ if (next.type !== "blocks") return next;
1475
+ const hasInlineBlocks = Array.isArray(next.blocks) && next.blocks.length > 0;
1476
+ const hasReferences = Array.isArray(next.blockReferences) && next.blockReferences.length > 0;
1477
+ if (hasInlineBlocks && hasReferences) {
1478
+ throw new Error(
1479
+ `Blocks field "${next.name ?? "(unnamed)"}" cannot define both "blocks" and "blockReferences". Use one or the other.`
1480
+ );
1481
+ }
1482
+ if (hasReferences) {
1483
+ next.blocks = next.blockReferences.map((slug) => {
1484
+ const block = registry.get(slug);
1485
+ if (!block) {
1486
+ throw new Error(
1487
+ `Unknown block reference "${slug}" on blocks field "${next.name ?? "(unnamed)"}". Add it to defineConfig({ blocks: [...] }).`
1488
+ );
1489
+ }
1490
+ return resolveBlock(block, registry, blockCache);
1491
+ });
1492
+ return next;
1493
+ }
1494
+ if (hasInlineBlocks) {
1495
+ next.blocks = next.blocks.map(
1496
+ (block) => resolveBlock(block, registry, blockCache)
1497
+ );
1498
+ }
1499
+ return next;
1500
+ }
1501
+ function resolveBlock(block, registry, blockCache) {
1502
+ const cached = blockCache.get(block);
1503
+ if (cached) return cached;
1504
+ const resolved = {
1505
+ ...block,
1506
+ fields: []
1507
+ };
1508
+ blockCache.set(block, resolved);
1509
+ resolved.fields = block.fields.map(
1510
+ (field) => resolveField(field, registry, blockCache)
1511
+ );
1512
+ return resolved;
1513
+ }
1514
+ function resolveFields(fields, registry, blockCache) {
1515
+ return fields.map((field) => resolveField(field, registry, blockCache));
1516
+ }
1517
+ function normalizeSchemaFragment(fragment) {
1518
+ const reusableBlocks = mergeUniqueBlocks(fragment.blocks ?? []);
1519
+ const registry = buildRegistry(reusableBlocks);
1520
+ const blockCache = /* @__PURE__ */ new WeakMap();
1521
+ const resolvedBlocks = reusableBlocks.map(
1522
+ (block) => resolveBlock(block, registry, blockCache)
1523
+ );
1524
+ const resolvedCollections = (fragment.collections ?? []).map(
1525
+ (collection) => ({
1526
+ ...collection,
1527
+ fields: resolveFields(collection.fields ?? [], registry, blockCache)
1528
+ })
1529
+ );
1530
+ const resolvedGlobals = (fragment.globals ?? []).map((global) => ({
1531
+ ...global,
1532
+ fields: resolveFields(global.fields ?? [], registry, blockCache)
1533
+ }));
1534
+ return {
1535
+ ...fragment,
1536
+ ...fragment.blocks ? { blocks: resolvedBlocks } : {},
1537
+ ...fragment.collections ? { collections: resolvedCollections } : {},
1538
+ ...fragment.globals ? { globals: resolvedGlobals } : {}
1539
+ };
1540
+ }
1541
+ function mergeDynamicConfig(baseConfig, dynamic) {
1542
+ const normalizedDynamic = normalizeSchemaFragment({
1543
+ ...dynamic,
1544
+ blocks: [...baseConfig.blocks ?? [], ...dynamic.blocks ?? []]
1545
+ });
1546
+ return {
1547
+ ...baseConfig,
1548
+ ...normalizedDynamic.blocks ? { blocks: normalizedDynamic.blocks } : {},
1549
+ ...dynamic.accessPolicies ? {
1550
+ accessPolicies: {
1551
+ ...baseConfig.accessPolicies ?? {},
1552
+ ...dynamic.accessPolicies
1553
+ }
1554
+ } : {},
1555
+ ...dynamic.admin ? { admin: { ...baseConfig.admin, ...dynamic.admin } } : {},
1556
+ ...dynamic.adminAuth ? { adminAuth: { ...baseConfig.adminAuth, ...dynamic.adminAuth } } : {},
1557
+ collections: normalizedDynamic.collections ? [...baseConfig.collections, ...normalizedDynamic.collections] : baseConfig.collections,
1558
+ globals: normalizedDynamic.globals ? [...baseConfig.globals, ...normalizedDynamic.globals] : baseConfig.globals
1559
+ };
1560
+ }
1561
+
1562
+ // src/utils/config.ts
1563
+ var AUDIT_COLLECTION_SLUG = "__audit";
1564
+ var SYSTEM_FIELDS = [
1565
+ {
1566
+ name: "createdAt",
1567
+ type: "date",
1568
+ label: "Created At",
1569
+ admin: { readOnly: true, hidden: true }
1570
+ },
1571
+ {
1572
+ name: "updatedAt",
1573
+ type: "date",
1574
+ label: "Updated At",
1575
+ admin: { readOnly: true, hidden: true }
1576
+ },
1577
+ {
1578
+ name: "createdBy",
1579
+ type: "text",
1580
+ label: "Created By",
1581
+ admin: { readOnly: true, hidden: true }
1582
+ },
1583
+ {
1584
+ name: "updatedBy",
1585
+ type: "text",
1586
+ label: "Updated By",
1587
+ admin: { readOnly: true, hidden: true }
1588
+ }
1589
+ ];
1590
+ var AUDIT_COLLECTION = {
1591
+ slug: AUDIT_COLLECTION_SLUG,
1592
+ labels: { singular: "Audit Log", plural: "Audit Logs" },
1593
+ fields: [
1594
+ { name: "collection", type: "text", label: "Collection", required: true },
1595
+ { name: "documentId", type: "text", label: "Document ID" },
1596
+ {
1597
+ name: "operation",
1598
+ type: "select",
1599
+ label: "Operation",
1600
+ options: ["create", "update", "delete"],
1601
+ required: true
1602
+ },
1603
+ { name: "user", type: "text", label: "User ID" },
1604
+ { name: "timestamp", type: "date", label: "Timestamp", required: true },
1605
+ { name: "changes", type: "json", label: "Changes" }
1606
+ ],
1607
+ access: {
1608
+ read: () => false,
1609
+ create: () => false,
1610
+ update: () => false,
1611
+ delete: () => false
1612
+ },
1613
+ admin: { hidden: true }
1614
+ };
1615
+ var WORKFLOW_HISTORY_COLLECTION_CONFIG = {
1616
+ slug: WORKFLOW_HISTORY_COLLECTION,
1617
+ labels: { singular: "Workflow transition", plural: "Workflow transitions" },
1618
+ fields: [
1619
+ { name: "collection", type: "text", required: true },
1620
+ { name: "documentId", type: "text", required: true },
1621
+ { name: "transition", type: "text", required: true },
1622
+ { name: "from", type: "text", required: true },
1623
+ { name: "to", type: "text", required: true },
1624
+ { name: "revision", type: "number", required: true },
1625
+ { name: "comment", type: "textarea" },
1626
+ { name: "actorId", type: "text" },
1627
+ { name: "createdAt", type: "date", required: true }
1628
+ ],
1629
+ access: {
1630
+ read: ({ user }) => !!user,
1631
+ create: () => false,
1632
+ update: () => false,
1633
+ delete: () => false
1634
+ },
1635
+ admin: { hidden: true }
1636
+ };
1637
+ var LIFECYCLE_EVENTS_COLLECTION_CONFIG = {
1638
+ slug: LIFECYCLE_EVENTS_COLLECTION,
1639
+ labels: { singular: "Lifecycle event", plural: "Lifecycle events" },
1640
+ fields: [
1641
+ { name: "name", type: "text", required: true },
1642
+ { name: "collection", type: "text", required: true },
1643
+ { name: "documentId", type: "text", required: true },
1644
+ { name: "occurredAt", type: "date", required: true },
1645
+ { name: "actorId", type: "text" },
1646
+ { name: "payload", type: "json", required: true },
1647
+ { name: "attempts", type: "number", required: true },
1648
+ {
1649
+ name: "status",
1650
+ type: "select",
1651
+ options: ["pending", "processing", "delivered", "failed"],
1652
+ required: true
1653
+ },
1654
+ { name: "nextAttemptAt", type: "date" },
1655
+ { name: "deliveredAt", type: "date" },
1656
+ { name: "lastError", type: "textarea" }
1657
+ ],
1658
+ access: {
1659
+ read: ({ user }) => !!user?.roles?.includes("admin"),
1660
+ create: () => false,
1661
+ update: () => false,
1662
+ delete: () => false
1663
+ },
1664
+ admin: { hidden: true }
1665
+ };
1666
+ var AUTH_SESSIONS_COLLECTION_CONFIG = {
1667
+ slug: AUTH_SESSIONS_COLLECTION,
1668
+ labels: { singular: "Auth session", plural: "Auth sessions" },
1669
+ fields: [
1670
+ { name: "userId", type: "text", required: true },
1671
+ { name: "email", type: "email", required: true },
1672
+ { name: "collection", type: "text", required: true },
1673
+ { name: "authSource", type: "text" },
1674
+ { name: "providerId", type: "text" },
1675
+ { name: "lastIp", type: "text" },
1676
+ { name: "lastSeenAt", type: "date" },
1677
+ { name: "expiresAt", type: "date" },
1678
+ { name: "revokedAt", type: "date" }
1679
+ ],
1680
+ access: {
1681
+ read: () => false,
1682
+ create: () => false,
1683
+ update: () => false,
1684
+ delete: () => false
1685
+ },
1686
+ admin: { hidden: true }
1687
+ };
1688
+ function normalizeConfig(config) {
1689
+ const schemaAwareConfig = normalizeSchemaFragment(config);
1690
+ assertValidDeclarativeHooksInConfig(schemaAwareConfig, "config");
1691
+ assertValidDeclarativeAccessInConfig(schemaAwareConfig, "config");
1692
+ assertValidAdminConditionsInConfig(schemaAwareConfig, "config");
1693
+ assertValidPreviewUrlsInConfig(schemaAwareConfig, "config");
1694
+ const collections = schemaAwareConfig?.collections || [];
1695
+ const globals = schemaAwareConfig?.globals || [];
1696
+ const needsAudit = collections.some((col) => col.audit);
1697
+ const needsWorkflow = collections.some((col) => col.workflow || col.drafts);
1698
+ const needsAuthSessions = collections.some((col) => !!col.auth);
1699
+ const adminAuthCollectionSlug = getAdminAuthCollection({
1700
+ collections,
1701
+ adminAuth: schemaAwareConfig.adminAuth
1702
+ })?.slug;
1703
+ const normalizedCollections = collections.map((col) => {
1704
+ let fields = col.fields || [];
1705
+ const existingFieldNames = new Set(fields.map((f) => f.name));
1706
+ if (col.auth) {
1707
+ if (!existingFieldNames.has("email")) {
1708
+ fields = [
1709
+ ...fields,
1710
+ {
1711
+ name: "email",
1712
+ type: "email",
1713
+ label: "Email",
1714
+ required: true,
1715
+ unique: true,
1716
+ promoted: true,
1717
+ access: {
1718
+ update: "!id"
1719
+ }
1720
+ }
1721
+ ];
1722
+ }
1723
+ if (!existingFieldNames.has("password")) {
1724
+ fields = [
1725
+ ...fields,
1726
+ {
1727
+ name: "password",
1728
+ type: "text",
1729
+ label: "Password",
1730
+ required: true,
1731
+ access: {
1732
+ update: "!id || user.id == id"
1733
+ }
1734
+ }
1735
+ ];
1736
+ }
1737
+ if (!existingFieldNames.has("roles")) {
1738
+ fields = [
1739
+ ...fields,
1740
+ {
1741
+ name: "roles",
1742
+ type: "select",
1743
+ label: "Roles",
1744
+ defaultValue: [],
1745
+ options: [
1746
+ { value: "admin", label: "Admin" },
1747
+ { value: "editor", label: "Editor" },
1748
+ { value: "viewer", label: "Viewer" }
1749
+ ],
1750
+ access: {
1751
+ update: "user.roles && 'admin' in user.roles"
1752
+ }
1753
+ }
1754
+ ];
1755
+ }
1756
+ if (!existingFieldNames.has("status")) {
1757
+ fields = [
1758
+ ...fields,
1759
+ {
1760
+ name: "status",
1761
+ type: "select",
1762
+ label: "Status",
1763
+ defaultValue: "active",
1764
+ options: [
1765
+ { value: "active", label: "Active" },
1766
+ { value: "pending", label: "Pending" }
1767
+ ],
1768
+ access: {
1769
+ update: "user.roles && 'admin' in user.roles && user.id != id"
1770
+ },
1771
+ admin: {
1772
+ condition: `!(data.roles && "admin" in data.roles)`
1773
+ }
1774
+ }
1775
+ ];
1776
+ }
1777
+ fields = fields.map((field) => {
1778
+ if (field.name === "email") {
1779
+ return {
1780
+ ...field,
1781
+ // Email is the login identifier. Keep the integrity constraints
1782
+ // auth relies on even when the field is explicitly redefined, so a
1783
+ // custom `email` field can never silently drop uniqueness.
1784
+ required: true,
1785
+ unique: true,
1786
+ promoted: true,
1787
+ access: {
1788
+ ...field.access || {},
1789
+ update: "!id"
1790
+ }
1791
+ };
1792
+ }
1793
+ if (field.name === "password") {
1794
+ return {
1795
+ ...field,
1796
+ // Password is required to authenticate; enforce it regardless of
1797
+ // how the field was declared.
1798
+ required: true,
1799
+ admin: { ...field.admin || {} },
1800
+ access: {
1801
+ ...field.access || {},
1802
+ update: "!id || user.id == id"
1803
+ }
1804
+ };
1805
+ }
1806
+ if (field.name === "roles") {
1807
+ return {
1808
+ ...field,
1809
+ access: {
1810
+ ...field.access || {},
1811
+ // Must be an admin; cannot edit own roles (no self-elevation).
1812
+ update: "user.roles && 'admin' in user.roles && user.id != id"
1813
+ }
1814
+ };
1815
+ }
1816
+ if (field.name === "status") {
1817
+ return {
1818
+ ...field,
1819
+ access: {
1820
+ ...field.access || {},
1821
+ update: "user.roles && 'admin' in user.roles && user.id != id"
1822
+ }
1823
+ };
1824
+ }
1825
+ return field;
1826
+ });
1827
+ }
1828
+ if (adminAuthCollectionSlug && col.slug === adminAuthCollectionSlug && schemaAwareConfig.adminAuth?.mode === "external") {
1829
+ const externalAdminFields = [
1830
+ {
1831
+ name: "authProvider",
1832
+ type: "text",
1833
+ label: "Auth Provider",
1834
+ admin: { readOnly: true, hidden: true }
1835
+ },
1836
+ {
1837
+ name: "externalSubject",
1838
+ type: "text",
1839
+ label: "External Subject",
1840
+ admin: { readOnly: true, hidden: true }
1841
+ },
1842
+ {
1843
+ name: "authSource",
1844
+ type: "text",
1845
+ label: "Auth Source",
1846
+ admin: { readOnly: true, hidden: true }
1847
+ },
1848
+ {
1849
+ name: "lastLoginAt",
1850
+ type: "date",
1851
+ label: "Last Login At",
1852
+ admin: { readOnly: true, hidden: true }
1853
+ }
1854
+ ];
1855
+ for (const field of externalAdminFields) {
1856
+ if (!existingFieldNames.has(field.name)) {
1857
+ fields = [...fields, field];
1858
+ }
1859
+ }
1860
+ }
1861
+ const updatedFieldNames = new Set(fields.map((f) => f.name));
1862
+ const fieldsToInject = SYSTEM_FIELDS.filter((f) => !updatedFieldNames.has(f.name));
1863
+ const workflow = col.workflow || (col.drafts ? simplePublishingWorkflow() : void 0);
1864
+ return {
1865
+ ...col,
1866
+ workflow,
1867
+ fields: [...fields, ...fieldsToInject]
1868
+ };
1869
+ });
1870
+ const hasAuditCollection = normalizedCollections.some((col) => col.slug === AUDIT_COLLECTION_SLUG);
1871
+ const systemCollections = [];
1872
+ if (needsAudit && !hasAuditCollection) systemCollections.push(AUDIT_COLLECTION);
1873
+ if (needsWorkflow && !normalizedCollections.some((col) => col.slug === WORKFLOW_HISTORY_COLLECTION)) {
1874
+ systemCollections.push(WORKFLOW_HISTORY_COLLECTION_CONFIG);
1875
+ }
1876
+ if (needsWorkflow && !normalizedCollections.some((col) => col.slug === LIFECYCLE_EVENTS_COLLECTION)) {
1877
+ systemCollections.push(LIFECYCLE_EVENTS_COLLECTION_CONFIG);
1878
+ }
1879
+ if (needsAuthSessions && !normalizedCollections.some((col) => col.slug === AUTH_SESSIONS_COLLECTION)) {
1880
+ systemCollections.push(AUTH_SESSIONS_COLLECTION_CONFIG);
1881
+ }
1882
+ return {
1883
+ ...schemaAwareConfig,
1884
+ collections: [...normalizedCollections, ...systemCollections],
1885
+ globals
1886
+ };
1887
+ }
1888
+
1889
+ // src/utils/hooks.ts
1890
+ import jexl3 from "jexl";
1891
+ async function runCollectionHooks(hooks, args, options = {}) {
1892
+ if (!hooks || hooks.length === 0) {
1893
+ return args.data ?? args.doc ?? args.query ?? void 0;
1894
+ }
1895
+ const payloadKey = args.data !== void 0 ? "data" : args.doc !== void 0 ? "doc" : "query" in args ? "query" : void 0;
1896
+ let currentPayload = payloadKey === void 0 ? void 0 : args[payloadKey];
1897
+ for (const hook of hooks) {
1898
+ try {
1899
+ const hookArgs = {
1900
+ ...args,
1901
+ ...payloadKey !== void 0 ? { [payloadKey]: currentPayload } : {}
1902
+ };
1903
+ const result = typeof hook === "string" ? await (() => {
1904
+ if (options.surface) {
1905
+ assertValidDeclarativeHookExpression(
1906
+ hook,
1907
+ options.surface,
1908
+ options.path ?? options.surface
1909
+ );
1910
+ }
1911
+ return jexl3.eval(hook, hookArgs);
1912
+ })() : await hook(hookArgs);
1913
+ if (result !== void 0) {
1914
+ if (typeof hook === "string" && options.surface) {
1915
+ assertValidDeclarativeHookResult(
1916
+ result,
1917
+ options.surface,
1918
+ options.path ?? options.surface
1919
+ );
1920
+ }
1921
+ currentPayload = typeof hook === "string" && currentPayload && typeof currentPayload === "object" && !Array.isArray(currentPayload) && result && typeof result === "object" && !Array.isArray(result) ? {
1922
+ ...currentPayload,
1923
+ ...result
1924
+ } : result;
1925
+ }
1926
+ } catch (err) {
1927
+ if (options.isolated) {
1928
+ console.error("Side-effect hook failed after a successful write", err);
1929
+ } else {
1930
+ throw err;
1931
+ }
1932
+ }
1933
+ }
1934
+ return currentPayload;
1935
+ }
1936
+ async function executeFieldBeforeChange(fields, data, originalDoc, user, db, pathPrefix = "") {
1937
+ if (!data || typeof data !== "object") return data;
1938
+ const result = { ...data };
1939
+ for (const field of fields) {
1940
+ if (!field.name) continue;
1941
+ const fieldPath = pathPrefix ? `${pathPrefix}.${field.name}` : field.name;
1942
+ const value = result[field.name];
1943
+ const origValue = originalDoc?.[field.name];
1944
+ let updatedValue = value;
1945
+ if (field.hooks?.beforeChange) {
1946
+ for (const hook of field.hooks.beforeChange) {
1947
+ const hookArgs = {
1948
+ value: updatedValue,
1949
+ originalDoc: originalDoc ?? void 0,
1950
+ data: result,
1951
+ user,
1952
+ db
1953
+ };
1954
+ updatedValue = typeof hook === "string" ? await (() => {
1955
+ assertValidDeclarativeHookExpression(
1956
+ hook,
1957
+ "field.beforeChange",
1958
+ fieldPath
1959
+ );
1960
+ return jexl3.eval(hook, hookArgs);
1961
+ })() : await hook(hookArgs);
1962
+ }
1963
+ result[field.name] = updatedValue;
1964
+ }
1965
+ if (updatedValue !== void 0 && updatedValue !== null) {
1966
+ if (field.type === "object" && field.fields) {
1967
+ result[field.name] = await executeFieldBeforeChange(
1968
+ field.fields,
1969
+ updatedValue,
1970
+ origValue,
1971
+ user,
1972
+ db,
1973
+ fieldPath
1974
+ );
1975
+ } else if (field.type === "array" && field.fields && Array.isArray(updatedValue)) {
1976
+ const arrayResult = [];
1977
+ for (let i = 0; i < updatedValue.length; i++) {
1978
+ const item = updatedValue[i];
1979
+ const origItem = Array.isArray(origValue) ? origValue[i] : null;
1980
+ arrayResult.push(
1981
+ await executeFieldBeforeChange(
1982
+ field.fields,
1983
+ item,
1984
+ origItem,
1985
+ user,
1986
+ db,
1987
+ fieldPath
1988
+ )
1989
+ );
1990
+ }
1991
+ result[field.name] = arrayResult;
1992
+ } else if (field.type === "blocks" && field.blocks && Array.isArray(updatedValue)) {
1993
+ const blocksResult = [];
1994
+ for (let i = 0; i < updatedValue.length; i++) {
1995
+ const blockData = updatedValue[i];
1996
+ const origBlock = Array.isArray(origValue) ? origValue[i] : null;
1997
+ const blockConfig = field.blocks.find(
1998
+ (b) => b.slug === blockData.blockType
1999
+ );
2000
+ if (blockConfig) {
2001
+ blocksResult.push(
2002
+ await executeFieldBeforeChange(
2003
+ blockConfig.fields,
2004
+ blockData,
2005
+ origBlock,
2006
+ user,
2007
+ db,
2008
+ fieldPath
2009
+ )
2010
+ );
2011
+ } else {
2012
+ blocksResult.push(blockData);
2013
+ }
2014
+ }
2015
+ result[field.name] = blocksResult;
2016
+ }
2017
+ }
2018
+ }
2019
+ return result;
2020
+ }
2021
+ async function executeFieldAfterRead(fields, doc, user, db) {
2022
+ if (!doc || typeof doc !== "object") return doc;
2023
+ const result = { ...doc };
2024
+ for (const field of fields) {
2025
+ if (!field.name) continue;
2026
+ const value = result[field.name];
2027
+ let updatedValue = value;
2028
+ if (field.hooks?.afterRead) {
2029
+ for (const hook of field.hooks.afterRead) {
2030
+ const typedHook = hook;
2031
+ const hookArgs = {
2032
+ value: updatedValue,
2033
+ doc: result,
2034
+ user,
2035
+ db
2036
+ };
2037
+ updatedValue = await typedHook(hookArgs);
2038
+ }
2039
+ result[field.name] = updatedValue;
2040
+ }
2041
+ if (updatedValue !== void 0 && updatedValue !== null) {
2042
+ if (field.type === "object" && field.fields) {
2043
+ result[field.name] = await executeFieldAfterRead(
2044
+ field.fields,
2045
+ updatedValue,
2046
+ user,
2047
+ db
2048
+ );
2049
+ } else if (field.type === "array" && field.fields && Array.isArray(updatedValue)) {
2050
+ const arrayResult = [];
2051
+ for (const item of updatedValue) {
2052
+ arrayResult.push(
2053
+ await executeFieldAfterRead(
2054
+ field.fields,
2055
+ item,
2056
+ user,
2057
+ db
2058
+ )
2059
+ );
2060
+ }
2061
+ result[field.name] = arrayResult;
2062
+ } else if (field.type === "blocks" && field.blocks && Array.isArray(updatedValue)) {
2063
+ const blocksResult = [];
2064
+ for (const blockData of updatedValue) {
2065
+ const typedBlock = blockData;
2066
+ const blockConfig = field.blocks.find(
2067
+ (b) => b.slug === typedBlock.blockType
2068
+ );
2069
+ if (blockConfig) {
2070
+ blocksResult.push(
2071
+ await executeFieldAfterRead(
2072
+ blockConfig.fields,
2073
+ typedBlock,
2074
+ user,
2075
+ db
2076
+ )
2077
+ );
2078
+ } else {
2079
+ blocksResult.push(blockData);
2080
+ }
2081
+ }
2082
+ result[field.name] = blocksResult;
2083
+ }
2084
+ }
2085
+ }
2086
+ return result;
2087
+ }
2088
+
2089
+ // src/utils/openapi.ts
2090
+ function getCollectionLabels(collection) {
2091
+ return collection.labels || { singular: collection.slug, plural: collection.slug };
2092
+ }
2093
+ function getCollectionTag(collection) {
2094
+ return `Collection: ${getCollectionLabels(collection).plural}`;
2095
+ }
2096
+ function getGlobalTag(global) {
2097
+ return `Global: ${global.label || global.slug}`;
2098
+ }
2099
+ function generateOpenApi(config) {
2100
+ const spec = {
2101
+ openapi: "3.0.0",
2102
+ info: {
2103
+ title: "Dyrected API",
2104
+ version: "1.0.0",
2105
+ description: "Automatically generated OpenAPI specification for the Dyrected project."
2106
+ },
2107
+ components: {
2108
+ schemas: {
2109
+ WorkflowMetadata: {
2110
+ type: "object",
2111
+ required: ["state", "revision"],
2112
+ properties: {
2113
+ state: { type: "string" },
2114
+ revision: { type: "integer", minimum: 1 },
2115
+ publishedRevision: { type: "integer", minimum: 1 },
2116
+ publishedAt: { type: "string", format: "date-time" },
2117
+ publishedBy: { type: "string" },
2118
+ availableTransitions: { type: "array", items: { type: "string" } }
2119
+ }
2120
+ },
2121
+ WorkflowTransitionRequest: {
2122
+ type: "object",
2123
+ properties: {
2124
+ expectedRevision: { type: "integer", minimum: 1 },
2125
+ comment: { type: "string" }
2126
+ }
2127
+ },
2128
+ WorkflowHistoryEntry: {
2129
+ type: "object",
2130
+ required: [
2131
+ "collection",
2132
+ "documentId",
2133
+ "transition",
2134
+ "from",
2135
+ "to",
2136
+ "revision",
2137
+ "createdAt"
2138
+ ],
2139
+ properties: {
2140
+ id: { type: "string" },
2141
+ collection: { type: "string" },
2142
+ documentId: { type: "string" },
2143
+ transition: { type: "string" },
2144
+ from: { type: "string" },
2145
+ to: { type: "string" },
2146
+ revision: { type: "integer" },
2147
+ comment: { type: "string", nullable: true },
2148
+ actorId: { type: "string", nullable: true },
2149
+ createdAt: { type: "string", format: "date-time" }
2150
+ }
2151
+ },
2152
+ AuditEntry: {
2153
+ type: "object",
2154
+ required: ["collection", "operation", "timestamp"],
2155
+ properties: {
2156
+ id: { type: "string" },
2157
+ collection: { type: "string" },
2158
+ documentId: { type: "string", nullable: true },
2159
+ operation: { type: "string" },
2160
+ user: { type: "string", nullable: true },
2161
+ timestamp: { type: "string", format: "date-time" },
2162
+ changes: {
2163
+ oneOf: [
2164
+ { type: "string" },
2165
+ { type: "object", additionalProperties: true },
2166
+ { type: "null" }
2167
+ ]
2168
+ }
2169
+ }
2170
+ },
2171
+ Error: {
2172
+ type: "object",
2173
+ properties: {
2174
+ message: { type: "string" },
2175
+ errors: {
2176
+ type: "array",
2177
+ items: { type: "object", additionalProperties: true }
2178
+ }
2179
+ }
2180
+ },
2181
+ AuthCredentials: {
2182
+ type: "object",
2183
+ required: ["email", "password"],
2184
+ properties: {
2185
+ email: { type: "string", format: "email" },
2186
+ password: { type: "string" }
2187
+ }
2188
+ },
2189
+ TokenResponse: {
2190
+ type: "object",
2191
+ properties: {
2192
+ token: { type: "string" },
2193
+ user: { type: "object", additionalProperties: true }
2194
+ }
2195
+ }
2196
+ },
2197
+ securitySchemes: {
2198
+ ApiKeyAuth: {
2199
+ type: "apiKey",
2200
+ in: "header",
2201
+ name: "x-api-key"
2202
+ }
2203
+ }
2204
+ },
2205
+ paths: {},
2206
+ security: [{ ApiKeyAuth: [] }]
2207
+ };
2208
+ spec.paths["/api/schemas"] = {
2209
+ get: {
2210
+ tags: ["System"],
2211
+ summary: "Get the serialized Dyrected schema",
2212
+ security: [],
2213
+ responses: {
2214
+ 200: { description: "Collection and global schema definitions" }
2215
+ }
2216
+ }
2217
+ };
2218
+ spec.paths["/api/openapi.json"] = {
2219
+ get: {
2220
+ tags: ["System"],
2221
+ summary: "Get the OpenAPI specification",
2222
+ security: [],
2223
+ responses: { 200: { description: "OpenAPI 3.0 document" } }
2224
+ }
2225
+ };
2226
+ spec.paths["/api/docs"] = {
2227
+ get: {
2228
+ tags: ["System"],
2229
+ summary: "Open interactive API documentation",
2230
+ security: [],
2231
+ responses: { 200: { description: "Swagger UI HTML" } }
2232
+ }
2233
+ };
2234
+ spec.paths["/api/dyrected/options/{collection}/{field}"] = {
2235
+ get: {
2236
+ tags: ["System"],
2237
+ summary: "Resolve dynamic field options",
2238
+ parameters: [
2239
+ {
2240
+ name: "collection",
2241
+ in: "path",
2242
+ required: true,
2243
+ schema: { type: "string" }
2244
+ },
2245
+ {
2246
+ name: "field",
2247
+ in: "path",
2248
+ required: true,
2249
+ schema: { type: "string" }
2250
+ }
2251
+ ],
2252
+ responses: { 200: { description: "Resolved option items" } }
2253
+ }
2254
+ };
2255
+ spec.paths["/api/preferences/{key}"] = {
2256
+ get: {
2257
+ tags: ["Preferences"],
2258
+ summary: "Get an authenticated user preference",
2259
+ parameters: [
2260
+ { name: "key", in: "path", required: true, schema: { type: "string" } }
2261
+ ],
2262
+ responses: { 200: { description: "Preference value" } }
2263
+ },
2264
+ put: {
2265
+ tags: ["Preferences"],
2266
+ summary: "Set an authenticated user preference",
2267
+ parameters: [
2268
+ { name: "key", in: "path", required: true, schema: { type: "string" } }
2269
+ ],
2270
+ requestBody: {
2271
+ required: true,
2272
+ content: { "application/json": { schema: { type: "object" } } }
2273
+ },
2274
+ responses: { 200: { description: "Updated preference" } }
2275
+ }
2276
+ };
2277
+ spec.paths["/api/preview-token"] = {
2278
+ post: {
2279
+ tags: ["Preview"],
2280
+ summary: "Create a preview token",
2281
+ responses: { 200: { description: "Short-lived preview token" } }
2282
+ }
2283
+ };
2284
+ spec.paths["/api/preview-data"] = {
2285
+ get: {
2286
+ tags: ["Preview"],
2287
+ summary: "Resolve preview data from a token",
2288
+ security: [],
2289
+ parameters: [
2290
+ {
2291
+ name: "token",
2292
+ in: "query",
2293
+ required: true,
2294
+ schema: { type: "string" }
2295
+ }
2296
+ ],
2297
+ responses: { 200: { description: "Preview document data" } }
2298
+ }
2299
+ };
2300
+ spec.paths["/api/audit"] = {
2301
+ get: {
2302
+ tags: ["Audit"],
2303
+ summary: "Get audit entries across all readable audited collections",
2304
+ parameters: [
2305
+ {
2306
+ name: "limit",
2307
+ in: "query",
2308
+ schema: { type: "integer", default: 50, maximum: 100 }
2309
+ },
2310
+ { name: "page", in: "query", schema: { type: "integer", default: 1 } },
2311
+ {
2312
+ name: "where",
2313
+ in: "query",
2314
+ schema: { type: "string" },
2315
+ description: "JSON filter"
2316
+ },
2317
+ {
2318
+ name: "sort",
2319
+ in: "query",
2320
+ schema: { type: "string", default: "-timestamp" }
2321
+ }
2322
+ ],
2323
+ responses: {
2324
+ 200: {
2325
+ description: "Audit entries",
2326
+ content: {
2327
+ "application/json": {
2328
+ schema: {
2329
+ type: "object",
2330
+ properties: {
2331
+ docs: {
2332
+ type: "array",
2333
+ items: { $ref: "#/components/schemas/AuditEntry" }
2334
+ },
2335
+ total: { type: "integer" },
2336
+ limit: { type: "integer" },
2337
+ page: { type: "integer" }
2338
+ }
2339
+ }
2340
+ }
2341
+ }
2342
+ }
2343
+ }
2344
+ }
2345
+ };
2346
+ for (const collection of config.collections) {
2347
+ spec.components.schemas[collection.slug] = collectionToSchema(collection);
2348
+ }
2349
+ for (const global of config.globals) {
2350
+ spec.components.schemas[global.slug] = globalToSchema(global);
2351
+ }
2352
+ for (const collection of config.collections) {
2353
+ const slug = collection.slug;
2354
+ const path = `/api/collections/${slug}`;
2355
+ const labels = getCollectionLabels(collection);
2356
+ const collectionTag = getCollectionTag(collection);
2357
+ spec.paths[path] = {
2358
+ get: {
2359
+ tags: [collectionTag],
2360
+ summary: `Find ${labels.plural}`,
2361
+ parameters: [
2362
+ {
2363
+ name: "limit",
2364
+ in: "query",
2365
+ schema: { type: "integer", default: 10 }
2366
+ },
2367
+ {
2368
+ name: "page",
2369
+ in: "query",
2370
+ schema: { type: "integer", default: 1 }
2371
+ },
2372
+ {
2373
+ name: "where",
2374
+ in: "query",
2375
+ schema: { type: "string" },
2376
+ description: "JSON filter"
2377
+ },
2378
+ {
2379
+ name: "search",
2380
+ in: "query",
2381
+ schema: { type: "string" },
2382
+ description: "Free-text search across configured searchable fields"
2383
+ },
2384
+ {
2385
+ name: "sort",
2386
+ in: "query",
2387
+ schema: { type: "string" },
2388
+ description: "Sort field (e.g. -createdAt)"
2389
+ }
2390
+ ],
2391
+ responses: {
2392
+ 200: {
2393
+ description: "Success",
2394
+ content: {
2395
+ "application/json": {
2396
+ schema: {
2397
+ type: "object",
2398
+ properties: {
2399
+ docs: {
2400
+ type: "array",
2401
+ items: { $ref: `#/components/schemas/${slug}` }
2402
+ },
2403
+ total: { type: "integer" },
2404
+ limit: { type: "integer" },
2405
+ page: { type: "integer" }
2406
+ }
2407
+ }
2408
+ }
2409
+ }
2410
+ }
2411
+ }
2412
+ },
2413
+ post: {
2414
+ tags: [collectionTag],
2415
+ summary: `Create ${labels.singular}`,
2416
+ requestBody: {
2417
+ required: true,
2418
+ content: {
2419
+ "application/json": {
2420
+ schema: { $ref: `#/components/schemas/${slug}` }
2421
+ }
2422
+ }
2423
+ },
2424
+ responses: {
2425
+ 201: {
2426
+ description: "Created",
2427
+ content: {
2428
+ "application/json": {
2429
+ schema: { $ref: `#/components/schemas/${slug}` }
2430
+ }
2431
+ }
2432
+ }
2433
+ }
2434
+ }
2435
+ };
2436
+ spec.paths[`${path}/{id}`] = {
2437
+ get: {
2438
+ tags: [collectionTag],
2439
+ summary: `Get a single ${labels.singular}`,
2440
+ parameters: [
2441
+ {
2442
+ name: "id",
2443
+ in: "path",
2444
+ required: true,
2445
+ schema: { type: "string" }
2446
+ }
2447
+ ],
2448
+ responses: {
2449
+ 200: {
2450
+ description: "Success",
2451
+ content: {
2452
+ "application/json": {
2453
+ schema: { $ref: `#/components/schemas/${slug}` }
2454
+ }
2455
+ }
2456
+ }
2457
+ }
2458
+ },
2459
+ patch: {
2460
+ tags: [collectionTag],
2461
+ summary: `Update ${labels.singular}`,
2462
+ parameters: [
2463
+ {
2464
+ name: "id",
2465
+ in: "path",
2466
+ required: true,
2467
+ schema: { type: "string" }
2468
+ }
2469
+ ],
2470
+ requestBody: {
2471
+ required: true,
2472
+ content: {
2473
+ "application/json": {
2474
+ schema: { $ref: `#/components/schemas/${slug}` }
2475
+ }
2476
+ }
2477
+ },
2478
+ responses: {
2479
+ 200: {
2480
+ description: "Updated",
2481
+ content: {
2482
+ "application/json": {
2483
+ schema: { $ref: `#/components/schemas/${slug}` }
2484
+ }
2485
+ }
2486
+ }
2487
+ }
2488
+ },
2489
+ delete: {
2490
+ tags: [collectionTag],
2491
+ summary: `Delete ${labels.singular}`,
2492
+ parameters: [
2493
+ {
2494
+ name: "id",
2495
+ in: "path",
2496
+ required: true,
2497
+ schema: { type: "string" }
2498
+ }
2499
+ ],
2500
+ responses: {
2501
+ 204: { description: "Deleted" }
2502
+ }
2503
+ }
2504
+ };
2505
+ spec.paths[`${path}/delete-many`] = {
2506
+ delete: {
2507
+ tags: [collectionTag],
2508
+ summary: `Delete multiple ${labels.plural}`,
2509
+ requestBody: {
2510
+ required: true,
2511
+ content: {
2512
+ "application/json": {
2513
+ schema: {
2514
+ type: "object",
2515
+ required: ["ids"],
2516
+ properties: {
2517
+ ids: { type: "array", items: { type: "string" } }
2518
+ }
2519
+ }
2520
+ }
2521
+ }
2522
+ },
2523
+ responses: { 200: { description: "Deleted and failed document IDs" } }
2524
+ }
2525
+ };
2526
+ spec.paths[`${path}/aggregate`] = {
2527
+ post: {
2528
+ tags: [collectionTag],
2529
+ summary: `Aggregate ${labels.plural}`,
2530
+ description: `Compute statistical aggregations (count, sum, avg, min, max) across ${labels.plural}.`,
2531
+ requestBody: {
2532
+ required: true,
2533
+ content: {
2534
+ "application/json": {
2535
+ schema: {
2536
+ type: "object",
2537
+ additionalProperties: {
2538
+ type: "object",
2539
+ properties: {
2540
+ count: { type: "string", example: "*" },
2541
+ sum: { type: "string", description: "Field to sum" },
2542
+ avg: { type: "string", description: "Field to average" },
2543
+ min: { type: "string", description: "Field for minimum" },
2544
+ max: { type: "string", description: "Field for maximum" },
2545
+ cast: {
2546
+ type: "string",
2547
+ enum: [
2548
+ "number",
2549
+ "integer",
2550
+ "float",
2551
+ "boolean",
2552
+ "date",
2553
+ "string"
2554
+ ]
2555
+ },
2556
+ where: {
2557
+ type: "object",
2558
+ description: "Per-aggregate filter condition",
2559
+ additionalProperties: true
2560
+ }
2561
+ }
2562
+ }
2563
+ }
2564
+ }
2565
+ }
2566
+ },
2567
+ responses: {
2568
+ 200: {
2569
+ description: "Success",
2570
+ content: {
2571
+ "application/json": {
2572
+ schema: {
2573
+ type: "object",
2574
+ additionalProperties: {
2575
+ type: "number",
2576
+ nullable: true
2577
+ }
2578
+ }
2579
+ }
2580
+ }
2581
+ },
2582
+ 400: {
2583
+ description: "Bad Request - Invalid aggregate input"
2584
+ },
2585
+ 403: {
2586
+ description: "Forbidden - Access denied by read rule"
2587
+ }
2588
+ }
2589
+ }
2590
+ };
2591
+ if (collection.audit) {
2592
+ spec.paths[`${path}/__audit`] = {
2593
+ get: {
2594
+ tags: [collectionTag],
2595
+ summary: `Get ${labels.singular} audit entries`,
2596
+ parameters: [
2597
+ {
2598
+ name: "limit",
2599
+ in: "query",
2600
+ schema: { type: "integer", default: 50, maximum: 100 }
2601
+ },
2602
+ {
2603
+ name: "page",
2604
+ in: "query",
2605
+ schema: { type: "integer", default: 1 }
2606
+ },
2607
+ {
2608
+ name: "where",
2609
+ in: "query",
2610
+ schema: { type: "string" },
2611
+ description: "JSON filter"
2612
+ },
2613
+ {
2614
+ name: "sort",
2615
+ in: "query",
2616
+ schema: { type: "string", default: "-timestamp" }
2617
+ }
2618
+ ],
2619
+ responses: {
2620
+ 200: {
2621
+ description: "Audit entries for this collection",
2622
+ content: {
2623
+ "application/json": {
2624
+ schema: {
2625
+ type: "object",
2626
+ properties: {
2627
+ docs: {
2628
+ type: "array",
2629
+ items: { $ref: "#/components/schemas/AuditEntry" }
2630
+ },
2631
+ total: { type: "integer" },
2632
+ limit: { type: "integer" },
2633
+ page: { type: "integer" }
2634
+ }
2635
+ }
2636
+ }
2637
+ }
2638
+ },
2639
+ 403: { description: "Collection read access denied" },
2640
+ 404: { description: "Audit is not enabled for this collection" }
2641
+ }
2642
+ }
2643
+ };
2644
+ }
2645
+ if (collection.upload) {
2646
+ spec.paths[`${path}/media`] = {
2647
+ get: {
2648
+ tags: [collectionTag],
2649
+ summary: `List ${labels.plural}`,
2650
+ responses: { 200: { description: "Paginated media documents" } }
2651
+ },
2652
+ post: {
2653
+ tags: [collectionTag],
2654
+ summary: `Upload ${labels.singular}`,
2655
+ requestBody: {
2656
+ required: true,
2657
+ content: {
2658
+ "multipart/form-data": {
2659
+ schema: {
2660
+ type: "object",
2661
+ required: ["file"],
2662
+ properties: { file: { type: "string", format: "binary" } }
2663
+ }
2664
+ }
2665
+ }
2666
+ },
2667
+ responses: { 201: { description: "Uploaded media document" } }
2668
+ }
2669
+ };
2670
+ spec.paths[`${path}/media/{filename}`] = {
2671
+ get: {
2672
+ tags: [collectionTag],
2673
+ summary: `Serve ${labels.singular} bytes`,
2674
+ parameters: [
2675
+ {
2676
+ name: "filename",
2677
+ in: "path",
2678
+ required: true,
2679
+ schema: { type: "string" }
2680
+ }
2681
+ ],
2682
+ security: [],
2683
+ responses: {
2684
+ 200: { description: "Stored file" },
2685
+ 404: { description: "File not found" }
2686
+ }
2687
+ }
2688
+ };
2689
+ }
2690
+ if (collection.auth) {
2691
+ const publicAuthPost = (summary) => ({
2692
+ tags: [collectionTag],
2693
+ summary,
2694
+ security: [],
2695
+ requestBody: {
2696
+ required: true,
2697
+ content: {
2698
+ "application/json": {
2699
+ schema: { type: "object", additionalProperties: true }
2700
+ }
2701
+ }
2702
+ },
2703
+ responses: {
2704
+ 200: { description: "Success" },
2705
+ 400: { description: "Invalid request" }
2706
+ }
2707
+ });
2708
+ spec.paths[`${path}/login`] = {
2709
+ post: {
2710
+ ...publicAuthPost(`Log in to ${labels.plural}`),
2711
+ requestBody: {
2712
+ required: true,
2713
+ content: {
2714
+ "application/json": {
2715
+ schema: { $ref: "#/components/schemas/AuthCredentials" }
2716
+ }
2717
+ }
2718
+ },
2719
+ responses: {
2720
+ 200: {
2721
+ description: "Authenticated",
2722
+ content: {
2723
+ "application/json": {
2724
+ schema: { $ref: "#/components/schemas/TokenResponse" }
2725
+ }
2726
+ }
2727
+ },
2728
+ 401: { description: "Invalid credentials" }
2729
+ }
2730
+ }
2731
+ };
2732
+ spec.paths[`${path}/logout`] = {
2733
+ post: {
2734
+ tags: [collectionTag],
2735
+ summary: `Log out of ${labels.plural}`,
2736
+ parameters: [
2737
+ {
2738
+ name: "allSessions",
2739
+ in: "query",
2740
+ required: false,
2741
+ schema: { type: "boolean" },
2742
+ description: "Revoke every active session for this account instead of only the current one."
2743
+ }
2744
+ ],
2745
+ responses: { 200: { description: "Logged out" } }
2746
+ }
2747
+ };
2748
+ spec.paths[`${path}/init`] = {
2749
+ get: {
2750
+ tags: [collectionTag],
2751
+ summary: `Get ${labels.plural} initialization state`,
2752
+ security: [],
2753
+ responses: { 200: { description: "Initialization state" } }
2754
+ }
2755
+ };
2756
+ spec.paths[`${path}/first-user`] = {
2757
+ post: publicAuthPost(`Register the first ${labels.singular}`)
2758
+ };
2759
+ spec.paths[`${path}/me`] = {
2760
+ get: {
2761
+ tags: [collectionTag],
2762
+ summary: `Get the current ${labels.singular}`,
2763
+ responses: { 200: { description: "Authenticated user" } }
2764
+ }
2765
+ };
2766
+ spec.paths[`${path}/refresh-token`] = {
2767
+ post: {
2768
+ tags: [collectionTag],
2769
+ summary: "Refresh an authentication token",
2770
+ responses: {
2771
+ 200: {
2772
+ description: "Refreshed token for the current active session"
2773
+ }
2774
+ }
2775
+ }
2776
+ };
2777
+ spec.paths[`${path}/forgot-password`] = {
2778
+ post: publicAuthPost("Request a password reset")
2779
+ };
2780
+ spec.paths[`${path}/reset-password`] = {
2781
+ post: publicAuthPost("Reset a password")
2782
+ };
2783
+ spec.paths[`${path}/invite`] = {
2784
+ post: {
2785
+ tags: [collectionTag],
2786
+ summary: `Invite a ${labels.singular}`,
2787
+ responses: { 200: { description: "Invitation sent" } }
2788
+ }
2789
+ };
2790
+ spec.paths[`${path}/accept-invite`] = {
2791
+ post: publicAuthPost("Accept an invitation")
2792
+ };
2793
+ spec.paths[`${path}/{id}/change-password`] = {
2794
+ post: {
2795
+ tags: [collectionTag],
2796
+ summary: `Change a ${labels.singular} password`,
2797
+ parameters: [
2798
+ {
2799
+ name: "id",
2800
+ in: "path",
2801
+ required: true,
2802
+ schema: { type: "string" }
2803
+ }
2804
+ ],
2805
+ responses: {
2806
+ 200: {
2807
+ description: "Password changed and active sessions revoked"
2808
+ }
2809
+ }
2810
+ }
2811
+ };
2812
+ }
2813
+ if (collection.workflow) {
2814
+ spec.paths[`${path}/{id}/transitions/{transition}`] = {
2815
+ post: {
2816
+ tags: [collectionTag],
2817
+ summary: `Transition ${labels.singular} workflow`,
2818
+ parameters: [
2819
+ {
2820
+ name: "id",
2821
+ in: "path",
2822
+ required: true,
2823
+ schema: { type: "string" }
2824
+ },
2825
+ {
2826
+ name: "transition",
2827
+ in: "path",
2828
+ required: true,
2829
+ schema: {
2830
+ type: "string",
2831
+ enum: collection.workflow.transitions.map((item) => item.name)
2832
+ }
2833
+ }
2834
+ ],
2835
+ requestBody: {
2836
+ content: {
2837
+ "application/json": {
2838
+ schema: {
2839
+ $ref: "#/components/schemas/WorkflowTransitionRequest"
2840
+ }
2841
+ }
2842
+ }
2843
+ },
2844
+ responses: {
2845
+ 200: {
2846
+ description: "Transition applied",
2847
+ content: {
2848
+ "application/json": {
2849
+ schema: { $ref: `#/components/schemas/${slug}` }
2850
+ }
2851
+ }
2852
+ },
2853
+ 400: { description: "Required transition input is missing" },
2854
+ 403: { description: "Transition capability denied" },
2855
+ 409: { description: "Invalid state or stale revision" }
2856
+ }
2857
+ }
2858
+ };
2859
+ spec.paths[`${path}/{id}/workflow-history`] = {
2860
+ get: {
2861
+ tags: [collectionTag],
2862
+ summary: `Get ${labels.singular} workflow history`,
2863
+ parameters: [
2864
+ {
2865
+ name: "id",
2866
+ in: "path",
2867
+ required: true,
2868
+ schema: { type: "string" }
2869
+ },
2870
+ {
2871
+ name: "limit",
2872
+ in: "query",
2873
+ schema: { type: "integer", default: 50, maximum: 100 }
2874
+ }
2875
+ ],
2876
+ responses: {
2877
+ 200: {
2878
+ description: "Workflow transition history",
2879
+ content: {
2880
+ "application/json": {
2881
+ schema: {
2882
+ type: "object",
2883
+ properties: {
2884
+ docs: {
2885
+ type: "array",
2886
+ items: {
2887
+ $ref: "#/components/schemas/WorkflowHistoryEntry"
2888
+ }
2889
+ },
2890
+ total: { type: "integer" },
2891
+ limit: { type: "integer" },
2892
+ page: { type: "integer" }
2893
+ }
2894
+ }
2895
+ }
2896
+ }
2897
+ },
2898
+ 403: { description: "Collection read access denied" }
2899
+ }
2900
+ }
2901
+ };
2902
+ }
2903
+ }
2904
+ for (const global of config.globals) {
2905
+ const slug = global.slug;
2906
+ const path = `/api/globals/${slug}`;
2907
+ const globalTag = getGlobalTag(global);
2908
+ spec.paths[path] = {
2909
+ get: {
2910
+ tags: [globalTag],
2911
+ summary: `Get ${global.label || slug}`,
2912
+ responses: {
2913
+ 200: {
2914
+ description: "Success",
2915
+ content: {
2916
+ "application/json": {
2917
+ schema: { $ref: `#/components/schemas/${slug}` }
2918
+ }
2919
+ }
2920
+ }
2921
+ }
2922
+ },
2923
+ patch: {
2924
+ tags: [globalTag],
2925
+ summary: `Update ${global.label || slug}`,
2926
+ requestBody: {
2927
+ required: true,
2928
+ content: {
2929
+ "application/json": {
2930
+ schema: { $ref: `#/components/schemas/${slug}` }
2931
+ }
2932
+ }
2933
+ },
2934
+ responses: {
2935
+ 200: {
2936
+ description: "Updated",
2937
+ content: {
2938
+ "application/json": {
2939
+ schema: { $ref: `#/components/schemas/${slug}` }
2940
+ }
2941
+ }
2942
+ }
2943
+ }
2944
+ }
2945
+ };
2946
+ }
2947
+ if (config.storage) {
2948
+ spec.paths["/api/media/{filename}"] = {
2949
+ get: {
2950
+ tags: ["Media"],
2951
+ summary: "Serve a stored file",
2952
+ security: [],
2953
+ parameters: [
2954
+ {
2955
+ name: "filename",
2956
+ in: "path",
2957
+ required: true,
2958
+ schema: { type: "string" }
2959
+ }
2960
+ ],
2961
+ responses: {
2962
+ 200: { description: "Stored file bytes" },
2963
+ 404: { description: "File not found" }
2964
+ }
2965
+ }
2966
+ };
2967
+ }
2968
+ return spec;
2969
+ }
2970
+ function collectionToSchema(collection) {
2971
+ const { properties, required } = fieldsToProperties(collection.fields);
2972
+ return {
2973
+ type: "object",
2974
+ properties: {
2975
+ id: { type: "string" },
2976
+ createdAt: { type: "string", format: "date-time" },
2977
+ updatedAt: { type: "string", format: "date-time" },
2978
+ ...collection.workflow ? { _workflow: { $ref: "#/components/schemas/WorkflowMetadata" } } : {},
2979
+ ...properties
2980
+ },
2981
+ required: ["id", ...required]
2982
+ };
2983
+ }
2984
+ function globalToSchema(global) {
2985
+ const { properties, required } = fieldsToProperties(global.fields);
2986
+ return {
2987
+ type: "object",
2988
+ properties,
2989
+ required
2990
+ };
2991
+ }
2992
+ function fieldsToProperties(fields) {
2993
+ const props = {};
2994
+ const required = [];
2995
+ for (const field of fields) {
2996
+ if (field.type === "row") {
2997
+ const nested = fieldsToProperties(field.fields || []);
2998
+ Object.assign(props, nested.properties);
2999
+ required.push(...nested.required);
3000
+ continue;
3001
+ }
3002
+ if (!field.name) continue;
3003
+ props[field.name] = fieldToSchema(field);
3004
+ if (field.required) {
3005
+ required.push(field.name);
3006
+ }
3007
+ }
3008
+ return { properties: props, required };
3009
+ }
3010
+ function fieldToSchema(field) {
3011
+ let schema;
3012
+ switch (field.type) {
3013
+ case "text":
3014
+ case "textarea":
3015
+ case "email":
3016
+ schema = { type: "string" };
3017
+ break;
3018
+ case "url":
3019
+ schema = {
3020
+ oneOf: [
3021
+ { type: "string" },
3022
+ { type: "object", additionalProperties: true }
3023
+ ]
3024
+ };
3025
+ break;
3026
+ case "icon":
3027
+ schema = { type: "string" };
3028
+ break;
3029
+ case "number":
3030
+ schema = { type: "number" };
3031
+ break;
3032
+ case "boolean":
3033
+ schema = { type: "boolean" };
3034
+ break;
3035
+ case "date":
3036
+ schema = { type: "string", format: "date" };
3037
+ break;
3038
+ case "datetime":
3039
+ schema = { type: "string", format: "date-time" };
3040
+ break;
3041
+ case "time":
3042
+ schema = { type: "string", format: "time" };
3043
+ break;
3044
+ case "select":
3045
+ case "radio":
3046
+ schema = {
3047
+ type: "string",
3048
+ enum: Array.isArray(field.options) ? field.options.map((o) => typeof o === "string" ? o : o.value) : void 0
3049
+ };
3050
+ break;
3051
+ case "multiSelect":
3052
+ schema = {
3053
+ type: "array",
3054
+ items: {
3055
+ type: "string",
3056
+ enum: Array.isArray(field.options) ? field.options.map((o) => typeof o === "string" ? o : o.value) : void 0
3057
+ }
3058
+ };
3059
+ break;
3060
+ case "relationship":
3061
+ case "image": {
3062
+ const valueSchema = {
3063
+ type: "string",
3064
+ description: `ID of a ${field.relationTo} record`
3065
+ };
3066
+ schema = field.hasMany ? { type: "array", items: valueSchema } : valueSchema;
3067
+ break;
3068
+ }
3069
+ case "join":
3070
+ schema = {
3071
+ type: "array",
3072
+ readOnly: true,
3073
+ items: { type: "object", additionalProperties: true }
3074
+ };
3075
+ break;
3076
+ case "object": {
3077
+ const { properties, required } = fieldsToProperties(field.fields || []);
3078
+ schema = { type: "object", properties, required };
3079
+ break;
3080
+ }
3081
+ case "array": {
3082
+ const { properties, required } = fieldsToProperties(field.fields || []);
3083
+ schema = {
3084
+ type: "array",
3085
+ items: { type: "object", properties, required }
3086
+ };
3087
+ break;
3088
+ }
3089
+ case "json":
3090
+ case "richText":
3091
+ schema = { type: "object", additionalProperties: true };
3092
+ break;
3093
+ case "blocks":
3094
+ schema = {
3095
+ type: "array",
3096
+ items: {
3097
+ oneOf: field.blocks?.map((block) => {
3098
+ const { properties, required } = fieldsToProperties(block.fields);
3099
+ return {
3100
+ type: "object",
3101
+ properties: {
3102
+ blockType: { type: "string", enum: [block.slug] },
3103
+ ...properties
3104
+ },
3105
+ required: ["blockType", ...required]
3106
+ };
3107
+ })
3108
+ }
3109
+ };
3110
+ break;
3111
+ default:
3112
+ schema = { type: "string" };
3113
+ }
3114
+ if (field.label) schema.description = field.label;
3115
+ return schema;
3116
+ }
3117
+
3118
+ export {
3119
+ signCollectionToken,
3120
+ verifyCollectionToken,
3121
+ issueAuthSessionToken,
3122
+ getAuthSession,
3123
+ isAuthSessionActive,
3124
+ touchAuthSession,
3125
+ revokeAuthSession,
3126
+ revokeAllAuthSessions,
3127
+ WORKFLOW_HISTORY_COLLECTION,
3128
+ LIFECYCLE_EVENTS_COLLECTION,
3129
+ definePublishingWorkflow,
3130
+ publishingWorkflow,
3131
+ simplePublishingWorkflow,
3132
+ workflowCapabilities,
3133
+ canViewWorkflowDraft,
3134
+ availableWorkflowTransitions,
3135
+ initializeWorkflowDocument,
3136
+ publishedStateName,
3137
+ materializeWorkflowDocument,
3138
+ createLifecycleEvent,
3139
+ dispatchLifecycleEvent,
3140
+ dispatchPendingLifecycleEvents,
3141
+ saveWorkflowDraft,
3142
+ createWorkflowDocument,
3143
+ transitionWorkflow,
3144
+ getAdminAuthCollection,
3145
+ resolveAdminAuthCollection,
3146
+ getPublicAdminAuthConfig,
3147
+ mergeDynamicConfig,
3148
+ slugify,
3149
+ lower,
3150
+ upper,
3151
+ trim,
3152
+ capitalize,
3153
+ truncate,
3154
+ readingTime,
3155
+ wordCount,
3156
+ replace,
3157
+ startsWith,
3158
+ endsWith,
3159
+ now,
3160
+ today,
3161
+ formatDate,
3162
+ addDays,
3163
+ diffDays,
3164
+ isPast,
3165
+ isFuture,
3166
+ includes,
3167
+ join,
3168
+ first,
3169
+ last,
3170
+ compact,
3171
+ unique,
3172
+ length,
3173
+ round,
3174
+ clamp,
3175
+ defaultValue,
3176
+ coalesce,
3177
+ isEmpty,
3178
+ get,
3179
+ registerJexlHelpers,
3180
+ BUILTIN_JEXL_HELPERS,
3181
+ validateDeclarativeHookExpression,
3182
+ validateDeclarativeAccessExpression,
3183
+ validateAdminConditionExpression,
3184
+ validatePreviewUrlExpression,
3185
+ assertValidDeclarativeHookExpression,
3186
+ assertValidDeclarativeHookResult,
3187
+ collectDeclarativeHookValidationIssues,
3188
+ collectDeclarativeAccessValidationIssues,
3189
+ collectAdminConditionValidationIssues,
3190
+ collectPreviewUrlValidationIssues,
3191
+ assertValidAdminConditionsInConfig,
3192
+ assertValidPreviewUrlsInConfig,
3193
+ collectConfigDiagnostics,
3194
+ formatConfigDiagnostics,
3195
+ ConfigValidationError,
3196
+ isConfigValidationError,
3197
+ assertValidDeclarativeHooksInConfig,
3198
+ assertValidDeclarativeAccessInConfig,
3199
+ normalizeConfig,
3200
+ runCollectionHooks,
3201
+ executeFieldBeforeChange,
3202
+ executeFieldAfterRead,
3203
+ generateOpenApi
3204
+ };