@dyrected/core 2.5.29 → 2.5.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-6ZXEGKT6.js +619 -0
- package/dist/chunk-CQDVPMEU.js +613 -0
- package/dist/chunk-Y4AYI52W.js +631 -0
- package/dist/chunk-YDOBB7MY.js +1457 -0
- package/dist/index-CdQwnbfh.d.cts +1889 -0
- package/dist/index-CdQwnbfh.d.ts +1889 -0
- package/dist/index-DTrpTru7.d.cts +1881 -0
- package/dist/index-DTrpTru7.d.ts +1881 -0
- package/dist/index-DzUlE5Hc.d.cts +1751 -0
- package/dist/index-DzUlE5Hc.d.ts +1751 -0
- package/dist/index-M_m6dXZV.d.cts +1889 -0
- package/dist/index-M_m6dXZV.d.ts +1889 -0
- package/dist/index-qhLus8ZO.d.cts +1881 -0
- package/dist/index-qhLus8ZO.d.ts +1881 -0
- package/dist/index.cjs +1159 -812
- package/dist/index.d.cts +66 -18
- package/dist/index.d.ts +66 -18
- package/dist/index.js +42 -825
- package/dist/server.cjs +1079 -217
- package/dist/server.d.cts +33 -1
- package/dist/server.d.ts +33 -1
- package/dist/server.js +267 -494
- package/dist/where-sanitizer-WJ2W2QCE.js +54 -0
- package/package.json +2 -1
|
@@ -0,0 +1,619 @@
|
|
|
1
|
+
// src/workflows.ts
|
|
2
|
+
var WORKFLOW_HISTORY_COLLECTION = "__workflow_history";
|
|
3
|
+
var LIFECYCLE_EVENTS_COLLECTION = "__lifecycle_events";
|
|
4
|
+
function publishingWorkflow() {
|
|
5
|
+
return {
|
|
6
|
+
initialState: "draft",
|
|
7
|
+
draftState: "draft",
|
|
8
|
+
states: [
|
|
9
|
+
{ name: "draft", label: "Draft", color: "neutral" },
|
|
10
|
+
{ name: "in_review", label: "In review", color: "warning" },
|
|
11
|
+
{ name: "published", label: "Published", color: "success", published: true }
|
|
12
|
+
],
|
|
13
|
+
transitions: [
|
|
14
|
+
{ name: "submit", label: "Submit for review", from: "draft", to: "in_review", requiredCapabilities: ["entry.submit"] },
|
|
15
|
+
{ name: "publish", label: "Publish", from: "in_review", to: "published", requiredCapabilities: ["entry.publish"] },
|
|
16
|
+
{ name: "reject", label: "Request changes", from: "in_review", to: "draft", requiredCapabilities: ["entry.publish"], requireComment: true },
|
|
17
|
+
{ name: "unpublish", label: "Unpublish", from: "published", to: "draft", requiredCapabilities: ["entry.unpublish"], unpublish: true }
|
|
18
|
+
],
|
|
19
|
+
roles: [
|
|
20
|
+
{ role: "editor", capabilities: ["entry.edit", "entry.submit"] },
|
|
21
|
+
{ role: "publisher", capabilities: ["entry.edit", "entry.submit", "entry.publish", "entry.unpublish"] },
|
|
22
|
+
{ role: "admin", capabilities: ["entry.edit", "entry.submit", "entry.publish", "entry.unpublish"] }
|
|
23
|
+
]
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function publicMetadata(meta) {
|
|
27
|
+
const { availableTransitions: _availableTransitions, ...safe } = meta;
|
|
28
|
+
return safe;
|
|
29
|
+
}
|
|
30
|
+
function workflowCapabilities(workflow, user) {
|
|
31
|
+
const capabilities = new Set(Array.isArray(user?.capabilities) ? user.capabilities : []);
|
|
32
|
+
const roles = Array.isArray(user?.roles) ? user.roles : [];
|
|
33
|
+
for (const mapping of workflow.roles ?? []) {
|
|
34
|
+
if (roles.includes(mapping.role)) mapping.capabilities.forEach((capability) => capabilities.add(capability));
|
|
35
|
+
}
|
|
36
|
+
return capabilities;
|
|
37
|
+
}
|
|
38
|
+
function availableWorkflowTransitions(workflow, state, user) {
|
|
39
|
+
const capabilities = workflowCapabilities(workflow, user);
|
|
40
|
+
return workflow.transitions.filter((transition) => {
|
|
41
|
+
const from = Array.isArray(transition.from) ? transition.from : [transition.from];
|
|
42
|
+
return from.includes(state) && (transition.requiredCapabilities ?? []).every((item) => capabilities.has(item));
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
function initializeWorkflowDocument(data, workflow) {
|
|
46
|
+
return {
|
|
47
|
+
...data,
|
|
48
|
+
__workflow: { state: workflow.initialState, revision: 1 }
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function materializeWorkflowDocument(doc, workflow, user) {
|
|
52
|
+
const meta = doc.__workflow;
|
|
53
|
+
if (!meta) return doc;
|
|
54
|
+
const { __published, __workflow, ...working } = doc;
|
|
55
|
+
if (!user) {
|
|
56
|
+
if (!__published || typeof __published !== "object") return null;
|
|
57
|
+
return { id: doc.id, ...__published, _workflow: publicMetadata(meta) };
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
...working,
|
|
61
|
+
_workflow: {
|
|
62
|
+
...meta,
|
|
63
|
+
availableTransitions: availableWorkflowTransitions(workflow, meta.state, user).map((item) => item.name)
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
function eventId() {
|
|
68
|
+
return globalThis.crypto?.randomUUID?.() ?? `evt_${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
|
69
|
+
}
|
|
70
|
+
function createLifecycleEvent(args) {
|
|
71
|
+
return {
|
|
72
|
+
id: eventId(),
|
|
73
|
+
name: args.name,
|
|
74
|
+
collection: args.collection,
|
|
75
|
+
documentId: args.documentId,
|
|
76
|
+
occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
77
|
+
actorId: args.actorId,
|
|
78
|
+
payload: args.payload,
|
|
79
|
+
attempts: 0,
|
|
80
|
+
status: "pending"
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
async function persistEvent(db, event) {
|
|
84
|
+
await db.create({ collection: LIFECYCLE_EVENTS_COLLECTION, data: event });
|
|
85
|
+
}
|
|
86
|
+
async function dispatchLifecycleEvent(config, event) {
|
|
87
|
+
const db = config.db;
|
|
88
|
+
if (!db || !config.events?.handlers.length) return;
|
|
89
|
+
const maxAttempts = config.events.maxAttempts ?? 8;
|
|
90
|
+
const retryDelayMs = config.events.retryDelayMs ?? 1e3;
|
|
91
|
+
const attempts = event.attempts + 1;
|
|
92
|
+
try {
|
|
93
|
+
await db.update({ collection: LIFECYCLE_EVENTS_COLLECTION, id: event.id, data: { status: "processing", attempts } });
|
|
94
|
+
for (const handler of config.events.handlers) await handler({ ...event, status: "processing", attempts });
|
|
95
|
+
await db.update({
|
|
96
|
+
collection: LIFECYCLE_EVENTS_COLLECTION,
|
|
97
|
+
id: event.id,
|
|
98
|
+
data: { status: "delivered", attempts, deliveredAt: (/* @__PURE__ */ new Date()).toISOString(), lastError: null }
|
|
99
|
+
});
|
|
100
|
+
} catch (error) {
|
|
101
|
+
const exhausted = attempts >= maxAttempts;
|
|
102
|
+
await db.update({
|
|
103
|
+
collection: LIFECYCLE_EVENTS_COLLECTION,
|
|
104
|
+
id: event.id,
|
|
105
|
+
data: {
|
|
106
|
+
status: "failed",
|
|
107
|
+
attempts,
|
|
108
|
+
lastError: error instanceof Error ? error.message : String(error),
|
|
109
|
+
nextAttemptAt: exhausted ? null : new Date(Date.now() + retryDelayMs * 2 ** (attempts - 1)).toISOString()
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
async function dispatchPendingLifecycleEvents(config, limit = 50) {
|
|
115
|
+
if (!config.db || !config.events?.handlers.length) return 0;
|
|
116
|
+
const result = await config.db.find({
|
|
117
|
+
collection: LIFECYCLE_EVENTS_COLLECTION,
|
|
118
|
+
where: { status: { in: ["pending", "failed"] } },
|
|
119
|
+
sort: "occurredAt",
|
|
120
|
+
limit
|
|
121
|
+
});
|
|
122
|
+
const now = Date.now();
|
|
123
|
+
const due = result.docs.filter((doc) => !doc.nextAttemptAt || new Date(doc.nextAttemptAt).getTime() <= now);
|
|
124
|
+
for (const event of due) await dispatchLifecycleEvent(config, event);
|
|
125
|
+
return due.length;
|
|
126
|
+
}
|
|
127
|
+
async function saveWorkflowDraft(args) {
|
|
128
|
+
const { config, collection, id, originalDoc, data, user } = args;
|
|
129
|
+
const db = config.db;
|
|
130
|
+
const workflow = collection.workflow;
|
|
131
|
+
if (!db.transaction) throw new Error(`The configured database adapter does not support workflow transactions.`);
|
|
132
|
+
const previous = originalDoc.__workflow;
|
|
133
|
+
const event = createLifecycleEvent({
|
|
134
|
+
name: "revision.created",
|
|
135
|
+
collection: collection.slug,
|
|
136
|
+
documentId: id,
|
|
137
|
+
actorId: user?.sub,
|
|
138
|
+
payload: { revision: previous.revision + 1, previousRevision: previous.revision }
|
|
139
|
+
});
|
|
140
|
+
const doc = await db.transaction(async (tx) => {
|
|
141
|
+
const nextMeta = {
|
|
142
|
+
...previous,
|
|
143
|
+
state: originalDoc.__published ? workflow.draftState ?? workflow.initialState : previous.state,
|
|
144
|
+
revision: previous.revision + 1
|
|
145
|
+
};
|
|
146
|
+
const updated = await tx.update({ collection: collection.slug, id, data: { ...data, __workflow: nextMeta } });
|
|
147
|
+
await persistEvent(tx, event);
|
|
148
|
+
return updated;
|
|
149
|
+
});
|
|
150
|
+
void dispatchLifecycleEvent(config, event);
|
|
151
|
+
return { doc, event };
|
|
152
|
+
}
|
|
153
|
+
async function createWorkflowDocument(args) {
|
|
154
|
+
const { config, collection, data, user } = args;
|
|
155
|
+
const db = config.db;
|
|
156
|
+
if (!db.transaction) throw new Error(`The configured database adapter does not support workflow transactions.`);
|
|
157
|
+
let event;
|
|
158
|
+
const doc = await db.transaction(async (tx) => {
|
|
159
|
+
const created = await tx.create({ collection: collection.slug, data });
|
|
160
|
+
event = createLifecycleEvent({
|
|
161
|
+
name: "revision.created",
|
|
162
|
+
collection: collection.slug,
|
|
163
|
+
documentId: created.id,
|
|
164
|
+
actorId: user?.sub,
|
|
165
|
+
payload: { revision: 1, previousRevision: null }
|
|
166
|
+
});
|
|
167
|
+
await persistEvent(tx, event);
|
|
168
|
+
return created;
|
|
169
|
+
});
|
|
170
|
+
void dispatchLifecycleEvent(config, event);
|
|
171
|
+
return { doc, event };
|
|
172
|
+
}
|
|
173
|
+
async function transitionWorkflow(args) {
|
|
174
|
+
const { config, collection, id, transitionName, expectedRevision, comment, user, req } = args;
|
|
175
|
+
const db = config.db;
|
|
176
|
+
const workflow = collection.workflow;
|
|
177
|
+
if (!db.transaction) throw new Error(`The configured database adapter does not support workflow transactions.`);
|
|
178
|
+
const original = await db.findOne({ collection: collection.slug, id });
|
|
179
|
+
if (!original) throw Object.assign(new Error("Not Found"), { statusCode: 404 });
|
|
180
|
+
const meta = original.__workflow;
|
|
181
|
+
if (!meta) throw Object.assign(new Error("Entry has no workflow metadata"), { statusCode: 409 });
|
|
182
|
+
if (expectedRevision !== void 0 && expectedRevision !== meta.revision) {
|
|
183
|
+
throw Object.assign(new Error("This entry changed since it was loaded. Refresh before transitioning it."), { statusCode: 409 });
|
|
184
|
+
}
|
|
185
|
+
const transition = workflow.transitions.find((item) => item.name === transitionName);
|
|
186
|
+
const fromStates = transition ? Array.isArray(transition.from) ? transition.from : [transition.from] : [];
|
|
187
|
+
if (!transition || !fromStates.includes(meta.state)) {
|
|
188
|
+
throw Object.assign(new Error(`Transition "${transitionName}" is not valid from "${meta.state}".`), { statusCode: 409 });
|
|
189
|
+
}
|
|
190
|
+
if (!availableWorkflowTransitions(workflow, meta.state, user).some((item) => item.name === transition.name)) {
|
|
191
|
+
throw Object.assign(new Error(`You do not have permission to perform "${transition.label}".`), { statusCode: 403 });
|
|
192
|
+
}
|
|
193
|
+
if (transition.requireComment && !comment?.trim()) {
|
|
194
|
+
throw Object.assign(new Error(`A comment is required for "${transition.label}".`), { statusCode: 400 });
|
|
195
|
+
}
|
|
196
|
+
const hookContext = { transition, from: meta.state, to: transition.to, doc: original, user, comment, req, db };
|
|
197
|
+
for (const hook of workflow.hooks?.beforeTransition ?? []) await hook(hookContext);
|
|
198
|
+
const events = [createLifecycleEvent({
|
|
199
|
+
name: "workflow.transitioned",
|
|
200
|
+
collection: collection.slug,
|
|
201
|
+
documentId: id,
|
|
202
|
+
actorId: user?.sub,
|
|
203
|
+
payload: { transition: transition.name, from: meta.state, to: transition.to, revision: meta.revision, comment }
|
|
204
|
+
})];
|
|
205
|
+
const targetState = workflow.states.find((state) => state.name === transition.to);
|
|
206
|
+
if (targetState.published) {
|
|
207
|
+
events.push(createLifecycleEvent({ name: "entry.published", collection: collection.slug, documentId: id, actorId: user?.sub, payload: { revision: meta.revision } }));
|
|
208
|
+
} else if (transition.unpublish) {
|
|
209
|
+
events.push(createLifecycleEvent({ name: "entry.unpublished", collection: collection.slug, documentId: id, actorId: user?.sub, payload: { revision: meta.publishedRevision } }));
|
|
210
|
+
}
|
|
211
|
+
const updated = await db.transaction(async (tx) => {
|
|
212
|
+
const locked = await tx.findOne({ collection: collection.slug, id });
|
|
213
|
+
if (!locked) throw Object.assign(new Error("Not Found"), { statusCode: 404 });
|
|
214
|
+
const lockedMeta = locked.__workflow;
|
|
215
|
+
if (lockedMeta.revision !== meta.revision || lockedMeta.state !== meta.state || expectedRevision !== void 0 && lockedMeta.revision !== expectedRevision) {
|
|
216
|
+
throw Object.assign(new Error("This entry changed since it was loaded. Refresh before transitioning it."), { statusCode: 409 });
|
|
217
|
+
}
|
|
218
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
219
|
+
const { __published: _published, __workflow: _workflow, id: _id, ...working } = locked;
|
|
220
|
+
const nextMeta = {
|
|
221
|
+
...lockedMeta,
|
|
222
|
+
state: transition.to,
|
|
223
|
+
...targetState.published ? { publishedRevision: lockedMeta.revision, publishedAt: now, publishedBy: user?.sub } : {},
|
|
224
|
+
...transition.unpublish ? { publishedRevision: void 0, publishedAt: void 0, publishedBy: void 0 } : {}
|
|
225
|
+
};
|
|
226
|
+
const data = { __workflow: nextMeta };
|
|
227
|
+
if (targetState.published) data.__published = working;
|
|
228
|
+
if (transition.unpublish) data.__published = null;
|
|
229
|
+
const next = await tx.update({ collection: collection.slug, id, data });
|
|
230
|
+
await tx.create({
|
|
231
|
+
collection: WORKFLOW_HISTORY_COLLECTION,
|
|
232
|
+
data: { collection: collection.slug, documentId: id, transition: transition.name, from: lockedMeta.state, to: transition.to, revision: lockedMeta.revision, comment: comment ?? null, actorId: user?.sub ?? null, createdAt: now }
|
|
233
|
+
});
|
|
234
|
+
for (const event of events) await persistEvent(tx, event);
|
|
235
|
+
if (collection.audit) {
|
|
236
|
+
await tx.create({ collection: "__audit", data: { collection: collection.slug, documentId: id, operation: "workflow.transition", user: user?.sub ?? null, timestamp: now, changes: JSON.stringify({ transition: transition.name, from: lockedMeta.state, to: transition.to, revision: lockedMeta.revision }) } });
|
|
237
|
+
}
|
|
238
|
+
return next;
|
|
239
|
+
});
|
|
240
|
+
for (const event of events) void dispatchLifecycleEvent(config, event);
|
|
241
|
+
for (const hook of workflow.hooks?.afterTransition ?? []) {
|
|
242
|
+
try {
|
|
243
|
+
await hook({ ...hookContext, doc: updated, event: events[0] });
|
|
244
|
+
} catch (error) {
|
|
245
|
+
console.error("[dyrected/workflow] afterTransition hook failed:", error);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
return updated;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// src/utils/config.ts
|
|
252
|
+
var AUDIT_COLLECTION_SLUG = "__audit";
|
|
253
|
+
var SYSTEM_FIELDS = [
|
|
254
|
+
{
|
|
255
|
+
name: "createdAt",
|
|
256
|
+
type: "date",
|
|
257
|
+
label: "Created At",
|
|
258
|
+
admin: { readOnly: true, hidden: true }
|
|
259
|
+
},
|
|
260
|
+
{
|
|
261
|
+
name: "updatedAt",
|
|
262
|
+
type: "date",
|
|
263
|
+
label: "Updated At",
|
|
264
|
+
admin: { readOnly: true, hidden: true }
|
|
265
|
+
},
|
|
266
|
+
{
|
|
267
|
+
name: "createdBy",
|
|
268
|
+
type: "text",
|
|
269
|
+
label: "Created By",
|
|
270
|
+
admin: { readOnly: true, hidden: true }
|
|
271
|
+
},
|
|
272
|
+
{
|
|
273
|
+
name: "updatedBy",
|
|
274
|
+
type: "text",
|
|
275
|
+
label: "Updated By",
|
|
276
|
+
admin: { readOnly: true, hidden: true }
|
|
277
|
+
}
|
|
278
|
+
];
|
|
279
|
+
var AUDIT_COLLECTION = {
|
|
280
|
+
slug: AUDIT_COLLECTION_SLUG,
|
|
281
|
+
labels: { singular: "Audit Log", plural: "Audit Logs" },
|
|
282
|
+
fields: [
|
|
283
|
+
{ name: "collection", type: "text", label: "Collection", required: true },
|
|
284
|
+
{ name: "documentId", type: "text", label: "Document ID" },
|
|
285
|
+
{ name: "operation", type: "select", label: "Operation", options: ["create", "update", "delete"], required: true },
|
|
286
|
+
{ name: "user", type: "text", label: "User ID" },
|
|
287
|
+
{ name: "timestamp", type: "date", label: "Timestamp", required: true },
|
|
288
|
+
{ name: "changes", type: "json", label: "Changes" }
|
|
289
|
+
],
|
|
290
|
+
admin: { hidden: true }
|
|
291
|
+
};
|
|
292
|
+
var WORKFLOW_HISTORY_COLLECTION_CONFIG = {
|
|
293
|
+
slug: WORKFLOW_HISTORY_COLLECTION,
|
|
294
|
+
labels: { singular: "Workflow transition", plural: "Workflow transitions" },
|
|
295
|
+
fields: [
|
|
296
|
+
{ name: "collection", type: "text", required: true },
|
|
297
|
+
{ name: "documentId", type: "text", required: true },
|
|
298
|
+
{ name: "transition", type: "text", required: true },
|
|
299
|
+
{ name: "from", type: "text", required: true },
|
|
300
|
+
{ name: "to", type: "text", required: true },
|
|
301
|
+
{ name: "revision", type: "number", required: true },
|
|
302
|
+
{ name: "comment", type: "textarea" },
|
|
303
|
+
{ name: "actorId", type: "text" },
|
|
304
|
+
{ name: "createdAt", type: "date", required: true }
|
|
305
|
+
],
|
|
306
|
+
access: { read: ({ user }) => !!user, create: () => false, update: () => false, delete: () => false },
|
|
307
|
+
admin: { hidden: true }
|
|
308
|
+
};
|
|
309
|
+
var LIFECYCLE_EVENTS_COLLECTION_CONFIG = {
|
|
310
|
+
slug: LIFECYCLE_EVENTS_COLLECTION,
|
|
311
|
+
labels: { singular: "Lifecycle event", plural: "Lifecycle events" },
|
|
312
|
+
fields: [
|
|
313
|
+
{ name: "name", type: "text", required: true },
|
|
314
|
+
{ name: "collection", type: "text", required: true },
|
|
315
|
+
{ name: "documentId", type: "text", required: true },
|
|
316
|
+
{ name: "occurredAt", type: "date", required: true },
|
|
317
|
+
{ name: "actorId", type: "text" },
|
|
318
|
+
{ name: "payload", type: "json", required: true },
|
|
319
|
+
{ name: "attempts", type: "number", required: true },
|
|
320
|
+
{ name: "status", type: "select", options: ["pending", "processing", "delivered", "failed"], required: true },
|
|
321
|
+
{ name: "nextAttemptAt", type: "date" },
|
|
322
|
+
{ name: "deliveredAt", type: "date" },
|
|
323
|
+
{ name: "lastError", type: "textarea" }
|
|
324
|
+
],
|
|
325
|
+
access: { read: ({ user }) => !!user?.roles?.includes("admin"), create: () => false, update: () => false, delete: () => false },
|
|
326
|
+
admin: { hidden: true }
|
|
327
|
+
};
|
|
328
|
+
function normalizeConfig(config) {
|
|
329
|
+
const collections = config?.collections || [];
|
|
330
|
+
const globals = config?.globals || [];
|
|
331
|
+
const needsAudit = collections.some((col) => col.audit);
|
|
332
|
+
const needsWorkflow = collections.some((col) => col.workflow);
|
|
333
|
+
const normalizedCollections = collections.map((col) => {
|
|
334
|
+
let fields = col.fields || [];
|
|
335
|
+
const existingFieldNames = new Set(fields.map((f) => f.name));
|
|
336
|
+
if (col.auth) {
|
|
337
|
+
if (!existingFieldNames.has("email")) {
|
|
338
|
+
fields = [
|
|
339
|
+
...fields,
|
|
340
|
+
{
|
|
341
|
+
name: "email",
|
|
342
|
+
type: "email",
|
|
343
|
+
label: "Email",
|
|
344
|
+
required: true,
|
|
345
|
+
unique: true,
|
|
346
|
+
promoted: true,
|
|
347
|
+
access: {
|
|
348
|
+
update: "!id"
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
];
|
|
352
|
+
}
|
|
353
|
+
if (!existingFieldNames.has("password")) {
|
|
354
|
+
fields = [
|
|
355
|
+
...fields,
|
|
356
|
+
{
|
|
357
|
+
name: "password",
|
|
358
|
+
type: "text",
|
|
359
|
+
label: "Password",
|
|
360
|
+
required: true,
|
|
361
|
+
access: {
|
|
362
|
+
update: "!id || user.id == id"
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
];
|
|
366
|
+
}
|
|
367
|
+
if (!existingFieldNames.has("roles")) {
|
|
368
|
+
fields = [
|
|
369
|
+
...fields,
|
|
370
|
+
{
|
|
371
|
+
name: "roles",
|
|
372
|
+
type: "select",
|
|
373
|
+
label: "Roles",
|
|
374
|
+
defaultValue: [],
|
|
375
|
+
options: [
|
|
376
|
+
{ value: "admin", label: "Admin" },
|
|
377
|
+
{ value: "editor", label: "Editor" },
|
|
378
|
+
{ value: "viewer", label: "Viewer" }
|
|
379
|
+
],
|
|
380
|
+
access: {
|
|
381
|
+
update: "user.roles && 'admin' in user.roles"
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
];
|
|
385
|
+
}
|
|
386
|
+
fields = fields.map((field) => {
|
|
387
|
+
if (field.name === "email") {
|
|
388
|
+
return {
|
|
389
|
+
...field,
|
|
390
|
+
access: {
|
|
391
|
+
...field.access || {},
|
|
392
|
+
update: "!id"
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
if (field.name === "password") {
|
|
397
|
+
return {
|
|
398
|
+
...field,
|
|
399
|
+
admin: { ...field.admin || {} },
|
|
400
|
+
access: {
|
|
401
|
+
...field.access || {},
|
|
402
|
+
update: "!id || user.id == id"
|
|
403
|
+
}
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
if (field.name === "roles") {
|
|
407
|
+
return {
|
|
408
|
+
...field,
|
|
409
|
+
access: {
|
|
410
|
+
...field.access || {},
|
|
411
|
+
// Must be an admin; cannot edit own roles (no self-elevation).
|
|
412
|
+
update: "user.roles && 'admin' in user.roles && user.id != id"
|
|
413
|
+
}
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
return field;
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
const updatedFieldNames = new Set(fields.map((f) => f.name));
|
|
420
|
+
const fieldsToInject = SYSTEM_FIELDS.filter((f) => !updatedFieldNames.has(f.name));
|
|
421
|
+
return {
|
|
422
|
+
...col,
|
|
423
|
+
fields: [...fields, ...fieldsToInject]
|
|
424
|
+
};
|
|
425
|
+
});
|
|
426
|
+
const hasAuditCollection = normalizedCollections.some((col) => col.slug === AUDIT_COLLECTION_SLUG);
|
|
427
|
+
const systemCollections = [];
|
|
428
|
+
if (needsAudit && !hasAuditCollection) systemCollections.push(AUDIT_COLLECTION);
|
|
429
|
+
if (needsWorkflow && !normalizedCollections.some((col) => col.slug === WORKFLOW_HISTORY_COLLECTION)) {
|
|
430
|
+
systemCollections.push(WORKFLOW_HISTORY_COLLECTION_CONFIG);
|
|
431
|
+
}
|
|
432
|
+
if (needsWorkflow && !normalizedCollections.some((col) => col.slug === LIFECYCLE_EVENTS_COLLECTION)) {
|
|
433
|
+
systemCollections.push(LIFECYCLE_EVENTS_COLLECTION_CONFIG);
|
|
434
|
+
}
|
|
435
|
+
return {
|
|
436
|
+
...config,
|
|
437
|
+
collections: [...normalizedCollections, ...systemCollections],
|
|
438
|
+
globals
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
// src/utils/hooks.ts
|
|
443
|
+
async function runCollectionHooks(hooks, args, options = {}) {
|
|
444
|
+
if (!hooks || hooks.length === 0) {
|
|
445
|
+
return args.data ?? args.doc ?? void 0;
|
|
446
|
+
}
|
|
447
|
+
let currentPayload = args.data ?? args.doc ?? void 0;
|
|
448
|
+
for (const hook of hooks) {
|
|
449
|
+
try {
|
|
450
|
+
const result = await hook({
|
|
451
|
+
...args,
|
|
452
|
+
data: args.data !== void 0 ? currentPayload : void 0,
|
|
453
|
+
doc: args.doc !== void 0 ? currentPayload : void 0
|
|
454
|
+
});
|
|
455
|
+
if (result !== void 0) {
|
|
456
|
+
currentPayload = result;
|
|
457
|
+
}
|
|
458
|
+
} catch (err) {
|
|
459
|
+
if (options.isolated) {
|
|
460
|
+
console.error("[dyrected/core] Side-effect hook failed (error isolated \u2014 DB write was successful):", err);
|
|
461
|
+
} else {
|
|
462
|
+
throw err;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
return currentPayload;
|
|
467
|
+
}
|
|
468
|
+
async function executeFieldBeforeChange(fields, data, originalDoc, user, db) {
|
|
469
|
+
if (!data || typeof data !== "object") return data;
|
|
470
|
+
const result = { ...data };
|
|
471
|
+
for (const field of fields) {
|
|
472
|
+
if (!field.name) continue;
|
|
473
|
+
const value = result[field.name];
|
|
474
|
+
const origValue = originalDoc?.[field.name];
|
|
475
|
+
let updatedValue = value;
|
|
476
|
+
if (field.hooks?.beforeChange) {
|
|
477
|
+
for (const hook of field.hooks.beforeChange) {
|
|
478
|
+
updatedValue = await hook({
|
|
479
|
+
value: updatedValue,
|
|
480
|
+
originalDoc: originalDoc ?? void 0,
|
|
481
|
+
data: result,
|
|
482
|
+
user,
|
|
483
|
+
db
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
result[field.name] = updatedValue;
|
|
487
|
+
}
|
|
488
|
+
if (updatedValue !== void 0 && updatedValue !== null) {
|
|
489
|
+
if (field.type === "object" && field.fields) {
|
|
490
|
+
result[field.name] = await executeFieldBeforeChange(
|
|
491
|
+
field.fields,
|
|
492
|
+
updatedValue,
|
|
493
|
+
origValue,
|
|
494
|
+
user,
|
|
495
|
+
db
|
|
496
|
+
);
|
|
497
|
+
} else if (field.type === "array" && field.fields && Array.isArray(updatedValue)) {
|
|
498
|
+
const arrayResult = [];
|
|
499
|
+
for (let i = 0; i < updatedValue.length; i++) {
|
|
500
|
+
const item = updatedValue[i];
|
|
501
|
+
const origItem = Array.isArray(origValue) ? origValue[i] : null;
|
|
502
|
+
arrayResult.push(
|
|
503
|
+
await executeFieldBeforeChange(field.fields, item, origItem, user, db)
|
|
504
|
+
);
|
|
505
|
+
}
|
|
506
|
+
result[field.name] = arrayResult;
|
|
507
|
+
} else if (field.type === "blocks" && field.blocks && Array.isArray(updatedValue)) {
|
|
508
|
+
const blocksResult = [];
|
|
509
|
+
for (let i = 0; i < updatedValue.length; i++) {
|
|
510
|
+
const blockData = updatedValue[i];
|
|
511
|
+
const origBlock = Array.isArray(origValue) ? origValue[i] : null;
|
|
512
|
+
const blockConfig = field.blocks.find(
|
|
513
|
+
(b) => b.slug === blockData.blockType
|
|
514
|
+
);
|
|
515
|
+
if (blockConfig) {
|
|
516
|
+
blocksResult.push(
|
|
517
|
+
await executeFieldBeforeChange(
|
|
518
|
+
blockConfig.fields,
|
|
519
|
+
blockData,
|
|
520
|
+
origBlock,
|
|
521
|
+
user,
|
|
522
|
+
db
|
|
523
|
+
)
|
|
524
|
+
);
|
|
525
|
+
} else {
|
|
526
|
+
blocksResult.push(blockData);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
result[field.name] = blocksResult;
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
return result;
|
|
534
|
+
}
|
|
535
|
+
async function executeFieldAfterRead(fields, doc, user, db) {
|
|
536
|
+
if (!doc || typeof doc !== "object") return doc;
|
|
537
|
+
const result = { ...doc };
|
|
538
|
+
for (const field of fields) {
|
|
539
|
+
if (!field.name) continue;
|
|
540
|
+
const value = result[field.name];
|
|
541
|
+
let updatedValue = value;
|
|
542
|
+
if (field.hooks?.afterRead) {
|
|
543
|
+
for (const hook of field.hooks.afterRead) {
|
|
544
|
+
updatedValue = await hook({
|
|
545
|
+
value: updatedValue,
|
|
546
|
+
doc: result,
|
|
547
|
+
user,
|
|
548
|
+
db
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
result[field.name] = updatedValue;
|
|
552
|
+
}
|
|
553
|
+
if (updatedValue !== void 0 && updatedValue !== null) {
|
|
554
|
+
if (field.type === "object" && field.fields) {
|
|
555
|
+
result[field.name] = await executeFieldAfterRead(
|
|
556
|
+
field.fields,
|
|
557
|
+
updatedValue,
|
|
558
|
+
user,
|
|
559
|
+
db
|
|
560
|
+
);
|
|
561
|
+
} else if (field.type === "array" && field.fields && Array.isArray(updatedValue)) {
|
|
562
|
+
const arrayResult = [];
|
|
563
|
+
for (const item of updatedValue) {
|
|
564
|
+
arrayResult.push(
|
|
565
|
+
await executeFieldAfterRead(
|
|
566
|
+
field.fields,
|
|
567
|
+
item,
|
|
568
|
+
user,
|
|
569
|
+
db
|
|
570
|
+
)
|
|
571
|
+
);
|
|
572
|
+
}
|
|
573
|
+
result[field.name] = arrayResult;
|
|
574
|
+
} else if (field.type === "blocks" && field.blocks && Array.isArray(updatedValue)) {
|
|
575
|
+
const blocksResult = [];
|
|
576
|
+
for (const blockData of updatedValue) {
|
|
577
|
+
const typedBlock = blockData;
|
|
578
|
+
const blockConfig = field.blocks.find(
|
|
579
|
+
(b) => b.slug === typedBlock.blockType
|
|
580
|
+
);
|
|
581
|
+
if (blockConfig) {
|
|
582
|
+
blocksResult.push(
|
|
583
|
+
await executeFieldAfterRead(
|
|
584
|
+
blockConfig.fields,
|
|
585
|
+
typedBlock,
|
|
586
|
+
user,
|
|
587
|
+
db
|
|
588
|
+
)
|
|
589
|
+
);
|
|
590
|
+
} else {
|
|
591
|
+
blocksResult.push(blockData);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
result[field.name] = blocksResult;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
return result;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
export {
|
|
602
|
+
WORKFLOW_HISTORY_COLLECTION,
|
|
603
|
+
LIFECYCLE_EVENTS_COLLECTION,
|
|
604
|
+
publishingWorkflow,
|
|
605
|
+
workflowCapabilities,
|
|
606
|
+
availableWorkflowTransitions,
|
|
607
|
+
initializeWorkflowDocument,
|
|
608
|
+
materializeWorkflowDocument,
|
|
609
|
+
createLifecycleEvent,
|
|
610
|
+
dispatchLifecycleEvent,
|
|
611
|
+
dispatchPendingLifecycleEvents,
|
|
612
|
+
saveWorkflowDraft,
|
|
613
|
+
createWorkflowDocument,
|
|
614
|
+
transitionWorkflow,
|
|
615
|
+
normalizeConfig,
|
|
616
|
+
runCollectionHooks,
|
|
617
|
+
executeFieldBeforeChange,
|
|
618
|
+
executeFieldAfterRead
|
|
619
|
+
};
|