@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,331 @@
|
|
|
1
|
+
// The tool catalog of the agent door (SPEC 16), kept apart from the calls in agent.ts: which tools exist
|
|
2
|
+
// for a person, how the model is told about them, and the pure helpers some of them use (search text).
|
|
3
|
+
// A tool is listed only when the person may use it; agent.ts checks the same list again at call time.
|
|
4
|
+
import type { Brick, Json, Task } from '@lupinum/ginko'
|
|
5
|
+
import { labelOf, type Schema } from '@lupinum/ginko/internal'
|
|
6
|
+
import type { Doc } from '../_generated/dataModel'
|
|
7
|
+
import { createdBy, type Actor } from './access'
|
|
8
|
+
|
|
9
|
+
export const HISTORY_MAX = 50
|
|
10
|
+
export const SEARCH_MAX = 20
|
|
11
|
+
|
|
12
|
+
export interface TaskTool { name: string; brick: string; task: Task; ref: string }
|
|
13
|
+
|
|
14
|
+
/** The tasks a person may run, as tool names. Admins and owners get every task; staff their grants (SPEC 2.7). */
|
|
15
|
+
export function taskTools(actor: Actor): TaskTool[] {
|
|
16
|
+
const schema = actor.site.schema as Schema
|
|
17
|
+
const out: TaskTool[] = []
|
|
18
|
+
for (const [brick, def] of Object.entries(schema.bricks)) {
|
|
19
|
+
if (def.retired) continue
|
|
20
|
+
for (const task of def.tasks ?? []) {
|
|
21
|
+
const ref = `${brick}.${task.id}`
|
|
22
|
+
if (actor.role === 'staff' && !actor.grants.includes(ref)) continue
|
|
23
|
+
out.push({ name: `task_${brick}_${task.id}`, brick, task, ref })
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return out
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The tool description of a task: the labels are the site's own words (main language), the rest is for the model. */
|
|
30
|
+
export function describeTask(brick: Brick, task: Task, main: string): string {
|
|
31
|
+
const what = task.kind === 'create' ? 'Creates a new entry.'
|
|
32
|
+
: task.kind === 'remove' ? 'Removes an entry; its ID is in ginko_read.'
|
|
33
|
+
: 'pick' in task && task.pick ? 'Changes an entry; its ID is in ginko_read. Fields you leave out stay as they are.'
|
|
34
|
+
: 'Changes the brick. Fields you leave out stay as they are.'
|
|
35
|
+
return `${labelOf(task.label, main, main)} (${labelOf(brick.label, main, main)}). ${what}`
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* A granted task of the brick and kind for staff (admins and owners need none), e.g. to undo through the door. For a
|
|
40
|
+
* change of an entry the person created (`entry`), their create task of the brick serves when no edit task covers it
|
|
41
|
+
* (lib/access.ts `authorize`).
|
|
42
|
+
*/
|
|
43
|
+
export function taskFor(actor: Actor, brick: string, kind: Task['kind'], fields: readonly string[] = [], entry?: Pick<Doc<'entries'>, 'createdBy'> | null): string | undefined {
|
|
44
|
+
const covers = (task: Task) => task.kind === kind && (task.kind !== 'edit' || fields.every((f) => task.fields.includes(f)))
|
|
45
|
+
const tools = taskTools(actor).filter((t) => t.brick === brick)
|
|
46
|
+
const found = tools.find((t) => covers(t.task))?.ref
|
|
47
|
+
if (found || kind !== 'edit' || !createdBy(actor, entry)) return found
|
|
48
|
+
return tools.find((t) => t.task.kind === 'create')?.ref
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Whether the person changes existing entries at all: owners and admins always, staff with an `edit` task, or a `create` task for the entries they made. */
|
|
52
|
+
export const mayEdit = (actor: Actor): boolean => actor.role !== 'staff' || taskTools(actor).some((t) => t.task.kind === 'edit' || t.task.kind === 'create')
|
|
53
|
+
|
|
54
|
+
/** The collections where this person may create entries (every new entry starts as a draft). */
|
|
55
|
+
export function draftBricks(actor: Actor): string[] {
|
|
56
|
+
const schema = actor.site.schema as Schema
|
|
57
|
+
return Object.entries(schema.bricks)
|
|
58
|
+
.filter(([key, def]) => def.kind === 'collection' && !def.retired && (actor.role !== 'staff' || taskFor(actor, key, 'create') !== undefined))
|
|
59
|
+
.map(([key]) => key)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* `publish` on every tool that creates or changes content (SPEC 15): a new entry is a draft and a change to a published
|
|
64
|
+
* entry waits as unpublished changes until the person publishes it, unless the person asked for it to go online now.
|
|
65
|
+
*/
|
|
66
|
+
export const PUBLISH = {
|
|
67
|
+
type: 'boolean',
|
|
68
|
+
description: 'true: goes on the website at once. Only when the person asked for that. Without it a new entry is a draft and a change waits unpublished; the person publishes it in the platform.',
|
|
69
|
+
} as const
|
|
70
|
+
|
|
71
|
+
/** `propose` on every write tool: "show me first". */
|
|
72
|
+
export const PROPOSE = { type: 'boolean', description: 'true: do not change anything now; show the change to the person as a proposal they approve.' } as const
|
|
73
|
+
|
|
74
|
+
/** `request_id` on every write tool: a retry key of the assistant's choice (agent.call). With `mcp-` in front it is an op id, so at most 60 characters. */
|
|
75
|
+
export const REQUEST_ID = {
|
|
76
|
+
type: 'string', pattern: '^[A-Za-z0-9_-]{1,60}$',
|
|
77
|
+
description: 'Optional. Send the same value when you retry this call, so it runs only once. Letters, digits, _ and -, at most 60.',
|
|
78
|
+
} as const
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* MCP tool hints (annotations) for the host, which may ask the person before a destructive call. In MCP,
|
|
82
|
+
* destructiveHint false means "only additive updates": that holds for a new entry or draft only. Any other write may
|
|
83
|
+
* overwrite a value or, as an undo of a create, remove an entry, as in the library's own door.
|
|
84
|
+
*/
|
|
85
|
+
export interface ToolHints { readOnlyHint: boolean; destructiveHint?: boolean; openWorldHint: boolean }
|
|
86
|
+
const READS: ToolHints = { readOnlyHint: true, openWorldHint: false }
|
|
87
|
+
const ADDS: ToolHints = { readOnlyHint: false, destructiveHint: false, openWorldHint: false }
|
|
88
|
+
const WRITES: ToolHints = { readOnlyHint: false, destructiveHint: true, openWorldHint: false }
|
|
89
|
+
/** The hints of a task tool: only a create task is additive. */
|
|
90
|
+
export const taskHints = (task: Task): ToolHints => (task.kind === 'create' ? ADDS : WRITES)
|
|
91
|
+
|
|
92
|
+
export interface ToolDef { name: string; description: string; inputSchema: Json; annotations: ToolHints }
|
|
93
|
+
|
|
94
|
+
const object = (properties: Record<string, Json>, required: string[] = []): Json => ({ type: 'object', properties, required, additionalProperties: false })
|
|
95
|
+
|
|
96
|
+
/** What the person's key may use besides the task tools. */
|
|
97
|
+
export function fixedTools(actor: Actor): ToolDef[] {
|
|
98
|
+
const schema = actor.site.schema as Schema
|
|
99
|
+
const main = schema.locales[0]!
|
|
100
|
+
const foreign = schema.locales.slice(1)
|
|
101
|
+
const entry = { type: 'string', description: 'ID of the entry (from ginko_read or ginko_search)' }
|
|
102
|
+
const change = { type: 'string', description: 'ID of the change (from ginko_history)' }
|
|
103
|
+
const tools: ToolDef[] = [
|
|
104
|
+
{
|
|
105
|
+
name: 'ginko_overview',
|
|
106
|
+
description: 'Overview: the website, its languages, its bricks (content areas) and the tasks you may run. Also says whether your changes wait for approval before they go live.',
|
|
107
|
+
inputSchema: object({}),
|
|
108
|
+
annotations: READS,
|
|
109
|
+
},
|
|
110
|
+
{
|
|
111
|
+
name: 'ginko_read',
|
|
112
|
+
description: 'Reads the published content of a brick as the website shows it. Collections include the entry IDs. Drafts are not in it. '
|
|
113
|
+
+ 'For another language, "fallback" lists the texts shown in the main language because their translation is missing; "stale" lists outdated translations, which the website still shows until they are translated again or confirmed. '
|
|
114
|
+
+ 'By default, an entry with its own page is left out of a language until its required texts are translated there; read the main language to find it.',
|
|
115
|
+
inputSchema: object({ brick: { type: 'string', description: 'Key of the brick (from ginko_overview)' }, locale: { type: 'string', description: `Language; default is the main language (${main})` } }, ['brick']),
|
|
116
|
+
annotations: READS,
|
|
117
|
+
},
|
|
118
|
+
{
|
|
119
|
+
name: 'ginko_search',
|
|
120
|
+
description: 'Searches the texts of all entries (drafts too) for words. Case does not matter; write umlauts as "ae", "oe", "ue". Returns ID, brick, label and a snippet.',
|
|
121
|
+
inputSchema: object({
|
|
122
|
+
query: { type: 'string', description: 'Search words', minLength: 1, maxLength: 200 },
|
|
123
|
+
brick: { type: 'string', description: 'Search only in this brick' },
|
|
124
|
+
limit: { type: 'integer', minimum: 1, maximum: SEARCH_MAX, description: `At most this many hits, default 10` },
|
|
125
|
+
}, ['query']),
|
|
126
|
+
annotations: READS,
|
|
127
|
+
},
|
|
128
|
+
{
|
|
129
|
+
name: 'ginko_history',
|
|
130
|
+
description: 'The latest changes to the website, newest first, with the ID that ginko_undo, ginko_version_at and ginko_revert take.',
|
|
131
|
+
inputSchema: object({ limit: { type: 'integer', minimum: 1, maximum: HISTORY_MAX } }),
|
|
132
|
+
annotations: READS,
|
|
133
|
+
},
|
|
134
|
+
{
|
|
135
|
+
name: 'ginko_undo',
|
|
136
|
+
description: 'Takes back one change, like the undo button in the platform. The ID comes from the answer of a task or from ginko_history.',
|
|
137
|
+
inputSchema: object({ change, request_id: REQUEST_ID }, ['change']),
|
|
138
|
+
annotations: WRITES,
|
|
139
|
+
},
|
|
140
|
+
{
|
|
141
|
+
name: 'ginko_version_at',
|
|
142
|
+
description: 'Shows how an entry looked right after an earlier change (fields in storage format). Changes nothing. "fields" names the fields that changed since; "diff" lists what ginko_revert would change, with now as "before" and that version as "after" (empty: it is the current state).',
|
|
143
|
+
inputSchema: object({ entry, change }, ['entry', 'change']),
|
|
144
|
+
annotations: READS,
|
|
145
|
+
},
|
|
146
|
+
]
|
|
147
|
+
if (mayEdit(actor)) {
|
|
148
|
+
tools.push({
|
|
149
|
+
name: 'ginko_revert',
|
|
150
|
+
description: 'Sets an entry back to its state after an earlier change (only the fields that changed since). This is a new change and ginko_undo can take it back. Look at ginko_version_at first.',
|
|
151
|
+
inputSchema: object({ entry, change, propose: PROPOSE, request_id: REQUEST_ID }, ['entry', 'change']),
|
|
152
|
+
annotations: WRITES,
|
|
153
|
+
})
|
|
154
|
+
if (foreign.length) {
|
|
155
|
+
tools.push({
|
|
156
|
+
name: 'ginko_translate',
|
|
157
|
+
// Not every entry has a task that changes its main language (events have add and remove only; the creator rule
|
|
158
|
+
// reaches only translate, revert and undo here), so the text promises no such path.
|
|
159
|
+
description: `Writes translations of an entry into a foreign language (${foreign.join(', ')}). The main language ${main} changes only through a task that changes entries; where there is none, the person changes it in the platform. `
|
|
160
|
+
+ 'Only translatable text fields, each with the text in the target language. "confirm" names fields whose existing translation may stay although the main text changed.',
|
|
161
|
+
inputSchema: object({
|
|
162
|
+
entry,
|
|
163
|
+
locale: { type: 'string', enum: foreign, description: 'Target language' },
|
|
164
|
+
fields: { type: 'object', description: 'Field name → translated text, e.g. { "name": "Pumpkin soup" }' },
|
|
165
|
+
confirm: { type: 'array', items: { type: 'string' }, description: 'Field names whose translation stays valid as it is' },
|
|
166
|
+
publish: PUBLISH,
|
|
167
|
+
propose: PROPOSE,
|
|
168
|
+
request_id: REQUEST_ID,
|
|
169
|
+
}, ['entry', 'locale']),
|
|
170
|
+
annotations: WRITES,
|
|
171
|
+
})
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const drafts = draftBricks(actor)
|
|
175
|
+
if (drafts.length) {
|
|
176
|
+
const lines = drafts.map((key) => {
|
|
177
|
+
const def = schema.bricks[key]!
|
|
178
|
+
const keys = Object.entries(def.fields).filter(([, f]) => f.type !== 'slug' && !f.retired).map(([k, f]) => `${k} (${labelOf(f.label, main, main)}${f.optional || f.default !== undefined ? '' : ', required'})`)
|
|
179
|
+
return `${key} (${labelOf(def.label, main, main)}): ${keys.join(', ')}`
|
|
180
|
+
})
|
|
181
|
+
tools.push({
|
|
182
|
+
name: 'ginko_draft',
|
|
183
|
+
description: 'Creates a new entry as a draft. A draft is not on the website; the person publishes it in the platform. '
|
|
184
|
+
+ `Values as in the tasks: texts in ${main} as plain text, money in whole currency units (19.90), lists as a list of objects. Fields per brick: ${lines.join('; ')}.`,
|
|
185
|
+
inputSchema: object({ brick: { type: 'string', enum: drafts }, fields: { type: 'object', description: 'Field name → value' }, request_id: REQUEST_ID }, ['brick', 'fields']),
|
|
186
|
+
annotations: ADDS,
|
|
187
|
+
})
|
|
188
|
+
}
|
|
189
|
+
tools.push(
|
|
190
|
+
{
|
|
191
|
+
name: 'ginko_file_usage',
|
|
192
|
+
description: 'Shows where a file (image or PDF) is used: entry, brick, label, paths, and whether an image lacks its description. '
|
|
193
|
+
+ 'A Markdown text names a file by its ID as $file.<ID>, e.g.  for an image; never write a storage address.',
|
|
194
|
+
inputSchema: object({ file: { type: 'string', description: 'ID of the file' } }, ['file']),
|
|
195
|
+
annotations: READS,
|
|
196
|
+
},
|
|
197
|
+
{
|
|
198
|
+
name: 'ginko_check_links',
|
|
199
|
+
description: "Checks the links in the texts of the website: broken internal links and unsafe links. Returns entry, field, link and reason. Ginko does not know the files in the website's public folder; links to them are reported as unknown.",
|
|
200
|
+
inputSchema: object({ brick: { type: 'string', description: 'Report only this brick' } }),
|
|
201
|
+
annotations: READS,
|
|
202
|
+
},
|
|
203
|
+
{
|
|
204
|
+
name: 'ginko_proposals',
|
|
205
|
+
description: 'Your own proposals with their state and reason (open, scheduled, applied, rejected, stale, withdrawn). Use it to tell the person what still waits for approval.',
|
|
206
|
+
inputSchema: object({ status: { type: 'string', enum: ['open', 'scheduled', 'applied', 'rejected', 'stale', 'withdrawn'] } }),
|
|
207
|
+
annotations: READS,
|
|
208
|
+
},
|
|
209
|
+
)
|
|
210
|
+
return tools
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// ---- Builder tools: owners and admins set up and fill a site, as they can in the Studio. ----
|
|
214
|
+
|
|
215
|
+
/** Thrown at the end of an import's dry run, so Convex rolls back every write; routes/mcp.ts turns it into the answer. */
|
|
216
|
+
export const DRY_RUN = 'DRY_RUN'
|
|
217
|
+
|
|
218
|
+
/** Items per ginko_import: one mutation writes them all or none. */
|
|
219
|
+
export const IMPORT_MAX = 50
|
|
220
|
+
|
|
221
|
+
/** Owners and admins write any field of any brick in the Studio; staff only run their tasks. */
|
|
222
|
+
export const isBuilder = (actor: Actor): boolean => actor.role !== 'staff'
|
|
223
|
+
|
|
224
|
+
export const BUILDER_TOOLS = new Set(['ginko_schema', 'ginko_write', 'ginko_create', 'ginko_import', 'ginko_upload'])
|
|
225
|
+
|
|
226
|
+
/** The tools for building and filling the site, for owners and admins only. */
|
|
227
|
+
export function builderTools(actor: Actor): ToolDef[] {
|
|
228
|
+
if (!isBuilder(actor)) return []
|
|
229
|
+
const schema = actor.site.schema as Schema
|
|
230
|
+
const main = schema.locales[0]!
|
|
231
|
+
const brick = { type: 'string', description: 'Key of the brick (from ginko_overview)' }
|
|
232
|
+
const entry = { type: 'string', description: 'ID of the entry (from ginko_read or ginko_search). Leave it out for a single brick.' }
|
|
233
|
+
const fields = { type: 'object', description: 'Field name → value in the form ginko_schema describes' }
|
|
234
|
+
const values = `Values as ginko_schema describes them: texts in ${main} as plain text or Markdown, money in whole currency units (19.90), `
|
|
235
|
+
+ 'dates as YYYY-MM-DD, references and files by ID, lists as a list of objects (a list replaces the whole list).'
|
|
236
|
+
return [
|
|
237
|
+
{
|
|
238
|
+
name: 'ginko_schema',
|
|
239
|
+
description: 'The fields of every brick (or one) as JSON Schema, in the form ginko_write, ginko_create and ginko_import take them, '
|
|
240
|
+
+ 'with kind, label and route. Read it before you write.',
|
|
241
|
+
inputSchema: object({ brick: { type: 'string', description: 'Only this brick' } }),
|
|
242
|
+
annotations: READS,
|
|
243
|
+
},
|
|
244
|
+
{
|
|
245
|
+
name: 'ginko_write',
|
|
246
|
+
description: `Changes fields of an entry, or of a single brick, in the main language (${main}). Fields you leave out stay as they are; null removes an optional value. `
|
|
247
|
+
+ `${values} Foreign languages go through ginko_translate. The change waits unpublished until the person publishes it in the platform, unless publish is true.`,
|
|
248
|
+
inputSchema: object({ brick, entry, fields, publish: PUBLISH, propose: PROPOSE, request_id: REQUEST_ID }, ['brick', 'fields']),
|
|
249
|
+
annotations: WRITES,
|
|
250
|
+
},
|
|
251
|
+
{
|
|
252
|
+
name: 'ginko_create',
|
|
253
|
+
description: `Creates an entry in a collection. ${values} The address (slug) comes from the title. `
|
|
254
|
+
+ 'The entry is a draft unless publish is true.',
|
|
255
|
+
inputSchema: object({
|
|
256
|
+
brick, fields,
|
|
257
|
+
publish: PUBLISH,
|
|
258
|
+
propose: PROPOSE, request_id: REQUEST_ID,
|
|
259
|
+
}, ['brick', 'fields']),
|
|
260
|
+
annotations: ADDS,
|
|
261
|
+
},
|
|
262
|
+
{
|
|
263
|
+
name: 'ginko_import',
|
|
264
|
+
description: `Writes up to ${IMPORT_MAX} items in one step, all or nothing: an item with entry (or for a single brick) changes it like ginko_write, `
|
|
265
|
+
+ 'one without creates an entry like ginko_create. An error names the item and nothing is saved. dry_run: true checks every item with the real save and saves nothing.',
|
|
266
|
+
inputSchema: object({
|
|
267
|
+
items: {
|
|
268
|
+
type: 'array', minItems: 1, maxItems: IMPORT_MAX,
|
|
269
|
+
items: object({ brick, entry, fields, publish: PUBLISH }, ['brick', 'fields']),
|
|
270
|
+
},
|
|
271
|
+
dry_run: { type: 'boolean', description: 'true: check only, save nothing.' },
|
|
272
|
+
request_id: REQUEST_ID,
|
|
273
|
+
}, ['items']),
|
|
274
|
+
annotations: WRITES,
|
|
275
|
+
},
|
|
276
|
+
{
|
|
277
|
+
name: 'ginko_upload',
|
|
278
|
+
description: 'Adds an image (JPEG, PNG, WebP) or a PDF to the files of the website. With url, Ginko fetches a public https address. '
|
|
279
|
+
+ 'Without url, the answer is a one-time upload address (10 minutes) and a curl command for a file on your computer. '
|
|
280
|
+
+ 'Use the file ID in an image field ({ "file": ID, "alt": "…" }) or in Markdown as . Images are processed for a few seconds.',
|
|
281
|
+
inputSchema: object({
|
|
282
|
+
url: { type: 'string', description: 'Public https address of the file' },
|
|
283
|
+
name: { type: 'string', description: 'File name with extension, e.g. team.jpg' },
|
|
284
|
+
}),
|
|
285
|
+
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
|
|
286
|
+
},
|
|
287
|
+
]
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* The keys a mistyped name probably means, best first, at most three: same letters ignoring case and separators, a key
|
|
292
|
+
* or label that contains the word (one that starts with it first), or a small edit distance. Empty when nothing is close.
|
|
293
|
+
*/
|
|
294
|
+
export function suggest(word: string, candidates: readonly { key: string; label: string }[]): string[] {
|
|
295
|
+
const norm = (s: string) => s.normalize('NFKD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z0-9]/g, '')
|
|
296
|
+
const w = norm(word)
|
|
297
|
+
if (!w) return []
|
|
298
|
+
const exact = candidates.find((c) => norm(c.key) === w || norm(c.label) === w)
|
|
299
|
+
if (exact) return [exact.key]
|
|
300
|
+
const starts = (c: { key: string; label: string }) => norm(c.key).startsWith(w) || norm(c.label).startsWith(w)
|
|
301
|
+
const part = candidates.filter((c) => w.length >= 3 && (norm(c.key).includes(w) || w.includes(norm(c.key)) || norm(c.label).includes(w)))
|
|
302
|
+
if (part.length) return [...part.filter(starts), ...part.filter((c) => !starts(c))].slice(0, 3).map((c) => c.key)
|
|
303
|
+
let best: { key: string; d: number } | undefined
|
|
304
|
+
for (const c of candidates) {
|
|
305
|
+
const d = distance(w, norm(c.key))
|
|
306
|
+
if (d <= Math.max(1, Math.floor(w.length / 3)) && (!best || d < best.d)) best = { key: c.key, d }
|
|
307
|
+
}
|
|
308
|
+
return best ? [best.key] : []
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function distance(a: string, b: string): number {
|
|
312
|
+
let row = Array.from({ length: b.length + 1 }, (_, i) => i)
|
|
313
|
+
for (let i = 1; i <= a.length; i++) {
|
|
314
|
+
const next = [i]
|
|
315
|
+
for (let j = 1; j <= b.length; j++) next[j] = Math.min(row[j]! + 1, next[j - 1]! + 1, row[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1))
|
|
316
|
+
row = next
|
|
317
|
+
}
|
|
318
|
+
return row[b.length]!
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** Tools that only read: the HTTP layer sends them to a query. */
|
|
322
|
+
export const READ_TOOLS = new Set(['ginko_search', 'ginko_version_at', 'ginko_file_usage', 'ginko_check_links', 'ginko_proposals', 'ginko_schema'])
|
|
323
|
+
|
|
324
|
+
// ---- Links ----
|
|
325
|
+
|
|
326
|
+
const MARKDOWN_LINK = /\]\(\s*<?([^)\s>]+)/g
|
|
327
|
+
|
|
328
|
+
/** The targets of the inline links in a Markdown text. */
|
|
329
|
+
export function linksIn(markdown: string): string[] {
|
|
330
|
+
return [...markdown.matchAll(MARKDOWN_LINK)].map((m) => m[1]!)
|
|
331
|
+
}
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
// Pure content rules of the write path (SPEC part 3 "Übersetzungs-Abdrücke", 4.2 save).
|
|
2
|
+
// No Convex here, so every rule is testable with plain data.
|
|
3
|
+
import type { CollectionBrick, Field, Fields, Json, Label, Locale } from '@lupinum/ginko'
|
|
4
|
+
import { effectiveAlt, factNamesIn, fileImagesWithoutAlt, fileRefsIn, isNavTree, isTranslatable, leavesOf, markdownTrees, printOf, stableJson, type Prints, type Schema } from '@lupinum/ginko/internal'
|
|
5
|
+
|
|
6
|
+
export type { Prints }
|
|
7
|
+
|
|
8
|
+
export type Data = Record<string, Json>
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Replaces one root field. With `locale`, translatable leaves are taken only in that
|
|
12
|
+
* locale from `next`; every other locale keeps its stored value. A leaf whose `next` has no
|
|
13
|
+
* entry for `locale` stays as stored; `null` or "" removes that locale's value. List rows are
|
|
14
|
+
* matched by `_id`; the row structure (order, added, removed rows) comes from `next`. An image
|
|
15
|
+
* with another file than the stored one keeps only the descriptions in `next`.
|
|
16
|
+
* Returns undefined when nothing is left of the field.
|
|
17
|
+
*/
|
|
18
|
+
export function mergeField(field: Field, stored: Json | undefined, next: Json, locale: Locale | undefined): Json | undefined {
|
|
19
|
+
// A whole-field save follows the same rule as a save in one language: null or "" removes that language.
|
|
20
|
+
if (!locale) return isTranslatable(field) && isRecord(next) ? withoutEmpty(next) : next
|
|
21
|
+
if (isTranslatable(field)) return mergeLocalized(stored, next, locale)
|
|
22
|
+
if (field.type === 'image' && isRecord(next)) {
|
|
23
|
+
// A description belongs to its picture: the other languages' texts of an old picture must not describe a new one.
|
|
24
|
+
const kept = next.file === asRecord(stored).file ? asRecord(stored).alt : undefined
|
|
25
|
+
return { ...next, alt: mergeLocalized(kept, next.alt, locale) ?? {} } as Json
|
|
26
|
+
}
|
|
27
|
+
if (field.type === 'list' && Array.isArray(next)) {
|
|
28
|
+
const oldRows = new Map((Array.isArray(stored) ? stored : []).filter(isRecord).map((r) => [r._id, r]))
|
|
29
|
+
return next.map((row) => {
|
|
30
|
+
if (!isRecord(row)) return row
|
|
31
|
+
const old = oldRows.get(row._id)
|
|
32
|
+
const out: Record<string, Json> = { ...row }
|
|
33
|
+
for (const [key, inner] of Object.entries(field.of)) {
|
|
34
|
+
if (row[key] === undefined) continue
|
|
35
|
+
const merged = mergeField(inner, old?.[key], row[key]!, locale)
|
|
36
|
+
if (merged === undefined) delete out[key]
|
|
37
|
+
else out[key] = merged
|
|
38
|
+
}
|
|
39
|
+
return out as Json
|
|
40
|
+
})
|
|
41
|
+
}
|
|
42
|
+
return next
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** A localized value without its null and "" entries; undefined when no language is left. */
|
|
46
|
+
function withoutEmpty(value: Record<string, Json>): Json | undefined {
|
|
47
|
+
const kept = Object.entries(value).filter(([, v]) => v !== null && v !== '')
|
|
48
|
+
return kept.length ? Object.fromEntries(kept) : undefined
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** `stored` with the entry of `locale` taken from `next`: absent stays, null or "" removes it. */
|
|
52
|
+
function mergeLocalized(stored: Json | undefined, next: Json | undefined, locale: Locale): Json | undefined {
|
|
53
|
+
const sent = asRecord(next)
|
|
54
|
+
if (!Object.hasOwn(sent, locale)) return stored
|
|
55
|
+
const merged = { ...asRecord(stored) }
|
|
56
|
+
if (sent[locale] === null || sent[locale] === '') delete merged[locale]
|
|
57
|
+
else merged[locale] = sent[locale]!
|
|
58
|
+
return Object.keys(merged).length ? merged : undefined
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** A Localized value without one language, or undefined when nothing is left (a field cleared in that language only). */
|
|
62
|
+
export function withoutLocale(stored: Json | undefined, locale: Locale): Json | undefined {
|
|
63
|
+
const { [locale]: _removed, ...rest } = asRecord(stored)
|
|
64
|
+
return Object.keys(rest).length ? rest : undefined
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* New prints for the changed roots. A foreign leaf that changed in this save, or is listed
|
|
69
|
+
* in `confirm` for `locale`, gets the print of its current main value. Unchanged foreign
|
|
70
|
+
* leaves keep their print, even when the whole value was sent. Prints of leaves that no
|
|
71
|
+
* longer exist (removed rows, removed fields) are dropped.
|
|
72
|
+
*/
|
|
73
|
+
export function nextPrints(input: {
|
|
74
|
+
fields: Fields
|
|
75
|
+
roots: string[]
|
|
76
|
+
before: Data
|
|
77
|
+
after: Data
|
|
78
|
+
prints: Prints
|
|
79
|
+
main: Locale
|
|
80
|
+
confirm: { locale: Locale; leaves: string[] } | undefined
|
|
81
|
+
}): Prints {
|
|
82
|
+
const out: Prints = {}
|
|
83
|
+
const touched = (leaf: string) => input.roots.some((r) => leaf === r || leaf.startsWith(`${r}.`))
|
|
84
|
+
for (const [leaf, byLocale] of Object.entries(input.prints)) if (!touched(leaf)) out[leaf] = { ...byLocale }
|
|
85
|
+
for (const root of input.roots) {
|
|
86
|
+
const field = input.fields[root]
|
|
87
|
+
if (!field) continue
|
|
88
|
+
const old = leavesOf(field, input.before[root], root)
|
|
89
|
+
const now = leavesOf(field, input.after[root], root)
|
|
90
|
+
for (const [leaf, values] of now) {
|
|
91
|
+
const kept = { ...(input.prints[leaf] ?? {}) }
|
|
92
|
+
const print = printOf(values[input.main])
|
|
93
|
+
for (const [locale, value] of Object.entries(values)) {
|
|
94
|
+
if (locale === input.main) continue
|
|
95
|
+
if (stableJson(old.get(leaf)?.[locale] ?? null) !== stableJson(value ?? null)) kept[locale] = print
|
|
96
|
+
}
|
|
97
|
+
if (input.confirm?.leaves.includes(leaf)) kept[input.confirm.locale] = print
|
|
98
|
+
// A removed translation has no print any more.
|
|
99
|
+
for (const locale of Object.keys(kept)) if (values[locale] === undefined || values[locale] === null) delete kept[locale]
|
|
100
|
+
if (Object.keys(kept).length) out[leaf] = kept
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return out
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The root field of a leaf path (`days.k3Fd9aZ0qx.dish` → `days`). */
|
|
107
|
+
export function rootOf(leaf: string): string {
|
|
108
|
+
return leaf.split('.')[0]!
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Whether a `$file.<id>` of a Markdown text has the form of an upload ID (on the server: `ctx.db.normalizeId('uploads', id)`).
|
|
113
|
+
* A shell example like `backup="$file.bak"` stands where a reference may stand but names no upload: it is text, not a
|
|
114
|
+
* reference, so it never reaches a `fileRefs` row or the file check.
|
|
115
|
+
*/
|
|
116
|
+
export type IsUploadId = (id: string) => boolean
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Upload IDs referenced anywhere in a value: image and file fields store `{ file }`, Markdown texts hold `$file.<id>`
|
|
120
|
+
* (those `isUploadId` accepts). `only` keeps those of one field type (no Markdown references).
|
|
121
|
+
*/
|
|
122
|
+
export function fileIdsOf(fields: Fields, data: Data, which: { isUploadId: IsUploadId } | { only: 'image' | 'file' }): Set<string> {
|
|
123
|
+
const only = 'only' in which ? which.only : undefined
|
|
124
|
+
const ids = new Set<string>()
|
|
125
|
+
const walk = (field: Field, value: Json | undefined) => {
|
|
126
|
+
if (value === undefined || value === null) return
|
|
127
|
+
if ((field.type === 'image' || field.type === 'file') && (!only || field.type === only) && typeof asRecord(value).file === 'string') ids.add(asRecord(value).file as string)
|
|
128
|
+
if (field.type === 'markdown' && 'isUploadId' in which) for (const text of textsOf(value)) for (const id of fileRefsIn(text)) if (which.isUploadId(id)) ids.add(id)
|
|
129
|
+
if (field.type === 'list' && Array.isArray(value)) for (const row of value) for (const [k, inner] of Object.entries(field.of)) walk(inner, asRecord(row)[k])
|
|
130
|
+
}
|
|
131
|
+
for (const [name, field] of Object.entries(fields)) walk(field, data[name])
|
|
132
|
+
return ids
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** One place where an entry uses a file: the path in the entry (list rows by their `_id`) and whether an image lacks its description in any language. */
|
|
136
|
+
export interface Use { path: string; missingAlt: boolean }
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Every use of a file in an entry, by upload ID. The same walk as `fileIdsOf`, so the file
|
|
140
|
+
* references and their `uses` can never disagree. An image needs an effective description (its own text, else the library text) in each
|
|
141
|
+
* of the site's `locales`; a file (PDF) has none. A Markdown text that references a file is one use at the text's
|
|
142
|
+
* path; it lacks a description where a language's text shows the file as `` and the library has no
|
|
143
|
+
* text for that language.
|
|
144
|
+
*/
|
|
145
|
+
export function usesOf(fields: Fields, data: Data, locales: readonly Locale[], isUploadId: IsUploadId, fileAlt?: (file: string) => Record<string, string> | undefined): Map<string, Use[]> {
|
|
146
|
+
const out = new Map<string, Use[]>()
|
|
147
|
+
const walk = (path: string, field: Field, value: Json | undefined) => {
|
|
148
|
+
if (value === undefined || value === null) return
|
|
149
|
+
if (field.type === 'image' || field.type === 'file') {
|
|
150
|
+
const file = asRecord(value).file
|
|
151
|
+
if (typeof file !== 'string') return
|
|
152
|
+
const alt = asRecord(value).alt
|
|
153
|
+
const library = fileAlt?.(file)
|
|
154
|
+
const missingAlt = field.type === 'image' && locales.some((l) => !effectiveAlt(alt, library, l))
|
|
155
|
+
out.set(file, [...(out.get(file) ?? []), { path, missingAlt }])
|
|
156
|
+
}
|
|
157
|
+
if (field.type === 'markdown') {
|
|
158
|
+
// A text for every language (translate: false) is checked against each of them.
|
|
159
|
+
const texts: [readonly Locale[], string][] = typeof value === 'string' ? [[locales, value]] : Object.entries(asRecord(value)).flatMap(([l, t]) => (typeof t === 'string' && locales.includes(l) ? [[[l], t] as [Locale[], string]] : []))
|
|
160
|
+
const files = new Set(texts.flatMap(([, text]) => [...fileRefsIn(text)]).filter(isUploadId))
|
|
161
|
+
for (const file of files) {
|
|
162
|
+
const library = fileAlt?.(file)
|
|
163
|
+
const missingAlt = texts.some(([langs, text]) => fileImagesWithoutAlt(text).has(file) && langs.some((l) => !effectiveAlt(undefined, library, l)))
|
|
164
|
+
out.set(file, [...(out.get(file) ?? []), { path, missingAlt }])
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
if (field.type === 'list' && Array.isArray(value)) {
|
|
168
|
+
value.forEach((row, i) => {
|
|
169
|
+
const key = typeof asRecord(row)._id === 'string' ? (asRecord(row)._id as string) : String(i)
|
|
170
|
+
for (const [k, inner] of Object.entries(field.of)) walk(`${path}.${key}.${k}`, inner, asRecord(row)[k])
|
|
171
|
+
})
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
for (const [name, field] of Object.entries(fields)) walk(name, field, data[name])
|
|
175
|
+
return out
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
type MarkdownField = Extract<Field, { type: 'markdown' }>
|
|
179
|
+
|
|
180
|
+
/** The Markdown texts of `data` with their paths (`intro`, `days.r1.note`), in any language, stored or as a tool sends them. */
|
|
181
|
+
export function markdownTextsOf(fields: Fields, data: Data): { path: string; text: string; field: MarkdownField }[] {
|
|
182
|
+
const out: { path: string; text: string; field: MarkdownField }[] = []
|
|
183
|
+
const walk = (path: string, field: Field, value: Json | undefined) => {
|
|
184
|
+
if (value === undefined || value === null) return
|
|
185
|
+
if (field.type === 'markdown') {
|
|
186
|
+
const texts = typeof value === 'string' ? [value] : Object.values(asRecord(value)).filter((t): t is string => typeof t === 'string')
|
|
187
|
+
for (const text of texts) out.push({ path, text, field })
|
|
188
|
+
}
|
|
189
|
+
if (field.type === 'list' && Array.isArray(value)) {
|
|
190
|
+
value.forEach((row, i) => {
|
|
191
|
+
const key = typeof asRecord(row)._id === 'string' ? (asRecord(row)._id as string) : String(i)
|
|
192
|
+
for (const [k, inner] of Object.entries(field.of)) walk(`${path}.${key}.${k}`, inner, asRecord(row)[k])
|
|
193
|
+
})
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
for (const [name, field] of Object.entries(fields)) if (!field.retired) walk(name, field, data[name])
|
|
197
|
+
return out
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** The facts the Markdown texts of `data` quote (`:fact{name="…"}`), each with the paths of the texts, in any language. */
|
|
201
|
+
export function factQuotesOf(fields: Fields, data: Data): Map<string, string[]> {
|
|
202
|
+
const out = new Map<string, string[]>()
|
|
203
|
+
for (const { path, text } of markdownTextsOf(fields, data)) {
|
|
204
|
+
for (const name of new Set(factNamesIn(text))) {
|
|
205
|
+
const paths = out.get(name) ?? []
|
|
206
|
+
if (!paths.includes(path)) out.set(name, [...paths, path])
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return out
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** The value at a path written by `usesOf`. */
|
|
213
|
+
export function valueAt(data: Data, path: string): Json | undefined {
|
|
214
|
+
let current: Json | undefined = data
|
|
215
|
+
for (const key of path.split('.')) {
|
|
216
|
+
if (Array.isArray(current)) current = current.find((row, i) => asRecord(row)._id === key || (typeof asRecord(row)._id !== 'string' && String(i) === key))
|
|
217
|
+
else if (isRecord(current)) current = current[key]
|
|
218
|
+
else return undefined
|
|
219
|
+
}
|
|
220
|
+
return current
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** An entry ID in a `ref` field: its root field, its content path (`author`, `credits.<row id>.who`) and the brick it points to. */
|
|
224
|
+
export interface RefId { root: string; path: string; to: string; id: string }
|
|
225
|
+
|
|
226
|
+
/** Every entry ID the `ref` fields of `data` hold: a single ID, a list with `multiple`, also in list rows. */
|
|
227
|
+
export function refIdsIn(fields: Fields, data: Data): RefId[] {
|
|
228
|
+
const out: RefId[] = []
|
|
229
|
+
const walk = (root: string, path: string, field: Field, value: Json | undefined) => {
|
|
230
|
+
if (field.type === 'ref') for (const id of [value].flat()) if (typeof id === 'string') out.push({ root, path, to: field.to, id })
|
|
231
|
+
if (field.type === 'list' && Array.isArray(value)) {
|
|
232
|
+
value.forEach((row, i) => {
|
|
233
|
+
if (!isRecord(row)) return
|
|
234
|
+
// Rows are named by `_id` like `usesOf` and `valueAt`; a row without one by its index.
|
|
235
|
+
const key = typeof row._id === 'string' ? row._id : String(i)
|
|
236
|
+
for (const [k, inner] of Object.entries(field.of)) walk(root, `${path}.${key}.${k}`, inner, row[k])
|
|
237
|
+
})
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
for (const [name, field] of Object.entries(fields)) walk(name, name, field, data[name])
|
|
241
|
+
return out
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** The label of the field at a content path (`hero`, `rows.<id>.image`): the leaf field's own label, so a use reads "Title image" and not a path. */
|
|
245
|
+
export function fieldLabelAt(schema: Schema, brick: string, path: string): Label | null {
|
|
246
|
+
let fields: Fields | undefined = Object.hasOwn(schema.bricks, brick) ? schema.bricks[brick]!.fields : undefined
|
|
247
|
+
let label: Label | null = null
|
|
248
|
+
const keys = path.split('.')
|
|
249
|
+
for (let i = 0; fields && i < keys.length; i++) {
|
|
250
|
+
const field: Field | undefined = Object.hasOwn(fields, keys[i]!) ? fields[keys[i]!] : undefined
|
|
251
|
+
if (!field) return label
|
|
252
|
+
label = field.label
|
|
253
|
+
if (field.type === 'list' && i + 2 < keys.length) {
|
|
254
|
+
fields = field.of
|
|
255
|
+
i += 1
|
|
256
|
+
} else fields = undefined
|
|
257
|
+
}
|
|
258
|
+
return label
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* The data with every entry ID of a `ref` field (a single ID, or a list with `multiple`, also in list rows)
|
|
263
|
+
* found in `map` replaced by its new ID. Unknown IDs stay as they are. Entry references live only in `data`;
|
|
264
|
+
* no index table repeats them.
|
|
265
|
+
*/
|
|
266
|
+
export function remapEntryRefs(fields: Fields, data: Data, map: ReadonlyMap<string, string>): Data {
|
|
267
|
+
const swap = (id: Json): Json => (typeof id === 'string' ? (map.get(id) ?? id) : id)
|
|
268
|
+
const walk = (field: Field, value: Json | undefined): Json | undefined => {
|
|
269
|
+
if (value === undefined || value === null) return value
|
|
270
|
+
if (field.type === 'ref') return Array.isArray(value) ? value.map(swap) : swap(value)
|
|
271
|
+
if (field.type === 'list' && Array.isArray(value)) {
|
|
272
|
+
return value.map((row) => {
|
|
273
|
+
if (!isRecord(row)) return row
|
|
274
|
+
const out: Record<string, Json> = { ...row }
|
|
275
|
+
for (const [key, inner] of Object.entries(field.of)) if (out[key] !== undefined) out[key] = walk(inner, out[key])!
|
|
276
|
+
return out
|
|
277
|
+
})
|
|
278
|
+
}
|
|
279
|
+
return value
|
|
280
|
+
}
|
|
281
|
+
const out: Data = { ...data }
|
|
282
|
+
for (const [name, field] of Object.entries(fields)) if (out[name] !== undefined) out[name] = walk(field, out[name])!
|
|
283
|
+
return out
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* The trees of an entry's Markdown texts as JSON text, which the bundle serves (`entryTrees` in schema.ts, lib/trees.ts),
|
|
288
|
+
* and their UTF-8 size. '' and 0 when the entry has no Markdown text. The trees do not count toward an entry's budget
|
|
289
|
+
* (core `entryBytes`); their size only feeds the site's `treeBytes` guard.
|
|
290
|
+
*/
|
|
291
|
+
export async function treesOf(fields: Fields, data: Data): Promise<{ json: string; bytes: number }> {
|
|
292
|
+
const trees = await markdownTrees(fields, data)
|
|
293
|
+
const json = Object.keys(trees).length ? JSON.stringify(trees) : ''
|
|
294
|
+
return { json, bytes: new TextEncoder().encode(json).byteLength }
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* The order value of a new or restored entry (SPEC 4.2): first, so the editor finds it at the top of the list and the
|
|
299
|
+
* site shows it first in a manually ordered collection. A navigation tree stores it last instead: it joins the last
|
|
300
|
+
* section until it is placed (NavPlace). `orders` are those of every row of the brick, removed ones included.
|
|
301
|
+
*/
|
|
302
|
+
export function newOrder(key: string, brick: CollectionBrick, orders: number[]): number {
|
|
303
|
+
return isNavTree(key, brick) ? Math.max(0, ...orders) + 1 : Math.min(1, ...orders) - 1
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** The texts of a Markdown value: one string, or one per language. */
|
|
307
|
+
function textsOf(value: Json): string[] {
|
|
308
|
+
return typeof value === 'string' ? [value] : Object.values(asRecord(value)).filter((text): text is string => typeof text === 'string')
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function isRecord(v: unknown): v is Record<string, Json> {
|
|
312
|
+
return typeof v === 'object' && v !== null && !Array.isArray(v)
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function asRecord(v: unknown): Record<string, Json> {
|
|
316
|
+
return isRecord(v) ? v : {}
|
|
317
|
+
}
|