@nickpaustian/tela 0.1.3 → 0.3.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.
@@ -34,6 +34,15 @@ export const STORAGE_TYPES: Record<string, (value: unknown) => boolean> = {
34
34
  number: (v) => typeof v === "number" && Number.isFinite(v),
35
35
  boolean: (v) => typeof v === "boolean",
36
36
  repeater: (v) => Array.isArray(v),
37
+ /**
38
+ * Somewhere to go: another entry, a file, or an address.
39
+ *
40
+ * Stored as `tela:<collection>/<id>` for an entry or a file, so it follows a
41
+ * rename the way a reference does, and as the address itself for anything
42
+ * else. Published with the entry's slug, as rich-text links are, or as the
43
+ * file's address.
44
+ */
45
+ link: (v) => typeof v === "string",
37
46
  /**
38
47
  * A pointer to another entry.
39
48
  *
@@ -91,6 +100,29 @@ export interface Block {
91
100
  * it, and so nothing has to move when it does.
92
101
  */
93
102
  preview?: string
103
+ /** A line in the row, above its fields: what is set elsewhere and who to ask. */
104
+ note?: string
105
+ /**
106
+ * The pages this block is made for, by address: `/membership`, or
107
+ * `/fellowships/*` for everything under one. Offered only there, in a group
108
+ * of its own, and never in the picker anywhere else.
109
+ */
110
+ for?: string[]
111
+ /**
112
+ * Data sources this block shows, by collection name. The site reads them
113
+ * when it builds, so a change to one reaches every block that uses it.
114
+ */
115
+ uses?: string[]
116
+ /** At most one in a list. Once added it leaves the picker. */
117
+ once?: boolean
118
+ /** Moved like any other, never removed in the editor. */
119
+ kept?: boolean
120
+ /**
121
+ * What the block holds that is written in code rather than typed. Published
122
+ * under the row's own values, so a field of the same name is a part of it an
123
+ * editor may change.
124
+ */
125
+ content?: Record<string, unknown>
94
126
  fields: Field[]
95
127
  }
96
128
 
@@ -141,8 +173,18 @@ export interface Field {
141
173
  * than guess.
142
174
  */
143
175
  required?: boolean
144
- /** What a field holds before anyone sets it. Seeded into the editor, never written for the field by the API. */
176
+ /**
177
+ * What a field holds before anyone sets it. Seeded into the editor, never
178
+ * written for the field by the API. A date field takes `"today"`: the
179
+ * editor's own date when the form opens.
180
+ */
145
181
  default?: unknown
182
+ /**
183
+ * What the field means while nobody has set it. Unlike `default` it is never
184
+ * copied into the entry: the editor shows it greyed until somebody changes
185
+ * it, and publishing fills it in, so a field left alone follows the code.
186
+ */
187
+ fallback?: unknown
146
188
  /** Shown, and judged, only when a sibling field agrees. */
147
189
  when?: Condition
148
190
  /** Unique within the collection. Checked server-side, excluding this entry. */
@@ -356,7 +398,8 @@ export interface Field {
356
398
  */
357
399
  of?: Field[]
358
400
  /**
359
- * How many rows a repeater must and may hold.
401
+ * How many rows a repeater must and may hold, or how many entries a `many`
402
+ * reference may pick.
360
403
  *
361
404
  * Not `min`/`max`: those already mean numeric bounds, and a key that means
362
405
  * two things depending on the type is the mistake `type`/`component` was
@@ -435,6 +478,22 @@ export interface Collection {
435
478
  * once, and the editor offers nothing to publish.
436
479
  */
437
480
  publishable?: boolean
481
+ /**
482
+ * A data source: one record of facts with no page of its own - memberships,
483
+ * opening hours, site switches - kept in one place so every page and every
484
+ * app that shows them reads the same thing. Lists inside it are repeaters,
485
+ * so editors set their order.
486
+ *
487
+ * The admin opens straight onto the record. Publishing writes it to
488
+ * `content/data/<name>.json`, with no index and no slug in the file.
489
+ */
490
+ data?: boolean
491
+ /**
492
+ * A data source's shape version, from 1. Raised by a developer when a change
493
+ * breaks the apps reading it: a field removed, retyped or no longer
494
+ * required. Publishing refuses such a change until it is raised.
495
+ */
496
+ version?: number
438
497
  /**
439
498
  * What this collection is drawn with, by id from the built-in set in
440
499
  * `config/icons.ts`. Left out, the collection's name suggests one, and a
@@ -595,6 +654,33 @@ export interface TelaConfig {
595
654
  * since a development copy and the real site are not at the same address.
596
655
  */
597
656
  site?: string
657
+ /**
658
+ * Other addresses the site is known by, such as the live site while a
659
+ * development copy is `site`. A link pasted from any of them is read as a
660
+ * page on this site.
661
+ */
662
+ siteAliases?: string[]
663
+ /**
664
+ * Where data sources can be read once published, if anywhere: a path on the
665
+ * site (`/data/{name}.json`) or a whole address, `{name}` standing for the
666
+ * source. Left out, the editor names the file in the content repo alone,
667
+ * since what serves it is the project's choice.
668
+ */
669
+ dataAddress?: string
670
+ /**
671
+ * Addresses told when published content changes, once it is committed and
672
+ * pushed: a data API to pull, an indexer, a build. A hook that fails is
673
+ * logged and never fails the publish.
674
+ */
675
+ afterPublish?: PublishHook[]
676
+ /**
677
+ * Lists gathered from everything published, each written to
678
+ * `content/data/<name>.json` as `{ values: [...] }` and kept up to date by
679
+ * every publish and takedown: the videos on the site, for a server that
680
+ * will only stream those. Run `tela republish` after adding one or changing
681
+ * what it gathers, since a list only learns of an entry when it is published.
682
+ */
683
+ gathered?: GatheredList[]
598
684
  /**
599
685
  * The site's name, as search results and link cards give it. Collections
600
686
  * with `seo` add it to titles in search results unless they say otherwise.
@@ -660,6 +746,24 @@ export interface TelaConfig {
660
746
  components?: string[]
661
747
  }
662
748
 
749
+ export interface GatheredList {
750
+ /** The file's name, and the `cms:data:<name>` cell. Not a collection's name. */
751
+ name: string
752
+ /** What one published entry adds to the list. Text or numbers; anything else is left out. */
753
+ from: (data: Record<string, unknown>, entry: { collection: string }) => Iterable<unknown> | null | undefined
754
+ /** Only entries of these collections. All of them when left out. */
755
+ collections?: string[]
756
+ }
757
+
758
+ export interface PublishHook {
759
+ /** POSTed `{ event, commit, files, cells, collections }`. */
760
+ url: string
761
+ /** Sent as `Authorization: Bearer <token>`. Read it from the environment. */
762
+ token?: string
763
+ /** Only when one of these changed, by collection or data source name. */
764
+ collections?: string[]
765
+ }
766
+
663
767
  export interface NavSection {
664
768
  heading: string
665
769
  /** Collection names, in the order they should appear under it. */
@@ -805,7 +909,7 @@ export const LABEL_KEY = "internalLabel"
805
909
  * as wrong as one at the top, and finding it at boot beats finding it in
806
910
  * JSONB.
807
911
  */
808
- function checkFields(fields: Field[], path: string, known: Set<string> = new Set()) {
912
+ function checkFields(fields: Field[], path: string, known: Set<string> = new Set(), dataNames: Set<string> = new Set()) {
809
913
  for (const field of fields) {
810
914
  const where = `${path}.${field.name}`
811
915
 
@@ -818,7 +922,7 @@ function checkFields(fields: Field[], path: string, known: Set<string> = new Set
818
922
  }
819
923
 
820
924
  // A group's children are ordinary fields and are checked as such.
821
- if (field.fields) checkFields(field.fields, where, known)
925
+ if (field.fields) checkFields(field.fields, where, known, dataNames)
822
926
 
823
927
  for (const tool of field.tools ?? []) {
824
928
  if (!TOOL_NAMES.includes(tool as any)) {
@@ -873,15 +977,26 @@ function checkFields(fields: Field[], path: string, known: Set<string> = new Set
873
977
  }
874
978
  }
875
979
 
876
- if (field.of) checkFields(field.of, where, known)
980
+ if (field.of) checkFields(field.of, where, known, dataNames)
877
981
 
878
982
  const seen = new Set<string>()
879
983
  for (const block of field.blocks ?? []) {
880
984
  if (seen.has(block.name)) {
881
985
  throw new Error(`${where}: two blocks are both named "${block.name}".`)
882
986
  }
987
+ if (block.content && BLOCK_KEY in block.content) {
988
+ throw new Error(`${where}: block "${block.name}" has "${BLOCK_KEY}" in its content, which is how a row records its shape.`)
989
+ }
990
+ for (const source of block.uses ?? []) {
991
+ if (!dataNames.has(source)) {
992
+ throw new Error(`${where}: block "${block.name}" uses "${source}", which is not a data source.`)
993
+ }
994
+ }
995
+ if (block.for?.some((page) => !page.startsWith("/"))) {
996
+ throw new Error(`${where}: block "${block.name}" is for pages by address, each starting with "/".`)
997
+ }
883
998
  seen.add(block.name)
884
- checkFields(block.fields, `${where}[${block.name}]`, known)
999
+ checkFields(block.fields, `${where}[${block.name}]`, known, dataNames)
885
1000
  }
886
1001
  }
887
1002
  }
@@ -895,6 +1010,23 @@ function checkFields(fields: Field[], path: string, known: Set<string> = new Set
895
1010
  */
896
1011
  export const BUILT_IN = ["users", "groups", "media"]
897
1012
 
1013
+ export const COLLECTION_NAME = /^[a-z][a-zA-Z0-9-]*$/
1014
+
1015
+ function checkCollectionName(name: string) {
1016
+ if (!COLLECTION_NAME.test(name)) {
1017
+ throw new Error(
1018
+ `"${name}": a collection's name is a folder in the content repo and part of its rebuild keys, ` +
1019
+ `so start with a lowercase letter and use only letters, digits and hyphens.`,
1020
+ )
1021
+ }
1022
+ if (name === "data") {
1023
+ throw new Error(
1024
+ `"data" is reserved: data sources are published to content/data/ and rebuilt as cms:data:<name>, ` +
1025
+ `so a collection called data would overwrite them. Choose another name.`,
1026
+ )
1027
+ }
1028
+ }
1029
+
898
1030
  /**
899
1031
  * The half of a workflow that can be checked without a database.
900
1032
  *
@@ -953,6 +1085,32 @@ function checkWorkflow(collection: Collection) {
953
1085
  }
954
1086
  }
955
1087
 
1088
+ /** A data source is one record with no page: nothing to address it by but its name. */
1089
+ function checkDataSource(collection: Collection) {
1090
+ const where = collection.name
1091
+ if (collection.url) throw new Error(`${where}: a data source has no page, so no \`url\`.`)
1092
+ if (collection.publishable === false) throw new Error(`${where}: a data source is published, so it cannot set \`publishable: false\`.`)
1093
+ if (collection.version !== undefined && !(Number.isInteger(collection.version) && collection.version >= 1)) {
1094
+ throw new Error(`${where}: \`version\` counts up from 1.`)
1095
+ }
1096
+ const flat = (fields: Field[]): Field[] => fields.flatMap((field) => (field.type === "group" ? flat(field.fields ?? []) : [field]))
1097
+ if (flat(collection.fields).some((field) => field.name === "slug")) {
1098
+ throw new Error(`${where}: a data source is named by its collection, so it has no "slug" field.`)
1099
+ }
1100
+ }
1101
+
1102
+ function checkHook(hook: PublishHook, known: Set<string>) {
1103
+ let url: URL
1104
+ try {
1105
+ url = new URL(hook.url)
1106
+ } catch {
1107
+ throw new Error(`afterPublish: "${hook.url}" is not an address.`)
1108
+ }
1109
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error(`afterPublish: ${hook.url} must be http or https.`)
1110
+ const unknown = (hook.collections ?? []).filter((name) => !known.has(name))
1111
+ if (unknown.length) throw new Error(`afterPublish: ${hook.url} names ${unknown.join(", ")}, which no collection is called.`)
1112
+ }
1113
+
956
1114
  export function defineConfig(config: TelaConfig): TelaConfig {
957
1115
  // A type nothing knows how to store would otherwise pass every check
958
1116
  // silently - the field simply never gets shape-checked, and nobody finds out
@@ -963,11 +1121,29 @@ export function defineConfig(config: TelaConfig): TelaConfig {
963
1121
 
964
1122
  const declaredCollections = config.collections.map((one) => withSeo(one, config.siteName))
965
1123
 
1124
+ const dataNames = new Set(config.collections.filter((one) => one.data).map((one) => one.name))
1125
+
966
1126
  for (const collection of declaredCollections) {
967
- checkFields(collection.fields, collection.name, known)
1127
+ checkCollectionName(collection.name)
1128
+ checkFields(collection.fields, collection.name, known, dataNames)
968
1129
  checkWorkflow(collection)
1130
+ if (collection.data) checkDataSource(collection)
1131
+ else if (collection.version !== undefined) throw new Error(`${collection.name}: only a data source has a \`version\`.`)
969
1132
  }
970
1133
 
1134
+ const gatheredNames = new Set<string>()
1135
+ for (const list of config.gathered ?? []) {
1136
+ if (!/^[a-z][a-z0-9-]*$/.test(list.name)) throw new Error(`gathered: "${list.name}" must start lowercase and use letters, digits and hyphens.`)
1137
+ if (known.has(list.name)) throw new Error(`gathered: "${list.name}" is a collection's name, and would be written over its data.`)
1138
+ if (gatheredNames.has(list.name)) throw new Error(`gathered: "${list.name}" is declared twice.`)
1139
+ const unknown = (list.collections ?? []).filter((name) => !known.has(name))
1140
+ if (unknown.length) throw new Error(`gathered: ${list.name} names ${unknown.join(", ")}, which no collection is called.`)
1141
+ gatheredNames.add(list.name)
1142
+ }
1143
+
1144
+ // A hook may wait on a gathered list as it would a data source.
1145
+ for (const hook of config.afterPublish ?? []) checkHook(hook, new Set([...known, ...gatheredNames]))
1146
+
971
1147
  const declared = declaredCollections.find((c) => c.name === "users")
972
1148
 
973
1149
  // Names sit straight after the address: who somebody is comes before what
@@ -1051,6 +1227,10 @@ export function defineConfig(config: TelaConfig): TelaConfig {
1051
1227
  ...(config.overrides ? { overrides: config.overrides } : {}),
1052
1228
  ...(config.components ? { components: config.components } : {}),
1053
1229
  ...(config.site ? { site: config.site } : {}),
1230
+ ...(config.siteAliases?.length ? { siteAliases: config.siteAliases } : {}),
1231
+ ...(config.dataAddress ? { dataAddress: config.dataAddress } : {}),
1232
+ ...(config.afterPublish?.length ? { afterPublish: config.afterPublish } : {}),
1233
+ ...(config.gathered?.length ? { gathered: config.gathered } : {}),
1054
1234
  ...(config.siteName ? { siteName: config.siteName } : {}),
1055
1235
  ...(config.userNames ? { userNames: true } : {}),
1056
1236
  }
@@ -1,4 +1,4 @@
1
- import type { Collection, Field } from "../config/types.ts"
1
+ import type { Block, Collection, Field } from "../config/types.ts"
2
2
  import { blockOf, blocksOf, dataFields, isSlot } from "../config/components.ts"
3
3
 
4
4
  /**
@@ -15,6 +15,9 @@ import { blockOf, blocksOf, dataFields, isSlot } from "../config/components.ts"
15
15
  * in somebody else's build - and a rule reduced to something safe to ship
16
16
  * cannot call `Intl`.
17
17
  *
18
+ * Fields left unset take their `fallback`, and a block written partly in code
19
+ * gets that `content` under what the editor set, so the file is whole.
20
+ *
18
21
  * Pure, and given the whole entry, so it can be applied to a draft on its way
19
22
  * to a preview as easily as to a release on its way to a file.
20
23
  */
@@ -82,10 +85,18 @@ export function withDerived(
82
85
  return walk(dataFields(collection.fields), data)
83
86
  }
84
87
 
88
+ const unset = (value: unknown) => value === undefined || value === null || value === ""
89
+
90
+ /** A block's code content under the row's own values: what an editor changed wins. */
91
+ function withContent(block: Block, row: Record<string, unknown>): Record<string, unknown> {
92
+ return block.content ? { ...structuredClone(block.content), ...row } : row
93
+ }
94
+
85
95
  function walk(fields: Field[], data: Record<string, unknown>): Record<string, unknown> {
86
96
  const out = { ...data }
87
97
 
88
98
  for (const field of dataFields(fields)) {
99
+ if (field.fallback !== undefined && unset(out[field.name])) out[field.name] = structuredClone(field.fallback)
89
100
  const value = out[field.name]
90
101
 
91
102
  if (isSlot(field)) {
@@ -93,7 +104,7 @@ function walk(fields: Field[], data: Record<string, unknown>): Record<string, un
93
104
 
94
105
  const inner = value as Record<string, unknown>
95
106
  const block = blockOf(field, inner)
96
- const walked = block ? walk(block.fields, inner) : inner
107
+ const walked = block ? walk(block.fields, withContent(block, inner)) : inner
97
108
 
98
109
  // A composite derives from its own parts; a slot holding a chosen block
99
110
  // derives from whatever that block put there.
@@ -107,7 +118,7 @@ function walk(fields: Field[], data: Record<string, unknown>): Record<string, un
107
118
  out[field.name] = value.map((row) => {
108
119
  if (!row || typeof row !== "object") return row
109
120
  const block = blockOf(field, row)
110
- return block ? walk(block.fields, row as Record<string, unknown>) : row
121
+ return block ? walk(block.fields, withContent(block, row as Record<string, unknown>)) : row
111
122
  })
112
123
  continue
113
124
  }
@@ -90,10 +90,24 @@ function walkFields(fields: Field[], data: Record<string, unknown>, prefix: stri
90
90
  continue
91
91
  }
92
92
 
93
- set(VALUE + path, value ?? field.default)
93
+ set(VALUE + path, value ?? defaultOf(field))
94
94
  }
95
95
  }
96
96
 
97
+ /**
98
+ * What a field starts as. A date's `"today"` is the editor's own today, worked
99
+ * out as the form opens rather than when the config was written, which is the
100
+ * only way a default can move.
101
+ */
102
+ export function defaultOf(field: Field, now: Date = new Date()): unknown {
103
+ if (field.type === "date" && field.default === "today") {
104
+ const month = String(now.getMonth() + 1).padStart(2, "0")
105
+ const day = String(now.getDate()).padStart(2, "0")
106
+ return `${now.getFullYear()}-${month}-${day}`
107
+ }
108
+ return field.default
109
+ }
110
+
97
111
  /** Gather the entry back out of the cells. */
98
112
  export function assemble(collection: Collection, get: Get): Record<string, unknown> {
99
113
  return gather(dataFields(collection.fields), "", get)
@@ -2,9 +2,13 @@ import { mkdir, writeFile, readFile, rm } from "fs/promises"
2
2
  import { existsSync } from "fs"
3
3
  import { dirname, join } from "path"
4
4
  import { sql } from "../db/client.ts"
5
+ import { config } from "../config/load.ts"
5
6
  import { findCollection } from "./collections.ts"
7
+ import { writeGathered } from "./gathered.ts"
6
8
  import { DIALECT } from "./richtext.ts"
7
9
  import { withDerived } from "./derive-values.ts"
10
+ import type { Collection } from "../config/types.ts"
11
+ import { dataShape, shapePath, shapeProblem, type DataShape } from "./shape.ts"
8
12
  import {
9
13
  collectReferences,
10
14
  findReferrers,
@@ -75,15 +79,31 @@ export function dialectDocument() {
75
79
  }
76
80
 
77
81
  export function entryPath(collection: string, slug: string) {
82
+ if (isDataSource(collection)) return join("content", "data", `${collection}.json`)
78
83
  return join("content", collection, `${slug}.json`)
79
84
  }
80
85
 
86
+ const isDataSource = (collection: string) => findCollection(collection)?.data === true
87
+
88
+ /**
89
+ * What goes in an entry's file: references as slugs, derived values beside
90
+ * their parts. A data source's slug is only how Tela finds its one record, so
91
+ * it stays out of the file.
92
+ */
93
+ function fileData(collection: Collection, data: Record<string, unknown>, slugs: Map<string, unknown>) {
94
+ const out = withDerived(collection, withSlugs(collection, data, slugs))
95
+ if (!collection.data) return out
96
+ const { slug: _slug, ...rest } = out
97
+ return rest
98
+ }
99
+
81
100
  export function indexPath(collection: string) {
82
101
  return join("content", collection, "index.json")
83
102
  }
84
103
 
85
104
  /** `cms:post:hello-world` — the key a page uses for its own entry. */
86
105
  export function entryCell(collection: string, slug: string) {
106
+ if (isDataSource(collection)) return `cms:data:${collection}`
87
107
  return `cms:${collection}:${slug}`
88
108
  }
89
109
 
@@ -174,10 +194,23 @@ export async function exportRelease(
174
194
  }
175
195
  }
176
196
 
177
- const slugs = new Map<string, unknown>([
178
- ...(await publishedReferences([...wanted].filter((id) => !staged.has(id)))),
179
- ...staged,
180
- ])
197
+ const elsewhere = [...wanted].filter((id) => !staged.has(id))
198
+ const slugs = new Map<string, unknown>([...(await publishedReferences(elsewhere, { pictures: "named" })), ...staged])
199
+ // A data source stands alone for other apps, so its pictures are copied in.
200
+ const sourced = [...published, ...alsoWrite].some((row) => findCollection(row.collection)?.data)
201
+ const copied = sourced ? new Map<string, unknown>([...(await publishedReferences(elsewhere)), ...staged]) : slugs
202
+ const referencesFor = (collection: Collection) => (collection.data ? copied : slugs)
203
+
204
+ // Before anything is written, so a refused shape leaves the repo untouched.
205
+ const shapes = new Map<string, DataShape>()
206
+ for (const row of [...published, ...alsoWrite]) {
207
+ const collection = findCollection(row.collection)
208
+ if (!collection?.data || shapes.has(collection.name)) continue
209
+ const next = dataShape(collection)
210
+ const problem = shapeProblem(await read(options.root, shapePath(collection.name)), next)
211
+ if (problem) throw problem
212
+ shapes.set(collection.name, next)
213
+ }
181
214
 
182
215
  // A slug is a file name, so moving one leaves the old file behind. Removed
183
216
  // before anything is written, so a release that renames A to B and B to
@@ -210,16 +243,31 @@ export async function exportRelease(
210
243
  await write(
211
244
  options.root,
212
245
  path,
213
- collection
214
- ? withDerived(collection, withSlugs(collection, row.data, slugs))
215
- : row.data,
246
+ collection ? fileData(collection, row.data, referencesFor(collection)) : row.data,
216
247
  )
217
248
 
218
249
  files.push(path)
219
250
  cells.push(entryCell(row.collection, slug))
220
- touched.add(row.collection)
251
+ if (!collection?.data) touched.add(row.collection)
252
+ }
253
+
254
+ for (const [name, shape] of shapes) {
255
+ const path = shapePath(name)
256
+ if (JSON.stringify(await read(options.root, path)) === JSON.stringify(shape)) continue
257
+ await write(options.root, path, shape)
258
+ files.push(path)
221
259
  }
222
260
 
261
+ const pictures = await writePictures(
262
+ [...published, ...alsoWrite].flatMap((row) => {
263
+ const collection = findCollection(row.collection)
264
+ return collection && !collection.data ? collectReferences(collection, row.data ?? {}).flatMap((one) => one.ids) : []
265
+ }),
266
+ options.root,
267
+ )
268
+ files.push(...pictures.files)
269
+ cells.push(...pictures.cells)
270
+
223
271
  for (const collection of touched) {
224
272
  const path = indexPath(collection)
225
273
  const rows = await publishedRows(collection, releaseId)
@@ -242,6 +290,14 @@ export async function exportRelease(
242
290
  cells.push(indexCell(collection))
243
291
  }
244
292
 
293
+ const gathered = await writeGathered(
294
+ config.gathered ?? [],
295
+ published.map((row: any) => ({ id: String(row.id), collection: String(row.collection), data: row.data ?? {} })),
296
+ options,
297
+ )
298
+ files.push(...gathered.files)
299
+ cells.push(...gathered.cells)
300
+
245
301
  return { files, cells }
246
302
  }
247
303
 
@@ -284,6 +340,14 @@ export async function exportRemoval(
284
340
  const files = [path]
285
341
  const cells = [entryCell(collection, slug)]
286
342
 
343
+ if (row) {
344
+ const gathered = await writeGathered(config.gathered ?? [], [{ id: String(row.id), collection, data: null }], options)
345
+ files.push(...gathered.files)
346
+ cells.push(...gathered.cells)
347
+ }
348
+
349
+ if (isDataSource(collection)) return { files, cells }
350
+
287
351
  // The index always changes: the entry has left it.
288
352
  const indexFile = indexPath(collection)
289
353
  const rows = await publishedRows(collection)
@@ -341,10 +405,10 @@ async function rewriteWithout(
341
405
  if (!collection || !slug) continue
342
406
 
343
407
  const wanted = collectReferences(collection, row.data).flatMap((one) => one.ids)
344
- const slugs = await publishedReferences(wanted)
408
+ const slugs = await publishedReferences(wanted, { pictures: collection.data ? "copied" : "named" })
345
409
 
346
410
  const path = entryPath(row.collection, slug)
347
- await write(root, path, withDerived(collection, withSlugs(collection, row.data, slugs)))
411
+ await write(root, path, fileData(collection, row.data, slugs))
348
412
 
349
413
  files.push(path)
350
414
  cells.push(entryCell(row.collection, slug))
@@ -467,14 +531,12 @@ async function writeMissing(
467
531
  const wanted = definition
468
532
  ? collectReferences(definition, row.data).flatMap((one) => one.ids)
469
533
  : []
470
- const slugs = await publishedReferences(wanted)
534
+ const slugs = await publishedReferences(wanted, { pictures: definition?.data ? "copied" : "named" })
471
535
 
472
536
  await write(
473
537
  root,
474
538
  path,
475
- definition
476
- ? withDerived(definition, withSlugs(definition, row.data, slugs))
477
- : row.data,
539
+ definition ? fileData(definition, row.data, slugs) : row.data,
478
540
  )
479
541
 
480
542
  files.push(path)
@@ -506,3 +568,126 @@ async function read(root: string, path: string) {
506
568
  return null
507
569
  }
508
570
  }
571
+
572
+ /** Where a picture a page names is published: `content/media/<id>.json`. */
573
+ export const picturePath = (id: string) => join("content", "media", `${id}.json`)
574
+
575
+ /** `cms:media:<id>` - the key a page's picture is read under. */
576
+ export const pictureCell = (id: string) => `cms:media:${id}`
577
+
578
+ /**
579
+ * The pictures some entries name, each written to its own file when what it
580
+ * says has changed. Ids that aren't pictures are passed over, and a picture
581
+ * the library no longer has is left unwritten, like the reference to it.
582
+ */
583
+ async function writePictures(ids: string[], root: string): Promise<ExportResult> {
584
+ const files: string[] = []
585
+ const cells: string[] = []
586
+ const unique = [...new Set(ids)]
587
+ if (!unique.length) return { files, cells }
588
+
589
+ const media = await sql`
590
+ select id from entries
591
+ where collection = 'media' and deleted_at is null
592
+ and id = any(string_to_array(${unique.join(",")}, ',')::uuid[])
593
+ `
594
+ const pictureIds = media.map((row: any) => String(row.id))
595
+ if (!pictureIds.length) return { files, cells }
596
+
597
+ const resolved = await publishedReferences(pictureIds)
598
+ for (const id of pictureIds) {
599
+ const picture = resolved.get(id)
600
+ if (picture === undefined) continue
601
+ const path = picturePath(id)
602
+ if (JSON.stringify(await read(root, path)) === JSON.stringify(picture)) continue
603
+ await write(root, path, picture)
604
+ files.push(path)
605
+ cells.push(pictureCell(id))
606
+ }
607
+ return { files, cells }
608
+ }
609
+
610
+ /**
611
+ * Pictures whose words or file changed (a credit corrected in the library, a
612
+ * new alt text), published again: each one's own file, and every data source
613
+ * using it, since those carry their pictures. Pages name a picture rather than
614
+ * copy it, so its file is all they need; a picture the library has dropped
615
+ * loses its file, and the pages naming it rebuild without it.
616
+ */
617
+ export async function republishPictures(ids: string[], options: { root: string }): Promise<ExportResult> {
618
+ const files: string[] = []
619
+ const cells: string[] = []
620
+ const resolved = await publishedReferences(ids)
621
+
622
+ for (const id of new Set(ids)) {
623
+ const path = picturePath(id)
624
+ const was = await read(options.root, path)
625
+ const now = resolved.get(id)
626
+ if (now === undefined) {
627
+ if (was === null) continue
628
+ await rm(join(options.root, path), { force: true })
629
+ } else {
630
+ if (JSON.stringify(was) === JSON.stringify(now)) continue
631
+ await write(options.root, path, now)
632
+ }
633
+ files.push(path)
634
+ cells.push(pictureCell(id))
635
+ }
636
+
637
+ const sources: { id: string }[] = []
638
+ for (const id of new Set(ids)) {
639
+ for (const one of await findReferrers(id)) {
640
+ if (findCollection(one.collection)?.data) sources.push({ id: one.id })
641
+ }
642
+ }
643
+ if (sources.length) {
644
+ const live = await sql`
645
+ select e.id from entries e
646
+ where e.published_version_id is not null
647
+ and e.id = any(string_to_array(${sources.map((one) => one.id).join(",")}, ',')::uuid[])
648
+ `
649
+ const rewritten = await rewriteWithout(live.map((row: any) => ({ id: String(row.id) })), options.root)
650
+ for (const [i, path] of rewritten.files.entries()) {
651
+ // Written again either way; only a change is worth a rebuild.
652
+ files.push(path)
653
+ cells.push(rewritten.cells[i]!)
654
+ }
655
+ }
656
+
657
+ return { files, cells }
658
+ }
659
+
660
+ /**
661
+ * Published entries written again from their published versions, under the
662
+ * rules publishing follows now, with the pictures they name: for when how
663
+ * content is written changes (pictures named rather than copied, say). Drafts
664
+ * stay drafts; nothing that isn't live is published.
665
+ */
666
+ export async function republishEntries(options: { root: string; collections?: string[] }): Promise<ExportResult> {
667
+ const live = await sql`
668
+ select e.id, e.collection, v.data
669
+ from entries e
670
+ join entry_versions v on v.id = e.published_version_id
671
+ where e.deleted_at is null
672
+ `
673
+ const rows = live.filter((row: any) => !options.collections || options.collections.includes(String(row.collection)))
674
+ const rewritten = await rewriteWithout(rows.map((row: any) => ({ id: String(row.id) })), options.root)
675
+ const pictures = await writePictures(
676
+ rows.flatMap((row: any) => {
677
+ const collection = findCollection(String(row.collection))
678
+ return collection && !collection.data ? collectReferences(collection, row.data ?? {}).flatMap((one) => one.ids) : []
679
+ }),
680
+ options.root,
681
+ )
682
+ // Every published entry is here unless the caller narrowed it, and then the
683
+ // ledger only hears about the ones it was given.
684
+ const gathered = await writeGathered(
685
+ config.gathered ?? [],
686
+ rows.map((row: any) => ({ id: String(row.id), collection: String(row.collection), data: row.data ?? {} })),
687
+ { root: options.root, complete: !options.collections },
688
+ )
689
+ return {
690
+ files: [...rewritten.files, ...pictures.files, ...gathered.files],
691
+ cells: [...rewritten.cells, ...pictures.cells, ...gathered.cells],
692
+ }
693
+ }