@mainsoft/agent-cms 0.7.0 → 0.10.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 (111) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +291 -32
  3. package/TODO.md +72 -26
  4. package/UPGRADE-0.10.md +36 -0
  5. package/UPGRADE-0.8.md +118 -0
  6. package/dist/agent.cjs +39 -17
  7. package/dist/agent.d.cts +2 -2
  8. package/dist/agent.d.ts +2 -2
  9. package/dist/agent.js +9 -7
  10. package/dist/bin.js +4528 -355
  11. package/dist/{chunk-OQ55GEF3.js → chunk-3OPKTBEI.js} +1 -1
  12. package/dist/chunk-6PB4ZCHH.js +328 -0
  13. package/dist/chunk-7SCYDG2G.js +2943 -0
  14. package/dist/chunk-7WJIIJCI.js +544 -0
  15. package/dist/chunk-7Y6TU2UA.js +150 -0
  16. package/dist/{chunk-QC2M4NZY.js → chunk-BFVBHIHV.js} +72 -1
  17. package/dist/chunk-DSJETZT4.js +493 -0
  18. package/dist/{chunk-IW3D4I7Q.js → chunk-IU2SMWAM.js} +246 -4
  19. package/dist/{chunk-VICZ76TR.js → chunk-KAO3Z3CF.js} +43 -2
  20. package/dist/{chunk-CRDW6Q72.js → chunk-MA6VKJ3F.js} +87 -25
  21. package/dist/{chunk-6K5ZTGHQ.js → chunk-PEQY4N73.js} +16 -0
  22. package/dist/{chunk-DOADAH4L.js → chunk-PGV2QPIL.js} +40 -0
  23. package/dist/{chunk-Y63XQS2J.js → chunk-QMPSOLLH.js} +1 -1
  24. package/dist/{chunk-EXV6JNLY.js → chunk-ZCUJ4MPT.js} +15 -22
  25. package/dist/cli.cjs +4528 -355
  26. package/dist/cli.d.cts +19 -3
  27. package/dist/cli.d.ts +19 -3
  28. package/dist/cli.js +206 -16
  29. package/dist/client.cjs +72 -1
  30. package/dist/client.d.cts +308 -6
  31. package/dist/client.d.ts +308 -6
  32. package/dist/client.js +1 -1
  33. package/dist/cms-C_vkAxYV.d.cts +1537 -0
  34. package/dist/cms-pqJyowu1.d.ts +1537 -0
  35. package/dist/config.d.cts +7 -1
  36. package/dist/config.d.ts +7 -1
  37. package/dist/drizzle-repo-CviH3EX7.d.cts +146 -0
  38. package/dist/drizzle-repo-DWLD0rWe.d.ts +146 -0
  39. package/dist/errors.cjs +82 -1
  40. package/dist/errors.d.cts +43 -3
  41. package/dist/errors.d.ts +43 -3
  42. package/dist/errors.js +2 -2
  43. package/dist/frontmatter.d.cts +5 -4
  44. package/dist/frontmatter.d.ts +5 -4
  45. package/dist/http.cjs +640 -94
  46. package/dist/http.d.cts +51 -2
  47. package/dist/http.d.ts +51 -2
  48. package/dist/http.js +203 -13
  49. package/dist/index.cjs +3759 -575
  50. package/dist/index.d.cts +8 -8
  51. package/dist/index.d.ts +8 -8
  52. package/dist/index.js +226 -30
  53. package/dist/markdown.cjs +89 -25
  54. package/dist/markdown.d.cts +57 -3
  55. package/dist/markdown.d.ts +57 -3
  56. package/dist/markdown.js +5 -1
  57. package/dist/mcp.cjs +314 -37
  58. package/dist/mcp.d.cts +3 -2
  59. package/dist/mcp.d.ts +3 -2
  60. package/dist/mcp.js +12 -9
  61. package/dist/messages/en.cjs +40 -0
  62. package/dist/messages/en.js +1 -1
  63. package/dist/messages/ko.cjs +40 -0
  64. package/dist/messages/ko.js +40 -0
  65. package/dist/registry/cms-audit.json +1 -1
  66. package/dist/registry/cms-doc-editor.json +15 -4
  67. package/dist/registry/cms-doc-list.json +2 -1
  68. package/dist/registry/cms-files.json +29 -0
  69. package/dist/registry/cms-lib.json +3 -3
  70. package/dist/registry/cms-media-picker.json +29 -0
  71. package/dist/registry/cms-media.json +28 -0
  72. package/dist/registry/cms-preview-comments.json +24 -0
  73. package/dist/registry/cms-releases.json +28 -0
  74. package/dist/registry/cms-shell.json +2 -2
  75. package/dist/registry/cms-trash.json +24 -0
  76. package/dist/registry/cms-versions.json +2 -1
  77. package/dist/registry/registry.json +163 -3
  78. package/dist/storage-s3.cjs +168 -0
  79. package/dist/storage-s3.d.cts +53 -0
  80. package/dist/storage-s3.d.ts +53 -0
  81. package/dist/storage-s3.js +143 -0
  82. package/dist/storage.cjs +373 -0
  83. package/dist/storage.d.cts +183 -0
  84. package/dist/storage.d.ts +183 -0
  85. package/dist/storage.js +49 -0
  86. package/dist/tables.cjs +251 -3
  87. package/dist/tables.d.cts +4965 -681
  88. package/dist/tables.d.ts +4965 -681
  89. package/dist/tables.js +14 -2
  90. package/dist/tools.cjs +331 -20
  91. package/dist/tools.d.cts +54 -7
  92. package/dist/tools.d.ts +54 -7
  93. package/dist/tools.js +16 -7
  94. package/dist/types.cjs +99 -1
  95. package/dist/types.d.cts +205 -5
  96. package/dist/types.d.ts +205 -5
  97. package/dist/types.js +5 -3
  98. package/package.json +32 -22
  99. package/dist/ai.cjs +0 -555
  100. package/dist/ai.d.cts +0 -48
  101. package/dist/ai.d.ts +0 -48
  102. package/dist/ai.js +0 -73
  103. package/dist/chunk-52NUUZC7.js +0 -1446
  104. package/dist/chunk-IGL2V6US.js +0 -324
  105. package/dist/chunk-QQV6VLYJ.js +0 -204
  106. package/dist/cms-BPp01z-8.d.ts +0 -411
  107. package/dist/cms-D6D89-qZ.d.cts +0 -411
  108. package/dist/drizzle-repo-B1rt7r4j.d.ts +0 -90
  109. package/dist/drizzle-repo-Cn-kL2FK.d.cts +0 -90
  110. package/dist/repo-BWI2Pkrv.d.ts +0 -162
  111. package/dist/repo-CeDxUxO6.d.cts +0 -162
@@ -0,0 +1,2943 @@
1
+ import {
2
+ anchorOf,
3
+ appLinkKeys,
4
+ assetUses,
5
+ externalImages,
6
+ extractToc,
7
+ inlineText,
8
+ parseInline,
9
+ parseMarkdown,
10
+ plainText,
11
+ splitSections
12
+ } from "./chunk-MA6VKJ3F.js";
13
+ import {
14
+ docState
15
+ } from "./chunk-PEQY4N73.js";
16
+ import {
17
+ SCHEMA_VERSION
18
+ } from "./chunk-3OPKTBEI.js";
19
+ import {
20
+ fieldChanges,
21
+ hunks,
22
+ splitLines,
23
+ unifiedDiff
24
+ } from "./chunk-AKN7SUXU.js";
25
+ import {
26
+ CmsError,
27
+ formatMessage,
28
+ isCmsError
29
+ } from "./chunk-KAO3Z3CF.js";
30
+ import {
31
+ ASSET_ID_RE,
32
+ DEFAULT_ACCEPT,
33
+ DEFAULT_MAX_FILE_SIZE,
34
+ MIME_BY_EXT,
35
+ PART_SIZE,
36
+ RESERVED_FOLDER,
37
+ THUMB_PREFIX,
38
+ acceptsFile,
39
+ cleanFolder,
40
+ cleanName,
41
+ contentMatches,
42
+ declaredMatches,
43
+ dispositionFor,
44
+ extOf,
45
+ joinKey,
46
+ kindOf,
47
+ mimeOf,
48
+ newAssetId,
49
+ numberedName,
50
+ sniff
51
+ } from "./chunk-6PB4ZCHH.js";
52
+
53
+ // src/net-guard.ts
54
+ var FetchGuardError = class extends Error {
55
+ constructor(reason, message) {
56
+ super(message);
57
+ this.reason = reason;
58
+ this.name = "FetchGuardError";
59
+ }
60
+ reason;
61
+ };
62
+ function v4Public(ip) {
63
+ const p = ip.split(".").map(Number);
64
+ if (p.length !== 4 || p.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return false;
65
+ const [a, b] = p;
66
+ if (a === 0 || a === 10 || a === 127 || a >= 224) return false;
67
+ if (a === 100 && b >= 64 && b <= 127) return false;
68
+ if (a === 169 && b === 254) return false;
69
+ if (a === 172 && b >= 16 && b <= 31) return false;
70
+ if (a === 192 && (b === 168 || b === 0 && p[2] === 0)) return false;
71
+ if (a === 198 && (b === 18 || b === 19)) return false;
72
+ return true;
73
+ }
74
+ function isPublicAddress(ip) {
75
+ const s = ip.trim().toLowerCase().replace(/^\[|\]$/g, "");
76
+ if (!s.includes(":")) return v4Public(s);
77
+ const mapped = /^(?:::ffff:|64:ff9b::)(\d+\.\d+\.\d+\.\d+)$/.exec(s);
78
+ if (mapped) return v4Public(mapped[1]);
79
+ if (s === "::" || s === "::1" || s.startsWith("::ffff:") || s.startsWith("64:ff9b:")) return false;
80
+ const first = parseInt(s.split(":")[0] || "0", 16);
81
+ if ((first & 65024) === 64512) return false;
82
+ if ((first & 65472) === 65152) return false;
83
+ if ((first & 65280) === 65280) return false;
84
+ if (first === 0) return false;
85
+ return true;
86
+ }
87
+ var defaultResolve = async (host) => {
88
+ const dns = await import("dns/promises");
89
+ return (await dns.lookup(host, { all: true })).map((a) => a.address);
90
+ };
91
+ async function guardedFetch(url, o) {
92
+ const doFetch = o.fetch ?? fetch;
93
+ const resolve = o.resolveHost ?? defaultResolve;
94
+ const signal = AbortSignal.timeout(o.timeoutMs ?? 3e4);
95
+ let current = url;
96
+ for (let hop = 0; hop <= (o.maxRedirects ?? 3); hop++) {
97
+ let u;
98
+ try {
99
+ u = new URL(current);
100
+ } catch {
101
+ throw new FetchGuardError("blocked", "not a URL");
102
+ }
103
+ if (u.protocol !== "https:" || u.username || u.password) throw new FetchGuardError("blocked", "only https addresses without credentials");
104
+ const host = u.hostname.replace(/^\[|\]$/g, "");
105
+ const literal = /^[\d.]+$/.test(host) || host.includes(":");
106
+ let addrs;
107
+ try {
108
+ addrs = literal ? [host] : await resolve(host);
109
+ } catch {
110
+ throw new FetchGuardError("failed", "the host name does not resolve");
111
+ }
112
+ if (!addrs.length || !addrs.every(isPublicAddress)) throw new FetchGuardError("blocked", "the address is not on the public internet");
113
+ let res;
114
+ try {
115
+ res = await doFetch(u, { redirect: "manual", signal, headers: { accept: "*/*" } });
116
+ } catch (e) {
117
+ throw new FetchGuardError("failed", e instanceof Error && e.name === "TimeoutError" ? "timed out" : "the request failed");
118
+ }
119
+ if (res.status >= 300 && res.status < 400) {
120
+ const next = res.headers.get("location");
121
+ await res.body?.cancel().catch(() => {
122
+ });
123
+ if (!next) throw new FetchGuardError("failed", "redirect without a location");
124
+ current = new URL(next, u).toString();
125
+ continue;
126
+ }
127
+ if (!res.ok) {
128
+ await res.body?.cancel().catch(() => {
129
+ });
130
+ throw new FetchGuardError("failed", `status ${res.status}`);
131
+ }
132
+ if (Number(res.headers.get("content-length") ?? 0) > o.maxBytes) {
133
+ await res.body?.cancel().catch(() => {
134
+ });
135
+ throw new FetchGuardError("too_large", "too large");
136
+ }
137
+ const chunks = [];
138
+ let total = 0;
139
+ const reader = res.body?.getReader();
140
+ try {
141
+ while (reader) {
142
+ const { done, value } = await reader.read();
143
+ if (done) break;
144
+ total += value.length;
145
+ if (total > o.maxBytes) {
146
+ await reader.cancel().catch(() => {
147
+ });
148
+ throw new FetchGuardError("too_large", "too large");
149
+ }
150
+ chunks.push(value);
151
+ }
152
+ } catch (e) {
153
+ if (e instanceof FetchGuardError) throw e;
154
+ throw new FetchGuardError("failed", "the download broke off");
155
+ }
156
+ const bytes = new Uint8Array(total);
157
+ let at = 0;
158
+ for (const c of chunks) {
159
+ bytes.set(c, at);
160
+ at += c.length;
161
+ }
162
+ return { bytes, mime: res.headers.get("content-type"), url: u.toString() };
163
+ }
164
+ throw new FetchGuardError("failed", "too many redirects");
165
+ }
166
+ function imageSize(b) {
167
+ const v = new DataView(b.buffer, b.byteOffset, b.byteLength);
168
+ const ascii = (i, n) => String.fromCharCode(...b.subarray(i, i + n));
169
+ try {
170
+ if (b[0] === 137 && ascii(1, 3) === "PNG" && b.length >= 24) return { width: v.getUint32(16), height: v.getUint32(20) };
171
+ if (ascii(0, 3) === "GIF" && b.length >= 10) return { width: v.getUint16(6, true), height: v.getUint16(8, true) };
172
+ if (ascii(0, 4) === "RIFF" && ascii(8, 4) === "WEBP" && b.length >= 30) {
173
+ const kind = ascii(12, 4);
174
+ if (kind === "VP8X") return { width: 1 + (b[24] | b[25] << 8 | b[26] << 16), height: 1 + (b[27] | b[28] << 8 | b[29] << 16) };
175
+ if (kind === "VP8 ") return { width: v.getUint16(26, true) & 16383, height: v.getUint16(28, true) & 16383 };
176
+ if (kind === "VP8L") {
177
+ const n = v.getUint32(21, true);
178
+ return { width: (n & 16383) + 1, height: (n >> 14 & 16383) + 1 };
179
+ }
180
+ }
181
+ if (b[0] === 255 && b[1] === 216) {
182
+ let i = 2;
183
+ while (i + 9 < b.length) {
184
+ if (b[i] !== 255) {
185
+ i++;
186
+ continue;
187
+ }
188
+ const marker = b[i + 1];
189
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) return { width: v.getUint16(i + 7), height: v.getUint16(i + 5) };
190
+ if (marker === 216 || marker >= 208 && marker <= 215 || marker === 1 || marker === 255) {
191
+ i += marker === 255 ? 1 : 2;
192
+ continue;
193
+ }
194
+ i += 2 + v.getUint16(i + 2);
195
+ }
196
+ }
197
+ } catch {
198
+ }
199
+ return null;
200
+ }
201
+
202
+ // src/assets.ts
203
+ import { z } from "zod";
204
+ var SIGN_SECONDS = 3600;
205
+ var MAX_THUMB_BYTES = 512 * 1024;
206
+ var TAG_MAX = 30;
207
+ var assetId = () => z.string().regex(ASSET_ID_RE, "not a file id");
208
+ function humanSize(bytes) {
209
+ const units = ["B", "KB", "MB", "GB", "TB"];
210
+ let n = bytes;
211
+ let i = 0;
212
+ while (n >= 1024 && i < units.length - 1) {
213
+ n /= 1024;
214
+ i++;
215
+ }
216
+ return `${n >= 10 || i === 0 || Number.isInteger(n) ? Math.round(n) : n.toFixed(1)}${units[i]}`;
217
+ }
218
+ var cleanTags = (tags) => [...new Set((Array.isArray(tags) ? tags : []).map((t) => String(t).trim().slice(0, 40)).filter(Boolean))].slice(0, TAG_MAX);
219
+ var getPath = (obj, path) => path.split(".").reduce((o, k) => o && typeof o === "object" ? o[k] : void 0, obj);
220
+ function assetFields(cfg) {
221
+ return Object.entries(cfg.admin?.fields ?? {}).filter(([, f]) => f.widget === "image" || f.widget === "file").map(([path, f]) => ({ path, widget: f.widget, accept: f.accept ?? (f.widget === "image" ? ["image/*"] : null), maxFileSize: f.maxFileSize ?? null, store: f.store ?? null }));
222
+ }
223
+ function createAssets(ctx) {
224
+ const { repo, media, fail } = ctx;
225
+ const names = Object.keys(media?.stores ?? {});
226
+ const filesUrl = (media?.filesUrl ?? "/api/cms/files").replace(/\/+$/, "");
227
+ const ttl = media?.linkTtlSeconds ?? 300;
228
+ for (const n of names) {
229
+ const s = media.stores[n];
230
+ const rules = s.accept ?? media.accept ?? DEFAULT_ACCEPT;
231
+ if (s.visibility === "public" && acceptsFile(rules, { name: "x.html", mime: "text/html" })) ctx.warn(`media-html-${n}`, `the public store "${n}" accepts HTML files: anyone who can upload can publish a web page under its address`);
232
+ }
233
+ function storeOf(name) {
234
+ if (!media || !names.length) throw fail("media_disabled");
235
+ const n = name || names[0];
236
+ const cfg = media.stores[n];
237
+ if (!cfg) throw fail("unknown_store", { store: n });
238
+ return { name: n, cfg };
239
+ }
240
+ function canAsset(actor, store, what) {
241
+ const cfg = media?.stores[store];
242
+ if (!cfg) return false;
243
+ if (actor.kind === "system") return true;
244
+ const own = cfg.access?.[what];
245
+ if (own) return own({ actor, store });
246
+ if (actor.kind === "anonymous") return false;
247
+ if (what === "read") return true;
248
+ if (actor.kind === "user") return actor.isAdmin;
249
+ return actor.scopes.includes("admin") || actor.scopes.includes(what === "write" ? "write" : "publish");
250
+ }
251
+ function need(actor, store, what) {
252
+ if (canAsset(actor, store, what)) return;
253
+ if (actor.kind !== "anonymous" && what !== "read") ctx.audit(actor, "access.denied", { outcome: "denied", detail: { store, need: `asset.${what}` } });
254
+ throw actor.kind === "anonymous" ? fail("unauthorized") : fail("forbidden_media", { store });
255
+ }
256
+ const rulesOf = (cfg) => ({ accept: cfg.accept ?? media?.accept ?? DEFAULT_ACCEPT, maxFileSize: cfg.maxFileSize ?? media?.maxFileSize ?? DEFAULT_MAX_FILE_SIZE });
257
+ function view(a) {
258
+ const cfg = media?.stores[a.store];
259
+ const href = `${filesUrl}/${a.id}/${encodeURIComponent(a.name)}`;
260
+ return { ...a, visibility: cfg?.visibility ?? "private", href, publicUrl: cfg?.visibility === "public" ? cfg.adapter.publicUrl(a.key) : null, thumbHref: a.thumbKey ? `${href}?thumb=1` : null };
261
+ }
262
+ const info = (a) => {
263
+ const v = view(a);
264
+ return { id: a.id, name: a.name, kind: a.kind, mime: a.mime, size: a.size, width: a.width, height: a.height, duration: a.duration, alt: a.alt, url: v.publicUrl ?? v.href, visibility: v.visibility };
265
+ };
266
+ async function load(id, o = {}) {
267
+ const a = ASSET_ID_RE.test(id) ? await repo.findAsset(id) : null;
268
+ if (!a || !media?.stores[a.store] || a.status !== "ready" && !o.pending) throw fail("asset_not_found", { id });
269
+ return a;
270
+ }
271
+ async function freeKey(store, folder, name, skipId) {
272
+ for (let n = 1; n <= 200; n++) {
273
+ const candidate = numberedName(name, n);
274
+ const key = joinKey(folder, candidate);
275
+ const row = await repo.findAssetByKey(store.name, key);
276
+ if (row && row.id !== skipId) continue;
277
+ if (!row && await store.cfg.adapter.head(key)) continue;
278
+ return { key, name: candidate };
279
+ }
280
+ throw fail("invalid", { reason: "too many files with this name" });
281
+ }
282
+ function admit(store, input) {
283
+ const name = cleanName(input.name);
284
+ const folder = cleanFolder(input.folder);
285
+ if (folder === null) throw fail("invalid_folder", { folder: String(input.folder) });
286
+ if (!Number.isInteger(input.size) || input.size <= 0) throw fail("invalid", { reason: "size" });
287
+ if (!declaredMatches(name, input.mime)) throw fail("asset_type_mismatch", { name, mime: String(input.mime) });
288
+ const mime = mimeOf(name, input.mime);
289
+ const rules = rulesOf(store.cfg);
290
+ let max = rules.maxFileSize;
291
+ let ok = acceptsFile(rules.accept, { name, mime });
292
+ let allowed = rules.accept;
293
+ if (input.field) {
294
+ const f = assetFields(ctx.collection(input.field.collection)).find((x) => x.path === input.field.path);
295
+ if (f?.accept) {
296
+ ok = ok && acceptsFile(f.accept, { name, mime });
297
+ allowed = f.accept;
298
+ }
299
+ if (f?.maxFileSize) max = Math.min(max, f.maxFileSize);
300
+ }
301
+ if (!ok) throw fail("asset_type_not_allowed", { name, mime, allowed: [...allowed] });
302
+ if (input.size > max) throw fail("asset_too_large", { size: input.size, max: humanSize(max), maxBytes: max }, { status: 413 });
303
+ return { name, folder, mime };
304
+ }
305
+ async function requestUpload(actor, input) {
306
+ await ctx.ready();
307
+ const store = storeOf(input.store);
308
+ need(actor, store.name, "write");
309
+ const a = admit(store, input);
310
+ const free = await freeKey(store, a.folder, a.name);
311
+ const put2 = { mime: a.mime, disposition: dispositionFor(free.name, a.mime) };
312
+ const who = ctx.actorRef(actor);
313
+ let upload;
314
+ let uploadId = null;
315
+ if (input.size <= PART_SIZE) {
316
+ const signed = await store.cfg.adapter.presignPut(free.key, { ...put2, expires: SIGN_SECONDS });
317
+ upload = { kind: "single", url: signed.url, headers: signed.headers };
318
+ } else {
319
+ uploadId = await store.cfg.adapter.createMultipart(free.key, put2);
320
+ upload = { kind: "multipart", partSize: PART_SIZE, partCount: Math.ceil(input.size / PART_SIZE) };
321
+ }
322
+ const row = await repo.insertAsset({
323
+ id: newAssetId(),
324
+ store: store.name,
325
+ key: free.key,
326
+ folder: a.folder,
327
+ name: free.name,
328
+ kind: kindOf(a.mime),
329
+ mime: a.mime,
330
+ size: input.size,
331
+ width: null,
332
+ height: null,
333
+ duration: null,
334
+ alt: (input.alt ?? "").trim().slice(0, 500),
335
+ tags: cleanTags(input.tags),
336
+ thumbKey: null,
337
+ status: "pending",
338
+ uploadId,
339
+ createdBy: who.label,
340
+ createdByKind: who.kind,
341
+ createdByAgent: who.agent,
342
+ createdAt: ctx.nowIso(),
343
+ updatedAt: ctx.nowIso()
344
+ });
345
+ return { asset: view(row), upload };
346
+ }
347
+ async function partUrls(actor, id, parts) {
348
+ const a = await load(id, { pending: true });
349
+ need(actor, a.store, "write");
350
+ if (a.status !== "pending" || !a.uploadId) throw fail("asset_not_found", { id });
351
+ const count = Math.ceil(a.size / PART_SIZE);
352
+ const wanted = [...new Set(parts)].filter((n) => Number.isInteger(n) && n >= 1 && n <= count).slice(0, 200);
353
+ const adapter = storeOf(a.store).cfg.adapter;
354
+ return Promise.all(wanted.map(async (partNumber) => ({ partNumber, url: await adapter.presignPart(a.key, a.uploadId, partNumber, SIGN_SECONDS) })));
355
+ }
356
+ async function uploadStatus(actor, id) {
357
+ const a = await load(id, { pending: true });
358
+ need(actor, a.store, "write");
359
+ const done = a.status === "pending" && a.uploadId ? (await storeOf(a.store).cfg.adapter.listParts(a.key, a.uploadId)).map((p) => p.partNumber) : [];
360
+ return { asset: view(a), partSize: PART_SIZE, partCount: Math.ceil(a.size / PART_SIZE), done };
361
+ }
362
+ async function discard(a) {
363
+ const adapter = media?.stores[a.store]?.adapter;
364
+ if (adapter) {
365
+ if (a.uploadId) await adapter.abortMultipart(a.key, a.uploadId).catch(() => {
366
+ });
367
+ await adapter.delete(a.key).catch(() => {
368
+ });
369
+ if (a.thumbKey) await adapter.delete(a.thumbKey).catch(() => {
370
+ });
371
+ }
372
+ await repo.deleteAsset(a.id);
373
+ }
374
+ const dims = (o) => {
375
+ const int = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 && v < 1e5 ? Math.round(v) : null;
376
+ return { width: int(o.width), height: int(o.height), duration: typeof o.duration === "number" && Number.isFinite(o.duration) && o.duration >= 0 ? o.duration : null };
377
+ };
378
+ async function completeUpload(actor, id, meta = {}) {
379
+ const a = await load(id, { pending: true });
380
+ need(actor, a.store, "write");
381
+ if (a.status === "ready") return view(a);
382
+ const adapter = storeOf(a.store).cfg.adapter;
383
+ if (a.uploadId) {
384
+ const parts = await adapter.listParts(a.key, a.uploadId);
385
+ const count = Math.ceil(a.size / PART_SIZE);
386
+ const have = new Set(parts.map((p) => p.partNumber));
387
+ const missing = Array.from({ length: count }, (_, i) => i + 1).filter((n) => !have.has(n));
388
+ if (missing.length || parts.reduce((s, p) => s + p.size, 0) !== a.size) throw fail("upload_incomplete", { missing: missing.slice(0, 50).join(",") });
389
+ await adapter.completeMultipart(a.key, a.uploadId, parts);
390
+ }
391
+ const head = await adapter.head(a.key);
392
+ if (!head) throw fail("upload_incomplete", {});
393
+ if (head.size !== a.size) {
394
+ await discard({ ...a, uploadId: null });
395
+ throw fail("upload_incomplete", { size: head.size, expected: a.size });
396
+ }
397
+ const start = await adapter.readStart(a.key, 4096) ?? new Uint8Array();
398
+ if (!contentMatches(a.mime, start)) {
399
+ await discard({ ...a, uploadId: null });
400
+ throw fail("asset_type_mismatch", { name: a.name, mime: a.mime });
401
+ }
402
+ await scanned(actor, { store: a.store, key: a.key, name: a.name, mime: a.mime, size: head.size }, adapter).catch(async (e) => {
403
+ await discard({ ...a, uploadId: null });
404
+ throw e;
405
+ });
406
+ const given = dims(meta);
407
+ const read = a.kind === "image" && !given.width ? imageSize(start) : null;
408
+ const row = await repo.updateAsset(a.id, { status: "ready", uploadId: null, width: given.width ?? read?.width ?? null, height: given.height ?? read?.height ?? null, duration: given.duration, updatedAt: ctx.nowIso() });
409
+ ctx.audit(actor, "asset.upload", { detail: { id: a.id, store: a.store, key: a.key, size: a.size } });
410
+ return view(row);
411
+ }
412
+ async function abortUpload(actor, id) {
413
+ const a = await load(id, { pending: true });
414
+ need(actor, a.store, "write");
415
+ if (a.status === "pending") await discard(a);
416
+ }
417
+ async function setThumb(actor, id, bytes) {
418
+ const a = await load(id);
419
+ need(actor, a.store, "write");
420
+ const family = sniff(bytes);
421
+ if (!bytes.length || bytes.length > MAX_THUMB_BYTES || !(family === "webp" || family === "jpeg" || family === "png")) throw fail("asset_type_not_allowed", { name: "thumbnail", mime: String(family), allowed: ["image/webp", "image/jpeg", "image/png"] });
422
+ const ext = family === "jpeg" ? "jpg" : family;
423
+ const key = `${THUMB_PREFIX}${a.id}.${ext}`;
424
+ await storeOf(a.store).cfg.adapter.put(key, bytes, { mime: `image/${family}`, cacheControl: "public, max-age=31536000, immutable" });
425
+ if (a.thumbKey && a.thumbKey !== key) await storeOf(a.store).cfg.adapter.delete(a.thumbKey).catch(() => {
426
+ });
427
+ return view(await repo.updateAsset(a.id, { thumbKey: key, updatedAt: ctx.nowIso() }));
428
+ }
429
+ async function put(actor, input) {
430
+ await ctx.ready();
431
+ const store = storeOf(input.store);
432
+ need(actor, store.name, "write");
433
+ const a = admit(store, { ...input, size: input.bytes.length });
434
+ if (!contentMatches(a.mime, input.bytes.subarray(0, 4096))) throw fail("asset_type_mismatch", { name: a.name, mime: a.mime });
435
+ const free = await freeKey(store, a.folder, a.name);
436
+ await scanned(actor, { store: store.name, key: free.key, name: free.name, mime: a.mime, size: input.bytes.length, bytes: input.bytes }, null);
437
+ await store.cfg.adapter.put(free.key, input.bytes, { mime: a.mime, disposition: dispositionFor(free.name, a.mime) });
438
+ const who = ctx.actorRef(actor);
439
+ const given = dims(input);
440
+ const kind = kindOf(a.mime);
441
+ const read = kind === "image" && !given.width ? imageSize(input.bytes) : null;
442
+ const row = await repo.insertAsset({
443
+ id: newAssetId(),
444
+ store: store.name,
445
+ key: free.key,
446
+ folder: a.folder,
447
+ name: free.name,
448
+ kind,
449
+ mime: a.mime,
450
+ size: input.bytes.length,
451
+ width: given.width ?? read?.width ?? null,
452
+ height: given.height ?? read?.height ?? null,
453
+ duration: given.duration,
454
+ alt: (input.alt ?? "").trim().slice(0, 500),
455
+ tags: cleanTags(input.tags),
456
+ thumbKey: null,
457
+ status: "ready",
458
+ uploadId: null,
459
+ createdBy: who.label,
460
+ createdByKind: who.kind,
461
+ createdByAgent: who.agent,
462
+ createdAt: ctx.nowIso(),
463
+ updatedAt: ctx.nowIso()
464
+ });
465
+ ctx.audit(actor, "asset.upload", { detail: { id: row.id, store: row.store, key: row.key, size: row.size } });
466
+ return view(row);
467
+ }
468
+ async function importFromUrl(actor, input) {
469
+ const store = storeOf(input.store);
470
+ need(actor, store.name, "write");
471
+ const maxBytes = Math.min(media?.importMaxBytes ?? 50 * 1024 * 1024, rulesOf(store.cfg).maxFileSize);
472
+ let got;
473
+ try {
474
+ got = await guardedFetch(input.url, { maxBytes, fetch: media?.fetch, resolveHost: media?.resolveHost });
475
+ } catch (e) {
476
+ if (!(e instanceof FetchGuardError)) throw e;
477
+ if (e.reason === "too_large") throw fail("asset_too_large", { max: humanSize(maxBytes), maxBytes }, { status: 413 });
478
+ throw e.reason === "blocked" ? fail("import_blocked", { reason: e.message }) : fail("import_failed", { reason: e.message });
479
+ }
480
+ let fromUrl = "";
481
+ try {
482
+ fromUrl = decodeURIComponent(new URL(got.url).pathname.split("/").pop() ?? "");
483
+ } catch {
484
+ }
485
+ return put(actor, { name: input.name?.trim() || fromUrl || "file", mime: got.mime, bytes: got.bytes, folder: input.folder, store: store.name, alt: input.alt, tags: input.tags });
486
+ }
487
+ async function list(actor, o = {}) {
488
+ await ctx.ready();
489
+ const store = storeOf(o.store);
490
+ need(actor, store.name, "read");
491
+ const under = cleanFolder(o.folder) ?? "";
492
+ const limit = Math.min(Math.max(o.limit ?? 48, 1), 200);
493
+ const rows = await repo.listAssets({ store: store.name, under, status: "ready", notKinds: ["folder"], kinds: o.kinds?.length ? o.kinds : void 0, q: o.q, tag: o.tag, before: o.cursor ?? null, limit: limit + 1 });
494
+ const page = rows.slice(0, limit);
495
+ const counts = { all: 0, image: 0, video: 0, audio: 0, document: 0, other: 0 };
496
+ for (const c of await repo.countAssets(store.name)) {
497
+ if (c.kind === "folder" || !(under === "" || c.folder === under || c.folder.startsWith(`${under}/`))) continue;
498
+ counts[c.kind] += c.n;
499
+ counts.all += c.n;
500
+ }
501
+ const last = page[page.length - 1];
502
+ return { assets: page.map(view), cursor: rows.length > limit && last ? `${last.createdAt}|${last.id}` : null, counts };
503
+ }
504
+ async function folders(actor) {
505
+ await ctx.ready();
506
+ if (!media) throw fail("media_disabled");
507
+ const out = [];
508
+ for (const name of names) {
509
+ if (!canAsset(actor, name, "read")) continue;
510
+ const cfg = media.stores[name];
511
+ const count = /* @__PURE__ */ new Map();
512
+ let total = 0;
513
+ for (const c of await repo.countAssets(name)) {
514
+ const parts = c.folder ? c.folder.split("/") : [];
515
+ for (let i = 1; i <= parts.length; i++) {
516
+ const p = parts.slice(0, i).join("/");
517
+ count.set(p, (count.get(p) ?? 0) + (c.kind === "folder" ? 0 : c.n));
518
+ }
519
+ if (c.kind !== "folder") total += c.n;
520
+ }
521
+ for (const f of await repo.listAssets({ store: name, kinds: ["folder"], status: "ready", limit: 2e3 })) {
522
+ const p = joinKey(f.folder, f.name);
523
+ if (!count.has(p)) count.set(p, 0);
524
+ }
525
+ out.push({ store: name, label: cfg.label ?? name, visibility: cfg.visibility, total, folders: [...count].map(([path, n]) => ({ path, count: n })).sort((a, b) => a.path.localeCompare(b.path)) });
526
+ }
527
+ return out;
528
+ }
529
+ async function createFolder(actor, input) {
530
+ await ctx.ready();
531
+ const store = storeOf(input.store);
532
+ need(actor, store.name, "write");
533
+ const path = cleanFolder(input.path);
534
+ if (!path) throw fail("invalid_folder", { folder: String(input.path) });
535
+ const key = `${path}/`;
536
+ if (!await repo.findAssetByKey(store.name, key)) {
537
+ const parts = path.split("/");
538
+ const who = ctx.actorRef(actor);
539
+ await store.cfg.adapter.put(key, new Uint8Array(), { mime: "application/x-directory" });
540
+ await repo.insertAsset({ id: newAssetId(), store: store.name, key, folder: parts.slice(0, -1).join("/"), name: parts[parts.length - 1], kind: "folder", mime: "application/x-directory", size: 0, width: null, height: null, duration: null, alt: "", tags: [], thumbKey: null, status: "ready", uploadId: null, createdBy: who.label, createdByKind: who.kind, createdByAgent: who.agent });
541
+ }
542
+ return { store: store.name, path };
543
+ }
544
+ async function deleteFolder(actor, input) {
545
+ const store = storeOf(input.store);
546
+ need(actor, store.name, "delete");
547
+ const path = cleanFolder(input.path);
548
+ if (!path) throw fail("invalid_folder", { folder: String(input.path) });
549
+ const inside = await repo.listAssets({ store: store.name, under: path, limit: 2 });
550
+ if (inside.length) throw fail("folder_not_empty", { folder: path });
551
+ const row = await repo.findAssetByKey(store.name, `${path}/`);
552
+ await store.cfg.adapter.delete(`${path}/`).catch(() => {
553
+ });
554
+ if (row) await repo.deleteAsset(row.id);
555
+ }
556
+ async function usage(actor, a) {
557
+ const documents = [];
558
+ let hidden = 0;
559
+ for (const r of await repo.listAssetRefs(a.id)) {
560
+ const d = await repo.findDocById(r.documentId);
561
+ if (!d) continue;
562
+ if (!ctx.canReadDoc(actor, d)) hidden++;
563
+ else documents.push({ collection: d.collection, slug: d.slug, title: d.title, status: d.status, inDraft: r.inDraft, inPublished: r.inPublished });
564
+ }
565
+ return { documents, hidden };
566
+ }
567
+ async function get(actor, id) {
568
+ await ctx.ready();
569
+ const a = await load(id);
570
+ need(actor, a.store, "read");
571
+ const u = await usage(actor, a);
572
+ return { ...view(a), usage: u.documents, usageHidden: u.hidden };
573
+ }
574
+ async function update(actor, id, patch) {
575
+ const a = await load(id);
576
+ need(actor, a.store, "write");
577
+ const row = await repo.updateAsset(a.id, { ...patch.alt !== void 0 ? { alt: String(patch.alt).trim().slice(0, 500) } : {}, ...patch.tags !== void 0 ? { tags: cleanTags(patch.tags) } : {}, updatedAt: ctx.nowIso() });
578
+ return view(row);
579
+ }
580
+ async function move(actor, id, to) {
581
+ const a = await load(id);
582
+ need(actor, a.store, "delete");
583
+ const store = storeOf(a.store);
584
+ const folder = to.folder === void 0 || to.folder === null ? a.folder : cleanFolder(to.folder);
585
+ if (folder === null) throw fail("invalid_folder", { folder: String(to.folder) });
586
+ let name = to.name ? cleanName(to.name) : a.name;
587
+ const ext = extOf(name);
588
+ if (extOf(a.name) && ext !== extOf(a.name) && MIME_BY_EXT[ext] !== a.mime) name = cleanName(`${name}.${extOf(a.name)}`);
589
+ if (folder === a.folder && name === a.name) return view(a);
590
+ const free = await freeKey(store, folder, name, a.id);
591
+ await store.cfg.adapter.copy(a.key, free.key);
592
+ const row = await repo.updateAsset(a.id, { key: free.key, folder, name: free.name, updatedAt: ctx.nowIso() });
593
+ await store.cfg.adapter.delete(a.key).catch(() => {
594
+ });
595
+ ctx.audit(actor, "asset.move", { detail: { id: a.id, store: a.store, from: a.key, to: free.key } });
596
+ return view(row);
597
+ }
598
+ async function remove(actor, id, o = {}) {
599
+ const a = await load(id);
600
+ need(actor, a.store, "delete");
601
+ const u = await usage(actor, a);
602
+ const count = u.documents.length + u.hidden;
603
+ if (count && !o.confirm) throw fail("asset_in_use", { count, documents: u.documents.map((d) => `${d.collection}/${d.slug}`) }, { current: { documents: u.documents, hidden: u.hidden } });
604
+ const trash = (ctx.trashDays ?? 0) > 0 && a.kind !== "folder";
605
+ if (trash) await repo.updateAsset(a.id, { deletedAt: ctx.nowIso(), deletedBy: ctx.actorRef(actor).label });
606
+ else await discard(a);
607
+ ctx.audit(actor, "asset.delete", { detail: { id: a.id, store: a.store, key: a.key, usedBy: count, trash } });
608
+ }
609
+ async function trashed(actor) {
610
+ await ctx.ready();
611
+ return (await repo.listAssets({ trashed: true, limit: 1e3 })).filter((a) => !!media?.stores[a.store] && canAsset(actor, a.store, "read"));
612
+ }
613
+ async function inTrash(id) {
614
+ const a = ASSET_ID_RE.test(id) ? await repo.findAsset(id, { trashed: true }) : null;
615
+ if (!a?.deletedAt || !media?.stores[a.store]) throw fail("trash_not_found", { id });
616
+ return a;
617
+ }
618
+ async function untrash(actor, id) {
619
+ await ctx.ready();
620
+ const a = await inTrash(id);
621
+ need(actor, a.store, "delete");
622
+ const out = await repo.updateAsset(a.id, { deletedAt: null, deletedBy: null });
623
+ ctx.audit(actor, "asset.restore", { detail: { id: a.id, store: a.store, key: a.key } });
624
+ return view(out);
625
+ }
626
+ async function purge(actor, id) {
627
+ const a = ASSET_ID_RE.test(id) ? await repo.findAsset(id, { trashed: true }) : null;
628
+ if (!a?.deletedAt) return false;
629
+ await discard(a);
630
+ ctx.audit(actor, "asset.delete", { detail: { id: a.id, store: a.store, key: a.key, purge: true } });
631
+ return true;
632
+ }
633
+ async function purgeOlder(cutoff) {
634
+ let n = 0;
635
+ for (const a of await repo.listAssets({ trashed: true, limit: 1e3 })) {
636
+ if (!a.deletedAt || a.deletedAt > cutoff) continue;
637
+ await discard(a);
638
+ n++;
639
+ }
640
+ return n;
641
+ }
642
+ async function open(actor, id, o = {}) {
643
+ await ctx.ready();
644
+ const a = await load(id);
645
+ const store = storeOf(a.store);
646
+ if (store.cfg.visibility === "private" || store.cfg.access?.read) need(actor, a.store, "read");
647
+ const key = o.thumb && a.thumbKey ? a.thumbKey : a.key;
648
+ const direct = store.cfg.visibility === "public" && !o.download ? store.cfg.adapter.publicUrl(key) : null;
649
+ return { url: direct ?? await store.cfg.adapter.presignGet(key, { expires: ttl, download: o.download ? a.name : null }), visibility: store.cfg.visibility, ttl };
650
+ }
651
+ async function cleanup(o = {}) {
652
+ if (!media) return { removed: 0 };
653
+ const before = new Date(Date.parse(ctx.nowIso()) - (o.olderThanMs ?? 24 * 3600 * 1e3)).toISOString();
654
+ const stale = await repo.listAssets({ status: "pending", createdBefore: before, limit: 500 });
655
+ for (const a of stale) await discard(a);
656
+ return { removed: stale.length };
657
+ }
658
+ function idsIn(cfg, c) {
659
+ const ids = new Set(assetUses(c.body).map((u) => u.id));
660
+ for (const f of assetFields(cfg)) {
661
+ const v = getPath(c.fields, f.path);
662
+ if (typeof v === "string" && ASSET_ID_RE.test(v)) ids.add(v);
663
+ }
664
+ return ids;
665
+ }
666
+ async function checkDoc(cfg, c, known = /* @__PURE__ */ new Set(), r = repo) {
667
+ const out = [];
668
+ const uses = assetUses(c.body);
669
+ const fields = assetFields(cfg);
670
+ const fieldValues = fields.map((f) => ({ f, v: getPath(c.fields, f.path) })).filter((x) => typeof x.v === "string" && x.v !== "");
671
+ const altSeverity = cfg.media?.requireAlt ? "error" : "warning";
672
+ for (const e of externalImages(c.body)) if (!e.alt) out.push(ctx.diag("body", "asset_alt_missing", { line: e.line }, altSeverity));
673
+ if (!uses.length && !fieldValues.length) return out;
674
+ const ids = [.../* @__PURE__ */ new Set([...uses.map((u) => u.id), ...fieldValues.map((x) => x.v)])];
675
+ const rows = new Map((media ? await r.findAssets(ids.filter((i) => ASSET_ID_RE.test(i))) : []).filter((a) => a.status === "ready" && a.kind !== "folder").map((a) => [a.id, a]));
676
+ const missing = (path, id, extra = {}) => out.push(ctx.diag(path, "asset_missing", { id, ...extra }, known.has(id) ? "warning" : "error"));
677
+ const isPublic = cfg.visibility === "public";
678
+ const flagged = /* @__PURE__ */ new Set();
679
+ const privateCheck = (path, a) => {
680
+ if (isPublic && media?.stores[a.store]?.visibility === "private" && !flagged.has(a.id)) {
681
+ flagged.add(a.id);
682
+ out.push(ctx.diag(path, "asset_private_in_public", { id: a.id, name: a.name }, "warning"));
683
+ }
684
+ };
685
+ for (const u of uses) {
686
+ const a = rows.get(u.id);
687
+ if (!a) {
688
+ missing("body", u.id, { line: u.line });
689
+ continue;
690
+ }
691
+ if (u.as !== "file" && a.kind === "image" && !u.alt && !a.alt) out.push(ctx.diag("body", "asset_alt_missing", { line: u.line, id: a.id }, altSeverity));
692
+ privateCheck("body", a);
693
+ }
694
+ for (const { f, v } of fieldValues) {
695
+ const path = `fields.${f.path}`;
696
+ const a = rows.get(v);
697
+ if (!a) {
698
+ missing(path, v);
699
+ continue;
700
+ }
701
+ const fits = (f.widget !== "image" || a.kind === "image") && (!f.accept || acceptsFile(f.accept, { name: a.name, mime: a.mime })) && (!f.store || f.store === a.store);
702
+ if (!fits) out.push(ctx.diag(path, "asset_wrong_kind", { id: a.id, name: a.name }, "error"));
703
+ else if (f.maxFileSize && a.size > f.maxFileSize) out.push(ctx.diag(path, "asset_too_large", { size: a.size, max: humanSize(f.maxFileSize), maxBytes: f.maxFileSize }, "error"));
704
+ else if (a.kind === "image" && !a.alt) out.push(ctx.diag(path, "asset_alt_empty", { id: a.id }, altSeverity));
705
+ privateCheck(path, a);
706
+ }
707
+ return out;
708
+ }
709
+ async function assertDoc(cfg, next, prev, r = repo) {
710
+ if (prev && next.body === prev.body && JSON.stringify(next.fields) === JSON.stringify(prev.fields)) return;
711
+ const errors = (await checkDoc(cfg, next, prev ? idsIn(cfg, prev) : void 0, r)).filter((d) => d.severity === "error");
712
+ if (errors.length) throw fail(errors[0].code, errors[0].params, { diagnostics: errors });
713
+ }
714
+ async function syncRefs(r, doc) {
715
+ if (!media) return;
716
+ const cfg = ctx.collection(doc.collection);
717
+ const draft = idsIn(cfg, doc);
718
+ const published = doc.published && doc.publishedVersion !== null ? idsIn(cfg, doc.published) : /* @__PURE__ */ new Set();
719
+ await r.setAssetRefs(doc.id, [.../* @__PURE__ */ new Set([...draft, ...published])].map((assetId2) => ({ assetId: assetId2, inDraft: draft.has(assetId2), inPublished: published.has(assetId2) })));
720
+ }
721
+ async function assetsFor(doc) {
722
+ if (!media) return {};
723
+ const ids = [...idsIn(ctx.collection(doc.collection), doc)];
724
+ const rows = ids.length ? await repo.findAssets(ids) : [];
725
+ return Object.fromEntries(rows.filter((a) => a.status === "ready" && media.stores[a.store]).map((a) => [a.id, info(a)]));
726
+ }
727
+ function imageUrl(asset, o) {
728
+ return media?.imageUrl && asset.kind === "image" && asset.mime !== "image/svg+xml" ? media.imageUrl({ url: asset.url, width: o.width, asset }) : asset.url;
729
+ }
730
+ async function scanned(actor, f, adapter) {
731
+ if (!media?.scan) return;
732
+ let reason = null;
733
+ try {
734
+ const r = await media.scan({ ...f, url: adapter ? await adapter.presignGet(f.key, { expires: 600, download: null }) : null });
735
+ if (r === false || typeof r === "object" && r && !r.ok) reason = typeof r === "object" && r.reason || "refused";
736
+ } catch (e) {
737
+ reason = e instanceof Error ? e.message : String(e);
738
+ }
739
+ if (reason === null) return;
740
+ ctx.audit(actor, "asset.upload", { outcome: "denied", detail: { store: f.store, key: f.key, reason } });
741
+ throw fail("asset_rejected", { name: f.name, reason });
742
+ }
743
+ const reserved = (key) => key === RESERVED_FOLDER || key.startsWith(`${RESERVED_FOLDER}/`);
744
+ const canBrowse = (actor, store) => {
745
+ const own = media?.stores[store]?.access?.browse;
746
+ return own ? actor.kind === "system" || own({ actor, store }) : canAsset(actor, store, "read");
747
+ };
748
+ function needBrowse(actor, store) {
749
+ if (!canBrowse(actor, store)) throw actor.kind === "anonymous" ? fail("unauthorized") : fail("forbidden_media", { store });
750
+ }
751
+ function objectKey(key) {
752
+ const k = String(key ?? "").replace(/^\/+/, "");
753
+ if (!k || k.length > 1024 || reserved(k) || /[\u0000-\u001f]/.test(k) || k.split("/").some((p) => p === ".." || p === ".")) throw fail("invalid_folder", { folder: String(key) });
754
+ return k;
755
+ }
756
+ function folderPath(folder, o = {}) {
757
+ const f = String(folder ?? "").split("/").filter(Boolean).join("/");
758
+ if (f && objectKey(f) !== f || !f && !o.top) throw fail("invalid_folder", { folder: String(folder) });
759
+ return f;
760
+ }
761
+ const split = (key) => {
762
+ const k = key.replace(/\/$/, "");
763
+ const cut = k.lastIndexOf("/");
764
+ return { folder: cut < 0 ? "" : k.slice(0, cut), name: k.slice(cut + 1) };
765
+ };
766
+ async function browse(actor, input = {}) {
767
+ await ctx.ready();
768
+ const store = storeOf(input.store);
769
+ needBrowse(actor, store.name);
770
+ const folder = folderPath(input.prefix, { top: true });
771
+ const base = folder ? `${folder}/` : "";
772
+ const r = await store.cfg.adapter.list({ prefix: base + String(input.q ?? "").replace(/\//g, ""), delimiter: "/", cursor: input.cursor || null, limit: Math.min(Math.max(input.limit ?? 200, 1), 1e3) });
773
+ const objects = r.objects.filter((o) => !o.key.endsWith("/") && !reserved(o.key));
774
+ const known = new Map((await repo.findAssetsByKeys(store.name, objects.map((o) => o.key))).map((a) => [a.key, a]));
775
+ return {
776
+ store: store.name,
777
+ prefix: folder,
778
+ folders: r.prefixes.map((p) => p.replace(/\/$/, "")).filter((p) => !reserved(p)).map((p) => ({ path: p, name: p.slice(base.length) })),
779
+ files: objects.map((o) => {
780
+ const a = known.get(o.key);
781
+ const name = split(o.key).name;
782
+ const mime = a?.mime ?? mimeOf(name, o.mime);
783
+ return { key: o.key, name, size: o.size, mime, kind: a?.kind ?? kindOf(mime), updatedAt: o.lastModified, asset: a?.status === "ready" ? view(a) : null };
784
+ }),
785
+ cursor: r.cursor
786
+ };
787
+ }
788
+ async function register(actor, input) {
789
+ await ctx.ready();
790
+ const store = storeOf(input.store);
791
+ need(actor, store.name, "write");
792
+ const key = objectKey(input.key);
793
+ const existing = await repo.findAssetByKey(store.name, key);
794
+ if (existing?.status === "ready") return view(existing);
795
+ const head = existing || key.endsWith("/") ? null : await store.cfg.adapter.head(key);
796
+ if (!head) throw fail("asset_not_found", { id: key });
797
+ const { folder, name } = split(key);
798
+ const mime = mimeOf(name, head.mime);
799
+ const kind = kindOf(mime);
800
+ await scanned(actor, { store: store.name, key, name, mime, size: head.size }, store.cfg.adapter);
801
+ const size = kind === "image" ? imageSize(await store.cfg.adapter.readStart(key, 256 * 1024).catch(() => null) ?? new Uint8Array()) : null;
802
+ const who = ctx.actorRef(actor);
803
+ const now = ctx.nowIso();
804
+ const row = await repo.insertAsset({ id: newAssetId(), store: store.name, key, folder, name, kind, mime, size: head.size, width: size?.width ?? null, height: size?.height ?? null, duration: null, alt: (input.alt ?? "").trim().slice(0, 500), tags: cleanTags(input.tags), thumbKey: null, status: "ready", uploadId: null, createdBy: who.label, createdByKind: who.kind, createdByAgent: who.agent, createdAt: now, updatedAt: now });
805
+ ctx.audit(actor, "asset.register", { detail: { id: row.id, store: row.store, key } });
806
+ return view(row);
807
+ }
808
+ const MANY = 1e3;
809
+ async function expand(store, input, max = MANY) {
810
+ const out = new Set((input.keys ?? []).map(objectKey));
811
+ for (const f of input.folders ?? []) {
812
+ let cursor = null;
813
+ do {
814
+ const r = await store.cfg.adapter.list({ prefix: `${folderPath(f)}/`, cursor, limit: 1e3 });
815
+ for (const o of r.objects) out.add(o.key);
816
+ cursor = r.cursor;
817
+ if (out.size > max) throw fail("too_many_files", { max });
818
+ } while (cursor);
819
+ }
820
+ if (out.size > max) throw fail("too_many_files", { max });
821
+ return [...out];
822
+ }
823
+ async function moveMany(actor, input) {
824
+ await ctx.ready();
825
+ const store = storeOf(input.store);
826
+ need(actor, store.name, "delete");
827
+ const to = folderPath(input.to, { top: true });
828
+ const plan = (input.keys ?? []).map(objectKey).map((k) => ({ from: k, dest: joinKey(to, split(k).name) }));
829
+ for (const f of input.folders ?? []) {
830
+ const folder = folderPath(f);
831
+ const base = joinKey(to, split(folder).name);
832
+ if (base === folder) continue;
833
+ if (base.startsWith(`${folder}/`)) throw fail("invalid_folder", { folder: to });
834
+ for (const k of await expand(store, { folders: [folder] })) plan.push({ from: k, dest: base + k.slice(folder.length) });
835
+ if (plan.length > MANY) throw fail("too_many_files", { max: MANY });
836
+ }
837
+ const adapter = store.cfg.adapter;
838
+ const failed = [];
839
+ let moved = 0;
840
+ for (const p of plan) {
841
+ if (p.from === p.dest) continue;
842
+ try {
843
+ const row = await repo.findAssetByKey(store.name, p.from);
844
+ const marker = p.from.endsWith("/");
845
+ const dest = marker ? p.dest : (await freeKey(store, split(p.dest).folder, split(p.dest).name, row?.id)).key;
846
+ await adapter.copy(p.from, dest);
847
+ if (row) await repo.updateAsset(row.id, { key: dest, ...split(dest), updatedAt: ctx.nowIso() });
848
+ await adapter.delete(p.from);
849
+ if (!marker) moved++;
850
+ } catch (e) {
851
+ failed.push({ key: p.from, message: e instanceof Error ? e.message : String(e) });
852
+ }
853
+ }
854
+ ctx.audit(actor, "asset.move", { outcome: failed.length ? "failed" : "ok", detail: { store: store.name, to, moved, failed: failed.length } });
855
+ return { moved, failed };
856
+ }
857
+ async function removeMany(actor, input) {
858
+ await ctx.ready();
859
+ const store = storeOf(input.store);
860
+ need(actor, store.name, "delete");
861
+ const keys = await expand(store, input);
862
+ const rows = await repo.findAssetsByKeys(store.name, keys);
863
+ const files = keys.filter((k) => !k.endsWith("/")).length;
864
+ let used = 0;
865
+ let hidden = 0;
866
+ const documents = /* @__PURE__ */ new Map();
867
+ for (const a of rows) {
868
+ const u = await usage(actor, a);
869
+ if (u.documents.length + u.hidden) used++;
870
+ hidden += u.hidden;
871
+ for (const d of u.documents) documents.set(`${d.collection}/${d.slug}`, d);
872
+ }
873
+ const found = { files, used, documents: [...documents.values()], hidden };
874
+ if (input.check) return { deleted: 0, ...found };
875
+ if (used && !input.confirm) throw fail("asset_in_use", { count: documents.size + hidden, documents: [...documents.keys()] }, { current: { documents: [...documents.values()], hidden, files, used } });
876
+ const byKey = new Map(rows.map((a) => [a.key, a]));
877
+ for (const k of keys) {
878
+ const a = byKey.get(k);
879
+ if (a) await discard(a);
880
+ else await store.cfg.adapter.delete(k);
881
+ }
882
+ ctx.audit(actor, "asset.delete", { detail: { store: store.name, files, usedBy: documents.size + hidden } });
883
+ return { deleted: files, ...found };
884
+ }
885
+ const SHARE_SECONDS = { "1h": 3600, "24h": 24 * 3600, "7d": 7 * 24 * 3600 };
886
+ async function share(actor, id, o = {}) {
887
+ await ctx.ready();
888
+ const a = await load(id);
889
+ need(actor, a.store, "delete");
890
+ const store = storeOf(a.store);
891
+ const period = o.ttl ?? "24h";
892
+ const seconds = SHARE_SECONDS[period];
893
+ if (!seconds) throw fail("invalid", { reason: "ttl must be 1h, 24h or 7d" });
894
+ const direct = store.cfg.visibility === "public" ? store.cfg.adapter.publicUrl(a.key) : null;
895
+ const url = direct ?? await store.cfg.adapter.presignGet(a.key, { expires: seconds, download: null });
896
+ ctx.audit(actor, "asset.share", { detail: { id: a.id, store: a.store, key: a.key, ttl: direct ? null : period } });
897
+ return { url, expiresAt: direct ? null : new Date(Date.parse(ctx.nowIso()) + seconds * 1e3).toISOString() };
898
+ }
899
+ async function openKey(actor, input) {
900
+ await ctx.ready();
901
+ const store = storeOf(input.store);
902
+ needBrowse(actor, store.name);
903
+ const key = objectKey(input.key);
904
+ const direct = store.cfg.visibility === "public" && !input.download ? store.cfg.adapter.publicUrl(key) : null;
905
+ return { url: direct ?? await store.cfg.adapter.presignGet(key, { expires: ttl, download: input.download ? split(key).name : null }), visibility: store.cfg.visibility };
906
+ }
907
+ async function sync(input = {}) {
908
+ await ctx.ready();
909
+ const store = storeOf(input.store);
910
+ const folder = folderPath(input.prefix, { top: true });
911
+ const system = { kind: "system", label: "storage sync" };
912
+ const seen = /* @__PURE__ */ new Set();
913
+ let registered = 0;
914
+ let cursor = null;
915
+ do {
916
+ const r = await store.cfg.adapter.list({ prefix: folder ? `${folder}/` : "", cursor, limit: 1e3 });
917
+ const objects = r.objects.filter((o) => !o.key.endsWith("/") && !reserved(o.key));
918
+ const have = new Set((await repo.findAssetsByKeys(store.name, objects.map((o) => o.key))).map((a) => a.key));
919
+ for (const o of objects) {
920
+ seen.add(o.key);
921
+ if (!have.has(o.key)) await register(system, { store: store.name, key: o.key }), registered++;
922
+ }
923
+ cursor = r.cursor;
924
+ } while (cursor);
925
+ const missing = [];
926
+ let before;
927
+ for (; ; ) {
928
+ const rows = await repo.listAssets({ store: store.name, under: folder || void 0, status: "ready", notKinds: ["folder"], before, limit: 500 });
929
+ for (const a of rows) if (!seen.has(a.key)) missing.push({ id: a.id, key: a.key });
930
+ if (rows.length < 500) break;
931
+ before = `${rows[rows.length - 1].createdAt}|${rows[rows.length - 1].id}`;
932
+ }
933
+ return { registered, known: seen.size - registered, missing };
934
+ }
935
+ function describe(actor) {
936
+ if (!media) return null;
937
+ const stores = names.filter((n) => canAsset(actor, n, "read")).map((n) => {
938
+ const cfg = media.stores[n];
939
+ return { name: n, label: cfg.label ?? n, visibility: cfg.visibility, ...rulesOf(cfg), can: { write: canAsset(actor, n, "write"), delete: canAsset(actor, n, "delete"), browse: canBrowse(actor, n) } };
940
+ });
941
+ return stores.length ? { stores, partSize: PART_SIZE } : null;
942
+ }
943
+ return {
944
+ enabled: !!media && names.length > 0,
945
+ stores: () => names.map((n) => ({ name: n, ...media.stores[n], ...rulesOf(media.stores[n]) })),
946
+ describe,
947
+ can: canAsset,
948
+ requestUpload,
949
+ partUrls,
950
+ uploadStatus,
951
+ completeUpload,
952
+ abortUpload,
953
+ setThumb,
954
+ put,
955
+ import: importFromUrl,
956
+ list,
957
+ folders,
958
+ createFolder,
959
+ deleteFolder,
960
+ get,
961
+ update,
962
+ move,
963
+ remove,
964
+ trashed,
965
+ untrash,
966
+ purge,
967
+ purgeOlder,
968
+ open,
969
+ cleanup,
970
+ browse,
971
+ register,
972
+ moveMany,
973
+ removeMany,
974
+ share,
975
+ openKey,
976
+ sync,
977
+ checkDoc,
978
+ assertDoc,
979
+ syncRefs,
980
+ idsIn,
981
+ assetsFor,
982
+ imageUrl
983
+ };
984
+ }
985
+
986
+ // src/patch.ts
987
+ function sectionRanges(body) {
988
+ const lines = body.replace(/\r/g, "").split("\n");
989
+ const out = [];
990
+ const used = /* @__PURE__ */ new Map();
991
+ let inFence = false;
992
+ let cur = { anchor: "", heading: "", start: 0, end: 0, hasHeading: false };
993
+ for (let i = 0; i < lines.length; i++) {
994
+ const line = lines[i];
995
+ if (/^```/.test(line)) inFence = !inFence;
996
+ const h = !inFence ? /^#{1,2}\s+(.+?)\s*#*\s*$/.exec(line) : null;
997
+ if (h) {
998
+ cur.end = i;
999
+ out.push(cur);
1000
+ const text = inlineText(parseInline(h[1]));
1001
+ const base = anchorOf(text);
1002
+ const n = used.get(base) ?? 0;
1003
+ used.set(base, n + 1);
1004
+ cur = { anchor: n ? `${base}-${n}` : base, heading: text, start: i, end: i + 1, hasHeading: true };
1005
+ continue;
1006
+ }
1007
+ const h3 = !inFence ? /^###\s+(.+?)\s*#*\s*$/.exec(line) : null;
1008
+ if (h3) {
1009
+ const base = anchorOf(inlineText(parseInline(h3[1])));
1010
+ used.set(base, (used.get(base) ?? 0) + 1);
1011
+ }
1012
+ }
1013
+ cur.end = lines.length;
1014
+ out.push(cur);
1015
+ return out.filter((s) => s.hasHeading || lines.slice(s.start, s.end).some((l) => l.trim()));
1016
+ }
1017
+ var trimBlank = (lines) => {
1018
+ let s = 0;
1019
+ let e = lines.length;
1020
+ while (s < e && !lines[s].trim()) s++;
1021
+ while (e > s && !lines[e - 1].trim()) e--;
1022
+ return lines.slice(s, e);
1023
+ };
1024
+ function applyPatch(body, ops) {
1025
+ let text = body.replace(/\r/g, "");
1026
+ for (const op of ops) {
1027
+ const lines = text.split("\n");
1028
+ if (op.op === "append") {
1029
+ const kept = trimBlank(lines);
1030
+ text = [...kept, ...kept.length ? [""] : [], ...trimBlank(op.markdown.replace(/\r/g, "").split("\n"))].join("\n");
1031
+ continue;
1032
+ }
1033
+ const ranges = sectionRanges(text);
1034
+ const s = ranges.find((r) => r.anchor === op.anchor);
1035
+ if (!s) throw new CmsError("invalid_anchor", { anchor: op.anchor, valid: ranges.map((r) => r.anchor || '""') });
1036
+ const before = lines.slice(0, s.start);
1037
+ const after = lines.slice(s.end);
1038
+ const block = trimBlank((("markdown" in op ? op.markdown : "") ?? "").replace(/\r/g, "").split("\n"));
1039
+ let mid;
1040
+ if (op.op === "delete") mid = [];
1041
+ else if (op.op === "replace") {
1042
+ const heading = s.hasHeading ? [op.heading ? lines[s.start].replace(/^(#{1,2}\s+).*$/, `$1${op.heading}`) : lines[s.start]] : [];
1043
+ mid = [...heading, ...heading.length ? [""] : [], ...block, ""];
1044
+ } else {
1045
+ const section = lines.slice(s.start, s.end);
1046
+ mid = op.op === "insert_after" ? [...trimBlank(section), "", ...block, ""] : [...block, "", ...section];
1047
+ }
1048
+ text = [before, mid, after].map(trimBlank).filter((p) => p.length).map((p) => p.join("\n")).join("\n\n");
1049
+ }
1050
+ return text;
1051
+ }
1052
+
1053
+ // src/keys.ts
1054
+ import { createHash, randomBytes } from "crypto";
1055
+ var ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1056
+ var KEY_PREFIX = "sgk_";
1057
+ var KEY_CHARS = 40;
1058
+ var UNBIASED_LIMIT = 256 - 256 % ALPHABET.length;
1059
+ function generateKey(random = randomBytes) {
1060
+ let s = "";
1061
+ while (s.length < KEY_CHARS) {
1062
+ for (const b of random(KEY_CHARS)) {
1063
+ if (b >= UNBIASED_LIMIT) continue;
1064
+ s += ALPHABET[b % ALPHABET.length];
1065
+ if (s.length === KEY_CHARS) break;
1066
+ }
1067
+ }
1068
+ return KEY_PREFIX + s;
1069
+ }
1070
+ function hashKey(raw) {
1071
+ return createHash("sha256").update(raw.trim()).digest("hex");
1072
+ }
1073
+ function displayPrefix(raw) {
1074
+ return `${KEY_PREFIX}\u2026${raw.slice(-4)}`;
1075
+ }
1076
+ function looksLikeKey(raw) {
1077
+ return !!raw && raw.startsWith(KEY_PREFIX) && raw.length >= KEY_PREFIX.length + 20;
1078
+ }
1079
+ function keyFromHeader(header) {
1080
+ if (!header) return null;
1081
+ const m = /^(?:Bearer|[A-Za-z-]+\s+API-Key)\s+(\S+)$/i.exec(header.trim());
1082
+ const raw = m?.[1] ?? null;
1083
+ return looksLikeKey(raw) ? raw : null;
1084
+ }
1085
+
1086
+ // src/search.ts
1087
+ var HANGUL = /[\uac00-\ud7a3]/;
1088
+ var STOP = /* @__PURE__ */ new Set([
1089
+ "\uC5B4\uB5BB\uAC8C",
1090
+ "\uC5B4\uB5A1\uD574",
1091
+ "\uC5B4\uB5BB\uAC8C\uD574",
1092
+ "\uC5B4\uB5BB\uAC8C\uD574\uC694",
1093
+ "\uBC29\uBC95",
1094
+ "\uD558\uB294\uBC95",
1095
+ "\uD558\uB294",
1096
+ "\uD574",
1097
+ "\uD574\uC918",
1098
+ "\uD574\uC694",
1099
+ "\uD558\uB098\uC694",
1100
+ "\uB418\uB098\uC694",
1101
+ "\uC5B4\uB514",
1102
+ "\uC5B4\uB514\uC11C",
1103
+ "\uC5B4\uB514\uC5D0",
1104
+ "\uBB50\uC57C",
1105
+ "\uBB50",
1106
+ "\uC880",
1107
+ "\uBC95",
1108
+ "\uBC29\uBC95\uC740",
1109
+ "\uBC95\uC740",
1110
+ "\uBCF4\uB294",
1111
+ "\uBD10",
1112
+ "\uD558\uACE0",
1113
+ "\uC2F6\uC5B4\uC694",
1114
+ "\uC54C\uB824\uC918",
1115
+ "\uC54C\uB824",
1116
+ "\uC54C\uB824\uC8FC\uC138\uC694",
1117
+ "\uC4F0\uB294",
1118
+ "\uC368",
1119
+ "\uC4F0\uB098\uC694",
1120
+ "\uC0AC\uC6A9\uBC95",
1121
+ "\uD558\uAE30",
1122
+ "\uC218",
1123
+ "\uC788\uC5B4",
1124
+ "\uC788\uB098\uC694",
1125
+ "\uC788\uC5B4\uC694",
1126
+ "\uB3FC",
1127
+ "\uB418",
1128
+ "\uB098",
1129
+ "\uB0B4",
1130
+ "\uC81C",
1131
+ "\uC800",
1132
+ "\uAC70",
1133
+ "\uAC83",
1134
+ "\uC774\uAC70",
1135
+ "\uADF8\uAC70",
1136
+ "\uC11C\uBE44\uC11C",
1137
+ "\uC11C\uBE44\uC11C\uC5D0\uC11C",
1138
+ "\uC11C\uBE44\uC11C\uC5D0",
1139
+ "\uD558\uBA74",
1140
+ "\uD558\uB824\uBA74",
1141
+ "\uC2F6\uC5B4",
1142
+ "\uC2F6\uC740\uB370",
1143
+ "\uADF8\uB9AC\uACE0",
1144
+ "the",
1145
+ "a",
1146
+ "an",
1147
+ "how",
1148
+ "to",
1149
+ "do",
1150
+ "i",
1151
+ "is",
1152
+ "can",
1153
+ "what",
1154
+ "where",
1155
+ "in",
1156
+ "on",
1157
+ "of",
1158
+ "and",
1159
+ "or",
1160
+ "my",
1161
+ "use"
1162
+ ]);
1163
+ var PARTICLES = ["\uC5D0\uC11C\uB294", "\uC73C\uB85C\uB294", "\uC5D0\uAC8C\uC11C", "\uD55C\uD14C\uC11C", "\uC774\uB791", "\uC5D0\uC11C", "\uC73C\uB85C", "\uC5D0\uAC8C", "\uD55C\uD14C", "\uD558\uACE0", "\uAE4C\uC9C0", "\uBD80\uD130", "\uCC98\uB7FC", "\uC740", "\uB294", "\uC774", "\uAC00", "\uC744", "\uB97C", "\uC5D0", "\uB85C", "\uC640", "\uACFC", "\uB3C4", "\uB9CC", "\uC758", "\uAED8", "\uB791"];
1164
+ function normalizeQuery(q) {
1165
+ return words(q).filter((w) => !STOP.has(w)).map(stemOf).map((w) => w.length === 2 && /[은는을를이가]$/.test(w) ? w[0] : w).filter((w, i, all) => all.indexOf(w) === i).sort().join(" ");
1166
+ }
1167
+ function words(text) {
1168
+ return text.toLowerCase().normalize("NFC").split(/[^0-9a-z\uac00-\ud7a3]+/i).filter(Boolean);
1169
+ }
1170
+ var VERB_ENDINGS = [
1171
+ "\uD558\uB824\uBA74",
1172
+ "\uD558\uB294\uBC95",
1173
+ "\uD560\uC218\uC788",
1174
+ "\uD558\uB098\uC694",
1175
+ "\uD588\uB294\uB370",
1176
+ "\uD558\uB294\uB370",
1177
+ "\uD574\uC8FC\uC138\uC694",
1178
+ "\uD574\uC918\uC694",
1179
+ "\uD569\uB2C8\uB2E4",
1180
+ "\uD574\uC57C",
1181
+ "\uD574\uC918",
1182
+ "\uD574\uC694",
1183
+ "\uD574\uC11C",
1184
+ "\uD558\uAE30",
1185
+ "\uD558\uB294",
1186
+ "\uD558\uBA74",
1187
+ "\uD558\uACE0",
1188
+ "\uD588\uC5B4",
1189
+ "\uD560\uB798",
1190
+ "\uD560\uAC8C",
1191
+ "\uB418\uB098\uC694",
1192
+ "\uB418\uC694",
1193
+ "\uB3FC\uC694",
1194
+ "\uB41C",
1195
+ "\uB418\uB294",
1196
+ "\uB418\uBA74",
1197
+ "\uD574",
1198
+ "\uD558",
1199
+ "\uD560",
1200
+ "\uD568",
1201
+ "\uB428"
1202
+ ];
1203
+ function stripParticle(w) {
1204
+ if (!HANGUL.test(w) || w.length < 3) return w;
1205
+ for (const p of PARTICLES) if (w.length - p.length >= 2 && w.endsWith(p)) return w.slice(0, -p.length);
1206
+ return w;
1207
+ }
1208
+ function stemOf(w) {
1209
+ const s = stripParticle(w);
1210
+ if (!HANGUL.test(s) || s.length < 3) return s;
1211
+ for (const e of VERB_ENDINGS) if (s.length - e.length >= 2 && s.endsWith(e)) return s.slice(0, -e.length);
1212
+ return s;
1213
+ }
1214
+ function tokensOf(w) {
1215
+ const out = [{ tok: w, weight: 1 }];
1216
+ const stem = stemOf(w);
1217
+ if (stem !== w) out.push({ tok: stem, weight: 1 });
1218
+ if (HANGUL.test(w) && w.length >= 3) {
1219
+ for (let i = 0; i + 2 <= w.length; i++) out.push({ tok: w.slice(i, i + 2), weight: 0.6 });
1220
+ }
1221
+ return out;
1222
+ }
1223
+ var FIELD_WEIGHT = { keywords: 3, title: 2, heading: 1.5, summary: 1.5, body: 1 };
1224
+ var SearchIndex = class {
1225
+ units = [];
1226
+ /** token → unit index → best field weight × token weight */
1227
+ postings = /* @__PURE__ */ new Map();
1228
+ latinVocab = [];
1229
+ constructor(units = []) {
1230
+ for (const u of units) this.add(u);
1231
+ this.latinVocab = [...this.postings.keys()].filter((t) => !HANGUL.test(t) && t.length >= 3);
1232
+ }
1233
+ get size() {
1234
+ return this.units.length;
1235
+ }
1236
+ add(u) {
1237
+ const idx = this.units.push(u) - 1;
1238
+ const put = (text, field) => {
1239
+ for (const w of words(text)) {
1240
+ for (const { tok, weight } of tokensOf(w)) {
1241
+ let m = this.postings.get(tok);
1242
+ if (!m) this.postings.set(tok, m = /* @__PURE__ */ new Map());
1243
+ const v = FIELD_WEIGHT[field] * weight;
1244
+ if ((m.get(idx) ?? 0) < v) m.set(idx, v);
1245
+ }
1246
+ }
1247
+ };
1248
+ put(u.keywords.join(" "), "keywords");
1249
+ put(u.title, "title");
1250
+ put(u.heading, "heading");
1251
+ put(u.summary, "summary");
1252
+ put(plainText(u.markdown), "body");
1253
+ }
1254
+ idf(tok) {
1255
+ const df = this.postings.get(tok)?.size ?? 0;
1256
+ return Math.log(1 + (this.units.length + 1) / (df + 0.5));
1257
+ }
1258
+ search(query, opts = {}) {
1259
+ const limit = opts.limit ?? 5;
1260
+ const perDoc = opts.perDoc ?? 2;
1261
+ const qWords = [...new Set(words(query).filter((w) => !STOP.has(w)))];
1262
+ if (!qWords.length || !this.units.length) return [];
1263
+ const scores = /* @__PURE__ */ new Map();
1264
+ const matchedWords = /* @__PURE__ */ new Map();
1265
+ qWords.forEach((w, wi) => {
1266
+ const best = /* @__PURE__ */ new Map();
1267
+ const consider = (tok, weight) => {
1268
+ const m = this.postings.get(tok);
1269
+ if (!m) return;
1270
+ const idf = this.idf(tok);
1271
+ for (const [u, fw] of m) {
1272
+ const s = fw * weight * idf;
1273
+ if ((best.get(u) ?? 0) < s) best.set(u, s);
1274
+ }
1275
+ };
1276
+ for (const { tok, weight } of tokensOf(w)) consider(tok, weight);
1277
+ if (!HANGUL.test(w) && w.length >= 3) {
1278
+ for (const v of this.latinVocab) {
1279
+ if (v !== w && (v.startsWith(w) || w.length >= 5 && editDistance1(v, w))) consider(v, 0.5);
1280
+ }
1281
+ }
1282
+ for (const [u, s] of best) {
1283
+ scores.set(u, (scores.get(u) ?? 0) + s);
1284
+ let set = matchedWords.get(u);
1285
+ if (!set) matchedWords.set(u, set = /* @__PURE__ */ new Set());
1286
+ set.add(wi);
1287
+ }
1288
+ });
1289
+ const docBoost = /* @__PURE__ */ new Map();
1290
+ for (const [u, s] of scores) {
1291
+ const id = this.units[u].docId;
1292
+ docBoost.set(id, Math.max(docBoost.get(id) ?? 0, s));
1293
+ }
1294
+ const docWords = /* @__PURE__ */ new Map();
1295
+ for (const [u, set] of matchedWords) {
1296
+ const id = this.units[u].docId;
1297
+ let all = docWords.get(id);
1298
+ if (!all) docWords.set(id, all = /* @__PURE__ */ new Set());
1299
+ set.forEach((x) => all.add(x));
1300
+ }
1301
+ const ranked = [];
1302
+ for (const [u, s] of scores) {
1303
+ const unit = this.units[u];
1304
+ if (opts.filter && !opts.filter(unit)) continue;
1305
+ const boosted = s + 0.25 * (docBoost.get(unit.docId) ?? 0);
1306
+ ranked.push({ unit, score: boosted, coverage: (docWords.get(unit.docId)?.size ?? 0) / qWords.length });
1307
+ }
1308
+ ranked.sort((a, b) => b.score - a.score);
1309
+ const perDocCount = /* @__PURE__ */ new Map();
1310
+ const out = [];
1311
+ for (const hit of ranked) {
1312
+ const n = perDocCount.get(hit.unit.docId) ?? 0;
1313
+ if (n >= perDoc) continue;
1314
+ perDocCount.set(hit.unit.docId, n + 1);
1315
+ out.push(hit);
1316
+ if (out.length >= limit) break;
1317
+ }
1318
+ return out;
1319
+ }
1320
+ };
1321
+ function editDistance1(a, b) {
1322
+ if (Math.abs(a.length - b.length) > 1) return false;
1323
+ let i = 0;
1324
+ let j = 0;
1325
+ let edits = 0;
1326
+ while (i < a.length && j < b.length) {
1327
+ if (a[i] === b[j]) {
1328
+ i++;
1329
+ j++;
1330
+ continue;
1331
+ }
1332
+ if (++edits > 1) return false;
1333
+ if (a.length > b.length) i++;
1334
+ else if (a.length < b.length) j++;
1335
+ else {
1336
+ i++;
1337
+ j++;
1338
+ }
1339
+ }
1340
+ return edits + (a.length - i) + (b.length - j) <= 1;
1341
+ }
1342
+ function unitsOf(doc) {
1343
+ const sections = splitSections(doc.body);
1344
+ const base = {
1345
+ docId: doc.id,
1346
+ collection: doc.collection,
1347
+ slug: doc.slug,
1348
+ title: doc.title,
1349
+ summary: doc.summary,
1350
+ category: doc.category,
1351
+ keywords: doc.keywords,
1352
+ publishedAt: doc.publishedAt,
1353
+ fields: doc.fields
1354
+ };
1355
+ if (!sections.length) return [{ ...base, anchor: "", heading: "", markdown: "" }];
1356
+ return sections.map((s) => ({ ...base, anchor: s.anchor, heading: s.heading, markdown: s.markdown }));
1357
+ }
1358
+
1359
+ // src/flow.ts
1360
+ var PRESENCE_MS = 45e3;
1361
+ var COMMENT_MAX = 4e3;
1362
+ var QUOTE_MAX = 500;
1363
+ var NAME_MAX = 80;
1364
+ var FILTER_KEYS = ["q", "state", "category", "by"];
1365
+ var DAY = 864e5;
1366
+ function createFlow(ctx) {
1367
+ const { repo, fail, audit, actorRef, can, assert, nowIso } = ctx;
1368
+ const scheduler = { kind: "system", label: "scheduler", via: "app" };
1369
+ const errorsOf = (d) => d.filter((x) => x.severity === "error");
1370
+ const known = (col) => ctx.collections().some((c) => c.slug === col);
1371
+ function future(v, field) {
1372
+ if (v === null || v === void 0 || v === "") return null;
1373
+ const t = Date.parse(String(v));
1374
+ if (!Number.isFinite(t) || t <= ctx.now().getTime()) throw fail("schedule_invalid", { field });
1375
+ return new Date(t).toISOString();
1376
+ }
1377
+ async function schedule(actor, col, slug, o) {
1378
+ await ctx.ready();
1379
+ ctx.collection(col);
1380
+ const publishAt = future(o.publishAt, "publishAt");
1381
+ const unpublishAt = future(o.unpublishAt, "unpublishAt");
1382
+ if (!publishAt && !unpublishAt) throw fail("schedule_invalid", { field: "publishAt" });
1383
+ if (publishAt && unpublishAt && unpublishAt <= publishAt) throw fail("schedule_invalid", { field: "unpublishAt" });
1384
+ const who = actorRef(actor);
1385
+ const doc = await repo.tx(async (r) => {
1386
+ const cur = await r.findDoc(col, slug);
1387
+ if (!cur) throw fail("not_found", { collection: col, slug });
1388
+ assert(actor, col, "publish", cur);
1389
+ if (o.expectedVersion !== void 0 && o.expectedVersion !== cur.version) throw ctx.conflict(cur, o.expectedVersion, actor, col);
1390
+ if (publishAt) {
1391
+ await ctx.assertReviewed(r, actor, cur, cur.version);
1392
+ const errors = errorsOf(await ctx.problems(cur, cur, r));
1393
+ if (errors.length) throw fail(errors[0].code, errors[0].params, { diagnostics: errors });
1394
+ } else if (cur.publishedVersion === null) throw fail("not_published");
1395
+ const s = { publishAt, unpublishAt, version: cur.version, by: who.label, byKind: who.kind, byId: who.id, byAgent: who.agent, at: nowIso() };
1396
+ return await r.updateDoc(cur.id, { schedule: s, dueAt: publishAt ?? unpublishAt, updatedAt: cur.updatedAt });
1397
+ });
1398
+ audit(actor, "doc.schedule", { collection: col, slug, version: doc.schedule.version, detail: { publishAt, unpublishAt } });
1399
+ return doc;
1400
+ }
1401
+ async function unschedule(actor, col, slug) {
1402
+ await ctx.ready();
1403
+ ctx.collection(col);
1404
+ const cur = await repo.findDoc(col, slug);
1405
+ if (!cur) throw fail("not_found", { collection: col, slug });
1406
+ assert(actor, col, "publish", cur);
1407
+ if (!cur.schedule) throw fail("not_scheduled");
1408
+ const doc = await repo.updateDoc(cur.id, { schedule: null, dueAt: null, updatedAt: cur.updatedAt });
1409
+ audit(actor, "doc.unschedule", { collection: col, slug, version: cur.schedule.version });
1410
+ return doc;
1411
+ }
1412
+ async function runScheduled(o = {}) {
1413
+ await ctx.ready();
1414
+ const at = (o.now ?? ctx.now()).toISOString();
1415
+ const out = { published: [], unpublished: [], failed: [], releases: [], purged: { documents: 0, assets: 0 } };
1416
+ for (const d of await repo.listDocs({ dueBefore: at })) {
1417
+ if (!known(d.collection) || !d.schedule) continue;
1418
+ let prev = null;
1419
+ let did = null;
1420
+ try {
1421
+ const doc = await repo.tx(async (r) => {
1422
+ const cur = prev = await r.findDocById(d.id);
1423
+ const s = cur?.schedule;
1424
+ if (!cur || !s || !cur.dueAt || cur.dueAt > at) return null;
1425
+ if (s.publishAt && s.publishAt <= at) {
1426
+ const snap = s.version === cur.version ? cur : (await r.getVersion(cur.id, s.version))?.snapshot;
1427
+ if (!snap) throw fail("version_not_found", { version: s.version });
1428
+ const errors = errorsOf(await ctx.problems(cur, { ...snap, slug: cur.slug }, r));
1429
+ if (errors.length) throw fail(errors[0].code, errors[0].params, { diagnostics: errors });
1430
+ did = "published";
1431
+ return ctx.publishIn(r, scheduler, cur, s.version);
1432
+ }
1433
+ did = "unpublished";
1434
+ return ctx.unpublishIn(r, scheduler, cur);
1435
+ });
1436
+ const what = did;
1437
+ if (!doc || !what) continue;
1438
+ audit(scheduler, what === "published" ? "doc.publish" : "doc.unpublish", { collection: d.collection, slug: d.slug, version: doc.publishedVersion ?? doc.version, detail: { scheduledBy: d.schedule.by, scheduledAt: d.schedule.at } });
1439
+ ctx.changed(prev, doc);
1440
+ out[what].push(`${d.collection}/${d.slug}`);
1441
+ } catch (e) {
1442
+ await repo.updateDoc(d.id, { schedule: null, dueAt: null, updatedAt: d.updatedAt }).catch((err) => ctx.report(err, "runScheduled"));
1443
+ const code = isCmsError(e) ? e.code : "internal";
1444
+ if (!isCmsError(e)) ctx.report(e, "runScheduled");
1445
+ audit(scheduler, "doc.schedule", { collection: d.collection, slug: d.slug, version: d.schedule.version, outcome: "failed", detail: { code, scheduledBy: d.schedule.by } });
1446
+ out.failed.push({ collection: d.collection, slug: d.slug, code, message: ctx.message(e) });
1447
+ }
1448
+ }
1449
+ for (const rel of await repo.listReleases()) {
1450
+ if (rel.state !== "scheduled" || !rel.publishAt || rel.publishAt > at) continue;
1451
+ try {
1452
+ await publishRelease(scheduler, rel.id);
1453
+ out.releases.push({ id: rel.id, name: rel.name, ok: true });
1454
+ } catch (e) {
1455
+ if (!isCmsError(e)) ctx.report(e, "runScheduled");
1456
+ const message = ctx.message(e);
1457
+ await repo.updateRelease(rel.id, { state: "open", publishAt: null, lastError: message }, "scheduled").catch((err) => ctx.report(err, "runScheduled"));
1458
+ audit(scheduler, "release.publish", { outcome: "failed", detail: { id: rel.id, name: rel.name, code: isCmsError(e) ? e.code : "internal" } });
1459
+ out.releases.push({ id: rel.id, name: rel.name, ok: false, message });
1460
+ }
1461
+ }
1462
+ if (ctx.trashDays > 0) {
1463
+ const cutoff = new Date(Date.parse(at) - ctx.trashDays * DAY).toISOString();
1464
+ for (const d of await repo.listDocs({ trashed: true })) {
1465
+ if (!d.deletedAt || d.deletedAt > cutoff) continue;
1466
+ await repo.deleteDoc(d.id);
1467
+ audit(scheduler, "doc.purge", { collection: d.collection, slug: d.slug, detail: { auto: true } });
1468
+ out.purged.documents++;
1469
+ }
1470
+ out.purged.assets = await ctx.assets.purgeOlder(cutoff);
1471
+ }
1472
+ await repo.prunePresence(new Date(Date.parse(at) - 36e5).toISOString()).catch((err) => ctx.report(err, "runScheduled"));
1473
+ return out;
1474
+ }
1475
+ const purgeAt = (deletedAt) => ctx.trashDays > 0 ? new Date(Date.parse(deletedAt) + ctx.trashDays * DAY).toISOString() : null;
1476
+ async function trashList(actor, o = {}) {
1477
+ await ctx.ready();
1478
+ if (actor.kind === "anonymous") throw fail("unauthorized");
1479
+ const items = [];
1480
+ if (o.kind !== "asset") {
1481
+ for (const d of await repo.listDocs({ trashed: true })) {
1482
+ if (!known(d.collection) || !can(actor, d.collection, "write", d)) continue;
1483
+ items.push({ kind: "document", id: d.id, title: d.title, where: `${ctx.collection(d.collection).label} / ${d.slug}`, collection: d.collection, slug: d.slug, state: docState(d).state, deletedAt: d.deletedAt, deletedBy: d.deletedBy, purgeAt: purgeAt(d.deletedAt), canRestore: can(actor, d.collection, "publish", d) });
1484
+ }
1485
+ }
1486
+ if (o.kind !== "document" && ctx.assets.enabled) {
1487
+ for (const a of await ctx.assets.trashed(actor)) {
1488
+ items.push({ kind: "asset", id: a.id, title: a.name, where: `${a.store} / ${a.key}`, collection: null, slug: null, state: a.kind, deletedAt: a.deletedAt, deletedBy: a.deletedBy, purgeAt: purgeAt(a.deletedAt), canRestore: ctx.assets.can(actor, a.store, "delete") });
1489
+ }
1490
+ }
1491
+ items.sort((a, b) => b.deletedAt.localeCompare(a.deletedAt));
1492
+ return { items, days: ctx.trashDays, canPurge: ctx.isAdmin(actor) };
1493
+ }
1494
+ const refs = (v) => Array.isArray(v) ? v.filter((x) => !!x && (x.kind === "document" || x.kind === "asset") && typeof x.id === "string").slice(0, 200) : [];
1495
+ async function trashRestore(actor, items) {
1496
+ await ctx.ready();
1497
+ let restored = 0;
1498
+ for (const it of refs(items)) {
1499
+ if (it.kind === "asset") {
1500
+ await ctx.assets.untrash(actor, it.id);
1501
+ } else {
1502
+ const d = await repo.findDocById(it.id, { trashed: true });
1503
+ if (!d?.deletedAt || !known(d.collection)) throw fail("trash_not_found", { id: it.id });
1504
+ assert(actor, d.collection, "publish", d);
1505
+ const doc = await repo.updateDoc(d.id, { deletedAt: null, deletedBy: null, updatedAt: nowIso() });
1506
+ audit(actor, "doc.undelete", { collection: d.collection, slug: d.slug, version: d.version });
1507
+ ctx.changed(null, doc);
1508
+ }
1509
+ restored++;
1510
+ }
1511
+ return { restored };
1512
+ }
1513
+ async function trashPurge(actor, items) {
1514
+ await ctx.ready();
1515
+ if (actor.kind === "anonymous") throw fail("unauthorized");
1516
+ if (!ctx.isAdmin(actor)) throw fail("forbidden_trash");
1517
+ const list = items === "all" ? (await trashList(actor)).items : refs(items);
1518
+ let purged = 0;
1519
+ for (const it of list) {
1520
+ if (it.kind === "asset") {
1521
+ if (!await ctx.assets.purge(actor, it.id)) continue;
1522
+ } else {
1523
+ const d = await repo.findDocById(it.id, { trashed: true });
1524
+ if (!d?.deletedAt) continue;
1525
+ await repo.deleteDoc(d.id);
1526
+ audit(actor, "doc.purge", { collection: d.collection, slug: d.slug, version: d.version });
1527
+ }
1528
+ purged++;
1529
+ }
1530
+ return { purged };
1531
+ }
1532
+ const text = (v, max) => typeof v === "string" && v.trim() ? v.trim().slice(0, max) : null;
1533
+ async function requestReview(actor, col, slug, o = {}) {
1534
+ const cur = await ctx.editable(actor, col, slug);
1535
+ const who = actorRef(actor);
1536
+ const review = { state: "requested", version: cur.version, by: who.label, byKind: who.kind, byId: who.id, byAgent: who.agent, at: nowIso(), note: text(o.note, 2e3) };
1537
+ const doc = await repo.updateDoc(cur.id, { review, updatedAt: cur.updatedAt });
1538
+ audit(actor, "review.request", { collection: col, slug, version: cur.version });
1539
+ return doc;
1540
+ }
1541
+ function answerable(actor, col, cur) {
1542
+ assert(actor, col, "publish", cur);
1543
+ if (actor.kind !== "user" || actor.agent) throw fail("review_people_only");
1544
+ const rv = cur.review;
1545
+ if (!rv || rv.state !== "requested") throw fail("review_not_requested");
1546
+ if (ctx.collection(col).review?.everyone === "required" && rv.byKind === "user" && !rv.byAgent && rv.byId === actor.id) throw fail("review_self");
1547
+ return rv;
1548
+ }
1549
+ async function approveReview(actor, col, slug, o = {}) {
1550
+ await ctx.ready();
1551
+ ctx.collection(col);
1552
+ let prev = null;
1553
+ let version = 0;
1554
+ const doc = await repo.tx(async (r) => {
1555
+ const cur = prev = await r.findDoc(col, slug);
1556
+ if (!cur) throw fail("not_found", { collection: col, slug });
1557
+ const rv = answerable(actor, col, cur);
1558
+ version = rv.version;
1559
+ await r.updateVersion(cur.id, rv.version, { approvedBy: actorRef(actor).label, approvedAt: nowIso() });
1560
+ if (o.publish === false) return await r.updateDoc(cur.id, { review: null, updatedAt: cur.updatedAt });
1561
+ return ctx.publishIn(r, actor, cur, rv.version);
1562
+ });
1563
+ audit(actor, "review.approve", { collection: col, slug, version, detail: { requestedBy: prev?.review?.by ?? null, published: o.publish !== false } });
1564
+ if (o.publish !== false) audit(actor, "doc.publish", { collection: col, slug, version });
1565
+ ctx.changed(prev, doc);
1566
+ return doc;
1567
+ }
1568
+ async function rejectReview(actor, col, slug, o = {}) {
1569
+ await ctx.ready();
1570
+ ctx.collection(col);
1571
+ const cur = await repo.findDoc(col, slug);
1572
+ if (!cur) throw fail("not_found", { collection: col, slug });
1573
+ const rv = answerable(actor, col, cur);
1574
+ const review = { ...rv, state: "changes_requested", note: text(o.note, 2e3), answeredBy: actorRef(actor).label, answeredAt: nowIso() };
1575
+ const doc = await repo.updateDoc(cur.id, { review, updatedAt: cur.updatedAt });
1576
+ audit(actor, "review.reject", { collection: col, slug, version: rv.version, detail: { requestedBy: rv.by } });
1577
+ return doc;
1578
+ }
1579
+ async function reviewRequests(actor, o = {}) {
1580
+ await ctx.ready();
1581
+ if (actor.kind === "anonymous") throw fail("unauthorized");
1582
+ if (o.collection) assert(actor, o.collection, "write");
1583
+ const cols = (o.collection ? [ctx.collection(o.collection)] : ctx.collections()).filter((c) => can(actor, c.slug, "write"));
1584
+ const out = [];
1585
+ for (const c of cols) for (const d of await repo.listDocs({ collection: c.slug })) if (d.review?.state === "requested") out.push(ctx.summaryOf(d));
1586
+ return out.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
1587
+ }
1588
+ function place(body, c) {
1589
+ const lines = body.replace(/\r/g, "").split("\n");
1590
+ const sec = sectionRanges(body).find((s) => s.anchor === c.anchor);
1591
+ const quote = c.quote.trim();
1592
+ if (quote) {
1593
+ const first = quote.split("\n")[0];
1594
+ const from = sec?.start ?? 0;
1595
+ const to = sec?.end ?? lines.length;
1596
+ for (let i = from; i < to; i++) if (lines[i].includes(first)) return { located: "quote", line: i + 1 };
1597
+ if (!sec) {
1598
+ for (let i = 0; i < lines.length; i++) if (lines[i].includes(first)) return { located: "quote", line: i + 1 };
1599
+ }
1600
+ }
1601
+ if (sec) return { located: "section", line: sec.start + 1 };
1602
+ return c.anchor === "" && !quote ? { located: "section", line: 1 } : { located: "lost", line: null };
1603
+ }
1604
+ async function threads(doc) {
1605
+ const rows = await repo.listComments(doc.id);
1606
+ return rows.filter((c) => !c.threadId).map((c) => ({ ...c, ...place(doc.body, c), replies: rows.filter((r) => r.threadId === c.id) }));
1607
+ }
1608
+ async function insertComment(doc, author, input) {
1609
+ const body = String(input.body ?? "").trim();
1610
+ if (!body || body.length > COMMENT_MAX) throw fail("comment_invalid", { max: COMMENT_MAX });
1611
+ let anchor = String(input.anchor ?? "");
1612
+ let quote = String(input.quote ?? "").slice(0, QUOTE_MAX);
1613
+ let threadId = null;
1614
+ if (input.threadId) {
1615
+ const root = await repo.findComment(String(input.threadId));
1616
+ if (!root || root.documentId !== doc.id) throw fail("comment_not_found");
1617
+ threadId = root.threadId ?? root.id;
1618
+ anchor = root.anchor;
1619
+ quote = "";
1620
+ }
1621
+ return repo.insertComment({ documentId: doc.id, threadId, anchor, quote, body, ...author, createdAt: nowIso() });
1622
+ }
1623
+ const authorOf = (actor) => {
1624
+ const who = actorRef(actor);
1625
+ return { authorKind: who.kind, authorId: who.id, authorLabel: who.label, authorAgent: who.agent };
1626
+ };
1627
+ async function comments(actor, col, slug) {
1628
+ return threads(await ctx.editable(actor, col, slug));
1629
+ }
1630
+ async function addComment(actor, col, slug, input) {
1631
+ return insertComment(await ctx.editable(actor, col, slug), authorOf(actor), input);
1632
+ }
1633
+ async function resolveComment(actor, col, slug, id, o = {}) {
1634
+ const doc = await ctx.editable(actor, col, slug);
1635
+ const c = await repo.findComment(String(id));
1636
+ if (!c || c.documentId !== doc.id) throw fail("comment_not_found");
1637
+ const done = o.resolved !== false;
1638
+ return await repo.updateComment(c.threadId ?? c.id, { resolvedAt: done ? nowIso() : null, resolvedBy: done ? actorRef(actor).label : null });
1639
+ }
1640
+ async function previewDoc(token) {
1641
+ await ctx.ready();
1642
+ const p = ctx.previewPayload(token);
1643
+ if (!p.cm) throw fail("comments_off");
1644
+ ctx.collection(p.c);
1645
+ const doc = await repo.findDoc(p.c, p.s);
1646
+ if (!doc) throw fail("not_found", { collection: p.c, slug: p.s });
1647
+ return doc;
1648
+ }
1649
+ async function previewComments(token) {
1650
+ return threads(await previewDoc(token));
1651
+ }
1652
+ async function addPreviewComment(token, input) {
1653
+ const doc = await previewDoc(token);
1654
+ return insertComment(doc, { authorKind: "guest", authorId: null, authorLabel: text(input.name, 60) ?? "Guest", authorAgent: null }, input);
1655
+ }
1656
+ async function labelVersion(actor, col, slug, n, o) {
1657
+ const doc = await ctx.editable(actor, col, slug);
1658
+ if (!await repo.getVersion(doc.id, n)) throw fail("version_not_found", { version: n });
1659
+ await repo.updateVersion(doc.id, n, { label: o.label === void 0 ? void 0 : text(o.label, 60), pinned: o.pinned === void 0 ? void 0 : !!o.pinned });
1660
+ return { ...await repo.getVersion(doc.id, n), published: n === doc.publishedVersion };
1661
+ }
1662
+ function needEditor(actor) {
1663
+ if (actor.kind === "anonymous") throw fail("unauthorized");
1664
+ if (!ctx.collections().some((c) => can(actor, c.slug, "write"))) throw fail("forbidden");
1665
+ }
1666
+ async function loadRelease(id, open = false) {
1667
+ await ctx.ready();
1668
+ const rel = await repo.findRelease(String(id));
1669
+ if (!rel) throw fail("release_not_found");
1670
+ if (open && rel.state === "published") throw fail("release_closed");
1671
+ return rel;
1672
+ }
1673
+ async function viewRelease(actor, rel) {
1674
+ const items = [];
1675
+ for (const it of rel.items) {
1676
+ const doc = known(it.collection) ? await repo.findDocById(it.documentId) : null;
1677
+ items.push({ ...it, slug: doc?.slug ?? it.slug, title: doc?.title ?? it.title, currentVersion: doc?.version ?? null, stale: !!doc && doc.version !== it.version, state: doc ? docState(doc).state : null, canPublish: !!doc && can(actor, it.collection, "publish", doc) });
1678
+ }
1679
+ return { ...rel, items, canPublish: rel.state !== "published" && items.length > 0 && items.every((i) => i.canPublish) };
1680
+ }
1681
+ async function releases(actor) {
1682
+ await ctx.ready();
1683
+ needEditor(actor);
1684
+ return repo.listReleases();
1685
+ }
1686
+ async function release(actor, id) {
1687
+ needEditor(actor);
1688
+ return viewRelease(actor, await loadRelease(id));
1689
+ }
1690
+ const nameOf = (v) => {
1691
+ const name = text(v, NAME_MAX + 1);
1692
+ if (!name || name.length > NAME_MAX) throw fail("name_invalid", { max: NAME_MAX });
1693
+ return name;
1694
+ };
1695
+ async function createRelease(actor, input) {
1696
+ await ctx.ready();
1697
+ needEditor(actor);
1698
+ const who = actorRef(actor);
1699
+ return viewRelease(actor, await repo.insertRelease({ name: nameOf(input.name), createdBy: who.label, createdById: who.id, createdAt: nowIso() }));
1700
+ }
1701
+ async function renameRelease(actor, id, input) {
1702
+ needEditor(actor);
1703
+ const rel = await loadRelease(id, true);
1704
+ return viewRelease(actor, await repo.updateRelease(rel.id, { name: nameOf(input.name), updatedAt: nowIso() }));
1705
+ }
1706
+ async function removeRelease(actor, id) {
1707
+ needEditor(actor);
1708
+ const rel = await loadRelease(id, true);
1709
+ await repo.deleteRelease(rel.id);
1710
+ }
1711
+ async function addToRelease(actor, id, input) {
1712
+ needEditor(actor);
1713
+ const rel = await loadRelease(id, true);
1714
+ const items = [...rel.items];
1715
+ const others = (await repo.listReleases()).filter((r) => r.id !== rel.id && r.state !== "published");
1716
+ for (const it of input.slice(0, 200)) {
1717
+ const doc = await ctx.editable(actor, it.collection, it.slug);
1718
+ const action = it.action === "unpublish" ? "unpublish" : "publish";
1719
+ if (action === "unpublish" && doc.publishedVersion === null) throw fail("not_published");
1720
+ const other = others.find((r) => r.items.some((x) => x.documentId === doc.id));
1721
+ if (other) throw fail("in_other_release", { release: other.name, slug: doc.slug });
1722
+ const item = { documentId: doc.id, collection: doc.collection, slug: doc.slug, title: doc.title, action, version: doc.version };
1723
+ const at = items.findIndex((x) => x.documentId === doc.id);
1724
+ if (at >= 0) items[at] = item;
1725
+ else items.push(item);
1726
+ }
1727
+ return viewRelease(actor, await repo.updateRelease(rel.id, { items, lastError: null, updatedAt: nowIso() }));
1728
+ }
1729
+ async function removeFromRelease(actor, id, documentId) {
1730
+ needEditor(actor);
1731
+ const rel = await loadRelease(id, true);
1732
+ return viewRelease(actor, await repo.updateRelease(rel.id, { items: rel.items.filter((x) => x.documentId !== documentId), updatedAt: nowIso() }));
1733
+ }
1734
+ async function publishRelease(actor, id) {
1735
+ await ctx.ready();
1736
+ if (actor.kind === "anonymous") throw fail("unauthorized");
1737
+ const done = [];
1738
+ const rel = await repo.tx(async (r) => {
1739
+ const cur = await r.findRelease(String(id));
1740
+ if (!cur) throw fail("release_not_found");
1741
+ if (cur.state === "published") throw fail("release_closed");
1742
+ if (!cur.items.length) throw fail("release_empty");
1743
+ const blocked = [];
1744
+ const ok = [];
1745
+ for (const item of cur.items) {
1746
+ const block = (code, params = {}, message) => blocked.push({ collection: item.collection, slug: item.slug, title: item.title, code, message: message ?? ctx.message(fail(code, params)) });
1747
+ const doc = known(item.collection) ? await r.findDocById(item.documentId) : null;
1748
+ if (!doc) block("not_found", { collection: item.collection, slug: item.slug });
1749
+ else if (!can(actor, doc.collection, "publish", doc)) block("forbidden_publish", { collection: doc.collection });
1750
+ else if (item.action === "unpublish") ok.push({ item, doc });
1751
+ else {
1752
+ const v = await r.getVersion(doc.id, item.version);
1753
+ const errors = v ? errorsOf(await ctx.problems(doc, { ...v.snapshot, slug: doc.slug }, r)) : [];
1754
+ if (!v) block("version_not_found", { version: item.version });
1755
+ else if (ctx.needsReview(actor, doc.collection) && !v.approvedBy) block("review_required", { collection: doc.collection });
1756
+ else if (errors.length) block(errors[0].code, errors[0].params, errors[0].message);
1757
+ else ok.push({ item, doc });
1758
+ }
1759
+ }
1760
+ if (blocked.length) throw fail("release_blocked", { count: blocked.length }, { current: { blocked } });
1761
+ for (const { item, doc } of ok) {
1762
+ const out = item.action === "publish" ? await ctx.publishIn(r, actor, doc, item.version) : await ctx.unpublishIn(r, actor, doc);
1763
+ if (item.action === "publish" && !(await r.getVersion(doc.id, item.version))?.label) await r.updateVersion(doc.id, item.version, { label: cur.name.slice(0, 60) });
1764
+ done.push({ item, prev: doc, doc: out });
1765
+ }
1766
+ const at = nowIso();
1767
+ const saved = await r.updateRelease(cur.id, { state: "published", publishAt: null, publishedAt: at, publishedBy: actorRef(actor).label, lastError: null, updatedAt: at }, cur.state);
1768
+ if (!saved) throw fail("release_closed");
1769
+ return saved;
1770
+ });
1771
+ for (const d of done) {
1772
+ audit(actor, d.item.action === "publish" ? "doc.publish" : "doc.unpublish", { collection: d.doc.collection, slug: d.doc.slug, version: d.item.version, detail: { release: rel.name } });
1773
+ ctx.changed(d.prev, d.doc);
1774
+ }
1775
+ audit(actor, "release.publish", { detail: { id: rel.id, name: rel.name, documents: done.length } });
1776
+ return rel;
1777
+ }
1778
+ async function scheduleRelease(actor, id, o) {
1779
+ needEditor(actor);
1780
+ const rel = await loadRelease(id, true);
1781
+ if (o.publishAt === null) return viewRelease(actor, await repo.updateRelease(rel.id, { state: "open", publishAt: null, updatedAt: nowIso() }));
1782
+ const publishAt = future(o.publishAt, "publishAt");
1783
+ if (!publishAt) throw fail("schedule_invalid", { field: "publishAt" });
1784
+ if (!rel.items.length) throw fail("release_empty");
1785
+ for (const it of rel.items) {
1786
+ const doc = known(it.collection) ? await repo.findDocById(it.documentId) : null;
1787
+ if (!doc) throw fail("not_found", { collection: it.collection, slug: it.slug });
1788
+ assert(actor, doc.collection, "publish", doc);
1789
+ if (it.action === "publish") await ctx.assertReviewed(repo, actor, doc, it.version);
1790
+ }
1791
+ return viewRelease(actor, await repo.updateRelease(rel.id, { state: "scheduled", publishAt, lastError: null, updatedAt: nowIso() }));
1792
+ }
1793
+ async function releaseOf(documentId) {
1794
+ const rel = (await repo.listReleases()).find((r) => r.state !== "published" && r.items.some((x) => x.documentId === documentId));
1795
+ return rel ? { id: rel.id, name: rel.name, state: rel.state, publishAt: rel.publishAt } : null;
1796
+ }
1797
+ async function filters(actor, col) {
1798
+ await ctx.ready();
1799
+ assert(actor, col, "write");
1800
+ const me = actor.kind === "user" ? actor.id : null;
1801
+ return (await repo.listFilters(col)).filter((f) => f.shared || f.ownerId === me).map((f) => ({ ...f, mine: f.ownerId === me }));
1802
+ }
1803
+ async function saveFilter(actor, col, input) {
1804
+ await ctx.ready();
1805
+ assert(actor, col, "write");
1806
+ if (actor.kind !== "user") throw fail("forbidden");
1807
+ if (input.shared && !ctx.isAdmin(actor)) throw fail("forbidden_filter");
1808
+ const name = text(input.name, 61);
1809
+ if (!name || name.length > 60) throw fail("name_invalid", { max: 60 });
1810
+ const query = {};
1811
+ for (const k of FILTER_KEYS) if (typeof input.query?.[k] === "string" && input.query[k]) query[k] = input.query[k].slice(0, 200);
1812
+ return repo.insertFilter({ collection: col, name, query, ownerId: actor.id, ownerLabel: actor.label, shared: !!input.shared, createdAt: nowIso() });
1813
+ }
1814
+ async function removeFilter(actor, id) {
1815
+ await ctx.ready();
1816
+ const f = await repo.findFilter(String(id));
1817
+ if (!f) throw fail("filter_not_found");
1818
+ assert(actor, f.collection, "write");
1819
+ if (!(actor.kind === "user" && actor.id === f.ownerId) && !ctx.isAdmin(actor)) throw fail("forbidden_filter");
1820
+ await repo.deleteFilter(f.id);
1821
+ }
1822
+ const presenceId = (actor) => actor.kind === "user" ? actor.agent ? `agent:${actor.id}:${actor.agent.label}` : `user:${actor.id}` : actor.kind === "key" ? `key:${actor.id}` : actor.kind === "system" ? `system:${actor.label}` : "anonymous";
1823
+ const pos = (v) => {
1824
+ const p = v;
1825
+ return p && Number.isInteger(p.line) && Number.isInteger(p.ch) ? { line: Math.max(0, p.line), ch: Math.max(0, p.ch) } : null;
1826
+ };
1827
+ const since = () => new Date(ctx.now().getTime() - PRESENCE_MS).toISOString();
1828
+ function presenceRow(actor, doc, o = {}) {
1829
+ const who = actorRef(actor);
1830
+ return { documentId: doc.id, actorId: presenceId(actor), label: who.label, kind: who.kind, agent: who.agent, cursor: pos(o.cursor), selection: pos(o.selection), seenAt: nowIso() };
1831
+ }
1832
+ async function touchPresence(actor, col, slug, o = {}) {
1833
+ const doc = await ctx.editable(actor, col, slug);
1834
+ const row = presenceRow(actor, doc, o);
1835
+ await repo.touchPresence(row);
1836
+ return { version: doc.version, updatedBy: doc.updatedBy, others: (await repo.listPresence(since(), [doc.id])).filter((p) => p.actorId !== row.actorId) };
1837
+ }
1838
+ async function leavePresence(actor, col, slug) {
1839
+ const doc = await ctx.editable(actor, col, slug);
1840
+ await repo.dropPresence(doc.id, presenceId(actor));
1841
+ }
1842
+ async function presenceIn(actor, col) {
1843
+ await ctx.ready();
1844
+ assert(actor, col, "write");
1845
+ const docs = await repo.listDocs({ collection: col });
1846
+ const bySlug = new Map(docs.map((d) => [d.id, d.slug]));
1847
+ const out = /* @__PURE__ */ new Map();
1848
+ for (const p of await repo.listPresence(since(), docs.map((d) => d.id))) {
1849
+ const slug = bySlug.get(p.documentId);
1850
+ if (slug) out.set(slug, [...out.get(slug) ?? [], p]);
1851
+ }
1852
+ return [...out].map(([slug, people]) => ({ slug, people }));
1853
+ }
1854
+ function markAgent(actor, doc) {
1855
+ if (actor.kind !== "key" && !(actor.kind === "user" && actor.agent)) return;
1856
+ void repo.touchPresence(presenceRow(actor, doc)).catch((e) => ctx.report(e, "presence"));
1857
+ }
1858
+ return {
1859
+ schedule,
1860
+ unschedule,
1861
+ runScheduled,
1862
+ trash: { list: trashList, restore: trashRestore, purge: trashPurge },
1863
+ requestReview,
1864
+ approveReview,
1865
+ rejectReview,
1866
+ reviewRequests,
1867
+ comments,
1868
+ addComment,
1869
+ resolveComment,
1870
+ previewComments,
1871
+ addPreviewComment,
1872
+ labelVersion,
1873
+ releases: { list: releases, get: release, create: createRelease, rename: renameRelease, remove: removeRelease, add: addToRelease, removeItem: removeFromRelease, publish: publishRelease, schedule: scheduleRelease, of: releaseOf },
1874
+ filters: { list: filters, save: saveFilter, remove: removeFilter },
1875
+ presence: { touch: touchPresence, leave: leavePresence, in: presenceIn },
1876
+ markAgent
1877
+ };
1878
+ }
1879
+
1880
+ // src/cms.ts
1881
+ import { createHash as createHash2, createHmac, timingSafeEqual } from "crypto";
1882
+ function defineCollection(c) {
1883
+ return c;
1884
+ }
1885
+ var SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
1886
+ var LIMITS = { slug: 120, title: 200, summary: 300, body: 6e4, keyword: 40, keywords: 30 };
1887
+ function dayIn(timeZone, d) {
1888
+ const parts = new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" }).formatToParts(d);
1889
+ const get = (t) => parts.find((p) => p.type === t)?.value ?? "";
1890
+ return `${get("year")}-${get("month")}-${get("day")}`;
1891
+ }
1892
+ function addDays(day, days) {
1893
+ return new Date(Date.parse(`${day}T00:00:00Z`) + days * 864e5).toISOString().slice(0, 10);
1894
+ }
1895
+ function mergePatch(target, patch) {
1896
+ if (!patch || typeof patch !== "object" || Array.isArray(patch)) return patch;
1897
+ const out = target && typeof target === "object" && !Array.isArray(target) ? { ...target } : {};
1898
+ for (const [k, v] of Object.entries(patch)) {
1899
+ if (v === null) delete out[k];
1900
+ else out[k] = mergePatch(out[k], v);
1901
+ }
1902
+ return out;
1903
+ }
1904
+ var PREVIEW_TTLS = { "1h": 36e5, "24h": 864e5, "7d": 7 * 864e5 };
1905
+ var BULK_ACTIONS = ["publish", "unpublish", "archive", "unarchive", "delete"];
1906
+ var stable = (v) => Array.isArray(v) ? v.map(stable) : v && typeof v === "object" ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, stable(v[k])])) : v;
1907
+ var stableJson = (v) => JSON.stringify(stable(v));
1908
+ var b64url = (b) => Buffer.from(b).toString("base64url");
1909
+ function contentOf(doc) {
1910
+ return {
1911
+ slug: doc.slug,
1912
+ title: doc.title,
1913
+ summary: doc.summary ?? "",
1914
+ body: doc.body ?? "",
1915
+ category: doc.category ?? null,
1916
+ keywords: [...doc.keywords ?? []],
1917
+ fields: structuredClone(doc.fields ?? {})
1918
+ };
1919
+ }
1920
+ function createCmsCore(opts) {
1921
+ const repo = opts.repo;
1922
+ const now = opts.now ?? (() => /* @__PURE__ */ new Date());
1923
+ const nowIso = () => now().toISOString();
1924
+ const collections = /* @__PURE__ */ new Map();
1925
+ const minCoverage = opts.minCoverage ?? 0.5;
1926
+ const refreshMs = opts.searchRefreshMs ?? 6e4;
1927
+ const messages = opts.messages;
1928
+ const report = opts.onError ?? ((err, where) => console.warn(`[agent-cms] ${where}:`, err));
1929
+ const warned = /* @__PURE__ */ new Set();
1930
+ const warnOnce = (key, msg) => {
1931
+ if (warned.has(key)) return;
1932
+ warned.add(key);
1933
+ (opts.warn ?? ((m) => console.warn(`[agent-cms] ${m}`)))(msg);
1934
+ };
1935
+ const listeners = /* @__PURE__ */ new Set();
1936
+ const timeZone = opts.timeZone ?? "UTC";
1937
+ dayIn(timeZone, /* @__PURE__ */ new Date());
1938
+ if (opts.previewSecret !== void 0 && opts.previewSecret.length < 32) throw new Error("[agent-cms] previewSecret must be at least 32 characters");
1939
+ for (const c of opts.collections) {
1940
+ if (collections.has(c.slug)) throw new Error(`[agent-cms] two collections are named "${c.slug}"`);
1941
+ if (c.visibility !== "public" && c.visibility !== "internal") {
1942
+ throw new Error(`[agent-cms] collection "${c.slug}": set visibility to "public" or "internal" (required since 0.6.0)`);
1943
+ }
1944
+ if (c.visibility === "internal" && !c.access?.read) {
1945
+ throw new Error(`[agent-cms] collection "${c.slug}" is internal, so it needs access.read (who may read it)`);
1946
+ }
1947
+ if (c.search?.gapLogging !== void 0) {
1948
+ warnOnce("gapLogging", `search.gapLogging was removed in 0.6.0 and is ignored ("${c.slug}"). Use createCms({ onSearchMiss }) and store misses in your app. See UPGRADE-0.6.md.`);
1949
+ }
1950
+ collections.set(c.slug, c);
1951
+ }
1952
+ const fail = (code, params = {}, o = {}) => new CmsError(code, params, { messages, ...o });
1953
+ const trashDays = Math.max(0, Math.floor(opts.trash?.days ?? 30));
1954
+ let schemaReady = null;
1955
+ function ensureSchema() {
1956
+ if (opts.schemaCheck === false) return;
1957
+ schemaReady ??= (async () => {
1958
+ const raw = await repo.getMeta("schema_version");
1959
+ const found = raw == null ? null : Number(raw);
1960
+ if (found === null || !(found >= SCHEMA_VERSION)) {
1961
+ throw fail("schema_outdated", { found: found ?? 1, expected: SCHEMA_VERSION, command: "npx agent-cms migrate check" }, { status: 503 });
1962
+ }
1963
+ })().catch((e) => {
1964
+ schemaReady = null;
1965
+ throw e;
1966
+ });
1967
+ return schemaReady;
1968
+ }
1969
+ function actorInfo(actor) {
1970
+ if (actor.kind === "anonymous") return { actorKind: "anonymous", actorId: null, actorLabel: "anonymous" };
1971
+ if (actor.kind === "system") return { actorKind: "system", actorId: null, actorLabel: actor.label };
1972
+ return { actorKind: actor.kind, actorId: actor.id, actorLabel: actor.label, actorAgent: actor.kind === "user" ? actor.agent?.label ?? null : null };
1973
+ }
1974
+ function audit(actor, action, o = {}) {
1975
+ void repo.insertAudit({
1976
+ at: nowIso(),
1977
+ ...actorInfo(actor),
1978
+ action,
1979
+ collection: o.collection ?? null,
1980
+ slug: o.slug ?? null,
1981
+ version: o.version ?? null,
1982
+ outcome: o.outcome ?? "ok",
1983
+ via: actor.via ?? null,
1984
+ detail: o.detail ?? {}
1985
+ }).catch((e) => report(e, "audit"));
1986
+ }
1987
+ function collection(slug) {
1988
+ const c = collections.get(slug);
1989
+ if (!c) throw fail("unknown_collection", { collection: slug });
1990
+ return c;
1991
+ }
1992
+ function keyCovers(actor, col) {
1993
+ return !actor.collections || actor.collections.includes(col);
1994
+ }
1995
+ function can(actor, col, what, doc) {
1996
+ const c = collection(col);
1997
+ if (actor.kind === "system") return true;
1998
+ if (c.managed && what !== "read") return false;
1999
+ if (actor.kind === "key") {
2000
+ if (!keyCovers(actor, col)) return false;
2001
+ return actor.scopes.includes(what) || actor.scopes.includes("admin") || what === "read" && (actor.scopes.includes("write") || actor.scopes.includes("publish"));
2002
+ }
2003
+ if (what === "read") {
2004
+ if (c.access?.read) return c.access.read({ actor, collection: col, doc });
2005
+ return c.visibility === "public";
2006
+ }
2007
+ const fn = what === "write" ? c.access?.write : c.access?.publish;
2008
+ if (fn) return fn({ actor, collection: col, doc });
2009
+ return actor.kind === "user" && actor.isAdmin;
2010
+ }
2011
+ function assert(actor, col, what, doc) {
2012
+ if (can(actor, col, what, doc)) return;
2013
+ if (actor.kind !== "anonymous" && what !== "read") audit(actor, "access.denied", { collection: col, slug: doc?.slug ?? null, outcome: "denied", detail: { need: what } });
2014
+ if (actor.kind === "anonymous") throw fail("unauthorized");
2015
+ throw fail(what === "publish" ? "forbidden_publish" : what === "write" ? "forbidden_write" : "forbidden_read", { collection: col });
2016
+ }
2017
+ function actorRef(actor) {
2018
+ if (actor.kind === "user") return { kind: "user", id: actor.id, label: actor.label, agent: actor.agent?.label?.trim() || null };
2019
+ if (actor.kind === "key") return { kind: "key", id: actor.id, label: actor.label, agent: null };
2020
+ if (actor.kind === "system") return { kind: "system", id: null, label: actor.label, agent: null };
2021
+ throw fail("unauthorized");
2022
+ }
2023
+ const assets = createAssets({
2024
+ repo,
2025
+ media: opts.media,
2026
+ fail,
2027
+ diag: (path, code, params, severity) => ({ path, code, params, severity, message: formatMessage(messages, code, params) }),
2028
+ audit: (actor, action, o) => audit(actor, action, o),
2029
+ nowIso,
2030
+ actorRef,
2031
+ collection,
2032
+ canReadDoc: (actor, doc) => collections.has(doc.collection) && can(actor, doc.collection, "read", doc),
2033
+ warn: warnOnce,
2034
+ ready: ensureSchema,
2035
+ trashDays
2036
+ });
2037
+ function check(col, c) {
2038
+ const cfg = collection(col);
2039
+ const out = contentOf(c);
2040
+ const diags = [];
2041
+ const add = (path, code, params = {}, severity = "error") => diags.push({ path, code, params, severity, message: formatMessage(messages, code, params) });
2042
+ out.slug = (out.slug ?? "").trim();
2043
+ out.title = (out.title ?? "").trim();
2044
+ out.summary = out.summary.trim();
2045
+ out.keywords = [...new Set(out.keywords.map((k) => String(k).trim()).filter(Boolean))];
2046
+ if (!(cfg.slugPattern ?? SLUG_RE).test(out.slug) || out.slug.length > LIMITS.slug) add("slug", "invalid_slug", { max: LIMITS.slug });
2047
+ if (!out.title || out.title.length > LIMITS.title) add("title", "invalid_title", { max: LIMITS.title });
2048
+ if (out.summary.length > LIMITS.summary) add("summary", "summary_too_long", { max: LIMITS.summary });
2049
+ if (out.body.length > LIMITS.body) add("body", "body_too_long", { max: LIMITS.body });
2050
+ if (out.keywords.length > LIMITS.keywords || out.keywords.some((k) => k.length > LIMITS.keyword)) add("keywords", "invalid_keywords", { max: LIMITS.keywords, maxLength: LIMITS.keyword });
2051
+ for (const ch of cfg.forbiddenChars ?? []) {
2052
+ for (const f of ["title", "summary", "body"]) if (out[f].includes(ch)) add(f, "forbidden_char", { char: ch });
2053
+ }
2054
+ if (cfg.categories && (out.category === null || !cfg.categories.includes(out.category))) add("category", "invalid_category", { allowed: [...cfg.categories] });
2055
+ if (cfg.fields) {
2056
+ const parsed = cfg.fields.safeParse(out.fields ?? {});
2057
+ if (!parsed.success) for (const i of parsed.error.issues) add(["fields", ...i.path].join("."), "invalid_field", { path: i.path.join("."), issue: i.message });
2058
+ else out.fields = parsed.data;
2059
+ }
2060
+ if (cfg.links) {
2061
+ const bad = appLinkKeys(out.body).filter((k) => !cfg.links.resolve(k));
2062
+ if (bad.length) add("body", "unknown_link", { keys: bad });
2063
+ }
2064
+ return { content: out, diagnostics: diags };
2065
+ }
2066
+ function validate(col, c) {
2067
+ const { content, diagnostics } = check(col, c);
2068
+ const errors = diagnostics.filter((d) => d.severity === "error");
2069
+ if (errors.length) throw fail(errors[0].code, errors[0].params, { diagnostics: errors });
2070
+ return content;
2071
+ }
2072
+ async function diagnose(actor, col, input, o = {}) {
2073
+ assert(actor, col, "write");
2074
+ const cfg = collection(col);
2075
+ const cur = o.slug ? await repo.findDoc(col, o.slug) : null;
2076
+ const base = cur ?? { slug: "", title: "", summary: "", body: "", category: cfg.categories?.[0] ?? null, keywords: [], fields: {} };
2077
+ const content = merged(base, input);
2078
+ const { diagnostics } = check(col, content);
2079
+ if (cur && content.slug !== cur.slug && cur.publishedVersion !== null) diagnostics.push({ path: "slug", code: "slug_locked", params: {}, severity: "error", message: formatMessage(messages, "slug_locked") });
2080
+ const other = content.slug ? await repo.findDoc(col, content.slug, { trashed: true }) : null;
2081
+ const taken = other?.deletedAt ? "slug_in_trash" : "slug_taken";
2082
+ if (other && other.id !== cur?.id) diagnostics.push({ path: "slug", code: taken, params: { slug: content.slug }, severity: "error", message: formatMessage(messages, taken, { slug: content.slug }) });
2083
+ diagnostics.push(...await assets.checkDoc(cfg, content, cur ? assets.idsIn(cfg, cur) : void 0));
2084
+ return diagnostics;
2085
+ }
2086
+ const same = (a, b) => stableJson(contentOf(a)) === stableJson(contentOf(b));
2087
+ function merged(cur, input) {
2088
+ return {
2089
+ slug: input.slug ?? cur.slug,
2090
+ title: input.title ?? cur.title,
2091
+ summary: input.summary ?? cur.summary,
2092
+ body: input.body ?? cur.body,
2093
+ category: input.category !== void 0 ? input.category : cur.category,
2094
+ keywords: input.keywords ?? cur.keywords,
2095
+ fields: input.fields !== void 0 ? mergePatch(cur.fields, input.fields) : cur.fields
2096
+ };
2097
+ }
2098
+ function publicView(doc) {
2099
+ if (doc.publishedVersion === null || doc.status === "archived" || !doc.published) return null;
2100
+ return { ...doc, ...contentOf(doc.published), version: doc.publishedVersion, autosave: null };
2101
+ }
2102
+ async function get(actor, col, slug, o = {}) {
2103
+ collection(col);
2104
+ await ensureSchema();
2105
+ const doc = await repo.findDoc(col, slug);
2106
+ if (!doc) throw fail("not_found", { collection: col, slug });
2107
+ if (o.draft && can(actor, col, "write", doc)) return doc;
2108
+ assert(actor, col, "read", doc);
2109
+ const pub = publicView(doc);
2110
+ if (!pub) throw fail("not_found", { collection: col, slug });
2111
+ return pub;
2112
+ }
2113
+ async function list(actor, col, o = {}) {
2114
+ collection(col);
2115
+ await ensureSchema();
2116
+ const editor = !!o.drafts && can(actor, col, "write");
2117
+ if (!editor) assert(actor, col, "read");
2118
+ const rows = editor ? await repo.listDocs({ collection: col, statuses: o.status ? [o.status] : void 0 }) : (await repo.listDocs({ collection: col, published: true })).map(publicView).filter((d) => !!d);
2119
+ const q = o.q?.trim().toLowerCase();
2120
+ return rows.filter((d) => !o.category || d.category === o.category).filter((d) => !q || d.title.toLowerCase().includes(q) || d.slug.includes(q) || d.summary.toLowerCase().includes(q)).filter((d) => !editor || !o.by || d.updatedByKind === o.by).filter((d) => {
2121
+ if (!editor || !o.state) return true;
2122
+ const s = docState(d);
2123
+ if (o.state === "scheduled") return !!d.schedule;
2124
+ if (o.state === "review") return d.review?.state === "requested";
2125
+ return o.state === "modified" ? s.modifiedSincePublish : s.state === o.state;
2126
+ }).sort((a, b) => editor ? b.updatedAt.localeCompare(a.updatedAt) : (b.publishedAt ?? b.updatedAt).localeCompare(a.publishedAt ?? a.updatedAt));
2127
+ }
2128
+ function summaryOf(d) {
2129
+ const s = docState(d);
2130
+ return {
2131
+ id: d.id,
2132
+ collection: d.collection,
2133
+ slug: d.slug,
2134
+ title: d.title,
2135
+ summary: d.summary,
2136
+ category: d.category,
2137
+ status: d.status,
2138
+ state: s.state,
2139
+ modifiedSincePublish: s.modifiedSincePublish,
2140
+ version: d.version,
2141
+ publishedVersion: d.publishedVersion,
2142
+ publishedAt: d.publishedAt,
2143
+ updatedAt: d.updatedAt,
2144
+ updatedBy: d.updatedBy,
2145
+ updatedByKind: d.updatedByKind,
2146
+ updatedByAgent: d.updatedByAgent ?? null,
2147
+ schedule: d.schedule ? { publishAt: d.schedule.publishAt, unpublishAt: d.schedule.unpublishAt, version: d.schedule.version, by: d.schedule.by } : null,
2148
+ review: d.review ? { state: d.review.state, version: d.review.version, by: d.review.by, note: d.review.note } : null
2149
+ };
2150
+ }
2151
+ async function page(actor, col, o = {}) {
2152
+ const all = await list(actor, col, o);
2153
+ const limit = Math.max(1, Math.min(o.limit ?? 50, 200));
2154
+ const offset = Math.max(0, Number(o.cursor ?? 0) || 0);
2155
+ const slice = all.slice(offset, offset + limit).map(summaryOf);
2156
+ if (o.hits && can(actor, col, "write")) {
2157
+ const counts2 = await hitCounts(actor, col, 7);
2158
+ for (const d of slice) d.hits7d = counts2.get(d.id) ?? 0;
2159
+ }
2160
+ return { docs: slice, total: all.length, nextCursor: offset + limit < all.length ? String(offset + limit) : null };
2161
+ }
2162
+ async function counts(actor, col) {
2163
+ assert(actor, col, "write");
2164
+ await ensureSchema();
2165
+ const out = { all: 0, draft: 0, published: 0, modified: 0, archived: 0, scheduled: 0, review: 0 };
2166
+ for (const d of await repo.listDocs({ collection: col })) {
2167
+ const s = docState(d);
2168
+ out.all++;
2169
+ out[s.state]++;
2170
+ if (s.modifiedSincePublish) out.modified++;
2171
+ if (d.schedule) out.scheduled++;
2172
+ if (d.review?.state === "requested") out.review++;
2173
+ }
2174
+ return out;
2175
+ }
2176
+ async function editable(actor, col, slug) {
2177
+ collection(col);
2178
+ await ensureSchema();
2179
+ const doc = await repo.findDoc(col, slug);
2180
+ if (!doc) throw fail("not_found", { collection: col, slug });
2181
+ assert(actor, col, "write", doc);
2182
+ return doc;
2183
+ }
2184
+ const withPublished = (v, doc) => ({ ...v, published: v.version === doc.publishedVersion });
2185
+ async function versions(actor, col, slug) {
2186
+ const doc = await editable(actor, col, slug);
2187
+ return (await repo.listVersions(doc.id)).map((v) => withPublished(v, doc));
2188
+ }
2189
+ async function versionList(actor, col, slug) {
2190
+ const doc = await editable(actor, col, slug);
2191
+ return (await repo.listVersions(doc.id)).map((v) => {
2192
+ const { snapshot, ...rest } = withPublished(v, doc);
2193
+ return { ...rest, title: snapshot.title };
2194
+ });
2195
+ }
2196
+ async function version(actor, col, slug, n) {
2197
+ const doc = await editable(actor, col, slug);
2198
+ const v = await repo.getVersion(doc.id, n);
2199
+ if (!v) throw fail("version_not_found", { version: n });
2200
+ return withPublished(v, doc);
2201
+ }
2202
+ async function diff(actor, col, slug, a, b, o = {}) {
2203
+ const doc = await editable(actor, col, slug);
2204
+ const [va, vb] = await Promise.all([repo.getVersion(doc.id, a), repo.getVersion(doc.id, b)]);
2205
+ if (!va) throw fail("version_not_found", { version: a });
2206
+ if (!vb) throw fail("version_not_found", { version: b });
2207
+ return { a, b, fields: fieldChanges(va.snapshot, vb.snapshot), hunks: hunks(va.snapshot.body, vb.snapshot.body, o.context ?? 3) };
2208
+ }
2209
+ function publicSig(doc) {
2210
+ const p = doc ? publicView(doc) : null;
2211
+ return p ? `${p.publishedVersion}:${stableJson(contentOf(p))}` : "";
2212
+ }
2213
+ function changed(prev, doc) {
2214
+ const target = doc ?? prev;
2215
+ if (!target) return;
2216
+ const info = { contentChanged: publicSig(prev) !== publicSig(doc) };
2217
+ if (info.contentChanged) index.dirty = true;
2218
+ for (const l of listeners) {
2219
+ try {
2220
+ l(target, info);
2221
+ } catch (e) {
2222
+ report(e, "onChange");
2223
+ }
2224
+ }
2225
+ for (const h of collection(target.collection).hooks?.afterChange ?? []) {
2226
+ Promise.resolve().then(() => h(target, info)).catch((e) => report(e, "afterChange"));
2227
+ }
2228
+ }
2229
+ async function prune(r, doc) {
2230
+ const max = collection(doc.collection).versions?.max ?? 100;
2231
+ if (max > 0) await r.pruneVersions(doc.id, max, doc.publishedVersion ? [doc.publishedVersion] : []);
2232
+ }
2233
+ const hunkId = (v, h) => createHash2("sha256").update(`${v}
2234
+ ${h.removed.join("\n")}
2235
+ --
2236
+ ${h.added.join("\n")}`).digest("hex").slice(0, 12);
2237
+ function changeOf(v, prev, next) {
2238
+ if (!prev) return { fields: [], hunks: [] };
2239
+ const fields = fieldChanges(prev, next).map((f) => f.path);
2240
+ const lines = splitLines(next.body);
2241
+ const hs = hunks(prev.body, next.body, 0).map((h) => ({
2242
+ id: hunkId(v, h),
2243
+ removed: h.removed,
2244
+ added: h.added,
2245
+ before: h.bStart > 1 || h.bLines === 0 && h.bStart > 0 ? lines[(h.bLines === 0 ? h.bStart : h.bStart - 1) - 1] ?? null : null
2246
+ }));
2247
+ if (hs.length) fields.push("body");
2248
+ return { fields, hunks: hs };
2249
+ }
2250
+ const conflict = (cur, expected, actor, col) => fail("conflict_version", { expected, current: cur.version }, { current: can(actor, col, "write", cur) ? cur : void 0 });
2251
+ function needsReview(actor, col) {
2252
+ const rule = collection(col).review;
2253
+ if (!rule || actor.kind === "system") return false;
2254
+ if (rule.everyone === "required") return true;
2255
+ return rule.agents === "required" && (actor.kind === "key" || actor.kind === "user" && !!actor.agent);
2256
+ }
2257
+ const reviewRequired = (actor, col, slug) => {
2258
+ audit(actor, "access.denied", { collection: col, slug, outcome: "denied", detail: { need: "review" } });
2259
+ return fail("review_required", { collection: col });
2260
+ };
2261
+ async function assertReviewed(r, actor, doc, n) {
2262
+ if (!needsReview(actor, doc.collection)) return;
2263
+ if (!(await r.getVersion(doc.id, n))?.approvedBy) throw reviewRequired(actor, doc.collection, doc.slug);
2264
+ }
2265
+ const slugTaken = (other) => fail(other.deletedAt ? "slug_in_trash" : "slug_taken", { slug: other.slug });
2266
+ async function create(actor, col, input, o = {}) {
2267
+ await ensureSchema();
2268
+ assert(actor, col, "write");
2269
+ if (o.publish) assert(actor, col, "publish");
2270
+ if (o.publish && needsReview(actor, col)) throw reviewRequired(actor, col, input.slug ?? null);
2271
+ const who = actorRef(actor);
2272
+ const cfg = collection(col);
2273
+ const content = validate(col, {
2274
+ slug: input.slug ?? "",
2275
+ title: input.title ?? "",
2276
+ summary: input.summary ?? "",
2277
+ body: input.body ?? "",
2278
+ category: input.category ?? cfg.categories?.[0] ?? null,
2279
+ keywords: input.keywords ?? [],
2280
+ fields: input.fields ?? {}
2281
+ });
2282
+ await assets.assertDoc(cfg, content);
2283
+ const at = nowIso();
2284
+ const doc = await repo.tx(async (r) => {
2285
+ const other = await r.findDoc(col, content.slug, { trashed: true });
2286
+ if (other) throw slugTaken(other);
2287
+ const publish2 = !!o.publish;
2288
+ const row = await r.insertDoc({
2289
+ collection: col,
2290
+ ...content,
2291
+ status: publish2 ? "published" : "draft",
2292
+ version: 1,
2293
+ publishedVersion: publish2 ? 1 : null,
2294
+ published: publish2 ? content : null,
2295
+ publishedAt: publish2 ? at : null,
2296
+ updatedBy: who.label,
2297
+ updatedByKind: who.kind,
2298
+ updatedByAgent: who.agent,
2299
+ createdAt: at,
2300
+ updatedAt: at
2301
+ });
2302
+ await r.insertVersion({ documentId: row.id, version: 1, snapshot: content, authorKind: who.kind, authorId: who.id, authorLabel: who.label, authorAgent: who.agent, note: o.note ?? null, createdAt: at, changed: changeOf(1, null, content) });
2303
+ await assets.syncRefs(r, row);
2304
+ return row;
2305
+ });
2306
+ if (o.publish) audit(actor, "doc.publish", { collection: col, slug: doc.slug, version: 1 });
2307
+ changed(null, doc);
2308
+ return doc;
2309
+ }
2310
+ async function commit(r, actor, doc, next, o) {
2311
+ const who = actorRef(actor);
2312
+ const cfg = collection(doc.collection);
2313
+ const at = nowIso();
2314
+ const v = doc.version + 1;
2315
+ if (next.slug !== doc.slug && doc.publishedVersion !== null) throw fail("slug_locked");
2316
+ const other = next.slug !== doc.slug ? await r.findDoc(doc.collection, next.slug, { trashed: true }) : null;
2317
+ if (other) throw slugTaken(other);
2318
+ const inPlace = cfg.versions?.drafts === false && doc.publishedVersion !== null && doc.status !== "archived";
2319
+ const publish2 = !!o.publish || inPlace;
2320
+ if (publish2 && needsReview(actor, doc.collection)) throw reviewRequired(actor, doc.collection, doc.slug);
2321
+ const wasPublic = doc.publishedVersion !== null && doc.status !== "archived";
2322
+ let patch2 = { ...next, version: v, updatedBy: who.label, updatedByKind: who.kind, updatedByAgent: who.agent, updatedAt: at, autosave: null };
2323
+ if (publish2) {
2324
+ patch2 = { ...patch2, status: "published", publishedVersion: v, published: next, publishedAt: doc.publishedAt ?? at, review: null, ...afterPublish(doc) };
2325
+ if (!wasPublic && doc.publishedAt) patch2.republishedAt = at;
2326
+ } else {
2327
+ patch2 = { ...patch2, status: doc.status === "archived" ? "archived" : "draft" };
2328
+ if (doc.review?.state === "requested") patch2.review = { ...doc.review, version: v };
2329
+ }
2330
+ const updated = await r.updateDoc(doc.id, patch2, o.expectedVersion ?? doc.version);
2331
+ if (!updated) {
2332
+ const cur = await r.findDoc(doc.collection, doc.slug) ?? doc;
2333
+ throw conflict(cur, o.expectedVersion ?? doc.version, actor, doc.collection);
2334
+ }
2335
+ await r.insertVersion({
2336
+ documentId: doc.id,
2337
+ version: v,
2338
+ snapshot: next,
2339
+ authorKind: who.kind,
2340
+ authorAgent: who.agent,
2341
+ authorId: who.id,
2342
+ authorLabel: who.label,
2343
+ note: o.note ?? (o.restoredFrom ? `restored v${o.restoredFrom}` : null),
2344
+ createdAt: at,
2345
+ changed: changeOf(v, doc, next)
2346
+ });
2347
+ await prune(r, updated);
2348
+ await assets.syncRefs(r, updated);
2349
+ return updated;
2350
+ }
2351
+ async function write(actor, col, slug, make, o = {}) {
2352
+ await ensureSchema();
2353
+ let prev = null;
2354
+ const doc = await repo.tx(async (r) => {
2355
+ const cur = prev = await r.findDoc(col, slug);
2356
+ if (!cur) throw fail("not_found", { collection: col, slug });
2357
+ assert(actor, col, "write", cur);
2358
+ if (o.publish || collection(col).versions?.drafts === false && cur.publishedVersion !== null) assert(actor, col, "publish", cur);
2359
+ if (o.expectedVersion !== void 0 && o.expectedVersion !== cur.version) throw conflict(cur, o.expectedVersion, actor, col);
2360
+ const next = validate(col, merged(cur, make(cur)));
2361
+ await assets.assertDoc(collection(col), next, cur, r);
2362
+ if (same(next, cur)) {
2363
+ if (o.publish && cur.publishedVersion !== cur.version) {
2364
+ await assertReviewed(r, actor, cur, cur.version);
2365
+ return publishIn(r, actor, cur, cur.version);
2366
+ }
2367
+ return cur.autosave ? await r.updateDoc(cur.id, { autosave: null, updatedAt: cur.updatedAt }) ?? cur : cur;
2368
+ }
2369
+ return commit(r, actor, cur, next, o);
2370
+ });
2371
+ if (o.publish && doc.publishedVersion === doc.version && prev && prev.publishedVersion !== doc.version) audit(actor, "doc.publish", { collection: col, slug: doc.slug, version: doc.version });
2372
+ changed(prev, doc);
2373
+ flow.markAgent(actor, doc);
2374
+ return { prev, doc };
2375
+ }
2376
+ async function update(actor, col, slug, input, o = {}) {
2377
+ return (await write(actor, col, slug, () => input, o)).doc;
2378
+ }
2379
+ async function patch(actor, col, slug, ops, o = {}) {
2380
+ if (o.dryRun) {
2381
+ const cur = await editable(actor, col, slug);
2382
+ if (o.expectedVersion !== void 0 && o.expectedVersion !== cur.version) throw conflict(cur, o.expectedVersion, actor, col);
2383
+ const body = applyPatch(cur.body, ops);
2384
+ const { diagnostics } = check(col, { ...cur, body });
2385
+ diagnostics.push(...await assets.checkDoc(collection(col), { ...cur, body }, assets.idsIn(collection(col), cur)));
2386
+ return { doc: null, diff: unifiedDiff(cur.body, body, { from: `v${cur.version}`, to: "patched" }), diagnostics, saved: false };
2387
+ }
2388
+ let before = "";
2389
+ const r = await write(
2390
+ actor,
2391
+ col,
2392
+ slug,
2393
+ (cur) => {
2394
+ before = cur.body;
2395
+ return { body: applyPatch(cur.body, ops) };
2396
+ },
2397
+ o
2398
+ );
2399
+ return { doc: r.doc, diff: unifiedDiff(before, r.doc.body, { from: `v${r.prev?.version ?? "?"}`, to: `v${r.doc.version}` }), diagnostics: [], saved: r.doc.version !== r.prev?.version };
2400
+ }
2401
+ async function sections(actor, col, slug) {
2402
+ const doc = await editable(actor, col, slug);
2403
+ return sectionRanges(doc.body).map((s) => ({ anchor: s.anchor, heading: s.heading }));
2404
+ }
2405
+ async function autosave(actor, col, slug, input, baseVersion) {
2406
+ await ensureSchema();
2407
+ const cur = await editable(actor, col, slug);
2408
+ const content = contentOf(merged(cur.autosave?.content ?? cur, input));
2409
+ if (JSON.stringify(content).length > LIMITS.body * 2) throw fail("body_too_large", {}, { status: 413 });
2410
+ const state = { content, at: nowIso(), by: actorRef(actor).label, baseVersion };
2411
+ await repo.updateDoc(cur.id, { autosave: state, updatedAt: cur.updatedAt });
2412
+ return state;
2413
+ }
2414
+ async function discardAutosave(actor, col, slug) {
2415
+ const cur = await editable(actor, col, slug);
2416
+ if (cur.autosave) await repo.updateDoc(cur.id, { autosave: null, updatedAt: cur.updatedAt });
2417
+ }
2418
+ const afterPublish = (doc) => ({ schedule: doc.schedule?.unpublishAt ? { ...doc.schedule, publishAt: null } : null, dueAt: doc.schedule?.unpublishAt ?? null });
2419
+ async function publishIn(r, actor, doc, n) {
2420
+ const v = n === doc.version ? { snapshot: contentOf(doc) } : await r.getVersion(doc.id, n);
2421
+ if (!v) throw fail("version_not_found", { version: n });
2422
+ const at = nowIso();
2423
+ const wasPublic = doc.publishedVersion !== null && doc.status !== "archived";
2424
+ const updated = await r.updateDoc(doc.id, {
2425
+ status: n === doc.version ? "published" : "draft",
2426
+ publishedVersion: n,
2427
+ published: v.snapshot,
2428
+ publishedAt: doc.publishedAt ?? at,
2429
+ ...!wasPublic && doc.publishedAt ? { republishedAt: at } : {},
2430
+ ...afterPublish(doc),
2431
+ ...doc.review && n >= doc.review.version ? { review: null } : {},
2432
+ updatedAt: at,
2433
+ updatedBy: actorRef(actor).label,
2434
+ updatedByKind: actorRef(actor).kind,
2435
+ updatedByAgent: actorRef(actor).agent
2436
+ });
2437
+ if (!updated) throw fail("not_found", { collection: doc.collection, slug: doc.slug });
2438
+ await assets.syncRefs(r, updated);
2439
+ return updated;
2440
+ }
2441
+ async function stateChange(actor, col, slug, expectedVersion, fn) {
2442
+ await ensureSchema();
2443
+ let prev = null;
2444
+ const doc = await repo.tx(async (r) => {
2445
+ const cur = prev = await r.findDoc(col, slug);
2446
+ if (!cur) throw fail("not_found", { collection: col, slug });
2447
+ assert(actor, col, "publish", cur);
2448
+ if (expectedVersion !== void 0 && expectedVersion !== cur.version) throw conflict(cur, expectedVersion, actor, col);
2449
+ return fn(r, cur);
2450
+ });
2451
+ changed(prev, doc);
2452
+ return doc;
2453
+ }
2454
+ async function publish(actor, col, slug, o = {}) {
2455
+ const doc = await stateChange(actor, col, slug, o.expectedVersion, async (r, cur) => {
2456
+ await assertReviewed(r, actor, cur, o.version ?? cur.version);
2457
+ return publishIn(r, actor, cur, o.version ?? cur.version);
2458
+ });
2459
+ audit(actor, "doc.publish", { collection: col, slug, version: doc.publishedVersion });
2460
+ return doc;
2461
+ }
2462
+ async function archive(actor, col, slug, o = {}) {
2463
+ const doc = await stateChange(actor, col, slug, o.expectedVersion, async (r, cur) => {
2464
+ if (cur.publishedVersion === null) throw fail("not_published");
2465
+ if (cur.status === "archived") return cur;
2466
+ return await r.updateDoc(cur.id, { status: "archived", updatedAt: nowIso() });
2467
+ });
2468
+ audit(actor, "doc.archive", { collection: col, slug, version: doc.version });
2469
+ return doc;
2470
+ }
2471
+ async function unarchive(actor, col, slug, o = {}) {
2472
+ const doc = await stateChange(actor, col, slug, o.expectedVersion, async (r, cur) => {
2473
+ if (cur.status !== "archived") return cur;
2474
+ const at = nowIso();
2475
+ return await r.updateDoc(cur.id, { status: cur.publishedVersion === cur.version ? "published" : "draft", republishedAt: at, updatedAt: at });
2476
+ });
2477
+ audit(actor, "doc.unarchive", { collection: col, slug, version: doc.version });
2478
+ return doc;
2479
+ }
2480
+ async function unpublishIn(r, actor, cur) {
2481
+ if (cur.publishedVersion === null && cur.status !== "archived") return cur.schedule ? await r.updateDoc(cur.id, { schedule: null, dueAt: null, updatedAt: cur.updatedAt }) : cur;
2482
+ const who = actorRef(actor);
2483
+ const out = await r.updateDoc(cur.id, { status: "draft", publishedVersion: null, published: null, schedule: null, dueAt: null, updatedAt: nowIso(), updatedBy: who.label, updatedByKind: who.kind, updatedByAgent: who.agent });
2484
+ await assets.syncRefs(r, out);
2485
+ return out;
2486
+ }
2487
+ async function unpublish(actor, col, slug, o = {}) {
2488
+ const doc = await stateChange(actor, col, slug, o.expectedVersion, (r, cur) => unpublishIn(r, actor, cur));
2489
+ audit(actor, "doc.unpublish", { collection: col, slug, version: doc.version });
2490
+ return doc;
2491
+ }
2492
+ async function restore(actor, col, slug, n, o = {}) {
2493
+ await ensureSchema();
2494
+ let prev = null;
2495
+ const doc = await repo.tx(async (r) => {
2496
+ const cur = prev = await r.findDoc(col, slug);
2497
+ if (!cur) throw fail("not_found", { collection: col, slug });
2498
+ assert(actor, col, "write", cur);
2499
+ if (o.publish || collection(col).versions?.drafts === false && cur.publishedVersion !== null) assert(actor, col, "publish", cur);
2500
+ if (o.expectedVersion !== void 0 && o.expectedVersion !== cur.version) throw conflict(cur, o.expectedVersion, actor, col);
2501
+ const v = await r.getVersion(cur.id, n);
2502
+ if (!v) throw fail("version_not_found", { version: n });
2503
+ return commit(r, actor, cur, validate(col, { ...v.snapshot, slug: cur.slug }), { ...o, restoredFrom: n });
2504
+ });
2505
+ audit(actor, "doc.restore", { collection: col, slug, version: doc.version, detail: { from: n } });
2506
+ changed(prev, doc);
2507
+ return doc;
2508
+ }
2509
+ async function remove(actor, col, slug, o = {}) {
2510
+ await ensureSchema();
2511
+ const cur = await repo.findDoc(col, slug);
2512
+ if (!cur) throw fail("not_found", { collection: col, slug });
2513
+ assert(actor, col, "publish", cur);
2514
+ if (o.expectedVersion !== void 0 && o.expectedVersion !== cur.version) throw conflict(cur, o.expectedVersion, actor, col);
2515
+ if (trashDays > 0) await repo.updateDoc(cur.id, { deletedAt: nowIso(), deletedBy: actorRef(actor).label, schedule: null, dueAt: null, updatedAt: nowIso() });
2516
+ else await repo.deleteDoc(cur.id);
2517
+ audit(actor, "doc.delete", { collection: col, slug, version: cur.version, detail: { trash: trashDays > 0 } });
2518
+ changed(cur, null);
2519
+ }
2520
+ async function preview(actor, col, input, o = {}) {
2521
+ const diagnostics = await diagnose(actor, col, input, o);
2522
+ const cfg = collection(col);
2523
+ const cur = o.slug ? await repo.findDoc(col, o.slug) : null;
2524
+ const content = merged(cur ?? { slug: "", title: "", summary: "", body: "", category: null, keywords: [], fields: {} }, input);
2525
+ const blocks = parseMarkdown(content.body, { lines: true });
2526
+ return {
2527
+ blocks,
2528
+ toc: extractToc(blocks),
2529
+ diagnostics,
2530
+ diff: cur ? unifiedDiff(cur.body, content.body, { from: `v${cur.version}`, to: "preview" }) : null,
2531
+ publicUrl: cfg.url && content.slug ? cfg.url({ slug: content.slug }) : null,
2532
+ assets: await assets.assetsFor({ collection: col, body: content.body, fields: content.fields })
2533
+ };
2534
+ }
2535
+ async function bulk(actor, col, action, items) {
2536
+ if (!BULK_ACTIONS.includes(action)) throw fail("invalid_request", { issues: `action: ${action}` });
2537
+ const out = [];
2538
+ const tagged = { ...actor };
2539
+ for (const it of items.slice(0, 200)) {
2540
+ try {
2541
+ const o = { expectedVersion: it.expectedVersion };
2542
+ if (action === "publish") await publish(tagged, col, it.slug, o);
2543
+ else if (action === "unpublish") await unpublish(tagged, col, it.slug, o);
2544
+ else if (action === "archive") await archive(tagged, col, it.slug, o);
2545
+ else if (action === "unarchive") await unarchive(tagged, col, it.slug, o);
2546
+ else await remove(tagged, col, it.slug, o);
2547
+ out.push({ slug: it.slug, ok: true });
2548
+ } catch (e) {
2549
+ if (!isCmsError(e)) report(e, "bulk");
2550
+ out.push({ slug: it.slug, ok: false, error: isCmsError(e) ? { code: e.code, message: message(e) } : { code: "internal", message: formatMessage(messages, "internal") } });
2551
+ }
2552
+ }
2553
+ return out;
2554
+ }
2555
+ const containsBlock = (body, block) => {
2556
+ if (!block.length) return true;
2557
+ const lines = splitLines(body);
2558
+ outer: for (let i = 0; i + block.length <= lines.length; i++) {
2559
+ for (let j = 0; j < block.length; j++) if (lines[i + j] !== block[j]) continue outer;
2560
+ return true;
2561
+ }
2562
+ return false;
2563
+ };
2564
+ async function agentChanges(actor, col, slug) {
2565
+ const doc = await editable(actor, col, slug);
2566
+ const out = [];
2567
+ for (const v of (await repo.listVersions(doc.id)).slice(0, 30)) {
2568
+ if (v.authorKind === "user" && !v.authorAgent || !v.changed) continue;
2569
+ const done = new Set(v.reviewed.map((m) => m.hunk));
2570
+ for (const h of v.changed.hunks) {
2571
+ if (done.has(h.id)) continue;
2572
+ if (h.added.length ? !containsBlock(doc.body, h.added) : containsBlock(doc.body, h.removed)) continue;
2573
+ out.push({ id: h.id, version: v.version, author: v.authorAgent ?? v.authorLabel, authorKind: v.authorKind, behalf: v.authorAgent ? v.authorLabel : null, at: v.createdAt, removed: h.removed, added: h.added, before: h.before ?? null });
2574
+ }
2575
+ }
2576
+ return out;
2577
+ }
2578
+ async function reviewChanges(actor, col, slug, o) {
2579
+ const doc = await editable(actor, col, slug);
2580
+ const who = actorRef(actor).label;
2581
+ const at = nowIso();
2582
+ const pending = await agentChanges(actor, col, slug);
2583
+ const want = o.hunks === "all" ? pending : pending.filter((p) => o.hunks.includes(p.id));
2584
+ const byVersion = /* @__PURE__ */ new Map();
2585
+ for (const p of want) byVersion.set(p.version, [...byVersion.get(p.version) ?? [], p.id]);
2586
+ for (const [n, ids] of byVersion) {
2587
+ const v = await repo.getVersion(doc.id, n);
2588
+ if (!v) continue;
2589
+ await repo.setVersionReviewed(doc.id, n, [...v.reviewed, ...ids.map((hunk) => ({ hunk, by: who, at, action: o.action ?? "accepted" }))]);
2590
+ }
2591
+ return { reviewed: want.length };
2592
+ }
2593
+ function sign(payload) {
2594
+ return createHmac("sha256", opts.previewSecret).update(payload).digest("base64url");
2595
+ }
2596
+ async function createPreviewLink(actor, col, slug, o = {}) {
2597
+ if (!opts.previewSecret) throw fail("preview_disabled");
2598
+ const cfg = collection(col);
2599
+ if (!cfg.url) throw fail("no_public_url");
2600
+ const doc = await editable(actor, col, slug);
2601
+ const ttl = PREVIEW_TTLS[o.ttl ?? "24h"];
2602
+ if (!ttl) throw fail("invalid_request", { issues: `ttl: ${o.ttl}` });
2603
+ const exp = now().getTime() + ttl;
2604
+ const payload = b64url(JSON.stringify({ c: col, s: doc.slug, v: doc.version, exp, ...o.comments ? { cm: 1 } : {} }));
2605
+ const token = `${payload}.${sign(payload)}`;
2606
+ const base = cfg.url({ slug: doc.slug });
2607
+ audit(actor, "preview.create", { collection: col, slug: doc.slug, version: doc.version, detail: { ttl: o.ttl ?? "24h", comments: !!o.comments } });
2608
+ return { url: `${base}${base.includes("?") ? "&" : "?"}cms_preview=${token}`, token, version: doc.version, expiresAt: new Date(exp).toISOString() };
2609
+ }
2610
+ function previewPayload(token) {
2611
+ if (!opts.previewSecret) throw fail("preview_disabled");
2612
+ const [payload, sig] = String(token).split(".");
2613
+ const good = payload && sig ? Buffer.from(sign(payload)) : null;
2614
+ if (!good || good.length !== Buffer.from(sig).length || !timingSafeEqual(good, Buffer.from(sig))) throw fail("preview_invalid");
2615
+ let p;
2616
+ try {
2617
+ p = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
2618
+ } catch {
2619
+ throw fail("preview_invalid");
2620
+ }
2621
+ if (!(p.exp > now().getTime())) throw fail("preview_expired");
2622
+ return p;
2623
+ }
2624
+ async function readPreview(token) {
2625
+ const p = previewPayload(token);
2626
+ await ensureSchema();
2627
+ collection(p.c);
2628
+ const doc = await repo.findDoc(p.c, p.s);
2629
+ if (!doc) throw fail("not_found", { collection: p.c, slug: p.s });
2630
+ const v = await repo.getVersion(doc.id, p.v);
2631
+ if (!v) throw fail("version_not_found", { version: p.v });
2632
+ return { collection: p.c, slug: p.s, version: p.v, expiresAt: new Date(p.exp).toISOString(), doc: contentOf(v.snapshot), comments: !!p.cm };
2633
+ }
2634
+ const index = { built: null, dirty: true, stamp: "", checkedAt: 0, building: null };
2635
+ async function buildIndex() {
2636
+ const searchable = [...collections.values()].filter((c) => c.search?.enabled !== false).map((c) => c.slug);
2637
+ const docs = (await repo.listDocs({ published: true })).filter((d) => searchable.includes(d.collection));
2638
+ const units = docs.flatMap((d) => {
2639
+ const p = publicView(d);
2640
+ return p ? unitsOf({ ...p, publishedAt: p.publishedAt }) : [];
2641
+ });
2642
+ return new SearchIndex(units);
2643
+ }
2644
+ async function searchIndex() {
2645
+ const t = Date.now();
2646
+ if (index.built && !index.dirty && t - index.checkedAt > refreshMs) {
2647
+ index.checkedAt = t;
2648
+ const stamp = await repo.changeStamp().catch(() => index.stamp);
2649
+ if (stamp !== index.stamp) index.dirty = true;
2650
+ }
2651
+ if (index.built && !index.dirty) return index.built;
2652
+ if (!index.building) {
2653
+ index.dirty = false;
2654
+ index.building = (async () => {
2655
+ const stamp = await repo.changeStamp();
2656
+ const built = await buildIndex();
2657
+ index.built = built;
2658
+ index.stamp = stamp;
2659
+ index.checkedAt = Date.now();
2660
+ return built;
2661
+ })().catch((err) => {
2662
+ index.dirty = true;
2663
+ report(err, "searchIndex");
2664
+ if (index.built) return index.built;
2665
+ throw err;
2666
+ }).finally(() => {
2667
+ index.building = null;
2668
+ });
2669
+ }
2670
+ return index.building;
2671
+ }
2672
+ async function search(actor, cols, query, o = {}) {
2673
+ await ensureSchema();
2674
+ for (const c of cols) assert(actor, c, "read");
2675
+ if (o.logGap !== void 0) warnOnce("logGap", "search option logGap was renamed to reportMiss in 0.6.0");
2676
+ const reportMiss = o.reportMiss ?? o.logGap ?? false;
2677
+ const idx = await searchIndex();
2678
+ const limit = Math.max(1, Math.min(o.limit ?? 5, 50));
2679
+ const raw = idx.search(query, { limit: limit + 3, perDoc: o.perDoc ?? 2, filter: (u) => cols.includes(u.collection) && (!o.filter || o.filter(u)) });
2680
+ const hits = raw.filter((h) => h.coverage >= minCoverage).slice(0, limit);
2681
+ const empty = hits.length === 0;
2682
+ if (empty && reportMiss && opts.onSearchMiss && query.trim()) {
2683
+ const e = {
2684
+ query: query.trim().slice(0, 500),
2685
+ normalized: normalizeQuery(query) || query.trim().toLowerCase(),
2686
+ collections: [...cols],
2687
+ actor,
2688
+ source: actor.via ?? "app",
2689
+ at: nowIso(),
2690
+ nearest: raw.slice(0, 3).map((h) => ({ collection: h.unit.collection, slug: h.unit.slug, anchor: h.unit.anchor || null, score: Number(h.score.toFixed(3)), coverage: Number(h.coverage.toFixed(3)) }))
2691
+ };
2692
+ void Promise.resolve().then(() => opts.onSearchMiss(e)).catch((err) => report(err, "onSearchMiss"));
2693
+ }
2694
+ return { hits, empty };
2695
+ }
2696
+ async function recordHits(docIds, source = "app") {
2697
+ if (!docIds.length) return;
2698
+ await repo.addHits([...new Set(docIds)], dayIn(timeZone, now()), source).catch((e) => report(e, "recordHits"));
2699
+ }
2700
+ async function hitCounts(actor, col, days = 7) {
2701
+ assert(actor, col, "write");
2702
+ const since = addDays(dayIn(timeZone, now()), -(Math.max(1, days) - 1));
2703
+ return repo.hitCounts(since, col);
2704
+ }
2705
+ const isAdmin = (actor) => actor.kind === "system" || actor.kind === "user" && actor.isAdmin || actor.kind === "key" && actor.scopes.includes("admin");
2706
+ function assertKeyAdmin(actor) {
2707
+ if (!isAdmin(actor)) throw fail(actor.kind === "anonymous" ? "unauthorized" : "forbidden_keys");
2708
+ }
2709
+ const toKey = (k) => ({
2710
+ id: k.id,
2711
+ name: k.name,
2712
+ prefix: k.prefix,
2713
+ scopes: k.scopes,
2714
+ collections: k.collections,
2715
+ lastUsedAt: k.lastUsedAt,
2716
+ revokedAt: k.revokedAt,
2717
+ expiresAt: k.expiresAt ?? null,
2718
+ createdAt: k.createdAt
2719
+ });
2720
+ async function createKey(actor, input) {
2721
+ await ensureSchema();
2722
+ assertKeyAdmin(actor);
2723
+ const name = input.name.trim();
2724
+ if (!name || name.length > 60) throw fail("invalid_key_name");
2725
+ if (!input.scopes.length) throw fail("scopes_required");
2726
+ for (const c of input.collections ?? []) collection(c);
2727
+ let expiresAt = null;
2728
+ if (input.expiresAt) {
2729
+ const t = Date.parse(input.expiresAt);
2730
+ if (!Number.isFinite(t) || t <= now().getTime()) throw fail("invalid_expiry");
2731
+ expiresAt = new Date(t).toISOString();
2732
+ }
2733
+ if (actor.kind === "key") {
2734
+ if (input.scopes.some((s) => !actor.scopes.includes(s))) throw fail("key_too_wide");
2735
+ if (actor.collections) {
2736
+ const asked = input.collections?.length ? input.collections : null;
2737
+ if (!asked || asked.some((c) => !actor.collections.includes(c))) throw fail("key_too_wide");
2738
+ }
2739
+ }
2740
+ const raw = generateKey();
2741
+ const row = await repo.insertKey({
2742
+ name,
2743
+ prefix: displayPrefix(raw),
2744
+ hash: hashKey(raw),
2745
+ scopes: [...new Set(input.scopes)],
2746
+ collections: input.collections?.length ? input.collections : null,
2747
+ createdBy: actor.kind === "user" ? actor.id : null,
2748
+ expiresAt
2749
+ });
2750
+ audit(actor, "key.create", { detail: { key: row.id, name, scopes: row.scopes, collections: row.collections, expiresAt } });
2751
+ return { key: toKey(row), secret: raw };
2752
+ }
2753
+ async function listKeys(actor) {
2754
+ await ensureSchema();
2755
+ assertKeyAdmin(actor);
2756
+ return (await repo.listKeys()).map(toKey).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
2757
+ }
2758
+ async function revokeKey(actor, id) {
2759
+ assertKeyAdmin(actor);
2760
+ if (!await repo.revokeKey(id, nowIso())) throw fail("key_not_found");
2761
+ audit(actor, "key.revoke", { detail: { key: id } });
2762
+ }
2763
+ async function authenticateKey(raw) {
2764
+ await ensureSchema();
2765
+ const row = await repo.findKeyByHash(hashKey(raw));
2766
+ if (!row) return null;
2767
+ const at = now();
2768
+ const anon = { kind: "anonymous" };
2769
+ if (row.revokedAt) {
2770
+ audit(anon, "auth.failed", { outcome: "denied", detail: { key: row.id, reason: "revoked" } });
2771
+ return null;
2772
+ }
2773
+ if (row.expiresAt && Date.parse(row.expiresAt) <= at.getTime()) {
2774
+ audit(anon, "auth.failed", { outcome: "denied", detail: { key: row.id, reason: "expired" } });
2775
+ throw fail("key_expired", { expiresAt: row.expiresAt.slice(0, 10) });
2776
+ }
2777
+ if (!row.lastUsedAt || at.getTime() - Date.parse(row.lastUsedAt) > 5 * 6e4) {
2778
+ void repo.touchKey(row.id, at.toISOString()).catch((e) => report(e, "touchKey"));
2779
+ }
2780
+ return { kind: "key", id: row.id, label: row.name, scopes: row.scopes, collections: row.collections };
2781
+ }
2782
+ async function auditLog(actor, o = {}) {
2783
+ await ensureSchema();
2784
+ if (!isAdmin(actor)) throw fail(actor.kind === "anonymous" ? "unauthorized" : "forbidden_audit");
2785
+ const limit = Math.max(1, Math.min(o.limit ?? 50, 200));
2786
+ const entries = await repo.listAudit({ before: o.cursor ?? null, limit: limit + 1, action: o.action, outcome: o.outcome, actorKind: o.actorKind });
2787
+ const more = entries.length > limit;
2788
+ const page2 = entries.slice(0, limit);
2789
+ return { entries: page2, nextCursor: more ? `${page2[page2.length - 1].at}|${page2[page2.length - 1].id}` : null };
2790
+ }
2791
+ function message(e) {
2792
+ if (isCmsError(e)) return formatMessage(messages, e.code, e.params);
2793
+ return formatMessage(messages, "internal");
2794
+ }
2795
+ const flow = createFlow({
2796
+ repo,
2797
+ now,
2798
+ nowIso,
2799
+ fail,
2800
+ audit,
2801
+ actorRef,
2802
+ collection,
2803
+ collections: () => [...collections.values()],
2804
+ can,
2805
+ assert,
2806
+ isAdmin,
2807
+ ready: ensureSchema,
2808
+ editable,
2809
+ conflict,
2810
+ publishIn,
2811
+ unpublishIn,
2812
+ changed,
2813
+ problems: async (doc, c, r) => {
2814
+ const cfg = collection(doc.collection);
2815
+ return [...check(doc.collection, c).diagnostics, ...await assets.checkDoc(cfg, c, assets.idsIn(cfg, doc), r)];
2816
+ },
2817
+ needsReview,
2818
+ assertReviewed,
2819
+ summaryOf,
2820
+ message,
2821
+ report,
2822
+ trashDays,
2823
+ assets,
2824
+ previewPayload
2825
+ });
2826
+ return {
2827
+ collections: () => [...collections.values()],
2828
+ collection,
2829
+ can,
2830
+ isAdmin,
2831
+ get,
2832
+ list,
2833
+ page,
2834
+ counts,
2835
+ versions,
2836
+ versionList,
2837
+ version,
2838
+ diff,
2839
+ diagnose,
2840
+ create,
2841
+ update,
2842
+ patch,
2843
+ sections,
2844
+ autosave,
2845
+ discardAutosave,
2846
+ publish,
2847
+ archive,
2848
+ unarchive,
2849
+ unpublish,
2850
+ restore,
2851
+ remove,
2852
+ bulk,
2853
+ agentChanges,
2854
+ reviewChanges,
2855
+ createPreviewLink,
2856
+ readPreview,
2857
+ previewEnabled: () => !!opts.previewSecret,
2858
+ /** The zone days and schedules are shown in (`createCms({ timeZone })`, default UTC). */
2859
+ timeZone,
2860
+ search,
2861
+ recordHits,
2862
+ hitCounts,
2863
+ createKey,
2864
+ listKeys,
2865
+ revokeKey,
2866
+ authenticateKey,
2867
+ audit: auditLog,
2868
+ preview,
2869
+ needsReview,
2870
+ /** Publish (and/or unpublish) at a time; what goes out is the version that is current now. */
2871
+ schedule: flow.schedule,
2872
+ unschedule: flow.unschedule,
2873
+ /** Run everything whose time has come (the `/_cron` route calls this). */
2874
+ runScheduled: flow.runScheduled,
2875
+ cronSecret: opts.cronSecret ?? null,
2876
+ /** Deleted documents and files: `list`, `restore`, `purge`. */
2877
+ trash: { ...flow.trash, days: trashDays },
2878
+ requestReview: flow.requestReview,
2879
+ approveReview: flow.approveReview,
2880
+ rejectReview: flow.rejectReview,
2881
+ reviewRequests: flow.reviewRequests,
2882
+ comments: flow.comments,
2883
+ addComment: flow.addComment,
2884
+ resolveComment: flow.resolveComment,
2885
+ previewComments: flow.previewComments,
2886
+ addPreviewComment: flow.addPreviewComment,
2887
+ labelVersion: flow.labelVersion,
2888
+ /** Documents that go public together: `list`, `get`, `create`, `add`, `publish`, `schedule`… */
2889
+ releases: flow.releases,
2890
+ /** Named list filters: `list`, `save`, `remove`. */
2891
+ filters: flow.filters,
2892
+ /** Who has a document open: `touch`, `leave`, `in`. */
2893
+ presence: flow.presence,
2894
+ /** The media library (`createCms({ media })`). */
2895
+ assets,
2896
+ /** The files a document uses, by id: address, size, alt text. For rendering. */
2897
+ assetsFor: assets.assetsFor,
2898
+ /** An image's address at a width, through `media.imageUrl` when set. */
2899
+ imageUrl: assets.imageUrl,
2900
+ message,
2901
+ messages,
2902
+ /** Fails with `schema_outdated` when the database needs a migration. */
2903
+ checkSchema: async () => {
2904
+ await ensureSchema();
2905
+ },
2906
+ /** Warm the search index (e.g. at boot) so the first agent call is fast. */
2907
+ warm: async () => {
2908
+ await ensureSchema();
2909
+ await searchIndex();
2910
+ },
2911
+ onChange(fn) {
2912
+ listeners.add(fn);
2913
+ return () => listeners.delete(fn);
2914
+ },
2915
+ repo
2916
+ };
2917
+ }
2918
+ var coreOf = (c) => "core" in c && c.core ? c.core : c;
2919
+ function createCms(opts) {
2920
+ const core = createCmsCore(opts);
2921
+ return Object.assign(/* @__PURE__ */ Object.create(null), core, { core });
2922
+ }
2923
+
2924
+ export {
2925
+ imageSize,
2926
+ assetId,
2927
+ humanSize,
2928
+ assetFields,
2929
+ sectionRanges,
2930
+ applyPatch,
2931
+ keyFromHeader,
2932
+ normalizeQuery,
2933
+ defineCollection,
2934
+ SLUG_RE,
2935
+ LIMITS,
2936
+ dayIn,
2937
+ mergePatch,
2938
+ PREVIEW_TTLS,
2939
+ BULK_ACTIONS,
2940
+ createCmsCore,
2941
+ coreOf,
2942
+ createCms
2943
+ };