@brimsites/brimjs 0.0.0-stage → 1.0.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/LICENSE +110 -0
- package/README.md +22 -2
- package/bin/brim.js +5 -0
- package/dist/cli.js +3802 -0
- package/editor-dist/editor.css +1 -0
- package/editor-dist/editor.js +91 -0
- package/package.json +71 -3
- package/skills/brim-convert/SKILL.md +256 -0
- package/skills/brim-hosting/SKILL.md +221 -0
- package/src/astro-shim.d.ts +5 -0
- package/src/auth/accounts.ts +341 -0
- package/src/auth/password.ts +34 -0
- package/src/auth/permissions.ts +44 -0
- package/src/blocks/accordion/Accordion.astro +48 -0
- package/src/blocks/accordion/accordion.css +63 -0
- package/src/blocks/analytics/Analytics.astro +45 -0
- package/src/blocks/analytics/ConsentBanner.astro +41 -0
- package/src/blocks/analytics/analytics.client.ts +125 -0
- package/src/blocks/analytics/analytics.css +51 -0
- package/src/blocks/analytics/consent.ts +51 -0
- package/src/blocks/button/Button.astro +64 -0
- package/src/blocks/button/button.css +100 -0
- package/src/blocks/carousel/Carousel.astro +140 -0
- package/src/blocks/carousel/carousel.client.ts +153 -0
- package/src/blocks/carousel/carousel.css +181 -0
- package/src/blocks/data/icons.ts +285 -0
- package/src/blocks/data/image-shapes.ts +91 -0
- package/src/blocks/data/social-icons.ts +41 -0
- package/src/blocks/data/social-networks.ts +256 -0
- package/src/blocks/divider/Divider.astro +27 -0
- package/src/blocks/divider/divider.css +17 -0
- package/src/blocks/form/Captcha.astro +27 -0
- package/src/blocks/form/Form.astro +250 -0
- package/src/blocks/form/FormField.astro +138 -0
- package/src/blocks/form/Newsletter.astro +80 -0
- package/src/blocks/form/form.client.ts +339 -0
- package/src/blocks/form/form.css +271 -0
- package/src/blocks/gallery/ImageGallery.astro +126 -0
- package/src/blocks/gallery/gallery.css +43 -0
- package/src/blocks/gallery/lightbox.client.ts +178 -0
- package/src/blocks/gallery/lightbox.css +134 -0
- package/src/blocks/icon/Icon.astro +41 -0
- package/src/blocks/icon/icon.css +16 -0
- package/src/blocks/image/Image.astro +158 -0
- package/src/blocks/image/image.css +42 -0
- package/src/blocks/images.ts +64 -0
- package/src/blocks/in-editor.client.ts +8 -0
- package/src/blocks/listing/Listing.astro +288 -0
- package/src/blocks/listing/ListingCards.astro +48 -0
- package/src/blocks/listing/listing.css +136 -0
- package/src/blocks/listing/query.ts +363 -0
- package/src/blocks/map/Map.astro +75 -0
- package/src/blocks/map/map.css +32 -0
- package/src/blocks/schemas/accordion.ts +118 -0
- package/src/blocks/schemas/button.ts +78 -0
- package/src/blocks/schemas/carousel.ts +133 -0
- package/src/blocks/schemas/divider.ts +29 -0
- package/src/blocks/schemas/form-field-types.ts +29 -0
- package/src/blocks/schemas/form.ts +350 -0
- package/src/blocks/schemas/icon.ts +24 -0
- package/src/blocks/schemas/image-gallery.ts +54 -0
- package/src/blocks/schemas/image.ts +87 -0
- package/src/blocks/schemas/index.ts +33 -0
- package/src/blocks/schemas/listing.ts +14 -0
- package/src/blocks/schemas/map.ts +81 -0
- package/src/blocks/schemas/newsletter.ts +324 -0
- package/src/blocks/schemas/social-media.ts +348 -0
- package/src/blocks/schemas/text.ts +151 -0
- package/src/blocks/schemas/video.ts +57 -0
- package/src/blocks/search/Search.astro +147 -0
- package/src/blocks/search/search.css +69 -0
- package/src/blocks/search/state.ts +28 -0
- package/src/blocks/settings.ts +94 -0
- package/src/blocks/social/SocialMedia.astro +102 -0
- package/src/blocks/social/social-links.ts +16 -0
- package/src/blocks/social/social.css +31 -0
- package/src/blocks/theme.ts +35 -0
- package/src/blocks/types.ts +52 -0
- package/src/blocks/video/Video.astro +90 -0
- package/src/blocks/video/video-source.ts +77 -0
- package/src/blocks/video/video.client.ts +43 -0
- package/src/blocks/video/video.css +29 -0
- package/src/check.ts +1119 -0
- package/src/cli.ts +493 -0
- package/src/components/Blocks.astro +68 -0
- package/src/components/Field.astro +61 -0
- package/src/components/Footer.astro +36 -0
- package/src/components/Link.astro +18 -0
- package/src/components/MobileMenu.astro +77 -0
- package/src/components/Navbar.astro +42 -0
- package/src/components/RichText.astro +32 -0
- package/src/components/Seo.astro +202 -0
- package/src/components/Setting.astro +46 -0
- package/src/components/Shared.astro +17 -0
- package/src/components/Text.astro +91 -0
- package/src/components/blocks.css +86 -0
- package/src/components/index.ts +27 -0
- package/src/components/mobile-menu.client.ts +21 -0
- package/src/components/mobile-menu.css +52 -0
- package/src/components/text.css +48 -0
- package/src/config.ts +413 -0
- package/src/content/block-layout.ts +63 -0
- package/src/content/block-values.ts +48 -0
- package/src/content/content-check.ts +174 -0
- package/src/content/content-types.ts +408 -0
- package/src/content/drafts.ts +115 -0
- package/src/content/feed.ts +237 -0
- package/src/content/field-types.ts +107 -0
- package/src/content/history.ts +140 -0
- package/src/content/ids.ts +50 -0
- package/src/content/image-size.ts +212 -0
- package/src/content/image-sizes.ts +126 -0
- package/src/content/item-fields.ts +110 -0
- package/src/content/item-head.ts +126 -0
- package/src/content/item-image.ts +26 -0
- package/src/content/item-path.ts +122 -0
- package/src/content/items.ts +580 -0
- package/src/content/language-scopes.ts +40 -0
- package/src/content/media.ts +271 -0
- package/src/content/menus.ts +51 -0
- package/src/content/page-templates.ts +52 -0
- package/src/content/redirects.ts +112 -0
- package/src/content/references.ts +165 -0
- package/src/content/rich-text.ts +63 -0
- package/src/content/search.ts +167 -0
- package/src/content/seed.ts +229 -0
- package/src/content/site-settings.ts +111 -0
- package/src/content/sitemap.ts +143 -0
- package/src/content/store.ts +225 -0
- package/src/content/tags.ts +67 -0
- package/src/content/text-default.ts +139 -0
- package/src/content/types.ts +137 -0
- package/src/content/validate.ts +253 -0
- package/src/content/validation-error.ts +2 -0
- package/src/db/cached.ts +140 -0
- package/src/db/database.ts +15 -0
- package/src/db/libsql.ts +29 -0
- package/src/db/schema.ts +189 -0
- package/src/db/url.ts +44 -0
- package/src/editor/client/BlockSettings.tsx +1063 -0
- package/src/editor/client/Chrome.tsx +284 -0
- package/src/editor/client/ContentBrowser.tsx +1299 -0
- package/src/editor/client/Editor.tsx +1756 -0
- package/src/editor/client/HistoryPanel.tsx +114 -0
- package/src/editor/client/ImagesWidget.tsx +113 -0
- package/src/editor/client/Inspector.tsx +127 -0
- package/src/editor/client/ItemForm.tsx +535 -0
- package/src/editor/client/LinkWidget.tsx +440 -0
- package/src/editor/client/ListingPanel.tsx +99 -0
- package/src/editor/client/Login.tsx +338 -0
- package/src/editor/client/Menu.tsx +64 -0
- package/src/editor/client/PageSettings.tsx +270 -0
- package/src/editor/client/RedirectsSettings.tsx +130 -0
- package/src/editor/client/Resize.tsx +204 -0
- package/src/editor/client/Sidebar.tsx +51 -0
- package/src/editor/client/SiteMap.tsx +568 -0
- package/src/editor/client/SiteSettings.tsx +409 -0
- package/src/editor/client/TextTools.tsx +391 -0
- package/src/editor/client/Toolbar.tsx +449 -0
- package/src/editor/client/VideoUpload.tsx +251 -0
- package/src/editor/client/api.ts +417 -0
- package/src/editor/client/brand.ts +20 -0
- package/src/editor/client/connection.ts +98 -0
- package/src/editor/client/context.ts +19 -0
- package/src/editor/client/css.d.ts +2 -0
- package/src/editor/client/editor.css +4656 -0
- package/src/editor/client/fields.tsx +812 -0
- package/src/editor/client/icons.tsx +174 -0
- package/src/editor/client/keys.ts +15 -0
- package/src/editor/client/kinds.ts +289 -0
- package/src/editor/client/languages.ts +32 -0
- package/src/editor/client/main.tsx +100 -0
- package/src/editor/client/responses.ts +26 -0
- package/src/editor/client/rich-text.ts +326 -0
- package/src/editor/client/site-tree.ts +239 -0
- package/src/editor/client/theme.ts +55 -0
- package/src/editor/client/tsconfig.json +18 -0
- package/src/editor/client/tus.ts +137 -0
- package/src/editor/client/use-rect.ts +50 -0
- package/src/editor/client/widgets.tsx +1218 -0
- package/src/forms/captcha.ts +83 -0
- package/src/forms/define.ts +166 -0
- package/src/forms/fields.ts +197 -0
- package/src/forms/file-types.ts +108 -0
- package/src/forms/files.ts +216 -0
- package/src/forms/form-page.ts +9 -0
- package/src/forms/handler.ts +622 -0
- package/src/forms/spec.ts +89 -0
- package/src/forms/store.ts +96 -0
- package/src/forms/work.ts +50 -0
- package/src/icons/library.ts +144 -0
- package/src/icons/load.ts +63 -0
- package/src/index.ts +99 -0
- package/src/init.ts +257 -0
- package/src/integration.ts +469 -0
- package/src/mail/mailer.ts +197 -0
- package/src/mail/notify.ts +272 -0
- package/src/mail/settings.ts +173 -0
- package/src/mail/templates.ts +191 -0
- package/src/mcp/page-nodes.ts +209 -0
- package/src/mcp/server.ts +111 -0
- package/src/mcp/tools.ts +637 -0
- package/src/runtime/TemplatePage.astro +39 -0
- package/src/runtime/TemplatePageStatic.astro +13 -0
- package/src/runtime/admin-route.ts +80 -0
- package/src/runtime/connect.ts +53 -0
- package/src/runtime/content.ts +188 -0
- package/src/runtime/context.ts +131 -0
- package/src/runtime/form-files.ts +18 -0
- package/src/runtime/forms-route.ts +33 -0
- package/src/runtime/forms.ts +28 -0
- package/src/runtime/icons.ts +5 -0
- package/src/runtime/media.ts +175 -0
- package/src/runtime/middleware.ts +186 -0
- package/src/runtime/nav.ts +13 -0
- package/src/runtime/query-reads.ts +49 -0
- package/src/runtime/query-store.ts +16 -0
- package/src/runtime/request-state.ts +69 -0
- package/src/runtime/robots.ts +29 -0
- package/src/runtime/rss-static.ts +16 -0
- package/src/runtime/rss.ts +29 -0
- package/src/runtime/server.ts +29 -0
- package/src/runtime/sitemap.ts +34 -0
- package/src/runtime/template-paths.ts +34 -0
- package/src/runtime/uploads-route.ts +13 -0
- package/src/seed-cli.ts +253 -0
- package/src/server/auth.ts +31 -0
- package/src/server/fetch-image.ts +219 -0
- package/src/server/handler.ts +2106 -0
- package/src/server/http.ts +162 -0
- package/src/server/locales.ts +73 -0
- package/src/server/node.ts +57 -0
- package/src/server/query-params.ts +249 -0
- package/src/server/rate-limit.ts +72 -0
- package/src/server/video-host.ts +162 -0
- package/src/starter.ts +70 -0
- package/src/version.ts +4 -0
- package/src/virtual.d.ts +65 -0
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import type { Database, Row, SqlValue } from "../db/database.ts";
|
|
5
|
+
import { imageSize } from "./image-size.ts";
|
|
6
|
+
import { rememberImageSize } from "./image-sizes.ts";
|
|
7
|
+
import { ValidationError } from "./validation-error.ts";
|
|
8
|
+
|
|
9
|
+
export interface MediaFile {
|
|
10
|
+
id: string;
|
|
11
|
+
/** Address the image is served from, e.g. `/uploads/3f2a….jpg`. */
|
|
12
|
+
url: string;
|
|
13
|
+
/** The name the file had on the owner's computer. */
|
|
14
|
+
name: string;
|
|
15
|
+
mime: string;
|
|
16
|
+
size: number;
|
|
17
|
+
createdAt: string;
|
|
18
|
+
/** "" for the site's gallery, or `<type>/<item id>` for the folder of one item. */
|
|
19
|
+
folder: string;
|
|
20
|
+
/** The image's size in pixels, as it is drawn; absent for images not measured yet. */
|
|
21
|
+
width?: number;
|
|
22
|
+
height?: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
|
|
26
|
+
|
|
27
|
+
const SERVED_TYPES: Record<string, string> = {
|
|
28
|
+
avif: "image/avif",
|
|
29
|
+
gif: "image/gif",
|
|
30
|
+
jpeg: "image/jpeg",
|
|
31
|
+
jpg: "image/jpeg",
|
|
32
|
+
png: "image/png",
|
|
33
|
+
svg: "image/svg+xml",
|
|
34
|
+
webp: "image/webp",
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* `/uploads/<file>`, read from the uploads folder when asked. The built server answers with it for images uploaded
|
|
39
|
+
* after the build; the dev server too, as its own list of public files learns of a new one only after the page
|
|
40
|
+
* drawn just after an upload has asked for it.
|
|
41
|
+
*/
|
|
42
|
+
export async function uploadResponse(directory: string, file: string, publicUrl?: string): Promise<Response> {
|
|
43
|
+
const type = SERVED_TYPES[file.split(".").pop()?.toLowerCase() ?? ""];
|
|
44
|
+
// Names are written by Brim; anything else, or a path climbing out of the folder, is not an upload.
|
|
45
|
+
if (!type || !/^[\w.-]+(\/[\w.-]+)*$/.test(file) || file.split("/").some((part) => part.startsWith("."))) {
|
|
46
|
+
return new Response("Not found", { status: 404 });
|
|
47
|
+
}
|
|
48
|
+
// Images served from elsewhere (a CDN): an address written by the site's own code, or shown in the editor, leads
|
|
49
|
+
// there. Files still on this server, uploaded before, are answered from here.
|
|
50
|
+
if (publicUrl) {
|
|
51
|
+
try {
|
|
52
|
+
const body = await readFile(join(directory, file));
|
|
53
|
+
return new Response(body, { headers: uploadHeaders(type) });
|
|
54
|
+
} catch {
|
|
55
|
+
return new Response(null, { status: 301, headers: { location: `${publicUrl}/uploads/${file}` } });
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
const body = await readFile(join(directory, file));
|
|
60
|
+
return new Response(body, { headers: uploadHeaders(type) });
|
|
61
|
+
} catch {
|
|
62
|
+
return new Response("Not found", { status: 404 });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function uploadHeaders(type: string): Record<string, string> {
|
|
67
|
+
return {
|
|
68
|
+
"content-type": type,
|
|
69
|
+
"cache-control": "public, max-age=31536000, immutable",
|
|
70
|
+
// An SVG can carry a script; shown as an image it never runs, opened on its own it must not either.
|
|
71
|
+
"content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox",
|
|
72
|
+
"x-content-type-options": "nosniff",
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Image formats accepted for upload, recognised by the file's first bytes rather than its name
|
|
78
|
+
* or declared type. SVG is left out on purpose: it can carry scripts.
|
|
79
|
+
*/
|
|
80
|
+
const FORMATS: { mime: string; extension: string; matches: (bytes: Uint8Array) => boolean }[] = [
|
|
81
|
+
{ mime: "image/jpeg", extension: "jpg", matches: (bytes) => startsWith(bytes, [0xff, 0xd8, 0xff]) },
|
|
82
|
+
{ mime: "image/png", extension: "png", matches: (bytes) => startsWith(bytes, [0x89, 0x50, 0x4e, 0x47]) },
|
|
83
|
+
{ mime: "image/gif", extension: "gif", matches: (bytes) => ascii(bytes, 0, 4) === "GIF8" },
|
|
84
|
+
{
|
|
85
|
+
mime: "image/webp",
|
|
86
|
+
extension: "webp",
|
|
87
|
+
matches: (bytes) => ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 12) === "WEBP",
|
|
88
|
+
},
|
|
89
|
+
{ mime: "image/avif", extension: "avif", matches: (bytes) => ascii(bytes, 4, 12) === "ftypavif" },
|
|
90
|
+
];
|
|
91
|
+
|
|
92
|
+
function startsWith(bytes: Uint8Array, signature: number[]): boolean {
|
|
93
|
+
return signature.every((byte, index) => bytes[index] === byte);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function ascii(bytes: Uint8Array, start: number, end: number): string {
|
|
97
|
+
return String.fromCharCode(...bytes.subarray(start, end));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Where the files of uploads are written: the server's disk, or a storage reached over HTTP. */
|
|
101
|
+
export interface MediaFiles {
|
|
102
|
+
/** `path` is the file's name under the uploads, e.g. `product/<id>/<uuid>.jpg`. */
|
|
103
|
+
write(path: string, bytes: Uint8Array, mime: string): Promise<void>;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Uploads as files in a folder of the server, `public/uploads` by default. */
|
|
107
|
+
export class DiskFiles implements MediaFiles {
|
|
108
|
+
readonly #directory: URL;
|
|
109
|
+
|
|
110
|
+
constructor(directory: URL) {
|
|
111
|
+
this.#directory = directory;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async write(path: string, bytes: Uint8Array): Promise<void> {
|
|
115
|
+
const file = new URL(path, this.#directory);
|
|
116
|
+
await mkdir(new URL(".", file), { recursive: true });
|
|
117
|
+
await writeFile(file, bytes);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Uploads sent to a storage over HTTP: `PUT <url>/uploads/<path>` with the headers the site gives (its key). Any
|
|
123
|
+
* storage that takes a file that way works, and so does a host's own endpoint in front of one.
|
|
124
|
+
*/
|
|
125
|
+
export class HttpFiles implements MediaFiles {
|
|
126
|
+
readonly #url: string;
|
|
127
|
+
readonly #headers: Record<string, string>;
|
|
128
|
+
readonly #fetch: typeof fetch;
|
|
129
|
+
|
|
130
|
+
constructor(url: string, headers: Record<string, string> = {}, fetcher: typeof fetch = fetch) {
|
|
131
|
+
this.#url = url.replace(/\/+$/, "");
|
|
132
|
+
this.#headers = headers;
|
|
133
|
+
this.#fetch = fetcher;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async write(path: string, bytes: Uint8Array, mime: string): Promise<void> {
|
|
137
|
+
const address = `${this.#url}/uploads/${path.split("/").map(encodeURIComponent).join("/")}`;
|
|
138
|
+
const response = await this.#fetch(address, {
|
|
139
|
+
method: "PUT",
|
|
140
|
+
headers: { ...this.#headers, "content-type": mime },
|
|
141
|
+
body: new Uint8Array(bytes),
|
|
142
|
+
});
|
|
143
|
+
// The storage's answer may name it; the owner only needs to know the image was not kept.
|
|
144
|
+
if (!response.ok) throw new Error(`The image could not be stored (${response.status}).`);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** The storage `media.storage` names, or nothing when uploads stay on the server's disk. */
|
|
149
|
+
export function storageFiles(
|
|
150
|
+
storage: { url: string; headers: Record<string, string> } | undefined,
|
|
151
|
+
): MediaFiles | undefined {
|
|
152
|
+
return storage ? new HttpFiles(storage.url, storage.headers) : undefined;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** The owner's uploaded images: files on disk or in a storage, listed in the database under `/uploads/…`. */
|
|
156
|
+
export class MediaStore {
|
|
157
|
+
readonly #db: Database;
|
|
158
|
+
readonly #files: MediaFiles;
|
|
159
|
+
readonly #publicPath: string;
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* `files` is where files are written (a folder of the server, or a storage); `publicPath` is the address prefix
|
|
163
|
+
* the database lists them under, the same wherever they are kept.
|
|
164
|
+
*/
|
|
165
|
+
constructor(db: Database, files: URL | MediaFiles, publicPath = "/uploads") {
|
|
166
|
+
this.#db = db;
|
|
167
|
+
this.#files = files instanceof URL ? new DiskFiles(files) : files;
|
|
168
|
+
this.#publicPath = publicPath;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Every image, newest first. A library of thousands is read a page at a time with `page`. */
|
|
172
|
+
async list(): Promise<MediaFile[]> {
|
|
173
|
+
const rows = await this.#db.query("SELECT * FROM brim_media ORDER BY created_at DESC, id DESC");
|
|
174
|
+
return rows.map(toMediaFile);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* One page of the library, newest first: the images whose name holds `search` (any case), in `folder` when it is
|
|
179
|
+
* given ("" is the gallery), after the one `after` names (the `next` of the page before). `next` is absent on the
|
|
180
|
+
* last page. The picker reads it this way, so every image of a library of thousands is reachable and searched.
|
|
181
|
+
*/
|
|
182
|
+
async page(
|
|
183
|
+
options: { search?: string; folder?: string; after?: string; limit?: number } = {},
|
|
184
|
+
): Promise<{ files: MediaFile[]; next?: string }> {
|
|
185
|
+
const limit = Math.min(Math.max(Math.trunc(options.limit ?? 120), 1), 500);
|
|
186
|
+
const where: string[] = [];
|
|
187
|
+
const args: SqlValue[] = [];
|
|
188
|
+
const search = options.search?.trim();
|
|
189
|
+
if (search) {
|
|
190
|
+
where.push("name LIKE ? ESCAPE '\\'");
|
|
191
|
+
args.push(`%${search.replace(/[\\%_]/g, (character) => `\\${character}`)}%`);
|
|
192
|
+
}
|
|
193
|
+
if (options.folder !== undefined) {
|
|
194
|
+
where.push("folder = ?");
|
|
195
|
+
args.push(options.folder);
|
|
196
|
+
}
|
|
197
|
+
const [createdAt, id] = (options.after ?? "").split("|");
|
|
198
|
+
if (createdAt && id) {
|
|
199
|
+
where.push("(created_at < ? OR (created_at = ? AND id < ?))");
|
|
200
|
+
args.push(createdAt, createdAt, id);
|
|
201
|
+
}
|
|
202
|
+
const rows = await this.#db.query(
|
|
203
|
+
`SELECT * FROM brim_media${where.length > 0 ? ` WHERE ${where.join(" AND ")}` : ""}
|
|
204
|
+
ORDER BY created_at DESC, id DESC LIMIT ?`,
|
|
205
|
+
[...args, limit + 1],
|
|
206
|
+
);
|
|
207
|
+
const files = rows.slice(0, limit).map(toMediaFile);
|
|
208
|
+
const last = files.at(-1);
|
|
209
|
+
return rows.length > limit && last ? { files, next: `${last.createdAt}|${last.id}` } : { files };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* `folder` is "" for the gallery or `<type>/<item id>`, checked by the caller against existing items;
|
|
214
|
+
* files of a folder are written to a subfolder of the same path.
|
|
215
|
+
*/
|
|
216
|
+
async upload(bytes: Uint8Array, name: string, folder = ""): Promise<MediaFile> {
|
|
217
|
+
if (folder !== "" && !/^[a-z][a-z0-9_]*\/[\w-]{1,64}$/.test(folder)) {
|
|
218
|
+
throw new ValidationError("This folder does not exist.");
|
|
219
|
+
}
|
|
220
|
+
if (bytes.byteLength > MAX_UPLOAD_BYTES) throw new ValidationError("The image is larger than 10 MB.");
|
|
221
|
+
const format = FORMATS.find((candidate) => candidate.matches(bytes));
|
|
222
|
+
if (!format) throw new ValidationError("Only JPEG, PNG, GIF, WebP and AVIF images can be uploaded.");
|
|
223
|
+
|
|
224
|
+
// The stored name is generated, so nothing in the uploaded name can reach the file system.
|
|
225
|
+
const id = randomUUID();
|
|
226
|
+
const fileName = `${folder ? `${folder}/` : ""}${id}.${format.extension}`;
|
|
227
|
+
await this.#files.write(fileName, bytes, format.mime);
|
|
228
|
+
const size = imageSize(bytes);
|
|
229
|
+
|
|
230
|
+
const file: MediaFile = {
|
|
231
|
+
id,
|
|
232
|
+
url: `${this.#publicPath}/${fileName}`,
|
|
233
|
+
name: name.slice(0, 200) || fileName,
|
|
234
|
+
mime: format.mime,
|
|
235
|
+
size: bytes.byteLength,
|
|
236
|
+
createdAt: new Date().toISOString(),
|
|
237
|
+
folder,
|
|
238
|
+
...size,
|
|
239
|
+
};
|
|
240
|
+
await this.#db.query(
|
|
241
|
+
"INSERT INTO brim_media (id, url, name, mime, size, created_at, folder, width, height) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
242
|
+
[
|
|
243
|
+
file.id,
|
|
244
|
+
file.url,
|
|
245
|
+
file.name,
|
|
246
|
+
file.mime,
|
|
247
|
+
file.size,
|
|
248
|
+
file.createdAt,
|
|
249
|
+
file.folder,
|
|
250
|
+
size?.width ?? 0,
|
|
251
|
+
size?.height ?? 0,
|
|
252
|
+
],
|
|
253
|
+
);
|
|
254
|
+
// Pages drawn by this server give the image its size from now on.
|
|
255
|
+
if (size) rememberImageSize(file.url, size);
|
|
256
|
+
return file;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function toMediaFile(row: Row): MediaFile {
|
|
261
|
+
return {
|
|
262
|
+
folder: String(row.folder ?? ""),
|
|
263
|
+
id: String(row.id),
|
|
264
|
+
url: String(row.url),
|
|
265
|
+
name: String(row.name),
|
|
266
|
+
mime: String(row.mime),
|
|
267
|
+
size: Number(row.size),
|
|
268
|
+
createdAt: String(row.created_at),
|
|
269
|
+
...(Number(row.width) > 0 && Number(row.height) > 0 && { width: Number(row.width), height: Number(row.height) }),
|
|
270
|
+
};
|
|
271
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { FooterValue, ImageValue, NavItem, NavLink, NavbarValue } from "./types.ts";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Menus built from content: a navbar link or a footer group with `from: "<content type>"` lists that type's items
|
|
5
|
+
* (title, address and first picture), so a category the owner adds shows in the menu without touching the code.
|
|
6
|
+
* `links` answers a type's items as links; the runtime reads them from the database (see runtime/nav.ts).
|
|
7
|
+
*/
|
|
8
|
+
export type ItemLinks = (type: string) => Promise<NavItem[]>;
|
|
9
|
+
|
|
10
|
+
/** An item as a menu link: its title, its page and the first of `imageFields` it has a picture in. */
|
|
11
|
+
export function itemLink(
|
|
12
|
+
item: { title: string; url: string; data: Record<string, unknown> },
|
|
13
|
+
imageFields: string[],
|
|
14
|
+
): NavItem {
|
|
15
|
+
const image = imageFields.map((name) => item.data[name] as ImageValue | undefined).find((value) => value?.src);
|
|
16
|
+
return { label: item.title, href: item.url, ...(image && { image: { src: image.src, alt: image.alt ?? "" } }) };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The navbar as the site shows it: every link `from` a content type gets that type's items as its sub-links. */
|
|
20
|
+
export async function expandNavbar(value: NavbarValue, links: ItemLinks): Promise<NavbarValue> {
|
|
21
|
+
const expand = async (items: NavItem[]): Promise<NavItem[]> =>
|
|
22
|
+
Promise.all(
|
|
23
|
+
items.map(async (item) =>
|
|
24
|
+
item.from
|
|
25
|
+
? { ...item, children: await links(item.from) }
|
|
26
|
+
: item.children
|
|
27
|
+
? { ...item, children: await expand(item.children) }
|
|
28
|
+
: item,
|
|
29
|
+
),
|
|
30
|
+
);
|
|
31
|
+
return { ...value, items: await expand(value.items) };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The footer as the site shows it: every group `from` a content type lists that type's items. */
|
|
35
|
+
export async function expandFooter(value: FooterValue, links: ItemLinks): Promise<FooterValue> {
|
|
36
|
+
const groups = await Promise.all(
|
|
37
|
+
value.groups.map(async (group) =>
|
|
38
|
+
group.from
|
|
39
|
+
? { ...group, items: (await links(group.from)).map(({ label, href }): NavLink => ({ label, href })) }
|
|
40
|
+
: group,
|
|
41
|
+
),
|
|
42
|
+
);
|
|
43
|
+
return { ...value, groups };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The content types a menu can be built from, for the editor's choice: those whose items have pages. */
|
|
47
|
+
export function navSources(types: { key: string; label: string; component?: unknown; path?: string }[]): string {
|
|
48
|
+
return JSON.stringify(
|
|
49
|
+
types.filter((type) => type.component || type.path).map((type) => ({ value: type.key, label: type.label })),
|
|
50
|
+
);
|
|
51
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An Astro component that draws a whole page. It gets the page as the `page` prop and builds it from the
|
|
3
|
+
* site's sections; every node in it is saved per page, so each page made from it is edited on its own.
|
|
4
|
+
* Brim only stores it and hands it back to its route, so any callable Astro component fits.
|
|
5
|
+
*/
|
|
6
|
+
export type PageComponent = (...args: never[]) => unknown;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The starting point of pages the owner adds: a layout and its sections, declared in code.
|
|
10
|
+
* A page made from it is content (an address, a title, private or published), not a file.
|
|
11
|
+
*/
|
|
12
|
+
export interface PageTemplate {
|
|
13
|
+
/** Identifies the template in code and in saved pages, e.g. `service`. */
|
|
14
|
+
key: string;
|
|
15
|
+
/** Name shown when choosing a template, e.g. `Service page`. */
|
|
16
|
+
label: string;
|
|
17
|
+
/** What the template is for and what it holds, shown under its name. */
|
|
18
|
+
description?: string;
|
|
19
|
+
/** Where new pages go: `services` puts a page titled "Lawn care" at `/services/lawn-care`. */
|
|
20
|
+
folder?: string;
|
|
21
|
+
component: PageComponent;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** A page made from a template, as the template's component receives it. */
|
|
25
|
+
export interface TemplatePageProps {
|
|
26
|
+
path: string;
|
|
27
|
+
title: string;
|
|
28
|
+
template: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** What the editor and the MCP see of a template: everything but the component. */
|
|
32
|
+
export type PageTemplateInfo = Omit<PageTemplate, "component">;
|
|
33
|
+
|
|
34
|
+
const KEY = /^[a-z][a-z0-9_]*$/;
|
|
35
|
+
const FOLDER = /^[a-z0-9]+(?:-[a-z0-9]+)*(?:\/[a-z0-9]+(?:-[a-z0-9]+)*)*$/;
|
|
36
|
+
|
|
37
|
+
/** Declares a page template. Mistakes in the declaration fail here, at startup, not when a page is added. */
|
|
38
|
+
export function definePageTemplate(template: PageTemplate): PageTemplate {
|
|
39
|
+
if (!KEY.test(template.key))
|
|
40
|
+
throw new Error(`Page template key "${template.key}" must be lowercase letters, digits or underscores.`);
|
|
41
|
+
if (template.folder !== undefined && !FOLDER.test(template.folder))
|
|
42
|
+
throw new Error(
|
|
43
|
+
`Folder "${template.folder}" of page template "${template.key}" must be lowercase words joined by dashes.`,
|
|
44
|
+
);
|
|
45
|
+
if (typeof template.component !== "function")
|
|
46
|
+
throw new Error(`Page template "${template.key}" needs an Astro component.`);
|
|
47
|
+
return template;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function templateInfo({ component: _component, ...info }: PageTemplate): PageTemplateInfo {
|
|
51
|
+
return info;
|
|
52
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { normalizePagePath } from "./ids.ts";
|
|
2
|
+
import { ValidationError } from "./validation-error.ts";
|
|
3
|
+
|
|
4
|
+
/** An old address of the site that sends visitors, and search engines, to another one. */
|
|
5
|
+
export interface Redirect {
|
|
6
|
+
/** A path of this site, e.g. `/old-pricing`. */
|
|
7
|
+
from: string;
|
|
8
|
+
/** A path of this site or a full address. */
|
|
9
|
+
to: string;
|
|
10
|
+
/** A temporary redirect (302): search engines keep the old address. By default it is permanent (301). */
|
|
11
|
+
temporary?: boolean;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const MAX_REDIRECTS = 1_000;
|
|
15
|
+
const MAX_ADDRESS = 2_000;
|
|
16
|
+
/** Brim's own routes answer themselves; a redirect there would lock the owner out of the editor. */
|
|
17
|
+
const OWN_ROUTES = /^\/(admin|_brim|uploads)(\/|$)/;
|
|
18
|
+
|
|
19
|
+
/** Checks a list of redirects as the owner sent it: addresses, no duplicates, no redirect to itself or in a loop. */
|
|
20
|
+
export function parseRedirects(input: unknown): Redirect[] {
|
|
21
|
+
if (!Array.isArray(input)) throw new ValidationError('"redirects" must be a list.');
|
|
22
|
+
if (input.length > MAX_REDIRECTS) throw new ValidationError(`A site can have up to ${MAX_REDIRECTS} redirects.`);
|
|
23
|
+
const redirects = input.map(parseRedirect);
|
|
24
|
+
const seen = new Set<string>();
|
|
25
|
+
for (const redirect of redirects) {
|
|
26
|
+
if (seen.has(redirect.from)) throw new ValidationError(`${redirect.from} is redirected twice.`);
|
|
27
|
+
seen.add(redirect.from);
|
|
28
|
+
}
|
|
29
|
+
const targets = new Map(redirects.map((redirect) => [redirect.from, redirect.to]));
|
|
30
|
+
for (const redirect of redirects) {
|
|
31
|
+
let next: string | undefined = redirect.to;
|
|
32
|
+
for (let step = 0; next !== undefined && step <= redirects.length; step++) {
|
|
33
|
+
if (next === redirect.from) throw new ValidationError(`The redirect from ${redirect.from} leads back to itself.`);
|
|
34
|
+
next = targets.get(pathOf(next) ?? "");
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return redirects;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function parseRedirect(input: unknown): Redirect {
|
|
41
|
+
if (typeof input !== "object" || input === null) throw new ValidationError("A redirect must be an object.");
|
|
42
|
+
const { from, to, temporary } = input as Record<string, unknown>;
|
|
43
|
+
if (typeof from !== "string" || !from.trim().startsWith("/") || from.trim().startsWith("//")) {
|
|
44
|
+
throw new ValidationError('A redirect\'s "from" must be a path of the site, starting with /.');
|
|
45
|
+
}
|
|
46
|
+
if (typeof to !== "string" || to.trim() === "") throw new ValidationError('A redirect needs a "to" address.');
|
|
47
|
+
if (from.length > MAX_ADDRESS || to.length > MAX_ADDRESS) throw new ValidationError("That address is too long.");
|
|
48
|
+
const source = normalizePagePath(from.trim().split(/[?#]/)[0] ?? "/");
|
|
49
|
+
if (OWN_ROUTES.test(source)) throw new ValidationError(`${source} belongs to Brim and cannot be redirected.`);
|
|
50
|
+
const target = to.trim();
|
|
51
|
+
const local = target.startsWith("/") && !target.startsWith("//");
|
|
52
|
+
if (!local && !/^https?:\/\/[^\s]+$/.test(target)) {
|
|
53
|
+
throw new ValidationError(`"${target}" must be a path of the site (/new) or a full address (https://…).`);
|
|
54
|
+
}
|
|
55
|
+
const destination = local ? normalizeTarget(target) : target;
|
|
56
|
+
if (local && pathOf(destination) === source) throw new ValidationError(`${source} cannot redirect to itself.`);
|
|
57
|
+
if (temporary !== undefined && typeof temporary !== "boolean") {
|
|
58
|
+
throw new ValidationError('"temporary" must be true or false.');
|
|
59
|
+
}
|
|
60
|
+
return { from: source, to: destination, ...(temporary === true && { temporary: true }) };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** `/new/?a=1` → `/new?a=1`: the path part normalized, a query or anchor kept. */
|
|
64
|
+
function normalizeTarget(target: string): string {
|
|
65
|
+
const index = target.search(/[?#]/);
|
|
66
|
+
const path = index === -1 ? target : target.slice(0, index);
|
|
67
|
+
return normalizePagePath(path) + (index === -1 ? "" : target.slice(index));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The path of a local address, without query or anchor; `undefined` for a full address. */
|
|
71
|
+
function pathOf(address: string): string | undefined {
|
|
72
|
+
if (!address.startsWith("/") || address.startsWith("//")) return undefined;
|
|
73
|
+
return normalizePagePath(address.split(/[?#]/)[0] ?? "/");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The redirects after a page moved from `from` to `to`: the old address leads to the new one, redirects that led to
|
|
78
|
+
* the old address lead straight to the new one, and the new address, a page now, is no longer redirected.
|
|
79
|
+
*/
|
|
80
|
+
export function redirectsAfterMove(redirects: Redirect[], from: string, to: string): Redirect[] {
|
|
81
|
+
const kept = redirects
|
|
82
|
+
.filter((redirect) => redirect.from !== to && redirect.from !== from)
|
|
83
|
+
.map((redirect) => (pathOf(redirect.to) === from ? { ...redirect, to: retarget(redirect.to, to) } : redirect));
|
|
84
|
+
return [...kept, { from, to }];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The new path with the old address's query or anchor, if it had one. */
|
|
88
|
+
function retarget(address: string, to: string): string {
|
|
89
|
+
const index = address.search(/[?#]/);
|
|
90
|
+
return to + (index === -1 ? "" : address.slice(index));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Where a request for `pathname` goes, with the visitor's query kept when the target has none of its own. */
|
|
94
|
+
export function redirectFor(redirects: Redirect[], pathname: string, search: string): Response | undefined {
|
|
95
|
+
const path = normalizePagePath(pathname);
|
|
96
|
+
// The visitor's address arrives percent-encoded (/cafea/%C8%99) while the owner writes it as read (/cafea/ș):
|
|
97
|
+
// both spellings are compared.
|
|
98
|
+
const decoded = decodedPath(path);
|
|
99
|
+
const redirect = redirects.find((candidate) => candidate.from === path || decodedPath(candidate.from) === decoded);
|
|
100
|
+
if (!redirect) return undefined;
|
|
101
|
+
const location =
|
|
102
|
+
search && !redirect.to.includes("?") && !redirect.to.includes("#") ? redirect.to + search : redirect.to;
|
|
103
|
+
return new Response(null, { status: redirect.temporary ? 302 : 301, headers: { location } });
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function decodedPath(path: string): string {
|
|
107
|
+
try {
|
|
108
|
+
return decodeURIComponent(path).normalize("NFC");
|
|
109
|
+
} catch {
|
|
110
|
+
return path;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import type { ContentField, ContentType } from "./content-types.ts";
|
|
2
|
+
import type { Item, ItemDraft, ItemStore } from "./items.ts";
|
|
3
|
+
import { ValidationError } from "./validation-error.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* References between items: a product's `category` points at a term of the `category` vocabulary by its slug. The
|
|
7
|
+
* item form checks the shape (`parseItem`); here the server, which sees every item, keeps references true: a term
|
|
8
|
+
* must exist to be pointed at, a term that changes its address takes its references along, and a term in use cannot
|
|
9
|
+
* be deleted.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** The reference fields of a type, with the type they point at. */
|
|
13
|
+
export function referenceFields(type: ContentType): (ContentField & { to: string })[] {
|
|
14
|
+
return type.fields.filter(
|
|
15
|
+
(field): field is ContentField & { to: string } => field.type === "reference" && !!field.to,
|
|
16
|
+
);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Whether items of some type point at items of this one: its items are terms, found by their slug. */
|
|
20
|
+
export function isReferenced(types: ContentType[], key: string): boolean {
|
|
21
|
+
return types.some((type) => referenceFields(type).some((field) => field.to === key));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* A term's translations share its slug: a product in English points at `faianta` and finds the English `faianta`,
|
|
26
|
+
* and its address (`/en/produse/faianta/…`) uses it. A translation given a slug of its own would lose every item
|
|
27
|
+
* pointing at it in that language, so a term's slug changes only on the term as written first.
|
|
28
|
+
*/
|
|
29
|
+
export function assertTermSlug(
|
|
30
|
+
types: ContentType[],
|
|
31
|
+
existing: Pick<Item, "type" | "slug" | "translationOf">,
|
|
32
|
+
slug: string,
|
|
33
|
+
): void {
|
|
34
|
+
if (existing.translationOf !== null && slug !== existing.slug && isReferenced(types, existing.type)) {
|
|
35
|
+
throw new ValidationError(
|
|
36
|
+
"A term's translations keep its address, so items pointing at it find it in every language: change it on the original.",
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The terms of a vocabulary by slug, for a page in one language: its own terms, and for a slug it has not translated
|
|
43
|
+
* yet, the term as it was written first (or else another translation of it), never nothing.
|
|
44
|
+
*/
|
|
45
|
+
export function termsBySlug<T extends Pick<Item, "slug" | "translationOf">>(own: T[], all: T[]): Map<string, T> {
|
|
46
|
+
const terms = new Map(own.map((term) => [term.slug, term]));
|
|
47
|
+
const others = all.filter((term) => !terms.has(term.slug));
|
|
48
|
+
others.sort((a, b) => Number(a.translationOf !== null) - Number(b.translationOf !== null));
|
|
49
|
+
for (const term of others) if (!terms.has(term.slug)) terms.set(term.slug, term);
|
|
50
|
+
return terms;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The slugs a reference field of an item holds: one, several, or none. */
|
|
54
|
+
export function referencedSlugs(item: { data: Record<string, unknown> }, field: string): string[] {
|
|
55
|
+
const value = item.data[field];
|
|
56
|
+
return (Array.isArray(value) ? value : [value]).filter(
|
|
57
|
+
(slug): slug is string => typeof slug === "string" && slug !== "",
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Declared types that point at a type which is not declared: a mistake in the code, told when the site starts. */
|
|
62
|
+
export function checkReferenceTargets(types: ContentType[]): void {
|
|
63
|
+
for (const type of types) {
|
|
64
|
+
for (const field of referenceFields(type)) {
|
|
65
|
+
const target = types.find((candidate) => candidate.key === field.to);
|
|
66
|
+
if (!target) {
|
|
67
|
+
throw new Error(
|
|
68
|
+
`Field "${field.name}" in "${type.key}" points at "${field.to}", which is not a declared content type.`,
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
if (field.vocabulary !== undefined && !target.vocabulary) {
|
|
72
|
+
throw new Error(
|
|
73
|
+
`Field "${field.name}" in "${type.key}" uses "${field.to}" as a vocabulary: declare it with defineVocabulary.`,
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Refuses an item whose references name items that do not exist (in any language: a translation keeps its slug). */
|
|
81
|
+
export async function checkReferences(
|
|
82
|
+
types: ContentType[],
|
|
83
|
+
items: ItemStore,
|
|
84
|
+
type: ContentType,
|
|
85
|
+
draft: ItemDraft,
|
|
86
|
+
): Promise<void> {
|
|
87
|
+
checkReferenceTargets(types);
|
|
88
|
+
for (const field of referenceFields(type)) {
|
|
89
|
+
const wanted = referencedSlugs(draft, field.name);
|
|
90
|
+
if (wanted.length === 0) continue;
|
|
91
|
+
const target = types.find((candidate) => candidate.key === field.to);
|
|
92
|
+
const known = new Set((await items.list(field.to)).map((item) => item.slug));
|
|
93
|
+
const missing = wanted.filter((slug) => !known.has(slug));
|
|
94
|
+
if (missing.length > 0) {
|
|
95
|
+
const what = target ? target.singular.toLowerCase() : field.to;
|
|
96
|
+
throw new ValidationError(
|
|
97
|
+
`"${field.label}" names ${missing.map((slug) => `"${slug}"`).join(", ")}: there is no such ${what}.`,
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The items that point at a term, with the field each one uses: what deleting or renaming the term touches. */
|
|
104
|
+
export async function referencesTo(
|
|
105
|
+
types: ContentType[],
|
|
106
|
+
items: ItemStore,
|
|
107
|
+
term: Pick<Item, "type" | "slug">,
|
|
108
|
+
): Promise<{ type: ContentType; field: string; item: Item }[]> {
|
|
109
|
+
const found: { type: ContentType; field: string; item: Item }[] = [];
|
|
110
|
+
for (const type of types) {
|
|
111
|
+
for (const field of referenceFields(type).filter((candidate) => candidate.to === term.type)) {
|
|
112
|
+
for (const item of await items.list(type.key)) {
|
|
113
|
+
if (referencedSlugs(item, field.name).includes(term.slug)) found.push({ type, field: field.name, item });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return found;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* A term moved to a new slug: the items that pointed at it point at the new one. Answers the items it changed, as they
|
|
122
|
+
* were and as they are, so the caller can tell what moved (a product whose address holds its category moves too, and
|
|
123
|
+
* its old address redirects).
|
|
124
|
+
*/
|
|
125
|
+
export async function renameReferences(
|
|
126
|
+
types: ContentType[],
|
|
127
|
+
items: ItemStore,
|
|
128
|
+
term: Pick<Item, "type" | "slug">,
|
|
129
|
+
slug: string,
|
|
130
|
+
): Promise<{ type: ContentType; before: Item; item: Item }[]> {
|
|
131
|
+
const changed = new Map<string, { type: ContentType; before: Item; item: Item }>();
|
|
132
|
+
for (const { type, field, item: before } of await referencesTo(types, items, term)) {
|
|
133
|
+
// An item that names the term in two fields was changed once already: the second change is made to that.
|
|
134
|
+
const item = changed.get(before.id)?.item ?? before;
|
|
135
|
+
const declared = type.fields.find((candidate) => candidate.name === field);
|
|
136
|
+
const value = item.data[field];
|
|
137
|
+
const next = Array.isArray(value) ? value.map((entry) => (entry === term.slug ? slug : entry)) : slug;
|
|
138
|
+
const draft: ItemDraft = {
|
|
139
|
+
title: item.title,
|
|
140
|
+
slug: item.slug,
|
|
141
|
+
visibility: item.visibility,
|
|
142
|
+
data: { ...item.data, [field]: declared?.multiple ? [...new Set(next as string[])] : next },
|
|
143
|
+
};
|
|
144
|
+
changed.set(item.id, { type, before, item: await items.update(item, draft) });
|
|
145
|
+
}
|
|
146
|
+
return [...changed.values()];
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Refuses to delete a term that items still point at, naming a few of them so the owner knows where to look. */
|
|
150
|
+
export async function assertUnused(
|
|
151
|
+
types: ContentType[],
|
|
152
|
+
items: ItemStore,
|
|
153
|
+
term: Pick<Item, "type" | "slug" | "title">,
|
|
154
|
+
): Promise<void> {
|
|
155
|
+
const users = await referencesTo(types, items, term);
|
|
156
|
+
if (users.length === 0) return;
|
|
157
|
+
const names = users
|
|
158
|
+
.slice(0, 3)
|
|
159
|
+
.map(({ item }) => `"${item.title}"`)
|
|
160
|
+
.join(", ");
|
|
161
|
+
const more = users.length > 3 ? ` and ${users.length - 3} more` : "";
|
|
162
|
+
throw new ValidationError(
|
|
163
|
+
`"${term.title}" is used by ${names}${more}. Point them at another one first, or remove it from them.`,
|
|
164
|
+
);
|
|
165
|
+
}
|