@nickpaustian/tela 0.1.3 → 0.2.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,25 @@ 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[]
598
676
  /**
599
677
  * The site's name, as search results and link cards give it. Collections
600
678
  * with `seo` add it to titles in search results unless they say otherwise.
@@ -660,6 +738,15 @@ export interface TelaConfig {
660
738
  components?: string[]
661
739
  }
662
740
 
741
+ export interface PublishHook {
742
+ /** POSTed `{ event, commit, files, cells, collections }`. */
743
+ url: string
744
+ /** Sent as `Authorization: Bearer <token>`. Read it from the environment. */
745
+ token?: string
746
+ /** Only when one of these changed, by collection or data source name. */
747
+ collections?: string[]
748
+ }
749
+
663
750
  export interface NavSection {
664
751
  heading: string
665
752
  /** Collection names, in the order they should appear under it. */
@@ -805,7 +892,7 @@ export const LABEL_KEY = "internalLabel"
805
892
  * as wrong as one at the top, and finding it at boot beats finding it in
806
893
  * JSONB.
807
894
  */
808
- function checkFields(fields: Field[], path: string, known: Set<string> = new Set()) {
895
+ function checkFields(fields: Field[], path: string, known: Set<string> = new Set(), dataNames: Set<string> = new Set()) {
809
896
  for (const field of fields) {
810
897
  const where = `${path}.${field.name}`
811
898
 
@@ -818,7 +905,7 @@ function checkFields(fields: Field[], path: string, known: Set<string> = new Set
818
905
  }
819
906
 
820
907
  // A group's children are ordinary fields and are checked as such.
821
- if (field.fields) checkFields(field.fields, where, known)
908
+ if (field.fields) checkFields(field.fields, where, known, dataNames)
822
909
 
823
910
  for (const tool of field.tools ?? []) {
824
911
  if (!TOOL_NAMES.includes(tool as any)) {
@@ -873,15 +960,26 @@ function checkFields(fields: Field[], path: string, known: Set<string> = new Set
873
960
  }
874
961
  }
875
962
 
876
- if (field.of) checkFields(field.of, where, known)
963
+ if (field.of) checkFields(field.of, where, known, dataNames)
877
964
 
878
965
  const seen = new Set<string>()
879
966
  for (const block of field.blocks ?? []) {
880
967
  if (seen.has(block.name)) {
881
968
  throw new Error(`${where}: two blocks are both named "${block.name}".`)
882
969
  }
970
+ if (block.content && BLOCK_KEY in block.content) {
971
+ throw new Error(`${where}: block "${block.name}" has "${BLOCK_KEY}" in its content, which is how a row records its shape.`)
972
+ }
973
+ for (const source of block.uses ?? []) {
974
+ if (!dataNames.has(source)) {
975
+ throw new Error(`${where}: block "${block.name}" uses "${source}", which is not a data source.`)
976
+ }
977
+ }
978
+ if (block.for?.some((page) => !page.startsWith("/"))) {
979
+ throw new Error(`${where}: block "${block.name}" is for pages by address, each starting with "/".`)
980
+ }
883
981
  seen.add(block.name)
884
- checkFields(block.fields, `${where}[${block.name}]`, known)
982
+ checkFields(block.fields, `${where}[${block.name}]`, known, dataNames)
885
983
  }
886
984
  }
887
985
  }
@@ -895,6 +993,23 @@ function checkFields(fields: Field[], path: string, known: Set<string> = new Set
895
993
  */
896
994
  export const BUILT_IN = ["users", "groups", "media"]
897
995
 
996
+ export const COLLECTION_NAME = /^[a-z][a-zA-Z0-9-]*$/
997
+
998
+ function checkCollectionName(name: string) {
999
+ if (!COLLECTION_NAME.test(name)) {
1000
+ throw new Error(
1001
+ `"${name}": a collection's name is a folder in the content repo and part of its rebuild keys, ` +
1002
+ `so start with a lowercase letter and use only letters, digits and hyphens.`,
1003
+ )
1004
+ }
1005
+ if (name === "data") {
1006
+ throw new Error(
1007
+ `"data" is reserved: data sources are published to content/data/ and rebuilt as cms:data:<name>, ` +
1008
+ `so a collection called data would overwrite them. Choose another name.`,
1009
+ )
1010
+ }
1011
+ }
1012
+
898
1013
  /**
899
1014
  * The half of a workflow that can be checked without a database.
900
1015
  *
@@ -953,6 +1068,32 @@ function checkWorkflow(collection: Collection) {
953
1068
  }
954
1069
  }
955
1070
 
1071
+ /** A data source is one record with no page: nothing to address it by but its name. */
1072
+ function checkDataSource(collection: Collection) {
1073
+ const where = collection.name
1074
+ if (collection.url) throw new Error(`${where}: a data source has no page, so no \`url\`.`)
1075
+ if (collection.publishable === false) throw new Error(`${where}: a data source is published, so it cannot set \`publishable: false\`.`)
1076
+ if (collection.version !== undefined && !(Number.isInteger(collection.version) && collection.version >= 1)) {
1077
+ throw new Error(`${where}: \`version\` counts up from 1.`)
1078
+ }
1079
+ const flat = (fields: Field[]): Field[] => fields.flatMap((field) => (field.type === "group" ? flat(field.fields ?? []) : [field]))
1080
+ if (flat(collection.fields).some((field) => field.name === "slug")) {
1081
+ throw new Error(`${where}: a data source is named by its collection, so it has no "slug" field.`)
1082
+ }
1083
+ }
1084
+
1085
+ function checkHook(hook: PublishHook, known: Set<string>) {
1086
+ let url: URL
1087
+ try {
1088
+ url = new URL(hook.url)
1089
+ } catch {
1090
+ throw new Error(`afterPublish: "${hook.url}" is not an address.`)
1091
+ }
1092
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error(`afterPublish: ${hook.url} must be http or https.`)
1093
+ const unknown = (hook.collections ?? []).filter((name) => !known.has(name))
1094
+ if (unknown.length) throw new Error(`afterPublish: ${hook.url} names ${unknown.join(", ")}, which no collection is called.`)
1095
+ }
1096
+
956
1097
  export function defineConfig(config: TelaConfig): TelaConfig {
957
1098
  // A type nothing knows how to store would otherwise pass every check
958
1099
  // silently - the field simply never gets shape-checked, and nobody finds out
@@ -963,11 +1104,18 @@ export function defineConfig(config: TelaConfig): TelaConfig {
963
1104
 
964
1105
  const declaredCollections = config.collections.map((one) => withSeo(one, config.siteName))
965
1106
 
1107
+ const dataNames = new Set(config.collections.filter((one) => one.data).map((one) => one.name))
1108
+
966
1109
  for (const collection of declaredCollections) {
967
- checkFields(collection.fields, collection.name, known)
1110
+ checkCollectionName(collection.name)
1111
+ checkFields(collection.fields, collection.name, known, dataNames)
968
1112
  checkWorkflow(collection)
1113
+ if (collection.data) checkDataSource(collection)
1114
+ else if (collection.version !== undefined) throw new Error(`${collection.name}: only a data source has a \`version\`.`)
969
1115
  }
970
1116
 
1117
+ for (const hook of config.afterPublish ?? []) checkHook(hook, known)
1118
+
971
1119
  const declared = declaredCollections.find((c) => c.name === "users")
972
1120
 
973
1121
  // Names sit straight after the address: who somebody is comes before what
@@ -1051,6 +1199,9 @@ export function defineConfig(config: TelaConfig): TelaConfig {
1051
1199
  ...(config.overrides ? { overrides: config.overrides } : {}),
1052
1200
  ...(config.components ? { components: config.components } : {}),
1053
1201
  ...(config.site ? { site: config.site } : {}),
1202
+ ...(config.siteAliases?.length ? { siteAliases: config.siteAliases } : {}),
1203
+ ...(config.dataAddress ? { dataAddress: config.dataAddress } : {}),
1204
+ ...(config.afterPublish?.length ? { afterPublish: config.afterPublish } : {}),
1054
1205
  ...(config.siteName ? { siteName: config.siteName } : {}),
1055
1206
  ...(config.userNames ? { userNames: true } : {}),
1056
1207
  }
@@ -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)
@@ -5,6 +5,8 @@ import { sql } from "../db/client.ts"
5
5
  import { findCollection } from "./collections.ts"
6
6
  import { DIALECT } from "./richtext.ts"
7
7
  import { withDerived } from "./derive-values.ts"
8
+ import type { Collection } from "../config/types.ts"
9
+ import { dataShape, shapePath, shapeProblem, type DataShape } from "./shape.ts"
8
10
  import {
9
11
  collectReferences,
10
12
  findReferrers,
@@ -75,15 +77,31 @@ export function dialectDocument() {
75
77
  }
76
78
 
77
79
  export function entryPath(collection: string, slug: string) {
80
+ if (isDataSource(collection)) return join("content", "data", `${collection}.json`)
78
81
  return join("content", collection, `${slug}.json`)
79
82
  }
80
83
 
84
+ const isDataSource = (collection: string) => findCollection(collection)?.data === true
85
+
86
+ /**
87
+ * What goes in an entry's file: references as slugs, derived values beside
88
+ * their parts. A data source's slug is only how Tela finds its one record, so
89
+ * it stays out of the file.
90
+ */
91
+ function fileData(collection: Collection, data: Record<string, unknown>, slugs: Map<string, unknown>) {
92
+ const out = withDerived(collection, withSlugs(collection, data, slugs))
93
+ if (!collection.data) return out
94
+ const { slug: _slug, ...rest } = out
95
+ return rest
96
+ }
97
+
81
98
  export function indexPath(collection: string) {
82
99
  return join("content", collection, "index.json")
83
100
  }
84
101
 
85
102
  /** `cms:post:hello-world` — the key a page uses for its own entry. */
86
103
  export function entryCell(collection: string, slug: string) {
104
+ if (isDataSource(collection)) return `cms:data:${collection}`
87
105
  return `cms:${collection}:${slug}`
88
106
  }
89
107
 
@@ -174,10 +192,23 @@ export async function exportRelease(
174
192
  }
175
193
  }
176
194
 
177
- const slugs = new Map<string, unknown>([
178
- ...(await publishedReferences([...wanted].filter((id) => !staged.has(id)))),
179
- ...staged,
180
- ])
195
+ const elsewhere = [...wanted].filter((id) => !staged.has(id))
196
+ const slugs = new Map<string, unknown>([...(await publishedReferences(elsewhere, { pictures: "named" })), ...staged])
197
+ // A data source stands alone for other apps, so its pictures are copied in.
198
+ const sourced = [...published, ...alsoWrite].some((row) => findCollection(row.collection)?.data)
199
+ const copied = sourced ? new Map<string, unknown>([...(await publishedReferences(elsewhere)), ...staged]) : slugs
200
+ const referencesFor = (collection: Collection) => (collection.data ? copied : slugs)
201
+
202
+ // Before anything is written, so a refused shape leaves the repo untouched.
203
+ const shapes = new Map<string, DataShape>()
204
+ for (const row of [...published, ...alsoWrite]) {
205
+ const collection = findCollection(row.collection)
206
+ if (!collection?.data || shapes.has(collection.name)) continue
207
+ const next = dataShape(collection)
208
+ const problem = shapeProblem(await read(options.root, shapePath(collection.name)), next)
209
+ if (problem) throw problem
210
+ shapes.set(collection.name, next)
211
+ }
181
212
 
182
213
  // A slug is a file name, so moving one leaves the old file behind. Removed
183
214
  // before anything is written, so a release that renames A to B and B to
@@ -210,16 +241,31 @@ export async function exportRelease(
210
241
  await write(
211
242
  options.root,
212
243
  path,
213
- collection
214
- ? withDerived(collection, withSlugs(collection, row.data, slugs))
215
- : row.data,
244
+ collection ? fileData(collection, row.data, referencesFor(collection)) : row.data,
216
245
  )
217
246
 
218
247
  files.push(path)
219
248
  cells.push(entryCell(row.collection, slug))
220
- touched.add(row.collection)
249
+ if (!collection?.data) touched.add(row.collection)
221
250
  }
222
251
 
252
+ for (const [name, shape] of shapes) {
253
+ const path = shapePath(name)
254
+ if (JSON.stringify(await read(options.root, path)) === JSON.stringify(shape)) continue
255
+ await write(options.root, path, shape)
256
+ files.push(path)
257
+ }
258
+
259
+ const pictures = await writePictures(
260
+ [...published, ...alsoWrite].flatMap((row) => {
261
+ const collection = findCollection(row.collection)
262
+ return collection && !collection.data ? collectReferences(collection, row.data ?? {}).flatMap((one) => one.ids) : []
263
+ }),
264
+ options.root,
265
+ )
266
+ files.push(...pictures.files)
267
+ cells.push(...pictures.cells)
268
+
223
269
  for (const collection of touched) {
224
270
  const path = indexPath(collection)
225
271
  const rows = await publishedRows(collection, releaseId)
@@ -284,6 +330,8 @@ export async function exportRemoval(
284
330
  const files = [path]
285
331
  const cells = [entryCell(collection, slug)]
286
332
 
333
+ if (isDataSource(collection)) return { files, cells }
334
+
287
335
  // The index always changes: the entry has left it.
288
336
  const indexFile = indexPath(collection)
289
337
  const rows = await publishedRows(collection)
@@ -341,10 +389,10 @@ async function rewriteWithout(
341
389
  if (!collection || !slug) continue
342
390
 
343
391
  const wanted = collectReferences(collection, row.data).flatMap((one) => one.ids)
344
- const slugs = await publishedReferences(wanted)
392
+ const slugs = await publishedReferences(wanted, { pictures: collection.data ? "copied" : "named" })
345
393
 
346
394
  const path = entryPath(row.collection, slug)
347
- await write(root, path, withDerived(collection, withSlugs(collection, row.data, slugs)))
395
+ await write(root, path, fileData(collection, row.data, slugs))
348
396
 
349
397
  files.push(path)
350
398
  cells.push(entryCell(row.collection, slug))
@@ -467,14 +515,12 @@ async function writeMissing(
467
515
  const wanted = definition
468
516
  ? collectReferences(definition, row.data).flatMap((one) => one.ids)
469
517
  : []
470
- const slugs = await publishedReferences(wanted)
518
+ const slugs = await publishedReferences(wanted, { pictures: definition?.data ? "copied" : "named" })
471
519
 
472
520
  await write(
473
521
  root,
474
522
  path,
475
- definition
476
- ? withDerived(definition, withSlugs(definition, row.data, slugs))
477
- : row.data,
523
+ definition ? fileData(definition, row.data, slugs) : row.data,
478
524
  )
479
525
 
480
526
  files.push(path)
@@ -506,3 +552,116 @@ async function read(root: string, path: string) {
506
552
  return null
507
553
  }
508
554
  }
555
+
556
+ /** Where a picture a page names is published: `content/media/<id>.json`. */
557
+ export const picturePath = (id: string) => join("content", "media", `${id}.json`)
558
+
559
+ /** `cms:media:<id>` - the key a page's picture is read under. */
560
+ export const pictureCell = (id: string) => `cms:media:${id}`
561
+
562
+ /**
563
+ * The pictures some entries name, each written to its own file when what it
564
+ * says has changed. Ids that aren't pictures are passed over, and a picture
565
+ * the library no longer has is left unwritten, like the reference to it.
566
+ */
567
+ async function writePictures(ids: string[], root: string): Promise<ExportResult> {
568
+ const files: string[] = []
569
+ const cells: string[] = []
570
+ const unique = [...new Set(ids)]
571
+ if (!unique.length) return { files, cells }
572
+
573
+ const media = await sql`
574
+ select id from entries
575
+ where collection = 'media' and deleted_at is null
576
+ and id = any(string_to_array(${unique.join(",")}, ',')::uuid[])
577
+ `
578
+ const pictureIds = media.map((row: any) => String(row.id))
579
+ if (!pictureIds.length) return { files, cells }
580
+
581
+ const resolved = await publishedReferences(pictureIds)
582
+ for (const id of pictureIds) {
583
+ const picture = resolved.get(id)
584
+ if (picture === undefined) continue
585
+ const path = picturePath(id)
586
+ if (JSON.stringify(await read(root, path)) === JSON.stringify(picture)) continue
587
+ await write(root, path, picture)
588
+ files.push(path)
589
+ cells.push(pictureCell(id))
590
+ }
591
+ return { files, cells }
592
+ }
593
+
594
+ /**
595
+ * Pictures whose words or file changed (a credit corrected in the library, a
596
+ * new alt text), published again: each one's own file, and every data source
597
+ * using it, since those carry their pictures. Pages name a picture rather than
598
+ * copy it, so its file is all they need; a picture the library has dropped
599
+ * loses its file, and the pages naming it rebuild without it.
600
+ */
601
+ export async function republishPictures(ids: string[], options: { root: string }): Promise<ExportResult> {
602
+ const files: string[] = []
603
+ const cells: string[] = []
604
+ const resolved = await publishedReferences(ids)
605
+
606
+ for (const id of new Set(ids)) {
607
+ const path = picturePath(id)
608
+ const was = await read(options.root, path)
609
+ const now = resolved.get(id)
610
+ if (now === undefined) {
611
+ if (was === null) continue
612
+ await rm(join(options.root, path), { force: true })
613
+ } else {
614
+ if (JSON.stringify(was) === JSON.stringify(now)) continue
615
+ await write(options.root, path, now)
616
+ }
617
+ files.push(path)
618
+ cells.push(pictureCell(id))
619
+ }
620
+
621
+ const sources: { id: string }[] = []
622
+ for (const id of new Set(ids)) {
623
+ for (const one of await findReferrers(id)) {
624
+ if (findCollection(one.collection)?.data) sources.push({ id: one.id })
625
+ }
626
+ }
627
+ if (sources.length) {
628
+ const live = await sql`
629
+ select e.id from entries e
630
+ where e.published_version_id is not null
631
+ and e.id = any(string_to_array(${sources.map((one) => one.id).join(",")}, ',')::uuid[])
632
+ `
633
+ const rewritten = await rewriteWithout(live.map((row: any) => ({ id: String(row.id) })), options.root)
634
+ for (const [i, path] of rewritten.files.entries()) {
635
+ // Written again either way; only a change is worth a rebuild.
636
+ files.push(path)
637
+ cells.push(rewritten.cells[i]!)
638
+ }
639
+ }
640
+
641
+ return { files, cells }
642
+ }
643
+
644
+ /**
645
+ * Published entries written again from their published versions, under the
646
+ * rules publishing follows now, with the pictures they name: for when how
647
+ * content is written changes (pictures named rather than copied, say). Drafts
648
+ * stay drafts; nothing that isn't live is published.
649
+ */
650
+ export async function republishEntries(options: { root: string; collections?: string[] }): Promise<ExportResult> {
651
+ const live = await sql`
652
+ select e.id, e.collection, v.data
653
+ from entries e
654
+ join entry_versions v on v.id = e.published_version_id
655
+ where e.deleted_at is null
656
+ `
657
+ const rows = live.filter((row: any) => !options.collections || options.collections.includes(String(row.collection)))
658
+ const rewritten = await rewriteWithout(rows.map((row: any) => ({ id: String(row.id) })), options.root)
659
+ const pictures = await writePictures(
660
+ rows.flatMap((row: any) => {
661
+ const collection = findCollection(String(row.collection))
662
+ return collection && !collection.data ? collectReferences(collection, row.data ?? {}).flatMap((one) => one.ids) : []
663
+ }),
664
+ options.root,
665
+ )
666
+ return { files: [...rewritten.files, ...pictures.files], cells: [...rewritten.cells, ...pictures.cells] }
667
+ }
@@ -139,7 +139,7 @@ export function commitMessage(
139
139
  label: string | null,
140
140
  exported: ExportResult,
141
141
  ): string {
142
- const entries = exported.files.filter((file) => !file.endsWith("index.json"))
142
+ const entries = exported.files.filter((file) => !file.endsWith("index.json") && !file.endsWith(".schema.json"))
143
143
  const subject = label
144
144
  ? `Publish ${label}`
145
145
  : entries.length === 1