@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,580 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { blockDefinitions } from "../blocks/schemas/index.ts";
|
|
3
|
+
import { parseSettings } from "../blocks/settings.ts";
|
|
4
|
+
import type { Database, Row, SqlValue } from "../db/database.ts";
|
|
5
|
+
import {
|
|
6
|
+
BLOCK_TYPES,
|
|
7
|
+
type BlockEntry,
|
|
8
|
+
type BlockType,
|
|
9
|
+
type ContentField,
|
|
10
|
+
type ContentType,
|
|
11
|
+
type KeyValueEntry,
|
|
12
|
+
isSlug,
|
|
13
|
+
optionValues,
|
|
14
|
+
slugify,
|
|
15
|
+
} from "./content-types.ts";
|
|
16
|
+
import { isNodeId } from "./ids.ts";
|
|
17
|
+
import { layoutOf } from "./block-layout.ts";
|
|
18
|
+
import { blocksOf } from "./block-values.ts";
|
|
19
|
+
import { itemPathFields } from "./item-path.ts";
|
|
20
|
+
import { parseTags } from "./tags.ts";
|
|
21
|
+
import type { Visibility } from "./types.ts";
|
|
22
|
+
import { parseImage, parseRichText } from "./validate.ts";
|
|
23
|
+
import { ValidationError } from "./validation-error.ts";
|
|
24
|
+
|
|
25
|
+
export interface Item {
|
|
26
|
+
id: string;
|
|
27
|
+
type: string;
|
|
28
|
+
slug: string;
|
|
29
|
+
title: string;
|
|
30
|
+
visibility: Visibility;
|
|
31
|
+
/** Values of the fields the content type declares. */
|
|
32
|
+
data: Record<string, unknown>;
|
|
33
|
+
/** "" for the site's default language (and on a site with one language), else the language's code. */
|
|
34
|
+
locale: string;
|
|
35
|
+
/** The item this one translates; `null` for an item written first. */
|
|
36
|
+
translationOf: string | null;
|
|
37
|
+
/**
|
|
38
|
+
* Its place among the items of its type (1 first), which the owner changes by dragging the items of a type
|
|
39
|
+
* declared `ordered`. A translation sorts by its original's place.
|
|
40
|
+
*/
|
|
41
|
+
position: number;
|
|
42
|
+
createdAt: string;
|
|
43
|
+
updatedAt: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** What the owner fills in for an item. */
|
|
47
|
+
export type ItemDraft = Pick<Item, "slug" | "title" | "visibility" | "data">;
|
|
48
|
+
|
|
49
|
+
export type ItemSort = "newest" | "oldest" | "title" | "position";
|
|
50
|
+
|
|
51
|
+
/** A translation takes its original's place, so every language lists the items in the same order. */
|
|
52
|
+
const PLACE =
|
|
53
|
+
"COALESCE((SELECT original.position FROM brim_items AS original WHERE original.id = brim_items.translation_of), position)";
|
|
54
|
+
|
|
55
|
+
const ORDER: Record<ItemSort, string> = {
|
|
56
|
+
newest: "created_at DESC",
|
|
57
|
+
oldest: "created_at ASC",
|
|
58
|
+
title: "title COLLATE NOCASE ASC",
|
|
59
|
+
position: `${PLACE} ASC, created_at ASC`,
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
/** SQLite's NOCASE: only A–Z are folded. */
|
|
63
|
+
const nocase = (text: string) => text.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
|
|
64
|
+
const byText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
|
|
65
|
+
|
|
66
|
+
/** `ORDER` for items kept in memory, ties broken by id so a list is always the same. */
|
|
67
|
+
const COMPARE: Record<ItemSort, (a: Item, b: Item) => number> = {
|
|
68
|
+
newest: (a, b) => byText(b.createdAt, a.createdAt) || byText(a.id, b.id),
|
|
69
|
+
oldest: (a, b) => byText(a.createdAt, b.createdAt) || byText(a.id, b.id),
|
|
70
|
+
title: (a, b) => byText(nocase(a.title), nocase(b.title)) || byText(a.id, b.id),
|
|
71
|
+
position: (a, b) => a.position - b.position || byText(a.createdAt, b.createdAt) || byText(a.id, b.id),
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
interface KeptItems {
|
|
75
|
+
fingerprint: string;
|
|
76
|
+
/** As stored: each item's own position. */
|
|
77
|
+
rows: Item[];
|
|
78
|
+
/** As listed: a translation at its original's place. */
|
|
79
|
+
items: Item[];
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const MAX_TITLE = 300;
|
|
83
|
+
const MAX_TEXT = 20_000;
|
|
84
|
+
const MAX_GALLERY = 200;
|
|
85
|
+
const MAX_BLOCKS = 200;
|
|
86
|
+
const MAX_ROWS = 100;
|
|
87
|
+
const MAX_REFERENCES = 100;
|
|
88
|
+
const MAX_ROW_LABEL = 200;
|
|
89
|
+
const DATE = /^\d{4}-\d{2}-\d{2}$/;
|
|
90
|
+
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
91
|
+
|
|
92
|
+
export class ItemStore {
|
|
93
|
+
readonly #db: Database;
|
|
94
|
+
|
|
95
|
+
constructor(db: Database) {
|
|
96
|
+
this.#db = db;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** `locale`: only the items in that language ("" is the default one); without it, all languages. */
|
|
100
|
+
async list(
|
|
101
|
+
type: string,
|
|
102
|
+
options: { publishedOnly?: boolean; sort?: ItemSort; limit?: number; locale?: string } = {},
|
|
103
|
+
): Promise<Item[]> {
|
|
104
|
+
const { publishedOnly = false, sort = "newest", limit, locale } = options;
|
|
105
|
+
const args: SqlValue[] = [type];
|
|
106
|
+
if (locale !== undefined) args.push(locale);
|
|
107
|
+
if (limit) args.push(limit);
|
|
108
|
+
const rows = await this.#db.query(
|
|
109
|
+
`SELECT *, ${PLACE} AS place FROM brim_items WHERE type = ?${locale !== undefined ? " AND locale = ?" : ""}${
|
|
110
|
+
publishedOnly ? " AND visibility = 'published'" : ""
|
|
111
|
+
}
|
|
112
|
+
ORDER BY ${ORDER[sort]}${limit ? " LIMIT ?" : ""}`,
|
|
113
|
+
args,
|
|
114
|
+
);
|
|
115
|
+
return rows.map(toItem);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* The items of a type as `list` answers them, kept in memory between requests. Each call asks the database one
|
|
120
|
+
* small question (`#fingerprint`): whether an item of the type was added, edited, shown or hidden, moved or removed
|
|
121
|
+
* since, by whoever. Only then are the items read again, and only the ones that changed: on a remote database a
|
|
122
|
+
* type with hundreds of items takes seconds to read whole, and most pages need the same list every time.
|
|
123
|
+
*/
|
|
124
|
+
async listCached(
|
|
125
|
+
type: string,
|
|
126
|
+
options: { publishedOnly?: boolean; sort?: ItemSort; limit?: number; locale?: string } = {},
|
|
127
|
+
): Promise<Item[]> {
|
|
128
|
+
const { publishedOnly = false, sort = "newest", limit, locale } = options;
|
|
129
|
+
const kept = await this.#kept(type);
|
|
130
|
+
const listed = kept.items.filter(
|
|
131
|
+
(item) => (locale === undefined || item.locale === locale) && (!publishedOnly || item.visibility === "published"),
|
|
132
|
+
);
|
|
133
|
+
listed.sort(COMPARE[sort]);
|
|
134
|
+
return limit ? listed.slice(0, limit) : listed;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* One item by its address (`slug`) in a language ("" is the default one), with the place `list` gives it.
|
|
139
|
+
* Without `locale`, the first of any language.
|
|
140
|
+
*/
|
|
141
|
+
async bySlug(
|
|
142
|
+
type: string,
|
|
143
|
+
slug: string,
|
|
144
|
+
options: { publishedOnly?: boolean; locale?: string } = {},
|
|
145
|
+
): Promise<Item | undefined> {
|
|
146
|
+
const { publishedOnly = false, locale } = options;
|
|
147
|
+
const args: SqlValue[] = [type, slug];
|
|
148
|
+
if (locale !== undefined) args.push(locale);
|
|
149
|
+
const rows = await this.#db.query(
|
|
150
|
+
`SELECT *, ${PLACE} AS place FROM brim_items WHERE type = ? AND slug = ?${locale !== undefined ? " AND locale = ?" : ""}${
|
|
151
|
+
publishedOnly ? " AND visibility = 'published'" : ""
|
|
152
|
+
} ORDER BY locale LIMIT 1`,
|
|
153
|
+
args,
|
|
154
|
+
);
|
|
155
|
+
return rows[0] ? toItem(rows[0]) : undefined;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Per type: its items as last read, with what the database said about them then. */
|
|
159
|
+
readonly #cache = new Map<string, Promise<KeptItems>>();
|
|
160
|
+
|
|
161
|
+
async #kept(type: string): Promise<KeptItems> {
|
|
162
|
+
const fingerprint = await this.#fingerprint(type);
|
|
163
|
+
const previous = this.#cache.get(type);
|
|
164
|
+
const before = previous ? await previous.catch(() => undefined) : undefined;
|
|
165
|
+
if (before && before.fingerprint === fingerprint) return before;
|
|
166
|
+
// Another request may already be reading the same change: it is shared.
|
|
167
|
+
const current = this.#cache.get(type);
|
|
168
|
+
if (current && current !== previous) return current;
|
|
169
|
+
const reading = this.#read(type, fingerprint, before);
|
|
170
|
+
this.#cache.set(type, reading);
|
|
171
|
+
reading.catch(() => {
|
|
172
|
+
if (this.#cache.get(type) === reading) this.#cache.delete(type);
|
|
173
|
+
});
|
|
174
|
+
return reading;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
async #read(type: string, fingerprint: string, before: KeptItems | undefined): Promise<KeptItems> {
|
|
178
|
+
let rows: Item[];
|
|
179
|
+
if (!before) {
|
|
180
|
+
rows = (await this.#db.query("SELECT * FROM brim_items WHERE type = ?", [type])).map(toItem);
|
|
181
|
+
} else {
|
|
182
|
+
// What every item is now, in a few bytes each; the items edited since are read whole.
|
|
183
|
+
const now = await this.#db.query(
|
|
184
|
+
"SELECT id, updated_at, position, translation_of, visibility FROM brim_items WHERE type = ?",
|
|
185
|
+
[type],
|
|
186
|
+
);
|
|
187
|
+
const known = new Map(before.rows.map((item) => [item.id, item]));
|
|
188
|
+
const changed = now
|
|
189
|
+
.filter((row) => known.get(String(row.id))?.updatedAt !== String(row.updated_at))
|
|
190
|
+
.map((row) => String(row.id));
|
|
191
|
+
const fresh = new Map<string, Item>();
|
|
192
|
+
for (let start = 0; start < changed.length; start += 100) {
|
|
193
|
+
const ids = changed.slice(start, start + 100);
|
|
194
|
+
const read = await this.#db.query(
|
|
195
|
+
`SELECT * FROM brim_items WHERE id IN (${ids.map(() => "?").join(", ")})`,
|
|
196
|
+
ids,
|
|
197
|
+
);
|
|
198
|
+
for (const row of read) fresh.set(String(row.id), toItem(row));
|
|
199
|
+
}
|
|
200
|
+
rows = now.flatMap((row) => {
|
|
201
|
+
const id = String(row.id);
|
|
202
|
+
const item = fresh.get(id) ?? known.get(id);
|
|
203
|
+
if (!item) return [];
|
|
204
|
+
// A move or a lost original changes these without touching `updated_at`.
|
|
205
|
+
return [
|
|
206
|
+
{
|
|
207
|
+
...item,
|
|
208
|
+
position: Number(row.position ?? 0),
|
|
209
|
+
translationOf: row.translation_of == null ? null : String(row.translation_of),
|
|
210
|
+
visibility: row.visibility === "private" ? "private" : "published",
|
|
211
|
+
} satisfies Item,
|
|
212
|
+
];
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
// Listed, a translation takes its original's place (see `PLACE`).
|
|
216
|
+
const byId = new Map(rows.map((item) => [item.id, item.position]));
|
|
217
|
+
const items = rows.map((item) => ({
|
|
218
|
+
...item,
|
|
219
|
+
position: (item.translationOf !== null ? byId.get(item.translationOf) : undefined) ?? item.position,
|
|
220
|
+
}));
|
|
221
|
+
return { fingerprint, rows, items };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Changes whenever an item of the type is added, removed, edited (`updated_at`), shown or hidden, or moved
|
|
226
|
+
* (positions weighted by a hash of each id, so swapping two items changes the sum).
|
|
227
|
+
*/
|
|
228
|
+
async #fingerprint(type: string): Promise<string> {
|
|
229
|
+
const rows = await this.#db.query(
|
|
230
|
+
`SELECT COUNT(*) AS n, MAX(updated_at) AS changed,
|
|
231
|
+
SUM(position * ((unicode(substr(id, 1, 1)) * 65599 + unicode(substr(id, 2, 1)) * 257
|
|
232
|
+
+ unicode(substr(id, 3, 1)) * 31 + unicode(substr(id, 4, 1))) % 1000003)) AS places,
|
|
233
|
+
SUM(length(COALESCE(translation_of, ''))) AS links,
|
|
234
|
+
SUM(visibility = 'published') AS shown
|
|
235
|
+
FROM brim_items WHERE type = ?`,
|
|
236
|
+
[type],
|
|
237
|
+
);
|
|
238
|
+
const row = rows[0] ?? {};
|
|
239
|
+
return `${row.n}|${row.changed}|${row.places}|${row.links}|${row.shown}`;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** The item and its translations: everything written first as `item` or its original, in every language. */
|
|
243
|
+
async translations(item: Item): Promise<Item[]> {
|
|
244
|
+
const original = item.translationOf ?? item.id;
|
|
245
|
+
const rows = await this.#db.query("SELECT * FROM brim_items WHERE id = ? OR translation_of = ? ORDER BY locale", [
|
|
246
|
+
original,
|
|
247
|
+
original,
|
|
248
|
+
]);
|
|
249
|
+
return rows.map(toItem);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
async get(id: string): Promise<Item | undefined> {
|
|
253
|
+
const rows = await this.#db.query("SELECT * FROM brim_items WHERE id = ?", [id]);
|
|
254
|
+
return rows[0] ? toItem(rows[0]) : undefined;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* `draft` must already be validated: see `parseItem`. `locale` and `translationOf` are checked by the caller:
|
|
259
|
+
* a language of the site, and an item of the same type written first.
|
|
260
|
+
*/
|
|
261
|
+
async create(
|
|
262
|
+
type: string,
|
|
263
|
+
draft: ItemDraft,
|
|
264
|
+
options: { locale?: string; translationOf?: string | null } = {},
|
|
265
|
+
): Promise<Item> {
|
|
266
|
+
const locale = options.locale ?? "";
|
|
267
|
+
await this.#assertSlugFree(type, locale, draft.slug, undefined);
|
|
268
|
+
const now = new Date().toISOString();
|
|
269
|
+
// A new item goes last among the items of its type and language.
|
|
270
|
+
const last = await this.#db.query(
|
|
271
|
+
"SELECT COALESCE(MAX(position), 0) AS last FROM brim_items WHERE type = ? AND locale = ?",
|
|
272
|
+
[type, locale],
|
|
273
|
+
);
|
|
274
|
+
const item: Item = {
|
|
275
|
+
id: randomUUID(),
|
|
276
|
+
type,
|
|
277
|
+
...draft,
|
|
278
|
+
locale,
|
|
279
|
+
translationOf: options.translationOf ?? null,
|
|
280
|
+
position: Number(last[0]?.last ?? 0) + 1,
|
|
281
|
+
createdAt: now,
|
|
282
|
+
updatedAt: now,
|
|
283
|
+
};
|
|
284
|
+
await this.#db.query(
|
|
285
|
+
`INSERT INTO brim_items (id, type, locale, translation_of, slug, title, visibility, data, position, created_at, updated_at)
|
|
286
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
287
|
+
[
|
|
288
|
+
item.id,
|
|
289
|
+
type,
|
|
290
|
+
locale,
|
|
291
|
+
item.translationOf,
|
|
292
|
+
item.slug,
|
|
293
|
+
item.title,
|
|
294
|
+
item.visibility,
|
|
295
|
+
JSON.stringify(item.data),
|
|
296
|
+
item.position,
|
|
297
|
+
now,
|
|
298
|
+
now,
|
|
299
|
+
],
|
|
300
|
+
);
|
|
301
|
+
return item;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** `draft` must already be validated: see `parseItem`. */
|
|
305
|
+
async update(existing: Item, draft: ItemDraft): Promise<Item> {
|
|
306
|
+
await this.#assertSlugFree(existing.type, existing.locale, draft.slug, existing.id);
|
|
307
|
+
const updatedAt = new Date().toISOString();
|
|
308
|
+
await this.#db.query(
|
|
309
|
+
"UPDATE brim_items SET slug = ?, title = ?, visibility = ?, data = ?, updated_at = ? WHERE id = ?",
|
|
310
|
+
[draft.slug, draft.title, draft.visibility, JSON.stringify(draft.data), updatedAt, existing.id],
|
|
311
|
+
);
|
|
312
|
+
return { ...existing, ...draft, updatedAt };
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Puts back an item that was deleted, as it was (see the site's history). Its address must still be free; a
|
|
317
|
+
* translation whose original is gone too comes back as an item of its own.
|
|
318
|
+
*/
|
|
319
|
+
async restore(item: Item): Promise<Item> {
|
|
320
|
+
await this.#assertSlugFree(item.type, item.locale, item.slug, undefined);
|
|
321
|
+
const original = item.translationOf ? await this.get(item.translationOf) : undefined;
|
|
322
|
+
const restored: Item = {
|
|
323
|
+
...item,
|
|
324
|
+
translationOf: original ? original.id : null,
|
|
325
|
+
updatedAt: new Date().toISOString(),
|
|
326
|
+
};
|
|
327
|
+
await this.#db.query(
|
|
328
|
+
`INSERT INTO brim_items (id, type, locale, translation_of, slug, title, visibility, data, position, created_at, updated_at)
|
|
329
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
330
|
+
[
|
|
331
|
+
restored.id,
|
|
332
|
+
restored.type,
|
|
333
|
+
restored.locale,
|
|
334
|
+
restored.translationOf,
|
|
335
|
+
restored.slug,
|
|
336
|
+
restored.title,
|
|
337
|
+
restored.visibility,
|
|
338
|
+
JSON.stringify(restored.data),
|
|
339
|
+
restored.position ?? 0,
|
|
340
|
+
restored.createdAt,
|
|
341
|
+
restored.updatedAt,
|
|
342
|
+
],
|
|
343
|
+
);
|
|
344
|
+
return restored;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Puts the items of a type in the order given: `ids` are its items written first (not translations, which follow
|
|
349
|
+
* their original), first to last. Items left out keep their places after those given.
|
|
350
|
+
*/
|
|
351
|
+
async reorder(type: string, ids: string[]): Promise<Item[]> {
|
|
352
|
+
const items = (await this.list(type, { sort: "position" })).filter((item) => item.translationOf === null);
|
|
353
|
+
const byId = new Map(items.map((item) => [item.id, item]));
|
|
354
|
+
const unknown = ids.filter((id) => !byId.has(id));
|
|
355
|
+
if (unknown.length > 0) {
|
|
356
|
+
throw new ValidationError(`Not items of "${type}" written first: ${unknown.slice(0, 5).join(", ")}.`);
|
|
357
|
+
}
|
|
358
|
+
if (new Set(ids).size !== ids.length) throw new ValidationError("An item is listed twice.");
|
|
359
|
+
const given = new Set(ids);
|
|
360
|
+
const order = [...ids, ...items.filter((item) => !given.has(item.id)).map((item) => item.id)];
|
|
361
|
+
await this.#db.batch(
|
|
362
|
+
order.map((id, index) => ({ sql: "UPDATE brim_items SET position = ? WHERE id = ?", args: [index + 1, id] })),
|
|
363
|
+
);
|
|
364
|
+
return order.map((id, index) => ({ ...(byId.get(id) as Item), position: index + 1 }));
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Makes `originalId` the original of the items `translationIds` names again (those that still exist and are not
|
|
369
|
+
* the original itself). An original that is put back after being removed takes back the translations it had
|
|
370
|
+
* handed to one of them.
|
|
371
|
+
*/
|
|
372
|
+
async relink(originalId: string, translationIds: string[]): Promise<void> {
|
|
373
|
+
const ids = translationIds.filter((id) => id !== originalId);
|
|
374
|
+
if (ids.length === 0) return;
|
|
375
|
+
await this.#db.batch(
|
|
376
|
+
ids.map((id) => ({ sql: "UPDATE brim_items SET translation_of = ? WHERE id = ?", args: [originalId, id] })),
|
|
377
|
+
);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** The ids of the items that are translations of `id`. */
|
|
381
|
+
async translationIds(id: string): Promise<string[]> {
|
|
382
|
+
const rows = await this.#db.query("SELECT id FROM brim_items WHERE translation_of = ?", [id]);
|
|
383
|
+
return rows.map((row) => String(row.id));
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** An original that is removed hands its translations to the first of them, so they stay linked. */
|
|
387
|
+
async remove(id: string): Promise<void> {
|
|
388
|
+
const rows = await this.#db.query("SELECT id FROM brim_items WHERE translation_of = ? ORDER BY created_at", [id]);
|
|
389
|
+
const heir = rows[0] ? String(rows[0].id) : undefined;
|
|
390
|
+
await this.#db.batch([
|
|
391
|
+
{ sql: "DELETE FROM brim_items WHERE id = ?", args: [id] },
|
|
392
|
+
...(heir
|
|
393
|
+
? [
|
|
394
|
+
{ sql: "UPDATE brim_items SET translation_of = NULL WHERE id = ?", args: [heir] },
|
|
395
|
+
{ sql: "UPDATE brim_items SET translation_of = ? WHERE translation_of = ?", args: [heir, id] },
|
|
396
|
+
]
|
|
397
|
+
: []),
|
|
398
|
+
]);
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
async #assertSlugFree(type: string, locale: string, slug: string, exceptId: string | undefined): Promise<void> {
|
|
402
|
+
const rows = await this.#db.query("SELECT id FROM brim_items WHERE type = ? AND locale = ? AND slug = ?", [
|
|
403
|
+
type,
|
|
404
|
+
locale,
|
|
405
|
+
slug,
|
|
406
|
+
]);
|
|
407
|
+
if (rows[0] && rows[0].id !== exceptId) throw new ValidationError(`The address "${slug}" is already used.`);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function toItem(row: Row): Item {
|
|
412
|
+
return {
|
|
413
|
+
id: String(row.id),
|
|
414
|
+
type: String(row.type),
|
|
415
|
+
slug: String(row.slug),
|
|
416
|
+
title: String(row.title),
|
|
417
|
+
visibility: row.visibility === "private" ? "private" : "published",
|
|
418
|
+
data: JSON.parse(String(row.data)) as Record<string, unknown>,
|
|
419
|
+
locale: String(row.locale ?? ""),
|
|
420
|
+
translationOf: row.translation_of == null ? null : String(row.translation_of),
|
|
421
|
+
// Listed, a translation answers its original's place (see `PLACE`).
|
|
422
|
+
position: Number(row.place ?? row.position ?? 0),
|
|
423
|
+
createdAt: String(row.created_at),
|
|
424
|
+
updatedAt: String(row.updated_at),
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/** Turns untrusted input into an item of the given type, keeping only the fields it declares. */
|
|
429
|
+
export function parseItem(type: ContentType, input: Record<string, unknown>): ItemDraft {
|
|
430
|
+
const title = typeof input.title === "string" ? input.title.trim() : "";
|
|
431
|
+
if (title === "") throw new ValidationError("The title is required.");
|
|
432
|
+
if (title.length > MAX_TITLE) throw new ValidationError("The title is too long.");
|
|
433
|
+
|
|
434
|
+
const slug = typeof input.slug === "string" && input.slug.trim() !== "" ? input.slug.trim() : slugify(title);
|
|
435
|
+
if (!isSlug(slug)) throw new ValidationError("The address can only have lowercase letters, digits and dashes.");
|
|
436
|
+
|
|
437
|
+
if (input.visibility !== "private" && input.visibility !== "published") {
|
|
438
|
+
throw new ValidationError('"visibility" must be "private" or "published".');
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
const values = typeof input.data === "object" && input.data !== null ? (input.data as Record<string, unknown>) : {};
|
|
442
|
+
const data: Record<string, unknown> = {};
|
|
443
|
+
for (const field of type.fields) {
|
|
444
|
+
const value = values[field.name];
|
|
445
|
+
// A value can turn out empty once checked, e.g. tags that were only spaces.
|
|
446
|
+
const parsed = isEmpty(value) ? undefined : parseField(field, value);
|
|
447
|
+
if (isEmpty(parsed)) {
|
|
448
|
+
if (field.required) throw new ValidationError(`"${field.label}" is required.`);
|
|
449
|
+
} else {
|
|
450
|
+
data[field.name] = parsed;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
// A field in the type's address must give it a segment: "Ceramică" is `ceramica`, but "—" is nothing.
|
|
454
|
+
for (const name of itemPathFields(type)) {
|
|
455
|
+
const field = type.fields.find((candidate) => candidate.name === name);
|
|
456
|
+
if (data[name] !== undefined && slugify(String(data[name])) === "") {
|
|
457
|
+
throw new ValidationError(`"${field?.label ?? name}" is part of the item's address: use letters or digits.`);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
return { title, slug, visibility: input.visibility, data };
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
function isEmpty(value: unknown): boolean {
|
|
464
|
+
return value === undefined || value === null || value === "" || (Array.isArray(value) && value.length === 0);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
function parseField(field: ContentField, value: unknown): unknown {
|
|
468
|
+
const fail = (problem: string): never => {
|
|
469
|
+
throw new ValidationError(`"${field.label}" ${problem}.`);
|
|
470
|
+
};
|
|
471
|
+
const text = (): string => {
|
|
472
|
+
if (typeof value !== "string") return fail("must be text");
|
|
473
|
+
return value.length <= MAX_TEXT ? value : fail("is too long");
|
|
474
|
+
};
|
|
475
|
+
|
|
476
|
+
switch (field.type) {
|
|
477
|
+
case "text":
|
|
478
|
+
case "textarea":
|
|
479
|
+
return text();
|
|
480
|
+
case "email":
|
|
481
|
+
return EMAIL.test(text()) ? value : fail("must be an email address");
|
|
482
|
+
case "date":
|
|
483
|
+
return DATE.test(text()) ? value : fail("must be a date");
|
|
484
|
+
case "url":
|
|
485
|
+
return /^(https?:\/\/|\/(?!\/)|mailto:|tel:)/i.test(text()) ? value : fail("must be a link");
|
|
486
|
+
case "select":
|
|
487
|
+
return optionValues(field).includes(text()) ? value : fail("is not one of the choices");
|
|
488
|
+
case "number":
|
|
489
|
+
return typeof value === "number" && Number.isFinite(value) ? value : fail("must be a number");
|
|
490
|
+
case "boolean":
|
|
491
|
+
return typeof value === "boolean" ? value : fail("must be yes or no");
|
|
492
|
+
case "image":
|
|
493
|
+
return parseImage(asRecord(value, field));
|
|
494
|
+
case "gallery":
|
|
495
|
+
if (!Array.isArray(value) || value.length > MAX_GALLERY) return fail("must be a list of images");
|
|
496
|
+
return value.map((entry) => parseImage(asRecord(entry, field)));
|
|
497
|
+
case "richtext":
|
|
498
|
+
return parseRichText(asRecord(value, field));
|
|
499
|
+
case "blocks": {
|
|
500
|
+
// A text saved while the field was `richtext` is its one text block.
|
|
501
|
+
const entries = Array.isArray(value) ? value : blocksOf(value);
|
|
502
|
+
if (entries.length === 0 || entries.length > MAX_BLOCKS) return fail("must be a list of blocks");
|
|
503
|
+
return parseBlocks(field, entries);
|
|
504
|
+
}
|
|
505
|
+
case "tags":
|
|
506
|
+
return parseTags(value, field.label, field.options && optionValues(field));
|
|
507
|
+
case "keyvalue":
|
|
508
|
+
return parseRows(value, fail);
|
|
509
|
+
case "reference":
|
|
510
|
+
return parseReference(field, value, fail);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* A reference keeps the slug of the item it points at, or a list of them with `multiple`. Only the shape is checked
|
|
516
|
+
* here; that those items exist is checked by the server, which can see them (`checkReferences`).
|
|
517
|
+
*/
|
|
518
|
+
function parseReference(field: ContentField, value: unknown, fail: (problem: string) => never): string | string[] {
|
|
519
|
+
const slugs = (Array.isArray(value) ? value : [value]).map((entry) =>
|
|
520
|
+
typeof entry === "string" ? entry.trim() : entry,
|
|
521
|
+
);
|
|
522
|
+
if (!field.multiple && Array.isArray(value)) return fail("takes one item, not a list");
|
|
523
|
+
if (slugs.length > MAX_REFERENCES) return fail(`can point at ${MAX_REFERENCES} items at most`);
|
|
524
|
+
if (!slugs.every((slug): slug is string => typeof slug === "string" && isSlug(slug))) {
|
|
525
|
+
return fail("must name items by their address, e.g. ceramica");
|
|
526
|
+
}
|
|
527
|
+
return field.multiple ? [...new Set(slugs)] : (slugs[0] as string);
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/** Rows of a key–value list, a label and a value each, as text. Rows left wholly empty are dropped. */
|
|
531
|
+
function parseRows(value: unknown, fail: (problem: string) => never): KeyValueEntry[] {
|
|
532
|
+
if (!Array.isArray(value)) return fail("must be a list of rows, each with a label and a value");
|
|
533
|
+
if (value.length > MAX_ROWS) return fail(`can hold at most ${MAX_ROWS} rows`);
|
|
534
|
+
const rows: KeyValueEntry[] = [];
|
|
535
|
+
for (const entry of value) {
|
|
536
|
+
const row = typeof entry === "object" && entry !== null ? (entry as Record<string, unknown>) : undefined;
|
|
537
|
+
const { label, value: text } = row ?? {};
|
|
538
|
+
const isText = (part: unknown) => part === undefined || typeof part === "string";
|
|
539
|
+
if (!row || !isText(label) || !isText(text)) return fail("must be a list of rows, each with a label and a value");
|
|
540
|
+
const kept = { label: String(label ?? "").trim(), value: String(text ?? "").trim() };
|
|
541
|
+
if (kept.label === "" && kept.value === "") continue;
|
|
542
|
+
if (kept.label.length > MAX_ROW_LABEL || kept.value.length > MAX_TEXT) return fail("has a row that is too long");
|
|
543
|
+
rows.push(kept);
|
|
544
|
+
}
|
|
545
|
+
return rows;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/** Each block keeps an id of its own, is one the field offers, and holds what that block accepts. */
|
|
549
|
+
function parseBlocks(field: ContentField, entries: unknown[]): BlockEntry[] {
|
|
550
|
+
const offered: readonly string[] = field.blocks ?? BLOCK_TYPES;
|
|
551
|
+
const ids = new Set<string>();
|
|
552
|
+
return entries.map((input) => {
|
|
553
|
+
const entry = asRecord(input, field);
|
|
554
|
+
const { id } = entry;
|
|
555
|
+
if (typeof id !== "string" || !isNodeId(id) || ids.has(id)) {
|
|
556
|
+
throw new ValidationError(`"${field.label}" has a block without an id of its own.`);
|
|
557
|
+
}
|
|
558
|
+
ids.add(id);
|
|
559
|
+
if (typeof entry.type !== "string" || !offered.includes(entry.type)) {
|
|
560
|
+
throw new ValidationError(`"${field.label}" does not offer the block "${String(entry.type)}".`);
|
|
561
|
+
}
|
|
562
|
+
const type = entry.type as BlockType;
|
|
563
|
+
const value = asRecord(entry.value ?? {}, field);
|
|
564
|
+
// Every block type but rich text is one of Brim's blocks, checked against its own settings. Its layout is read
|
|
565
|
+
// before them, from the old size and alignment settings of a block saved without one.
|
|
566
|
+
return {
|
|
567
|
+
id,
|
|
568
|
+
type,
|
|
569
|
+
value: type === "richtext" ? { ...parseRichText(value) } : parseSettings(blockDefinitions[type]!, value),
|
|
570
|
+
layout: layoutOf(type, entry.layout, value),
|
|
571
|
+
};
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
function asRecord(value: unknown, field: ContentField): Record<string, unknown> {
|
|
576
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
577
|
+
throw new ValidationError(`"${field.label}" has the wrong shape.`);
|
|
578
|
+
}
|
|
579
|
+
return value as Record<string, unknown>;
|
|
580
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { Database } from "../db/database.ts";
|
|
2
|
+
import { siteScope, typeScope } from "./ids.ts";
|
|
3
|
+
|
|
4
|
+
const adopted = new WeakSet<Database>();
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* A site that turns languages on keeps what its owner saved before. Without languages the site's shared content
|
|
8
|
+
* (navbar, footer, `scope="site"` texts, Site Settings) is kept as `site` and a template's changes as
|
|
9
|
+
* `type:<key>`; with languages each language has its own, `site:<lang>` and `type:<key>:<lang>`. What was saved
|
|
10
|
+
* before becomes the default language's, once per server, in the database itself: the two updates find nothing
|
|
11
|
+
* once it is done, and a language that already has its own value keeps it. Unsaved changes (drafts) move too.
|
|
12
|
+
*/
|
|
13
|
+
export async function adoptLanguageScopes(db: Database, defaultLocale: string): Promise<void> {
|
|
14
|
+
if (adopted.has(db)) return;
|
|
15
|
+
adopted.add(db);
|
|
16
|
+
const site = siteScope(defaultLocale);
|
|
17
|
+
const suffix = typeScope("", defaultLocale).slice("type:".length);
|
|
18
|
+
try {
|
|
19
|
+
await db.batch([
|
|
20
|
+
{ sql: "UPDATE OR IGNORE brim_nodes SET scope = ? WHERE scope = 'site'", args: [site] },
|
|
21
|
+
{
|
|
22
|
+
sql: "UPDATE OR IGNORE brim_nodes SET scope = scope || ? WHERE scope LIKE 'type:%' AND scope NOT LIKE 'type:%:%'",
|
|
23
|
+
args: [suffix],
|
|
24
|
+
},
|
|
25
|
+
// A drafted element is keyed `<scope>\n<nodeId>`.
|
|
26
|
+
{
|
|
27
|
+
sql: "UPDATE OR IGNORE brim_drafts SET key = ? || substr(key, 5) WHERE target = 'node' AND key LIKE 'site' || char(10) || '%'",
|
|
28
|
+
args: [site],
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
sql: `UPDATE OR IGNORE brim_drafts SET key = substr(key, 1, instr(key, char(10)) - 1) || ? || substr(key, instr(key, char(10)))
|
|
32
|
+
WHERE target = 'node' AND key LIKE 'type:%' AND substr(key, 1, instr(key, char(10)) - 1) NOT LIKE 'type:%:%'`,
|
|
33
|
+
args: [suffix],
|
|
34
|
+
},
|
|
35
|
+
]);
|
|
36
|
+
} catch (error) {
|
|
37
|
+
adopted.delete(db);
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
}
|