@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.
- package/CHANGELOG.md +40 -0
- package/bin/tela.ts +8 -0
- package/lib/index.js +171 -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 +187 -7
- package/src/content/derive-values.ts +14 -3
- package/src/content/entry.ts +15 -1
- package/src/content/export.ts +199 -14
- package/src/content/gathered.ts +103 -0
- 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,103 @@
|
|
|
1
|
+
import { mkdir, readFile, writeFile } from "fs/promises"
|
|
2
|
+
import { dirname, join } from "path"
|
|
3
|
+
import type { GatheredList } from "../config/types.ts"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Lists gathered from what is published: every Vimeo video on the site, say,
|
|
7
|
+
* for a server that will only stream those.
|
|
8
|
+
*
|
|
9
|
+
* Kept as a ledger of what each published entry adds, so a publish touches one
|
|
10
|
+
* line of it rather than reading the whole site again. The ledger lives in the
|
|
11
|
+
* content repo with the list it explains: the list is then only ever a
|
|
12
|
+
* function of the ledger, and the repo's history shows which entry brought a
|
|
13
|
+
* value in.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** Published like a data source, so whatever serves those serves this. */
|
|
17
|
+
export const gatheredPath = (name: string) => join("content", "data", `${name}.json`)
|
|
18
|
+
/** Outside `content/`: the ledger is Tela's bookkeeping, and a site rebuilds nothing when it moves. */
|
|
19
|
+
export const ledgerPath = (name: string) => join(".tela", "gathered", `${name}.json`)
|
|
20
|
+
export const gatheredCell = (name: string) => `cms:data:${name}`
|
|
21
|
+
|
|
22
|
+
/** An entry as it is now published, or `data: null` for one taken off the site. */
|
|
23
|
+
export interface GatherChange {
|
|
24
|
+
id: string
|
|
25
|
+
collection: string
|
|
26
|
+
data: Record<string, unknown> | null
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
type Ledger = Record<string, string[]>
|
|
30
|
+
|
|
31
|
+
async function read(root: string, path: string): Promise<unknown> {
|
|
32
|
+
try {
|
|
33
|
+
return JSON.parse(await readFile(join(root, path), "utf-8"))
|
|
34
|
+
} catch {
|
|
35
|
+
return null
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function write(root: string, path: string, data: unknown) {
|
|
40
|
+
const file = join(root, path)
|
|
41
|
+
await mkdir(dirname(file), { recursive: true })
|
|
42
|
+
await writeFile(file, JSON.stringify(data, null, 2) + "\n")
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function ledgerFrom(file: unknown): Ledger {
|
|
46
|
+
if (!file || typeof file !== "object" || Array.isArray(file)) return {}
|
|
47
|
+
return Object.fromEntries(
|
|
48
|
+
Object.entries(file).filter(([, values]) => Array.isArray(values) && values.every((one) => typeof one === "string")),
|
|
49
|
+
) as Ledger
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** What one entry adds: text, once each, in a steady order. */
|
|
53
|
+
export function valuesFrom(list: GatheredList, change: GatherChange): string[] {
|
|
54
|
+
if (!change.data) return []
|
|
55
|
+
if (list.collections && !list.collections.includes(change.collection)) return []
|
|
56
|
+
const found = list.from(change.data, { collection: change.collection }) ?? []
|
|
57
|
+
const values = [...found].filter((one) => typeof one === "string" || typeof one === "number").map(String).filter(Boolean)
|
|
58
|
+
return [...new Set(values)].sort()
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const sorted = (ledger: Ledger): Ledger => Object.fromEntries(Object.keys(ledger).sort().map((id) => [id, ledger[id]!]))
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Bring each list up to date with entries that were just published or taken
|
|
65
|
+
* down. `complete` says the changes are everything published, so entries the
|
|
66
|
+
* ledger remembers and the changes don't name are gone.
|
|
67
|
+
*
|
|
68
|
+
* Returns the files written. A list's cell is reported only when the list
|
|
69
|
+
* itself changed; the ledger moving alone rebuilds nothing.
|
|
70
|
+
*/
|
|
71
|
+
export async function writeGathered(
|
|
72
|
+
lists: GatheredList[],
|
|
73
|
+
changes: GatherChange[],
|
|
74
|
+
options: { root: string; complete?: boolean },
|
|
75
|
+
): Promise<{ files: string[]; cells: string[] }> {
|
|
76
|
+
const files: string[] = []
|
|
77
|
+
const cells: string[] = []
|
|
78
|
+
|
|
79
|
+
for (const list of lists) {
|
|
80
|
+
const was = ledgerFrom(await read(options.root, ledgerPath(list.name)))
|
|
81
|
+
const next: Ledger = options.complete ? {} : { ...was }
|
|
82
|
+
|
|
83
|
+
for (const change of changes) {
|
|
84
|
+
const values = valuesFrom(list, change)
|
|
85
|
+
if (values.length) next[change.id] = values
|
|
86
|
+
else delete next[change.id]
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const ledger = sorted(next)
|
|
90
|
+
if (JSON.stringify(ledger) !== JSON.stringify(sorted(was))) {
|
|
91
|
+
await write(options.root, ledgerPath(list.name), ledger)
|
|
92
|
+
files.push(ledgerPath(list.name))
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const published = { values: [...new Set(Object.values(ledger).flat())].sort() }
|
|
96
|
+
if (JSON.stringify(await read(options.root, gatheredPath(list.name))) === JSON.stringify(published)) continue
|
|
97
|
+
await write(options.root, gatheredPath(list.name), published)
|
|
98
|
+
files.push(gatheredPath(list.name))
|
|
99
|
+
cells.push(gatheredCell(list.name))
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return { files, cells }
|
|
103
|
+
}
|
package/src/content/git.ts
CHANGED
|
@@ -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
|
|
@@ -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
|
|