@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.
- package/CHANGELOG.md +34 -0
- package/bin/tela.ts +8 -0
- package/lib/index.js +157 -7
- package/package.json +5 -2
- package/scripts/check-components.ts +20 -0
- package/scripts/media-sync.ts +41 -0
- package/scripts/republish.ts +24 -0
- package/src/api.ts +3 -3
- package/src/components/EntryEditor.lsp +174 -11
- package/src/components/EntryList.lsp +8 -0
- package/src/components/Field.lsp +92 -2
- package/src/components/LinkField.lsp +477 -0
- package/src/components/MarkdownField.lsp +19 -24
- package/src/components/ReferenceField.lsp +22 -1
- package/src/components/RepeaterField.lsp +141 -13
- package/src/components/ToggleField.lsp +63 -0
- package/src/config/fields.ts +104 -1
- package/src/config/seo.ts +4 -2
- package/src/config/types.ts +158 -7
- package/src/content/derive-values.ts +14 -3
- package/src/content/entry.ts +15 -1
- package/src/content/export.ts +173 -14
- package/src/content/git.ts +1 -1
- package/src/content/hooks.ts +75 -0
- package/src/content/link-address.ts +168 -0
- package/src/content/links.ts +13 -0
- package/src/content/placement.ts +48 -0
- package/src/content/references.ts +31 -4
- package/src/content/rules.ts +24 -4
- package/src/content/shape.ts +192 -0
- package/src/content/store.ts +17 -0
- package/src/content/url.ts +15 -1
- package/src/content/validate.ts +12 -2
- package/src/index.ts +4 -1
- package/src/keys.ts +47 -0
- package/src/media/index.ts +5 -0
- package/src/server/index.ts +145 -33
- package/src/server/library-routes.ts +11 -3
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { PublishHook } from "../config/types.ts"
|
|
2
|
+
import type { CommitResult } from "./git.ts"
|
|
3
|
+
|
|
4
|
+
export type PublishEvent = "published" | "unpublished" | "removed"
|
|
5
|
+
|
|
6
|
+
export interface PublishNotice {
|
|
7
|
+
event: PublishEvent
|
|
8
|
+
commit: string | null
|
|
9
|
+
files: string[]
|
|
10
|
+
cells: string[]
|
|
11
|
+
collections: string[]
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** `content/posts/a.json` is posts; `content/data/hours.json` is the hours data source. */
|
|
15
|
+
export function collectionsIn(files: string[]): string[] {
|
|
16
|
+
const names = files.flatMap((file) => {
|
|
17
|
+
const parts = file.split("/")
|
|
18
|
+
if (parts[0] !== "content" || parts.length < 3 || parts[1] === ".tela") return []
|
|
19
|
+
if (parts[1] === "data") return [parts[2]!.replace(/(\.schema)?\.json$/, "")]
|
|
20
|
+
return [parts[1]!]
|
|
21
|
+
})
|
|
22
|
+
return [...new Set(names)]
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function noticeOf(event: PublishEvent, commit: CommitResult): PublishNotice | null {
|
|
26
|
+
if (!commit.sha && !commit.pushed) return null
|
|
27
|
+
return { event, commit: commit.sha, files: commit.files, cells: commit.cells, collections: collectionsIn(commit.files) }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const wants = (hook: PublishHook, notice: PublishNotice) =>
|
|
31
|
+
!hook.collections?.length || notice.collections.some((name) => hook.collections!.includes(name))
|
|
32
|
+
|
|
33
|
+
async function call(hook: PublishHook, notice: PublishNotice, timeoutMs: number) {
|
|
34
|
+
const res = await fetch(hook.url, {
|
|
35
|
+
method: "POST",
|
|
36
|
+
headers: {
|
|
37
|
+
"content-type": "application/json",
|
|
38
|
+
...(hook.token ? { authorization: `Bearer ${hook.token}` } : {}),
|
|
39
|
+
},
|
|
40
|
+
body: JSON.stringify(notice),
|
|
41
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
42
|
+
})
|
|
43
|
+
if (!res.ok) throw new Error(`answered ${res.status}`)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Tell each hook what changed. Never throws: the content is already live, so a
|
|
48
|
+
* hook that is down is logged and tried once more, not a failed publish.
|
|
49
|
+
*/
|
|
50
|
+
export async function notifyHooks(
|
|
51
|
+
hooks: PublishHook[] | undefined,
|
|
52
|
+
notice: PublishNotice | null,
|
|
53
|
+
{ retryAfterMs = 2000, timeoutMs = 10_000 } = {},
|
|
54
|
+
): Promise<{ url: string; ok: boolean }[]> {
|
|
55
|
+
if (!notice || !hooks?.length) return []
|
|
56
|
+
return Promise.all(
|
|
57
|
+
hooks
|
|
58
|
+
.filter((hook) => wants(hook, notice))
|
|
59
|
+
.map(async (hook) => {
|
|
60
|
+
for (const attempt of [1, 2]) {
|
|
61
|
+
try {
|
|
62
|
+
await call(hook, notice, timeoutMs)
|
|
63
|
+
return { url: hook.url, ok: true }
|
|
64
|
+
} catch (error) {
|
|
65
|
+
if (attempt === 2) {
|
|
66
|
+
console.error(`[tela] publish hook ${hook.url} failed: ${(error as Error).message}`)
|
|
67
|
+
return { url: hook.url, ok: false }
|
|
68
|
+
}
|
|
69
|
+
await Bun.sleep(retryAfterMs)
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return { url: hook.url, ok: false }
|
|
73
|
+
}),
|
|
74
|
+
)
|
|
75
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What an editor typed into a link field, read the way they meant it.
|
|
3
|
+
*
|
|
4
|
+
* Words are a search for a page. Anything shaped like an address is tidied
|
|
5
|
+
* into one: an email gets `mailto:`, a phone number `tel:`, a bare
|
|
6
|
+
* `example.org` its `https://`, and an address on this site's own hosts
|
|
7
|
+
* becomes the path, so it keeps working wherever the site is served from.
|
|
8
|
+
*/
|
|
9
|
+
export type TypedLink =
|
|
10
|
+
| { kind: "empty" }
|
|
11
|
+
| { kind: "words"; words: string }
|
|
12
|
+
| { kind: "address"; href: string; label: string; own: boolean }
|
|
13
|
+
|
|
14
|
+
const EMAIL = /^[^\s@/:]+@[^\s@/]+\.[^\s@/]+$/
|
|
15
|
+
const PHONE = /^\+?[\d ()-]{8,}$/
|
|
16
|
+
const DOMAIN = /^[\w-]+(\.[\w-]+)*\.[a-z]{2,}(:\d+)?([/?#]\S*)?$/i
|
|
17
|
+
|
|
18
|
+
const bareHost = (host: string) => host.toLowerCase().replace(/^www\./, "")
|
|
19
|
+
|
|
20
|
+
/** The hosts an address on this site may be written with, from its root addresses. */
|
|
21
|
+
export function hostsOf(roots: (string | undefined | null)[]): string[] {
|
|
22
|
+
const hosts = new Set<string>()
|
|
23
|
+
for (const root of roots) {
|
|
24
|
+
if (!root) continue
|
|
25
|
+
try {
|
|
26
|
+
hosts.add(bareHost(new URL(root).host))
|
|
27
|
+
} catch {
|
|
28
|
+
// A root that is not an address names no host.
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return [...hosts]
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function fromUrl(text: string, hosts: string[]): TypedLink {
|
|
35
|
+
let url: URL
|
|
36
|
+
try {
|
|
37
|
+
url = new URL(text)
|
|
38
|
+
} catch {
|
|
39
|
+
return { kind: "words", words: text }
|
|
40
|
+
}
|
|
41
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") return { kind: "words", words: text }
|
|
42
|
+
if (hosts.includes(bareHost(url.host))) {
|
|
43
|
+
const path = url.pathname + url.search + url.hash
|
|
44
|
+
return { kind: "address", href: path, label: path, own: true }
|
|
45
|
+
}
|
|
46
|
+
return { kind: "address", href: url.href, label: url.host.replace(/^www\./, "") + (url.pathname === "/" ? "" : url.pathname), own: false }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function readTypedLink(typed: string | undefined | null, hosts: string[] = []): TypedLink {
|
|
50
|
+
const text = (typed ?? "").trim()
|
|
51
|
+
if (!text) return { kind: "empty" }
|
|
52
|
+
|
|
53
|
+
if (/^tela:/i.test(text)) return { kind: "address", href: text, label: text, own: true }
|
|
54
|
+
if (/^mailto:/i.test(text)) return { kind: "address", href: text, label: text.slice(7), own: false }
|
|
55
|
+
if (/^tel:/i.test(text)) return { kind: "address", href: text, label: text.slice(4), own: false }
|
|
56
|
+
if (EMAIL.test(text)) return { kind: "address", href: "mailto:" + text, label: text, own: false }
|
|
57
|
+
if (PHONE.test(text) && (text.match(/\d/g) ?? []).length >= 8) {
|
|
58
|
+
return { kind: "address", href: "tel:" + text.replace(/[^\d+]/g, ""), label: text, own: false }
|
|
59
|
+
}
|
|
60
|
+
if (text.startsWith("/") && !text.startsWith("//")) return { kind: "address", href: text, label: text, own: true }
|
|
61
|
+
if (text.startsWith("#")) return { kind: "address", href: text, label: text, own: true }
|
|
62
|
+
if (/^https?:\/\//i.test(text)) return fromUrl(text, hosts)
|
|
63
|
+
if (text.startsWith("//")) return fromUrl("https:" + text, hosts)
|
|
64
|
+
if (!/\s/.test(text) && DOMAIN.test(text)) return fromUrl("https://" + text, hosts)
|
|
65
|
+
|
|
66
|
+
return { kind: "words", words: text }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** A path to compare with an entry's address: no query, no fragment, no trailing slash. */
|
|
70
|
+
export function comparablePath(href: string): string {
|
|
71
|
+
const path = href.replace(/[?#].*$/, "").replace(/\/+$/, "")
|
|
72
|
+
return path || "/"
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The fragment of an address, kept when it is swapped for the page it names. */
|
|
76
|
+
export const fragmentOf = (href: string) => /#.*$/.exec(href)?.[0] ?? ""
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* What a link field may go to.
|
|
80
|
+
*
|
|
81
|
+
* `pages` is anything on this site: an entry picked from the list, or a path.
|
|
82
|
+
* `files` is the library's files; `web` another site's address; `sections` a
|
|
83
|
+
* part of the same page; `email` and `phone` writing to or calling someone.
|
|
84
|
+
*/
|
|
85
|
+
export const LINK_KINDS = ["pages", "files", "web", "sections", "email", "phone"] as const
|
|
86
|
+
export type LinkKind = (typeof LINK_KINDS)[number]
|
|
87
|
+
|
|
88
|
+
/** What a link field takes when it says nothing: everything but files. */
|
|
89
|
+
export const DEFAULT_LINK_KINDS: LinkKind[] = ["pages", "web", "sections", "email", "phone"]
|
|
90
|
+
|
|
91
|
+
export function acceptedKinds(accepts: readonly string[] | undefined): LinkKind[] {
|
|
92
|
+
const known = (accepts ?? DEFAULT_LINK_KINDS).filter((one): one is LinkKind => (LINK_KINDS as readonly string[]).includes(one))
|
|
93
|
+
return known.length ? known : DEFAULT_LINK_KINDS
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Which kind an address is. */
|
|
97
|
+
export function kindOfHref(href: string): LinkKind | null {
|
|
98
|
+
if (/^tela:media\//i.test(href)) return "files"
|
|
99
|
+
if (/^tela:/i.test(href) || (href.startsWith("/") && !href.startsWith("//"))) return "pages"
|
|
100
|
+
if (href.startsWith("#")) return "sections"
|
|
101
|
+
if (/^mailto:/i.test(href)) return "email"
|
|
102
|
+
if (/^tel:/i.test(href)) return "phone"
|
|
103
|
+
if (/^https?:\/\//i.test(href)) return "web"
|
|
104
|
+
return null
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
|
|
108
|
+
const escapeName = (name: string) => name.replace(/[^\w-]/g, "")
|
|
109
|
+
|
|
110
|
+
/** The pattern a stored link must match, for the kinds a field takes. */
|
|
111
|
+
export function linkPattern(kinds: LinkKind[], collections?: string[]): string {
|
|
112
|
+
const entries = collections?.length ? `(${collections.map(escapeName).join("|")})` : "(?!media/)[\\w-]+"
|
|
113
|
+
const parts: Record<LinkKind, string[]> = {
|
|
114
|
+
pages: [`tela:${entries}/${UUID}(#\\S*)?`, "/(?!/)\\S*"],
|
|
115
|
+
files: [`tela:media/${UUID}`],
|
|
116
|
+
web: ["https?://\\S+"],
|
|
117
|
+
sections: ["#\\S+"],
|
|
118
|
+
email: ["mailto:\\S+@\\S+"],
|
|
119
|
+
phone: ["tel:\\+?\\d+"],
|
|
120
|
+
}
|
|
121
|
+
return `^(${kinds.flatMap((kind) => parts[kind]).join("|")})$`
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const listed = (words: string[]) =>
|
|
125
|
+
words.length <= 1 ? (words[0] ?? "") : `${words.slice(0, -1).join(", ")} or ${words[words.length - 1]}`
|
|
126
|
+
|
|
127
|
+
/** What the box says before anything is typed. */
|
|
128
|
+
export function linkPlaceholder(kinds: LinkKind[]): string {
|
|
129
|
+
const search = [kinds.includes("pages") ? "pages" : "", kinds.includes("files") ? "files" : ""].filter(Boolean)
|
|
130
|
+
const paste = [
|
|
131
|
+
kinds.includes("web") ? "an address" : kinds.includes("pages") ? "a path" : "",
|
|
132
|
+
kinds.includes("email") ? "an email" : "",
|
|
133
|
+
kinds.includes("phone") ? "a phone number" : "",
|
|
134
|
+
].filter(Boolean)
|
|
135
|
+
const searching = search.length ? `Search ${search.join(" and ")}` : ""
|
|
136
|
+
const pasting = paste.length ? `paste ${listed(paste)}` : ""
|
|
137
|
+
const said = [searching, pasting].filter(Boolean).join(", or ")
|
|
138
|
+
return said.charAt(0).toUpperCase() + said.slice(1)
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** What to say when a link is not one the field takes. */
|
|
142
|
+
export function linkMessage(kinds: LinkKind[]): string {
|
|
143
|
+
const choose = [kinds.includes("pages") ? "a page" : "", kinds.includes("files") ? "a file" : ""].filter(Boolean)
|
|
144
|
+
const paste = [
|
|
145
|
+
kinds.includes("web") ? "a full address" : "",
|
|
146
|
+
kinds.includes("email") ? "an email" : "",
|
|
147
|
+
kinds.includes("phone") ? "a phone number" : "",
|
|
148
|
+
].filter(Boolean)
|
|
149
|
+
const said = [
|
|
150
|
+
choose.length ? `Choose ${choose.join(" or ")} from the list` : "",
|
|
151
|
+
paste.length ? `paste ${listed(paste)}` : "",
|
|
152
|
+
]
|
|
153
|
+
.filter(Boolean)
|
|
154
|
+
.join(", or ")
|
|
155
|
+
return said.charAt(0).toUpperCase() + said.slice(1) + "."
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const REFUSED: Record<LinkKind, string> = {
|
|
159
|
+
pages: "This link can't go to a page on this site.",
|
|
160
|
+
files: "This link can't go to a file.",
|
|
161
|
+
web: "This link can't go to another site.",
|
|
162
|
+
sections: "This link can't go to a part of the page.",
|
|
163
|
+
email: "This link can't be an email address.",
|
|
164
|
+
phone: "This link can't be a phone number.",
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Why an address of this kind is turned away. */
|
|
168
|
+
export const refusedKind = (kind: LinkKind) => REFUSED[kind]
|
package/src/content/links.ts
CHANGED
|
@@ -40,6 +40,19 @@ export function linkedEntries(markdown: string): EntryLink[] {
|
|
|
40
40
|
}))
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
+
/**
|
|
44
|
+
* What a link field publishes: an entry by its slug, a file by its address,
|
|
45
|
+
* anything else as written. Nothing, when what it named is not on the site.
|
|
46
|
+
*/
|
|
47
|
+
export function publishedLink(value: string, resolved: Map<string, unknown>): string | undefined {
|
|
48
|
+
const link = parseLink(value)
|
|
49
|
+
if (!link) return value
|
|
50
|
+
const target = resolved.get(link.id)
|
|
51
|
+
if (typeof target === "string" && target) return linkTo(link.collection, target, link.fragment)
|
|
52
|
+
const src = target && typeof target === "object" ? (target as { src?: unknown }).src : undefined
|
|
53
|
+
return typeof src === "string" && src ? src : undefined
|
|
54
|
+
}
|
|
55
|
+
|
|
43
56
|
/**
|
|
44
57
|
* The markdown with each id swapped for what it publishes as, and each link
|
|
45
58
|
* to something that publishes as nothing reduced to its words.
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { Block } from "../config/types.ts"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Which blocks the picker offers, and where.
|
|
5
|
+
*
|
|
6
|
+
* Most blocks are the shared library and go anywhere. A block made `for` some
|
|
7
|
+
* pages is offered on those alone, in a group of its own, so one-off sections
|
|
8
|
+
* never crowd the library. A block that comes `once` leaves the picker when
|
|
9
|
+
* the list already holds it.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const trimmed = (path: string) => {
|
|
13
|
+
const bare = path.replace(/[?#].*$/, "").replace(/\/+$/, "")
|
|
14
|
+
return bare || "/"
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Whether an address is one of the pages a block is for. `/x/*` is everything under `/x`. */
|
|
18
|
+
export function madeFor(path: string | null | undefined, patterns: readonly string[] | undefined): boolean {
|
|
19
|
+
if (!path || !patterns?.length) return false
|
|
20
|
+
const here = trimmed(path)
|
|
21
|
+
return patterns.some((pattern) => {
|
|
22
|
+
if (pattern.endsWith("/*")) {
|
|
23
|
+
const under = trimmed(pattern.slice(0, -2))
|
|
24
|
+
return here.startsWith(under === "/" ? "/" : under + "/")
|
|
25
|
+
}
|
|
26
|
+
return trimmed(pattern) === here
|
|
27
|
+
})
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface Offered {
|
|
31
|
+
/** Made for this page. */
|
|
32
|
+
here: Block[]
|
|
33
|
+
/** The shared library. */
|
|
34
|
+
library: Block[]
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function offeredBlocks(blocks: readonly Block[], path: string | null | undefined, used: readonly string[] = []): Offered {
|
|
38
|
+
const available = blocks.filter((block) => !(block.once && used.includes(block.name)))
|
|
39
|
+
return {
|
|
40
|
+
here: available.filter((block) => block.for?.length && madeFor(path, block.for)),
|
|
41
|
+
library: available.filter((block) => !block.for?.length),
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Blocks a list holds more than once that may only be there once. */
|
|
46
|
+
export function repeatedOnce(blocks: readonly Block[], used: readonly string[]): Block[] {
|
|
47
|
+
return blocks.filter((block) => block.once && used.filter((name) => name === block.name).length > 1)
|
|
48
|
+
}
|
|
@@ -3,7 +3,7 @@ import type { Collection, Field } from "../config/types.ts"
|
|
|
3
3
|
import { blockOf, blocksOf, dataFields, isSlot } from "../config/components.ts"
|
|
4
4
|
import { findCollection } from "./collections.ts"
|
|
5
5
|
import { summarise } from "./summary.ts"
|
|
6
|
-
import { linkedEntries, withLinkSlugs } from "./links.ts"
|
|
6
|
+
import { linkedEntries, parseLink, publishedLink, withLinkSlugs } from "./links.ts"
|
|
7
7
|
import { media } from "../media/index.ts"
|
|
8
8
|
import { publicName } from "./person.ts"
|
|
9
9
|
import type { MediaStore, StoredInfo } from "../media/store.ts"
|
|
@@ -99,6 +99,11 @@ export function collectReferences(
|
|
|
99
99
|
if (ids.length) found.push({ field, ids })
|
|
100
100
|
return text
|
|
101
101
|
},
|
|
102
|
+
(field, href) => {
|
|
103
|
+
const link = parseLink(href)
|
|
104
|
+
if (link) found.push({ field, ids: [link.id] })
|
|
105
|
+
return href
|
|
106
|
+
},
|
|
102
107
|
)
|
|
103
108
|
|
|
104
109
|
return found
|
|
@@ -122,7 +127,7 @@ export function withSlugs(
|
|
|
122
127
|
}
|
|
123
128
|
|
|
124
129
|
return slugs.get(String(value))
|
|
125
|
-
}, (_field, text) => withLinkSlugs(text, slugs))
|
|
130
|
+
}, (_field, text) => withLinkSlugs(text, slugs), (_field, href) => publishedLink(href, slugs))
|
|
126
131
|
}
|
|
127
132
|
|
|
128
133
|
function idsOf(value: unknown): string[] {
|
|
@@ -144,6 +149,8 @@ function walk(
|
|
|
144
149
|
visit: (field: Field, value: unknown) => unknown,
|
|
145
150
|
/** Rich text, whose links to other entries are references too. */
|
|
146
151
|
visitText?: (field: Field, text: string) => string,
|
|
152
|
+
/** A link field, which may name an entry or a file. */
|
|
153
|
+
visitLink?: (field: Field, href: string) => string | undefined,
|
|
147
154
|
): Record<string, unknown> {
|
|
148
155
|
const out = { ...data }
|
|
149
156
|
|
|
@@ -156,6 +163,14 @@ function walk(
|
|
|
156
163
|
continue
|
|
157
164
|
}
|
|
158
165
|
|
|
166
|
+
if (field.type === "link") {
|
|
167
|
+
if (!visitLink || typeof value !== "string") continue
|
|
168
|
+
const next = visitLink(field, value)
|
|
169
|
+
if (next === undefined) delete out[field.name]
|
|
170
|
+
else out[field.name] = next
|
|
171
|
+
continue
|
|
172
|
+
}
|
|
173
|
+
|
|
159
174
|
if (field.type === "reference") {
|
|
160
175
|
const next = visit(field, value)
|
|
161
176
|
if (next === undefined) delete out[field.name]
|
|
@@ -167,7 +182,7 @@ function walk(
|
|
|
167
182
|
if (typeof value !== "object" || Array.isArray(value)) continue
|
|
168
183
|
const inner = value as Record<string, unknown>
|
|
169
184
|
const block = blockOf(field, inner)
|
|
170
|
-
if (block) out[field.name] = walk(block.fields, inner, visit, visitText)
|
|
185
|
+
if (block) out[field.name] = walk(block.fields, inner, visit, visitText, visitLink)
|
|
171
186
|
continue
|
|
172
187
|
}
|
|
173
188
|
|
|
@@ -175,7 +190,7 @@ function walk(
|
|
|
175
190
|
out[field.name] = value.map((row) => {
|
|
176
191
|
if (!row || typeof row !== "object") return row
|
|
177
192
|
const block = blockOf(field, row)
|
|
178
|
-
return block ? walk(block.fields, row as Record<string, unknown>, visit, visitText) : row
|
|
193
|
+
return block ? walk(block.fields, row as Record<string, unknown>, visit, visitText, visitLink) : row
|
|
179
194
|
})
|
|
180
195
|
}
|
|
181
196
|
}
|
|
@@ -197,6 +212,14 @@ function walk(
|
|
|
197
212
|
*/
|
|
198
213
|
export async function publishedReferences(
|
|
199
214
|
ids: string[],
|
|
215
|
+
/**
|
|
216
|
+
* What a picture becomes. `copied`: the picture itself, address, size and
|
|
217
|
+
* words, for what has to stand alone (a data source other apps read, a
|
|
218
|
+
* preview of a draft). `named`: its id, for an entry whose site reads the
|
|
219
|
+
* picture from its own file (`content/media/<id>.json`), so a corrected
|
|
220
|
+
* credit is one file and every page using it rebuilds.
|
|
221
|
+
*/
|
|
222
|
+
{ pictures = "copied" }: { pictures?: "copied" | "named" } = {},
|
|
200
223
|
): Promise<Map<string, unknown>> {
|
|
201
224
|
if (!ids.length) return new Map()
|
|
202
225
|
|
|
@@ -248,6 +271,10 @@ export async function publishedReferences(
|
|
|
248
271
|
console.warn(`[tela] ${file} is not in the media library, so it is left out of what is published.`)
|
|
249
272
|
continue
|
|
250
273
|
}
|
|
274
|
+
if (pictures === "named" && collection.uploads) {
|
|
275
|
+
resolved.set(String(row.id), String(row.id))
|
|
276
|
+
continue
|
|
277
|
+
}
|
|
251
278
|
// Not a page, so being published is not the question - a media entry is
|
|
252
279
|
// usable the moment it exists.
|
|
253
280
|
resolved.set(
|
package/src/content/rules.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { BLOCK_KEY, type Collection, type Field, type PatternRule } from "../config/types.ts"
|
|
2
2
|
import { blockOf, dataFields, isSlot, tagsRows } from "../config/components.ts"
|
|
3
3
|
import { shown } from "./visibility.ts"
|
|
4
|
+
import { repeatedOnce } from "./placement.ts"
|
|
5
|
+
import { plainWords } from "./markdown.ts"
|
|
4
6
|
|
|
5
7
|
/**
|
|
6
8
|
* Declarative field rules, evaluated identically wherever they run.
|
|
@@ -71,7 +73,7 @@ export function checkField(
|
|
|
71
73
|
// `required` is only judged when they try to save.
|
|
72
74
|
if (mode === "live" && empty(value)) return issues
|
|
73
75
|
|
|
74
|
-
if (field.required && empty(value)) {
|
|
76
|
+
if (field.required && empty(value) && field.fallback === undefined) {
|
|
75
77
|
fail(`${nameOf(field)} is required.`)
|
|
76
78
|
// Nothing else is worth saying about an empty field.
|
|
77
79
|
return issues
|
|
@@ -79,6 +81,15 @@ export function checkField(
|
|
|
79
81
|
|
|
80
82
|
if (empty(value)) return issues
|
|
81
83
|
|
|
84
|
+
if (field.type === "reference" && field.many && Array.isArray(value)) {
|
|
85
|
+
if (field.maxRows !== undefined && value.length > field.maxRows) {
|
|
86
|
+
fail(`${nameOf(field)} takes at most ${field.maxRows}.`)
|
|
87
|
+
}
|
|
88
|
+
if (mode === "save" && field.minRows !== undefined && value.length < field.minRows) {
|
|
89
|
+
fail(`${nameOf(field)} needs at least ${field.minRows}.`)
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
82
93
|
if (field.choices && typeof value === "string") {
|
|
83
94
|
// The same list the editor offers. A value from outside it usually means
|
|
84
95
|
// content written before the list changed.
|
|
@@ -88,10 +99,13 @@ export function checkField(
|
|
|
88
99
|
}
|
|
89
100
|
|
|
90
101
|
if (typeof value === "string") {
|
|
91
|
-
|
|
102
|
+
// What a reader sees, as the editor's counter measures it: a link's address
|
|
103
|
+
// and the formatting marks are not characters of the caption.
|
|
104
|
+
const length = field.type === "markdown" ? plainWords(value).replace(/\s+/g, " ").trim().length : value.length
|
|
105
|
+
if (field.minLength !== undefined && length < field.minLength) {
|
|
92
106
|
fail(`${nameOf(field)} must be at least ${field.minLength} characters.`)
|
|
93
107
|
}
|
|
94
|
-
if (field.maxLength !== undefined &&
|
|
108
|
+
if (field.maxLength !== undefined && length > field.maxLength) {
|
|
95
109
|
fail(`${nameOf(field)} must be at most ${field.maxLength} characters.`)
|
|
96
110
|
}
|
|
97
111
|
// Only the first failing pattern is reported. The rules are ordered
|
|
@@ -171,7 +185,8 @@ function checkNested(field: Field, data: Record<string, unknown>, mode: Mode): I
|
|
|
171
185
|
* already said so - repeating it here would be two messages for one gap.
|
|
172
186
|
*/
|
|
173
187
|
function checkSlot(field: Field, data: Record<string, unknown>, mode: Mode): Issue[] {
|
|
174
|
-
const
|
|
188
|
+
const absent = data[field.name] === undefined || data[field.name] === null
|
|
189
|
+
const value = absent && mode === "save" && !tagsRows(field) ? {} : data[field.name]
|
|
175
190
|
if (!value || typeof value !== "object" || Array.isArray(value)) return []
|
|
176
191
|
|
|
177
192
|
const inner = value as Record<string, unknown>
|
|
@@ -229,6 +244,11 @@ function checkRows(field: Field, data: Record<string, unknown>, mode: Mode): Iss
|
|
|
229
244
|
}
|
|
230
245
|
}
|
|
231
246
|
|
|
247
|
+
const used = rows.map((row) => (row && typeof row === "object" ? (row as any)[BLOCK_KEY] : undefined)).filter(Boolean)
|
|
248
|
+
for (const block of repeatedOnce(field.blocks ?? [], used)) {
|
|
249
|
+
issues.push({ field: field.name, message: `${block.label ?? block.name} can only be added once.` })
|
|
250
|
+
}
|
|
251
|
+
|
|
232
252
|
return issues.concat(rows.flatMap((row, index) => {
|
|
233
253
|
if (!row || typeof row !== "object") return []
|
|
234
254
|
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { join } from "path"
|
|
2
|
+
import { BLOCK_KEY, type Block, type Collection, type Field } from "../config/types.ts"
|
|
3
|
+
import { blocksOf, dataFields, tagsRows } from "../config/components.ts"
|
|
4
|
+
import { findCollection } from "./collections.ts"
|
|
5
|
+
|
|
6
|
+
export interface ShapeNode {
|
|
7
|
+
type?: string | string[]
|
|
8
|
+
"x-tela-type"?: string
|
|
9
|
+
"x-tela-to"?: string
|
|
10
|
+
const?: string
|
|
11
|
+
properties?: Record<string, ShapeNode>
|
|
12
|
+
required?: string[]
|
|
13
|
+
items?: ShapeNode
|
|
14
|
+
oneOf?: ShapeNode[]
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface DataShape extends ShapeNode {
|
|
18
|
+
$schema: string
|
|
19
|
+
title: string
|
|
20
|
+
"x-tela": { source: string; version: number }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const JSON_TYPES: Record<string, string> = {
|
|
24
|
+
text: "string",
|
|
25
|
+
markdown: "string",
|
|
26
|
+
link: "string",
|
|
27
|
+
date: "string",
|
|
28
|
+
number: "number",
|
|
29
|
+
boolean: "boolean",
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const shapePath = (name: string) => join("content", "data", `${name}.schema.json`)
|
|
33
|
+
|
|
34
|
+
export const versionOf = (collection: Collection) => collection.version ?? 1
|
|
35
|
+
|
|
36
|
+
export function dataShape(collection: Collection): DataShape {
|
|
37
|
+
return {
|
|
38
|
+
$schema: "https://json-schema.org/draft/2020-12/schema",
|
|
39
|
+
title: collection.label ?? collection.name,
|
|
40
|
+
"x-tela": { source: collection.name, version: versionOf(collection) },
|
|
41
|
+
...objectOf(collection.fields),
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const alwaysThere = (field: Field) => (field.required === true && !field.when) || field.fallback !== undefined
|
|
46
|
+
|
|
47
|
+
function objectOf(fields: Field[], extra: Record<string, ShapeNode> = {}, extraRequired: string[] = []): ShapeNode {
|
|
48
|
+
const properties: Record<string, ShapeNode> = { ...extra }
|
|
49
|
+
const required = [...extraRequired]
|
|
50
|
+
for (const field of dataFields(fields)) {
|
|
51
|
+
const there = alwaysThere(field)
|
|
52
|
+
properties[field.name] = fieldNode(field, there)
|
|
53
|
+
if (there && !required.includes(field.name)) required.push(field.name)
|
|
54
|
+
}
|
|
55
|
+
return { type: "object", properties, ...(required.length ? { required } : {}) }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function blockNode(block: Block, tagged: boolean): ShapeNode {
|
|
59
|
+
const content: Record<string, ShapeNode> = {}
|
|
60
|
+
for (const [key, value] of Object.entries(block.content ?? {})) {
|
|
61
|
+
content[key] = { type: Array.isArray(value) ? "array" : value === null ? "null" : typeof value, "x-tela-type": "content" }
|
|
62
|
+
}
|
|
63
|
+
const tag: Record<string, ShapeNode> = tagged ? { [BLOCK_KEY]: { const: block.name } } : {}
|
|
64
|
+
return objectOf(block.fields, { ...tag, ...content }, [...Object.keys(tag), ...Object.keys(content)])
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function withDerivedKeys(field: Field, node: ShapeNode): ShapeNode {
|
|
68
|
+
const keys = Object.keys(field.derive ?? {})
|
|
69
|
+
if (!keys.length) return node
|
|
70
|
+
const derived = Object.fromEntries(keys.map((key) => [key, { type: "string", "x-tela-type": "derived" }]))
|
|
71
|
+
const add = (one: ShapeNode): ShapeNode => ({ ...one, properties: { ...one.properties, ...derived } })
|
|
72
|
+
return node.oneOf ? { ...node, oneOf: node.oneOf.map(add) } : add(node)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function rowsOf(field: Field): ShapeNode {
|
|
76
|
+
const blocks = blocksOf(field)
|
|
77
|
+
if (tagsRows(field)) return { oneOf: blocks.map((block) => blockNode(block, true)) }
|
|
78
|
+
return blockNode(blocks[0]!, false)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function fieldNode(field: Field, there: boolean): ShapeNode {
|
|
82
|
+
const telaType = { "x-tela-type": field.type }
|
|
83
|
+
const maybe = (type: string) => (there ? type : [type, "null"])
|
|
84
|
+
|
|
85
|
+
if (field.type === "repeater" && blocksOf(field).length) {
|
|
86
|
+
return { type: maybe("array"), ...telaType, items: rowsOf(field) }
|
|
87
|
+
}
|
|
88
|
+
if (field.type === "block" && blocksOf(field).length) {
|
|
89
|
+
const rows = withDerivedKeys(field, rowsOf(field))
|
|
90
|
+
return { ...rows, type: maybe("object"), ...telaType }
|
|
91
|
+
}
|
|
92
|
+
if (field.type === "reference") {
|
|
93
|
+
const to = field.to ? { "x-tela-to": field.to } : {}
|
|
94
|
+
const one: ShapeNode = field.to && findCollection(field.to)?.referencedAs ? { type: "object" } : { type: "string" }
|
|
95
|
+
return field.many
|
|
96
|
+
? { type: maybe("array"), ...telaType, ...to, items: one }
|
|
97
|
+
: { type: maybe(String(one.type)), ...telaType, ...to }
|
|
98
|
+
}
|
|
99
|
+
const json = JSON_TYPES[field.type]
|
|
100
|
+
return json ? { type: maybe(json), ...telaType } : telaType
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const types = (node: ShapeNode) => (node.type === undefined ? [] : Array.isArray(node.type) ? node.type : [node.type])
|
|
104
|
+
const kind = (node: ShapeNode) =>
|
|
105
|
+
[node["x-tela-type"] ?? "", types(node).filter((type) => type !== "null").join("|"), node["x-tela-to"] ?? "", node.const ?? ""].join("/")
|
|
106
|
+
const nullable = (node: ShapeNode) => types(node).includes("null")
|
|
107
|
+
const describe = (node: ShapeNode) =>
|
|
108
|
+
node["x-tela-to"] ? `${node["x-tela-type"]} to ${node["x-tela-to"]}` : node["x-tela-type"] ?? types(node).join(" or ")
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* What an app written against `before` would trip over in `after`. Adding is
|
|
112
|
+
* never a break; taking away, retyping and no longer promising a value are.
|
|
113
|
+
*/
|
|
114
|
+
export function breaks(before: ShapeNode, after: ShapeNode, path = ""): string[] {
|
|
115
|
+
const here = path || "the record"
|
|
116
|
+
if (kind(before) !== kind(after)) {
|
|
117
|
+
const many = (node: ShapeNode) => types(node).includes("array") && node["x-tela-type"] === "reference"
|
|
118
|
+
const what = many(before) !== many(after) ? `${many(before) ? "a list" : "one"}, now ${many(after) ? "a list" : "one"}` : `${describe(before)}, now ${describe(after)}`
|
|
119
|
+
return [`${here} was ${what}`]
|
|
120
|
+
}
|
|
121
|
+
const out: string[] = []
|
|
122
|
+
if (!nullable(before) && nullable(after)) out.push(`${here} may now be empty`)
|
|
123
|
+
|
|
124
|
+
const at = (key: string) => (path ? `${path}.${key}` : key)
|
|
125
|
+
for (const [key, was] of Object.entries(before.properties ?? {})) {
|
|
126
|
+
const now = after.properties?.[key]
|
|
127
|
+
if (!now) {
|
|
128
|
+
out.push(`${at(key)} is gone`)
|
|
129
|
+
continue
|
|
130
|
+
}
|
|
131
|
+
const inside = breaks(was, now, at(key))
|
|
132
|
+
if (before.required?.includes(key) && !after.required?.includes(key)) {
|
|
133
|
+
out.push(`${at(key)} may now be missing`, ...inside.filter((one) => one !== `${at(key)} may now be empty`))
|
|
134
|
+
} else out.push(...inside)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (before.items && after.items) out.push(...breaks(before.items, after.items, path))
|
|
138
|
+
|
|
139
|
+
if (before.oneOf || after.oneOf) {
|
|
140
|
+
if (!before.oneOf || !after.oneOf) return [...out, `${here} changed from one shape to a choice of shapes, or back`]
|
|
141
|
+
const named = (nodes: ShapeNode[]) => new Map(nodes.map((node) => [node.properties?.[BLOCK_KEY]?.const ?? "", node]))
|
|
142
|
+
const now = named(after.oneOf)
|
|
143
|
+
for (const [name, was] of named(before.oneOf)) {
|
|
144
|
+
const next = now.get(name)
|
|
145
|
+
if (next) out.push(...breaks(was, next, path ? `${path} (${name})` : name))
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return out
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export class ShapeBreaks extends Error {
|
|
153
|
+
constructor(
|
|
154
|
+
readonly source: string,
|
|
155
|
+
readonly label: string,
|
|
156
|
+
readonly problems: string[],
|
|
157
|
+
readonly went: "back" | "unraised",
|
|
158
|
+
) {
|
|
159
|
+
super(
|
|
160
|
+
went === "back"
|
|
161
|
+
? `${label} can't be published: its version in the config is lower than the one already published. A developer needs to fix the version first.`
|
|
162
|
+
: `${label} can't be published: its fields changed in a way that would break the apps reading it (${problems.join("; ")}). A developer needs to raise its version in the config first.`,
|
|
163
|
+
)
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Why `next` may not replace the published `before`, or null when it may. */
|
|
168
|
+
export function shapeProblem(before: DataShape | null, next: DataShape): ShapeBreaks | null {
|
|
169
|
+
if (!before) return null
|
|
170
|
+
const source = next["x-tela"].source
|
|
171
|
+
const was = before["x-tela"]?.version ?? 1
|
|
172
|
+
const now = next["x-tela"].version
|
|
173
|
+
if (now < was) return new ShapeBreaks(source, next.title, [`version ${was} is published, the config says ${now}`], "back")
|
|
174
|
+
if (now > was) return null
|
|
175
|
+
const problems = breaks(before, next)
|
|
176
|
+
return problems.length ? new ShapeBreaks(source, next.title, problems, "unraised") : null
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Every data source against the shape last published to `root`: what would
|
|
181
|
+
* refuse to publish, found before a deploy rather than by an editor.
|
|
182
|
+
*/
|
|
183
|
+
export async function checkShapes(collections: Collection[], root: string): Promise<ShapeBreaks[]> {
|
|
184
|
+
const found: ShapeBreaks[] = []
|
|
185
|
+
for (const collection of collections.filter((one) => one.data)) {
|
|
186
|
+
const file = Bun.file(join(root, shapePath(collection.name)))
|
|
187
|
+
const before = (await file.exists()) ? ((await file.json()) as DataShape) : null
|
|
188
|
+
const problem = shapeProblem(before, dataShape(collection))
|
|
189
|
+
if (problem) found.push(problem)
|
|
190
|
+
}
|
|
191
|
+
return found
|
|
192
|
+
}
|