@lupinum/ginko-server 0.0.0-stage → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/LICENSE +21 -0
  3. package/README.md +176 -2
  4. package/convex/_generated/api.d.ts +185 -0
  5. package/convex/_generated/api.js +23 -0
  6. package/convex/_generated/dataModel.d.ts +60 -0
  7. package/convex/_generated/server.d.ts +162 -0
  8. package/convex/_generated/server.js +101 -0
  9. package/convex/account.ts +110 -0
  10. package/convex/agent.ts +814 -0
  11. package/convex/auth.config.ts +4 -0
  12. package/convex/auth.ts +62 -0
  13. package/convex/backup.ts +94 -0
  14. package/convex/betterAuth/_generated/api.ts +56 -0
  15. package/convex/betterAuth/_generated/component.ts +431 -0
  16. package/convex/betterAuth/_generated/dataModel.ts +60 -0
  17. package/convex/betterAuth/_generated/server.ts +169 -0
  18. package/convex/betterAuth/adapter.ts +7 -0
  19. package/convex/betterAuth/convex.config.ts +3 -0
  20. package/convex/betterAuth/schema.ts +102 -0
  21. package/convex/betterAuth/schemaMetadata.ts +697 -0
  22. package/convex/betterAuth/schemaOptions.ts +13 -0
  23. package/convex/betterAuth/schemaPlugins.ts +13 -0
  24. package/convex/bundle.ts +183 -0
  25. package/convex/changes.ts +136 -0
  26. package/convex/cleanup.ts +44 -0
  27. package/convex/connect.ts +143 -0
  28. package/convex/convex.config.ts +7 -0
  29. package/convex/crons.ts +14 -0
  30. package/convex/demo.ts +72 -0
  31. package/convex/entries.ts +1770 -0
  32. package/convex/facts.ts +129 -0
  33. package/convex/files.ts +631 -0
  34. package/convex/http.ts +21 -0
  35. package/convex/image.ts +45 -0
  36. package/convex/images.ts +54 -0
  37. package/convex/invites.ts +227 -0
  38. package/convex/lib/access.ts +180 -0
  39. package/convex/lib/agentTools.ts +331 -0
  40. package/convex/lib/content.ts +317 -0
  41. package/convex/lib/corpus.ts +83 -0
  42. package/convex/lib/diff.ts +50 -0
  43. package/convex/lib/fail.ts +27 -0
  44. package/convex/lib/files.ts +70 -0
  45. package/convex/lib/history.ts +103 -0
  46. package/convex/lib/i18n.ts +52 -0
  47. package/convex/lib/input.ts +57 -0
  48. package/convex/lib/library.ts +28 -0
  49. package/convex/lib/lifecycle.ts +100 -0
  50. package/convex/lib/list.ts +112 -0
  51. package/convex/lib/migrations.ts +126 -0
  52. package/convex/lib/names.ts +56 -0
  53. package/convex/lib/pending.ts +84 -0
  54. package/convex/lib/policy.ts +155 -0
  55. package/convex/lib/publicness.ts +87 -0
  56. package/convex/lib/reminders.ts +27 -0
  57. package/convex/lib/search.ts +132 -0
  58. package/convex/lib/siteUrl.ts +95 -0
  59. package/convex/lib/status.ts +109 -0
  60. package/convex/lib/translation.ts +56 -0
  61. package/convex/lib/trees.ts +43 -0
  62. package/convex/lib/write.ts +296 -0
  63. package/convex/mail.ts +136 -0
  64. package/convex/members.ts +129 -0
  65. package/convex/migrations.ts +105 -0
  66. package/convex/navigation.ts +276 -0
  67. package/convex/ops.ts +50 -0
  68. package/convex/proposals.ts +753 -0
  69. package/convex/refresh.ts +163 -0
  70. package/convex/release.ts +435 -0
  71. package/convex/reminders.ts +116 -0
  72. package/convex/retention.ts +121 -0
  73. package/convex/routes/bundle.ts +62 -0
  74. package/convex/routes/connect.ts +80 -0
  75. package/convex/routes/export.ts +23 -0
  76. package/convex/routes/file.ts +34 -0
  77. package/convex/routes/key.ts +53 -0
  78. package/convex/routes/mcp.ts +300 -0
  79. package/convex/routes/release.ts +66 -0
  80. package/convex/routes/upload.ts +94 -0
  81. package/convex/schema.ts +443 -0
  82. package/convex/search.ts +58 -0
  83. package/convex/seed.ts +624 -0
  84. package/convex/siteDeletion.ts +78 -0
  85. package/convex/sites.ts +393 -0
  86. package/convex/tasks.ts +51 -0
  87. package/convex/tsconfig.json +27 -0
  88. package/convex/uploads.ts +429 -0
  89. package/convex/uploadsNode.ts +86 -0
  90. package/convex/views.ts +111 -0
  91. package/i18n/de.json +364 -0
  92. package/i18n/en.json +364 -0
  93. package/i18n/es.json +364 -0
  94. package/i18n/fr.json +364 -0
  95. package/package.json +45 -3
@@ -0,0 +1,1770 @@
1
+ // Entry operations (SPEC 4.2). `save` is the reference for the shared flow of SPEC 4.1:
2
+ // actor → repeated op → load → may they → precondition → check → write → record op.
3
+ import type { Brick, CollectionBrick, Field, Fields, Json, Label, Locale } from '@lupinum/ginko'
4
+ import { blockedSlugs, effectiveMax, SLUG_PATTERN, entryBytes, fitsBudget, isNavTree, isTranslatable, labelOf as labelIn, leavesOf, listHaystack, listSort, deletesExpired, isVisible, liveFrom, ordered, resolveToken, searchable, sha256, slugBases, slugify, sortEntries, SITE_BUDGET, todayIn, uniqueSlug, urlsFor, validate, visibleUntil, weeklyTask, type Schema, type StoredEntry } from '@lupinum/ginko/internal'
5
+ import { paginationOptsValidator } from 'convex/server'
6
+ import { ConvexError, v, type ObjectType } from 'convex/values'
7
+ import type { Doc, Id } from './_generated/dataModel'
8
+ import { internal } from './_generated/api'
9
+ import { internalMutation, internalQuery, mutation, query, type MutationCtx, type QueryCtx } from './_generated/server'
10
+ import { actorFor, authorize, authorizeWriter, byOf, checkRev, createdBy, entryOf, fail, idempotent, SYSTEM, taskBrickOf, type Actor, type By } from './lib/access'
11
+ import { fieldLabelAt, fileIdsOf, mergeField, newOrder, nextPrints, refIdsIn, rootOf, treesOf, withoutLocale, type Data, type Prints } from './lib/content'
12
+ import { labeler, type Who } from './lib/names'
13
+ import { msg, recorded, undoBlockOf, type HistoryMsg, type Recorded } from './lib/history'
14
+ import { DEFAULT_LOCALE, isLocale, t, type MessageKey } from './lib/i18n'
15
+ import { dropPending, dropPendingRoots, keepsPending, overlay, pendingBySite, pendingInfo, pendingOf, syncPendingRefs, type Pending } from './lib/pending'
16
+ import { countersOf, DELETED_KEPT, overflowingTrash, purgeEntry, softRemove, storageSums, writeCounters, type Counters } from './lib/lifecycle'
17
+ import { directWriteRefused, needsProposal, propose, refuseAgentUndo, refuseDirectWrite } from './lib/policy'
18
+ import { publicness } from './lib/publicness'
19
+ import { translationNotes } from './lib/translation'
20
+ import { taskFor } from './lib/agentTools'
21
+ import { BUDGET, checkFiles, checkNewFiles, brokenNewLinks, checkNewLinks, commitEntry, entryUses, lookupsFor, overBudget, same, sizeText, syncEntryRefs, syncFileRefs, untrashFilesOf, uploadIdsOf } from './lib/write'
22
+ import { putTrees, readTreesJson } from './lib/trees'
23
+ import { advance, stepArgs } from './lib/migrations'
24
+ import { editorEntry, editorEntryWithTranslation, listRow, slimEntry, titleOf } from './lib/list'
25
+ import { diffFields, localeDiffs } from './lib/diff'
26
+
27
+ const underRoot = (leaf: string, root: string) => leaf === root || leaf.startsWith(`${root}.`)
28
+
29
+ function liveField(brick: Schema['bricks'][string], key: string): Field {
30
+ const field = Object.hasOwn(brick.fields, key) ? brick.fields[key] : undefined
31
+ if (!field || field.retired) fail('INVALID', 'errors.fieldNoLongerExists', { key }, { field: key })
32
+ return field
33
+ }
34
+
35
+ function brickOf(schema: Schema, entry: Doc<'entries'>) {
36
+ const brick = Object.hasOwn(schema.bricks, entry.brick) ? schema.bricks[entry.brick] : undefined
37
+ if (!brick || brick.retired) fail('INVALID', 'errors.brickNoLongerEditable')
38
+ return brick
39
+ }
40
+
41
+ function current(entry: Doc<'entries'>): Json {
42
+ return { entry: entry._id, rev: entry.rev, data: entry.data as Json, fieldRevs: entry.fieldRevs, deleted: !!entry.deletedAt }
43
+ }
44
+
45
+ /**
46
+ * Who made the newest change of each conflicting root, for the conflict panel ("anna@… hat „…“ hinzugefügt").
47
+ * Only the changes after the person's base are read, newest first, and only on this failing path.
48
+ */
49
+ async function conflictAuthors(ctx: QueryCtx, actor: Actor, entry: Doc<'entries'>, roots: string[], baseRev: number, held: Pending | null): Promise<Record<string, Who>> {
50
+ const names = await labeler(ctx, actor)
51
+ const by: Record<string, Who> = {}
52
+ const open = new Set(roots)
53
+ // A field saved as an unpublished change after the base has no history line yet: its saver is the last one.
54
+ for (const root of roots) {
55
+ if (held && (held.revs[root] ?? 0) > baseRev && open.delete(root)) by[root] = await names.who(held.by)
56
+ }
57
+ for await (const change of ctx.db.query('changes').withIndex('by_entry', (q) => q.eq('entry', entry._id)).order('desc')) {
58
+ if (!open.size || (change.entryRev !== undefined && change.entryRev <= baseRev)) break
59
+ for (const root of change.fields ?? []) {
60
+ if (!open.delete(root)) continue
61
+ by[root] = await names.who(change.actor)
62
+ }
63
+ }
64
+ return by
65
+ }
66
+
67
+ const saveArgs = {
68
+ site: v.string(),
69
+ opId: v.string(),
70
+ task: v.optional(v.string()),
71
+ entry: v.string(),
72
+ baseRev: v.number(),
73
+ /** Root field → value in storage format, or null to remove an optional field. A list is one field. */
74
+ fields: v.record(v.string(), v.any()),
75
+ /** Replace translatable values only in this locale; required with `confirm`. */
76
+ locale: v.optional(v.string()),
77
+ /** Leaf paths whose outdated translation in `locale` stays as is and counts as fresh. */
78
+ confirm: v.optional(v.array(v.string())),
79
+ /** Ignored: the server words the history line itself (`saveMsg`). Still accepted so older callers keep working. */
80
+ sentence: v.optional(v.string()),
81
+ /**
82
+ * true: a save of a live entry goes online at once instead of waiting as unpublished changes (a task's
83
+ * "Veröffentlichen", an assistant asked to publish). Only the saved fields go; other unpublished ones keep waiting.
84
+ */
85
+ publish: v.optional(v.literal(true)),
86
+ }
87
+
88
+ export const save = mutation({ args: saveArgs, handler: async (ctx, args) => saveAs(ctx, await actorFor(ctx, args.site), args) })
89
+
90
+ /** `save` for an actor already known: the platform's signed-in person, or the agent door's key (SPEC 16). */
91
+ export async function saveAs(ctx: MutationCtx, actor: Actor, args: ObjectType<typeof saveArgs>) {
92
+ checkRev(args.baseRev)
93
+ return idempotent(ctx, actor, args, () => saveNow(ctx, actor, args))
94
+ }
95
+
96
+ /**
97
+ * The languages a save changed when it changed only translations: the upper-case codes (as the diff tags them), or
98
+ * undefined when it changed the main language or a field that has no languages.
99
+ */
100
+ function onlyTranslations(schema: Schema, brick: Schema['bricks'][string], roots: string[], before: Data, after: Data): string | undefined {
101
+ const main = schema.locales[0]!
102
+ const changed = new Set<string>()
103
+ for (const root of roots) {
104
+ if (!isTranslatable(brick.fields[root]!)) return undefined
105
+ for (const { locale } of localeDiffs(before[root] ?? null, after[root] ?? null)) changed.add(locale)
106
+ }
107
+ if (!changed.size || changed.has(main)) return undefined
108
+ return schema.locales.filter((l) => changed.has(l)).map((l) => l.toUpperCase()).join(', ')
109
+ }
110
+
111
+ /**
112
+ * The history line of a save, built from what changed: "{brick}: {fields} changed" for a single,
113
+ * "{fields} changed in “{title}”" for an entry, with the languages in brackets when only translations changed.
114
+ * The field names are one label per locale, joined, so every reader gets their own language. The title is the
115
+ * entry's before the save, like the Studio showed it.
116
+ */
117
+ function saveMsg(schema: Schema, brick: Schema['bricks'][string], entry: Doc<'entries'>, roots: string[], after: Data, onlyConfirm: boolean): HistoryMsg {
118
+ if (onlyConfirm) return msg('history.translationConfirmed')
119
+ const main = schema.locales[0]!
120
+ const fields: Label = Object.fromEntries(schema.locales.map((l) => [l, roots.map((k) => labelIn(brick.fields[k]!.label, l, main)).join(', ')]))
121
+ const languages = onlyTranslations(schema, brick, roots, entry.data as Data, after)
122
+ if (brick.kind === 'single') return languages ? msg('history.changedSingleIn', { label: brick.label, fields, languages }) : msg('history.changedSingle', { label: brick.label, fields })
123
+ const title = labelOf(schema, entry.brick, entry.data as Data)
124
+ return languages ? msg('history.changedEntryIn', { fields, title, languages }) : msg('history.changedEntry', { fields, title })
125
+ }
126
+
127
+ /**
128
+ * The weekly task (`weeklyTask`, "this week's lunch") always covers the current week: a week start it writes must be
129
+ * today's work week in the site's time zone. Checked on every save, so a proposal made last week and approved after
130
+ * the week changed goes stale instead of moving the website's week.
131
+ */
132
+ function refuseOtherWeek(schema: Schema, task: string | undefined, taskBrick: string, fields: Record<string, unknown>) {
133
+ const brick = Object.hasOwn(schema.bricks, taskBrick) ? schema.bricks[taskBrick] : undefined
134
+ const weekly = brick ? weeklyTask(brick) : undefined
135
+ if (!weekly || task !== `${taskBrick}.${weekly.task.id}` || !Object.hasOwn(fields, weekly.field)) return
136
+ if (fields[weekly.field] !== resolveToken('@workWeek', schema.timeZone, schema.week)) fail('INVALID', 'errors.weeklyTaskThisWeek', undefined, { field: weekly.field })
137
+ }
138
+
139
+ /**
140
+ * A collection that plans a single ahead (`plans`) holds one entry per week: a second plan for the same week would
141
+ * never show (the site takes the first). Checked on every write that can put a plan on a week: create, save, restore
142
+ * and undo. `self` is the entry being written, `changed` its changed fields (a write that keeps the week is not
143
+ * checked); the trash does not count. A create or save is refused at the week field, so the Studio's form shows it
144
+ * there; a restore or undo has no form, so its message says it (`whole`).
145
+ */
146
+ async function refuseSecondPlan(ctx: QueryCtx, actor: Actor, brickKey: string, brick: Brick, data: Data, o: { self?: Id<'entries'>; changed?: readonly string[]; whole?: boolean } = {}) {
147
+ const field = brick.kind === 'collection' ? brick.plans?.field : undefined
148
+ if (!field || data[field] === undefined || (o.changed && !o.changed.includes(field))) return
149
+ const rows = await rowsOf(ctx, actor.site._id, brickKey)
150
+ if (!rows.some((r) => r._id !== o.self && !r.deletedAt && same((r.data as Data)[field], data[field]))) return
151
+ const issue = { path: field, code: 'weekAlreadyPlanned', key: 'errors.weekAlreadyPlanned', message: t(DEFAULT_LOCALE, 'errors.weekAlreadyPlanned') }
152
+ fail('INVALID', o.whole ? 'errors.weekAlreadyPlanned' : 'errors.pleaseCheckMarkedFields', undefined, { errors: [issue] })
153
+ }
154
+
155
+ /**
156
+ * The answer of a save or revert that had nothing to write: the entry as it is, and no history row. A named type, so
157
+ * the answers that wrote one keep `change` as a required field instead of an optional one (which JSON cannot hold).
158
+ */
159
+ type Unchanged = { entry: Id<'entries'>; rev: number; contentRev: number; warnings: Json[] }
160
+
161
+ /** The save itself, steps 3 to 7 of SPEC 4.1 without the repeated-op step: `revert` wraps it in its own and words the line (`line`). */
162
+ async function saveNow(ctx: MutationCtx, actor: Actor, args: ObjectType<typeof saveArgs>, line?: HistoryMsg) {
163
+ const entry = await entryOf(ctx, actor, args.entry)
164
+ const schema = actor.site.schema as Schema
165
+ const brick = brickOf(schema, entry)
166
+ const main = schema.locales[0]!
167
+ const locale = args.locale as Locale | undefined
168
+ if (locale !== undefined && !schema.locales.includes(locale)) fail('INVALID', 'errors.languageNotSetUp', { locale })
169
+ const confirm = args.confirm ?? []
170
+ if (confirm.length && (!locale || locale === main)) fail('INVALID', 'errors.confirmOnlyForForeignLanguage')
171
+
172
+ for (const key of Object.keys(args.fields)) {
173
+ if (liveField(brick, key).type === 'slug') fail('INVALID', 'errors.addressFixed', undefined, { field: key })
174
+ }
175
+ for (const leaf of confirm) liveField(brick, rootOf(leaf))
176
+ // Confirmed leaves count like a change of their root field: rights and conflicts (SPEC 3).
177
+ const roots = [...new Set([...Object.keys(args.fields), ...confirm.map(rootOf)])]
178
+ // A planned week is edited with the weekly task of the single it stands in for (`taskBrickOf`).
179
+ const taskBrick = taskBrickOf(schema, args.task, entry)
180
+ authorize(actor, schema, { task: args.task, brick: taskBrick, kind: 'edit', fields: roots, entry })
181
+ refuseOtherWeek(schema, args.task, taskBrick, args.fields)
182
+
183
+ if (entry.deletedAt) fail('CHANGED_SINCE', 'errors.thisEntryDeletedSince', undefined, current(entry))
184
+ // A base above the entry's revision was never read, so it cannot vouch for anything.
185
+ if (args.baseRev > entry.rev) fail('CHANGED_SINCE', 'errors.someoneChangedMeanwhile', undefined, current(entry))
186
+ const held = await pendingOf(ctx, entry._id)
187
+ const conflicts = roots.filter((r) => (entry.fieldRevs[r] ?? 0) > args.baseRev)
188
+ // The conflict panel shows what the Studio shows: unpublished changes over the live version.
189
+ if (conflicts.length) fail('CHANGED_SINCE', 'errors.someoneChangedMeanwhile', undefined, { ...(current(entry) as object), data: overlay(entry, held).data as Json, conflicts, by: await conflictAuthors(ctx, actor, entry, conflicts, args.baseRev, held) })
190
+
191
+ // A live entry keeps the save as unpublished changes (SPEC 15): the form showed them, so they are the base.
192
+ // "Show me first" (`forceProposal`) asks for a yes to go online, so it publishes once approved.
193
+ const publishNow = args.publish === true || actor.forceProposal === true
194
+ const toPending = keepsPending(entry) && !publishNow
195
+ // A navigation tree's place goes online at once and only through the tree (navigation.move): never into pending changes.
196
+ if (toPending && isNavTree(entry.brick, schema.bricks[entry.brick]!) && ['parent', 'section', 'tab'].some((k) => Object.hasOwn(args.fields, k))) fail('INVALID', 'errors.moveInNavigationTree')
197
+ const shown = overlay(entry, held)
198
+ // Published at once, the save writes over the website's version: the other fields stay as they are online.
199
+ const base = toPending ? shown : { data: entry.data as Data, prints: entry.prints }
200
+ const before = base.data
201
+ const data: Data = { ...before }
202
+ for (const [key, value] of Object.entries(args.fields)) {
203
+ const field = brick.fields[key]!
204
+ // The form's value (an unpublished one included) is what the input changed.
205
+ const was = shown.data[key]
206
+ // Cleared in a foreign language: only that language's value goes, the main language stays.
207
+ const merged = value === null
208
+ ? (locale && locale !== main && isTranslatable(field) ? withoutLocale(was, locale) : undefined)
209
+ : mergeField(field, was, value as Json, locale)
210
+ if (merged === undefined) delete data[key]
211
+ else data[key] = merged
212
+ }
213
+ const moved = locale !== undefined && locale !== main ? await foreignSlugs(ctx, actor, entry, brick, locale, before, data) : []
214
+ for (const leaf of confirm) {
215
+ if (!leavesOf(brick.fields[rootOf(leaf)]!, data[rootOf(leaf)], rootOf(leaf)).has(leaf)) fail('INVALID', 'errors.leafNotTranslatable', { leaf }, { leaf })
216
+ }
217
+ const prints = nextPrints({ fields: brick.fields, roots, before, after: data, prints: base.prints, main, confirm: confirm.length ? { locale: locale!, leaves: confirm } : undefined })
218
+
219
+ // A root counts as changed when its value or one of its prints changed.
220
+ const changed = roots.filter((r) => !same(data[r], before[r]) || !same(printsOf(prints, r), printsOf(base.prints, r)))
221
+ if (!changed.length) {
222
+ // Published as it is online: what waited for these fields is no longer wanted.
223
+ if (held && !toPending) await dropPendingRoots(ctx, schema, held, roots)
224
+ const unchanged: Unchanged = { entry: entry._id, rev: entry.rev, contentRev: actor.site.contentRev, warnings: [] }
225
+ return unchanged
226
+ }
227
+
228
+ const { errors, warnings } = await validate(schema, entry.brick, data, { mode: 'patch', changed: new Set(Object.keys(args.fields)), ...(await lookupsFor(ctx, actor.site._id, brick.fields, data)) })
229
+ if (errors.length) fail('INVALID', 'errors.pleaseCheckMarkedFields', undefined, { errors: errors as unknown as Json })
230
+ await refuseSecondPlan(ctx, actor, entry.brick, brick, data, { self: entry._id, changed })
231
+ await checkNewFiles(ctx, actor.site._id, brick.fields, before, data)
232
+ // A draft and unpublished changes are not online yet: their links are checked when they go live.
233
+ if (stateOf(entry) === 'live' && !toPending) await checkNewLinks(ctx, actor.site, [{ entry, fields: brick.fields, before, after: data }])
234
+
235
+ const onlyConfirm = Object.keys(args.fields).length === 0
236
+ // Nothing goes online: no proposal, no history line yet (publishing writes it).
237
+ // A foreign address made from a new title (`foreignSlugs`) waits with it; its row moves when it is published.
238
+ if (toPending) return await savePending(ctx, actor, { entry, held, roots: [...new Set([...changed, ...moved.map((m) => m.key)])], data, prints, warnings: warnings as unknown as Json })
239
+
240
+ const history = recorded(line ?? saveMsg(schema, brick, entry, changed, data, onlyConfirm), schema)
241
+
242
+ // Everything is checked: a change that needs a yes becomes a proposal and writes nothing (SPEC 17).
243
+ if (await needsProposal(ctx, actor, 'save', args.task, taskBrick, entry)) {
244
+ const pick = (d: Data) => Object.fromEntries(changed.filter((r) => d[r] !== undefined).map((r) => [r, d[r]!]))
245
+ return await propose(ctx, actor, {
246
+ op: 'save', brick: entry.brick, entry: entry._id, args: (publishNow ? { ...args, publish: true } : args) as unknown as Json,
247
+ base: { rev: entry.rev, fieldRevs: Object.fromEntries(changed.map((r) => [r, entry.fieldRevs[r] ?? 0])) },
248
+ before: pick(before) as Json, after: pick(data) as Json, ...history,
249
+ })
250
+ }
251
+
252
+ const written = await commitEntry(ctx, {
253
+ actor, entry, fields: brick.fields, roots: changed, data, prints,
254
+ kind: onlyConfirm ? 'confirm' : 'save', history, opId: args.opId,
255
+ })
256
+ if (moved.length) await moveSlugRows(ctx, actor, entry, locale!, moved)
257
+ // What is online now no longer waits; the other unpublished fields do.
258
+ if (held) await dropPendingRoots(ctx, schema, held, changed)
259
+ // What the other languages show now (the Studio's message after saving); a draft is not on the website.
260
+ const translation = stateOf(entry) === 'draft' ? [] : translationNotes(schema, entry.brick, { _id: entry._id, data, prints }, before, changed, locale)
261
+ // A week planned ahead or a planned price shows later than "in about a minute": the Studio says from when.
262
+ const from = stateOf(entry) === 'live' ? liveFrom(schema, entry.brick, data, changed, todayIn(schema.timeZone)) : undefined
263
+ return { entry: entry._id, rev: written.rev, contentRev: written.contentRev, change: written.change, warnings: warnings as unknown as Json, translation, ...(from ? { liveFrom: from } : {}) }
264
+ }
265
+
266
+ const printsOf = (p: Prints, root: string) => Object.fromEntries(Object.entries(p).filter(([leaf]) => underRoot(leaf, root)))
267
+
268
+ async function moveSlugRows(ctx: MutationCtx, actor: Actor, entry: Doc<'entries'>, locale: Locale, moved: { slug: string }[]) {
269
+ const rows = (await ctx.db.query('slugs').withIndex('by_entry', (q) => q.eq('entry', entry._id)).collect()).filter((r) => r.locale === locale && !r.old)
270
+ for (const { slug } of moved) {
271
+ // The slugs rows hold no field key: this pairs them by language only, which is exact while a brick has one slug field.
272
+ const row = rows.shift()
273
+ if (row) await ctx.db.patch(row._id, { slug })
274
+ else await ctx.db.insert('slugs', { site: actor.site._id, brick: entry.brick, locale, slug, entry: entry._id })
275
+ }
276
+ }
277
+
278
+ /**
279
+ * An owner or admin changes an entry's address in one language (decisions.md D35; a save never sends a slug, D9). When
280
+ * the entry has a page there, the old slug stays as an `old` row: still reserved, and the site forwards it with a 301
281
+ * (bundle `oldUrls`). Taking back one of its own old slugs makes that one current again.
282
+ */
283
+ export const changeSlug = mutation({
284
+ args: { site: v.string(), opId: v.string(), entry: v.string(), locale: v.string(), slug: v.string() },
285
+ handler: async (ctx, args) => {
286
+ const actor = await actorFor(ctx, args.site)
287
+ if (actor.role === 'staff') fail('FORBIDDEN', 'errors.ownersOnly')
288
+ return idempotent(ctx, actor, args, async () => {
289
+ const entry = await entryOf(ctx, actor, args.entry)
290
+ if (entry.deletedAt) fail('CHANGED_SINCE', 'errors.thisEntryDeletedSince', undefined, current(entry))
291
+ const schema = actor.site.schema as Schema
292
+ const brick = brickOf(schema, entry)
293
+ const locale = args.locale as Locale
294
+ if (!schema.locales.includes(locale)) fail('INVALID', 'errors.languageNotSetUp', { locale })
295
+ const key = Object.keys(brick.fields).find((k) => brick.fields[k]!.type === 'slug' && !brick.fields[k]!.retired)
296
+ if (brick.kind !== 'collection' || !brick.route?.[locale] || !key) fail('INVALID', 'errors.addressFixed')
297
+ const slug = args.slug.trim()
298
+ if (!SLUG_PATTERN.test(slug)) fail('INVALID', 'errors.addressFormat')
299
+ const before = entry.data as Data
300
+ const was = textOf(plainObject(before[key])[locale])
301
+ if (slug === was) return { entry: entry._id, rev: entry.rev, slug }
302
+ if ((await freeSlug(ctx, actor, entry.brick, locale, slug, entry._id)) !== slug) fail('INVALID', 'errors.addressTaken')
303
+
304
+ // A page that is online keeps its old address as a forward; one that is not (a draft, an untranslated language) just moves.
305
+ const online = stateOf(entry) === 'live' && !!urlsFor(schema, entry.brick, brick, { id: entry._id, data: before, prints: entry.prints as Prints })[locale]
306
+ const rows = (await ctx.db.query('slugs').withIndex('by_entry', (q) => q.eq('entry', entry._id)).collect()).filter((r) => r.locale === locale)
307
+ const currentRow = rows.find((r) => !r.old)
308
+ const back = rows.find((r) => r.old && r.slug === slug)
309
+ if (currentRow) {
310
+ if (online) await ctx.db.patch(currentRow._id, { old: true })
311
+ else await ctx.db.delete(currentRow._id)
312
+ }
313
+ if (back) await ctx.db.patch(back._id, { old: undefined })
314
+ else await ctx.db.insert('slugs', { site: actor.site._id, brick: entry.brick, locale, slug, entry: entry._id })
315
+
316
+ const data: Data = { ...before, [key]: { ...plainObject(before[key]), [locale]: slug } }
317
+ const history = recorded(msg('history.addressChanged', { title: labelOf(schema, entry.brick, data), from: was, to: slug }), schema)
318
+ const written = await commitEntry(ctx, { actor, entry, fields: brick.fields, roots: [key], data, prints: entry.prints as Prints, kind: 'save', history, opId: args.opId })
319
+ // Unpublished changes that hold the address would put the old one back when they are published.
320
+ const held = await pendingOf(ctx, entry._id)
321
+ if (held && Object.hasOwn(held.fields, key)) await ctx.db.patch(held._id, { fields: { ...held.fields, [key]: { ...plainObject(held.fields[key] as Json), [locale]: slug } } })
322
+ return { entry: entry._id, rev: written.rev, slug }
323
+ })
324
+ },
325
+ })
326
+
327
+ // ---- Unpublished changes (lib/pending.ts): saved, published, scheduled, discarded. ----
328
+
329
+ /**
330
+ * Keeps a checked save of a live entry as unpublished changes. The entry's rev and the fieldRevs of the roots move, so
331
+ * other open forms see a conflict as after any save; the content, its counters and the website stay as they are. A root
332
+ * saved back to its live value leaves the set, and an empty set leaves nothing behind.
333
+ */
334
+ async function savePending(ctx: MutationCtx, actor: Actor, w: { entry: Doc<'entries'>; held: Pending | null; roots: string[]; data: Data; prints: Prints; warnings: Json }) {
335
+ const { entry, held } = w
336
+ const site = actor.site
337
+ // The limits as if it were published, so publishing never fails on them; the bytes count once they are published.
338
+ const bytes = entryBytes(w.data, w.prints)
339
+ if (!fitsBudget(bytes, entry.bytes, BUDGET.entryBytes)) fail('TOO_LARGE', 'errors.entryTooLarge', overBudget(bytes, BUDGET.entryBytes))
340
+ const siteBytes = site.bytes - entry.bytes + bytes
341
+ if (!fitsBudget(siteBytes, site.bytes, BUDGET.siteBytes)) fail('TOO_LARGE', 'errors.siteStorageLimitReached', overBudget(siteBytes, BUDGET.siteBytes))
342
+
343
+ const rev = entry.rev + 1
344
+ const fields: Record<string, Json> = { ...held?.fields }
345
+ const revs: Record<string, number> = { ...held?.revs }
346
+ const prints: Prints = Object.fromEntries(Object.entries(held?.prints ?? {}).filter(([leaf]) => !w.roots.some((r) => underRoot(leaf, r))))
347
+ const live = entry.data as Data
348
+ for (const root of w.roots) {
349
+ if (same(w.data[root], live[root]) && same(printsOf(w.prints, root), printsOf(entry.prints, root))) {
350
+ delete fields[root]
351
+ delete revs[root]
352
+ continue
353
+ }
354
+ fields[root] = w.data[root] ?? null
355
+ revs[root] = rev
356
+ Object.assign(prints, printsOf(w.prints, root))
357
+ }
358
+ await bumpRevs(ctx, entry, w.roots)
359
+ const now = Date.now()
360
+ const pending = Object.keys(fields).length > 0
361
+ if (!pending) {
362
+ if (held) await dropPending(ctx, held)
363
+ } else {
364
+ if (held) await ctx.db.patch(held._id, { fields, prints, revs, by: actor.user.id, at: now })
365
+ else await ctx.db.insert('pendingChanges', { site: site._id, entry: entry._id, brick: entry.brick, fields, prints, revs, by: actor.user.id, since: now, at: now })
366
+ await syncPendingRefs(ctx, site.schema as Schema, { site: site._id, entry: entry._id, brick: entry.brick, fields })
367
+ }
368
+ return { entry: entry._id, rev, contentRev: site.contentRev, warnings: w.warnings, translation: [], pending }
369
+ }
370
+
371
+ /** Moves the entry's rev and the fieldRevs of `roots` without touching its content, so open forms see a conflict. */
372
+ async function bumpRevs(ctx: MutationCtx, entry: Doc<'entries'>, roots: string[]) {
373
+ const rev = entry.rev + 1
374
+ await ctx.db.patch(entry._id, { rev, fieldRevs: { ...entry.fieldRevs, ...Object.fromEntries(roots.map((r) => [r, rev])) } })
375
+ return rev
376
+ }
377
+
378
+ /**
379
+ * What publishing the unpublished changes writes, checked like a save that puts them live: no root changed online
380
+ * since it was saved (an undo, a revert or an older proposal), the values still fit the schema, files and links
381
+ * hold, and a foreign address is still free. Reads only, so a scheduled run can catch the refusal.
382
+ */
383
+ async function pendingPlan(ctx: MutationCtx, actor: Actor, entry: Doc<'entries'>, held: Pending) {
384
+ const schema = actor.site.schema as Schema
385
+ const brick = brickOf(schema, entry)
386
+ // In the form's order, for the history line.
387
+ const roots = Object.keys(held.fields).sort((a, b) => fieldOrder(brick, a) - fieldOrder(brick, b))
388
+ const moved = roots.filter((r) => (entry.fieldRevs[r] ?? 0) > (held.revs[r] ?? 0))
389
+ if (moved.length) fail('CHANGED_SINCE', 'errors.liveChangedMeanwhile', undefined, { ...(current(entry) as object), conflicts: moved })
390
+ const { data, prints } = overlay(entry, held)
391
+ const live = entry.data as Data
392
+ const { errors } = await validate(schema, entry.brick, data, { mode: 'patch', changed: new Set(roots), ...(await lookupsFor(ctx, actor.site._id, brick.fields, data)) })
393
+ if (errors.length) fail('INVALID', 'errors.pleaseCheckMarkedFields', undefined, { errors: errors as unknown as Json })
394
+ await refuseSecondPlan(ctx, actor, entry.brick, brick, data, { self: entry._id, changed: roots })
395
+ await checkNewFiles(ctx, actor.site._id, brick.fields, live, data)
396
+ await checkNewLinks(ctx, actor.site, [{ entry, fields: brick.fields, before: live, after: data }])
397
+ // A foreign address made while saving goes online now: still free, or the next free one.
398
+ const slugs: { locale: Locale; moved: { slug: string }[] }[] = []
399
+ for (const root of roots) {
400
+ const field = brick.fields[root]
401
+ if (field?.type !== 'slug') continue
402
+ const next = plainObject(data[root])
403
+ const was = plainObject(live[root])
404
+ for (const locale of schema.locales.slice(1)) {
405
+ const wanted = textOf(next[locale])
406
+ if (!wanted || wanted === textOf(was[locale])) continue
407
+ const slug = await freeSlug(ctx, actor, entry.brick, locale, wanted, entry._id)
408
+ data[root] = { ...plainObject(data[root]), [locale]: slug }
409
+ slugs.push({ locale, moved: [{ slug }] })
410
+ }
411
+ }
412
+ return { brick, roots, data, prints, slugs }
413
+ }
414
+
415
+ const fieldOrder = (brick: Brick, key: string) => {
416
+ const at = Object.keys(brick.fields).indexOf(key)
417
+ return at === -1 ? Number.MAX_SAFE_INTEGER : at
418
+ }
419
+
420
+ type PendingPlan = Awaited<ReturnType<typeof pendingPlan>>
421
+
422
+ /** Puts the unpublished changes online through the normal write path: one undoable change with the diff to the live version. */
423
+ async function applyPending(ctx: MutationCtx, actor: Actor, entry: Doc<'entries'>, held: Pending, plan: PendingPlan, history: Recorded, opId: string, running = false) {
424
+ const written = await commitEntry(ctx, { actor, entry, fields: plan.brick.fields, roots: plan.roots, data: plan.data, prints: plan.prints, kind: 'save', history, opId })
425
+ for (const s of plan.slugs) await moveSlugRows(ctx, actor, entry, s.locale, s.moved)
426
+ await dropPending(ctx, held, running)
427
+ return written
428
+ }
429
+
430
+ const pickRoots = (roots: string[], d: Data) => Object.fromEntries(roots.filter((r) => d[r] !== undefined).map((r) => [r, d[r]!]))
431
+
432
+ /** The field names of the unpublished changes, one label per language, for the history lines. */
433
+ function fieldsLabel(schema: Schema, brick: Brick, roots: string[]): Label {
434
+ const main = schema.locales[0]!
435
+ return Object.fromEntries(schema.locales.map((l) => [l, roots.map((k) => labelIn(brick.fields[k]!.label, l, main)).join(', ')]))
436
+ }
437
+
438
+ /** `publish` of a live entry: its unpublished changes, now or at `at`. `rev` (optional) is the version the person saw. */
439
+ async function publishPending(ctx: MutationCtx, actor: Actor, entry: Doc<'entries'>, args: ObjectType<typeof publishArgs>) {
440
+ const schema = actor.site.schema as Schema
441
+ const held = await pendingOf(ctx, entry._id)
442
+ if (!held) fail('INVALID', 'errors.entryAlreadyOnline', undefined, lifeStateOf(entry))
443
+ // Publishing puts every waiting field online: the person needs the right to change each of them, as for a save.
444
+ authorize(actor, schema, { task: args.task, brick: taskBrickOf(schema, args.task, entry), kind: 'edit', fields: Object.keys(held.fields), entry })
445
+ if (args.rev !== undefined && args.rev !== entry.rev) fail('CHANGED_SINCE', 'errors.entryChangedMeanwhile', undefined, lifeStateOf(entry))
446
+ const late = lapsed(actor, args.at)
447
+ const at = late ? undefined : args.at
448
+ if (at !== undefined) checkFuture(at)
449
+ const plan = await pendingPlan(ctx, actor, entry, held)
450
+ const title = labelOf(schema, entry.brick, entry.data as Data)
451
+ const fields = fieldsLabel(schema, plan.brick, plan.roots)
452
+
453
+ if (await needsProposal(ctx, actor, 'publish', args.task, entry.brick, entry)) {
454
+ return await propose(ctx, actor, {
455
+ op: 'publish', brick: entry.brick, entry: entry._id, args: { ...args, rev: entry.rev } as unknown as Json, base: { lifeRev: entry.lifeRev, rev: entry.rev },
456
+ before: pickRoots(plan.roots, entry.data as Data) as Json, after: pickRoots(plan.roots, plan.data) as Json,
457
+ ...recorded(at === undefined ? msg('history.publishChangesProposal', { title, fields }) : msg('history.publishChangesProposalScheduled', { title, fields, at }), schema),
458
+ })
459
+ }
460
+ if (at === undefined) {
461
+ const written = await applyPending(ctx, actor, entry, held, plan, recorded(msg(late ? 'history.publishedChangesLate' : 'history.publishedChanges', { title, fields }), schema), args.opId)
462
+ const translation = translationNotes(schema, entry.brick, { _id: entry._id, data: plan.data, prints: plan.prints }, entry.data as Data, plan.roots)
463
+ return { entry: entry._id, lifeRev: entry.lifeRev, rev: written.rev, contentRev: written.contentRev, change: written.change, state: 'live', translation }
464
+ }
465
+ // A new time replaces the old job, so the changes never go online at the old time.
466
+ if (held.publishJob) await ctx.scheduler.cancel(held.publishJob)
467
+ const publishJob = await ctx.scheduler.runAt(at, internal.entries.publishDue, { entry: entry._id, at })
468
+ await ctx.db.patch(held._id, { publishAt: at, publishJob })
469
+ const change = await ctx.db.insert('changes', {
470
+ site: actor.site._id, entry: entry._id, brick: entry.brick, ...byOf(actor), opId: args.opId, kind: 'schedule',
471
+ ...recorded(msg('history.changesScheduled', { title, at }), schema), entryRev: entry.rev, contentRev: actor.site.contentRev, at: Date.now(),
472
+ })
473
+ return { entry: entry._id, lifeRev: entry.lifeRev, rev: entry.rev, contentRev: actor.site.contentRev, change, state: 'live', publishAt: at, translation: [] }
474
+ }
475
+
476
+ /** The scheduled run of unpublished changes: applies them as the system, or stops with a history line that says why. */
477
+ async function publishPendingDue(ctx: MutationCtx, entry: Doc<'entries'>, at: number) {
478
+ const held = await pendingOf(ctx, entry._id)
479
+ if (!held || held.publishAt !== at) return
480
+ const site = await ctx.db.get(entry.site)
481
+ if (!site || site.deleting) return
482
+ const actor: Actor = { user: { id: SYSTEM.actor }, site, role: 'admin', grants: [] }
483
+ const schema = site.schema as Schema
484
+ const title = labelOf(schema, entry.brick, entry.data as Data)
485
+ const opId = `publish:${entry._id}:${at}`
486
+ let plan: PendingPlan
487
+ try {
488
+ plan = await pendingPlan(ctx, actor, entry, held)
489
+ } catch (error) {
490
+ // A throwing job would fail silently: the changes stay unpublished and the history says why.
491
+ if (!(error instanceof ConvexError) || typeof error.data !== 'object' || error.data === null) throw error
492
+ const data = error.data as { key?: string; params?: Record<string, string | number> }
493
+ const why = data.key ? msg(data.key as MessageKey, data.params) : msg('history.staleNoLonger')
494
+ await ctx.db.patch(held._id, { publishAt: undefined, publishJob: undefined })
495
+ await ctx.db.insert('changes', {
496
+ site: entry.site, entry: entry._id, brick: entry.brick, ...SYSTEM, opId, kind: 'publishStopped',
497
+ ...recorded(msg('history.changesPublishStopped', { title, why }), schema), entryRev: entry.rev, contentRev: site.contentRev, at: Date.now(),
498
+ })
499
+ return
500
+ }
501
+ await applyPending(ctx, actor, entry, held, plan, recorded(msg('history.publishedChangesDue', { title, fields: fieldsLabel(schema, plan.brick, plan.roots) }), schema), opId, true)
502
+ }
503
+
504
+ const discardArgs = { site: v.string(), opId: v.string(), task: v.optional(v.string()), entry: v.string(), rev: v.optional(v.number()) }
505
+
506
+ export const discard = mutation({ args: discardArgs, handler: async (ctx, args) => discardAs(ctx, await actorFor(ctx, args.site), args) })
507
+
508
+ /**
509
+ * Verwerfen: the unpublished changes go, the live version stays. Needs the right to change those fields, no yes (nothing
510
+ * online changes). `rev`: the version the person saw, so a newer save of someone else is not thrown away unseen.
511
+ */
512
+ export async function discardAs(ctx: MutationCtx, actor: Actor, args: ObjectType<typeof discardArgs>) {
513
+ if (args.rev !== undefined) checkRev(args.rev)
514
+ return idempotent(ctx, actor, args, async () => {
515
+ const entry = await entryOf(ctx, actor, args.entry)
516
+ const schema = actor.site.schema as Schema
517
+ const held = await pendingOf(ctx, entry._id)
518
+ if (!held) fail('INVALID', 'errors.noUnpublishedChanges')
519
+ const roots = Object.keys(held.fields)
520
+ authorize(actor, schema, { task: args.task, brick: taskBrickOf(schema, args.task, entry), kind: 'edit', fields: roots, entry })
521
+ if (args.rev !== undefined && args.rev !== entry.rev) fail('CHANGED_SINCE', 'errors.someoneChangedMeanwhile', undefined, current(entry))
522
+ await dropPending(ctx, held)
523
+ // Open forms that show the unpublished values see a conflict, as after a save.
524
+ const rev = await bumpRevs(ctx, entry, roots)
525
+ const change = await ctx.db.insert('changes', {
526
+ site: actor.site._id, entry: entry._id, brick: entry.brick, ...byOf(actor), opId: args.opId, kind: 'discard',
527
+ ...recorded(msg('history.changesDiscarded', { title: labelOf(schema, entry.brick, entry.data as Data) }), schema), entryRev: rev, contentRev: actor.site.contentRev, at: Date.now(),
528
+ })
529
+ return { entry: entry._id, rev, change }
530
+ })
531
+ }
532
+
533
+ const undoArgs = { site: v.string(), opId: v.string(), task: v.optional(v.string()), change: v.string() }
534
+
535
+ export const undo = mutation({ args: undoArgs, handler: async (ctx, args) => undoAs(ctx, await actorFor(ctx, args.site), args) })
536
+
537
+ /** `undo` for an actor already known: the platform's signed-in person, or the agent door's key (SPEC 16). */
538
+ export async function undoAs(ctx: MutationCtx, actor: Actor, args: ObjectType<typeof undoArgs>): Promise<Json> {
539
+ return idempotent(ctx, actor, args, async () => {
540
+ const changeId = ctx.db.normalizeId('changes', args.change)
541
+ const change = changeId ? await ctx.db.get(changeId) : null
542
+ if (!change || change.site !== actor.site._id) fail('NOT_FOUND', 'errors.changeNotFound')
543
+ // Structural changes (remove, restore, reorder) and releases are not undoable (SPEC 4.2).
544
+ if (change.kind !== 'save' || !change.entry) fail('NOT_UNDOABLE', 'errors.changeNotUndoable')
545
+ const entry = await entryOf(ctx, actor, change.entry)
546
+ const schema = actor.site.schema as Schema
547
+ const brick = brickOf(schema, entry)
548
+ const roots = change.fields ?? []
549
+ const taskBrick = taskBrickOf(schema, args.task, entry)
550
+ authorize(actor, schema, { task: args.task, brick: taskBrick, kind: 'edit', fields: roots, entry })
551
+ refuseDirectWrite(actor, taskBrick, args.task)
552
+ await refuseAgentUndo(ctx, actor, entry)
553
+
554
+ const migrated = await ctx.db.query('migrationsApplied').withIndex('by_site_id', (q) => q.eq('site', actor.site._id)).collect()
555
+ const block = undoBlockOf(change, entry, migrated)
556
+ if (block === 'undone') fail('NOT_UNDOABLE', 'errors.changeNotUndoable')
557
+ if (block === 'removed') fail('NOT_UNDOABLE', 'errors.entryDeletedSince')
558
+ if (block === 'changed') fail('CHANGED_SINCE', 'errors.someoneChangedMeanwhileNoUndo', undefined, current(entry))
559
+ if (block === 'schema') fail('NOT_UNDOABLE', 'errors.schemaChangedSinceChange')
560
+
561
+ // Values and prints come back exactly; an undo never confirms a translation.
562
+ const before = (change.before ?? {}) as Data
563
+ const data: Data = { ...(entry.data as Data) }
564
+ for (const root of roots) {
565
+ liveField(brick, root)
566
+ if (before[root] === undefined) delete data[root]
567
+ else data[root] = before[root]!
568
+ }
569
+ const prints: Prints = Object.fromEntries(Object.entries(entry.prints).filter(([leaf]) => !roots.some((r) => underRoot(leaf, r))))
570
+ Object.assign(prints, (change.printsBefore ?? {}) as Prints)
571
+
572
+ const restoredFiles = await untrashFilesOf(ctx, actor.site._id, brick.fields, entry.data as Data, data)
573
+ const { errors } = await validate(schema, entry.brick, data, { mode: 'patch', changed: new Set(roots), ...(await lookupsFor(ctx, actor.site._id, brick.fields, data)) })
574
+ if (errors.length) fail('NOT_UNDOABLE', 'errors.oldVersionNoLongerFitsSchema', undefined, { errors: errors as unknown as Json })
575
+ // Moving a plan back to a week that was planned again since would hide one of the two.
576
+ await refuseSecondPlan(ctx, actor, entry.brick, brick, data, { self: entry._id, changed: roots, whole: true })
577
+ await checkNewFiles(ctx, actor.site._id, brick.fields, entry.data as Data, data)
578
+ if (stateOf(entry) === 'live') await checkNewLinks(ctx, actor.site, [{ entry, fields: brick.fields, before: entry.data as Data, after: data }])
579
+
580
+ const written = await commitEntry(ctx, {
581
+ actor, entry, fields: brick.fields, roots, data, prints, kind: 'undo', history: recorded(msg('history.undo', { what: change.msg ? (change.msg as HistoryMsg) : change.sentence }), schema), opId: args.opId,
582
+ })
583
+ await ctx.db.patch(change._id, { undoneBy: written.change })
584
+ const result: Json = { entry: entry._id, rev: written.rev, contentRev: written.contentRev, warnings: [], ...(restoredFiles.length ? { restoredFiles: restoredFiles.map((f) => f.name) } : {}) }
585
+ return result
586
+ })
587
+ }
588
+
589
+ // ---- Verlauf (SPEC 4.2): an earlier version of an entry, and going back to it. ----
590
+
591
+ /**
592
+ * The entry's field values right after `changeId`. Per field, the earliest later change of this entry
593
+ * that touched it gives the value through its `before`; a field no later change touched keeps its
594
+ * current live value. `touched` lists the fields that a later change touched or that wait as unpublished changes
595
+ * (the only ones that can differ). `now` is what the Studio shows: the live values under the unpublished changes.
596
+ */
597
+ async function versionOf(ctx: QueryCtx, actor: Actor, entryId: string, changeId: string) {
598
+ const entry = await entryOf(ctx, actor, entryId)
599
+ const id = ctx.db.normalizeId('changes', changeId)
600
+ const change = id ? await ctx.db.get(id) : null
601
+ // A change older than the retention window is gone (SPEC 12): then there is no such version.
602
+ if (!change || change.site !== actor.site._id || change.entry !== entry._id) fail('NOT_FOUND', 'errors.versionNotFound')
603
+ // The index lists the entry's changes oldest first; "later" is what follows the requested one.
604
+ const all = await ctx.db.query('changes').withIndex('by_entry', (q) => q.eq('entry', entry._id)).collect()
605
+ const later = all.slice(all.findIndex((c) => c._id === change._id) + 1)
606
+ const data: Data = { ...(entry.data as Data) }
607
+ const touched = new Set<string>()
608
+ for (const c of later) {
609
+ const before = (c.before ?? {}) as Data
610
+ for (const root of c.fields ?? []) {
611
+ if (touched.has(root)) continue
612
+ touched.add(root)
613
+ if (before[root] === undefined) delete data[root]
614
+ else data[root] = before[root]
615
+ }
616
+ }
617
+ const held = await pendingOf(ctx, entry._id)
618
+ for (const root of Object.keys(held?.fields ?? {})) touched.add(root)
619
+ return { entry, change, data, touched: [...touched], now: overlay(entry, held).data }
620
+ }
621
+
622
+ /**
623
+ * What going back to `data` writes: the touched fields whose value differs from now (`null` removes one), without
624
+ * the address (it is fixed), fields the schema no longer has, and a navigation tree's place fields: a move changes
625
+ * several pages at once, so only the tree moves a page (navigation.move); one page's old place would split a section
626
+ * or nest a page inside its own subpages.
627
+ */
628
+ function revertFields(key: string, brick: Brick | undefined, touched: string[], data: Data, now: Data): Record<string, Json> {
629
+ const fields: Record<string, Json> = {}
630
+ const place = brick && isNavTree(key, brick) ? new Set(['parent', 'section', 'tab']) : undefined
631
+ for (const root of touched) {
632
+ const field = brick && Object.hasOwn(brick.fields, root) ? brick.fields[root] : undefined
633
+ if (!field || field.retired || field.type === 'slug' || place?.has(root)) continue
634
+ if (!same(data[root], now[root])) fields[root] = data[root] ?? null
635
+ }
636
+ return fields
637
+ }
638
+
639
+ /**
640
+ * What a revert through `task` writes: `revertFields`, minus the week a weekly task is fixed to. Through the weekly task
641
+ * the version's values come back for this week: the task always covers it (`refuseOtherWeek`). `revert` saves exactly
642
+ * these and `versionAt` shows exactly these, so the preview never promises a week change the save will not make.
643
+ */
644
+ function revertWrites(schema: Schema, entry: Doc<'entries'>, touched: string[], data: Data, now: Data, task: string | undefined): Record<string, Json> {
645
+ const brick = Object.hasOwn(schema.bricks, entry.brick) ? schema.bricks[entry.brick] : undefined
646
+ const fields = revertFields(entry.brick, brick, touched, data, now)
647
+ const taskBrick = taskBrickOf(schema, task, entry)
648
+ const weekly = Object.hasOwn(schema.bricks, taskBrick) ? weeklyTask(schema.bricks[taskBrick]!) : undefined
649
+ if (weekly && task === `${taskBrick}.${weekly.task.id}`) delete fields[weekly.field]
650
+ return fields
651
+ }
652
+
653
+ /**
654
+ * The entry right after a change (`data`; `fields` names the ones a later change touched), plus `diff`: what going
655
+ * back to it changes, field by field, with now as `before` and that version as `after`. Empty: it is the current
656
+ * version. One answer for the Studio (`versionAt`, shown before the person confirms) and the agent door
657
+ * (`ginko_version_at`), for an actor already known (SPEC 16). With the `task` the revert will use, the diff leaves out
658
+ * what that task keeps (the week of the weekly task, `revertWrites`).
659
+ */
660
+ export async function versionAtAs(ctx: QueryCtx, actor: Actor, args: { entry: string; change: string; task?: string | undefined }) {
661
+ const { entry, change, data, touched, now } = await versionOf(ctx, actor, args.entry, args.change)
662
+ const schema = actor.site.schema as Schema
663
+ const brick = Object.hasOwn(schema.bricks, entry.brick) ? schema.bricks[entry.brick] : undefined
664
+ const fields = revertWrites(schema, entry, touched, data, now, args.task)
665
+ const pick = (from: Data) => Object.fromEntries(Object.keys(fields).filter((root) => from[root] !== undefined).map((root) => [root, from[root]!]))
666
+ return { entry: entry._id, change: change._id, at: change.at, data, fields: touched, diff: diffFields(brick?.fields, pick(now), pick(data), schema.locales[0]!) }
667
+ }
668
+
669
+ export const versionAt = query({
670
+ args: { site: v.string(), task: v.optional(v.string()), entry: v.string(), change: v.string() },
671
+ handler: async (ctx, args) => versionAtAs(ctx, await actorFor(ctx, args.site), args),
672
+ })
673
+
674
+ const revertArgs = { site: v.string(), opId: v.string(), task: v.optional(v.string()), entry: v.string(), change: v.string() }
675
+
676
+ export const revert = mutation({ args: revertArgs, handler: async (ctx, args) => revertAs(ctx, await actorFor(ctx, args.site), args) })
677
+
678
+ /**
679
+ * Goes back to the version after `change` as a new, normal save: rights, validation, prints, file
680
+ * references, proposals and undo all apply. Only fields that differ from now are written. Like undo it goes online at
681
+ * once (D60): going back is a repair of what the website shows; those fields leave any unpublished changes.
682
+ */
683
+ export async function revertAs(ctx: MutationCtx, actor: Actor, args: ObjectType<typeof revertArgs>) {
684
+ return idempotent(ctx, actor, args, async () => {
685
+ const { entry, change, data, touched, now } = await versionOf(ctx, actor, args.entry, args.change)
686
+ if (entry.deletedAt) fail('INVALID', 'errors.entryDeletedRestoreFirst')
687
+ const schema = actor.site.schema as Schema
688
+ const brick = brickOf(schema, entry)
689
+ const fields = revertWrites(schema, entry, touched, data, now, args.task)
690
+ if (!Object.keys(fields).length) {
691
+ const unchanged: Unchanged = { entry: entry._id, rev: entry.rev, contentRev: actor.site.contentRev, warnings: [] }
692
+ return unchanged
693
+ }
694
+ // Out of the trash before the save, so its file checks pass.
695
+ const restoredFiles = await untrashFilesOf(ctx, actor.site._id, brick.fields, now, { ...now, ...fields })
696
+ const saved = await saveNow(ctx, actor, {
697
+ site: args.site, opId: args.opId, ...(args.task === undefined ? {} : { task: args.task }),
698
+ entry: entry._id, baseRev: entry.rev, fields, publish: true,
699
+ }, msg('history.revert', { when: change.at }))
700
+ // A revert that needs a yes writes nothing, so the files go back to the trash: taking a file out of it is the
701
+ // owner's step (files.restore). The approval then refuses until someone restored the file.
702
+ if ('proposal' in saved) {
703
+ for (const file of restoredFiles) await ctx.db.patch(file.id, { trashedAt: file.trashedAt })
704
+ return saved
705
+ }
706
+ return restoredFiles.length ? { ...saved, restoredFiles: restoredFiles.map((f) => f.name) } : saved
707
+ })
708
+ }
709
+
710
+ // ---- Structural operations (SPEC 4.2): create, remove, restore, move. ----
711
+ // They follow the flow of SPEC 4.1 like `save`. The site's counters (`Counters` in lib/lifecycle.ts)
712
+ // are changed in memory and written back once at the end.
713
+
714
+ const plainObject = (value: Json | undefined): Record<string, Json> =>
715
+ typeof value === 'object' && value !== null && !Array.isArray(value) ? value : {}
716
+
717
+ const textOf = (value: Json | undefined): string => (typeof value === 'string' ? value : '')
718
+
719
+ /**
720
+ * Label of an entry for history lines, proposals, search hits and file uses: its title as the Studio shows it (core
721
+ * `entryTitle`, so a planned week is "Woche ab 19.10.2026"), else the brick's label, in the main language.
722
+ */
723
+ export function labelOf(schema: Schema, brickKey: string, data: Data): string {
724
+ const brick = Object.hasOwn(schema.bricks, brickKey) ? schema.bricks[brickKey] : undefined
725
+ if (!brick) return brickKey
726
+ const main = schema.locales[0]!
727
+ return titleOf(schema, brick, data, undefined) ?? labelIn(brick.label, main, main)
728
+ }
729
+
730
+ function structuralBrick(schema: Schema, key: string): CollectionBrick {
731
+ const brick = Object.hasOwn(schema.bricks, key) ? schema.bricks[key] : undefined
732
+ if (!brick || brick.retired) fail('INVALID', 'errors.brickNoLongerEditable')
733
+ if (brick.kind !== 'collection') fail('INVALID', 'errors.brickNotCollection', undefined, { brick: key })
734
+ return brick
735
+ }
736
+
737
+ /** Every row of a brick in order, deleted ones included: their order values stay in use. */
738
+ function rowsOf(ctx: QueryCtx, site: Id<'sites'>, brick: string) {
739
+ return ctx.db.query('entries').withIndex('by_site_brick_order', (q) => q.eq('site', site).eq('brick', brick)).collect()
740
+ }
741
+
742
+ const stateOf = (entry: Doc<'entries'>) => entry.state ?? 'live'
743
+
744
+ /** What the UI needs to show an entry's place in its life: deleted, draft, scheduled or live (SPEC 15). */
745
+ const lifeStateOf = (entry: Doc<'entries'>): Json => ({
746
+ entry: entry._id, lifeRev: entry.lifeRev, deleted: !!entry.deletedAt, state: stateOf(entry),
747
+ ...(entry.publishAt === undefined ? {} : { publishAt: entry.publishAt }),
748
+ })
749
+
750
+ /**
751
+ * The first free slug from `base` in one brick and locale: not used by another entry of the brick (removed ones keep
752
+ * theirs until they are deleted for good), and no URL of a static page or of another brick's entry. `own` is the entry
753
+ * the slug is for: its own slug in that locale is free for it.
754
+ */
755
+ async function freeSlug(ctx: MutationCtx, actor: Actor, brick: string, locale: Locale, base: string, own?: Id<'entries'>) {
756
+ const schema = actor.site.schema as Schema
757
+ const rowsOf = (key: string) => ctx.db.query('slugs').withIndex('by_key', (q) => q.eq('site', actor.site._id).eq('brick', key).eq('locale', locale)).collect()
758
+ const taken = new Set((await rowsOf(brick)).filter((r) => r.entry !== own).map((r) => r.slug))
759
+ // Other bricks and static pages may own the URL this slug would make.
760
+ const others: Record<string, string[]> = {}
761
+ for (const [key, other] of Object.entries(schema.bricks)) if (key !== brick && other.kind === 'collection' && other.route) others[key] = (await rowsOf(key)).map((r) => r.slug)
762
+ for (const slug of blockedSlugs(schema, brick, locale, others)) taken.add(slug)
763
+ return uniqueSlug(base, (s) => taken.has(s))
764
+ }
765
+
766
+ /**
767
+ * Slugs of a new entry (SPEC 2.2): per locale from its `from` field, unique in the brick and
768
+ * locale. A missing foreign value takes the main-language slug of the same entry until the
769
+ * translated title is saved (`foreignSlugs`).
770
+ */
771
+ async function slugsFor(ctx: MutationCtx, actor: Actor, brick: string, fields: Fields, data: Data) {
772
+ const schema = actor.site.schema as Schema
773
+ const main = schema.locales[0]!
774
+ const out: Data = { ...data }
775
+ const rows: { locale: string; slug: string }[] = []
776
+ for (const [name, field] of Object.entries(fields)) {
777
+ if (field.type !== 'slug') continue
778
+ const from = plainObject(data[field.from])
779
+ const bases = slugBases(schema.locales, Object.fromEntries(schema.locales.map((locale) => [locale, textOf(from[locale])])))
780
+ const made: Record<string, string> = {}
781
+ for (const locale of schema.locales) {
782
+ made[locale] = await freeSlug(ctx, actor, brick, locale, bases[locale] ?? made[main]!)
783
+ }
784
+ out[name] = made
785
+ for (const [locale, slug] of Object.entries(made)) rows.push({ locale, slug })
786
+ }
787
+ return { data: out, slugs: rows }
788
+ }
789
+
790
+ /**
791
+ * A foreign address comes from the translated title (SPEC 2.2, decisions.md): an entry made in the main language has
792
+ * the main slug in every other language. While the entry has no page in `locale`, a new title there makes its slug
793
+ * there anew; once the page is online, its address stays. The main slug never changes. Writes into `data` and returns
794
+ * the new slugs, whose rows the caller moves once the save is written.
795
+ */
796
+ async function foreignSlugs(ctx: MutationCtx, actor: Actor, entry: Doc<'entries'>, brick: Schema['bricks'][string], locale: Locale, before: Data, data: Data) {
797
+ const schema = actor.site.schema as Schema
798
+ const made: { key: string; slug: string }[] = []
799
+ if (brick.kind !== 'collection' || !brick.route?.[locale]) return made
800
+ if (urlsFor(schema, entry.brick, brick, { id: entry._id, data: before, prints: entry.prints as Prints })[locale]) return made
801
+ for (const [key, field] of Object.entries(brick.fields)) {
802
+ if (field.type !== 'slug' || field.retired) continue
803
+ const from = Object.hasOwn(brick.fields, field.from) ? brick.fields[field.from]! : undefined
804
+ if (!from || from.retired || !isTranslatable(from)) continue
805
+ const title = textOf(plainObject(data[field.from])[locale])
806
+ if (!title || title === textOf(plainObject(before[field.from])[locale])) continue
807
+ const slug = await freeSlug(ctx, actor, entry.brick, locale, slugify(title), entry._id)
808
+ if (slug === plainObject(data[key])[locale]) continue
809
+ data[key] = { ...plainObject(data[key]), [locale]: slug }
810
+ made.push({ key, slug })
811
+ }
812
+ return made
813
+ }
814
+
815
+ /**
816
+ * Room for one more live entry in a collection (SPEC 4.2 create). Returns the expired entries
817
+ * to remove first, oldest order first; fails when the collection is full and nothing expired.
818
+ */
819
+ function roomPlan(actor: Actor, brick: CollectionBrick, rows: Doc<'entries'>[]): Doc<'entries'>[] {
820
+ const live = rows.filter((r) => !r.deletedAt)
821
+ if (live.length < brick.max) return []
822
+ const need = live.length - brick.max + 1
823
+ const today = todayIn((actor.site.schema as Schema).timeZone)
824
+ // A draft is never expired: it is not published yet (SPEC 15). It still takes a place in `max`.
825
+ const expired = deletesExpired(brick) ? live.filter((r) => r.state !== 'draft' && !isVisible(brick as Brick, r.data, today)) : []
826
+ if (expired.length < need) fail('INVALID', 'errors.collectionFull', { max: brick.max }, { max: brick.max })
827
+ return expired.slice(0, need)
828
+ }
829
+
830
+ const createArgs = {
831
+ site: v.string(),
832
+ opId: v.string(),
833
+ task: v.optional(v.string()),
834
+ brick: v.string(),
835
+ /** Stored-format values of the whole entry; list rows carry their `_id`s. Slugs are set by the server. */
836
+ data: v.record(v.string(), v.any()),
837
+ /**
838
+ * Only for a collection with `drafts` (SPEC 15). Absent: a draft. `{}`: live at once.
839
+ * `{ at }`: a draft that goes online at `at` (ms). Ignored for a collection without `drafts`.
840
+ */
841
+ publish: v.optional(v.object({ at: v.optional(v.number()) })),
842
+ }
843
+
844
+ export const create = mutation({ args: createArgs, handler: async (ctx, args) => createAs(ctx, await actorFor(ctx, args.site), args) })
845
+
846
+ /** `create` for an actor already known: the platform's signed-in person, or the agent door's key (SPEC 16). */
847
+ export async function createAs(ctx: MutationCtx, actor: Actor, args: ObjectType<typeof createArgs>, opts: { copy?: boolean } = {}) {
848
+ return idempotent(ctx, actor, args, async () => {
849
+ const schema = actor.site.schema as Schema
850
+ const brick = structuralBrick(schema, args.brick)
851
+ // A create task that lists `fields` writes only those (`authorize`); a copy carries over what the entry already holds.
852
+ authorize(actor, schema, { task: args.task, brick: args.brick, kind: 'create', ...(opts.copy ? {} : { fields: Object.keys(args.data), values: args.data as Record<string, Json> }) })
853
+
854
+ // Retired fields are not writable (SPEC 4.1 step 3); validation skips them, so reject them here.
855
+ for (const key of Object.keys(args.data)) liveField(brick, key)
856
+ const slugged = await slugsFor(ctx, actor, args.brick, brick.fields, args.data as Data)
857
+ const data = slugged.data
858
+ // Translations sent with a new entry are fresh: every foreign leaf gets the print of its main value.
859
+ const prints = nextPrints({ fields: brick.fields, roots: Object.keys(brick.fields), before: {}, after: data, prints: {}, main: schema.locales[0]!, confirm: undefined })
860
+ const { errors } = await validate(schema, args.brick, data, { mode: 'create', ...(await lookupsFor(ctx, actor.site._id, brick.fields, data)) })
861
+ if (errors.length) fail('INVALID', 'errors.pleaseCheckMarkedFields', undefined, { errors: errors as unknown as Json })
862
+ await refuseSecondPlan(ctx, actor, args.brick, brick, data)
863
+
864
+ const rows = await rowsOf(ctx, actor.site._id, args.brick)
865
+ const removing = roomPlan(actor, brick, rows)
866
+ const c = countersOf(actor.site)
867
+ if (c.entryCount - removing.length >= BUDGET.entries) fail('TOO_LARGE', 'errors.siteEntryLimitReached')
868
+ const size = entryBytes(data, prints)
869
+ if (size > BUDGET.entryBytes) fail('TOO_LARGE', 'errors.entryTooLarge', overBudget(size, BUDGET.entryBytes))
870
+ if (c.bytes + size > BUDGET.siteBytes) fail('TOO_LARGE', 'errors.siteStorageLimitReached', overBudget(c.bytes + size, BUDGET.siteBytes))
871
+ const trees = await treesOf(brick.fields, data)
872
+ if (c.treeBytes + trees.bytes > BUDGET.treeBytes) fail('TOO_LARGE', 'errors.entryTooComplex')
873
+ const files = fileIdsOf(brick.fields, data, { isUploadId: uploadIdsOf(ctx) })
874
+ await checkFiles(ctx, actor.site._id, files, fileIdsOf(brick.fields, data, { only: 'image' }))
875
+ // A new entry is a draft (SPEC 15); only `publish: {}` puts it live at once. "Show me first" asks to go online.
876
+ const publish = args.publish ?? (actor.forceProposal ? {} : undefined)
877
+ const lateAt = lapsed(actor, publish?.at)
878
+ const draft = publish === undefined || (publish.at !== undefined && !lateAt)
879
+ const at = draft ? publish?.at : undefined
880
+ // Checked before anything is written, so a late failure (apply of a proposal) leaves no half-done removal behind.
881
+ if (at !== undefined) checkFuture(at)
882
+
883
+ // A plain draft is not live; a live or scheduled entry is (SPEC 17).
884
+ if (await needsProposal(ctx, actor, 'create', args.task, args.brick, { state: draft && at === undefined ? 'draft' : 'live' })) {
885
+ // A proposal that would go live with a broken link is refused now, not only when approved. The entry does not exist yet: it joins the link check under a temporary id.
886
+ if (!draft || at !== undefined) await checkNewLinks(ctx, actor.site, [{ entry: { _id: 'proposed' as Id<'entries'>, brick: args.brick }, fields: brick.fields, before: {}, after: data, isNew: true }])
887
+ return await propose(ctx, actor, {
888
+ // A copy keeps its flag, so applying the proposal skips the fields check like the direct write.
889
+ op: 'create', brick: args.brick, args: { ...args, ...(publish ? { publish } : {}), ...(opts.copy ? { copy: true } : {}) } as unknown as Json, base: {}, after: data as Json,
890
+ ...recorded(msg('history.createProposal', { title: labelOf(schema, args.brick, data) }), schema),
891
+ })
892
+ }
893
+
894
+ for (const expired of removing) {
895
+ await softRemove(ctx, c, expired, args.opId, SYSTEM, recorded(msg('history.expiredRemoved', { title: labelOf(schema, args.brick, expired.data) }), schema))
896
+ }
897
+ const order = newOrder(args.brick, brick, rows.map((r) => r.order))
898
+ const entry = await ctx.db.insert('entries', {
899
+ site: actor.site._id, brick: args.brick, kind: 'item', order, data, rev: 1,
900
+ fieldRevs: Object.fromEntries(Object.keys(brick.fields).map((name) => [name, 1])), lifeRev: 1, prints, bytes: size, treeBytes: trees.bytes,
901
+ // A draft's `contentAt` is set again when it goes live.
902
+ contentAt: Date.now(),
903
+ ...(draft ? { state: 'draft' as const } : {}),
904
+ // Staff always create through a create task, and may change what they created with it later (`authorize`).
905
+ ...(actor.role === 'staff' ? { createdBy: actor.user.id } : {}),
906
+ })
907
+ await putTrees(ctx, actor.site._id, entry, trees.json)
908
+ if (at !== undefined) await ctx.db.patch(entry, { publishAt: at, publishJob: await ctx.scheduler.runAt(at, internal.entries.publishDue, { entry, at }) })
909
+ for (const row of slugged.slugs) {
910
+ await ctx.db.insert('slugs', { site: actor.site._id, brick: args.brick, locale: row.locale, slug: row.slug, entry })
911
+ }
912
+ // A live or scheduled entry puts its links online; checked after the insert so its own URL is known (a failure undoes the whole create).
913
+ if (!draft || at !== undefined) await checkNewLinks(ctx, actor.site, [{ entry: (await ctx.db.get(entry))!, fields: brick.fields, before: {}, after: data }])
914
+ c.entryCount += 1
915
+ c.bytes += size
916
+ c.treeBytes += trees.bytes
917
+ if (!draft) c.contentRev += 1
918
+ const label = labelOf(schema, args.brick, data)
919
+ const change = await ctx.db.insert('changes', {
920
+ site: actor.site._id, entry, brick: args.brick, ...byOf(actor), opId: args.opId, kind: 'create',
921
+ ...recorded(!draft ? (lateAt ? msg('history.publishedLate', { title: label }) : msg('history.created', { title: label })) : at === undefined ? msg('history.draftCreated', { title: label }) : msg('history.draftCreatedScheduled', { title: label, at }), schema),
922
+ after: data, entryRev: 1, contentRev: c.contentRev, at: Date.now(),
923
+ })
924
+ await syncEntryRefs(ctx, actor.site._id, entry, await entryUses(ctx, brick.fields, data, schema.locales))
925
+ if (files.size) await syncFileRefs(ctx, actor.site._id, 'change', change, files)
926
+ await writeCounters(ctx, actor.site._id, c)
927
+
928
+ // What the other languages show of the new entry (the Studio's message after saving); a draft is not on the website.
929
+ const translation = draft ? [] : translationNotes(schema, args.brick, { _id: entry, data, prints }, {}, Object.keys(brick.fields))
930
+ // A new planned week shows from its first day; the Studio says from when.
931
+ const from = draft ? undefined : liveFrom(schema, args.brick, data, Object.keys(data), todayIn(schema.timeZone))
932
+ return { entry, rev: 1, contentRev: c.contentRev, state: draft ? 'draft' : 'live', ...(at === undefined ? {} : { publishAt: at }), translation, ...(from ? { liveFrom: from } : {}) }
933
+ })
934
+ }
935
+
936
+ // ---- Duplicate (SPEC 4.2): a new entry made with the normal create path. ----
937
+
938
+ const duplicateArgs = { site: v.string(), opId: v.string(), task: v.optional(v.string()), entry: v.string() }
939
+
940
+ /** The same row `_id` for the same operation, so a retry with the same `opId` sends the same data and is replayed. */
941
+ const rowIdFor = (opId: string, path: string) => sha256(`${opId}:${path}`).slice(0, 10)
942
+
943
+ /** List rows of the copy get their own `_id`s, so the two entries share no row identity (history, translation prints). */
944
+ function withNewRowIds(field: Field, value: Json, path: string, opId: string): Json {
945
+ if (field.type !== 'list' || !Array.isArray(value)) return value
946
+ return value.map((row, i) => {
947
+ if (typeof row !== 'object' || row === null || Array.isArray(row)) return row
948
+ const out: Record<string, Json> = { ...row, _id: rowIdFor(opId, `${path}.${i}`) }
949
+ for (const [key, inner] of Object.entries(field.of)) if (out[key] !== undefined) out[key] = withNewRowIds(inner, out[key]!, `${path}.${i}.${key}`, opId)
950
+ return out
951
+ })
952
+ }
953
+
954
+ /** The copy's label in that text's language ("Weinabend (Kopie)", "Wine evening (copy)"); English for a language the catalog lacks. */
955
+ const copyText = (text: string, locale: string) => t(isLocale(locale) ? locale : 'en', 'content.copyOf', { text })
956
+
957
+ /** The copy mark after every text of the value, or the value as it is when one of them would then be too long. `main` is the language of a plain text. */
958
+ function withCopySuffix(field: Field, value: Json, main: string): Json {
959
+ const texts: [string, Json][] = typeof value === 'string' ? [[main, value]] : Object.entries(plainObject(value))
960
+ const max = effectiveMax(field)
961
+ const marked = texts.map(([locale, text]) => [locale, typeof text === 'string' && text !== '' ? copyText(text, locale) : text] as const)
962
+ if (marked.some(([, text]) => typeof text === 'string' && [...text].length > max)) return value
963
+ return typeof value === 'string' ? marked[0]![1] : Object.fromEntries(marked)
964
+ }
965
+
966
+ /**
967
+ * The data of the copy: live fields only; slugs left out (create makes new, free ones from the title,
968
+ * so "Wildwoche (Kopie)" becomes `wildwoche-kopie`, then `wildwoche-kopie-2`).
969
+ */
970
+ function copyOf(brick: CollectionBrick, data: Data, opId: string, main: string): Data {
971
+ const slugSources = new Set(Object.values(brick.fields).flatMap((field) => (field.type === 'slug' && !field.retired ? [field.from] : [])))
972
+ const label = ordered(brick.fields).find(([, field]) => field.type === 'text' && !field.retired)?.[0]
973
+ const out: Data = {}
974
+ for (const [name, field] of Object.entries(brick.fields)) {
975
+ if (field.retired || field.type === 'slug' || data[name] === undefined) continue
976
+ const value = withNewRowIds(field, data[name]!, name, opId)
977
+ out[name] = field.type === 'text' && (name === label || slugSources.has(name)) ? withCopySuffix(field, value, main) : value
978
+ }
979
+ return out
980
+ }
981
+
982
+ export const duplicate = mutation({ args: duplicateArgs, handler: async (ctx, args) => duplicateAs(ctx, await actorFor(ctx, args.site), args) })
983
+
984
+ /**
985
+ * Creates a copy of an entry. Rights, limits, checks, file references and the approval policy are
986
+ * those of `create`; the copy is a draft. Staff names the create task.
987
+ */
988
+ export async function duplicateAs(ctx: MutationCtx, actor: Actor, args: ObjectType<typeof duplicateArgs>) {
989
+ const entry = await entryOf(ctx, actor, args.entry)
990
+ const schema = actor.site.schema as Schema
991
+ const brick = structuralBrick(schema, entry.brick)
992
+ authorize(actor, schema, { task: args.task, brick: entry.brick, kind: 'create' })
993
+ if (entry.deletedAt) fail('INVALID', 'errors.removedEntryCannotCopy')
994
+ return createAs(ctx, actor, {
995
+ site: args.site, opId: args.opId, ...(args.task === undefined ? {} : { task: args.task }),
996
+ brick: entry.brick, data: copyOf(brick, entry.data as Data, args.opId, schema.locales[0]!),
997
+ }, { copy: true })
998
+ }
999
+
1000
+ const removeArgs = { site: v.string(), opId: v.string(), task: v.optional(v.string()), entry: v.string(), lifeRev: v.number() }
1001
+
1002
+ export const remove = mutation({ args: removeArgs, handler: async (ctx, args) => removeAs(ctx, await actorFor(ctx, args.site), args) })
1003
+
1004
+ /** `remove` for an actor already known: the platform's signed-in person, or the agent door's key (SPEC 16). */
1005
+ export async function removeAs(ctx: MutationCtx, actor: Actor, args: ObjectType<typeof removeArgs>) {
1006
+ checkRev(args.lifeRev)
1007
+ return idempotent(ctx, actor, args, async () => {
1008
+ const entry = await entryOf(ctx, actor, args.entry)
1009
+ const schema = actor.site.schema as Schema
1010
+ structuralBrick(schema, entry.brick)
1011
+ authorize(actor, schema, { task: args.task, brick: entry.brick, kind: 'remove' })
1012
+ if (entry.deletedAt || entry.lifeRev !== args.lifeRev) fail('CHANGED_SINCE', 'errors.entryChangedMeanwhile', undefined, lifeStateOf(entry))
1013
+
1014
+ const label = labelOf(schema, entry.brick, entry.data as Data)
1015
+ if (await needsProposal(ctx, actor, 'remove', args.task, entry.brick, entry)) {
1016
+ return await propose(ctx, actor, {
1017
+ op: 'remove', brick: entry.brick, entry: entry._id, args: args as unknown as Json, base: { lifeRev: entry.lifeRev },
1018
+ before: entry.data as Json, ...recorded(msg('history.removeProposal', { title: label }), schema),
1019
+ })
1020
+ }
1021
+
1022
+ const c = countersOf(actor.site)
1023
+ await softRemove(ctx, c, entry, args.opId, byOf(actor), recorded(msg('history.removed', { title: label }), schema))
1024
+ await writeCounters(ctx, actor.site._id, c)
1025
+ // The new lifeRev lets the UI undo this at once (restore after remove, remove after restore).
1026
+ return { entry: entry._id, contentRev: c.contentRev, lifeRev: entry.lifeRev + 1 }
1027
+ })
1028
+ }
1029
+
1030
+ export const restore = mutation({
1031
+ args: { site: v.string(), opId: v.string(), task: v.optional(v.string()), entry: v.string(), lifeRev: v.number() },
1032
+ handler: async (ctx, args) => {
1033
+ const actor = await actorFor(ctx, args.site)
1034
+ checkRev(args.lifeRev)
1035
+ return idempotent(ctx, actor, args, async () => {
1036
+ const entry = await entryOf(ctx, actor, args.entry)
1037
+ const schema = actor.site.schema as Schema
1038
+ const brick = structuralBrick(schema, entry.brick)
1039
+ // Restoring belongs to the remove task (SPEC 2.7: restore is part of remove).
1040
+ authorize(actor, schema, { task: args.task, brick: entry.brick, kind: 'remove' })
1041
+ refuseDirectWrite(actor, entry.brick, args.task)
1042
+ if (!entry.deletedAt || entry.lifeRev !== args.lifeRev) fail('CHANGED_SINCE', 'errors.entryChangedMeanwhile', undefined, lifeStateOf(entry))
1043
+
1044
+ const rows = await rowsOf(ctx, actor.site._id, entry.brick)
1045
+ const live = rows.filter((r) => !r.deletedAt).length
1046
+ if (live >= brick.max) fail('INVALID', 'errors.collectionFull', { max: brick.max }, { max: brick.max })
1047
+ // A plan whose week was planned again while it was in the trash would hide one of the two.
1048
+ await refuseSecondPlan(ctx, actor, entry.brick, brick, entry.data as Data, { whole: true })
1049
+ const c = countersOf(actor.site)
1050
+ if (c.entryCount >= BUDGET.entries) fail('TOO_LARGE', 'errors.siteEntryLimitReached')
1051
+ // The trash does not count toward the site's budget, so a restore needs room for the entry again.
1052
+ if (c.bytes + entry.bytes > BUDGET.siteBytes) fail('TOO_LARGE', 'errors.restoreNoRoom', { limit: sizeText(BUDGET.siteBytes) })
1053
+ // The trash keeps no trees: they are made again.
1054
+ const trees = await treesOf(brick.fields, entry.data as Data)
1055
+ if (c.treeBytes + trees.bytes > BUDGET.treeBytes) fail('TOO_LARGE', 'errors.entryTooComplex')
1056
+
1057
+ const order = newOrder(entry.brick, brick, rows.map((r) => r.order))
1058
+ const now = Date.now()
1059
+ await ctx.db.patch(entry._id, {
1060
+ deletedAt: undefined, lifeRev: entry.lifeRev + 1, rev: entry.rev + 1, order, treeBytes: trees.bytes, ...(entry.state === 'draft' ? {} : { contentAt: now }),
1061
+ })
1062
+ await putTrees(ctx, actor.site._id, entry._id, trees.json)
1063
+ c.entryCount += 1
1064
+ c.bytes += entry.bytes
1065
+ c.trashBytes -= entry.bytes
1066
+ c.treeBytes += trees.bytes
1067
+ // A restored draft stays out of the bundle (its schedule went with the removal).
1068
+ if (entry.state !== 'draft') c.contentRev += 1
1069
+ await ctx.db.insert('changes', {
1070
+ site: actor.site._id, entry: entry._id, brick: entry.brick, ...byOf(actor), opId: args.opId, kind: 'restore',
1071
+ ...recorded(msg('history.restored', { title: labelOf(schema, entry.brick, entry.data as Data) }), schema), entryRev: entry.rev + 1, contentRev: c.contentRev, at: now,
1072
+ })
1073
+ await writeCounters(ctx, actor.site._id, c)
1074
+ // The new lifeRev lets the UI undo this at once (restore after remove, remove after restore).
1075
+ return { entry: entry._id, contentRev: c.contentRev, lifeRev: entry.lifeRev + 1 }
1076
+ })
1077
+ },
1078
+ })
1079
+
1080
+ /**
1081
+ * Deletes a removed entry for good now, as retention does after 30 days (lib/lifecycle purgeEntry): its slugs, file
1082
+ * references, trees and the row. Its change rows stay, with their old values, as long as retention keeps them. Owners
1083
+ * and admins only, because it cannot be undone; the agent door has no tool for it.
1084
+ */
1085
+ export const purge = mutation({
1086
+ args: { site: v.string(), opId: v.string(), entry: v.string(), lifeRev: v.number() },
1087
+ handler: async (ctx, args): Promise<Json> => {
1088
+ const actor = await actorFor(ctx, args.site)
1089
+ if (actor.role === 'staff') fail('FORBIDDEN', 'errors.purgeOwnersOnly')
1090
+ checkRev(args.lifeRev)
1091
+ return idempotent(ctx, actor, args, async () => {
1092
+ const entry = await entryOf(ctx, actor, args.entry)
1093
+ if (!entry.deletedAt || entry.lifeRev !== args.lifeRev) fail('CHANGED_SINCE', 'errors.entryChangedMeanwhile', undefined, lifeStateOf(entry))
1094
+ const schema = actor.site.schema as Schema
1095
+ const c = countersOf(actor.site)
1096
+ await purgeEntry(ctx, c, entry)
1097
+ await ctx.db.insert('changes', {
1098
+ site: actor.site._id, entry: entry._id, brick: entry.brick, ...byOf(actor), opId: args.opId, kind: 'purge',
1099
+ ...recorded(msg('history.purged', { title: labelOf(schema, entry.brick, entry.data as Data) }), schema), entryRev: entry.rev + 1, contentRev: c.contentRev, at: Date.now(),
1100
+ })
1101
+ await writeCounters(ctx, actor.site._id, c)
1102
+ const result: Json = { entry: entry._id }
1103
+ return result
1104
+ })
1105
+ },
1106
+ })
1107
+
1108
+ // ---- Drafts (SPEC 15): publish, unpublish and the scheduled publishDue. ----
1109
+
1110
+ const YEAR = 365 * 24 * 60 * 60 * 1000
1111
+
1112
+ /** A publish time must lie in the future and at most one year ahead. */
1113
+ export function checkFuture(at: number) {
1114
+ const now = Date.now()
1115
+ if (!Number.isFinite(at) || !Number.isInteger(at)) fail('INVALID', 'errors.timeInvalid')
1116
+ if (at <= now) fail('INVALID', 'errors.timeMustBeFuture')
1117
+ if (at > now + YEAR) fail('INVALID', 'errors.timeTooFarAhead')
1118
+ }
1119
+
1120
+ /**
1121
+ * A proposal that asked for a publish time is approved after that time: the approval publishes at once, it does not
1122
+ * refuse (the author cannot send it again, and the approver did not choose the time). Only an approved proposal being
1123
+ * applied (`approvedBy`) gets this; a person's own call with a past time is still refused by `checkFuture`.
1124
+ */
1125
+ function lapsed(actor: Actor, at: number | undefined): boolean {
1126
+ return actor.approvedBy !== undefined && at !== undefined && at <= Date.now()
1127
+ }
1128
+
1129
+ async function cancelJob(ctx: MutationCtx, entry: Doc<'entries'>) {
1130
+ if (entry.publishJob) await ctx.scheduler.cancel(entry.publishJob)
1131
+ }
1132
+
1133
+ /** Draft → live: state, no schedule, `contentAt`, lifeRev+1, contentRev+1 and one 'publish' change. Shared by `publishAs` and `publishDue`. */
1134
+ async function goLive(ctx: MutationCtx, c: Counters, entry: Doc<'entries'>, by: By, opId: string, history: Recorded, now = Date.now()) {
1135
+ await cancelJob(ctx, entry)
1136
+ await ctx.db.patch(entry._id, { state: 'live', publishAt: undefined, publishJob: undefined, lifeRev: entry.lifeRev + 1, rev: entry.rev + 1, contentAt: now })
1137
+ c.contentRev += 1
1138
+ return ctx.db.insert('changes', {
1139
+ site: entry.site, entry: entry._id, brick: entry.brick, ...by, opId, kind: 'publish', ...history, entryRev: entry.rev + 1, contentRev: c.contentRev, at: now,
1140
+ })
1141
+ }
1142
+
1143
+ const publishArgs = {
1144
+ site: v.string(),
1145
+ opId: v.string(),
1146
+ task: v.optional(v.string()),
1147
+ entry: v.string(),
1148
+ lifeRev: v.number(),
1149
+ /** Absent: online now. Present: online at this time (ms, in the future, within a year). */
1150
+ at: v.optional(v.number()),
1151
+ /** For a live entry's unpublished changes: the entry rev the person saw; a newer save refuses the publish. */
1152
+ rev: v.optional(v.number()),
1153
+ }
1154
+
1155
+ export const publish = mutation({ args: publishArgs, handler: async (ctx, args) => publishAs(ctx, await actorFor(ctx, args.site), args) })
1156
+
1157
+ /** `publish` for an actor already known: the platform's signed-in person, or the agent door's key (SPEC 16). */
1158
+ export async function publishAs(ctx: MutationCtx, actor: Actor, args: ObjectType<typeof publishArgs>) {
1159
+ checkRev(args.lifeRev)
1160
+ return idempotent(ctx, actor, args, async () => {
1161
+ const entry = await entryOf(ctx, actor, args.entry)
1162
+ const schema = actor.site.schema as Schema
1163
+ // A single is always live: publishing it means its unpublished changes.
1164
+ brickOf(schema, entry)
1165
+ authorizeWriter(actor, schema, { task: args.task, brick: entry.brick })
1166
+ if (entry.deletedAt || entry.lifeRev !== args.lifeRev) fail('CHANGED_SINCE', 'errors.entryChangedMeanwhile', undefined, lifeStateOf(entry))
1167
+ if (stateOf(entry) !== 'draft') return await publishPending(ctx, actor, entry, args)
1168
+ const late = lapsed(actor, args.at)
1169
+ const at = late ? undefined : args.at
1170
+ if (at !== undefined) checkFuture(at)
1171
+ // Everything the draft holds goes live, so every link in it counts as new (also when it is only scheduled: the job does not check again).
1172
+ await checkNewLinks(ctx, actor.site, [{ entry, fields: structuralBrick(schema, entry.brick).fields, before: {}, after: entry.data as Data }])
1173
+
1174
+ const label = labelOf(schema, entry.brick, entry.data as Data)
1175
+ if (await needsProposal(ctx, actor, 'publish', args.task, entry.brick, entry)) {
1176
+ return await propose(ctx, actor, {
1177
+ op: 'publish', brick: entry.brick, entry: entry._id, args: args as unknown as Json, base: { lifeRev: entry.lifeRev },
1178
+ before: { state: 'draft' }, after: at === undefined ? { state: 'live' } : { state: 'draft', publishAt: at },
1179
+ ...recorded(at === undefined ? msg('history.publishProposal', { title: label }) : msg('history.publishProposalScheduled', { title: label, at }), schema),
1180
+ })
1181
+ }
1182
+ const c = countersOf(actor.site)
1183
+ let change: Id<'changes'>
1184
+ if (at === undefined) {
1185
+ change = await goLive(ctx, c, entry, byOf(actor), args.opId, recorded(msg(late ? 'history.publishedLate' : 'history.published', { title: label }), schema))
1186
+ } else {
1187
+ // A new time replaces the old job, so the entry never goes online at the old time.
1188
+ await cancelJob(ctx, entry)
1189
+ const publishJob = await ctx.scheduler.runAt(at, internal.entries.publishDue, { entry: entry._id, at })
1190
+ await ctx.db.patch(entry._id, { publishAt: at, publishJob, lifeRev: entry.lifeRev + 1, rev: entry.rev + 1 })
1191
+ change = await ctx.db.insert('changes', {
1192
+ site: actor.site._id, entry: entry._id, brick: entry.brick, ...byOf(actor), opId: args.opId, kind: 'schedule',
1193
+ ...recorded(msg('history.scheduled', { title: label, at }), schema), entryRev: entry.rev + 1, contentRev: c.contentRev, at: Date.now(),
1194
+ })
1195
+ }
1196
+ await writeCounters(ctx, actor.site._id, c)
1197
+ // What the other languages show of the entry that went online now (the Studio's message after publishing, as after a create).
1198
+ const translation = at === undefined ? translationNotes(schema, entry.brick, entry, {}, Object.keys(structuralBrick(schema, entry.brick).fields)) : []
1199
+ return {
1200
+ entry: entry._id, lifeRev: entry.lifeRev + 1, rev: entry.rev + 1, contentRev: c.contentRev, change,
1201
+ state: at === undefined ? 'live' : 'draft', ...(at === undefined ? {} : { publishAt: at }), translation,
1202
+ }
1203
+ })
1204
+ }
1205
+
1206
+ const unpublishArgs = { site: v.string(), opId: v.string(), task: v.optional(v.string()), entry: v.string(), lifeRev: v.number() }
1207
+
1208
+ export const unpublish = mutation({ args: unpublishArgs, handler: async (ctx, args) => unpublishAs(ctx, await actorFor(ctx, args.site), args) })
1209
+
1210
+ /** `unpublish` for an actor already known: the platform's signed-in person, or the agent door's key (SPEC 16). */
1211
+ export async function unpublishAs(ctx: MutationCtx, actor: Actor, args: ObjectType<typeof unpublishArgs>) {
1212
+ checkRev(args.lifeRev)
1213
+ return idempotent(ctx, actor, args, async () => {
1214
+ const entry = await entryOf(ctx, actor, args.entry)
1215
+ const schema = actor.site.schema as Schema
1216
+ const brick = brickOf(schema, entry)
1217
+ authorizeWriter(actor, schema, { task: args.task, brick: entry.brick })
1218
+ if (entry.deletedAt || entry.lifeRev !== args.lifeRev) fail('CHANGED_SINCE', 'errors.entryChangedMeanwhile', undefined, lifeStateOf(entry))
1219
+ const wasLive = stateOf(entry) === 'live'
1220
+ if (!wasLive && entry.publishAt === undefined) fail('INVALID', 'errors.entryAlreadyDraft', undefined, lifeStateOf(entry))
1221
+ const held = wasLive ? await pendingOf(ctx, entry._id) : null
1222
+ // One step back: planned unpublished changes lose their time first, as a scheduled draft does; the entry stays online.
1223
+ if (held?.publishAt !== undefined) return await unschedulePending(ctx, actor, entry, held, args)
1224
+ // A single has no draft state: it can lose a planned time, never go offline.
1225
+ if (brick.kind === 'single') fail('INVALID', 'errors.singleStaysOnline', undefined, lifeStateOf(entry))
1226
+
1227
+ const label = labelOf(schema, entry.brick, entry.data as Data)
1228
+ if (await needsProposal(ctx, actor, 'unpublish', args.task, entry.brick, entry)) {
1229
+ return await propose(ctx, actor, {
1230
+ op: 'unpublish', brick: entry.brick, entry: entry._id, args: args as unknown as Json, base: { lifeRev: entry.lifeRev },
1231
+ before: { state: wasLive ? 'live' : 'draft' }, after: { state: 'draft' },
1232
+ ...recorded(msg(wasLive ? 'history.unpublishProposal' : 'history.unscheduleProposal', { title: label }), schema),
1233
+ })
1234
+ }
1235
+
1236
+ const c = countersOf(actor.site)
1237
+ await cancelJob(ctx, entry)
1238
+ await ctx.db.patch(entry._id, { state: 'draft', publishAt: undefined, publishJob: undefined, lifeRev: entry.lifeRev + 1, rev: entry.rev + 1 })
1239
+ // Only a live entry leaves the bundle; a scheduled draft was never in it.
1240
+ if (wasLive) c.contentRev += 1
1241
+ const change = await ctx.db.insert('changes', {
1242
+ site: actor.site._id, entry: entry._id, brick: entry.brick, ...byOf(actor), opId: args.opId, kind: 'unpublish',
1243
+ ...recorded(msg(wasLive ? 'history.unpublished' : 'history.unscheduled', { title: label }), schema), entryRev: entry.rev + 1, contentRev: c.contentRev, at: Date.now(),
1244
+ })
1245
+ await writeCounters(ctx, actor.site._id, c)
1246
+ // A draft is not online: its unpublished changes become part of it.
1247
+ if (held) {
1248
+ const draft = (await ctx.db.get(entry._id))!
1249
+ const { data, prints } = overlay(entry, held)
1250
+ const roots = Object.keys(held.fields)
1251
+ const brick = brickOf(schema, entry)
1252
+ const written = await commitEntry(ctx, { actor: { ...actor, site: (await ctx.db.get(actor.site._id))! }, entry: draft, fields: brick.fields, roots, data, prints, kind: 'save', history: recorded(saveMsg(schema, brick, entry, roots, data, false), schema), opId: args.opId })
1253
+ await dropPending(ctx, held)
1254
+ return { entry: entry._id, lifeRev: entry.lifeRev + 1, rev: written.rev, contentRev: written.contentRev, change, state: 'draft' }
1255
+ }
1256
+ return { entry: entry._id, lifeRev: entry.lifeRev + 1, rev: entry.rev + 1, contentRev: c.contentRev, change, state: 'draft' }
1257
+ })
1258
+ }
1259
+
1260
+ /** `unpublish` of a live entry whose unpublished changes have a time: only the time goes. */
1261
+ async function unschedulePending(ctx: MutationCtx, actor: Actor, entry: Doc<'entries'>, held: Pending, args: ObjectType<typeof unpublishArgs>) {
1262
+ const schema = actor.site.schema as Schema
1263
+ const title = labelOf(schema, entry.brick, entry.data as Data)
1264
+ if (await needsProposal(ctx, actor, 'unpublish', args.task, entry.brick, entry)) {
1265
+ return await propose(ctx, actor, {
1266
+ op: 'unpublish', brick: entry.brick, entry: entry._id, args: args as unknown as Json, base: { lifeRev: entry.lifeRev },
1267
+ before: { state: 'live', publishAt: held.publishAt! }, after: { state: 'live' }, ...recorded(msg('history.unscheduleProposal', { title }), schema),
1268
+ })
1269
+ }
1270
+ if (held.publishJob) await ctx.scheduler.cancel(held.publishJob)
1271
+ await ctx.db.patch(held._id, { publishAt: undefined, publishJob: undefined })
1272
+ const change = await ctx.db.insert('changes', {
1273
+ site: actor.site._id, entry: entry._id, brick: entry.brick, ...byOf(actor), opId: args.opId, kind: 'unschedule',
1274
+ ...recorded(msg('history.changesUnscheduled', { title }), schema), entryRev: entry.rev, contentRev: actor.site.contentRev, at: Date.now(),
1275
+ })
1276
+ return { entry: entry._id, lifeRev: entry.lifeRev, rev: entry.rev, contentRev: actor.site.contentRev, change, state: 'live' }
1277
+ }
1278
+
1279
+ /**
1280
+ * The scheduled job of a draft (SPEC 15): publishes it when it is still a draft with exactly this
1281
+ * `publishAt` (a rescheduled, unpublished or removed entry does nothing). The actor is `system`.
1282
+ */
1283
+ export const publishDue = internalMutation({
1284
+ args: { entry: v.id('entries'), at: v.number() },
1285
+ handler: async (ctx, args): Promise<null> => {
1286
+ const entry = await ctx.db.get(args.entry)
1287
+ if (!entry || entry.deletedAt) return null
1288
+ // A live entry's job publishes its unpublished changes.
1289
+ if (stateOf(entry) === 'live') {
1290
+ await publishPendingDue(ctx, entry, args.at)
1291
+ return null
1292
+ }
1293
+ if (entry.publishAt !== args.at) return null
1294
+ const site = await ctx.db.get(entry.site)
1295
+ if (!site || site.deleting) return null
1296
+ const c = countersOf(site)
1297
+ const schema = site.schema as Schema
1298
+ const label = labelOf(schema, entry.brick, entry.data as Data)
1299
+ // Links may have broken since it was scheduled. A throwing job would fail silently, so the entry stays a draft and the history says why.
1300
+ const broken = await brokenNewLinks(ctx, site, [{ entry, fields: structuralBrick(schema, entry.brick).fields, before: {}, after: entry.data as Data }])
1301
+ if (broken) {
1302
+ await ctx.db.patch(entry._id, { publishAt: undefined, publishJob: undefined })
1303
+ await ctx.db.insert('changes', {
1304
+ site: entry.site, entry: entry._id, brick: entry.brick, ...SYSTEM, opId: `publish:${entry._id}:${args.at}`, kind: 'publishStopped',
1305
+ ...recorded(msg('history.publishStoppedBrokenLink', { title: label, link: broken.href }), schema), entryRev: entry.rev, contentRev: site.contentRev, at: Date.now(),
1306
+ })
1307
+ return null
1308
+ }
1309
+ // The job is running now, so there is nothing left to cancel.
1310
+ await goLive(ctx, c, { ...entry, publishJob: undefined }, SYSTEM, `publish:${entry._id}:${args.at}`, recorded(msg('history.publishedDue', { title: label }), site.schema as Schema))
1311
+ await writeCounters(ctx, site._id, c)
1312
+ return null
1313
+ },
1314
+ })
1315
+
1316
+ /**
1317
+ * The new order value of `entry` one place up or down: halfway to the live neighbour after the next one, or one past
1318
+ * the last. `null`: it is first or last already. `undefined`: no value fits (a live entry shares its order, or the gap
1319
+ * between the neighbours is used up); `renumber` makes room.
1320
+ */
1321
+ async function movedOrder(ctx: QueryCtx, entry: Doc<'entries'>, direction: 'up' | 'down'): Promise<number | null | undefined> {
1322
+ const tied = await ctx.db.query('entries').withIndex('by_site_brick_order', (q) => q.eq('site', entry.site).eq('brick', entry.brick).eq('order', entry.order)).collect()
1323
+ if (tied.some((row) => row._id !== entry._id && row.deletedAt === undefined)) return undefined
1324
+ const rows = ctx.db.query('entries')
1325
+ .withIndex('by_site_brick_order', (q) => (direction === 'up' ? q.eq('site', entry.site).eq('brick', entry.brick).lt('order', entry.order) : q.eq('site', entry.site).eq('brick', entry.brick).gt('order', entry.order)))
1326
+ .order(direction === 'up' ? 'desc' : 'asc')
1327
+ // Removed entries keep their order values (a restore puts them first again); they are passed over.
1328
+ const live: number[] = []
1329
+ for await (const row of rows) {
1330
+ if (row.deletedAt !== undefined) continue
1331
+ live.push(row.order)
1332
+ if (live.length === 2) break
1333
+ }
1334
+ const [near, far] = live
1335
+ if (near === undefined) return null
1336
+ const order = far === undefined ? near + (direction === 'up' ? -1 : 1) : (near + far) / 2
1337
+ return order === near || order === far ? undefined : order
1338
+ }
1339
+
1340
+ /** Gives the rows of a manual brick the orders 1..n in their current order (sortEntries, removed ones included); only `order` changes. */
1341
+ async function renumber(ctx: MutationCtx, brick: CollectionBrick, site: Id<'sites'>, key: string) {
1342
+ const rows = await rowsOf(ctx, site, key)
1343
+ const byId = new Map(rows.map((row) => [row._id as string, row]))
1344
+ const sorted = sortEntries(brick, rows.map((row): StoredEntry => ({ id: row._id, order: row.order, data: row.data })))
1345
+ for (const [index, stored] of sorted.entries()) {
1346
+ const row = byId.get(stored.id)!
1347
+ if (row.order !== index + 1) await ctx.db.patch(row._id, { order: index + 1 })
1348
+ }
1349
+ }
1350
+
1351
+ /**
1352
+ * Moves one entry of a manually ordered collection one place up or down (SPEC 4.2). It writes one order value
1353
+ * between the neighbours, so moves by two people at once both apply. Owners and admins only: no task covers it.
1354
+ */
1355
+ export const move = mutation({
1356
+ args: { site: v.string(), opId: v.string(), entry: v.string(), direction: v.union(v.literal('up'), v.literal('down')) },
1357
+ handler: async (ctx, args): Promise<Json> => {
1358
+ const actor = await actorFor(ctx, args.site)
1359
+ return idempotent(ctx, actor, args, async () => {
1360
+ let entry = await entryOf(ctx, actor, args.entry)
1361
+ const schema = actor.site.schema as Schema
1362
+ const brick = structuralBrick(schema, entry.brick)
1363
+ if (brick.order !== 'manual') fail('INVALID', 'errors.collectionAutoSorted', undefined, { brick: entry.brick })
1364
+ // A navigation tree moves a page with its subpages and headings (navigation.move); one order step would not.
1365
+ if (isNavTree(entry.brick, schema.bricks[entry.brick]!)) fail('INVALID', 'errors.moveInNavigationTree')
1366
+ // No task covers reordering (SPEC 2.7), so staff may not reorder.
1367
+ if (actor.role === 'staff') fail('FORBIDDEN', 'errors.notYourTask')
1368
+ if (entry.deletedAt) fail('CHANGED_SINCE', 'errors.thisEntryDeletedSince', undefined, current(entry))
1369
+
1370
+ const c = countersOf(actor.site)
1371
+ let order = await movedOrder(ctx, entry, args.direction)
1372
+ if (order === undefined) {
1373
+ // Rare: equal orders from older data, or about 50 moves into the same gap.
1374
+ await renumber(ctx, brick, actor.site._id, entry.brick)
1375
+ entry = (await ctx.db.get(entry._id))!
1376
+ order = await movedOrder(ctx, entry, args.direction)
1377
+ }
1378
+ // Already first or last: nothing to do.
1379
+ if (order === null || order === undefined) {
1380
+ const result: Json = { order: entry.order, contentRev: c.contentRev }
1381
+ return result
1382
+ }
1383
+ await ctx.db.patch(entry._id, { order, rev: entry.rev + 1 })
1384
+ c.contentRev += 1
1385
+ await ctx.db.insert('changes', {
1386
+ site: actor.site._id, entry: entry._id, brick: entry.brick, ...byOf(actor), opId: args.opId, kind: 'reorder',
1387
+ ...recorded(msg('history.reordered', { label: brick.label }), schema), entryRev: entry.rev + 1, contentRev: c.contentRev, at: Date.now(),
1388
+ })
1389
+ await writeCounters(ctx, actor.site._id, c)
1390
+ const result: Json = { order, contentRev: c.contentRev }
1391
+ return result
1392
+ })
1393
+ },
1394
+ })
1395
+
1396
+ /**
1397
+ * The live entries that point at an entry through a `ref` field (a single ref, a `multiple` list, a list
1398
+ * row), drafts too, in the shape of a file's "Used in" (files.ts), so the Studio shows both lists alike.
1399
+ * Removing still works: the entry goes to the trash, and these entries show without it until it is back.
1400
+ * The referring bricks are read whole; they are part of the site, which its storage budget bounds.
1401
+ * Refs in retired fields are not counted: the website no longer shows them. Any member may read (SPEC 2.7).
1402
+ */
1403
+ export const usedBy = query({
1404
+ args: { site: v.string(), entry: v.string() },
1405
+ handler: async (ctx, args) => {
1406
+ const actor = await actorFor(ctx, args.site)
1407
+ return usesOfEntry(ctx, actor, await entryOf(ctx, actor, args.entry))
1408
+ },
1409
+ })
1410
+
1411
+ /** `usedBy` for an entry of the actor's site already loaded; the agent door's remove names the same uses. */
1412
+ export async function usesOfEntry(ctx: QueryCtx, actor: Actor, target: Doc<'entries'>) {
1413
+ const schema = actor.site.schema as Schema
1414
+ const out: { entry: string; brick: string; title: string; paths: string[]; fieldLabels: (Label | null)[]; locale: null; missingAlt: false; deleted: false; state: 'draft' | 'live' }[] = []
1415
+ for (const [key, brick] of Object.entries(schema.bricks)) {
1416
+ if (brick.retired) continue
1417
+ const fields = Object.fromEntries(Object.entries(brick.fields).filter(([, field]) => !field.retired && pointsAt(field, target.brick)))
1418
+ if (!Object.keys(fields).length) continue
1419
+ const rows = await liveRowsQuery(ctx, actor.site._id, key).collect()
1420
+ for (const row of rows) {
1421
+ if (row._id === target._id) continue
1422
+ const paths = refIdsIn(fields, row.data as Data).filter((ref) => ref.to === target.brick && ref.id === target._id).map((ref) => ref.path)
1423
+ if (!paths.length) continue
1424
+ out.push({
1425
+ entry: row._id, brick: key, title: labelOf(schema, key, row.data as Data), paths, fieldLabels: paths.map((path) => fieldLabelAt(schema, key, path)),
1426
+ locale: null, missingAlt: false, deleted: false, state: stateOf(row),
1427
+ })
1428
+ }
1429
+ }
1430
+ return out
1431
+ }
1432
+
1433
+ /** A `ref` field to `brick`, or a list with such a column. */
1434
+ const pointsAt = (field: Field, brick: string): boolean =>
1435
+ (field.type === 'ref' && field.to === brick) || (field.type === 'list' && Object.values(field.of).some((inner) => !inner.retired && pointsAt(inner, brick)))
1436
+
1437
+ /**
1438
+ * Removed entries of a brick that can still be restored (30 days, SPEC 12), newest first, with only what the area list
1439
+ * shows: the title (null while untitled, as in `list`) and what a restore needs. Any member may read (SPEC 2.7).
1440
+ */
1441
+ export const removed = query({
1442
+ args: { site: v.string(), brick: v.string() },
1443
+ handler: async (ctx, args) => {
1444
+ const actor = await actorFor(ctx, args.site)
1445
+ const schema = actor.site.schema as Schema
1446
+ const brick = Object.hasOwn(schema.bricks, args.brick) ? schema.bricks[args.brick] : undefined
1447
+ // Absent deletedAt sorts before numbers, so the lower bound keeps live entries out.
1448
+ const rows = await ctx.db.query('entries')
1449
+ .withIndex('by_site_brick_deleted', (q) => q.eq('site', actor.site._id).eq('brick', args.brick).gt('deletedAt', 0))
1450
+ .order('desc')
1451
+ .take(100)
1452
+ return rows.map((e) => ({ _id: e._id, title: brick ? titleOf(schema, brick, e.data as Data, undefined) : null, lifeRev: e.lifeRev, deletedAt: e.deletedAt! }))
1453
+ },
1454
+ })
1455
+
1456
+ // ---- What the Studio's pages read (VOL-1): each page subscribes only to the entries it shows. ----
1457
+ // Any member may read, as with every Studio read (SPEC 2.7). Each reads only the live rows (by_site_brick_deleted), never
1458
+ // the brick's trash: one brick's live rows are bounded by SITE_BUDGET (bytes and entries), which keeps a whole-brick
1459
+ // read inside Convex's per-query limits.
1460
+
1461
+ /** A brick of the schema that is not retired. */
1462
+ function liveBrick(schema: Schema, key: string) {
1463
+ const brick = Object.hasOwn(schema.bricks, key) ? schema.bricks[key] : undefined
1464
+ if (!brick || brick.retired) fail('INVALID', 'errors.brickNoLongerEditable')
1465
+ return brick
1466
+ }
1467
+
1468
+ /** The rows of a brick that are not removed. Index order, not the site's order: sort them when the order matters. */
1469
+ function liveRowsQuery(ctx: QueryCtx, site: Id<'sites'>, key: string) {
1470
+ return ctx.db.query('entries').withIndex('by_site_brick_deleted', (q) => q.eq('site', site).eq('brick', key).eq('deletedAt', undefined))
1471
+ }
1472
+
1473
+ /** The live rows of a brick, in the site's order for a collection (core sortEntries, as on the website). */
1474
+ async function liveRowsOf(ctx: QueryCtx, site: Id<'sites'>, key: string, brick: Brick): Promise<Doc<'entries'>[]> {
1475
+ const rows = await liveRowsQuery(ctx, site, key).collect()
1476
+ if (brick.kind !== 'collection') return rows
1477
+ const byId = new Map(rows.map((row) => [row._id as string, row]))
1478
+ return sortEntries(brick, rows.map((row): StoredEntry => ({ id: row._id, order: row.order, data: row.data }))).map((stored) => byId.get(stored.id)!)
1479
+ }
1480
+
1481
+ /** Rows a list shows at first and adds per "Show more". */
1482
+ export const LIST_PAGE = 50
1483
+ /** Longest search text the list takes; more is cut. */
1484
+ const SEARCH_MAX = 200
1485
+
1486
+ /**
1487
+ * One collection's list (SPEC 4.2): the live entries in the site's order, narrowed by `search` (every word in a text or
1488
+ * longtext field, any language, without accents) and sorted by `sort` (a saved view), the first `limit` of them as
1489
+ * small rows (lib/list.ts listRow). `total` counts every match.
1490
+ */
1491
+ export const list = query({
1492
+ args: {
1493
+ site: v.string(),
1494
+ brick: v.string(),
1495
+ search: v.optional(v.string()),
1496
+ sort: v.optional(v.object({ field: v.string(), dir: v.union(v.literal('asc'), v.literal('desc')) })),
1497
+ limit: v.optional(v.number()),
1498
+ /** The person's language, for labels inside a title (a planned week's "Woche ab"); default: the site's main language. */
1499
+ language: v.optional(v.string()),
1500
+ },
1501
+ handler: async (ctx, args) => {
1502
+ const actor = await actorFor(ctx, args.site)
1503
+ const schema = actor.site.schema as Schema
1504
+ const brick = structuralBrick(schema, args.brick)
1505
+ const limit = args.limit !== undefined && Number.isFinite(args.limit) ? Math.min(Math.max(Math.floor(args.limit), 1), SITE_BUDGET.entries) : LIST_PAGE
1506
+ let rows = await liveRowsOf(ctx, actor.site._id, args.brick, brick)
1507
+ const words = searchable((args.search ?? '').trim().slice(0, SEARCH_MAX)).split(/\s+/).filter(Boolean)
1508
+ if (words.length) {
1509
+ rows = rows.filter((row) => {
1510
+ const hay = listHaystack(brick, row.data as Data, schema.locales)
1511
+ return words.every((word) => hay.includes(word))
1512
+ })
1513
+ }
1514
+ if (args.sort) rows = listSort(rows, brick, args.sort, schema.locales[0]!)
1515
+ const held = await pendingBySite(ctx, actor.site._id)
1516
+ return { total: rows.length, rows: rows.slice(0, limit).map((row) => listRow(schema, args.brick, row, args.language, held.has(row._id))) }
1517
+ },
1518
+ })
1519
+
1520
+ /**
1521
+ * One entry for an editor, with its translation gaps; `null` when no such entry of this site exists. A removed entry
1522
+ * comes back with `deleted: true`, so a form open on it keeps the person's input (N1).
1523
+ */
1524
+ export const get = query({
1525
+ args: { site: v.string(), entry: v.string() },
1526
+ handler: async (ctx, args) => {
1527
+ const actor = await actorFor(ctx, args.site)
1528
+ const id = ctx.db.normalizeId('entries', args.entry)
1529
+ const row = id ? await ctx.db.get(id) : null
1530
+ if (!row || row.site !== actor.site._id) return null
1531
+ // `own`: the person created it, so staff may change it with their create task (lib/access.ts `authorize`).
1532
+ return { ...editorEntryWithTranslation(actor.site.schema as Schema, row, await pendingOf(ctx, row._id), actor.user.id), ...(createdBy(actor, row) ? { own: true } : {}) }
1533
+ },
1534
+ })
1535
+
1536
+ /** The one entry of a single brick for its editor, with its translation gaps; `null` before it exists (and for a collection). */
1537
+ export const single = query({
1538
+ args: { site: v.string(), brick: v.string() },
1539
+ handler: async (ctx, args) => {
1540
+ const actor = await actorFor(ctx, args.site)
1541
+ const schema = actor.site.schema as Schema
1542
+ if (liveBrick(schema, args.brick).kind !== 'single') return null
1543
+ const row = await liveRowsQuery(ctx, actor.site._id, args.brick).first()
1544
+ return row ? editorEntryWithTranslation(schema, row, await pendingOf(ctx, row._id), actor.user.id) : null
1545
+ },
1546
+ })
1547
+
1548
+ /**
1549
+ * The live entries of a brick by title (lib/list.ts titleOf; null while untitled), with their state and the last day
1550
+ * they show (`until`, for `visible: until`): what a ref picker, a pick list and the duplicate check need. About 60 B a row.
1551
+ * A retired brick still answers: a ref field that points at it keeps showing the titles of the entries it holds.
1552
+ */
1553
+ export const titles = query({
1554
+ args: { site: v.string(), brick: v.string(), language: v.optional(v.string()) },
1555
+ handler: async (ctx, args) => {
1556
+ const actor = await actorFor(ctx, args.site)
1557
+ const schema = actor.site.schema as Schema
1558
+ const brick = Object.hasOwn(schema.bricks, args.brick) ? schema.bricks[args.brick] : undefined
1559
+ if (!brick) fail('INVALID', 'errors.brickNoLongerEditable')
1560
+ return (await liveRowsOf(ctx, actor.site._id, args.brick, brick)).map((row) => {
1561
+ const until = visibleUntil(brick, row.data as Data)
1562
+ return {
1563
+ _id: row._id,
1564
+ title: titleOf(schema, brick, row.data as Data, args.language),
1565
+ ...(row.state === undefined ? {} : { state: row.state }),
1566
+ ...(until === undefined ? {} : { until }),
1567
+ }
1568
+ })
1569
+ },
1570
+ })
1571
+
1572
+ /**
1573
+ * The live entries of the named bricks for an editor (lib/list.ts editorEntry), each collection in the site's order:
1574
+ * Schnell ändern's sections and the preview, which builds the site from them. Names the schema lacks are skipped.
1575
+ * `slim`: collection entries carry only their titles and dates (lib/list.ts slimEntry), as Schnell ändern needs.
1576
+ */
1577
+ export const ofBricks = query({
1578
+ args: { site: v.string(), bricks: v.array(v.string()), slim: v.optional(v.boolean()) },
1579
+ handler: async (ctx, args) => {
1580
+ const actor = await actorFor(ctx, args.site)
1581
+ const schema = actor.site.schema as Schema
1582
+ const out = []
1583
+ const held = await pendingBySite(ctx, actor.site._id)
1584
+ for (const key of new Set(args.bricks)) {
1585
+ const brick = Object.hasOwn(schema.bricks, key) ? schema.bricks[key]! : undefined
1586
+ if (!brick) continue
1587
+ for (const row of await liveRowsOf(ctx, actor.site._id, key, brick)) {
1588
+ const pending = held.get(row._id)
1589
+ const entry = args.slim && brick.kind === 'collection' ? slimEntry(brick, row, pending, actor.user.id) : editorEntry(row, pending, actor.user.id)
1590
+ // A draft says since when it exists and whether the person made it: Heute lists a person's own drafts (staff see no others).
1591
+ out.push(row.state === 'draft' ? { ...entry, since: row._creationTime, ...(createdBy(actor, row) ? { own: true } : {}) } : entry)
1592
+ }
1593
+ }
1594
+ return out
1595
+ },
1596
+ })
1597
+
1598
+ const TRASH_PAGE = 50
1599
+ /** Bytes of removed entries one trash page reads at most (as changes.list): fewer rows when they are large. */
1600
+ const TRASH_PAGE_BYTES = 2 * 1024 * 1024
1601
+
1602
+ /** The collections whose removed entries the trash shows (not retired ones); `only` narrows them to one. */
1603
+ const trashBricks = (schema: Schema, only?: string) =>
1604
+ Object.entries(schema.bricks).filter(([key, def]) => def.kind === 'collection' && !def.retired && (only === undefined || only === key)).map(([key]) => key)
1605
+
1606
+ /**
1607
+ * The trash (SPEC 12): removed entries that can still be restored, newest first, across bricks or in one. A
1608
+ * paginated query (`useConvexPaginatedQuery`), at most 50 entries a page. Any member may read; `mayRestore` says
1609
+ * whether this person can use `restore` (staff needs the remove task, and it must not need approval).
1610
+ */
1611
+ export const trash = query({
1612
+ args: { site: v.string(), brick: v.optional(v.string()), paginationOpts: paginationOptsValidator },
1613
+ handler: async (ctx, args) => {
1614
+ const actor = await actorFor(ctx, args.site)
1615
+ const schema = actor.site.schema as Schema
1616
+ if (args.brick !== undefined && !(Object.hasOwn(schema.bricks, args.brick) && schema.bricks[args.brick]!.kind === 'collection')) fail('INVALID', 'errors.brickNotFound')
1617
+ const site = actor.site._id
1618
+ const brick = args.brick
1619
+ const keys = trashBricks(schema, brick)
1620
+ // Absent deletedAt sorts before numbers, so the lower bound keeps live entries out.
1621
+ const rows = (brick === undefined
1622
+ ? ctx.db.query('entries').withIndex('by_site_deleted', (q) => q.eq('site', site).gt('deletedAt', 0))
1623
+ : ctx.db.query('entries').withIndex('by_site_brick_deleted', (q) => q.eq('site', site).eq('brick', brick).gt('deletedAt', 0)))
1624
+ .filter((q) => (keys.length ? q.or(...keys.map((key) => q.eq(q.field('brick'), key))) : false))
1625
+ .order('desc')
1626
+ const opts = args.paginationOpts
1627
+ let result
1628
+ try {
1629
+ result = await rows.paginate({ ...opts, numItems: Math.min(opts.numItems, TRASH_PAGE), maximumBytesRead: TRASH_PAGE_BYTES })
1630
+ } catch (error) {
1631
+ // The cursor comes from the client; the database refuses one it did not hand out.
1632
+ if (opts.cursor === null) throw error
1633
+ fail('INVALID', 'errors.pageMarkerInvalid')
1634
+ }
1635
+
1636
+ const page = await Promise.all(result.page.map(async (row) => {
1637
+ // Every write refuses a removed entry, so its newest change is the removal (none after an import). Older changes
1638
+ // can hold the full before and after of a 480 KiB entry: reading them made the page pass Convex's read limit.
1639
+ const newest = await ctx.db.query('changes').withIndex('by_entry', (q) => q.eq('entry', row._id)).order('desc').first()
1640
+ const removal = newest?.kind === 'remove' ? newest : undefined
1641
+ const member = removal && removal.actor !== 'system'
1642
+ ? await ctx.db.query('memberships').withIndex('by_user_site', (q) => q.eq('user', removal.actor).eq('site', actor.site._id)).unique()
1643
+ : null
1644
+ const task = actor.role === 'staff' ? taskFor(actor, row.brick, 'remove') : undefined
1645
+ return {
1646
+ entry: row._id, brick: row.brick, brickLabel: labelIn(schema.bricks[row.brick]!.label, schema.locales[0]!, schema.locales[0]!), label: labelOf(schema, row.brick, row.data as Data),
1647
+ lifeRev: row.lifeRev, deletedAt: row.deletedAt!, purgeAt: row.deletedAt! + DELETED_KEPT, wasDraft: row.state === 'draft',
1648
+ deletedBy: removal ? { actor: removal.actor, ...(member?.email ? { email: member.email } : {}), ...(removal.via ? { via: removal.via } : {}) } : null,
1649
+ mayRestore: actor.role !== 'staff' || (task !== undefined && !directWriteRefused(actor, row.brick, task)),
1650
+ mayPurge: actor.role !== 'staff',
1651
+ ...(task === undefined ? {} : { task }),
1652
+ }
1653
+ }))
1654
+ return { ...result, page }
1655
+ },
1656
+ })
1657
+
1658
+ /**
1659
+ * The removed entries that removing `entry` now would delete for good, oldest first, because the trash would pass
1660
+ * SITE_BUDGET.trashBytes (lib/lifecycle softRemove): the remove question names them. Usually none. Any member may ask.
1661
+ */
1662
+ export const trashOverflow = query({
1663
+ args: { site: v.string(), entry: v.string() },
1664
+ handler: async (ctx, args) => {
1665
+ const actor = await actorFor(ctx, args.site)
1666
+ const entry = await entryOf(ctx, actor, args.entry)
1667
+ if (entry.deletedAt) return []
1668
+ const schema = actor.site.schema as Schema
1669
+ const rows = await overflowingTrash(ctx, actor.site._id, (actor.site.trashBytes ?? 0) + entry.bytes)
1670
+ return rows.map((row) => ({ entry: row._id, brick: row.brick, title: labelOf(schema, row.brick, row.data as Data) }))
1671
+ },
1672
+ })
1673
+
1674
+ /** Why an entry is not on the website in a language (default: the main language), in plain German. Any member may ask. */
1675
+ export const whyNotPublic = query({
1676
+ args: { site: v.string(), entry: v.string(), locale: v.optional(v.string()) },
1677
+ handler: async (ctx, args) => {
1678
+ const actor = await actorFor(ctx, args.site)
1679
+ const entry = await entryOf(ctx, actor, args.entry)
1680
+ const schema = actor.site.schema as Schema
1681
+ const locale = schema.locales.find((l) => l === (args.locale ?? schema.locales[0]))
1682
+ if (!locale) fail('INVALID', 'errors.languageNotOnSite', { locale: args.locale ?? '' })
1683
+ if (!Object.hasOwn(schema.bricks, entry.brick)) fail('NOT_FOUND', 'errors.entryNotFound')
1684
+ return { locale, ...publicness(actor.site, entry.brick, entry, locale) }
1685
+ },
1686
+ })
1687
+
1688
+ /** Change kinds that alter what the public bundle shows: before `contentAt`, the newest of them was an entry's `updatedAt`. */
1689
+ const CONTENT_KINDS = new Set(['create', 'save', 'confirm', 'undo', 'restore', 'publish'])
1690
+
1691
+ /**
1692
+ * Brings every entry to the storage model of now (internals/migrations.md) and writes its Markdown trees again
1693
+ * from its data, also after a parser change (a row keeps the trees of the parser it was saved with). Per entry:
1694
+ * `bytes` = core `entryBytes`, the trees into `entryTrees` (none in the trash), `treeBytes`, no legacy `trees`, and
1695
+ * `contentAt` from its change history when it has none. A migration step (lib/migrations.ts): 10 entries per page;
1696
+ * the list runs `recountStorage` after it. Running it again is safe. Entries of a brick the schema no longer has keep
1697
+ * the trees they have. After a parser change, add a new list entry that points here.
1698
+ */
1699
+ export const migrateStorage = internalMutation({
1700
+ args: stepArgs,
1701
+ handler: async (ctx, args): Promise<null> => {
1702
+ const page = await ctx.db.query('entries').paginate({ cursor: args.cursor, numItems: 10 })
1703
+ const sites = new Map<Id<'sites'>, Doc<'sites'> | null>()
1704
+ const changed = new Set<Id<'sites'>>()
1705
+ for (const row of page.page) {
1706
+ if (!sites.has(row.site)) sites.set(row.site, await ctx.db.get(row.site))
1707
+ const schema = sites.get(row.site)?.schema as Schema | undefined
1708
+ const brick = schema && Object.hasOwn(schema.bricks, row.brick) ? schema.bricks[row.brick]! : undefined
1709
+ const stored = row.trees ?? await readTreesJson(ctx, row._id)
1710
+ const json = row.deletedAt !== undefined ? '' : brick ? (await treesOf(brick.fields, row.data as Data)).json : stored
1711
+ const treeBytes = new TextEncoder().encode(json).byteLength
1712
+ const bytes = entryBytes(row.data, row.prints)
1713
+ let contentAt = row.contentAt
1714
+ if (contentAt === undefined) {
1715
+ const recent = await ctx.db.query('changes').withIndex('by_entry', (q) => q.eq('entry', row._id)).order('desc').take(10)
1716
+ contentAt = recent.find((change) => CONTENT_KINDS.has(change.kind))?.at ?? row._creationTime
1717
+ }
1718
+ if (json === stored && row.trees === undefined && bytes === row.bytes && treeBytes === row.treeBytes && contentAt === row.contentAt) continue
1719
+ await ctx.db.patch(row._id, { bytes, treeBytes, contentAt, trees: undefined })
1720
+ if (json !== stored || row.trees !== undefined) await putTrees(ctx, row.site, row._id, json)
1721
+ // New trees change what the bundle serves: its caches must refresh.
1722
+ if (json !== stored && row.deletedAt === undefined && row.state !== 'draft') changed.add(row.site)
1723
+ }
1724
+ for (const id of changed) {
1725
+ const site = sites.get(id)
1726
+ if (site) await ctx.db.patch(id, { contentRev: site.contentRev + 1 })
1727
+ }
1728
+ return advance(ctx, args.run, page.isDone ? null : page.continueCursor)
1729
+ },
1730
+ })
1731
+
1732
+ /** A migration step after the entry migrations: per site (one per page), `bytes`, `trashBytes` and `treeBytes` become the sums over its entries. */
1733
+ export const recountStorage = internalMutation({
1734
+ args: stepArgs,
1735
+ handler: async (ctx, args): Promise<null> => {
1736
+ const page = await ctx.db.query('sites').paginate({ cursor: args.cursor, numItems: 1 })
1737
+ for (const site of page.page) {
1738
+ const rows = await ctx.db.query('entries').withIndex('by_site_brick_order', (q) => q.eq('site', site._id)).collect()
1739
+ await ctx.db.patch(site._id, storageSums(rows))
1740
+ }
1741
+ return advance(ctx, args.run, page.isDone ? null : page.continueCursor)
1742
+ },
1743
+ })
1744
+
1745
+ /**
1746
+ * Read-only check of the storage migrations, one site per call (repeat with `cursor` until `isDone`): entries that still
1747
+ * hold legacy `trees` or have no `contentAt`, counters that differ from the sums over the entries, and entries over
1748
+ * the entry limit (expected: none of each).
1749
+ */
1750
+ export const storageStatus = internalQuery({
1751
+ args: { cursor: v.optional(v.union(v.string(), v.null())) },
1752
+ handler: async (ctx, args) => {
1753
+ const page = await ctx.db.query('sites').paginate({ cursor: args.cursor ?? null, numItems: 1 })
1754
+ const sites = []
1755
+ for (const site of page.page) {
1756
+ const rows = await ctx.db.query('entries').withIndex('by_site_brick_order', (q) => q.eq('site', site._id)).collect()
1757
+ const sums = storageSums(rows)
1758
+ const counters = { bytes: site.bytes, trashBytes: site.trashBytes, treeBytes: site.treeBytes }
1759
+ sites.push({
1760
+ site: site.slug,
1761
+ legacyRows: rows.filter((row) => row.trees !== undefined || row.contentAt === undefined || row.treeBytes === undefined).length,
1762
+ countersMatch: counters.bytes === sums.bytes && counters.trashBytes === sums.trashBytes && counters.treeBytes === sums.treeBytes,
1763
+ counters,
1764
+ sums,
1765
+ overLimit: rows.filter((row) => entryBytes(row.data, row.prints) > BUDGET.entryBytes).map((row) => row._id),
1766
+ })
1767
+ }
1768
+ return { sites, cursor: page.continueCursor, isDone: page.isDone }
1769
+ },
1770
+ })