@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,83 @@
1
+ // Demo content from a corpus (contracts/<site>/data.json), shared by the local reset (seed.ts) and
2
+ // the demo fill (demo.ts): the entries with their slugs and counters, and invites for the demo people.
3
+ import type { Json } from '@lupinum/ginko'
4
+ import { entryBytes, sha256, type Schema } from '@lupinum/ginko/internal'
5
+ import type { Doc } from '../_generated/dataModel'
6
+ import type { MutationCtx } from '../_generated/server'
7
+ import { checkGrants, normalizeEmail } from '../members'
8
+ import { treesOf } from './content'
9
+ import { putTrees } from './trees'
10
+
11
+ type CorpusEntry = { id: string; order?: number; data: Record<string, Json>; prints?: Record<string, Record<string, string>> }
12
+
13
+ /** File fields point at uploads; the corpus names files that do not exist here, so they are left out. */
14
+ function withoutFiles(schema: Schema, brick: string, data: Record<string, Json>): Record<string, Json> {
15
+ const fields = schema.bricks[brick]!.fields
16
+ const out: Record<string, Json> = {}
17
+ for (const [key, value] of Object.entries(data)) {
18
+ const field = fields[key]
19
+ if (field?.type === 'image' || field?.type === 'file') continue
20
+ if (field?.type === 'list' && Array.isArray(value) && Object.values(field.of).some((f) => f.type === 'image' || f.type === 'file')) {
21
+ out[key] = []
22
+ continue
23
+ }
24
+ out[key] = value
25
+ }
26
+ return out
27
+ }
28
+
29
+ export type Corpus = Record<string, CorpusEntry[]>
30
+ export type Person = { email: string; role: 'owner' | 'staff'; grants: string[] }
31
+
32
+ /** Inserts the corpus entries of the bricks the site knows; sets the byte counters and entryCount, and raises contentRev. */
33
+ export async function insertCorpus(ctx: MutationCtx, site: Doc<'sites'>, corpus: Corpus) {
34
+ const schema = site.schema as Schema
35
+ let bytes = 0
36
+ let treeBytes = 0
37
+ let count = 0
38
+ for (const [brick, rows] of Object.entries(corpus)) {
39
+ const def = schema.bricks[brick]
40
+ if (!def) continue
41
+ for (const [index, row] of rows.entries()) {
42
+ const data = withoutFiles(schema, brick, row.data)
43
+ const prints = row.prints ?? {}
44
+ const size = entryBytes(data, prints)
45
+ const trees = await treesOf(def.fields, data)
46
+ const fieldRevs = Object.fromEntries(Object.keys(def.fields).map((f) => [f, 1]))
47
+ const id = await ctx.db.insert('entries', {
48
+ site: site._id, brick, kind: def.kind === 'single' ? 'single' : 'item', order: row.order ?? index + 1,
49
+ data, rev: 1, fieldRevs, lifeRev: 1, prints, bytes: size, treeBytes: trees.bytes, contentAt: Date.now(),
50
+ })
51
+ await putTrees(ctx, site._id, id, trees.json)
52
+ bytes += size
53
+ treeBytes += trees.bytes
54
+ count++
55
+ for (const [name, field] of Object.entries(def.fields)) {
56
+ if (field.type !== 'slug') continue
57
+ for (const [locale, slug] of Object.entries((data[name] ?? {}) as Record<string, string>)) {
58
+ await ctx.db.insert('slugs', { site: site._id, brick, locale, slug, entry: id })
59
+ }
60
+ }
61
+ }
62
+ }
63
+ await ctx.db.patch(site._id, { bytes, trashBytes: 0, treeBytes, entryCount: count, contentRev: site.contentRev + 1 })
64
+ return { count }
65
+ }
66
+
67
+ /** One invite per person (7 days); returns the links, which a local or demo setup hands out directly. */
68
+ export async function invitePeople(ctx: MutationCtx, site: Doc<'sites'>, people: Person[], invitedBy: string) {
69
+ const schema = site.schema as Schema
70
+ const origin = (process.env.SITE_URL ?? 'http://localhost:3100').replace(/\/$/, '')
71
+ const links: { email: string; role: string; link: string }[] = []
72
+ for (const person of people) {
73
+ const bytes32 = crypto.getRandomValues(new Uint8Array(32))
74
+ const token = btoa(String.fromCharCode(...bytes32)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
75
+ const email = normalizeEmail(person.email)
76
+ await ctx.db.insert('invites', {
77
+ site: site._id, email, role: person.role, grants: person.role === 'owner' ? [] : checkGrants(schema, person.grants),
78
+ tokenHash: sha256(token), invitedBy, expiresAt: Date.now() + 7 * 24 * 60 * 60 * 1000,
79
+ })
80
+ links.push({ email, role: person.role, link: `${origin}/invite/${token}` })
81
+ }
82
+ return links
83
+ }
@@ -0,0 +1,50 @@
1
+ // The one diff builder (SPEC 4.2 "Verlauf"): changes.get and proposals.get show a change as
2
+ // a list of root fields with their old and new value. Pure functions, no Convex. Rows of a list
3
+ // are compared in core (rowDiffs), which the Studio's conflict panel uses too.
4
+ import type { Fields, Json } from '@lupinum/ginko'
5
+ import { isTranslatable, labelOf, rowDiffs, stableJson, type RowDiff } from '@lupinum/ginko/internal'
6
+
7
+ export interface LocaleDiff { locale: string; before: Json | null; after: Json | null }
8
+ export interface FieldDiff {
9
+ field: string
10
+ label: string
11
+ /** The field type from the schema (`state` for the status of a publish; `unknown` when the schema no longer has the field). */
12
+ kind: string
13
+ before: Json | null
14
+ after: Json | null
15
+ /** Translatable fields: the locales whose value differs. */
16
+ locales?: LocaleDiff[]
17
+ /** Lists: added, removed and changed rows by `_id`. */
18
+ rows?: RowDiff[]
19
+ /** Lists: the same rows in a different order. */
20
+ reordered?: boolean
21
+ }
22
+
23
+ const isRecord = (value: Json | null | undefined): value is Record<string, Json> => typeof value === 'object' && value !== null && !Array.isArray(value)
24
+ const differs = (a: Json | null | undefined, b: Json | null | undefined) => stableJson((a ?? null) as Json) !== stableJson((b ?? null) as Json)
25
+
26
+ /** The locales whose value differs between two values of a translatable field. */
27
+ export function localeDiffs(before: Json | null, after: Json | null): LocaleDiff[] {
28
+ const a = isRecord(before) ? before : {}
29
+ const b = isRecord(after) ? after : {}
30
+ return [...new Set([...Object.keys(a), ...Object.keys(b)])]
31
+ .filter((locale) => differs(a[locale], b[locale]))
32
+ .map((locale) => ({ locale, before: a[locale] ?? null, after: b[locale] ?? null }))
33
+ }
34
+
35
+ /**
36
+ * One entry per root field that appears in `before` or `after`: label and type from the schema,
37
+ * plus the per-locale or per-row detail for translatable fields and lists.
38
+ */
39
+ export function diffFields(fields: Fields | undefined, before: Record<string, Json>, after: Record<string, Json>, main: string): FieldDiff[] {
40
+ return [...new Set([...Object.keys(before), ...Object.keys(after)])].map((name): FieldDiff => {
41
+ const field = fields && Object.hasOwn(fields, name) ? fields[name] : undefined
42
+ const was = before[name] ?? null
43
+ const now = after[name] ?? null
44
+ const base = { field: name, label: field ? labelOf(field.label, main, main) : name, kind: field?.type ?? 'unknown', before: was, after: now }
45
+ if (!field) return base
46
+ if (isTranslatable(field)) return { ...base, locales: localeDiffs(was, now) }
47
+ if (field.type === 'list') return { ...base, ...rowDiffs(was, now) }
48
+ return base
49
+ })
50
+ }
@@ -0,0 +1,27 @@
1
+ import type { Json } from '@lupinum/ginko'
2
+ import { ConvexError } from 'convex/values'
3
+ import { DEFAULT_LOCALE, t, type MessageKey } from './i18n'
4
+
5
+ export type ErrorCode =
6
+ | 'FORBIDDEN' | 'NOT_FOUND' | 'CHANGED_SINCE' | 'OP_REUSED' | 'INVALID' | 'TOO_LARGE' | 'SLUG_TAKEN'
7
+ | 'NOT_UNDOABLE' | 'SCHEMA_REJECTED' | 'MIGRATION_CHANGED' | 'MIGRATION_INCOMPLETE' | 'RELEASE_TOO_LARGE'
8
+ | 'SITE_NOT_FOUND' | 'FORMAT_UNSUPPORTED' | 'STALE' | 'RATE_LIMITED' | 'UPLOAD_REJECTED'
9
+
10
+ /**
11
+ * Every error has a code, a catalog `key` with its `params`, and `message` (the German text, for agents
12
+ * and logs). The Studio translates `key` with `params` into the person's language (the catalogs are
13
+ * shared); the server holds no per-request language, so nothing depends on how Convex reuses isolates.
14
+ * `details` carries e.g. validation issues or the current state. Clients branch on `code`.
15
+ */
16
+ /** Error parameters travel to clients as Convex values: text and numbers only (no `Date`). */
17
+ export type ErrorParams = Record<string, string | number>
18
+
19
+ export function fail(code: ErrorCode, key: MessageKey, params?: ErrorParams, details?: Json): never {
20
+ throw new ConvexError({
21
+ code,
22
+ message: t(DEFAULT_LOCALE, key, params),
23
+ key,
24
+ ...(params === undefined ? {} : { params }),
25
+ ...(details === undefined ? {} : { details }),
26
+ })
27
+ }
@@ -0,0 +1,70 @@
1
+ // Allowed upload types (SPEC 4.3): the core table gives type and limit; here are the first bytes
2
+ // that prove the content, so a file cannot pass as another kind by its declared type alone.
3
+ import { formatMb, limitOf, UPLOAD_TYPES, type UploadType } from '@lupinum/ginko/internal'
4
+
5
+ const at = (bytes: Uint8Array, offset: number, text: string) => [...text].every((c, i) => bytes[offset + i] === c.charCodeAt(0))
6
+
7
+ const SIGNATURES: Record<UploadType, (bytes: Uint8Array) => boolean> = {
8
+ 'image/jpeg': (b) => b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff,
9
+ 'image/png': (b) => b[0] === 0x89 && at(b, 1, 'PNG'),
10
+ 'image/webp': (b) => at(b, 0, 'RIFF') && at(b, 8, 'WEBP'),
11
+ 'application/pdf': (b) => at(b, 0, '%PDF-'),
12
+ }
13
+
14
+ /** The brands of an HEIC/HEIF photo (an ISO media file: `ftyp` at byte 4, the main brand at byte 8). */
15
+ const HEIF_BRANDS = ['heic', 'heix', 'heim', 'heis', 'hevc', 'hevx', 'mif1', 'msf1']
16
+
17
+ /**
18
+ * An HEIC photo (iPhone) by its name, its declared type or its bytes. The image processing here (sharp) cannot read
19
+ * one, so it is refused at once with a message that says how to send a JPEG instead.
20
+ */
21
+ export function isHeic(file: { name?: string; mime?: string; bytes?: Uint8Array }): boolean {
22
+ if (/\.hei[cf]$/i.test(file.name?.trim() ?? '')) return true
23
+ if (/^image\/hei[cf](-sequence)?$/i.test((file.mime ?? '').split(';')[0]!.trim())) return true
24
+ const b = file.bytes
25
+ return !!b && at(b, 4, 'ftyp') && HEIF_BRANDS.some((brand) => at(b, 8, brand))
26
+ }
27
+
28
+ /** Why the route refuses a file, as a catalog message (the Studio shows it in the person's language). */
29
+ export const TOO_LARGE = { key: 'errors.uploadTooLarge', params: { imageMb: formatMb(limitOf('image')), fileMb: formatMb(limitOf('file')) } } as const
30
+ export const WRONG_TYPE = { key: 'errors.uploadWrongType', params: { types: Object.values(UPLOAD_TYPES).map((t) => t.label).join(', ') } } as const
31
+ export const WRONG_CONTENT = { key: 'errors.uploadWrongContent' } as const
32
+ export const EMPTY = { key: 'errors.uploadEmpty' } as const
33
+ export const HEIC = { key: 'errors.uploadHeicUnreadable' } as const
34
+
35
+ const NAME_FALLBACK = 'datei'
36
+ const NAME_MAX = 120
37
+
38
+ /**
39
+ * The name an upload is stored under. It must be safe to use as a file name later (`pnpm local:pull`,
40
+ * `ginko export`): only the part after the last / or \, no control characters (bidi overrides
41
+ * count, they hide the real extension), NFC, at most 120 characters with the extension kept.
42
+ * A name that ends up empty, or only dots, becomes "datei".
43
+ */
44
+ export function cleanName(raw: string): string {
45
+ const base = raw.normalize('NFC').split(/[\\/]/).pop()!
46
+ const name = base.replace(/[\p{Cc}\u2028\u2029\u202a-\u202e\u2066-\u2069]/gu, '').trim()
47
+ if (/^\.*$/.test(name)) return NAME_FALLBACK
48
+ if (name.length <= NAME_MAX) return name
49
+ const dot = name.lastIndexOf('.')
50
+ const extension = dot > 0 && name.length - dot <= 20 ? name.slice(dot) : ''
51
+ const head = name.slice(0, NAME_MAX - extension.length)
52
+ // Never end on half of a surrogate pair.
53
+ return (/[\ud800-\udbff]$/.test(head) ? head.slice(0, -1) : head) + extension
54
+ }
55
+
56
+ /** The kind of a declared type, or undefined when it is not allowed. */
57
+ export function kindOf(mime: string | undefined) {
58
+ const key = (mime ?? '').split(';')[0]!.trim().toLowerCase()
59
+ if (!Object.hasOwn(UPLOAD_TYPES, key)) return undefined
60
+ const type = key as UploadType
61
+ return { mime: type, kind: UPLOAD_TYPES[type].kind, limit: UPLOAD_TYPES[type].limit, signature: SIGNATURES[type] }
62
+ }
63
+
64
+ /**
65
+ * The allowed type of `kind` that the bytes prove, or undefined. The declared type only names the kind: a JPEG saved
66
+ * as `.png` (common for downloaded or forwarded photos) is a JPEG, and an image never passes as a PDF or back.
67
+ */
68
+ export function typeOfBytes(kind: 'image' | 'file', bytes: Uint8Array): UploadType | undefined {
69
+ return (Object.keys(SIGNATURES) as UploadType[]).find((type) => UPLOAD_TYPES[type].kind === kind && SIGNATURES[type](bytes))
70
+ }
@@ -0,0 +1,103 @@
1
+ // What the history says about a change or a proposal, stored as a catalog key plus params (`msg`), so
2
+ // each team member reads it in their own Studio language and dates in the site's time zone. Next to it
3
+ // the row keeps `sentence`, the German rendering, as the fallback for rows written before `msg`.
4
+ import type { Label } from '@lupinum/ginko'
5
+ import { labelOf, stableJson, type Schema } from '@lupinum/ginko/internal'
6
+ import type { Doc } from '../_generated/dataModel'
7
+ import { storedSentence } from './input'
8
+ import { t, type MessageKey } from './i18n'
9
+
10
+ /** A value in a message: text, a number (a date is milliseconds), a label per locale, or another message. */
11
+ export type Param = string | number | Label | HistoryMsg
12
+
13
+ /** A type, not an interface, so it counts as `Json` where a mutation returns it. */
14
+ export type HistoryMsg = {
15
+ /** A key of the server catalog (`history.*`, `publicness.*`). */
16
+ key: string
17
+ params?: Record<string, Param>
18
+ }
19
+
20
+ /** A message with its German rendering: what a change or proposal row stores. */
21
+ export interface Recorded {
22
+ msg: HistoryMsg
23
+ sentence: string
24
+ }
25
+
26
+ /** The site facts a message needs: the main language (labels fall back to it) and the zone of its dates. */
27
+ type Where = Pick<Schema, 'locales' | 'timeZone'>
28
+
29
+ /** The key is checked against the catalog where a message is built. */
30
+ export const msg = (key: MessageKey, params?: Record<string, Param>): HistoryMsg => (params ? { key, params } : { key })
31
+
32
+ const isMsg = (value: Param): value is HistoryMsg =>
33
+ typeof value === 'object' && typeof value.key === 'string' && Object.keys(value).every((k) => k === 'key' || k === 'params')
34
+
35
+ const HOUR = 3_600_000
36
+ const walls = new Map<string, Intl.DateTimeFormat>()
37
+ const wall = (ms: number, timeZone: string) => {
38
+ let reader = walls.get(timeZone)
39
+ if (!reader) walls.set(timeZone, reader = new Intl.DateTimeFormat('en-US', { timeZone, hourCycle: 'h23', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric' }))
40
+ return reader.format(ms)
41
+ }
42
+
43
+ /**
44
+ * Whether the clock in `timeZone` shows the time of `ms` twice: the hour the clocks go back. The catalog's
45
+ * `{twice, select, yes …}` then adds the zone's short name ("02:30 MEZ"); the Studio's `textOf` follows the same rule.
46
+ */
47
+ const twiceOnClock = (ms: number, timeZone: string) => [ms - HOUR, ms + HOUR].some((other) => wall(other, timeZone) === wall(ms, timeZone))
48
+
49
+ /** The text of a message in `locale`: nested messages first, labels in `locale` (else the main language), dates in the site's zone. */
50
+ export function historyText(message: HistoryMsg, locale: string, where: Where | undefined): string {
51
+ const main = where?.locales[0] ?? 'de'
52
+ const timeZone = where?.timeZone ?? 'UTC'
53
+ const params = Object.fromEntries(Object.entries(message.params ?? {}).map(([name, value]) => [
54
+ name,
55
+ typeof value === 'string' || typeof value === 'number' ? value : isMsg(value) ? historyText(value, locale, where) : labelOf(value, locale, main),
56
+ ]))
57
+ if (typeof params.at === 'number' && twiceOnClock(params.at, timeZone)) params.twice = 'yes'
58
+ return t(locale, message.key as MessageKey, params, { timeZone })
59
+ }
60
+
61
+ /** The row fields `msg` and `sentence` (German, cut to the stored length) for a message. */
62
+ export function recorded(message: HistoryMsg, where?: Where): Recorded {
63
+ return { msg: message, sentence: storedSentence(historyText(message, 'de', where)) }
64
+ }
65
+
66
+ /**
67
+ * Why a save can no longer be undone: undone already, its entry removed, a field changed since (another value or other
68
+ * prints than the save left, see asSaved), or the fields restructured since.
69
+ */
70
+ export type UndoBlock = 'undone' | 'removed' | 'changed' | 'schema'
71
+
72
+ /** The prints of the leaves under `root`, as one comparable text. */
73
+ const printsUnder = (prints: Record<string, unknown> | undefined, root: string) =>
74
+ stableJson(Object.fromEntries(Object.entries(prints ?? {}).filter(([leaf]) => leaf === root || leaf.startsWith(`${root}.`))))
75
+
76
+ /**
77
+ * Whether a field of the entry is still as the save left it. A later write of the field (its revision moved on) counts
78
+ * only when it left another value or other prints: after the newer save is undone, the older one is undoable again,
79
+ * while a later "Passt so" (prints only) still blocks it. An absent value and null compare equal (stableJson).
80
+ */
81
+ function asSaved(change: Pick<Doc<'changes'>, 'entryRev' | 'after' | 'printsAfter'>, entry: Pick<Doc<'entries'>, 'fieldRevs' | 'data' | 'prints'>, root: string) {
82
+ if (entry.fieldRevs[root] === change.entryRev) return true
83
+ const after: Record<string, unknown> | undefined = change.after
84
+ const data: Record<string, unknown> = entry.data
85
+ return !!after && stableJson(data[root]) === stableJson(after[root]) && printsUnder(entry.prints, root) === printsUnder(change.printsAfter, root)
86
+ }
87
+
88
+ /**
89
+ * The one rule for "can this save still be undone": the undo mutation refuses with it, and the
90
+ * history list shows it, so the list never offers an undo the server refuses. `migrated` are the
91
+ * site's applied migrations. A full validation of the old values stays a refusal at undo time.
92
+ */
93
+ export function undoBlockOf(
94
+ change: Pick<Doc<'changes'>, 'undoneBy' | 'fields' | 'entryRev' | 'at' | 'after' | 'printsAfter'>,
95
+ entry: Pick<Doc<'entries'>, 'deletedAt' | 'fieldRevs' | 'brick' | 'data' | 'prints'> | null,
96
+ migrated: Pick<Doc<'migrationsApplied'>, 'brick' | '_creationTime'>[],
97
+ ): UndoBlock | undefined {
98
+ if (change.undoneBy) return 'undone'
99
+ if (!entry || entry.deletedAt) return 'removed'
100
+ if ((change.fields ?? []).some((root) => !asSaved(change, entry, root))) return 'changed'
101
+ if (migrated.some((m) => m.brick === entry.brick && m._creationTime > change.at)) return 'schema'
102
+ return undefined
103
+ }
@@ -0,0 +1,52 @@
1
+ // Every text the server sends to a person (errors, mail) comes from a catalog in `i18n/<code>.json`
2
+ // and is written in that person's language. German is the source language and the fallback: a locale
3
+ // that lacks a key, or a locale nobody supports, shows the German text. A new language is a new
4
+ // catalog file plus one import line in `CATALOGS`.
5
+ import { compileCatalogs, type RawTree } from '@lupinum/ginko-i18n/compile'
6
+ import { defineCatalog, type KeysOf, type Params, type TranslateOptions } from '@lupinum/ginko-i18n/core'
7
+ import de from '../../i18n/de.json'
8
+ import en from '../../i18n/en.json'
9
+ import es from '../../i18n/es.json'
10
+ import fr from '../../i18n/fr.json'
11
+ import type { QueryCtx } from '../_generated/server'
12
+
13
+ export type MessageKey = KeysOf<typeof de>
14
+
15
+ export const DEFAULT_LOCALE = 'de'
16
+ export const CATALOGS: Record<string, RawTree> = { de, en, es, fr }
17
+ export const LOCALES = Object.keys(CATALOGS)
18
+
19
+ /** Compiled once when the module loads, not per call. */
20
+ const catalog = defineCatalog<MessageKey>(compileCatalogs(CATALOGS), { defaultLocale: DEFAULT_LOCALE })
21
+
22
+ export const isLocale = (value: unknown): value is string => catalog.isLocale(value)
23
+
24
+ /**
25
+ * The name of a site language (`en`) in every language the server writes, as a label that a message renders in its
26
+ * reader's language ("Englisch", "English", "inglés"). The code stays where the runtime knows no name for it.
27
+ */
28
+ export function languageLabel(code: string): Record<string, string> {
29
+ return Object.fromEntries(LOCALES.map((reader) => {
30
+ try {
31
+ return [reader, new Intl.DisplayNames(reader, { type: 'language' }).of(code) ?? code]
32
+ } catch {
33
+ return [reader, code]
34
+ }
35
+ }))
36
+ }
37
+
38
+ /**
39
+ * The text for `key` in `locale`. An unknown locale gets German; a key missing there falls back to German.
40
+ * `options.timeZone` is the zone of the dates in `params` (a site's zone), not the reader's.
41
+ */
42
+ export function t(locale: string | undefined, key: MessageKey, params?: Params, options?: TranslateOptions): string {
43
+ return catalog.t(locale, key, params, options)
44
+ }
45
+
46
+ /** The language a person chose (`userSettings.locale`), else German. */
47
+ export async function localeOfUser(ctx: Pick<QueryCtx, 'db'>, userId: string | undefined): Promise<string> {
48
+ if (!userId) return DEFAULT_LOCALE
49
+ const row = await ctx.db.query('userSettings').withIndex('by_user', (q) => q.eq('user', userId)).unique()
50
+ // The chosen language, else the one the person's browser showed the Studio in.
51
+ return isLocale(row?.locale) ? row.locale : isLocale(row?.seenLocale) ? row.seenLocale : DEFAULT_LOCALE
52
+ }
@@ -0,0 +1,57 @@
1
+ // Input rules shared by several functions (SPEC 3, 4, 11). Plain values and pure functions: the
2
+ // callers turn a failed check into `fail('INVALID', …)`.
3
+
4
+ /** A site slug (SPEC 2.1): the one rule for the schema, `sites.create` and the push key. */
5
+ export const SLUG_PATTERN = '[a-z][a-z0-9-]{1,40}'
6
+ export const SLUG = new RegExp(`^${SLUG_PATTERN}$`)
7
+
8
+ export const NAME_MAX = 100
9
+ export const SENTENCE_MAX = 200
10
+
11
+ /** A change sentence as stored: at most SENTENCE_MAX characters, cut with "…". A long title never blocks a save. */
12
+ export function storedSentence(sentence: string): string {
13
+ const text = sentence.trim()
14
+ return text.length > SENTENCE_MAX ? `${text.slice(0, SENTENCE_MAX - 1)}…` : text
15
+ }
16
+
17
+ /** The id of one user action: it is stored with the result and compared on every retry. */
18
+ export const OP_ID = /^[A-Za-z0-9_-]{1,64}$/
19
+
20
+ /** RFC 5321: an address has at most 254 characters. */
21
+ export const EMAIL_MAX = 254
22
+
23
+ /** `local@domain.tld`. Every class excludes `@` and the dot is the only separator, so a match needs one pass. */
24
+ const EMAIL = /^[^\s@]+@[^\s@.]+(?:\.[^\s@.]+)+$/
25
+
26
+ /** Length first, so no pattern ever runs on a long input. */
27
+ export function isEmail(email: string): boolean {
28
+ return email.length <= EMAIL_MAX && EMAIL.test(email)
29
+ }
30
+
31
+ /** A revision (baseRev, lifeRev …) is a count: NaN, fractions, negative and infinite numbers are no revision. */
32
+ export function isRev(value: number): boolean {
33
+ return Number.isSafeInteger(value) && value >= 0
34
+ }
35
+
36
+ /**
37
+ * The first object key Convex would refuse (starts with `$`, has a character outside ASCII 32–126, or is longer than
38
+ * 1024 characters), as a dotted path; undefined when every key is fine. Convex refuses such keys while it serializes
39
+ * the arguments, before any handler runs, with an uncoded error; the JSON boundaries check them first.
40
+ */
41
+ export function badKey(value: unknown, path = ''): string | undefined {
42
+ if (Array.isArray(value)) {
43
+ for (const [i, inner] of value.entries()) {
44
+ const bad = badKey(inner, path ? `${path}.${i}` : String(i))
45
+ if (bad) return bad
46
+ }
47
+ return undefined
48
+ }
49
+ if (typeof value !== 'object' || value === null) return undefined
50
+ for (const [key, inner] of Object.entries(value)) {
51
+ const at = path ? `${path}.${key}` : key
52
+ if (key.startsWith('$') || key.length > 1024 || /[^\x20-\x7e]/.test(key)) return at
53
+ const bad = badKey(inner, at)
54
+ if (bad) return bad
55
+ }
56
+ return undefined
57
+ }
@@ -0,0 +1,28 @@
1
+ // Shared by uploads (sweep), files (library) and retention: removing stored files and upload rows.
2
+ import type { Doc, Id } from '../_generated/dataModel'
3
+ import type { MutationCtx } from '../_generated/server'
4
+
5
+ /** Deletes a stored file if it still exists; a file can be named twice (PDF: original is processed). */
6
+ export async function deleteStorage(ctx: MutationCtx, storageId: Id<'_storage'> | undefined) {
7
+ if (storageId && await ctx.db.system.get(storageId)) await ctx.storage.delete(storageId)
8
+ }
9
+
10
+ /** Deletes the files of one entry of `previous`. */
11
+ export async function deletePrevious(ctx: MutationCtx, old: NonNullable<Doc<'uploads'>['previous']>[number]) {
12
+ await deleteStorage(ctx, old.storageId)
13
+ await deleteStorage(ctx, old.processedId)
14
+ for (const variant of old.variants ?? []) await deleteStorage(ctx, variant.storageId)
15
+ }
16
+
17
+ /** Removes an upload row with its stored files and the files of earlier versions. */
18
+ export async function purgeUpload(ctx: MutationCtx, row: Doc<'uploads'>) {
19
+ await deleteStorage(ctx, row.storageId)
20
+ await deleteStorage(ctx, row.processedId)
21
+ for (const variant of row.variants ?? []) await deleteStorage(ctx, variant.storageId)
22
+ for (const old of row.previous ?? []) await deletePrevious(ctx, old)
23
+ for (const ref of await ctx.db.query('fileRefs').withIndex('by_file', (q) => q.eq('file', row._id)).collect()) await ctx.db.delete(ref._id)
24
+ await ctx.db.delete(row._id)
25
+ }
26
+
27
+ /** The 7-day sweep skips kept, foldered and trashed uploads (the trash has its own 30-day rule). */
28
+ export const isKeptUpload = (row: Doc<'uploads'>) => !!(row.kept || row.folder || row.trashedAt)
@@ -0,0 +1,100 @@
1
+ // Entry lifecycle shared by the entry operations and the retention job (SPEC 4.2, 12),
2
+ // so a removal writes the same fields and counters wherever it happens.
3
+ import { SITE_BUDGET } from '@lupinum/ginko/internal'
4
+ import type { Doc, Id } from '../_generated/dataModel'
5
+ import type { MutationCtx, QueryCtx } from '../_generated/server'
6
+ import type { By } from './access'
7
+ import type { Recorded } from './history'
8
+ import { dropPending } from './pending'
9
+ import { dropTrees } from './trees'
10
+
11
+ /** A removed entry can be restored this long, then retention deletes it for good (SPEC 12). */
12
+ export const DELETED_KEPT = 30 * 24 * 60 * 60 * 1000
13
+
14
+ /**
15
+ * Site values one operation changes, changed in memory and written back once. `entryCount` and `bytes` count the
16
+ * live entries (drafts included), `trashBytes` the removed ones, `treeBytes` the stored trees of the live ones.
17
+ */
18
+ export interface Counters {
19
+ contentRev: number
20
+ entryCount: number
21
+ bytes: number
22
+ trashBytes: number
23
+ treeBytes: number
24
+ }
25
+
26
+ export const countersOf = (site: Doc<'sites'>): Counters => ({
27
+ contentRev: site.contentRev, entryCount: site.entryCount, bytes: site.bytes, trashBytes: site.trashBytes ?? 0, treeBytes: site.treeBytes ?? 0,
28
+ })
29
+
30
+ export async function writeCounters(ctx: MutationCtx, site: Id<'sites'>, c: Counters) {
31
+ await ctx.db.patch(site, { contentRev: c.contentRev, entryCount: c.entryCount, bytes: c.bytes, trashBytes: c.trashBytes, treeBytes: c.treeBytes })
32
+ }
33
+
34
+ /** The byte counters of a site as the sums over its entry rows: what every write keeps them equal to. */
35
+ export function storageSums(rows: readonly Pick<Doc<'entries'>, 'deletedAt' | 'bytes' | 'treeBytes'>[]) {
36
+ let bytes = 0
37
+ let trashBytes = 0
38
+ let treeBytes = 0
39
+ for (const row of rows) {
40
+ if (row.deletedAt === undefined) {
41
+ bytes += row.bytes
42
+ treeBytes += row.treeBytes ?? 0
43
+ } else trashBytes += row.bytes
44
+ }
45
+ return { bytes, trashBytes, treeBytes }
46
+ }
47
+
48
+ /**
49
+ * Soft-deletes one entry (SPEC 4.2 remove): `deletedAt`, lifeRev+1, one change row. Its slug stays reserved and its
50
+ * file references stay; its trees go (the trash keeps none). Its bytes move from `bytes` to `trashBytes`, so removing
51
+ * frees room at once; when the trash then holds more than SITE_BUDGET.trashBytes, the oldest removed entries are deleted for good
52
+ * now instead of after 30 days. A draft was never in the bundle, so removing it leaves `contentRev` alone; a scheduled
53
+ * draft loses its job and its time.
54
+ */
55
+ export async function softRemove(ctx: MutationCtx, c: Counters, entry: Doc<'entries'>, opId: string, by: By, history: Recorded, at = Date.now()) {
56
+ // rev counts every change of the entry (SPEC 3), structural ones included.
57
+ await ctx.db.patch(entry._id, { deletedAt: at, lifeRev: entry.lifeRev + 1, rev: entry.rev + 1, publishAt: undefined, publishJob: undefined, trees: undefined, treeBytes: 0 })
58
+ await dropTrees(ctx, entry._id)
59
+ if (entry.publishJob) await ctx.scheduler.cancel(entry.publishJob)
60
+ // Unpublished changes go with the entry: a restore brings back the live version.
61
+ for (const p of await ctx.db.query('pendingChanges').withIndex('by_entry', (q) => q.eq('entry', entry._id)).collect()) await dropPending(ctx, p)
62
+ c.entryCount -= 1
63
+ c.bytes -= entry.bytes
64
+ c.trashBytes += entry.bytes
65
+ c.treeBytes -= entry.treeBytes ?? 0
66
+ if (entry.state !== 'draft') c.contentRev += 1
67
+ await ctx.db.insert('changes', {
68
+ site: entry.site, entry: entry._id, brick: entry.brick, ...by, opId, kind: 'remove', ...history,
69
+ entryRev: entry.rev + 1, contentRev: c.contentRev, at,
70
+ })
71
+ for (const oldest of await overflowingTrash(ctx, entry.site, c.trashBytes)) await purgeEntry(ctx, c, oldest)
72
+ }
73
+
74
+ /**
75
+ * The removed entries of a site, oldest first, that a trash of `trashBytes` deletes for good to get back within
76
+ * SITE_BUDGET.trashBytes. `softRemove` deletes exactly these; entries.trashOverflow names them before a removal.
77
+ */
78
+ export async function overflowingTrash(ctx: QueryCtx, site: Id<'sites'>, trashBytes: number): Promise<Doc<'entries'>[]> {
79
+ const out: Doc<'entries'>[] = []
80
+ let bytes = trashBytes
81
+ if (bytes <= SITE_BUDGET.trashBytes) return out
82
+ for await (const row of ctx.db.query('entries').withIndex('by_site_deleted', (q) => q.eq('site', site).gt('deletedAt', 0))) {
83
+ out.push(row)
84
+ bytes -= row.bytes
85
+ if (bytes <= SITE_BUDGET.trashBytes) break
86
+ }
87
+ return out
88
+ }
89
+
90
+ /** Deletes a removed entry for good: its slugs, file references, trees and the row. Its changes stay for a year (SPEC 12). */
91
+ export async function purgeEntry(ctx: MutationCtx, c: Counters, row: Doc<'entries'>) {
92
+ for (const p of await ctx.db.query('pendingChanges').withIndex('by_entry', (q) => q.eq('entry', row._id)).collect()) await dropPending(ctx, p)
93
+ for (const slug of await ctx.db.query('slugs').withIndex('by_entry', (q) => q.eq('entry', row._id)).collect()) await ctx.db.delete(slug._id)
94
+ const refs = await ctx.db.query('fileRefs').withIndex('by_holder', (q) => q.eq('holder', 'entry').eq('holderId', row._id)).collect()
95
+ for (const ref of refs) await ctx.db.delete(ref._id)
96
+ await dropTrees(ctx, row._id)
97
+ await ctx.db.delete(row._id)
98
+ // entryCount and bytes dropped at the soft delete; only the trash shrinks now.
99
+ c.trashBytes -= row.bytes
100
+ }