@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,105 @@
1
+ // One-time data migrations of the platform, run by themselves after each deploy: the build script calls
2
+ // `migrations:runPending` right after `convex deploy`. The list and the runner are in lib/migrations.ts; every
3
+ // migration has its entry in internals/migrations.md. Progress: `npx convex run ops:status`.
4
+ import { carryPrints, entryBytes, mapMarkdownTexts, stableJson, type Schema } from '@lupinum/ginko/internal'
5
+ import { v } from 'convex/values'
6
+ import type { Doc, Id } from './_generated/dataModel'
7
+ import { internalMutation, type MutationCtx } from './_generated/server'
8
+ import { treesOf, type Data, type Prints } from './lib/content'
9
+ import { advance as advanceRun, runPending as startPending, stepArgs } from './lib/migrations'
10
+ import { putTrees } from './lib/trees'
11
+ import { entryUses, syncEntryRefs } from './lib/write'
12
+
13
+ /**
14
+ * Starts what is pending after a deploy and returns one line for the build log (lib/migrations.ts `runPending`).
15
+ * `npx convex run --prod migrations:runPending` in the build script; safe to call at any time.
16
+ */
17
+ export const runPending = internalMutation({
18
+ args: {},
19
+ handler: (ctx): Promise<string> => startPending(ctx),
20
+ })
21
+
22
+ /** The end of an action step's page (mutation steps call lib/migrations.ts `advance` in their own transaction). */
23
+ export const advance = internalMutation({
24
+ args: { run: v.id('serverMigrations'), next: v.union(v.string(), v.null()) },
25
+ handler: (ctx, args): Promise<null> => advanceRun(ctx, args.run, args.next),
26
+ })
27
+
28
+ /** A storage address in a text, with or without its host: group 1 is its token (everything after `/api/storage/`). */
29
+ const STORAGE_URL = /(?:https?:\/\/[^\s()<>"'\]]+?)?\/api\/storage\/([^\s()<>"']+)/g
30
+
31
+ /** The token of a storage address, or undefined. */
32
+ const tokenOf = (url: string | null) => (url ? /\/api\/storage\/([^\s()<>"']+)/.exec(url)?.[1] : undefined)
33
+
34
+ /**
35
+ * Markdown texts that hold a picture as its storage address (`http://127.0.0.1:3210/api/storage/…`, written by the
36
+ * editor before `$file.<id>` existed) get the reference instead: the file then counts as used (the daily sweep keeps
37
+ * it, Trash warns, backups take it) and the address no longer depends on the host it was written on. An address is
38
+ * matched by its token against the current addresses of the site's uploads (original, processed file, variants);
39
+ * an address that matches none stays as it is. Changed entries get new trees and file references; at the end the
40
+ * site counters are recounted (the list runs `entries:recountStorage` after it). A migration step, 10 entries per page.
41
+ */
42
+ export const markdownStorageUrls = internalMutation({
43
+ args: stepArgs,
44
+ handler: async (ctx, args): Promise<null> => {
45
+ const page = await ctx.db.query('entries').paginate({ cursor: args.cursor, numItems: 10 })
46
+ const sites = new Map<Id<'sites'>, { site: Doc<'sites'> | null } & TokenScan>()
47
+ const touched = new Set<Id<'sites'>>()
48
+ for (const row of page.page) {
49
+ if (!sites.has(row.site)) sites.set(row.site, { site: await ctx.db.get(row.site), found: new Map() })
50
+ const known = sites.get(row.site)!
51
+ const schema = known.site?.schema as Schema | undefined
52
+ const brick = schema && Object.hasOwn(schema.bricks, row.brick) ? schema.bricks[row.brick]! : undefined
53
+ if (!schema || !brick) continue
54
+ const tokens = new Set<string>()
55
+ mapMarkdownTexts(brick.fields, row.data, (text) => { for (const m of text.matchAll(STORAGE_URL)) tokens.add(m[1]!); return text })
56
+ if (!tokens.size) continue
57
+ const uploads = await uploadTokens(ctx, row.site, tokens, known)
58
+ const data = mapMarkdownTexts(brick.fields, row.data, (text) => text.replace(STORAGE_URL, (url, token: string) => {
59
+ const upload = uploads.get(token)
60
+ return upload ? `$file.${upload}` : url
61
+ })) as Data
62
+ if (stableJson(data) === stableJson(row.data)) continue
63
+ const trees = row.deletedAt === undefined ? await treesOf(brick.fields, data) : { json: '', bytes: 0 }
64
+ // A changed field raises its revision like a save: a Studio draft that still holds the old addresses gets a
65
+ // conflict instead of saving over the migrated text.
66
+ const rev = row.rev + 1
67
+ const fieldRevs = { ...row.fieldRevs }
68
+ for (const root of Object.keys(data)) if (stableJson(data[root] ?? null) !== stableJson(row.data[root] ?? null)) fieldRevs[root] = rev
69
+ // The same picture under its new name: a translation that was current stays current.
70
+ const prints = carryPrints(brick.fields, row.data as Data, data, row.prints as Prints, schema.locales[0]!)
71
+ await ctx.db.patch(row._id, { data, rev, fieldRevs, prints, bytes: entryBytes(data, prints), treeBytes: trees.bytes })
72
+ await putTrees(ctx, row.site, row._id, trees.json)
73
+ await syncEntryRefs(ctx, row.site, row._id, await entryUses(ctx, brick.fields, data, schema.locales))
74
+ if (row.deletedAt === undefined && row.state !== 'draft') touched.add(row.site)
75
+ }
76
+ // The bundle now serves the files' sizes and variants: its caches must refresh.
77
+ for (const id of touched) {
78
+ const site = await ctx.db.get(id)
79
+ if (site) await ctx.db.patch(id, { contentRev: site.contentRev + 1 })
80
+ }
81
+ return advanceRun(ctx, args.run, page.isDone ? null : page.continueCursor)
82
+ },
83
+ })
84
+
85
+ /** What one run learned of a site's storage addresses: token → upload, and the site's uploads not yet read. */
86
+ interface TokenScan { found: Map<string, Id<'uploads'>>; rest?: AsyncIterator<Doc<'uploads'>> }
87
+
88
+ /**
89
+ * The uploads behind `tokens` (storage address tokens of one text) among the current addresses of the site's uploads
90
+ * (original, processed file, variants). Reads the site's uploads only until every token is known and remembers what it
91
+ * read in `scan` for the next entry of the run, so a run asks for the address of each file at most once.
92
+ */
93
+ async function uploadTokens(ctx: MutationCtx, site: Id<'sites'>, tokens: ReadonlySet<string>, scan: TokenScan): Promise<Map<string, Id<'uploads'>>> {
94
+ scan.rest ??= ctx.db.query('uploads').withIndex('by_site', (q) => q.eq('site', site))[Symbol.asyncIterator]()
95
+ while ([...tokens].some((token) => !scan.found.has(token))) {
96
+ const next = await scan.rest.next()
97
+ if (next.done) break
98
+ const upload = next.value
99
+ for (const id of [upload.processedId, upload.storageId, ...(upload.variants ?? []).map((variant) => variant.storageId)]) {
100
+ const token = id === undefined ? undefined : tokenOf(await ctx.storage.getUrl(id))
101
+ if (token && !scan.found.has(token)) scan.found.set(token, upload._id)
102
+ }
103
+ }
104
+ return scan.found
105
+ }
@@ -0,0 +1,276 @@
1
+ // The side navigation of a manually ordered collection whose pages nest through a `parent` ref to the same collection
2
+ // (the docs layer): the Studio reads it as a tree, moves a page (order, parent and the section/tab handover in one
3
+ // step) and sets, renames or removes a section or tab heading. The rules are core's (`outline`, `placePlan`), the same the website uses.
4
+ import type { CollectionBrick, Field, Json, Locale } from '@lupinum/ginko'
5
+ import { isNavTree, isTranslatable, outline, placePlan, sortEntries, validate, walkOutline, type OutlineRow, type Place, type Schema } from '@lupinum/ginko/internal'
6
+ import { v } from 'convex/values'
7
+ import type { Doc, Id } from './_generated/dataModel'
8
+ import { mutation, query, type MutationCtx, type QueryCtx } from './_generated/server'
9
+ import { actorFor, byOf, checkRev, entryOf, fail, idempotent, type Actor } from './lib/access'
10
+ import { mergeField, nextPrints, type Data } from './lib/content'
11
+ import { msg, recorded } from './lib/history'
12
+ import { commitEntry, lookupsFor } from './lib/write'
13
+ import { titleOf } from './lib/list'
14
+
15
+ /** The fields that place a page in the navigation; a move checks and writes only these. */
16
+ const PLACE_FIELDS = ['parent', 'section', 'tab'] as const
17
+
18
+ /** A collection shown as a tree: manual order and a `parent` ref to itself. Fails for any other brick. */
19
+ export function treeBrick(schema: Schema, key: string): CollectionBrick {
20
+ const brick = Object.hasOwn(schema.bricks, key) ? schema.bricks[key] : undefined
21
+ if (!brick || brick.retired) fail('INVALID', 'errors.brickNoLongerEditable')
22
+ if (!isNavTree(key, brick)) fail('INVALID', 'errors.notANavigationTree', undefined, { brick: key })
23
+ return brick
24
+ }
25
+
26
+ /** A text field's value in one language ('' counts as none); undefined when the brick has no such text field. */
27
+ function textIn(field: Field | undefined, value: unknown, locale: Locale, main: Locale): string | undefined {
28
+ if (!field || (field.type !== 'text' && field.type !== 'longtext')) return undefined
29
+ const text = typeof value === 'string' ? value : value && typeof value === 'object' ? ((value as Record<string, unknown>)[locale] ?? (value as Record<string, unknown>)[main]) : undefined
30
+ return typeof text === 'string' && text.trim() ? text : undefined
31
+ }
32
+
33
+ /** The brick's pages that are not in the trash, drafts included, in stored order. */
34
+ async function pagesOf(ctx: QueryCtx, site: Id<'sites'>, key: string, brick: CollectionBrick): Promise<Doc<'entries'>[]> {
35
+ const rows = await ctx.db.query('entries').withIndex('by_site_brick_deleted', (q) => q.eq('site', site).eq('brick', key).eq('deletedAt', undefined)).collect()
36
+ const byId = new Map(rows.map((r) => [r._id as string, r]))
37
+ return sortEntries(brick, rows.map((r) => ({ id: r._id, order: r.order, data: r.data }))).map((s) => byId.get(s.id)!)
38
+ }
39
+
40
+ /**
41
+ * The pages as core's outline rows: the stored parent (a page in the trash is missing from the rows, so the page is a
42
+ * root, as on the website), the own section and tab in the main language (the rules run on it), and `draft` for a page
43
+ * the website does not show.
44
+ */
45
+ function rowsOf(schema: Schema, brick: CollectionBrick, pages: Doc<'entries'>[]): OutlineRow[] {
46
+ const main = schema.locales[0]!
47
+ return pages.map((p) => {
48
+ const data = p.data as Data
49
+ const parent = typeof data.parent === 'string' ? data.parent : undefined
50
+ const section = textIn(brick.fields.section, data.section, main, main)
51
+ const tab = textIn(brick.fields.tab, data.tab, main, main)
52
+ return { id: p._id, ...(parent ? { parent } : {}), ...(section ? { section } : {}), ...(tab ? { tab } : {}), ...((p.state ?? 'live') !== 'live' ? { draft: true } : {}) }
53
+ })
54
+ }
55
+
56
+ /**
57
+ * The pages of a tree collection in stored order, as core's outline rows (`outline` builds the website's tree from
58
+ * them) with what the Studio's tree shows and checks: title, short title, badge, state, the heading labels in
59
+ * `language` (else the main one) and the revision a move is based on. Any member may read (SPEC 2.7).
60
+ */
61
+ export const tree = query({
62
+ args: { site: v.string(), brick: v.string(), language: v.optional(v.string()) },
63
+ handler: async (ctx, args) => {
64
+ const actor = await actorFor(ctx, args.site)
65
+ const schema = actor.site.schema as Schema
66
+ const brick = treeBrick(schema, args.brick)
67
+ const main = schema.locales[0]!
68
+ const language = (args.language && schema.locales.includes(args.language as Locale) ? args.language : main) as Locale
69
+ const pages = await pagesOf(ctx, actor.site._id, args.brick, brick)
70
+ const rows = rowsOf(schema, brick, pages)
71
+ return pages.map((p, i) => {
72
+ const data = p.data as Data
73
+ const text = (key: string) => textIn(brick.fields[key], data[key], language, main) ?? null
74
+ return {
75
+ ...rows[i]!, rev: p.rev, state: p.state ?? 'live', publishAt: p.publishAt ?? null,
76
+ title: titleOf(schema, brick, data, language), navTitle: text('navTitle'), badge: text('badge'),
77
+ // Labels in the language shown, for the headings (the rules run on the main language).
78
+ sectionLabel: text('section'), tabLabel: text('tab'),
79
+ }
80
+ })
81
+ },
82
+ })
83
+
84
+ const placeArg = v.union(
85
+ v.object({ parent: v.string(), after: v.optional(v.string()) }),
86
+ v.object({ after: v.string() }),
87
+ v.object({ before: v.string() }),
88
+ )
89
+
90
+ /** Owners and admins only: no task covers the structure (SPEC 2.7), as for `entries.move`. */
91
+ function refuseStaff(actor: Actor) {
92
+ if (actor.role === 'staff') fail('FORBIDDEN', 'errors.notYourTask')
93
+ }
94
+
95
+ /** Refuses when the fields `roots` of the entry changed after the revision the person saw. */
96
+ function refuseChanged(entry: Doc<'entries'>, baseRev: number, roots: readonly string[]) {
97
+ if (entry.deletedAt) fail('CHANGED_SINCE', 'errors.thisEntryDeletedSince')
98
+ const current = { entry: entry._id, rev: entry.rev, data: entry.data as Json, fieldRevs: entry.fieldRevs, deleted: false }
99
+ if (baseRev > entry.rev) fail('CHANGED_SINCE', 'errors.someoneChangedMeanwhile', undefined, current)
100
+ const conflicts = roots.filter((r) => (entry.fieldRevs[r] ?? 0) > baseRev)
101
+ if (conflicts.length) fail('CHANGED_SINCE', 'errors.someoneChangedMeanwhile', undefined, { ...current, conflicts })
102
+ }
103
+
104
+ /** Writes `data` into one entry with the shared write path (revisions, history, budget); re-reads the site each time. */
105
+ async function writeData(ctx: MutationCtx, actor: Actor, entry: Doc<'entries'>, brick: CollectionBrick, roots: string[], data: Data, line: ReturnType<typeof msg>, opId: string) {
106
+ const schema = actor.site.schema as Schema
107
+ const site = (await ctx.db.get(actor.site._id))!
108
+ const prints = nextPrints({ fields: brick.fields, roots, before: entry.data as Data, after: data, prints: entry.prints, main: schema.locales[0]!, confirm: undefined })
109
+ return commitEntry(ctx, { actor: { ...actor, site }, entry, fields: brick.fields, roots, data, prints, kind: 'place', history: recorded(line, schema), opId })
110
+ }
111
+
112
+ /**
113
+ * Moves one page, with its subpages, to `place` in a tree collection (SPEC 4.2): its order, its parent, and the
114
+ * section or tab heading it hands over or takes over, in one step. Every other page keeps where the website shows it
115
+ * (core `placePlan`). `baseRev` is the page's revision the person saw: a change of its place since then is a conflict;
116
+ * text edits are not. Refuses a place inside the page itself or its subpages. Owners and admins only.
117
+ */
118
+ export const move = mutation({
119
+ args: { site: v.string(), opId: v.string(), entry: v.string(), baseRev: v.number(), place: placeArg },
120
+ handler: async (ctx, args): Promise<Json> => {
121
+ checkRev(args.baseRev)
122
+ const actor = await actorFor(ctx, args.site)
123
+ return idempotent(ctx, actor, args, async () => {
124
+ const entry = await entryOf(ctx, actor, args.entry)
125
+ const schema = actor.site.schema as Schema
126
+ const brick = treeBrick(schema, entry.brick)
127
+ refuseStaff(actor)
128
+ refuseChanged(entry, args.baseRev, PLACE_FIELDS)
129
+
130
+ const pages = await pagesOf(ctx, actor.site._id, entry.brick, brick)
131
+ const rows = rowsOf(schema, brick, pages)
132
+ const plan = placePlan(rows, entry._id, args.place as Place)
133
+ if (plan === 'cycle') fail('INVALID', 'errors.placeInsideItself')
134
+ if (plan === 'missing') fail('CHANGED_SINCE', 'errors.placeGone')
135
+ if (plan === 'invalid') fail('INVALID', 'errors.placeInvalid')
136
+ if (!Object.keys(plan.patch).length && plan.order.every((id, i) => id === pages[i]!._id)) {
137
+ return { moved: false, contentRev: actor.site.contentRev }
138
+ }
139
+
140
+ const byId = new Map(pages.map((p) => [p._id as string, p]))
141
+ const block = new Set(walkOutline([walkOutline(outline(rows)).find((n) => n.row.id === entry._id)!]).map((n) => n.row.id))
142
+ const orders = newOrders(plan.order.map((id) => byId.get(id)!), block)
143
+ const title = titleOf(schema, brick, entry.data as Data, undefined) ?? entry.brick
144
+ let publicChange = false
145
+ let committed = false
146
+
147
+ for (const [id, p] of Object.entries(plan.patch)) {
148
+ const page = (await ctx.db.get(id as Id<'entries'>))!
149
+ const before = page.data as Data
150
+ const data: Data = { ...before }
151
+ if (p.parent === null) delete data.parent
152
+ else if (p.parent !== undefined) data.parent = p.parent
153
+ for (const key of ['section', 'tab'] as const) {
154
+ const w = p[key]
155
+ if (w === null) delete data[key]
156
+ else if (w) data[key] = (byId.get(w.from)!.data as Data)[key]!
157
+ }
158
+ const roots = PLACE_FIELDS.filter((k) => p[k] !== undefined)
159
+ const pageTitle = titleOf(schema, brick, before, undefined) ?? entry.brick
160
+ await writeData(ctx, actor, page, brick, roots, data, id === entry._id ? msg('history.placed', { title }) : msg('history.headingHandedOver', { title: pageTitle, from: title }), args.opId)
161
+ if ((page.state ?? 'live') === 'live') { publicChange = true; committed = true }
162
+ }
163
+
164
+ for (const [id, order] of orders) {
165
+ const page = (await ctx.db.get(id as Id<'entries'>))!
166
+ // A page whose data was written above has its new revision already; an order alone counts as a change too.
167
+ await ctx.db.patch(page._id, plan.patch[id] ? { order } : { order, rev: page.rev + 1 })
168
+ if ((page.state ?? 'live') === 'live') publicChange = true
169
+ }
170
+
171
+ let site = (await ctx.db.get(actor.site._id))!
172
+ if (publicChange && !committed) {
173
+ await ctx.db.patch(site._id, { contentRev: site.contentRev + 1 })
174
+ site = (await ctx.db.get(site._id))!
175
+ }
176
+ // The history line of a move that only changed the order (with data, `commitEntry` wrote it).
177
+ if (!plan.patch[entry._id]) {
178
+ const now = (await ctx.db.get(entry._id))!
179
+ await ctx.db.insert('changes', {
180
+ site: site._id, entry: entry._id, brick: entry.brick, ...byOf(actor), opId: args.opId, kind: 'reorder',
181
+ ...recorded(msg('history.placed', { title }), schema), entryRev: now.rev, contentRev: site.contentRev, at: Date.now(),
182
+ })
183
+ }
184
+ return { moved: true, contentRev: site.contentRev }
185
+ })
186
+ },
187
+ })
188
+
189
+ /**
190
+ * New order values for the pages in `order` (the brick's live pages in their new order) that need one: the block
191
+ * between its neighbours, or every page 1..n when the gap is used up or older data has equal values. Pages in the
192
+ * trash keep theirs (a restore puts a page last).
193
+ */
194
+ function newOrders(order: Doc<'entries'>[], block: Set<string>): Map<string, number> {
195
+ const out = new Map<string, number>()
196
+ const first = order.findIndex((p) => block.has(p._id))
197
+ const last = first + block.size - 1
198
+ const lo = order[first - 1]?.order
199
+ const hi = order[last + 1]?.order
200
+ const step = lo !== undefined && hi !== undefined ? (hi - lo) / (block.size + 1) : 1
201
+ const start = lo ?? (hi !== undefined ? hi - block.size - 1 : 0)
202
+ const values = Array.from({ length: block.size }, (_, i) => start + step * (i + 1))
203
+ const others = order.filter((p) => !block.has(p._id)).map((p) => p.order)
204
+ const fits = others.every((o, i) => i === 0 || o > others[i - 1]!)
205
+ && [lo ?? -Infinity, ...values, hi ?? Infinity].every((o, i, all) => i === 0 || o > all[i - 1]!)
206
+ if (fits) {
207
+ order.slice(first, last + 1).forEach((p, i) => { if (p.order !== values[i]) out.set(p._id, values[i]!) })
208
+ return out
209
+ }
210
+ order.forEach((p, i) => { if (p.order !== i + 1) out.set(p._id, i + 1) })
211
+ return out
212
+ }
213
+
214
+ /**
215
+ * Sets a section or tab heading on a top-level page, in one language (SPEC 4.2): a page without one starts a new
216
+ * heading there (the pages after it join it); a page that starts one renames it, together with the following pages of
217
+ * the same run (a section) or tab that repeat the text, so the heading stays one group; an empty text removes the
218
+ * heading in every language (its pages join the heading before). `baseRev`: the page's revision. Goes online at once,
219
+ * like a move. Owners and admins only.
220
+ */
221
+ export const heading = mutation({
222
+ args: { site: v.string(), opId: v.string(), entry: v.string(), baseRev: v.number(), field: v.union(v.literal('section'), v.literal('tab')), locale: v.string(), text: v.string() },
223
+ handler: async (ctx, args): Promise<Json> => {
224
+ checkRev(args.baseRev)
225
+ const actor = await actorFor(ctx, args.site)
226
+ return idempotent(ctx, actor, args, async () => {
227
+ const entry = await entryOf(ctx, actor, args.entry)
228
+ const schema = actor.site.schema as Schema
229
+ const brick = treeBrick(schema, entry.brick)
230
+ const field = brick.fields[args.field]
231
+ if (!field || field.type !== 'text') fail('INVALID', 'errors.notANavigationTree', undefined, { brick: entry.brick })
232
+ refuseStaff(actor)
233
+ refuseChanged(entry, args.baseRev, [args.field, 'parent'])
234
+ const locale = args.locale as Locale
235
+ if (!schema.locales.includes(locale)) fail('INVALID', 'errors.languageNotSetUp', { locale })
236
+ const text = args.text.trim()
237
+
238
+ const main = schema.locales[0]!
239
+ const pages = await pagesOf(ctx, actor.site._id, entry.brick, brick)
240
+ const roots = outline(rowsOf(schema, brick, pages))
241
+ const at = roots.findIndex((r) => r.row.id === entry._id)
242
+ // Nested pages follow their parent: the website ignores a heading on them.
243
+ if (at < 0) fail('INVALID', 'errors.headingOnSubpage')
244
+ const own = (p: Doc<'entries'>) => textIn(field, (p.data as Data)[args.field], locale, main)
245
+ const old = own(entry)
246
+ if (!old && !text) return { changed: 0, contentRev: actor.site.contentRev }
247
+ if (old === text) return { changed: 0, contentRev: actor.site.contentRev }
248
+ const byId = new Map(pages.map((p) => [p._id as string, p]))
249
+ // A new heading starts at this page only; a tab is all roots with that name; a section the run from this page.
250
+ let targets: Doc<'entries'>[] = [entry]
251
+ if (old && args.field === 'tab') targets = roots.map((r) => byId.get(r.row.id)!).filter((p) => own(p) === old)
252
+ else if (old) {
253
+ const run = [roots[at]!]
254
+ for (let i = at + 1; i < roots.length && roots[i]!.section === roots[at]!.section && roots[i]!.tab === roots[at]!.tab; i++) run.push(roots[i]!)
255
+ targets = run.map((r) => byId.get(r.row.id)!).filter((p) => own(p) === old)
256
+ }
257
+ const line = !text ? msg(args.field === 'tab' ? 'history.tabRemoved' : 'history.sectionRemoved', { name: old! })
258
+ : !old ? msg(args.field === 'tab' ? 'history.tabStarted' : 'history.sectionStarted', { name: text })
259
+ : msg(args.field === 'tab' ? 'history.tabRenamed' : 'history.sectionRenamed', { from: old, to: text })
260
+
261
+ for (const page of targets) {
262
+ const before = page.data as Data
263
+ const data: Data = { ...before }
264
+ if (!text) delete data[args.field]
265
+ // A new heading gets the text in the main language too: the structure follows the main language.
266
+ else if (!old && isTranslatable(field)) data[args.field] = mergeField(field, undefined, { [main]: text, [locale]: text }, undefined)!
267
+ else data[args.field] = mergeField(field, before[args.field] as Json | undefined, isTranslatable(field) ? { [locale]: text } : text, locale)!
268
+ const { errors } = await validate(schema, page.brick, data, { mode: 'patch', changed: new Set([args.field]), ...(await lookupsFor(ctx, actor.site._id, brick.fields, data)) })
269
+ if (errors.length) fail('INVALID', 'errors.pleaseCheckMarkedFields', undefined, { errors: errors as unknown as Json })
270
+ await writeData(ctx, actor, page, brick, [args.field], data, line, args.opId)
271
+ }
272
+ const site = (await ctx.db.get(actor.site._id))!
273
+ return { changed: targets.length, contentRev: site.contentRev }
274
+ })
275
+ },
276
+ })
package/convex/ops.ts ADDED
@@ -0,0 +1,50 @@
1
+ // Operator tools (internal; run with `convex run ops:<name>`): what state the uploads are in, so a stuck or
2
+ // failed upload can be found and repaired (`uploads:retry`) without reading Convex's tables by hand, and how far the
3
+ // data migrations that run after each deploy are.
4
+ import { v } from 'convex/values'
5
+ import type { Doc } from './_generated/dataModel'
6
+ import { internalQuery, type QueryCtx } from './_generated/server'
7
+ import { migrationStatus } from './lib/migrations'
8
+ import { isStale } from './uploads'
9
+
10
+ const LIST_MAX = 50
11
+
12
+ async function describe(ctx: QueryCtx, row: Doc<'uploads'>, slugs: Map<string, string>, now: number) {
13
+ if (!slugs.has(row.site)) slugs.set(row.site, (await ctx.db.get(row.site))?.slug ?? '(deleted site)')
14
+ const referenced = (await ctx.db.query('fileRefs').withIndex('by_file', (q) => q.eq('file', row._id)).first()) !== null
15
+ return {
16
+ id: row._id, site: slugs.get(row.site)!, name: row.name, attempts: row.attempts, error: row.error ?? null,
17
+ ageMinutes: Math.round((now - row._creationTime) / 60_000), referenced,
18
+ }
19
+ }
20
+
21
+ /**
22
+ * Upload counts per status and, for the rows that need a look, up to 50 stuck `processing` uploads (uploads.isStale)
23
+ * and up to 50 `failed` ones (oldest first). `site` is a slug; leave it out for every site. Ready uploads are counted
24
+ * for one site only: across the platform they are too many for one query.
25
+ * `migrations`: how many are done, which are pending, and the one running or stopped (with its error); a stopped one
26
+ * starts again from where it stopped with the next deploy (lib/migrations.ts).
27
+ */
28
+ export const status = internalQuery({
29
+ args: { site: v.optional(v.string()) },
30
+ handler: async (ctx, { site }) => {
31
+ const now = Date.now()
32
+ const siteRow = site === undefined ? null : await ctx.db.query('sites').withIndex('by_slug', (q) => q.eq('slug', site)).unique()
33
+ if (site !== undefined && !siteRow) return null
34
+ // One site: all its uploads in one read. Every site: only the processing and failed ones.
35
+ const rows = siteRow
36
+ ? await ctx.db.query('uploads').withIndex('by_site', (q) => q.eq('site', siteRow._id)).collect()
37
+ : [
38
+ ...await ctx.db.query('uploads').withIndex('by_status', (q) => q.eq('status', 'processing')).collect(),
39
+ ...await ctx.db.query('uploads').withIndex('by_status', (q) => q.eq('status', 'failed')).collect(),
40
+ ]
41
+ const counts: { processing: number; failed: number; ready?: number } = siteRow ? { processing: 0, failed: 0, ready: 0 } : { processing: 0, failed: 0 }
42
+ for (const row of rows) if (counts[row.status] !== undefined) counts[row.status]!++
43
+ const slugs = new Map<string, string>()
44
+ const stuck = []
45
+ for (const row of rows.filter((r) => isStale(r, now)).slice(0, LIST_MAX)) stuck.push(await describe(ctx, row, slugs, now))
46
+ const failed = []
47
+ for (const row of rows.filter((r) => r.status === 'failed').slice(0, LIST_MAX)) failed.push(await describe(ctx, row, slugs, now))
48
+ return { counts, stuck, failed, migrations: await migrationStatus(ctx) }
49
+ },
50
+ })