@nickpaustian/tela 0.1.2 → 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.
Files changed (43) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +1 -1
  3. package/bin/tela.ts +18 -2
  4. package/lib/index.js +172 -7
  5. package/package.json +5 -2
  6. package/scripts/check-components.ts +20 -0
  7. package/scripts/media-sync.ts +41 -0
  8. package/scripts/republish.ts +24 -0
  9. package/src/api.ts +3 -3
  10. package/src/components/EntryEditor.lsp +174 -11
  11. package/src/components/EntryList.lsp +8 -0
  12. package/src/components/Field.lsp +92 -2
  13. package/src/components/LinkField.lsp +477 -0
  14. package/src/components/MarkdownField.lsp +19 -24
  15. package/src/components/PersonField.lsp +255 -0
  16. package/src/components/ReferenceField.lsp +22 -1
  17. package/src/components/RepeaterField.lsp +141 -13
  18. package/src/components/ToggleField.lsp +63 -0
  19. package/src/config/fields.ts +134 -1
  20. package/src/config/seo.ts +4 -2
  21. package/src/config/types.ts +158 -7
  22. package/src/content/derive-values.ts +14 -3
  23. package/src/content/entries.ts +1 -1
  24. package/src/content/entry.ts +15 -1
  25. package/src/content/export.ts +173 -14
  26. package/src/content/git.ts +1 -1
  27. package/src/content/hooks.ts +75 -0
  28. package/src/content/link-address.ts +168 -0
  29. package/src/content/links.ts +13 -0
  30. package/src/content/person.ts +11 -0
  31. package/src/content/placement.ts +48 -0
  32. package/src/content/references.ts +48 -4
  33. package/src/content/rules.ts +24 -4
  34. package/src/content/shape.ts +192 -0
  35. package/src/content/store.ts +17 -0
  36. package/src/content/url.ts +15 -1
  37. package/src/content/users.ts +32 -0
  38. package/src/content/validate.ts +12 -2
  39. package/src/index.ts +4 -1
  40. package/src/keys.ts +47 -0
  41. package/src/media/index.ts +5 -0
  42. package/src/server/index.ts +168 -34
  43. package/src/server/library-routes.ts +11 -3
@@ -9,10 +9,14 @@ import {
9
9
  draftReleaseFor,
10
10
  discardDraft,
11
11
  } from "../content/releases.ts"
12
+ import { ShapeBreaks } from "../content/shape.ts"
13
+ import { republishPictures } from "../content/export.ts"
14
+ import { noticeOf, notifyHooks } from "../content/hooks.ts"
12
15
  import {
13
16
  exportRelease,
14
17
  exportRemoval,
15
18
  entryCell,
19
+ entryPath,
16
20
  indexCell,
17
21
  } from "../content/export.ts"
18
22
  import { commitContent, commitMessage } from "../content/git.ts"
@@ -30,9 +34,10 @@ import { config } from "../config/load.ts"
30
34
  import { DIST } from "../project.ts"
31
35
  import { navigationFor } from "../config/navigation.ts"
32
36
  import { iconFor } from "../config/icons.ts"
33
- import { entryUrl, linkSearch, siteRoot, urlRule, urlUses } from "../content/url.ts"
37
+ import { dataAddressOf, entryUrl, linkSearch, siteRoot, urlRule, urlUses } from "../content/url.ts"
34
38
  import { libraryRoutes, writeGroupsOf } from "./library-routes.ts"
35
39
  import { linkTo, parseLink } from "../content/links.ts"
40
+ import { hostsOf } from "../content/link-address.ts"
36
41
  import { previewAssetPaths } from "../content/preview.ts"
37
42
  import { governingChanges } from "../content/governing.ts"
38
43
  import { personName } from "../content/person.ts"
@@ -53,13 +58,14 @@ import { accessCondition, explainScope, mayOn } from "../content/access.ts"
53
58
  import { verifyCredentials } from "../auth/login.ts"
54
59
  import { createFirstAdmin, needsSetup, MIN_PASSWORD_LENGTH } from "../auth/setup.ts"
55
60
  import { findCollection } from "../content/collections.ts"
56
- import { createAndStage, storeFor, isPublishable } from "../content/store.ts"
61
+ import { DataSourceExists, createAndStage, storeFor, isPublishable } from "../content/store.ts"
57
62
  import { withDerived } from "../content/derive-values.ts"
58
63
  import { withoutSecrets } from "../config/components.ts"
59
- import { countUsers } from "../content/users.ts"
64
+ import { countUsers, peopleNamed } from "../content/users.ts"
60
65
  import { blocking, checkEverything, checkServerRules } from "../content/validate.ts"
61
66
  import {
62
67
  getEntry,
68
+ isEntryId,
63
69
  isPublished,
64
70
  purgeEntry,
65
71
  } from "../content/entries.ts"
@@ -284,6 +290,55 @@ const authed =
284
290
  * Returns a Response on failure so handlers can return it directly - a route
285
291
  * that forgets to check gets a type error rather than an unguarded query.
286
292
  */
293
+ /** What the editor sends to see its draft: the values on screen, and a saved draft to fall back on. */
294
+ interface PreviewBody {
295
+ entryId?: string
296
+ data?: Record<string, unknown>
297
+ exact?: boolean
298
+ /** For a data source: which page that shows it to draw. */
299
+ page?: string
300
+ }
301
+
302
+ /**
303
+ * The draft as publishing would write it.
304
+ *
305
+ * Sent values win; anything absent falls back to the saved draft, so a preview
306
+ * opened before any edit still shows something. A comparison asks for a
307
+ * version exactly as it was, with nothing borrowed from the draft. Derived
308
+ * and with references as slugs, the same way a publish writes them, or a
309
+ * preview would be missing what the live page has - the one drift a preview
310
+ * exists to prevent.
311
+ */
312
+ /** The media records holding a stored file: usually one, since adopting finds before it creates. */
313
+ async function mediaIdsFor(key: string): Promise<string[]> {
314
+ const rows = await sql`select id from entries where collection = 'media' and data ->> 'file' = ${key} and deleted_at is null`
315
+ return rows.map((row: any) => String(row.id))
316
+ }
317
+
318
+ /**
319
+ * Pictures whose words or file changed, published again where they already
320
+ * are: their own files, and the data sources carrying them. Committed like a
321
+ * publish, so the site rebuilds the pages showing them. A picture no page has
322
+ * published writes nothing.
323
+ */
324
+ async function picturesChanged(ids: string[], user: SessionUser) {
325
+ if (!CONTENT_REPO || !ids.length) return
326
+ const exported = await republishPictures(ids, { root: CONTENT_REPO })
327
+ if (!exported.files.length) return
328
+ const commit = await commitContent(exported, {
329
+ root: CONTENT_REPO,
330
+ message: `Update ${exported.cells.filter((cell) => cell.startsWith("cms:media:")).length || "a"} picture(s)\n\nRebuild: ${exported.cells.join(" ")}\n`,
331
+ push: process.env.TELA_PUSH !== "false",
332
+ author: authorOf(user),
333
+ })
334
+ void notifyHooks(config.afterPublish, noticeOf("published", commit))
335
+ }
336
+
337
+ async function asPublished(collection: Collection, body: PreviewBody | null) {
338
+ const saved = body?.entryId && !body.exact ? await draftData(body.entryId) : {}
339
+ return withDerived(collection, await withResolvedReferences(collection, { ...saved, ...(body?.data ?? {}) }))
340
+ }
341
+
287
342
  function resolveCollection(name: string) {
288
343
  const collection = findCollection(name)
289
344
 
@@ -637,7 +692,13 @@ const server = Bun.serve({
637
692
  const escalatingCreate = refuseEscalation(user, found.collection, "", body)
638
693
  if (escalatingCreate) return escalatingCreate
639
694
 
640
- const created = await createAndStage(found.collection, body)
695
+ let created
696
+ try {
697
+ created = await createAndStage(found.collection, body)
698
+ } catch (error) {
699
+ if (error instanceof DataSourceExists) return json({ error: error.message, id: error.id }, 409)
700
+ throw error
701
+ }
641
702
  if (isPublishable(found.collection)) await recordSave(created.id, created.data, user.id)
642
703
  return json({ entry: withoutSecrets(found.collection, created) }, 201)
643
704
  }),
@@ -740,6 +801,8 @@ const server = Bun.serve({
740
801
  if (!isPublishable(found.collection)) {
741
802
  const saved = await store.update(found.collection, req.params.id, body)
742
803
  if (!saved) return json({ error: "Not found" }, 404)
804
+ // A picture's own words, where the store keeps none: what publishes it follows.
805
+ if (found.collection.uploads) await picturesChanged([req.params.id], user)
743
806
  return json({ entry: withoutSecrets(found.collection, saved), draft: false })
744
807
  }
745
808
 
@@ -858,12 +921,13 @@ const server = Bun.serve({
858
921
  root: CONTENT_REPO,
859
922
  })
860
923
 
861
- await commitContent(exported, {
924
+ const removed = await commitContent(exported, {
862
925
  root: CONTENT_REPO,
863
926
  message: `Remove ${found.collection.name}/${slug}`,
864
927
  push: process.env.TELA_PUSH !== "false",
865
928
  author: authorOf(user),
866
929
  })
930
+ void notifyHooks(config.afterPublish, noticeOf("removed", removed))
867
931
  }
868
932
 
869
933
  const gone = await storeFor(found.collection).remove(
@@ -1020,6 +1084,7 @@ const server = Bun.serve({
1020
1084
  push: process.env.TELA_PUSH !== "false",
1021
1085
  author: authorOf(user),
1022
1086
  })
1087
+ void notifyHooks(config.afterPublish, noticeOf("unpublished", commit))
1023
1088
 
1024
1089
  // Stage what it holds, so there is something to publish again.
1025
1090
  //
@@ -1187,6 +1252,27 @@ const server = Bun.serve({
1187
1252
  * Unpublished ones are included and say so, since a link written now may
1188
1253
  * go live with them.
1189
1254
  */
1255
+ /**
1256
+ * People to name on an entry: ids and names only, for anyone signed in.
1257
+ *
1258
+ * The person field asks this rather than `/api/entries/users`, which an
1259
+ * editor may not read - accounts are how permissions are held - and which
1260
+ * would hand over addresses and roles to offer a byline.
1261
+ */
1262
+ "/api/people": {
1263
+ GET: authed(async (req: { params?: unknown } & Request) => {
1264
+ const params = new URL(req.url).searchParams
1265
+ const ids = (params.get("ids") ?? "").split(",").filter((one) => isEntryId(one))
1266
+ return json({
1267
+ people: await peopleNamed({
1268
+ search: params.get("q") ?? "",
1269
+ ids,
1270
+ limit: Number(params.get("limit") ?? 20) || 20,
1271
+ }),
1272
+ })
1273
+ }),
1274
+ },
1275
+
1190
1276
  "/api/links": {
1191
1277
  GET: authed(async (req: { params?: unknown } & Request, user) => {
1192
1278
  const params = new URL(req.url).searchParams
@@ -1196,7 +1282,10 @@ const server = Bun.serve({
1196
1282
  const asked = parseLink(params.get("ref") ?? "")
1197
1283
  // The entry being edited, which a link from itself would only reload.
1198
1284
  const self = params.get("not") ?? ""
1285
+ // Only these collections, for a link field that takes only some.
1286
+ const only = (params.get("in") ?? "").split(",").filter(Boolean)
1199
1287
  const site = siteRoot(config, process.env)
1288
+ if (params.has("hosts")) return json({ links: [], hosts: hostsOf([site, config.site, ...(config.siteAliases ?? [])]) })
1200
1289
  const found: {
1201
1290
  collection: string
1202
1291
  collectionLabel: string
@@ -1210,6 +1299,7 @@ const server = Bun.serve({
1210
1299
  for (const collection of config.collections) {
1211
1300
  if (!urlRule(collection) || !isPublishable(collection) || !can(user, "read", collection.name)) continue
1212
1301
  if (asked && asked.collection !== collection.name) continue
1302
+ if (only.length && !only.includes(collection.name)) continue
1213
1303
 
1214
1304
  const { entries } = await storeFor(collection).list(collection, {
1215
1305
  limit: 8,
@@ -1243,7 +1333,9 @@ const server = Bun.serve({
1243
1333
  }
1244
1334
  }
1245
1335
 
1246
- return json({ links: found.slice(0, 12) })
1336
+ // The hosts this site's own addresses are written with, so a pasted
1337
+ // one can be read as the page it names.
1338
+ return json({ links: found.slice(0, 12), hosts: hostsOf([site, config.site, ...(config.siteAliases ?? [])]) })
1247
1339
  }),
1248
1340
  },
1249
1341
 
@@ -1322,6 +1414,27 @@ const server = Bun.serve({
1322
1414
  * are sitting in the editor - so making the id optional is the whole
1323
1415
  * difference between previewing a new entry and being told to save first.
1324
1416
  */
1417
+ /**
1418
+ * A data source as it would be published from what is on screen: the
1419
+ * file's contents, where in the content repo it goes, and where it can be
1420
+ * read if the project serves it somewhere.
1421
+ */
1422
+ "/api/collections/:collection/published": {
1423
+ POST: authed(async (req: { params: { collection: string } } & Request, user) => {
1424
+ const found = resolveCollection(req.params.collection)
1425
+ if (found.error) return found.error
1426
+ if (!can(user, "read", found.collection.name)) return refuse("read", found.collection.name)
1427
+ if (!found.collection.data) return json({ error: `"${found.collection.name}" is not a data source.` }, 409)
1428
+
1429
+ const { slug: _slug, ...record } = await asPublished(found.collection, (await readBody(req)) as PreviewBody | null)
1430
+ return json({
1431
+ data: record,
1432
+ file: entryPath(found.collection.name, found.collection.name),
1433
+ address: dataAddressOf(config, found.collection.name, process.env),
1434
+ })
1435
+ }),
1436
+ },
1437
+
1325
1438
  "/api/collections/:collection/preview": {
1326
1439
  POST: authed(async (req: { params: { collection: string } } & Request, user) => {
1327
1440
  if (!AGENT_URL) {
@@ -1338,33 +1451,39 @@ const server = Bun.serve({
1338
1451
  return refuse("read", found.collection.name)
1339
1452
  }
1340
1453
 
1341
- const body = (await readBody(req)) as {
1342
- entryId?: string
1343
- data?: Record<string, unknown>
1344
- exact?: boolean
1345
- } | null
1346
-
1347
- // Only to find something to fall back on. A new entry has neither, and
1348
- // that is fine - everything needed is in `data`. A comparison asks for
1349
- // a version exactly as it was, with nothing borrowed from the draft.
1350
- const saved = body?.entryId && !body.exact ? await draftData(body.entryId) : {}
1454
+ const body = (await readBody(req)) as PreviewBody | null
1455
+ const data = await asPublished(found.collection, body)
1456
+
1457
+ // A data source is drawn on a page that shows it, chosen by path; the
1458
+ // site says which pages those are.
1459
+ if (found.collection.data) {
1460
+ const { slug: _slug, ...record } = data
1461
+ const response = await fetch(`${AGENT_URL}/preview`, {
1462
+ method: "POST",
1463
+ headers: { "content-type": "application/json", "x-lightspeed-secret": AGENT_SECRET },
1464
+ body: JSON.stringify({
1465
+ entryCell: entryCell(found.collection.name, found.collection.name),
1466
+ indexCell: indexCell(found.collection.name),
1467
+ slug: found.collection.name,
1468
+ data: record,
1469
+ page: typeof body?.page === "string" ? body.page : undefined,
1470
+ }),
1471
+ }).catch(() => null)
1472
+ if (!response) return json({ error: "The build agent is not reachable." }, 502)
1473
+ const pages = response.headers.get("x-preview-pages") ?? "[]"
1474
+ if (!response.ok) {
1475
+ return new Response(await response.text(), { status: response.status, headers: { "x-preview-pages": pages } })
1476
+ }
1477
+ return new Response(previewAssetPaths(await response.text()), {
1478
+ headers: {
1479
+ "content-type": "text/html; charset=utf-8",
1480
+ "cache-control": "no-store",
1481
+ "x-preview-pages": pages,
1482
+ "x-preview-page": response.headers.get("x-lightspeed-path") ?? "",
1483
+ },
1484
+ })
1485
+ }
1351
1486
 
1352
- // Sent values win; anything absent falls back to the saved draft, so a
1353
- // preview opened before any edit still shows something.
1354
- //
1355
- // Derived the same way a publish derives, or a preview would be
1356
- // missing every `name.full` the live page has - the one drift a
1357
- // preview exists to prevent.
1358
- // References resolved to slugs as well, for the same reason: the site
1359
- // reads a slug, and a preview handing it an id shows a page with its
1360
- // venue and its artists missing.
1361
- const data = withDerived(
1362
- found.collection,
1363
- await withResolvedReferences(found.collection, {
1364
- ...saved,
1365
- ...(body?.data ?? {}),
1366
- }),
1367
- )
1368
1487
  const slug = String(data.slug ?? "")
1369
1488
  if (!slug) {
1370
1489
  // The one thing a preview genuinely cannot do without: the slug is
@@ -1474,12 +1593,14 @@ const server = Bun.serve({
1474
1593
  author: authorOf(user),
1475
1594
  })
1476
1595
  await publishRelease(releaseId, { force: true, by: user.id })
1596
+ void notifyHooks(config.afterPublish, noticeOf("published", commit))
1477
1597
 
1478
1598
  return json({ published: true, commit: commit.sha, rebuild: commit.cells })
1479
1599
  } catch (error) {
1480
1600
  if (error instanceof ReleaseConflict) {
1481
1601
  return json({ error: error.message, conflicts: error.conflicts }, 409)
1482
1602
  }
1603
+ if (error instanceof ShapeBreaks) return json({ error: error.message, breaks: error.problems }, 409)
1483
1604
  throw error
1484
1605
  }
1485
1606
  }),
@@ -1516,7 +1637,11 @@ const server = Bun.serve({
1516
1637
  }
1517
1638
  }
1518
1639
 
1519
- const exported = await exportRelease(req.params.id, { root: CONTENT_REPO })
1640
+ const exported = await exportRelease(req.params.id, { root: CONTENT_REPO }).catch((error) => {
1641
+ if (error instanceof ShapeBreaks) return error
1642
+ throw error
1643
+ })
1644
+ if (exported instanceof ShapeBreaks) return json({ error: exported.message, breaks: exported.problems }, 409)
1520
1645
  const [release] = await sql`select label from releases where id = ${req.params.id}`
1521
1646
 
1522
1647
  // Export and commit before the database advances. If either fails, the
@@ -1532,6 +1657,7 @@ const server = Bun.serve({
1532
1657
 
1533
1658
  // Cheapest, most reliable step, done last.
1534
1659
  await publishRelease(req.params.id, { force: true, by: user.id })
1660
+ void notifyHooks(config.afterPublish, noticeOf("published", commit))
1535
1661
 
1536
1662
  return json({
1537
1663
  published: true,
@@ -1692,7 +1818,15 @@ const server = Bun.serve({
1692
1818
  authed,
1693
1819
  can,
1694
1820
  json,
1695
- fallback: { list: plainList as never, describe: plainDescribe as never },
1821
+ changed: async (key, user) => picturesChanged(await mediaIdsFor(key), user),
1822
+ fallback: {
1823
+ list: plainList as never,
1824
+ describe: (async (req: { params: { key: string } } & Request, user: SessionUser) => {
1825
+ const answer = await plainDescribe(req as never, user)
1826
+ if (answer.ok) await picturesChanged(await mediaIdsFor(req.params.key), user)
1827
+ return answer
1828
+ }) as never,
1829
+ },
1696
1830
  }),
1697
1831
 
1698
1832
  /**
@@ -199,6 +199,8 @@ export function libraryRoutes(deps: {
199
199
  ) => (req: T) => Promise<Response>
200
200
  can: Can
201
201
  json: Json
202
+ /** After a picture's words, or whether it exists, changed: so what publishes it can be brought up to date. */
203
+ changed?: (key: string, user: SessionUser) => Promise<void>
202
204
  /** Tela's own browse and describe, for a store that is not a library. */
203
205
  fallback: {
204
206
  list: (req: Req, user: SessionUser) => Promise<Response>
@@ -360,12 +362,16 @@ export function libraryRoutes(deps: {
360
362
  PATCH: either(async (req, user, library) => {
361
363
  const found = await asset(user, library, req.params.key)
362
364
  await changeable(user, library, found)
363
- return json(await upstream(library.client.describe(found.pid, patchOf(await body(req), { defaults: true }))))
365
+ const described = await upstream(library.client.describe(found.pid, patchOf(await body(req), { defaults: true })))
366
+ await deps.changed?.(req.params.key, user)
367
+ return json(described)
364
368
  }, deps.fallback.describe),
365
369
  DELETE: route(async (req, user, library) => {
366
370
  const found = await asset(user, library, req.params.key)
367
371
  await changeable(user, library, found, "delete")
368
- return json(await upstream(library.client.remove(found.pid, reasonOf(await body(req)))))
372
+ const removed = await upstream(library.client.remove(found.pid, reasonOf(await body(req))))
373
+ await deps.changed?.(req.params.key, user)
374
+ return json(removed)
369
375
  }),
370
376
  },
371
377
 
@@ -373,7 +379,9 @@ export function libraryRoutes(deps: {
373
379
  POST: route(async (req, user, library) => {
374
380
  const found = await asset(user, library, req.params.key)
375
381
  await changeable(user, library, found, "delete")
376
- return json(await upstream(library.client.restore(found.pid)))
382
+ const restored = await upstream(library.client.restore(found.pid))
383
+ await deps.changed?.(req.params.key, user)
384
+ return json(restored)
377
385
  }),
378
386
  },
379
387