aicms 0.0.0-stage → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +467 -0
- package/LICENSE +21 -0
- package/README.md +200 -2
- package/README.uk.md +201 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +722 -0
- package/dist/config-edit.d.ts +18 -0
- package/dist/config-edit.js +201 -0
- package/dist/config.d.ts +55 -0
- package/dist/config.js +32 -0
- package/dist/edge.d.ts +22 -0
- package/dist/edge.js +56 -0
- package/dist/gates/a2a.d.ts +45 -0
- package/dist/gates/a2a.js +126 -0
- package/dist/gates/discovery.d.ts +36 -0
- package/dist/gates/discovery.js +54 -0
- package/dist/gates/events.d.ts +14 -0
- package/dist/gates/events.js +86 -0
- package/dist/gates/graphql.d.ts +41 -0
- package/dist/gates/graphql.js +226 -0
- package/dist/gates/mcp.d.ts +8 -0
- package/dist/gates/mcp.js +60 -0
- package/dist/gates/openapi.d.ts +56 -0
- package/dist/gates/openapi.js +61 -0
- package/dist/gates/rest.d.ts +21 -0
- package/dist/gates/rest.js +263 -0
- package/dist/gates/studio.d.ts +21 -0
- package/dist/gates/studio.js +107 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +19 -0
- package/dist/kernel/action.d.ts +49 -0
- package/dist/kernel/action.js +22 -0
- package/dist/kernel/briefs.d.ts +161 -0
- package/dist/kernel/briefs.js +197 -0
- package/dist/kernel/changesets.d.ts +367 -0
- package/dist/kernel/changesets.js +765 -0
- package/dist/kernel/cms.d.ts +127 -0
- package/dist/kernel/cms.js +419 -0
- package/dist/kernel/core-actions.d.ts +5 -0
- package/dist/kernel/core-actions.js +487 -0
- package/dist/kernel/errors.d.ts +14 -0
- package/dist/kernel/errors.js +25 -0
- package/dist/kernel/install.d.ts +32 -0
- package/dist/kernel/install.js +34 -0
- package/dist/kernel/model-actions.d.ts +5 -0
- package/dist/kernel/model-actions.js +126 -0
- package/dist/kernel/modules.d.ts +221 -0
- package/dist/kernel/modules.js +207 -0
- package/dist/kernel/policy.d.ts +42 -0
- package/dist/kernel/policy.js +47 -0
- package/dist/load.d.ts +10 -0
- package/dist/load.js +63 -0
- package/dist/modules/catalog.d.ts +15 -0
- package/dist/modules/catalog.js +21 -0
- package/dist/modules/commerce.d.ts +67 -0
- package/dist/modules/commerce.js +260 -0
- package/dist/modules/git-sync.d.ts +20 -0
- package/dist/modules/git-sync.js +187 -0
- package/dist/modules/i18n.d.ts +6 -0
- package/dist/modules/i18n.js +168 -0
- package/dist/modules/index.d.ts +9 -0
- package/dist/modules/index.js +10 -0
- package/dist/modules/lint.d.ts +22 -0
- package/dist/modules/lint.js +126 -0
- package/dist/modules/media.d.ts +52 -0
- package/dist/modules/media.js +319 -0
- package/dist/modules/payments.d.ts +19 -0
- package/dist/modules/payments.js +110 -0
- package/dist/modules/search.d.ts +27 -0
- package/dist/modules/search.js +81 -0
- package/dist/modules/seo.d.ts +34 -0
- package/dist/modules/seo.js +189 -0
- package/dist/modules/text.d.ts +10 -0
- package/dist/modules/text.js +42 -0
- package/dist/node.d.ts +7 -0
- package/dist/node.js +11 -0
- package/dist/registry.d.ts +57 -0
- package/dist/registry.js +110 -0
- package/dist/schema/fields.d.ts +100 -0
- package/dist/schema/fields.js +134 -0
- package/dist/schema/markdown.d.ts +7 -0
- package/dist/schema/markdown.js +168 -0
- package/dist/schema/model.d.ts +44 -0
- package/dist/schema/model.js +104 -0
- package/dist/schema/slug.d.ts +2 -0
- package/dist/schema/slug.js +40 -0
- package/dist/store/d1.d.ts +30 -0
- package/dist/store/d1.js +27 -0
- package/dist/store/postgres.d.ts +164 -0
- package/dist/store/postgres.js +552 -0
- package/dist/store/sql.d.ts +135 -0
- package/dist/store/sql.js +530 -0
- package/dist/store/sqlite.d.ts +14 -0
- package/dist/store/sqlite.js +60 -0
- package/dist/store/types.d.ts +226 -0
- package/dist/store/types.js +21 -0
- package/dist/studio/assets/geologica-cyrillic-ext-wght-normal-C8B9Chlh.woff2 +0 -0
- package/dist/studio/assets/geologica-cyrillic-wght-normal-DbeVG3Ps.woff2 +0 -0
- package/dist/studio/assets/geologica-greek-wght-normal-DPM5d9ub.woff2 +0 -0
- package/dist/studio/assets/geologica-latin-ext-wght-normal-DZyYlgcm.woff2 +0 -0
- package/dist/studio/assets/geologica-latin-wght-normal-BBL8hQxZ.woff2 +0 -0
- package/dist/studio/assets/geologica-vietnamese-wght-normal-DcI17N1q.woff2 +0 -0
- package/dist/studio/assets/index-3dJ0YHxb.js +22 -0
- package/dist/studio/assets/index-DuyGLFw4.css +1 -0
- package/dist/studio/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
- package/dist/studio/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
- package/dist/studio/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
- package/dist/studio/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
- package/dist/studio/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
- package/dist/studio/assets/unbounded-cyrillic-wght-normal-C627f1f8.woff2 +0 -0
- package/dist/studio/assets/unbounded-latin-ext-wght-normal-D6H-S6MW.woff2 +0 -0
- package/dist/studio/assets/unbounded-latin-wght-normal-D5afBTBx.woff2 +0 -0
- package/dist/studio/assets/unbounded-vietnamese-wght-normal-rat7GD3o.woff2 +0 -0
- package/dist/studio/index.html +21 -0
- package/dist/typegen.d.ts +7 -0
- package/dist/typegen.js +55 -0
- package/package.json +88 -4
|
@@ -0,0 +1,765 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { displayTitle, normalizePatch, projectData, storedSchema, uniqueFields } from "../schema/model.js";
|
|
3
|
+
import { slugify } from "../schema/slug.js";
|
|
4
|
+
import { applyPatch } from "../store/sql.js";
|
|
5
|
+
import { ConflictError } from "../store/types.js";
|
|
6
|
+
import { AicmsError } from "./errors.js";
|
|
7
|
+
import { findCatalog } from "../modules/catalog.js";
|
|
8
|
+
import { catalogEntry, installFromCatalog } from "./install.js";
|
|
9
|
+
import { moduleContext, moduleManifest } from "./modules.js";
|
|
10
|
+
import { allows, modelPermissions } from "./policy.js";
|
|
11
|
+
export const newId = (prefix) => `${prefix}_${BigInt("0x" + randomBytes(8).toString("hex")).toString(36)}`;
|
|
12
|
+
const now = () => new Date().toISOString();
|
|
13
|
+
async function openChangeset(k, actor) {
|
|
14
|
+
const existing = await k.store.findOpenChangeset(actor.id);
|
|
15
|
+
if (existing)
|
|
16
|
+
return existing;
|
|
17
|
+
const at = now();
|
|
18
|
+
const cs = { id: newId("cs"), actor: actor.id, status: "open", items: [], issues: [], createdAt: at, updatedAt: at };
|
|
19
|
+
await k.store.createChangeset(cs);
|
|
20
|
+
return cs;
|
|
21
|
+
}
|
|
22
|
+
/** Fill empty slug fields from their source field (e.g. title → slug). */
|
|
23
|
+
function fillSlugs(model, data) {
|
|
24
|
+
for (const [key, f] of Object.entries(model.fields)) {
|
|
25
|
+
if (f.kind !== "slug" || data[key] || !f.options.from)
|
|
26
|
+
continue;
|
|
27
|
+
const source = data[f.options.from];
|
|
28
|
+
if (typeof source === "string" && source.trim())
|
|
29
|
+
data[key] = slugify(source);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function itemLimit(actor) {
|
|
33
|
+
return actor.budget?.maxChangesetItems ?? 100;
|
|
34
|
+
}
|
|
35
|
+
/** Create or change an entry inside the actor's open changeset. */
|
|
36
|
+
export async function draftEntry(k, actor, model, input, opts = {}) {
|
|
37
|
+
const { id, locale: rawLocale, ...rest } = input;
|
|
38
|
+
const changed = Object.keys(rest).filter((key) => rest[key] !== undefined);
|
|
39
|
+
const unknown = changed.filter((key) => !(key in model.fields));
|
|
40
|
+
if (unknown.length)
|
|
41
|
+
throw new AicmsError("invalid", `Model "${model.name}" has no field ${unknown.map((u) => `"${u}"`).join(", ")}`);
|
|
42
|
+
const patch = normalizePatch(model, rest);
|
|
43
|
+
const perms = modelPermissions(actor, model);
|
|
44
|
+
const requireCreate = () => {
|
|
45
|
+
if (!opts.trusted && !perms.create)
|
|
46
|
+
throw new AicmsError("forbidden", `You can't create ${model.name} entries`);
|
|
47
|
+
};
|
|
48
|
+
const requireFields = () => {
|
|
49
|
+
if (opts.trusted)
|
|
50
|
+
return;
|
|
51
|
+
const denied = changed.filter((key) => !perms.updateFields.includes(key));
|
|
52
|
+
if (denied.length) {
|
|
53
|
+
const allowed = perms.updateFields.length ? ` You may change: ${perms.updateFields.join(", ")}.` : "";
|
|
54
|
+
throw new AicmsError("forbidden", `You can't change ${denied.map((d) => `${model.name}.${d}`).join(", ")}.${allowed}`);
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
const cs = await openChangeset(k, actor);
|
|
58
|
+
let item = id ? cs.items.find((i) => i.id === id) : undefined;
|
|
59
|
+
let before = {};
|
|
60
|
+
if (id && item) {
|
|
61
|
+
if (item.model !== model.name)
|
|
62
|
+
throw new AicmsError("invalid", `${id} is a ${item.model}, not a ${model.name}`);
|
|
63
|
+
if (item.op === "delete")
|
|
64
|
+
throw new AicmsError("invalid", `You already proposed deleting ${id}. Draft a new entry instead.`);
|
|
65
|
+
if (item.op === "create") {
|
|
66
|
+
requireCreate();
|
|
67
|
+
item.data = applyPatch(item.data ?? {}, patch);
|
|
68
|
+
fillSlugs(model, item.data);
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
requireFields();
|
|
72
|
+
item.data = { ...item.data, ...patch };
|
|
73
|
+
before = (await k.store.getEntry(id))?.data ?? {};
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
else if (id) {
|
|
77
|
+
const entry = await k.store.getEntry(id);
|
|
78
|
+
if (!entry || entry.model !== model.name)
|
|
79
|
+
throw new AicmsError("not_found", `No ${model.name} with id ${id}`);
|
|
80
|
+
requireFields();
|
|
81
|
+
before = entry.data;
|
|
82
|
+
item = { op: "update", model: model.name, id, locale: entry.locale, data: patch, baseVersion: entry.version };
|
|
83
|
+
cs.items.push(item);
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
requireCreate();
|
|
87
|
+
const locale = rawLocale ?? k.defaultLocale;
|
|
88
|
+
if (!k.config.locales.includes(locale))
|
|
89
|
+
throw new AicmsError("invalid", `Unknown locale "${locale}". Use one of: ${k.config.locales.join(", ")}`);
|
|
90
|
+
const data = applyPatch({}, patch);
|
|
91
|
+
fillSlugs(model, data);
|
|
92
|
+
item = { op: "create", model: model.name, id: newId(model.name.slice(0, 3)), locale, data };
|
|
93
|
+
cs.items.push(item);
|
|
94
|
+
}
|
|
95
|
+
if (cs.items.length > itemLimit(actor)) {
|
|
96
|
+
throw new AicmsError("budget", `A changeset may hold ${itemLimit(actor)} items. Submit this one with cms_submit first.`);
|
|
97
|
+
}
|
|
98
|
+
cs.updatedAt = now();
|
|
99
|
+
cs.issues = [];
|
|
100
|
+
await k.store.saveChangeset(cs);
|
|
101
|
+
// People in Studio see an agent working on an entry as it happens.
|
|
102
|
+
if (actor.kind === "agent" && item.op === "update")
|
|
103
|
+
k.presence.touch(actor, item.id, model.name, "editing");
|
|
104
|
+
const result = item.op === "create" ? item.data ?? {} : applyPatch(before, item.data ?? {});
|
|
105
|
+
return {
|
|
106
|
+
changeset: cs.id,
|
|
107
|
+
op: item.op,
|
|
108
|
+
id: item.id,
|
|
109
|
+
model: model.name,
|
|
110
|
+
entry: projectData(model, result, "markdown"),
|
|
111
|
+
next: "Saved as a draft, not public yet. Call cms_submit when your changes are ready.",
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/** Drop drafted changes from the actor's open changeset: one entry, or all of them. */
|
|
115
|
+
export async function discardDrafts(k, actor, id) {
|
|
116
|
+
const cs = await k.store.findOpenChangeset(actor.id);
|
|
117
|
+
if (!cs || !cs.items.length) {
|
|
118
|
+
if (id)
|
|
119
|
+
throw new AicmsError("not_found", `You have no draft of ${id}`);
|
|
120
|
+
return { changeset: cs?.id ?? null, discarded: 0, left: 0 };
|
|
121
|
+
}
|
|
122
|
+
const before = cs.items.length;
|
|
123
|
+
cs.items = id ? cs.items.filter((i) => i.id !== id) : [];
|
|
124
|
+
if (cs.items.length === before)
|
|
125
|
+
throw new AicmsError("not_found", `You have no draft of ${id}`);
|
|
126
|
+
cs.issues = [];
|
|
127
|
+
cs.updatedAt = now();
|
|
128
|
+
await k.store.saveChangeset(cs);
|
|
129
|
+
return { changeset: cs.id, discarded: before - cs.items.length, left: cs.items.length };
|
|
130
|
+
}
|
|
131
|
+
/** Propose deleting an entry, or drop a draft that was never published. */
|
|
132
|
+
export async function deleteEntry(k, actor, model, id, opts = {}) {
|
|
133
|
+
if (!opts.trusted && !modelPermissions(actor, model).delete)
|
|
134
|
+
throw new AicmsError("forbidden", `You can't delete ${model.name} entries`);
|
|
135
|
+
const cs = await openChangeset(k, actor);
|
|
136
|
+
const idx = cs.items.findIndex((i) => i.id === id);
|
|
137
|
+
let op;
|
|
138
|
+
if (idx >= 0 && cs.items[idx].op === "create") {
|
|
139
|
+
cs.items.splice(idx, 1);
|
|
140
|
+
op = "discarded";
|
|
141
|
+
}
|
|
142
|
+
else {
|
|
143
|
+
const entry = await k.store.getEntry(id);
|
|
144
|
+
if (!entry || entry.model !== model.name)
|
|
145
|
+
throw new AicmsError("not_found", `No ${model.name} with id ${id}`);
|
|
146
|
+
const item = { op: "delete", model: model.name, id, locale: entry.locale, baseVersion: entry.version };
|
|
147
|
+
if (idx >= 0)
|
|
148
|
+
cs.items[idx] = item;
|
|
149
|
+
else
|
|
150
|
+
cs.items.push(item);
|
|
151
|
+
op = "delete";
|
|
152
|
+
}
|
|
153
|
+
cs.updatedAt = now();
|
|
154
|
+
await k.store.saveChangeset(cs);
|
|
155
|
+
return {
|
|
156
|
+
changeset: cs.id,
|
|
157
|
+
op,
|
|
158
|
+
id,
|
|
159
|
+
next: op === "discarded" ? "The unpublished draft was dropped." : "Deletion proposed. Call cms_submit to send it for review.",
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* An entry as this actor sees it: the published version with their open
|
|
164
|
+
* changeset applied on top. `null` if it doesn't exist or they proposed deleting it.
|
|
165
|
+
*/
|
|
166
|
+
export async function entryWithDrafts(k, actor, id) {
|
|
167
|
+
const published = await k.store.getEntry(id);
|
|
168
|
+
const cs = actor.kind === "public" ? null : await k.store.findOpenChangeset(actor.id);
|
|
169
|
+
const item = cs?.items.find((i) => i.id === id);
|
|
170
|
+
if (!item)
|
|
171
|
+
return published;
|
|
172
|
+
if (item.op === "delete")
|
|
173
|
+
return null;
|
|
174
|
+
if (item.op === "create") {
|
|
175
|
+
const at = cs.updatedAt;
|
|
176
|
+
return { id, model: item.model, locale: item.locale, data: item.data ?? {}, version: 0, createdAt: at, updatedAt: at, createdBy: actor.id, updatedBy: actor.id };
|
|
177
|
+
}
|
|
178
|
+
return published ? { ...published, data: applyPatch(published.data, item.data ?? {}) } : null;
|
|
179
|
+
}
|
|
180
|
+
/** Schema, uniqueness, reference and conflict checks for every item. */
|
|
181
|
+
export async function checkChangeset(k, cs) {
|
|
182
|
+
const issues = [];
|
|
183
|
+
const created = new Map(cs.items.filter((i) => i.op === "create").map((i) => [i.id, i.model]));
|
|
184
|
+
const deleted = new Set(cs.items.filter((i) => i.op === "delete").map((i) => i.id));
|
|
185
|
+
const seen = new Map();
|
|
186
|
+
for (const item of cs.items) {
|
|
187
|
+
const add = (message, field) => issues.push({ entry: item.id, model: item.model, ...(field ? { field } : {}), message });
|
|
188
|
+
if (item.op === "install") {
|
|
189
|
+
try {
|
|
190
|
+
catalogEntry(k, item.id);
|
|
191
|
+
}
|
|
192
|
+
catch (e) {
|
|
193
|
+
add(e instanceof Error ? e.message : String(e));
|
|
194
|
+
}
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
const model = k.models.get(item.model);
|
|
198
|
+
if (!model) {
|
|
199
|
+
add(`Model "${item.model}" no longer exists`);
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
let current = null;
|
|
203
|
+
if (item.op !== "create") {
|
|
204
|
+
current = await k.store.getEntry(item.id);
|
|
205
|
+
if (!current) {
|
|
206
|
+
add("This entry was deleted after you drafted the change");
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
if (item.baseVersion !== undefined && current.version !== item.baseVersion) {
|
|
210
|
+
add(`Someone changed this entry after you drafted (v${item.baseVersion} → v${current.version}). Read it again and redo your change.`);
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
if (item.op === "delete")
|
|
215
|
+
continue;
|
|
216
|
+
const doc = item.op === "create" ? item.data ?? {} : applyPatch(current.data, item.data ?? {});
|
|
217
|
+
const parsed = storedSchema(model).safeParse(doc);
|
|
218
|
+
if (!parsed.success)
|
|
219
|
+
for (const issue of parsed.error.issues)
|
|
220
|
+
add(issue.message, issue.path.join(".") || undefined);
|
|
221
|
+
for (const f of uniqueFields(model)) {
|
|
222
|
+
const value = doc[f];
|
|
223
|
+
if (value == null || value === "")
|
|
224
|
+
continue;
|
|
225
|
+
const key = `${item.model}|${item.locale}|${f}|${String(value)}`;
|
|
226
|
+
if (seen.has(key))
|
|
227
|
+
add(`"${value}" is used twice in this changeset (also by ${seen.get(key)})`, f);
|
|
228
|
+
seen.set(key, item.id);
|
|
229
|
+
const other = await k.store.findOne(item.model, f, value, item.locale);
|
|
230
|
+
if (other && other.id !== item.id && !deleted.has(other.id))
|
|
231
|
+
add(`"${value}" is already used by ${other.id}`, f);
|
|
232
|
+
}
|
|
233
|
+
for (const [f, def] of Object.entries(model.fields)) {
|
|
234
|
+
if (def.kind !== "ref" || doc[f] == null)
|
|
235
|
+
continue;
|
|
236
|
+
const target = def.options.model;
|
|
237
|
+
const ids = Array.isArray(doc[f]) ? doc[f] : [doc[f]];
|
|
238
|
+
for (const ref of ids) {
|
|
239
|
+
if (created.get(ref) === target)
|
|
240
|
+
continue;
|
|
241
|
+
const entry = deleted.has(ref) ? null : await k.store.getEntry(ref);
|
|
242
|
+
if (!entry || entry.model !== target)
|
|
243
|
+
add(`No ${target} with id ${ref}`, f);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
return issues;
|
|
248
|
+
}
|
|
249
|
+
/** Module checks on every create and update: errors block, warnings go to the reviewer. A check that throws becomes a warning. */
|
|
250
|
+
export async function runModuleChecks(k, cs) {
|
|
251
|
+
const errors = [];
|
|
252
|
+
const warnings = [];
|
|
253
|
+
const checkers = k.modules.filter((m) => m.checks && Object.keys(m.checks).length);
|
|
254
|
+
if (!checkers.length)
|
|
255
|
+
return { errors, warnings };
|
|
256
|
+
for (const item of cs.items) {
|
|
257
|
+
if (item.op !== "create" && item.op !== "update")
|
|
258
|
+
continue;
|
|
259
|
+
const model = k.models.get(item.model);
|
|
260
|
+
if (!model)
|
|
261
|
+
continue;
|
|
262
|
+
const current = item.op === "update" ? await k.store.getEntry(item.id) : null;
|
|
263
|
+
if (item.op === "update" && !current)
|
|
264
|
+
continue;
|
|
265
|
+
const data = item.op === "create" ? item.data ?? {} : applyPatch(current.data, item.data ?? {});
|
|
266
|
+
const input = {
|
|
267
|
+
op: item.op,
|
|
268
|
+
model,
|
|
269
|
+
id: item.id,
|
|
270
|
+
locale: item.locale,
|
|
271
|
+
data: projectData(model, data, "blocks"),
|
|
272
|
+
before: current ? projectData(model, current.data, "blocks") : null,
|
|
273
|
+
changed: Object.keys(item.data ?? {}),
|
|
274
|
+
author: cs.actor,
|
|
275
|
+
};
|
|
276
|
+
for (const mod of checkers) {
|
|
277
|
+
const scope = new Set([...(mod.models ?? []).map((m) => m.name), ...(mod.uses ?? [])]);
|
|
278
|
+
if (!scope.has("*") && !scope.has(model.name))
|
|
279
|
+
continue;
|
|
280
|
+
const ctx = moduleContext(k, mod, { id: `module:${mod.name}`, kind: "system", scopes: ["*"], review: "auto" }, "internal");
|
|
281
|
+
for (const [name, check] of Object.entries(mod.checks)) {
|
|
282
|
+
const tag = `${mod.name}/${name}`;
|
|
283
|
+
try {
|
|
284
|
+
for (const f of (await check(input, ctx)) ?? []) {
|
|
285
|
+
const issue = { entry: item.id, model: model.name, ...(f.field ? { field: f.field } : {}), message: f.message, check: tag };
|
|
286
|
+
(f.level === "error" ? errors : warnings).push(issue);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
catch (e) {
|
|
290
|
+
warnings.push({ entry: item.id, model: model.name, message: `The ${tag} check failed: ${e instanceof Error ? e.message : String(e)}`, check: tag });
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
return { errors, warnings };
|
|
296
|
+
}
|
|
297
|
+
/** Everything a changeset must pass: schema, uniqueness, references, conflicts and module checks. */
|
|
298
|
+
async function fullCheck(k, cs) {
|
|
299
|
+
const issues = await checkChangeset(k, cs);
|
|
300
|
+
const { errors, warnings } = await runModuleChecks(k, cs);
|
|
301
|
+
return { issues: [...issues, ...errors], warnings };
|
|
302
|
+
}
|
|
303
|
+
/** The scope each item needs, for `review: { auto: [...] }` rules. */
|
|
304
|
+
function neededScopes(item) {
|
|
305
|
+
if (item.op === "install")
|
|
306
|
+
return ["modules:install"];
|
|
307
|
+
if (item.op === "create")
|
|
308
|
+
return [`${item.model}:create`];
|
|
309
|
+
if (item.op === "delete")
|
|
310
|
+
return [`${item.model}:delete`];
|
|
311
|
+
return Object.keys(item.data ?? {}).map((f) => `${item.model}:update.${f}`);
|
|
312
|
+
}
|
|
313
|
+
function reviewReason(k, actor, cs) {
|
|
314
|
+
if (actor.kind === "owner" || actor.kind === "system")
|
|
315
|
+
return undefined;
|
|
316
|
+
const rule = actor.review;
|
|
317
|
+
if (rule === "human")
|
|
318
|
+
return `Changes from ${actor.id} are reviewed by a person`;
|
|
319
|
+
if (typeof rule === "object") {
|
|
320
|
+
const outside = [...new Set(cs.items.flatMap(neededScopes))].filter((s) => !allows(rule.auto, s));
|
|
321
|
+
if (outside.length)
|
|
322
|
+
return `${actor.id} publishes without review only ${rule.auto.join(", ") || "nothing"}; this also changes ${outside.slice(0, 3).join(", ")}${outside.length > 3 ? "…" : ""}`;
|
|
323
|
+
}
|
|
324
|
+
for (const item of cs.items) {
|
|
325
|
+
const can = k.models.get(item.model)?.agent?.can;
|
|
326
|
+
if (can && !can.includes("publish"))
|
|
327
|
+
return `Model "${item.model}" requires a person to publish`;
|
|
328
|
+
}
|
|
329
|
+
const w = cs.warnings?.length ?? 0;
|
|
330
|
+
if (w)
|
|
331
|
+
return `${w} check warning${w === 1 ? "" : "s"} for a person to look at`;
|
|
332
|
+
return undefined;
|
|
333
|
+
}
|
|
334
|
+
const SCHEDULE_SLACK_MS = 5_000;
|
|
335
|
+
/** A future time as ISO, or undefined for "now". Throws on nonsense. */
|
|
336
|
+
export function parsePublishAt(at) {
|
|
337
|
+
if (!at || at === "now")
|
|
338
|
+
return undefined;
|
|
339
|
+
const t = Date.parse(at);
|
|
340
|
+
if (Number.isNaN(t))
|
|
341
|
+
throw new AicmsError("invalid", `"${at}" isn't a date. Use ISO 8601, e.g. 2026-12-01T09:00:00Z`);
|
|
342
|
+
if (t > Date.now() + 366 * 86_400_000)
|
|
343
|
+
throw new AicmsError("invalid", "Schedule at most a year ahead");
|
|
344
|
+
return t > Date.now() + SCHEDULE_SLACK_MS ? new Date(t).toISOString() : undefined;
|
|
345
|
+
}
|
|
346
|
+
/** Checks on the caller's open changeset, without submitting: what cms_submit would say. */
|
|
347
|
+
export async function checkDrafts(k, actor) {
|
|
348
|
+
const cs = await k.store.findOpenChangeset(actor.id);
|
|
349
|
+
if (!cs || !cs.items.length)
|
|
350
|
+
throw new AicmsError("invalid", "You have no drafted changes. Use a <model>_draft tool first.");
|
|
351
|
+
const { issues, warnings } = await fullCheck(k, cs);
|
|
352
|
+
const reason = issues.length ? undefined : reviewReason(k, actor, { ...cs, warnings });
|
|
353
|
+
return {
|
|
354
|
+
changeset: cs.id,
|
|
355
|
+
ready: !issues.length,
|
|
356
|
+
issues,
|
|
357
|
+
warnings,
|
|
358
|
+
...(issues.length ? {} : { onSubmit: reason ? `waits for a person: ${reason}` : "merged right away" }),
|
|
359
|
+
next: issues.length
|
|
360
|
+
? "Fix the issues with the <model>_draft tools, then check again."
|
|
361
|
+
: warnings.length
|
|
362
|
+
? "Fix the warnings if you can, or explain them in the cms_submit note."
|
|
363
|
+
: "All checks pass. Call cms_submit.",
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
export async function submitChangeset(k, actor, input = {}) {
|
|
367
|
+
const opts = typeof input === "string" ? { note: input } : input;
|
|
368
|
+
const cs = await k.store.findOpenChangeset(actor.id);
|
|
369
|
+
if (!cs || !cs.items.length)
|
|
370
|
+
throw new AicmsError("invalid", "You have no drafted changes. Use a <model>_draft tool first.");
|
|
371
|
+
const publishAt = parsePublishAt(opts.publishAt);
|
|
372
|
+
const { issues, warnings } = await fullCheck(k, cs);
|
|
373
|
+
cs.updatedAt = now();
|
|
374
|
+
if (opts.note)
|
|
375
|
+
cs.note = opts.note;
|
|
376
|
+
if (opts.brief)
|
|
377
|
+
cs.brief = opts.brief;
|
|
378
|
+
cs.publishAt = publishAt;
|
|
379
|
+
cs.warnings = warnings;
|
|
380
|
+
if (issues.length) {
|
|
381
|
+
cs.issues = issues;
|
|
382
|
+
await k.store.saveChangeset(cs);
|
|
383
|
+
return {
|
|
384
|
+
status: "needs_changes",
|
|
385
|
+
changeset: cs.id,
|
|
386
|
+
issues,
|
|
387
|
+
...(warnings.length ? { warnings } : {}),
|
|
388
|
+
next: "Fix these with the <model>_draft tools, then call cms_submit again.",
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
const reason = reviewReason(k, actor, cs);
|
|
392
|
+
cs.issues = [];
|
|
393
|
+
cs.comment = undefined;
|
|
394
|
+
// Submitting ends the work on these entries: the agent is no longer "editing" them.
|
|
395
|
+
for (const item of cs.items)
|
|
396
|
+
if (item.op !== "install")
|
|
397
|
+
k.presence.leave(actor, item.id);
|
|
398
|
+
if (reason) {
|
|
399
|
+
cs.status = "submitted";
|
|
400
|
+
cs.reviewReason = reason;
|
|
401
|
+
await k.store.saveChangeset(cs);
|
|
402
|
+
await k.emit("changeset.submitted", summarize(cs));
|
|
403
|
+
return {
|
|
404
|
+
status: "submitted",
|
|
405
|
+
changeset: cs.id,
|
|
406
|
+
reason,
|
|
407
|
+
...(warnings.length ? { warnings } : {}),
|
|
408
|
+
...(publishAt ? { publishAt } : {}),
|
|
409
|
+
next: publishAt
|
|
410
|
+
? `Waiting for review. If approved, it is published at ${publishAt}. Check cms_changes later.`
|
|
411
|
+
: "Waiting for review. Check cms_changes later for the decision and any comment.",
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
await k.store.saveChangeset(cs);
|
|
415
|
+
if (publishAt)
|
|
416
|
+
return schedule(k, cs, publishAt, actor.id);
|
|
417
|
+
return { status: "merged", ...(await mergeChangeset(k, cs.id, actor.id, { at: "now" })) };
|
|
418
|
+
}
|
|
419
|
+
async function schedule(k, cs, at, by) {
|
|
420
|
+
cs.status = "scheduled";
|
|
421
|
+
cs.publishAt = at;
|
|
422
|
+
cs.scheduledBy = by;
|
|
423
|
+
cs.reviewReason = undefined;
|
|
424
|
+
cs.updatedAt = now();
|
|
425
|
+
await k.store.saveChangeset(cs);
|
|
426
|
+
await k.emit("changeset.scheduled", summarize(cs));
|
|
427
|
+
return { status: "scheduled", changeset: cs.id, publishAt: at, next: `Published automatically at ${at}.` };
|
|
428
|
+
}
|
|
429
|
+
export async function mergeChangeset(k, id, by, opts = {}) {
|
|
430
|
+
const cs = await k.store.getChangeset(id);
|
|
431
|
+
if (!cs)
|
|
432
|
+
throw new AicmsError("not_found", `No changeset ${id}`);
|
|
433
|
+
if (cs.status === "merged" || cs.status === "rejected")
|
|
434
|
+
throw new AicmsError("invalid", `Changeset ${id} is already ${cs.status}`);
|
|
435
|
+
if (!cs.items.length)
|
|
436
|
+
throw new AicmsError("invalid", `Changeset ${id} is empty`);
|
|
437
|
+
const install = cs.items.some((i) => i.op === "install");
|
|
438
|
+
const at = install ? undefined : parsePublishAt(opts.at ?? (cs.status === "submitted" ? cs.publishAt : undefined));
|
|
439
|
+
const sendBack = async (issues) => {
|
|
440
|
+
cs.status = "open";
|
|
441
|
+
cs.issues = issues;
|
|
442
|
+
cs.comment = "Checks failed when merging. Fix the issues and submit again.";
|
|
443
|
+
cs.updatedAt = now();
|
|
444
|
+
await k.store.saveChangeset(cs);
|
|
445
|
+
throw new AicmsError("conflict", `Changeset ${id} can't be merged; it went back to ${cs.actor}`, { issues });
|
|
446
|
+
};
|
|
447
|
+
if (install)
|
|
448
|
+
return mergeInstall(k, cs, by, await checkChangeset(k, cs));
|
|
449
|
+
const { issues, warnings } = await fullCheck(k, cs);
|
|
450
|
+
if (issues.length)
|
|
451
|
+
await sendBack(issues);
|
|
452
|
+
cs.warnings = warnings;
|
|
453
|
+
if (at)
|
|
454
|
+
return schedule(k, cs, at, by);
|
|
455
|
+
let entries;
|
|
456
|
+
try {
|
|
457
|
+
entries = await k.store.mergeChangeset(id, by, now());
|
|
458
|
+
}
|
|
459
|
+
catch (e) {
|
|
460
|
+
if (e instanceof ConflictError)
|
|
461
|
+
return sendBack([{ entry: e.entry, model: "", message: e.message }]);
|
|
462
|
+
throw e;
|
|
463
|
+
}
|
|
464
|
+
const ops = new Map(cs.items.map((i) => [i.id, i.op]));
|
|
465
|
+
const summary = {
|
|
466
|
+
changeset: id,
|
|
467
|
+
actor: cs.actor,
|
|
468
|
+
mergedBy: by,
|
|
469
|
+
...(cs.brief ? { brief: cs.brief } : {}),
|
|
470
|
+
entries: entries.map((e) => ({ id: e.id, model: e.model, op: ops.get(e.id), version: e.version })),
|
|
471
|
+
};
|
|
472
|
+
await k.emit("changeset.merged", summary);
|
|
473
|
+
return summary;
|
|
474
|
+
}
|
|
475
|
+
/** Take a scheduled changeset off the schedule; it waits for review again. */
|
|
476
|
+
export async function unscheduleChangeset(k, id, by) {
|
|
477
|
+
const cs = await k.store.getChangeset(id);
|
|
478
|
+
if (!cs)
|
|
479
|
+
throw new AicmsError("not_found", `No changeset ${id}`);
|
|
480
|
+
if (cs.status !== "scheduled")
|
|
481
|
+
throw new AicmsError("invalid", `Changeset ${id} isn't scheduled; it is ${cs.status}`);
|
|
482
|
+
cs.status = "submitted";
|
|
483
|
+
cs.reviewReason = `Taken off the schedule by ${by}`;
|
|
484
|
+
cs.publishAt = undefined;
|
|
485
|
+
cs.scheduledBy = undefined;
|
|
486
|
+
cs.updatedAt = now();
|
|
487
|
+
await k.store.saveChangeset(cs);
|
|
488
|
+
await k.emit("changeset.unscheduled", { ...summarize(cs), by });
|
|
489
|
+
return { changeset: id, status: cs.status };
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* Merge every scheduled changeset whose time has come. One that no longer
|
|
493
|
+
* passes its checks goes back to its author, like a manual merge would.
|
|
494
|
+
*/
|
|
495
|
+
export async function publishDue(k, at = new Date()) {
|
|
496
|
+
const due = (await k.store.listChangesets({ status: ["scheduled"], limit: 500 })).filter((cs) => cs.publishAt && Date.parse(cs.publishAt) <= at.getTime());
|
|
497
|
+
const merged = [];
|
|
498
|
+
const failed = [];
|
|
499
|
+
for (const cs of due.sort((a, b) => a.publishAt.localeCompare(b.publishAt))) {
|
|
500
|
+
try {
|
|
501
|
+
await mergeChangeset(k, cs.id, cs.scheduledBy ?? "owner", { at: "now" });
|
|
502
|
+
merged.push(cs.id);
|
|
503
|
+
}
|
|
504
|
+
catch (e) {
|
|
505
|
+
failed.push({ changeset: cs.id, error: e instanceof Error ? e.message : String(e) });
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
return { merged, failed };
|
|
509
|
+
}
|
|
510
|
+
/** A module proposal: install each module, then record the changeset as merged. */
|
|
511
|
+
async function mergeInstall(k, cs, by, issues) {
|
|
512
|
+
if (issues.length) {
|
|
513
|
+
cs.status = "rejected";
|
|
514
|
+
cs.issues = issues;
|
|
515
|
+
cs.comment = issues.map((i) => i.message).join("; ");
|
|
516
|
+
cs.updatedAt = now();
|
|
517
|
+
await k.store.saveChangeset(cs);
|
|
518
|
+
throw new AicmsError("conflict", `Can't install: ${cs.comment}`, { issues });
|
|
519
|
+
}
|
|
520
|
+
const installed = [];
|
|
521
|
+
for (const item of cs.items)
|
|
522
|
+
installed.push(await installFromCatalog(k, item.id));
|
|
523
|
+
const at = now();
|
|
524
|
+
cs.status = "merged";
|
|
525
|
+
cs.mergedAt = at;
|
|
526
|
+
cs.mergedBy = by;
|
|
527
|
+
cs.updatedAt = at;
|
|
528
|
+
cs.reviewReason = undefined;
|
|
529
|
+
await k.store.saveChangeset(cs);
|
|
530
|
+
const summary = { changeset: cs.id, actor: cs.actor, mergedBy: by, entries: [], modules: installed.map((i) => i.module), installed };
|
|
531
|
+
await k.emit("changeset.merged", summary);
|
|
532
|
+
return summary;
|
|
533
|
+
}
|
|
534
|
+
/** An agent's request to install a catalog module; it waits in the Inbox for a person. */
|
|
535
|
+
export async function proposeModule(k, actor, name, reason) {
|
|
536
|
+
const entry = catalogEntry(k, name);
|
|
537
|
+
const pending = await k.store.listChangesets({ status: ["submitted"], limit: 500 });
|
|
538
|
+
if (pending.some((cs) => cs.items.some((i) => i.op === "install" && i.id === entry.name)))
|
|
539
|
+
throw new AicmsError("conflict", `Installing "${entry.name}" is already waiting for review`);
|
|
540
|
+
const at = now();
|
|
541
|
+
const cs = {
|
|
542
|
+
id: newId("cs"),
|
|
543
|
+
actor: actor.id,
|
|
544
|
+
status: "submitted",
|
|
545
|
+
note: reason,
|
|
546
|
+
reviewReason: "Installing a module is decided by a person",
|
|
547
|
+
items: [{ op: "install", model: "", id: entry.name, locale: "" }],
|
|
548
|
+
issues: [],
|
|
549
|
+
createdAt: at,
|
|
550
|
+
updatedAt: at,
|
|
551
|
+
};
|
|
552
|
+
await k.store.createChangeset(cs);
|
|
553
|
+
await k.emit("changeset.submitted", summarize(cs));
|
|
554
|
+
return {
|
|
555
|
+
status: "submitted",
|
|
556
|
+
changeset: cs.id,
|
|
557
|
+
module: moduleManifest(entry.create()),
|
|
558
|
+
next: "A person will see what the module may do and decide. Check cms_changes for the answer.",
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
export async function rejectChangeset(k, id, by, comment, final = false) {
|
|
562
|
+
const cs = await k.store.getChangeset(id);
|
|
563
|
+
if (!cs)
|
|
564
|
+
throw new AicmsError("not_found", `No changeset ${id}`);
|
|
565
|
+
// A module proposal never reopens: it would turn into the agent's content draft.
|
|
566
|
+
if (cs.items.some((i) => i.op === "install"))
|
|
567
|
+
final = true;
|
|
568
|
+
if (cs.status !== "submitted" && cs.status !== "open" && cs.status !== "scheduled")
|
|
569
|
+
throw new AicmsError("invalid", `Changeset ${id} is already ${cs.status}`);
|
|
570
|
+
const otherOpen = await k.store.findOpenChangeset(cs.actor);
|
|
571
|
+
const reopen = !final && (!otherOpen || otherOpen.id === cs.id);
|
|
572
|
+
cs.status = reopen ? "open" : "rejected";
|
|
573
|
+
cs.comment = comment;
|
|
574
|
+
cs.reviewReason = undefined;
|
|
575
|
+
cs.scheduledBy = undefined;
|
|
576
|
+
cs.updatedAt = now();
|
|
577
|
+
await k.store.saveChangeset(cs);
|
|
578
|
+
await k.emit("changeset.rejected", { ...summarize(cs), comment, by, reopened: reopen });
|
|
579
|
+
return { changeset: id, status: cs.status, reopened: reopen };
|
|
580
|
+
}
|
|
581
|
+
export function summarize(cs) {
|
|
582
|
+
return {
|
|
583
|
+
id: cs.id,
|
|
584
|
+
actor: cs.actor,
|
|
585
|
+
status: cs.status,
|
|
586
|
+
...(cs.note ? { note: cs.note } : {}),
|
|
587
|
+
...(cs.comment ? { comment: cs.comment } : {}),
|
|
588
|
+
...(cs.reviewReason ? { waitingBecause: cs.reviewReason } : {}),
|
|
589
|
+
...(cs.issues.length ? { issues: cs.issues } : {}),
|
|
590
|
+
...(cs.warnings?.length ? { warnings: cs.warnings } : {}),
|
|
591
|
+
...(cs.publishAt ? { publishAt: cs.publishAt } : {}),
|
|
592
|
+
...(cs.scheduledBy ? { scheduledBy: cs.scheduledBy } : {}),
|
|
593
|
+
...(cs.brief ? { brief: cs.brief } : {}),
|
|
594
|
+
items: cs.items.map((i) => ({ op: i.op, model: i.model, id: i.id, ...(i.data ? { fields: Object.keys(i.data) } : {}) })),
|
|
595
|
+
updatedAt: cs.updatedAt,
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
/** Before/after per field, for reviewers. Block fields are shown as Markdown. */
|
|
599
|
+
export async function diffChangeset(k, cs) {
|
|
600
|
+
const items = [];
|
|
601
|
+
for (const item of cs.items) {
|
|
602
|
+
if (item.op === "install") {
|
|
603
|
+
const entry = findCatalog(item.id);
|
|
604
|
+
items.push({ op: item.op, model: "module", id: item.id, title: entry?.title ?? item.id, summary: entry?.summary, module: entry ? moduleManifest(entry.create()) : null, changes: [] });
|
|
605
|
+
continue;
|
|
606
|
+
}
|
|
607
|
+
const model = k.models.get(item.model);
|
|
608
|
+
const current = item.op === "create" ? null : await k.store.getEntry(item.id);
|
|
609
|
+
const before = model && current ? projectData(model, current.data, "markdown") : {};
|
|
610
|
+
const after = model && item.data ? projectData(model, item.data, "markdown") : {};
|
|
611
|
+
const order = model ? Object.keys(model.fields) : [];
|
|
612
|
+
const fields = item.op === "delete" ? [] : Object.keys(item.data ?? {}).sort((a, b) => order.indexOf(a) - order.indexOf(b));
|
|
613
|
+
const merged = item.op === "create" ? item.data ?? {} : current ? applyPatch(current.data, item.data ?? {}) : {};
|
|
614
|
+
items.push({
|
|
615
|
+
op: item.op,
|
|
616
|
+
model: item.model,
|
|
617
|
+
id: item.id,
|
|
618
|
+
title: model ? displayTitle(model, item.op === "delete" ? current?.data ?? {} : merged) : "",
|
|
619
|
+
changes: fields.map((f) => ({ field: f, before: before[f] ?? null, after: item.data?.[f] === null ? null : after[f] ?? null })),
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
return { ...summarize(cs), items };
|
|
623
|
+
}
|
|
624
|
+
/** Which model and locale an entry belongs to, even after it was deleted. */
|
|
625
|
+
async function locateEntry(k, id) {
|
|
626
|
+
const current = await k.store.getEntry(id);
|
|
627
|
+
if (current)
|
|
628
|
+
return { model: current.model, locale: current.locale };
|
|
629
|
+
for (const v of await k.store.versions(id)) {
|
|
630
|
+
if (!v.changesetId)
|
|
631
|
+
continue;
|
|
632
|
+
const item = (await k.store.getChangeset(v.changesetId))?.items.find((i) => i.id === id);
|
|
633
|
+
if (item)
|
|
634
|
+
return { model: item.model, locale: item.locale };
|
|
635
|
+
}
|
|
636
|
+
return null;
|
|
637
|
+
}
|
|
638
|
+
/** Every version of an entry, newest first, with the fields each one changed. */
|
|
639
|
+
export async function entryHistory(k, actor, id) {
|
|
640
|
+
const where = await locateEntry(k, id);
|
|
641
|
+
const model = where && k.models.get(where.model);
|
|
642
|
+
if (!where || !model || !modelPermissions(actor, model).read)
|
|
643
|
+
throw new AicmsError("not_found", `No entry ${id}`);
|
|
644
|
+
const versions = await k.store.versions(id);
|
|
645
|
+
const current = await k.store.getEntry(id);
|
|
646
|
+
return {
|
|
647
|
+
id,
|
|
648
|
+
model: model.name,
|
|
649
|
+
locale: where.locale,
|
|
650
|
+
current: current?.version ?? null,
|
|
651
|
+
versions: versions.map((v, i) => {
|
|
652
|
+
const prev = versions[i + 1]?.data ?? {};
|
|
653
|
+
const data = v.data ?? {};
|
|
654
|
+
const changed = v.data === null ? [] : [...new Set([...Object.keys(prev), ...Object.keys(data)])].filter((f) => JSON.stringify(prev[f]) !== JSON.stringify(data[f]));
|
|
655
|
+
return {
|
|
656
|
+
version: v.version,
|
|
657
|
+
at: v.createdAt,
|
|
658
|
+
actor: v.actor,
|
|
659
|
+
changeset: v.changesetId,
|
|
660
|
+
...(v.data === null ? { deleted: true } : { changed }),
|
|
661
|
+
};
|
|
662
|
+
}),
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
/** One version's data, for reading or comparing. */
|
|
666
|
+
export async function entryVersion(k, actor, id, version) {
|
|
667
|
+
const history = await entryHistory(k, actor, id);
|
|
668
|
+
const row = (await k.store.versions(id)).find((v) => v.version === version);
|
|
669
|
+
if (!row)
|
|
670
|
+
throw new AicmsError("not_found", `${id} has no version ${version}. Versions: ${history.versions.map((v) => v.version).join(", ")}`);
|
|
671
|
+
const model = k.models.get(history.model);
|
|
672
|
+
return { id, model: model.name, version, at: row.createdAt, actor: row.actor, changeset: row.changesetId, deleted: row.data === null, data: row.data };
|
|
673
|
+
}
|
|
674
|
+
/**
|
|
675
|
+
* Draft a change that brings an entry back to the state it had at `version`.
|
|
676
|
+
* A deleted entry is re-created with the same id. Replaces any draft of that entry in the caller's changeset.
|
|
677
|
+
*/
|
|
678
|
+
export async function restoreEntry(k, actor, id, version) {
|
|
679
|
+
const target = await entryVersion(k, actor, id, version);
|
|
680
|
+
if (target.deleted)
|
|
681
|
+
throw new AicmsError("invalid", `Version ${version} of ${id} is its deletion. Restore an earlier version.`);
|
|
682
|
+
const model = k.models.get(target.model);
|
|
683
|
+
const data = Object.fromEntries(Object.entries(target.data ?? {}).filter(([key]) => key in model.fields));
|
|
684
|
+
const perms = modelPermissions(actor, model);
|
|
685
|
+
const current = await k.store.getEntry(id);
|
|
686
|
+
const cs = await openChangeset(k, actor);
|
|
687
|
+
const others = cs.items.filter((i) => i.id !== id);
|
|
688
|
+
let item;
|
|
689
|
+
if (current) {
|
|
690
|
+
const patch = {};
|
|
691
|
+
for (const key of new Set([...Object.keys(current.data), ...Object.keys(data)])) {
|
|
692
|
+
if (!(key in model.fields))
|
|
693
|
+
continue;
|
|
694
|
+
if (JSON.stringify(current.data[key]) !== JSON.stringify(data[key]))
|
|
695
|
+
patch[key] = data[key] ?? null;
|
|
696
|
+
}
|
|
697
|
+
const fields = Object.keys(patch);
|
|
698
|
+
if (!fields.length)
|
|
699
|
+
throw new AicmsError("invalid", `${id} already matches version ${version}`);
|
|
700
|
+
const denied = fields.filter((f) => !perms.updateFields.includes(f));
|
|
701
|
+
if (denied.length)
|
|
702
|
+
throw new AicmsError("forbidden", `Restoring needs changes to ${denied.map((d) => `${model.name}.${d}`).join(", ")}, which you can't change`);
|
|
703
|
+
item = { op: "update", model: model.name, id, locale: current.locale, data: patch, baseVersion: current.version };
|
|
704
|
+
}
|
|
705
|
+
else {
|
|
706
|
+
if (!perms.create)
|
|
707
|
+
throw new AicmsError("forbidden", `Restoring a deleted ${model.name} needs permission to create ${model.name} entries`);
|
|
708
|
+
const locale = (await locateEntry(k, id)).locale;
|
|
709
|
+
item = { op: "create", model: model.name, id, locale, data };
|
|
710
|
+
}
|
|
711
|
+
cs.items = [...others, item];
|
|
712
|
+
if (cs.items.length > itemLimit(actor))
|
|
713
|
+
throw new AicmsError("budget", `A changeset may hold ${itemLimit(actor)} items. Submit this one first.`);
|
|
714
|
+
cs.updatedAt = now();
|
|
715
|
+
cs.issues = [];
|
|
716
|
+
await k.store.saveChangeset(cs);
|
|
717
|
+
return {
|
|
718
|
+
changeset: cs.id,
|
|
719
|
+
op: item.op,
|
|
720
|
+
id,
|
|
721
|
+
model: model.name,
|
|
722
|
+
restores: version,
|
|
723
|
+
fields: Object.keys(item.data ?? {}),
|
|
724
|
+
next: "The restore is drafted. Call cms_submit to publish it.",
|
|
725
|
+
};
|
|
726
|
+
}
|
|
727
|
+
/** Draft the inverse of a merged changeset: creations are deleted, edits and deletions are undone. */
|
|
728
|
+
export async function revertChangeset(k, actor, id) {
|
|
729
|
+
const cs = await k.store.getChangeset(id);
|
|
730
|
+
if (!cs)
|
|
731
|
+
throw new AicmsError("not_found", `No changeset ${id}`);
|
|
732
|
+
if (cs.status !== "merged")
|
|
733
|
+
throw new AicmsError("invalid", `Only merged changesets can be reverted; ${id} is ${cs.status}`);
|
|
734
|
+
const plan = [];
|
|
735
|
+
const moved = [];
|
|
736
|
+
for (const item of cs.items) {
|
|
737
|
+
const versions = await k.store.versions(item.id);
|
|
738
|
+
const made = versions.find((v) => v.changesetId === cs.id);
|
|
739
|
+
if (!made)
|
|
740
|
+
continue;
|
|
741
|
+
if (versions[0].version !== made.version)
|
|
742
|
+
moved.push(item.id);
|
|
743
|
+
plan.push({ item, made: made.version });
|
|
744
|
+
}
|
|
745
|
+
if (moved.length) {
|
|
746
|
+
throw new AicmsError("conflict", `Changed again after ${id} was merged: ${moved.join(", ")}. Restore those entries from their history instead.`, { entries: moved });
|
|
747
|
+
}
|
|
748
|
+
const done = [];
|
|
749
|
+
for (const { item, made } of plan) {
|
|
750
|
+
const model = k.models.get(item.model);
|
|
751
|
+
if (!model)
|
|
752
|
+
throw new AicmsError("invalid", `Model "${item.model}" no longer exists`);
|
|
753
|
+
if (item.op === "create")
|
|
754
|
+
done.push(await deleteEntry(k, actor, model, item.id));
|
|
755
|
+
else
|
|
756
|
+
done.push(await restoreEntry(k, actor, item.id, made - 1));
|
|
757
|
+
}
|
|
758
|
+
const open = await k.store.findOpenChangeset(actor.id);
|
|
759
|
+
return {
|
|
760
|
+
changeset: open?.id,
|
|
761
|
+
reverts: id,
|
|
762
|
+
items: done.map((d) => ({ op: d.op, id: d.id })),
|
|
763
|
+
next: "The revert is drafted. Call cms_submit to publish it.",
|
|
764
|
+
};
|
|
765
|
+
}
|