@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.
- package/CHANGELOG.md +13 -0
- package/LICENSE +21 -0
- package/README.md +176 -2
- package/convex/_generated/api.d.ts +185 -0
- package/convex/_generated/api.js +23 -0
- package/convex/_generated/dataModel.d.ts +60 -0
- package/convex/_generated/server.d.ts +162 -0
- package/convex/_generated/server.js +101 -0
- package/convex/account.ts +110 -0
- package/convex/agent.ts +814 -0
- package/convex/auth.config.ts +4 -0
- package/convex/auth.ts +62 -0
- package/convex/backup.ts +94 -0
- package/convex/betterAuth/_generated/api.ts +56 -0
- package/convex/betterAuth/_generated/component.ts +431 -0
- package/convex/betterAuth/_generated/dataModel.ts +60 -0
- package/convex/betterAuth/_generated/server.ts +169 -0
- package/convex/betterAuth/adapter.ts +7 -0
- package/convex/betterAuth/convex.config.ts +3 -0
- package/convex/betterAuth/schema.ts +102 -0
- package/convex/betterAuth/schemaMetadata.ts +697 -0
- package/convex/betterAuth/schemaOptions.ts +13 -0
- package/convex/betterAuth/schemaPlugins.ts +13 -0
- package/convex/bundle.ts +183 -0
- package/convex/changes.ts +136 -0
- package/convex/cleanup.ts +44 -0
- package/convex/connect.ts +143 -0
- package/convex/convex.config.ts +7 -0
- package/convex/crons.ts +14 -0
- package/convex/demo.ts +72 -0
- package/convex/entries.ts +1770 -0
- package/convex/facts.ts +129 -0
- package/convex/files.ts +631 -0
- package/convex/http.ts +21 -0
- package/convex/image.ts +45 -0
- package/convex/images.ts +54 -0
- package/convex/invites.ts +227 -0
- package/convex/lib/access.ts +180 -0
- package/convex/lib/agentTools.ts +331 -0
- package/convex/lib/content.ts +317 -0
- package/convex/lib/corpus.ts +83 -0
- package/convex/lib/diff.ts +50 -0
- package/convex/lib/fail.ts +27 -0
- package/convex/lib/files.ts +70 -0
- package/convex/lib/history.ts +103 -0
- package/convex/lib/i18n.ts +52 -0
- package/convex/lib/input.ts +57 -0
- package/convex/lib/library.ts +28 -0
- package/convex/lib/lifecycle.ts +100 -0
- package/convex/lib/list.ts +112 -0
- package/convex/lib/migrations.ts +126 -0
- package/convex/lib/names.ts +56 -0
- package/convex/lib/pending.ts +84 -0
- package/convex/lib/policy.ts +155 -0
- package/convex/lib/publicness.ts +87 -0
- package/convex/lib/reminders.ts +27 -0
- package/convex/lib/search.ts +132 -0
- package/convex/lib/siteUrl.ts +95 -0
- package/convex/lib/status.ts +109 -0
- package/convex/lib/translation.ts +56 -0
- package/convex/lib/trees.ts +43 -0
- package/convex/lib/write.ts +296 -0
- package/convex/mail.ts +136 -0
- package/convex/members.ts +129 -0
- package/convex/migrations.ts +105 -0
- package/convex/navigation.ts +276 -0
- package/convex/ops.ts +50 -0
- package/convex/proposals.ts +753 -0
- package/convex/refresh.ts +163 -0
- package/convex/release.ts +435 -0
- package/convex/reminders.ts +116 -0
- package/convex/retention.ts +121 -0
- package/convex/routes/bundle.ts +62 -0
- package/convex/routes/connect.ts +80 -0
- package/convex/routes/export.ts +23 -0
- package/convex/routes/file.ts +34 -0
- package/convex/routes/key.ts +53 -0
- package/convex/routes/mcp.ts +300 -0
- package/convex/routes/release.ts +66 -0
- package/convex/routes/upload.ts +94 -0
- package/convex/schema.ts +443 -0
- package/convex/search.ts +58 -0
- package/convex/seed.ts +624 -0
- package/convex/siteDeletion.ts +78 -0
- package/convex/sites.ts +393 -0
- package/convex/tasks.ts +51 -0
- package/convex/tsconfig.json +27 -0
- package/convex/uploads.ts +429 -0
- package/convex/uploadsNode.ts +86 -0
- package/convex/views.ts +111 -0
- package/i18n/de.json +364 -0
- package/i18n/en.json +364 -0
- package/i18n/es.json +364 -0
- package/i18n/fr.json +364 -0
- package/package.json +45 -3
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// The hard delete of a site (GDPR). `sites.startDeletion` schedules `purge` for 7 days later; it removes every row that
|
|
2
|
+
// names the site, the stored files and image variants behind its uploads, and last the site row itself. `purgeNow`
|
|
3
|
+
// starts it at once, for operators on a local backend or the demo platform only.
|
|
4
|
+
// One run handles a bounded batch per table and schedules itself again until nothing is left.
|
|
5
|
+
import { v } from 'convex/values'
|
|
6
|
+
import { internal } from './_generated/api'
|
|
7
|
+
import type { Doc, Id, TableNames } from './_generated/dataModel'
|
|
8
|
+
import { internalMutation } from './_generated/server'
|
|
9
|
+
import { fail } from './lib/access'
|
|
10
|
+
import { purgeUpload } from './lib/library'
|
|
11
|
+
|
|
12
|
+
/** Rows per table and run. Entries, changes and proposals carry big documents, so fewer of them fit in one transaction. */
|
|
13
|
+
const BATCH = 100
|
|
14
|
+
const HEAVY_BATCH = 20
|
|
15
|
+
const TREE_BATCH = 5
|
|
16
|
+
|
|
17
|
+
export const purge = internalMutation({
|
|
18
|
+
args: { site: v.id('sites') },
|
|
19
|
+
handler: async (ctx, args): Promise<null> => {
|
|
20
|
+
const site = await ctx.db.get(args.site)
|
|
21
|
+
// Cancelled (or an old job after a cancel and a new start): nothing to do.
|
|
22
|
+
if (!site?.deleting || site.deleting.at > Date.now()) return null
|
|
23
|
+
const id = args.site
|
|
24
|
+
let more = false
|
|
25
|
+
const sweep = async <T extends { _id: Id<TableNames> }>(cap: number, find: (n: number) => Promise<T[]>, remove?: (row: T) => Promise<void>) => {
|
|
26
|
+
const rows = await find(cap)
|
|
27
|
+
for (const row of rows) await (remove ? remove(row) : ctx.db.delete(row._id))
|
|
28
|
+
if (rows.length === cap) more = true
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
await sweep(BATCH, (n) => ctx.db.query('uploads').withIndex('by_site', (q) => q.eq('site', id)).take(n), (row: Doc<'uploads'>) => purgeUpload(ctx, row))
|
|
32
|
+
await sweep(BATCH, (n) => ctx.db.query('fileRefs').withIndex('by_site_holder', (q) => q.eq('site', id)).take(n))
|
|
33
|
+
await sweep(BATCH, (n) => ctx.db.query('folders').withIndex('by_site_parent', (q) => q.eq('site', id)).take(n))
|
|
34
|
+
await sweep(BATCH, (n) => ctx.db.query('revBumps').withIndex('by_site', (q) => q.eq('site', id)).take(n))
|
|
35
|
+
await sweep(BATCH, (n) => ctx.db.query('uploadTickets').withIndex('by_site', (q) => q.eq('site', id)).take(n))
|
|
36
|
+
await sweep(BATCH, (n) => ctx.db.query('pendingChanges').withIndex('by_site', (q) => q.eq('site', id)).take(n))
|
|
37
|
+
await sweep(BATCH, (n) => ctx.db.query('slugs').withIndex('by_key', (q) => q.eq('site', id)).take(n))
|
|
38
|
+
// A part of an entry's trees holds up to about 900 KB.
|
|
39
|
+
await sweep(TREE_BATCH, (n) => ctx.db.query('entryTrees').withIndex('by_site', (q) => q.eq('site', id)).take(n))
|
|
40
|
+
await sweep(HEAVY_BATCH, (n) => ctx.db.query('entries').withIndex('by_site_brick_order', (q) => q.eq('site', id)).take(n))
|
|
41
|
+
await sweep(HEAVY_BATCH, (n) => ctx.db.query('changes').withIndex('by_site_at', (q) => q.eq('site', id)).take(n))
|
|
42
|
+
await sweep(HEAVY_BATCH, (n) => ctx.db.query('proposals').withIndex('by_site', (q) => q.eq('site', id)).take(n))
|
|
43
|
+
await sweep(BATCH, (n) => ctx.db.query('releases').withIndex('by_site_status', (q) => q.eq('site', id)).take(n))
|
|
44
|
+
await sweep(BATCH, (n) => ctx.db.query('ops').withIndex('by_site_actor_op', (q) => q.eq('site', id)).take(n))
|
|
45
|
+
await sweep(BATCH, (n) => ctx.db.query('migrationsApplied').withIndex('by_site_id', (q) => q.eq('site', id)).take(n))
|
|
46
|
+
await sweep(BATCH, (n) => ctx.db.query('views').withIndex('by_site_user_brick', (q) => q.eq('site', id)).take(n))
|
|
47
|
+
await sweep(BATCH, (n) => ctx.db.query('reminders').withIndex('by_site_brick_week_user', (q) => q.eq('site', id)).take(n))
|
|
48
|
+
await sweep(BATCH, (n) => ctx.db.query('rateWindows').withIndex('by_site_kind_window', (q) => q.eq('site', id)).take(n))
|
|
49
|
+
await sweep(BATCH, (n) => ctx.db.query('agentKeys').withIndex('by_site_user', (q) => q.eq('site', id)).take(n))
|
|
50
|
+
await sweep(BATCH, (n) => ctx.db.query('pushKeys').withIndex('by_site', (q) => q.eq('site', id)).take(n))
|
|
51
|
+
await sweep(BATCH, (n) => ctx.db.query('connectRequests').withIndex('by_site', (q) => q.eq('site', id)).take(n))
|
|
52
|
+
await sweep(BATCH, (n) => ctx.db.query('invites').withIndex('by_site', (q) => q.eq('site', id)).take(n))
|
|
53
|
+
await sweep(BATCH, (n) => ctx.db.query('memberships').withIndex('by_site', (q) => q.eq('site', id)).take(n))
|
|
54
|
+
|
|
55
|
+
// The site row goes in the same transaction that found every other table empty, so no orphan can follow.
|
|
56
|
+
if (more) await ctx.scheduler.runAfter(0, internal.siteDeletion.purge, { site: id })
|
|
57
|
+
else await ctx.db.delete(id)
|
|
58
|
+
return null
|
|
59
|
+
},
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Operator: deletes a site now instead of in 7 days (`npx convex run siteDeletion:purgeNow '{"slug":"…"}'`). Only on a
|
|
64
|
+
* local backend or the demo platform (GINKO_DEMO=1), whose sites are rebuilt from git; a client's site keeps the 7 days
|
|
65
|
+
* in which its owner can still cancel.
|
|
66
|
+
*/
|
|
67
|
+
export const purgeNow = internalMutation({
|
|
68
|
+
args: { slug: v.string() },
|
|
69
|
+
handler: async (ctx, args) => {
|
|
70
|
+
if (process.env.GINKO_LOCAL !== '1' && process.env.GINKO_DEMO !== '1') fail('FORBIDDEN', 'errors.localOrDemoOnly')
|
|
71
|
+
const site = await ctx.db.query('sites').withIndex('by_slug', (q) => q.eq('slug', args.slug)).unique()
|
|
72
|
+
if (!site) fail('SITE_NOT_FOUND', 'errors.siteMissing')
|
|
73
|
+
if (site.deleting) await ctx.scheduler.cancel(site.deleting.job)
|
|
74
|
+
const job = await ctx.scheduler.runAfter(0, internal.siteDeletion.purge, { site: site._id })
|
|
75
|
+
await ctx.db.patch(site._id, { deleting: { at: Date.now(), job } })
|
|
76
|
+
return { slug: args.slug }
|
|
77
|
+
},
|
|
78
|
+
})
|
package/convex/sites.ts
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
// Site queries for the UI and the admin-only creation of a site (SPEC 4.2, 10).
|
|
2
|
+
import { isCurrency, isLocale, isTimeZone, isVisible, labelOf as labelIn, MAX_LOCALES, ordered, todayIn, weekInfoOf, type Schema } from '@lupinum/ginko/internal'
|
|
3
|
+
import { v } from 'convex/values'
|
|
4
|
+
import { internal } from './_generated/api'
|
|
5
|
+
import type { Doc } from './_generated/dataModel'
|
|
6
|
+
import { internalMutation, mutation, query, type MutationCtx, type QueryCtx } from './_generated/server'
|
|
7
|
+
import { actorFor, currentUser, fail, memberOf, type Actor } from './lib/access'
|
|
8
|
+
import { NAME_MAX, SLUG } from './lib/input'
|
|
9
|
+
import { secret } from './release'
|
|
10
|
+
import { isReminded, reminderBricks } from './lib/reminders'
|
|
11
|
+
import { statesOf } from './lib/status'
|
|
12
|
+
import { isFetchableSiteUrl } from './lib/siteUrl'
|
|
13
|
+
import { leafStatus } from './lib/translation'
|
|
14
|
+
import { titleOf } from './lib/list'
|
|
15
|
+
import { pendingBySite } from './lib/pending'
|
|
16
|
+
import { advance, stepArgs } from './lib/migrations'
|
|
17
|
+
import type { Data } from './lib/content'
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The sites the signed-in user may open, with their role. Admins see every site. A site being deleted is listed for
|
|
21
|
+
* owners and admins only (they can cancel), marked `deleting`. `weekly`: the weekly reminder can mail this person about
|
|
22
|
+
* the site, for a weekly task or a status line (reminders.ts; it mails members only). The order is the database's; the Studio sorts by name.
|
|
23
|
+
*/
|
|
24
|
+
export const mine = query({
|
|
25
|
+
args: {},
|
|
26
|
+
handler: async (ctx) => {
|
|
27
|
+
const user = await currentUser(ctx)
|
|
28
|
+
const memberships = await ctx.db.query('memberships').withIndex('by_user_site', (q) => q.eq('user', user.id)).collect()
|
|
29
|
+
const row = (site: Doc<'sites'>, role: 'admin' | Doc<'memberships'>['role']) => {
|
|
30
|
+
const member = memberships.find((m) => m.site === site._id)
|
|
31
|
+
const weekly = !!member && reminderBricks(site.schema as Schema).some(({ refs }) => isReminded(member, refs))
|
|
32
|
+
return { slug: site.slug, name: site.name, url: site.url, role, deleting: !!site.deleting, weekly }
|
|
33
|
+
}
|
|
34
|
+
const admin = await ctx.db.query('admins').withIndex('by_user', (q) => q.eq('user', user.id)).unique()
|
|
35
|
+
if (admin) return (await ctx.db.query('sites').collect()).map((site) => row(site, 'admin'))
|
|
36
|
+
const sites = await Promise.all(memberships.map((member) => ctx.db.get(member.site)))
|
|
37
|
+
return memberships.flatMap((member, index) => {
|
|
38
|
+
const site = sites[index]
|
|
39
|
+
return site && (!site.deleting || member.role === 'owner') ? [row(site, member.role)] : []
|
|
40
|
+
})
|
|
41
|
+
},
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The status lines of Today (UI.md 3) for the bricks this person has a task on, in schema order: each brick's line
|
|
46
|
+
* (`status` on the brick, or the drafts of a collection) and whether its section is due. Bricks with neither are
|
|
47
|
+
* left out. Staff count only their own drafts.
|
|
48
|
+
*/
|
|
49
|
+
export const today = query({
|
|
50
|
+
args: { site: v.string() },
|
|
51
|
+
handler: async (ctx, args) => {
|
|
52
|
+
const actor = await actorFor(ctx, args.site)
|
|
53
|
+
const schema = actor.site.schema as Schema
|
|
54
|
+
const staff = actor.role === 'staff'
|
|
55
|
+
const keys = ordered(schema.bricks).filter(([key, brick]) => (brick.tasks ?? []).some((task) => !staff || actor.grants.includes(`${key}.${task.id}`))).map(([key]) => key)
|
|
56
|
+
const states = await statesOf(ctx, actor.site, keys, todayIn(schema.timeZone), staff ? actor.user.id : undefined)
|
|
57
|
+
return states.filter((state) => state.line || state.due)
|
|
58
|
+
},
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
/** Days between the start of a site deletion and the hard delete. */
|
|
62
|
+
export const DELETION_DAYS = 7
|
|
63
|
+
|
|
64
|
+
/** Owner or admin of the site, also while it is being deleted. Anyone else (and an unknown site) gets FORBIDDEN as everywhere. */
|
|
65
|
+
async function deletionActor(ctx: QueryCtx, slug: string): Promise<Actor> {
|
|
66
|
+
const user = await currentUser(ctx)
|
|
67
|
+
const site = await ctx.db.query('sites').withIndex('by_slug', (q) => q.eq('slug', slug)).unique()
|
|
68
|
+
const actor = site ? await memberOf(ctx, site, user, { deleting: true }) : null
|
|
69
|
+
if (!actor) fail('FORBIDDEN', 'errors.noAccess')
|
|
70
|
+
if (actor.role === 'staff') fail('FORBIDDEN', 'errors.ownersOnly')
|
|
71
|
+
return actor
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** When the site will be deleted (ms) and its name, for the banner; null when no deletion is running or the caller may not cancel it. */
|
|
75
|
+
export const deletion = query({
|
|
76
|
+
args: { site: v.string() },
|
|
77
|
+
handler: async (ctx, args) => {
|
|
78
|
+
const user = await currentUser(ctx)
|
|
79
|
+
const site = await ctx.db.query('sites').withIndex('by_slug', (q) => q.eq('slug', args.site)).unique()
|
|
80
|
+
const actor = site?.deleting ? await memberOf(ctx, site, user, { deleting: true }) : null
|
|
81
|
+
return actor && actor.role !== 'staff' ? { name: actor.site.name, at: actor.site.deleting!.at } : null
|
|
82
|
+
},
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Starts the deletion of a site (GDPR): confirmed by its address, owners and admins only. From now on nobody opens the site
|
|
87
|
+
* but to cancel, the public bundle answers as for an unknown site and keys stop working; `siteDeletion.purge` removes
|
|
88
|
+
* everything after `DELETION_DAYS` days.
|
|
89
|
+
*/
|
|
90
|
+
export const startDeletion = mutation({
|
|
91
|
+
args: { site: v.string(), confirm: v.string() },
|
|
92
|
+
handler: async (ctx, args) => {
|
|
93
|
+
const actor = await deletionActor(ctx, args.site)
|
|
94
|
+
if (args.confirm !== actor.site.slug) fail('INVALID', 'errors.deleteSiteConfirm')
|
|
95
|
+
if (actor.site.deleting) return { at: actor.site.deleting.at }
|
|
96
|
+
const at = Date.now() + DELETION_DAYS * 24 * 60 * 60 * 1000
|
|
97
|
+
const job = await ctx.scheduler.runAt(at, internal.siteDeletion.purge, { site: actor.site._id })
|
|
98
|
+
await ctx.db.patch(actor.site._id, { deleting: { at, job } })
|
|
99
|
+
return { at }
|
|
100
|
+
},
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
/** Stops a running site deletion; owners and admins only. */
|
|
104
|
+
export const cancelDeletion = mutation({
|
|
105
|
+
args: { site: v.string() },
|
|
106
|
+
handler: async (ctx, args) => {
|
|
107
|
+
const actor = await deletionActor(ctx, args.site)
|
|
108
|
+
if (actor.site.deleting) {
|
|
109
|
+
await ctx.scheduler.cancel(actor.site.deleting.job)
|
|
110
|
+
await ctx.db.patch(actor.site._id, { deleting: undefined })
|
|
111
|
+
}
|
|
112
|
+
return null
|
|
113
|
+
},
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* One site's settings and counters with its schema, and the caller's own role and grants: what every Studio page
|
|
118
|
+
* reads. No entries: each page reads the ones it shows (entries.list, get, single, titles, ofBricks), so a save
|
|
119
|
+
* does not send the whole site to every open tab. `refreshToken` is never returned.
|
|
120
|
+
*/
|
|
121
|
+
export const meta = query({
|
|
122
|
+
args: { site: v.string() },
|
|
123
|
+
handler: async (ctx, args) => {
|
|
124
|
+
const actor = await actorFor(ctx, args.site)
|
|
125
|
+
const site = actor.site
|
|
126
|
+
return {
|
|
127
|
+
site: {
|
|
128
|
+
slug: site.slug,
|
|
129
|
+
name: site.name,
|
|
130
|
+
url: site.url,
|
|
131
|
+
previewOrigins: site.previewOrigins,
|
|
132
|
+
schema: site.schema,
|
|
133
|
+
schemaRev: site.schemaRev,
|
|
134
|
+
contentRev: site.contentRev,
|
|
135
|
+
entryCount: site.entryCount,
|
|
136
|
+
bytes: site.bytes,
|
|
137
|
+
/** Whether the trash holds removed entries (Alles bearbeiten links to it). From the trash's byte counter, so no read of the trash; removed entries of retired bricks count too. */
|
|
138
|
+
hasTrash: (site.trashBytes ?? 0) > 0,
|
|
139
|
+
release: site.release,
|
|
140
|
+
/** The site setting for agent review (SPEC 17); null: the config's `agents.review` decides. */
|
|
141
|
+
agentReview: site.agentReview ?? null,
|
|
142
|
+
/** When the live site last proved it shows the current revision (an urgent refresh that every page confirmed); null: never. */
|
|
143
|
+
lastRefreshAt: site.lastRefreshAt ?? null,
|
|
144
|
+
/** Whether the site has a site token (`refreshToken`); the token itself is never returned. */
|
|
145
|
+
hasSiteToken: site.refreshToken !== undefined,
|
|
146
|
+
},
|
|
147
|
+
role: actor.role,
|
|
148
|
+
grants: actor.grants,
|
|
149
|
+
}
|
|
150
|
+
},
|
|
151
|
+
})
|
|
152
|
+
|
|
153
|
+
/** Switches review of agent writes for the whole site (SPEC 17); `null` hands the decision back to the config. Owners and admins only. */
|
|
154
|
+
export const setAgentReview = mutation({
|
|
155
|
+
args: { site: v.string(), review: v.union(v.boolean(), v.null()) },
|
|
156
|
+
handler: async (ctx, args) => {
|
|
157
|
+
const actor = await actorFor(ctx, args.site)
|
|
158
|
+
if (actor.role === 'staff') fail('FORBIDDEN', 'errors.ownersOnly')
|
|
159
|
+
await ctx.db.patch(actor.site._id, { agentReview: args.review ?? undefined })
|
|
160
|
+
return { review: args.review }
|
|
161
|
+
},
|
|
162
|
+
})
|
|
163
|
+
|
|
164
|
+
/** Creates a site with an empty schema (SPEC 2.1 shape, no bricks yet); its first release brings the bricks. */
|
|
165
|
+
async function insertSite(ctx: MutationCtx, args: { slug: string; name: string; url: string; timeZone?: string; locales?: string[]; currency?: string }) {
|
|
166
|
+
if (!SLUG.test(args.slug)) fail('INVALID', 'errors.siteAddressFormat')
|
|
167
|
+
const name = args.name.trim()
|
|
168
|
+
if (!name) fail('INVALID', 'errors.nameMissing')
|
|
169
|
+
if (name.length > NAME_MAX) fail('INVALID', 'errors.nameTooLong', { nameMax: NAME_MAX })
|
|
170
|
+
let url: URL | undefined
|
|
171
|
+
try {
|
|
172
|
+
url = new URL(args.url)
|
|
173
|
+
} catch {
|
|
174
|
+
// fails below
|
|
175
|
+
}
|
|
176
|
+
if (url?.protocol !== 'http:' && url?.protocol !== 'https:') fail('INVALID', 'errors.siteAddressNotUrl')
|
|
177
|
+
if (!isFetchableSiteUrl(args.url, process.env.GINKO_LOCAL === '1')) fail('INVALID', 'errors.siteUrlNotAllowed')
|
|
178
|
+
// Defaults stay Vienna, German, EUR; the first release may still change them while the site has no bricks.
|
|
179
|
+
const timeZone = args.timeZone ?? 'Europe/Vienna'
|
|
180
|
+
const locales = args.locales ?? ['de']
|
|
181
|
+
const currency = args.currency ?? 'EUR'
|
|
182
|
+
if (!isTimeZone(timeZone)) fail('INVALID', 'errors.siteTimezoneInvalid', { timeZone })
|
|
183
|
+
if (locales.length < 1 || locales.length > MAX_LOCALES || !locales.every(isLocale) || new Set(locales).size !== locales.length) fail('INVALID', 'errors.siteLocalesInvalid', { max: MAX_LOCALES })
|
|
184
|
+
if (!isCurrency(currency)) fail('INVALID', 'errors.siteCurrencyInvalid', { currency })
|
|
185
|
+
const existing = await ctx.db.query('sites').withIndex('by_slug', (q) => q.eq('slug', args.slug)).unique()
|
|
186
|
+
if (existing) fail('SLUG_TAKEN', 'errors.addressTaken')
|
|
187
|
+
|
|
188
|
+
const schema = {
|
|
189
|
+
site: args.slug,
|
|
190
|
+
name,
|
|
191
|
+
url: args.url,
|
|
192
|
+
timeZone,
|
|
193
|
+
locales,
|
|
194
|
+
currency,
|
|
195
|
+
// Every stored schema has `week` (the hourly reminder sweep reads it for every site); the first release replaces it.
|
|
196
|
+
week: weekInfoOf(locales[0]!),
|
|
197
|
+
pages: {},
|
|
198
|
+
bricks: {},
|
|
199
|
+
migrations: [],
|
|
200
|
+
retired: {},
|
|
201
|
+
}
|
|
202
|
+
await ctx.db.insert('sites', {
|
|
203
|
+
slug: args.slug,
|
|
204
|
+
name,
|
|
205
|
+
url: args.url,
|
|
206
|
+
previewOrigins: [],
|
|
207
|
+
schema,
|
|
208
|
+
schemaRev: 1,
|
|
209
|
+
contentRev: 1,
|
|
210
|
+
entryCount: 0,
|
|
211
|
+
bytes: 0,
|
|
212
|
+
trashBytes: 0,
|
|
213
|
+
treeBytes: 0,
|
|
214
|
+
release: null,
|
|
215
|
+
})
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Whether the signed-in person is a platform admin: only they create sites. */
|
|
219
|
+
async function isAdmin(ctx: QueryCtx): Promise<boolean> {
|
|
220
|
+
const user = await currentUser(ctx)
|
|
221
|
+
return (await ctx.db.query('admins').withIndex('by_user', (q) => q.eq('user', user.id)).unique()) !== null
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Whether the signed-in person may create a site, for "New site" on "My sites". `sites.mine` cannot tell: an admin of
|
|
226
|
+
* a platform without a site has no row there.
|
|
227
|
+
*/
|
|
228
|
+
export const mayCreate = query({
|
|
229
|
+
args: {},
|
|
230
|
+
handler: (ctx) => isAdmin(ctx),
|
|
231
|
+
})
|
|
232
|
+
|
|
233
|
+
/** Admin only, from the Studio's "New site" page. */
|
|
234
|
+
export const create = mutation({
|
|
235
|
+
args: { slug: v.string(), name: v.string(), url: v.string(), timeZone: v.optional(v.string()), locales: v.optional(v.array(v.string())), currency: v.optional(v.string()) },
|
|
236
|
+
handler: async (ctx, args) => {
|
|
237
|
+
if (!(await isAdmin(ctx))) fail('FORBIDDEN', 'errors.onlyAdminsCreateSites')
|
|
238
|
+
await insertSite(ctx, args)
|
|
239
|
+
return { slug: args.slug }
|
|
240
|
+
},
|
|
241
|
+
})
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* The first site of a new deployment, before anyone can sign in (`npx convex run sites:bootstrap`).
|
|
245
|
+
* Internal: only a holder of the deployment's admin or deploy key reaches it.
|
|
246
|
+
*/
|
|
247
|
+
export const bootstrap = internalMutation({
|
|
248
|
+
args: { slug: v.string(), name: v.string(), url: v.string() },
|
|
249
|
+
handler: async (ctx, args) => {
|
|
250
|
+
await insertSite(ctx, args)
|
|
251
|
+
return { slug: args.slug }
|
|
252
|
+
},
|
|
253
|
+
})
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* The site's Vercel bypass token (`NUXT_GINKO_REVALIDATE_TOKEN` in the site), so "urgent refresh" can
|
|
257
|
+
* regenerate its pages (SPEC 4.4). Set once per deploy setup; never returned by any query.
|
|
258
|
+
* Internal: deploy or admin key only (`npx convex run sites:setRefreshToken`).
|
|
259
|
+
*/
|
|
260
|
+
export const setRefreshToken = internalMutation({
|
|
261
|
+
args: { slug: v.string(), token: v.string() },
|
|
262
|
+
handler: async (ctx, args) => {
|
|
263
|
+
const site = await ctx.db.query('sites').withIndex('by_slug', (q) => q.eq('slug', args.slug)).unique()
|
|
264
|
+
if (!site) fail('SITE_NOT_FOUND', 'errors.siteMissing')
|
|
265
|
+
if (args.token.length < 32) fail('INVALID', 'errors.tokenTooShort')
|
|
266
|
+
await ctx.db.patch(site._id, { refreshToken: args.token })
|
|
267
|
+
return { slug: args.slug }
|
|
268
|
+
},
|
|
269
|
+
})
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* An owner creates the site token, or replaces it: the website sets it as `NUXT_GINKO_REVALIDATE_TOKEN`. It lets the
|
|
273
|
+
* site's server load content without the visitor rate limit and lets "Update website now" refresh the pages. The
|
|
274
|
+
* platform must send it to Vercel, so it is stored as it is (like `setRefreshToken`) and returned only here, once.
|
|
275
|
+
*/
|
|
276
|
+
export const createSiteToken = mutation({
|
|
277
|
+
args: { site: v.string() },
|
|
278
|
+
handler: async (ctx, args) => {
|
|
279
|
+
const actor = await actorFor(ctx, args.site)
|
|
280
|
+
// Owners, and the platform's admins who set sites up for them; never staff.
|
|
281
|
+
if (actor.role === 'staff') fail('FORBIDDEN', 'errors.ownersOnly')
|
|
282
|
+
// 64 characters: Vercel's bypass token needs at least 32.
|
|
283
|
+
const token = `${secret()}${secret()}`
|
|
284
|
+
await ctx.db.patch(actor.site._id, { refreshToken: token })
|
|
285
|
+
return { token }
|
|
286
|
+
},
|
|
287
|
+
})
|
|
288
|
+
|
|
289
|
+
/** The most entries the translation overview lists; the counts stay complete beyond it. */
|
|
290
|
+
const TRANSLATION_ROWS = 200
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Translation status (SPEC 4.2): per brick and per language other than the main one, how many entries
|
|
294
|
+
* have every text (`ok`), at least one missing text (`missing`), or only outdated ones (`outdated`).
|
|
295
|
+
* It uses the rule of the bundle (`resolveEntry`), so it matches what ginko_read reports. It counts what the
|
|
296
|
+
* website shows: live entries and singles, not drafts, and no entry whose date has passed (`isVisible`, as the
|
|
297
|
+
* site's listings). `entries` lists the entries with a gap for the Studio's overview ("Übersetzungen"), by
|
|
298
|
+
* brick in config order and then the site's order, at most TRANSLATION_ROWS (`truncated`): the title (null for
|
|
299
|
+
* a single and an untitled entry: the Studio shows the area), how many texts are missing or outdated, and
|
|
300
|
+
* whether the gap keeps the page off the website in that language (`hidden`). Titles of planned weeks are in
|
|
301
|
+
* `language`. Any member may read; staff get the areas of their tasks (as in Alles bearbeiten), so the list
|
|
302
|
+
* and the count cover the same entries.
|
|
303
|
+
*/
|
|
304
|
+
export const translationStatus = query({
|
|
305
|
+
args: { site: v.string(), language: v.optional(v.string()) },
|
|
306
|
+
handler: async (ctx, args) => {
|
|
307
|
+
const actor = await actorFor(ctx, args.site)
|
|
308
|
+
const schema = actor.site.schema as Schema
|
|
309
|
+
const foreign = schema.locales.slice(1)
|
|
310
|
+
const bricks = []
|
|
311
|
+
const entries: { brick: string; entry: string; title: string | null; locale: string; missing: number; outdated: number; hidden: boolean }[] = []
|
|
312
|
+
let truncated = false
|
|
313
|
+
const today = todayIn(schema.timeZone)
|
|
314
|
+
const opens = (key: string, tasks: readonly { id: string }[] = []) => actor.role !== 'staff' || tasks.some((t) => actor.grants.includes(`${key}.${t.id}`))
|
|
315
|
+
for (const [key, def] of ordered(schema.bricks)) {
|
|
316
|
+
if (def.retired || !opens(key, def.tasks)) continue
|
|
317
|
+
const rows = (await ctx.db.query('entries').withIndex('by_site_brick_order', (q) => q.eq('site', actor.site._id).eq('brick', key)).collect())
|
|
318
|
+
.filter((row) => !row.deletedAt && row.state !== 'draft' && isVisible(def, row.data as Data, today))
|
|
319
|
+
const locales: Record<string, { missing: number; outdated: number; ok: number }> = {}
|
|
320
|
+
for (const locale of foreign) locales[locale] = { missing: 0, outdated: 0, ok: 0 }
|
|
321
|
+
for (const row of rows) {
|
|
322
|
+
for (const locale of foreign) {
|
|
323
|
+
const status = leafStatus(schema, key, row, locale)
|
|
324
|
+
const out = locales[locale]!
|
|
325
|
+
// One count per entry: a missing text outweighs an outdated one.
|
|
326
|
+
if (status.missing.length) out.missing += 1
|
|
327
|
+
else if (status.outdated.length) out.outdated += 1
|
|
328
|
+
else out.ok += 1
|
|
329
|
+
if (!status.missing.length && !status.outdated.length) continue
|
|
330
|
+
if (entries.length >= TRANSLATION_ROWS) { truncated = true; continue }
|
|
331
|
+
entries.push({
|
|
332
|
+
brick: key, entry: row._id, title: def.kind === 'single' ? null : titleOf(schema, def, row.data as Data, args.language),
|
|
333
|
+
locale, missing: status.missing.length, outdated: status.outdated.length, hidden: status.page === 'hidden',
|
|
334
|
+
})
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
bricks.push({ brick: key, label: labelIn(def.label, schema.locales[0]!, schema.locales[0]!), kind: def.kind, locales })
|
|
338
|
+
}
|
|
339
|
+
return { main: schema.locales[0]!, locales: foreign, bricks, entries, truncated }
|
|
340
|
+
},
|
|
341
|
+
})
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* The areas of the site as the Studio lists them (Content overview, area list): per brick in config order the number
|
|
345
|
+
* of entries (drafts included, removed ones not), drafts, live entries with unpublished changes, ended entries (not visible today), open translations (one
|
|
346
|
+
* per entry and foreign language with a missing or outdated text, counted like `translationStatus`) and when its
|
|
347
|
+
* content last changed. Staff see the bricks of their tasks only, like `translationStatus`. One read per brick.
|
|
348
|
+
*/
|
|
349
|
+
export const areas = query({
|
|
350
|
+
args: { site: v.string() },
|
|
351
|
+
handler: async (ctx, args) => {
|
|
352
|
+
const actor = await actorFor(ctx, args.site)
|
|
353
|
+
const schema = actor.site.schema as Schema
|
|
354
|
+
const foreign = schema.locales.slice(1)
|
|
355
|
+
const today = todayIn(schema.timeZone)
|
|
356
|
+
const opens = (key: string, tasks: readonly { id: string }[] = []) => actor.role !== 'staff' || tasks.some((t) => actor.grants.includes(`${key}.${t.id}`))
|
|
357
|
+
const held = await pendingBySite(ctx, actor.site._id)
|
|
358
|
+
const out: { brick: string; kind: 'single' | 'collection'; count: number; drafts: number; changes: number; ended: number; translations: number; changedAt: number | null }[] = []
|
|
359
|
+
for (const [key, def] of ordered(schema.bricks)) {
|
|
360
|
+
if (def.retired || !opens(key, def.tasks)) continue
|
|
361
|
+
const rows = (await ctx.db.query('entries').withIndex('by_site_brick_order', (q) => q.eq('site', actor.site._id).eq('brick', key)).collect())
|
|
362
|
+
.filter((row) => !row.deletedAt)
|
|
363
|
+
let drafts = 0, changes = 0, ended = 0, translations = 0, changedAt: number | null = null
|
|
364
|
+
for (const row of rows) {
|
|
365
|
+
const at = row.contentAt ?? row._creationTime
|
|
366
|
+
if (changedAt === null || at > changedAt) changedAt = at
|
|
367
|
+
if (row.state === 'draft') { drafts += 1; continue }
|
|
368
|
+
if (held.has(row._id)) changes += 1
|
|
369
|
+
if (!isVisible(def, row.data as Data, today)) { ended += 1; continue }
|
|
370
|
+
for (const locale of foreign) {
|
|
371
|
+
const status = leafStatus(schema, key, row, locale)
|
|
372
|
+
if (status.missing.length || status.outdated.length) translations += 1
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
out.push({ brick: key, kind: def.kind, count: rows.length, drafts, changes, ended, translations, changedAt })
|
|
376
|
+
}
|
|
377
|
+
return out
|
|
378
|
+
},
|
|
379
|
+
})
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* A migration step (lib/migrations.ts, internals/migrations.md): removes the unused `orderRevs` from every site, in
|
|
383
|
+
* one page. Running it again is safe.
|
|
384
|
+
*/
|
|
385
|
+
export const dropOrderRevs = internalMutation({
|
|
386
|
+
args: stepArgs,
|
|
387
|
+
handler: async (ctx, args): Promise<null> => {
|
|
388
|
+
for (const site of await ctx.db.query('sites').collect()) {
|
|
389
|
+
if (site.orderRevs !== undefined) await ctx.db.patch(site._id, { orderRevs: undefined })
|
|
390
|
+
}
|
|
391
|
+
return advance(ctx, args.run, null)
|
|
392
|
+
},
|
|
393
|
+
})
|
package/convex/tasks.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Task queries (SPEC 2.7). `prefill` gives the starting values of a task's form. The server
|
|
2
|
+
// resolves date tokens in the site's time zone; mutations never apply these values.
|
|
3
|
+
import type { Json } from '@lupinum/ginko'
|
|
4
|
+
import { duePlan, resolveToken, todayIn, type Schema } from '@lupinum/ginko/internal'
|
|
5
|
+
import { v, type ObjectType } from 'convex/values'
|
|
6
|
+
import { query, type QueryCtx } from './_generated/server'
|
|
7
|
+
import { actorFor, entryOf, fail, taskBrickOf, type Actor } from './lib/access'
|
|
8
|
+
|
|
9
|
+
const prefillArgs = { site: v.string(), task: v.string(), entry: v.optional(v.string()) }
|
|
10
|
+
|
|
11
|
+
export const prefill = query({ args: prefillArgs, handler: async (ctx, args) => prefillAs(ctx, await actorFor(ctx, args.site), args) })
|
|
12
|
+
|
|
13
|
+
/** `prefill` for an actor already known (platform or agent door, SPEC 16). */
|
|
14
|
+
export async function prefillAs(ctx: QueryCtx, actor: Actor, args: ObjectType<typeof prefillArgs>): Promise<Json> {
|
|
15
|
+
const schema = actor.site.schema as Schema
|
|
16
|
+
// Every member may read the whole site (SPEC 2.7), so the task is looked up without grants.
|
|
17
|
+
const [brickKey, taskId, ...rest] = args.task.split('.')
|
|
18
|
+
const brick = brickKey && Object.hasOwn(schema.bricks, brickKey) ? schema.bricks[brickKey] : undefined
|
|
19
|
+
const task = brick && taskId && rest.length === 0 ? brick.tasks?.find((t) => t.id === taskId) : undefined
|
|
20
|
+
if (!brickKey || !brick || !task) fail('INVALID', 'errors.taskNotFound', undefined, { task: args.task })
|
|
21
|
+
|
|
22
|
+
const prefill = 'prefill' in task ? (task.prefill ?? {}) : {}
|
|
23
|
+
const values: Record<string, Json> = {}
|
|
24
|
+
for (const [key, raw] of Object.entries(prefill)) {
|
|
25
|
+
if (!Object.hasOwn(brick.fields, key) || raw === undefined) continue
|
|
26
|
+
const token = typeof raw === 'string' ? resolveToken(raw, schema.timeZone, schema.week) : undefined
|
|
27
|
+
values[key] = token ?? raw
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// An edit starts from the stored values of the fields it touches; the prefill overrides them.
|
|
31
|
+
let stored: Record<string, Json> = {}
|
|
32
|
+
if (task.kind === 'edit' && args.entry !== undefined) {
|
|
33
|
+
const entry = await entryOf(ctx, actor, args.entry)
|
|
34
|
+
// The entry of the task's brick, or a week planned ahead that stands in for it this week.
|
|
35
|
+
if (taskBrickOf(schema, args.task, entry) !== brickKey) fail('NOT_FOUND', 'errors.entryNotFound')
|
|
36
|
+
const data = entry.data as Record<string, Json>
|
|
37
|
+
stored = Object.fromEntries(task.fields.filter((f) => data[f] !== undefined).map((f): [string, Json] => [f, data[f]!]))
|
|
38
|
+
// A planned change whose day has come is what the site shows: the task opens on it, and saving drops the spent plan.
|
|
39
|
+
const plan = brick.planned
|
|
40
|
+
const due = plan && [plan.field, plan.next, plan.from].every((f) => task.fields.includes(f)) ? duePlan(brick, data, todayIn(schema.timeZone)) : undefined
|
|
41
|
+
if (plan && due !== undefined) stored = { ...stored, [plan.field]: due, [plan.next]: null, [plan.from]: null }
|
|
42
|
+
}
|
|
43
|
+
// A day already set that has not passed stays: reopening "Heute geschlossen" keeps tomorrow's closure instead of
|
|
44
|
+
// moving it to today. Only @today does this; a week token always gives the week the task is for.
|
|
45
|
+
for (const [key, raw] of Object.entries(prefill)) {
|
|
46
|
+
const kept = stored[key]
|
|
47
|
+
const today = values[key]
|
|
48
|
+
if (raw === '@today' && typeof kept === 'string' && typeof today === 'string' && kept >= today) delete values[key]
|
|
49
|
+
}
|
|
50
|
+
return { ...stored, ...values }
|
|
51
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
/* This TypeScript project config describes the environment that
|
|
3
|
+
* Convex functions run in and is used to typecheck them.
|
|
4
|
+
* You can modify it, but some settings are required to use Convex.
|
|
5
|
+
*/
|
|
6
|
+
"compilerOptions": {
|
|
7
|
+
/* These settings are not required by Convex and can be modified. */
|
|
8
|
+
"allowJs": true,
|
|
9
|
+
"strict": true,
|
|
10
|
+
"moduleResolution": "Bundler",
|
|
11
|
+
"jsx": "react-jsx",
|
|
12
|
+
"skipLibCheck": true,
|
|
13
|
+
"allowSyntheticDefaultImports": true,
|
|
14
|
+
"allowImportingTsExtensions": true,
|
|
15
|
+
"types": ["node"],
|
|
16
|
+
|
|
17
|
+
/* These compiler options are required by Convex */
|
|
18
|
+
"target": "ESNext",
|
|
19
|
+
"lib": ["ES2023", "dom"],
|
|
20
|
+
"forceConsistentCasingInFileNames": true,
|
|
21
|
+
"module": "ESNext",
|
|
22
|
+
"isolatedModules": true,
|
|
23
|
+
"noEmit": true
|
|
24
|
+
},
|
|
25
|
+
"include": ["./**/*"],
|
|
26
|
+
"exclude": ["./_generated", "./**/*.test.ts"]
|
|
27
|
+
}
|