@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
package/convex/seed.ts
ADDED
|
@@ -0,0 +1,624 @@
|
|
|
1
|
+
// Local demo content (GINKO_LOCAL=1 only): resets one site to a corpus and invites its people.
|
|
2
|
+
// `scripts/seed-local.ts` passes contracts/<site>/data.json. The same file holds the import of a
|
|
3
|
+
// `ginko export` (SPEC 9, 12). Internal, so only `npx convex run` with the deployment's admin key
|
|
4
|
+
// reaches it; every function is refused on any deployment without GINKO_LOCAL, except the import steps, which a hosted
|
|
5
|
+
// deployment also allows into one empty site that an operator opened with `importOpen` (see importAllowed).
|
|
6
|
+
import type { Fields } from '@lupinum/ginko'
|
|
7
|
+
import { carryPrints, defaultsFor, entryBytes, fitsBudget, mapMarkdownTexts, remapFileIds, rewriteEntryLinks, routeUrls, stableJson, urlClashes, validate, type Msg, type Schema } from '@lupinum/ginko/internal'
|
|
8
|
+
import { v } from 'convex/values'
|
|
9
|
+
import type { Doc, Id, TableNames } from './_generated/dataModel'
|
|
10
|
+
import { components, internal } from './_generated/api'
|
|
11
|
+
import { internalAction, internalMutation, internalQuery, type MutationCtx, type QueryCtx } from './_generated/server'
|
|
12
|
+
import { fail } from './lib/access'
|
|
13
|
+
import type { ErrorParams } from './lib/fail'
|
|
14
|
+
import { DEFAULT_LOCALE, t, type MessageKey } from './lib/i18n'
|
|
15
|
+
import { badKey } from './lib/input'
|
|
16
|
+
import { normalizeEmail } from './members'
|
|
17
|
+
import { insertSingle, newSingle } from './release'
|
|
18
|
+
import { remapEntryRefs, treesOf, usesOf, type Data, type Prints } from './lib/content'
|
|
19
|
+
import { insertCorpus, invitePeople, type Corpus } from './lib/corpus'
|
|
20
|
+
import { cleanName, kindOf, WRONG_TYPE } from './lib/files'
|
|
21
|
+
import { deleteStorage } from './lib/library'
|
|
22
|
+
import { dropTrees, putTrees } from './lib/trees'
|
|
23
|
+
import { BUDGET, same, sizeText, syncEntryRefs, uploadIdsOf } from './lib/write'
|
|
24
|
+
|
|
25
|
+
function localOnly() {
|
|
26
|
+
if (process.env.GINKO_LOCAL !== '1') fail('FORBIDDEN', 'errors.localOnly')
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Clearing a site's content: a local backend, or the demo platform (GINKO_DEMO=1), whose template sites are reset from
|
|
31
|
+
* git every week. The client platform never sets GINKO_DEMO, so no key or command can clear a client's site there.
|
|
32
|
+
*/
|
|
33
|
+
function localOrDemoOnly() {
|
|
34
|
+
if (process.env.GINKO_LOCAL !== '1' && process.env.GINKO_DEMO !== '1') fail('FORBIDDEN', 'errors.localOrDemoOnly')
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The import steps run with GINKO_LOCAL=1, or on a site that is open for import (`sites.importOpen`, set by `importOpen`
|
|
39
|
+
* only on an empty site). `importClear` runs on a hosted deployment only with GINKO_DEMO=1 (localOrDemoOnly).
|
|
40
|
+
*/
|
|
41
|
+
async function importAllowed(ctx: QueryCtx, slug: string) {
|
|
42
|
+
if (process.env.GINKO_LOCAL === '1') return true
|
|
43
|
+
const site = await ctx.db.query('sites').withIndex('by_slug', (q) => q.eq('slug', slug)).unique()
|
|
44
|
+
return site?.importOpen === true
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function requireImportAllowed(ctx: QueryCtx, slug: string) {
|
|
48
|
+
if (!(await importAllowed(ctx, slug))) fail('FORBIDDEN', 'errors.importClosed')
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Empties Better Auth's rate-limit buckets. The local backend sees no client IP, so all requests share one bucket per
|
|
53
|
+
* path, and a bucket only empties after 10 s without a request: an e2e run that never pauses that long got 429 on its
|
|
54
|
+
* 301st token request and was sent to the sign-in. A reset starts the next test with empty buckets. Local only.
|
|
55
|
+
*/
|
|
56
|
+
async function dropRateLimits(ctx: MutationCtx) {
|
|
57
|
+
const page = await ctx.runQuery(components.betterAuth.adapter.findMany, { model: 'rateLimit', select: ['id'], paginationOpts: { cursor: null, numItems: 100 } })
|
|
58
|
+
const ids = page.page.map((row) => String(row.id))
|
|
59
|
+
// By id, like cleanup.ts: `deleteMany` touches at most 128 rows at once.
|
|
60
|
+
if (ids.length) await ctx.runMutation(components.betterAuth.adapter.deleteMany, { model: 'rateLimit', where: [{ field: 'id', operator: 'in', value: ids }] })
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export const reset = internalMutation({
|
|
64
|
+
args: {
|
|
65
|
+
site: v.string(),
|
|
66
|
+
corpus: v.any(),
|
|
67
|
+
/** Without people, only the content is reset; members and invites stay (e2e tests between runs). */
|
|
68
|
+
people: v.optional(v.array(v.object({ email: v.string(), role: v.union(v.literal('owner'), v.literal('staff')), grants: v.array(v.string()) }))),
|
|
69
|
+
},
|
|
70
|
+
handler: async (ctx, args) => {
|
|
71
|
+
localOnly()
|
|
72
|
+
const site = await ctx.db.query('sites').withIndex('by_slug', (q) => q.eq('slug', args.site)).unique()
|
|
73
|
+
if (!site) fail('SITE_NOT_FOUND', 'errors.siteNotStartedDev')
|
|
74
|
+
const schema = site.schema as Schema
|
|
75
|
+
|
|
76
|
+
// Proposals point at the entries deleted here, so they go too; members and invites only when fresh people come.
|
|
77
|
+
// Fresh people also get fresh settings: a language stored by an earlier run would change every text they see.
|
|
78
|
+
if (args.people) {
|
|
79
|
+
for (const person of args.people) {
|
|
80
|
+
const user = await ctx.runQuery(components.betterAuth.adapter.findOne, { model: 'user', where: [{ field: 'email', value: normalizeEmail(person.email) }] })
|
|
81
|
+
const id = user?.id
|
|
82
|
+
const settings = typeof id === 'string' ? await ctx.db.query('userSettings').withIndex('by_user', (q) => q.eq('user', id)).unique() : null
|
|
83
|
+
if (settings) await ctx.db.delete(settings._id)
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
// Each table through an index that starts with the site, so the reset reads only this site's rows: a full scan
|
|
87
|
+
// would also read other sites and conflict with any write to them (an import running at the same time).
|
|
88
|
+
const id = site._id
|
|
89
|
+
const rows = [
|
|
90
|
+
...(await ctx.db.query('entries').withIndex('by_site_deleted', (q) => q.eq('site', id)).collect()),
|
|
91
|
+
...(await ctx.db.query('entryTrees').withIndex('by_site', (q) => q.eq('site', id)).collect()),
|
|
92
|
+
...(await ctx.db.query('pendingChanges').withIndex('by_site', (q) => q.eq('site', id)).collect()),
|
|
93
|
+
...(await ctx.db.query('slugs').withIndex('by_key', (q) => q.eq('site', id)).collect()),
|
|
94
|
+
...(await ctx.db.query('fileRefs').withIndex('by_site_holder', (q) => q.eq('site', id)).collect()),
|
|
95
|
+
...(await ctx.db.query('changes').withIndex('by_site_at', (q) => q.eq('site', id)).collect()),
|
|
96
|
+
...(await ctx.db.query('ops').withIndex('by_site_actor_op', (q) => q.eq('site', id)).collect()),
|
|
97
|
+
...(await ctx.db.query('proposals').withIndex('by_site', (q) => q.eq('site', id)).collect()),
|
|
98
|
+
...(args.people ? await ctx.db.query('memberships').withIndex('by_site', (q) => q.eq('site', id)).collect() : []),
|
|
99
|
+
...(args.people ? await ctx.db.query('invites').withIndex('by_site', (q) => q.eq('site', id)).collect() : []),
|
|
100
|
+
]
|
|
101
|
+
for (const row of rows) await ctx.db.delete(row._id)
|
|
102
|
+
|
|
103
|
+
const { count } = await insertCorpus(ctx, site, args.corpus as Corpus)
|
|
104
|
+
const links = await invitePeople(ctx, site, args.people ?? [], 'seed')
|
|
105
|
+
await dropRateLimits(ctx)
|
|
106
|
+
return { entries: count, links }
|
|
107
|
+
},
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
// ---- Import of a `ginko export` (SPEC 9, 12). The CLI calls these in steps because `convex run`
|
|
111
|
+
// takes its arguments on the command line and one mutation has document limits. ----
|
|
112
|
+
|
|
113
|
+
/** An upload URL of the local storage; the CLI posts one exported file to it and gets a storage id. */
|
|
114
|
+
export const uploadUrl = internalMutation({
|
|
115
|
+
args: { site: v.string() },
|
|
116
|
+
handler: async (ctx, args) => {
|
|
117
|
+
await requireImportAllowed(ctx, args.site)
|
|
118
|
+
return ctx.storage.generateUploadUrl()
|
|
119
|
+
},
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
async function siteBySlug(ctx: MutationCtx, slug: string) {
|
|
123
|
+
const site = await ctx.db.query('sites').withIndex('by_slug', (q) => q.eq('slug', slug)).unique()
|
|
124
|
+
if (!site) fail('SITE_NOT_FOUND', 'errors.siteNotPushedSchema')
|
|
125
|
+
return site
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** What one importClear call may read before it stops: a quarter of a mutation's 16 MiB, leaving room for its writes. */
|
|
129
|
+
const CLEAR_BYTES = 4_000_000
|
|
130
|
+
const CLEAR_DOCS = 2000
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Import step 1: deletes the site's entries, trees, slugs, file references, changes and ops, like `reset` without
|
|
134
|
+
* people. One call stops after about CLEAR_BYTES of documents (or CLEAR_DOCS of them), so it stays under the limits of a
|
|
135
|
+
* mutation whatever the size of the rows, and returns `done: false` until nothing is left; the CLI repeats it, and a
|
|
136
|
+
* rerun after a failure continues where the last call stopped. When done, the counters are zero and contentRev has
|
|
137
|
+
* risen. Uploads and their files stay; the retention sweep removes them.
|
|
138
|
+
*/
|
|
139
|
+
export const importClear = internalMutation({
|
|
140
|
+
args: { site: v.string() },
|
|
141
|
+
handler: async (ctx, args) => {
|
|
142
|
+
localOrDemoOnly()
|
|
143
|
+
const site = await siteBySlug(ctx, args.site)
|
|
144
|
+
let spent = 0
|
|
145
|
+
let docs = 0
|
|
146
|
+
const full = () => spent > CLEAR_BYTES || docs >= CLEAR_DOCS
|
|
147
|
+
const drop = async (doc: { _id: Id<TableNames> }) => {
|
|
148
|
+
spent += JSON.stringify(doc).length
|
|
149
|
+
docs++
|
|
150
|
+
await ctx.db.delete(doc._id)
|
|
151
|
+
}
|
|
152
|
+
const dropRefs = async (holder: Doc<'fileRefs'>['holder'], holderId: string) => {
|
|
153
|
+
for (const ref of await ctx.db.query('fileRefs').withIndex('by_holder', (q) => q.eq('holder', holder).eq('holderId', holderId)).collect()) await drop(ref)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
for await (const change of ctx.db.query('changes').withIndex('by_site_at', (q) => q.eq('site', site._id))) {
|
|
157
|
+
if (full()) return { done: false }
|
|
158
|
+
await dropRefs('change', change._id)
|
|
159
|
+
await drop(change)
|
|
160
|
+
}
|
|
161
|
+
for await (const op of ctx.db.query('ops').withIndex('by_site_actor_op', (q) => q.eq('site', site._id))) {
|
|
162
|
+
if (full()) return { done: false }
|
|
163
|
+
await drop(op)
|
|
164
|
+
}
|
|
165
|
+
// The trees first, by site: an entry's parts can be larger than the entry.
|
|
166
|
+
for await (const part of ctx.db.query('entryTrees').withIndex('by_site', (q) => q.eq('site', site._id))) {
|
|
167
|
+
if (full()) return { done: false }
|
|
168
|
+
await drop(part)
|
|
169
|
+
}
|
|
170
|
+
for await (const row of ctx.db.query('pendingChanges').withIndex('by_site', (q) => q.eq('site', site._id))) {
|
|
171
|
+
if (full()) return { done: false }
|
|
172
|
+
await dropRefs('pending', row.entry)
|
|
173
|
+
await drop(row)
|
|
174
|
+
}
|
|
175
|
+
for await (const entry of ctx.db.query('entries').withIndex('by_site_brick_order', (q) => q.eq('site', site._id))) {
|
|
176
|
+
if (full()) return { done: false }
|
|
177
|
+
await dropRefs('entry', entry._id)
|
|
178
|
+
for (const slug of await ctx.db.query('slugs').withIndex('by_entry', (q) => q.eq('entry', entry._id)).collect()) await drop(slug)
|
|
179
|
+
await drop(entry)
|
|
180
|
+
}
|
|
181
|
+
for await (const slug of ctx.db.query('slugs').withIndex('by_key', (q) => q.eq('site', site._id))) {
|
|
182
|
+
if (full()) return { done: false }
|
|
183
|
+
await drop(slug)
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
await ctx.db.patch(site._id, { bytes: 0, trashBytes: 0, treeBytes: 0, entryCount: 0, contentRev: site.contentRev + 1 })
|
|
187
|
+
return { done: true }
|
|
188
|
+
},
|
|
189
|
+
})
|
|
190
|
+
|
|
191
|
+
/** One reason an import batch is refused; the batch answers with all of them (details.problems), the first as its error. */
|
|
192
|
+
type ImportProblem = { code: 'INVALID' | 'TOO_LARGE'; key: MessageKey; params: ErrorParams }
|
|
193
|
+
|
|
194
|
+
/** The first value of an import batch that the Studio would refuse today: the exported entry ID, its brick and the issue. */
|
|
195
|
+
export type ImportWarning = { id: string; brick: string; path: string } & Msg
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Import step 2, repeated per batch: stores the batch's files as ready uploads and its entries.
|
|
199
|
+
* - `files` name uploaded storage ids. A storage id that already has an upload row is not stored twice,
|
|
200
|
+
* so a repeated batch changes nothing.
|
|
201
|
+
* - Entry data gets the new upload IDs in place of the exported ones (an ID that is not in `files` stays).
|
|
202
|
+
* - Slugs and file references are rebuilt from the data; deletedAt, rev and prints are restored.
|
|
203
|
+
* - The site's counters grow by the batch (entryCount for live entries only).
|
|
204
|
+
* - `warnings` counts the entries that hold values the Studio would refuse today (they are stored as they are);
|
|
205
|
+
* `firstWarning` names the first one.
|
|
206
|
+
* - The answer's `ids` pair each exported entry ID with the new one, as a list: Convex refuses an object with more than
|
|
207
|
+
* 1024 fields. Entry references in `data` still hold the exported IDs until `importRefs` rewrites them.
|
|
208
|
+
*/
|
|
209
|
+
export const importExport = internalMutation({
|
|
210
|
+
args: {
|
|
211
|
+
site: v.string(),
|
|
212
|
+
files: v.array(v.object({
|
|
213
|
+
/** The upload ID in the export. */
|
|
214
|
+
id: v.string(),
|
|
215
|
+
storageId: v.id('_storage'),
|
|
216
|
+
name: v.string(),
|
|
217
|
+
mime: v.string(),
|
|
218
|
+
size: v.number(),
|
|
219
|
+
width: v.optional(v.number()),
|
|
220
|
+
height: v.optional(v.number()),
|
|
221
|
+
/** Library fields of a backup (SPEC 12): the folder's ID in the export, kept, focus, hash. */
|
|
222
|
+
folder: v.optional(v.string()),
|
|
223
|
+
kept: v.optional(v.boolean()),
|
|
224
|
+
focus: v.optional(v.object({ x: v.number(), y: v.number() })),
|
|
225
|
+
sha256: v.optional(v.string()),
|
|
226
|
+
/** The original file (`local:files-export`), not a processed copy from a backup: it goes through the upload pipeline. */
|
|
227
|
+
original: v.optional(v.boolean()),
|
|
228
|
+
/** The Files library description per language. */
|
|
229
|
+
alt: v.optional(v.record(v.string(), v.string())),
|
|
230
|
+
})),
|
|
231
|
+
/** The folders of the export, parents first or in any order. */
|
|
232
|
+
folders: v.optional(v.array(v.object({ id: v.string(), name: v.string(), parent: v.optional(v.string()) }))),
|
|
233
|
+
entries: v.array(v.object({
|
|
234
|
+
id: v.string(),
|
|
235
|
+
brick: v.string(),
|
|
236
|
+
kind: v.union(v.literal('single'), v.literal('item')),
|
|
237
|
+
order: v.number(),
|
|
238
|
+
data: v.any(),
|
|
239
|
+
prints: v.record(v.string(), v.record(v.string(), v.string())),
|
|
240
|
+
rev: v.number(),
|
|
241
|
+
deletedAt: v.optional(v.number()),
|
|
242
|
+
state: v.optional(v.union(v.literal('draft'), v.literal('live'))),
|
|
243
|
+
publishAt: v.optional(v.number()),
|
|
244
|
+
/** When the entry last changed for the public (the bundle's updatedAt); absent in older exports, then the import time. */
|
|
245
|
+
contentAt: v.optional(v.number()),
|
|
246
|
+
})),
|
|
247
|
+
},
|
|
248
|
+
handler: async (ctx, args) => {
|
|
249
|
+
await requireImportAllowed(ctx, args.site)
|
|
250
|
+
const site = await siteBySlug(ctx, args.site)
|
|
251
|
+
const schema = site.schema as Schema
|
|
252
|
+
|
|
253
|
+
// Folders are matched by name and parent, so a repeated batch does not make them twice.
|
|
254
|
+
const folders = new Map<string, Id<'folders'>>()
|
|
255
|
+
const pending = [...(args.folders ?? [])]
|
|
256
|
+
while (pending.length) {
|
|
257
|
+
const before = pending.length
|
|
258
|
+
for (const folder of [...pending]) {
|
|
259
|
+
if (folder.parent !== undefined && !folders.has(folder.parent)) continue
|
|
260
|
+
const parent = folder.parent === undefined ? undefined : folders.get(folder.parent)
|
|
261
|
+
const siblings = await ctx.db.query('folders').withIndex('by_site_parent', (q) => q.eq('site', site._id).eq('parent', parent)).collect()
|
|
262
|
+
const have = siblings.find((f) => f.name === folder.name)
|
|
263
|
+
folders.set(folder.id, have?._id ?? await ctx.db.insert('folders', { site: site._id, name: folder.name, ...(parent ? { parent } : {}) }))
|
|
264
|
+
pending.splice(pending.indexOf(folder), 1)
|
|
265
|
+
}
|
|
266
|
+
if (pending.length === before) fail('INVALID', 'errors.backupFoldersInconsistent')
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
const uploads = new Map<string, Id<'uploads'>>()
|
|
270
|
+
// A backup carries no smaller copies (variants): restored images get them made afterwards.
|
|
271
|
+
let withoutVariants = false
|
|
272
|
+
// Originals that go (or already went) through the upload pipeline: the CLI waits for these (importUploads).
|
|
273
|
+
const originals: Id<'uploads'>[] = []
|
|
274
|
+
for (const file of args.files) {
|
|
275
|
+
// A repeated batch names the same stored file: it is stored once.
|
|
276
|
+
const have = await ctx.db.query('uploads').withIndex('by_storage', (q) => q.eq('storageId', file.storageId)).first()
|
|
277
|
+
if (have) {
|
|
278
|
+
uploads.set(file.id, have._id)
|
|
279
|
+
if (file.original) originals.push(have._id)
|
|
280
|
+
continue
|
|
281
|
+
}
|
|
282
|
+
const sha256 = file.sha256
|
|
283
|
+
const library = {
|
|
284
|
+
...(file.folder !== undefined && folders.has(file.folder) ? { folder: folders.get(file.folder)! } : {}),
|
|
285
|
+
...(file.kept ? { kept: true } : {}),
|
|
286
|
+
...(file.focus ? { focus: file.focus } : {}),
|
|
287
|
+
...(sha256 ? { sha256 } : {}),
|
|
288
|
+
...(file.alt && Object.keys(file.alt).length ? { alt: file.alt } : {}),
|
|
289
|
+
}
|
|
290
|
+
// The same content is already in this site's library (an earlier import, or the owner's own upload): the entries
|
|
291
|
+
// use that file, with its description, and the copy the CLI stored again is not kept. An original from
|
|
292
|
+
// files-export takes any such file (the export holds each content once). A backup may hold the same content as two
|
|
293
|
+
// library files with their own description, folder, focus or kept flag: it takes only a file that has the same.
|
|
294
|
+
const candidates = sha256 === undefined ? [] : await ctx.db.query('uploads').withIndex('by_site_sha256', (q) => q.eq('site', site._id).eq('sha256', sha256))
|
|
295
|
+
.filter((q) => q.and(q.eq(q.field('trashedAt'), undefined), q.neq(q.field('status'), 'failed'))).collect()
|
|
296
|
+
const libraryOf = (row: { folder?: Id<'folders'>; kept?: boolean; focus?: { x: number; y: number }; alt?: Record<string, string> }) =>
|
|
297
|
+
stableJson([row.folder ?? null, row.kept ?? false, row.focus ?? null, row.alt ?? {}])
|
|
298
|
+
const same = candidates.find((row) => file.original || libraryOf(row) === libraryOf(library))
|
|
299
|
+
if (same) {
|
|
300
|
+
uploads.set(file.id, same._id)
|
|
301
|
+
if (file.original) originals.push(same._id)
|
|
302
|
+
await deleteStorage(ctx, file.storageId)
|
|
303
|
+
continue
|
|
304
|
+
}
|
|
305
|
+
if (file.original) {
|
|
306
|
+
// An original takes the path of every upload (uploadsNode): content check, metadata removed, WebP, size limit, variants.
|
|
307
|
+
if (!kindOf(file.mime)) fail('INVALID', WRONG_TYPE.key, WRONG_TYPE.params)
|
|
308
|
+
const id = await ctx.db.insert('uploads', { site: site._id, uploader: 'import', storageId: file.storageId, name: cleanName(file.name), size: file.size, mime: file.mime, status: 'processing', attempts: 0, ...library })
|
|
309
|
+
await ctx.scheduler.runAfter(0, internal.uploadsNode.run, { upload: id })
|
|
310
|
+
uploads.set(file.id, id)
|
|
311
|
+
originals.push(id)
|
|
312
|
+
continue
|
|
313
|
+
}
|
|
314
|
+
uploads.set(file.id, await ctx.db.insert('uploads', {
|
|
315
|
+
// Exported bytes are already processed (a WebP for photos), so they are their own processed file (Astra 9).
|
|
316
|
+
site: site._id, uploader: 'import', storageId: file.storageId, processedId: file.storageId, name: file.name, size: file.size, mime: file.mime,
|
|
317
|
+
...(file.width === undefined ? {} : { width: file.width }),
|
|
318
|
+
...(file.height === undefined ? {} : { height: file.height }),
|
|
319
|
+
status: 'ready', attempts: 0, ...library,
|
|
320
|
+
}))
|
|
321
|
+
if (file.mime.startsWith('image/')) withoutVariants = true
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// 1. Check every row before anything is stored, and collect every problem, so the operator fixes them in one pass.
|
|
325
|
+
// Values the Studio and the site cannot read at all (a wrong type, an unknown field or language) are refused, so
|
|
326
|
+
// an export cannot store what the editor cannot open. Rules a save enforces on top (row id format, alt texts, lengths,
|
|
327
|
+
// Markdown profiles) are not: a backup must restore what the platform once stored, so they come back as warnings.
|
|
328
|
+
// Entry references are not looked up; they still name exported IDs until importRefs. Removed entries are checked
|
|
329
|
+
// too: a restore checks nothing, so this is the only check they get. The budget is checked like a save: each entry,
|
|
330
|
+
// removed ones too (a restore must be able to save them), the live entries against the site, the removed ones
|
|
331
|
+
// against the trash.
|
|
332
|
+
const problems: ImportProblem[] = []
|
|
333
|
+
const rows: { row: (typeof args.entries)[number]; fields: Fields; data: Data; prints: Prints; size: number; trees: { json: string; bytes: number } }[] = []
|
|
334
|
+
let bytes = 0
|
|
335
|
+
let trashBytes = 0
|
|
336
|
+
let treeBytes = 0
|
|
337
|
+
let live = 0
|
|
338
|
+
// Entries with values the Studio would refuse today, and the first such value (for the CLI's one-line notice).
|
|
339
|
+
let warnings = 0
|
|
340
|
+
let firstWarning: ImportWarning | undefined
|
|
341
|
+
for (const row of args.entries) {
|
|
342
|
+
const def = Object.hasOwn(schema.bricks, row.brick) ? schema.bricks[row.brick] : undefined
|
|
343
|
+
if (!def) {
|
|
344
|
+
problems.push({ code: 'INVALID', key: 'errors.entryBrickMissingFromSchema', params: { id: row.id, brick: row.brick } })
|
|
345
|
+
continue
|
|
346
|
+
}
|
|
347
|
+
const data = remapFileIds(def.fields, row.data as Data, uploads)
|
|
348
|
+
// New file IDs change the main-language text a translation was made from, not its meaning.
|
|
349
|
+
const prints = carryPrints(def.fields, row.data as Data, data, row.prints, schema.locales[0]!)
|
|
350
|
+
const checked = await validate(schema, row.brick, data, { mode: 'restore' })
|
|
351
|
+
if (checked.errors.length) problems.push({ code: 'INVALID', key: 'errors.importEntryInvalid', params: { id: row.id, path: checked.errors[0]!.path, count: checked.errors.length } })
|
|
352
|
+
const warning = checked.warnings[0]
|
|
353
|
+
if (warning) {
|
|
354
|
+
warnings++
|
|
355
|
+
firstWarning ??= { id: row.id, brick: row.brick, path: warning.path, key: warning.key, ...(warning.params ? { params: warning.params } : {}) }
|
|
356
|
+
}
|
|
357
|
+
const size = entryBytes(data, prints)
|
|
358
|
+
if (size > BUDGET.entryBytes) problems.push({ code: 'TOO_LARGE', key: 'errors.importEntryTooLarge', params: { id: row.id, used: sizeText(size), limit: sizeText(BUDGET.entryBytes) } })
|
|
359
|
+
// The trash keeps no trees.
|
|
360
|
+
const trees = row.deletedAt === undefined ? await treesOf(def.fields, data) : { json: '', bytes: 0 }
|
|
361
|
+
if (row.deletedAt === undefined) {
|
|
362
|
+
live++
|
|
363
|
+
bytes += size
|
|
364
|
+
treeBytes += trees.bytes
|
|
365
|
+
} else trashBytes += size
|
|
366
|
+
rows.push({ row, fields: def.fields, data, prints, size, trees })
|
|
367
|
+
}
|
|
368
|
+
// What the Studio keeps true: every entry once, a collection within its max, one entry per address. An export that
|
|
369
|
+
// breaks it gives two pages one URL, or a collection whose removed entries cannot come back. The CLI checks the
|
|
370
|
+
// whole export before it clears anything (checkImport); here a batch is checked in itself, and the max with the
|
|
371
|
+
// entries stored before it.
|
|
372
|
+
const seen = new Set<string>()
|
|
373
|
+
for (const { row } of rows) {
|
|
374
|
+
if (seen.has(row.id)) problems.push({ code: 'INVALID', key: 'errors.importDuplicateId', params: { id: row.id } })
|
|
375
|
+
seen.add(row.id)
|
|
376
|
+
}
|
|
377
|
+
const added = new Map<string, number>()
|
|
378
|
+
for (const { row } of rows) if (row.deletedAt === undefined) added.set(row.brick, (added.get(row.brick) ?? 0) + 1)
|
|
379
|
+
for (const [brick, count] of added) {
|
|
380
|
+
const def = schema.bricks[brick]!
|
|
381
|
+
if (def.kind !== 'collection') continue
|
|
382
|
+
const stored = await ctx.db.query('entries').withIndex('by_site_brick_deleted', (q) => q.eq('site', site._id).eq('brick', brick).eq('deletedAt', undefined)).collect()
|
|
383
|
+
if (stored.length + count > def.max) problems.push({ code: 'INVALID', key: 'errors.importCollectionTooFull', params: { brick, count: stored.length + count, max: def.max } })
|
|
384
|
+
}
|
|
385
|
+
const addresses = rows.flatMap(({ row, data }) => {
|
|
386
|
+
const def = schema.bricks[row.brick]!
|
|
387
|
+
return def.kind === 'collection' ? [{ id: row.id, urls: routeUrls(schema, def, { id: row.id, order: row.order, data }) }] : []
|
|
388
|
+
})
|
|
389
|
+
for (const clash of urlClashes(addresses)) problems.push({ code: 'INVALID', key: 'errors.importSameUrl', params: { a: clash.first, b: clash.second, url: clash.url } })
|
|
390
|
+
if (site.entryCount + live > BUDGET.entries) problems.push({ code: 'TOO_LARGE', key: 'errors.siteEntryLimitReached', params: {} })
|
|
391
|
+
if (site.bytes + bytes > BUDGET.siteBytes) problems.push({ code: 'TOO_LARGE', key: 'errors.importSiteTooLarge', params: { used: sizeText(site.bytes + bytes), limit: sizeText(BUDGET.siteBytes) } })
|
|
392
|
+
const trashAfter = (site.trashBytes ?? 0) + trashBytes
|
|
393
|
+
if (trashAfter > BUDGET.trashBytes) problems.push({ code: 'TOO_LARGE', key: 'errors.importTrashTooLarge', params: { used: sizeText(trashAfter), limit: sizeText(BUDGET.trashBytes) } })
|
|
394
|
+
// The bundle reads every live entry's trees: past the hidden guard, every public page would fail.
|
|
395
|
+
if ((site.treeBytes ?? 0) + treeBytes > BUDGET.treeBytes) problems.push({ code: 'TOO_LARGE', key: 'errors.entryTooComplex', params: {} })
|
|
396
|
+
const first = problems[0]
|
|
397
|
+
if (first) fail(first.code, first.key, first.params, { problems: problems.map((p) => ({ ...p, message: t(DEFAULT_LOCALE, p.key, p.params) })) })
|
|
398
|
+
|
|
399
|
+
// 2. Store.
|
|
400
|
+
const ids: [string, Id<'entries'>][] = []
|
|
401
|
+
const known = new Set<string>(uploads.values())
|
|
402
|
+
for (const { row, fields, data, prints, size, trees } of rows) {
|
|
403
|
+
const id = await ctx.db.insert('entries', {
|
|
404
|
+
site: site._id, brick: row.brick, kind: row.kind, order: row.order, data, rev: row.rev,
|
|
405
|
+
fieldRevs: Object.fromEntries(Object.keys(fields).map((f) => [f, row.rev])),
|
|
406
|
+
lifeRev: row.deletedAt === undefined ? 1 : 2, prints, bytes: size, treeBytes: trees.bytes, contentAt: row.contentAt ?? Date.now(),
|
|
407
|
+
...(row.deletedAt === undefined ? {} : { deletedAt: row.deletedAt }),
|
|
408
|
+
...(row.state === 'draft' ? { state: 'draft' as const } : {}),
|
|
409
|
+
})
|
|
410
|
+
await putTrees(ctx, site._id, id, trees.json)
|
|
411
|
+
// A scheduled draft gets its job back (a time in the past runs at once); `contentRev` is not touched.
|
|
412
|
+
if (row.state === 'draft' && row.publishAt !== undefined && row.deletedAt === undefined) {
|
|
413
|
+
await ctx.db.patch(id, { publishAt: row.publishAt, publishJob: await ctx.scheduler.runAt(row.publishAt, internal.entries.publishDue, { entry: id, at: row.publishAt }) })
|
|
414
|
+
}
|
|
415
|
+
ids.push([row.id, id])
|
|
416
|
+
for (const [name, field] of Object.entries(fields)) {
|
|
417
|
+
if (field.type !== 'slug') continue
|
|
418
|
+
for (const [locale, slug] of Object.entries((data[name] ?? {}) as Record<string, string>)) {
|
|
419
|
+
await ctx.db.insert('slugs', { site: site._id, brick: row.brick, locale, slug, entry: id })
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
await syncEntryRefs(ctx, site._id, id, new Map([...usesOf(fields, data, schema.locales, uploadIdsOf(ctx))].filter(([file]) => known.has(file))))
|
|
423
|
+
}
|
|
424
|
+
// It only touches ready images without variants, so a second run (next batch) changes nothing.
|
|
425
|
+
if (withoutVariants) await ctx.scheduler.runAfter(0, internal.images.backfillVariants, {})
|
|
426
|
+
await ctx.db.patch(site._id, {
|
|
427
|
+
bytes: site.bytes + bytes, trashBytes: trashAfter, treeBytes: (site.treeBytes ?? 0) + treeBytes, entryCount: site.entryCount + live,
|
|
428
|
+
})
|
|
429
|
+
return { entries: args.entries.length, files: args.files.length, ids, uploads: originals, warnings, ...(firstWarning ? { firstWarning } : {}) }
|
|
430
|
+
},
|
|
431
|
+
})
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* Import step 2 as the CLI calls it: one batch that the CLI stored as JSON in local storage (the
|
|
435
|
+
* command line is too small for entries of up to 480 KiB). Reads it, runs importExport, removes it.
|
|
436
|
+
*/
|
|
437
|
+
export const importBatch = internalAction({
|
|
438
|
+
args: { site: v.string(), batch: v.id('_storage') },
|
|
439
|
+
handler: async (ctx, args): Promise<ImportAnswer> => {
|
|
440
|
+
if (!(await ctx.runQuery(internal.seed.isImportAllowed, { site: args.site }))) fail('FORBIDDEN', 'errors.importClosed')
|
|
441
|
+
const blob = await ctx.storage.get(args.batch)
|
|
442
|
+
if (!blob) fail('NOT_FOUND', 'errors.importBatchNotLocal')
|
|
443
|
+
const batch = JSON.parse(await blob.text()) as { site: string; files: never[]; entries: never[] }
|
|
444
|
+
if (batch.site !== args.site) fail('INVALID', 'errors.importBatchOtherSite')
|
|
445
|
+
// runMutation would refuse such a key with an uncoded error; name it instead.
|
|
446
|
+
const bad = badKey(batch)
|
|
447
|
+
if (bad) fail('INVALID', 'errors.nameNotAllowed', { name: bad })
|
|
448
|
+
const result: ImportAnswer = await ctx.runMutation(internal.seed.importExport, batch)
|
|
449
|
+
await ctx.storage.delete(args.batch)
|
|
450
|
+
return result
|
|
451
|
+
},
|
|
452
|
+
})
|
|
453
|
+
|
|
454
|
+
/** What one import batch answers (importExport, importBatch). */
|
|
455
|
+
type ImportAnswer = { entries: number; files: number; ids: [string, string][]; uploads: Id<'uploads'>[]; warnings: number; firstWarning?: ImportWarning }
|
|
456
|
+
|
|
457
|
+
/** For `importBatch`, an action without database access. */
|
|
458
|
+
export const isImportAllowed = internalQuery({
|
|
459
|
+
args: { site: v.string() },
|
|
460
|
+
handler: (ctx, args) => importAllowed(ctx, args.site),
|
|
461
|
+
})
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* Import step 3 (after the last batch): entries got new IDs, so the entry references in `data` (`ref` fields, also in list
|
|
465
|
+
* rows, and links in Markdown texts, `[Anna]($authors.<id>)`) still name the exported IDs. This rewrites every ID found in
|
|
466
|
+
* `ids` (exported ID → new ID); unknown IDs and slugs stay. `ids` is a list of pairs, not an object: Convex refuses an
|
|
467
|
+
* object with more than 1024 fields. The entry's `bytes` and the site's budget follow (the IDs differ in length); a text
|
|
468
|
+
* with a rewritten link also gets its trees parsed again (the bundle serves those) and keeps a translation current that
|
|
469
|
+
* was current before. One call handles one page and names the entries it changed; the CLI repeats it with the returned
|
|
470
|
+
* `cursor` until `done`, and once per part of the pairs when they do not fit one call.
|
|
471
|
+
*/
|
|
472
|
+
export const importRefs = internalMutation({
|
|
473
|
+
args: { site: v.string(), ids: v.array(v.object({ from: v.string(), to: v.string() })), cursor: v.optional(v.string()) },
|
|
474
|
+
handler: async (ctx, args) => {
|
|
475
|
+
await requireImportAllowed(ctx, args.site)
|
|
476
|
+
const site = await siteBySlug(ctx, args.site)
|
|
477
|
+
const schema = site.schema as Schema
|
|
478
|
+
const ids = new Map(args.ids.map(({ from, to }) => [from, to]))
|
|
479
|
+
const exportedOf = new Map(args.ids.map(({ from, to }) => [to, from]))
|
|
480
|
+
// 25 entries of up to 480 KiB stay under the 16 MiB a mutation may read.
|
|
481
|
+
const page = await ctx.db.query('entries').withIndex('by_site_brick_order', (q) => q.eq('site', site._id)).paginate({ numItems: 25, cursor: args.cursor ?? null })
|
|
482
|
+
let delta = 0
|
|
483
|
+
let trashDelta = 0
|
|
484
|
+
let treeDelta = 0
|
|
485
|
+
const changed: Id<'entries'>[] = []
|
|
486
|
+
for (const entry of page.page) {
|
|
487
|
+
const def = schema.bricks[entry.brick]
|
|
488
|
+
if (!def) continue
|
|
489
|
+
const refs = remapEntryRefs(def.fields, entry.data as Data, ids)
|
|
490
|
+
const data = mapMarkdownTexts(def.fields, refs, (text) => rewriteEntryLinks(text, ids)) as Data
|
|
491
|
+
if (same(data, entry.data)) continue
|
|
492
|
+
// New IDs in a link change the main-language text a translation was made from, not its meaning.
|
|
493
|
+
const texts = !same(data, refs)
|
|
494
|
+
const prints = texts ? carryPrints(def.fields, entry.data as Data, data, entry.prints as Prints, schema.locales[0]!) : entry.prints
|
|
495
|
+
const size = entry.bytes + entryBytes(data, prints) - entryBytes(entry.data, entry.prints)
|
|
496
|
+
// A path ID from `ginko files-export` is shorter than a Convex ID: an entry with many references grows here. The CLI
|
|
497
|
+
// checks this before it clears anything (checkImport); this is the platform's own guard.
|
|
498
|
+
if (!fitsBudget(size, entry.bytes, BUDGET.entryBytes)) {
|
|
499
|
+
fail('TOO_LARGE', 'errors.importEntryTooLarge', { id: exportedOf.get(entry._id) ?? entry._id, used: sizeText(size), limit: sizeText(BUDGET.entryBytes) })
|
|
500
|
+
}
|
|
501
|
+
// The trash keeps no trees.
|
|
502
|
+
const trees = texts && entry.deletedAt === undefined ? await treesOf(def.fields, data) : undefined
|
|
503
|
+
await ctx.db.patch(entry._id, { data, prints, bytes: size, ...(trees ? { treeBytes: trees.bytes } : {}) })
|
|
504
|
+
if (trees) {
|
|
505
|
+
await putTrees(ctx, site._id, entry._id, trees.json)
|
|
506
|
+
treeDelta += trees.bytes - (entry.treeBytes ?? 0)
|
|
507
|
+
}
|
|
508
|
+
if (entry.deletedAt === undefined) delta += size - entry.bytes
|
|
509
|
+
else trashDelta += size - entry.bytes
|
|
510
|
+
changed.push(entry._id)
|
|
511
|
+
}
|
|
512
|
+
const bytes = site.bytes + delta
|
|
513
|
+
const trashBytes = (site.trashBytes ?? 0) + trashDelta
|
|
514
|
+
const treeBytes = (site.treeBytes ?? 0) + treeDelta
|
|
515
|
+
if (!fitsBudget(bytes, site.bytes, BUDGET.siteBytes)) fail('TOO_LARGE', 'errors.importSiteTooLarge', { used: sizeText(bytes), limit: sizeText(BUDGET.siteBytes) })
|
|
516
|
+
if (!fitsBudget(trashBytes, site.trashBytes ?? 0, BUDGET.trashBytes)) fail('TOO_LARGE', 'errors.importTrashTooLarge', { used: sizeText(trashBytes), limit: sizeText(BUDGET.trashBytes) })
|
|
517
|
+
// The bundle reads every live entry's trees: past the guard, every public page would fail.
|
|
518
|
+
if (!fitsBudget(treeBytes, site.treeBytes ?? 0, BUDGET.treeBytes)) fail('TOO_LARGE', 'errors.entryTooComplex')
|
|
519
|
+
if (delta !== 0 || trashDelta !== 0 || treeDelta !== 0) await ctx.db.patch(site._id, { bytes, trashBytes, treeBytes })
|
|
520
|
+
return { done: page.isDone, cursor: page.continueCursor, changed }
|
|
521
|
+
},
|
|
522
|
+
})
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* Opens an EMPTY site for the import steps on a hosted deployment (`npx convex run --prod seed:importOpen`). Empty means
|
|
526
|
+
* the state after `sites:bootstrap` and the first release: no changes but the release's own, no ops, and no entries
|
|
527
|
+
* except the singles that release created from their defaults (release.ts newSingle) and nobody has touched. Those are
|
|
528
|
+
* removed here, so the export's singles take their place; `importDone` creates again any single the export did not
|
|
529
|
+
* bring, and closes the site.
|
|
530
|
+
*/
|
|
531
|
+
export const importOpen = internalMutation({
|
|
532
|
+
args: { site: v.string() },
|
|
533
|
+
handler: async (ctx, args) => {
|
|
534
|
+
const site = await siteBySlug(ctx, args.site)
|
|
535
|
+
const schema = site.schema as Schema
|
|
536
|
+
// A release records itself in the history (kind 'release'); that is not content.
|
|
537
|
+
const used = (await ctx.db.query('changes').withIndex('by_site_at', (q) => q.eq('site', site._id)).filter((q) => q.neq(q.field('kind'), 'release')).first())
|
|
538
|
+
?? (await ctx.db.query('ops').withIndex('by_site_actor_op', (q) => q.eq('site', site._id)).first())
|
|
539
|
+
const entries = await ctx.db.query('entries').withIndex('by_site_brick_order', (q) => q.eq('site', site._id)).collect()
|
|
540
|
+
const untouched = (e: Doc<'entries'>) => {
|
|
541
|
+
const def = Object.hasOwn(schema.bricks, e.brick) ? schema.bricks[e.brick] : undefined
|
|
542
|
+
return def?.kind === 'single' && e.kind === 'single' && e.rev === 1 && e.deletedAt === undefined && e.state === undefined
|
|
543
|
+
&& stableJson(e.data) === stableJson(defaultsFor(def.fields))
|
|
544
|
+
}
|
|
545
|
+
if (used || !entries.every(untouched) || site.entryCount !== entries.length) fail('INVALID', 'errors.importNeedsEmptySite')
|
|
546
|
+
let bytes = 0
|
|
547
|
+
let treeBytes = 0
|
|
548
|
+
for (const entry of entries) {
|
|
549
|
+
await syncEntryRefs(ctx, site._id, entry._id, new Map())
|
|
550
|
+
await dropTrees(ctx, entry._id)
|
|
551
|
+
await ctx.db.delete(entry._id)
|
|
552
|
+
bytes += entry.bytes
|
|
553
|
+
treeBytes += entry.treeBytes ?? 0
|
|
554
|
+
}
|
|
555
|
+
await ctx.db.patch(site._id, {
|
|
556
|
+
importOpen: true,
|
|
557
|
+
...(entries.length ? { entryCount: 0, bytes: site.bytes - bytes, treeBytes: (site.treeBytes ?? 0) - treeBytes } : {}),
|
|
558
|
+
})
|
|
559
|
+
return { site: args.site, open: true }
|
|
560
|
+
},
|
|
561
|
+
})
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* Closes the import of a site and raises contentRev, so bundles and caches see the new content. A single brick without
|
|
565
|
+
* an entry gets one from its defaults, as a release makes it: the export may lack one that importOpen removed.
|
|
566
|
+
*/
|
|
567
|
+
export const importDone = internalMutation({
|
|
568
|
+
args: { site: v.string() },
|
|
569
|
+
handler: async (ctx, args) => {
|
|
570
|
+
const site = await siteBySlug(ctx, args.site)
|
|
571
|
+
if (site.importOpen) {
|
|
572
|
+
const schema = site.schema as Schema
|
|
573
|
+
const created = []
|
|
574
|
+
for (const [brick, def] of Object.entries(schema.bricks)) {
|
|
575
|
+
if (def.kind !== 'single') continue
|
|
576
|
+
const have = await ctx.db.query('entries').withIndex('by_site_brick_order', (q) => q.eq('site', site._id).eq('brick', brick)).first()
|
|
577
|
+
if (have) continue
|
|
578
|
+
const single = await newSingle(brick, def.fields, schema.locales[0]!)
|
|
579
|
+
await insertSingle(ctx, site._id, single, schema.locales)
|
|
580
|
+
created.push(single)
|
|
581
|
+
}
|
|
582
|
+
if (created.length) {
|
|
583
|
+
await ctx.db.patch(site._id, {
|
|
584
|
+
entryCount: site.entryCount + created.length,
|
|
585
|
+
bytes: site.bytes + created.reduce((sum, c) => sum + c.bytes, 0),
|
|
586
|
+
treeBytes: (site.treeBytes ?? 0) + created.reduce((sum, c) => sum + c.trees.bytes, 0),
|
|
587
|
+
})
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
await ctx.db.patch(site._id, { importOpen: undefined, ...(site.importOpen ? { contentRev: site.contentRev + 1 } : {}) })
|
|
591
|
+
return { site: args.site, open: false }
|
|
592
|
+
},
|
|
593
|
+
})
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* How far the processing of imported originals is (the IDs importExport answered): counts per status and the name and
|
|
597
|
+
* reason (in English, for the CLI) of each failed file. Ids of another site are ignored. Internal like the rest of the import, so the CLI polls it
|
|
598
|
+
* with the same access (`convex run`).
|
|
599
|
+
*/
|
|
600
|
+
export const importUploads = internalQuery({
|
|
601
|
+
args: { site: v.string(), ids: v.array(v.id('uploads')) },
|
|
602
|
+
handler: async (ctx, args) => {
|
|
603
|
+
const site = await ctx.db.query('sites').withIndex('by_slug', (q) => q.eq('slug', args.site)).unique()
|
|
604
|
+
const count = { processing: 0, ready: 0, failed: 0 }
|
|
605
|
+
const failedFiles: { name: string; error: string }[] = []
|
|
606
|
+
if (!site) return { ...count, failedFiles }
|
|
607
|
+
for (const id of args.ids) {
|
|
608
|
+
const row = await ctx.db.get(id)
|
|
609
|
+
if (!row || row.site !== site._id) continue
|
|
610
|
+
count[row.status]++
|
|
611
|
+
if (row.status === 'failed') failedFiles.push({ name: row.name, error: t('en', (row.error ?? 'errors.uploadFailed') as MessageKey) })
|
|
612
|
+
}
|
|
613
|
+
return { ...count, failedFiles }
|
|
614
|
+
},
|
|
615
|
+
})
|
|
616
|
+
|
|
617
|
+
/** What `pnpm ops:import` checks before it opens a hosted site: the bricks of the stored (released) schema, or null for an unknown site. */
|
|
618
|
+
export const importStatus = internalQuery({
|
|
619
|
+
args: { site: v.string() },
|
|
620
|
+
handler: async (ctx, args) => {
|
|
621
|
+
const site = await ctx.db.query('sites').withIndex('by_slug', (q) => q.eq('slug', args.site)).unique()
|
|
622
|
+
return site ? { bricks: Object.keys((site.schema as Schema).bricks) } : null
|
|
623
|
+
},
|
|
624
|
+
})
|