@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.
Files changed (238) hide show
  1. package/LICENSE +110 -0
  2. package/README.md +22 -2
  3. package/bin/brim.js +5 -0
  4. package/dist/cli.js +3802 -0
  5. package/editor-dist/editor.css +1 -0
  6. package/editor-dist/editor.js +91 -0
  7. package/package.json +71 -3
  8. package/skills/brim-convert/SKILL.md +256 -0
  9. package/skills/brim-hosting/SKILL.md +221 -0
  10. package/src/astro-shim.d.ts +5 -0
  11. package/src/auth/accounts.ts +341 -0
  12. package/src/auth/password.ts +34 -0
  13. package/src/auth/permissions.ts +44 -0
  14. package/src/blocks/accordion/Accordion.astro +48 -0
  15. package/src/blocks/accordion/accordion.css +63 -0
  16. package/src/blocks/analytics/Analytics.astro +45 -0
  17. package/src/blocks/analytics/ConsentBanner.astro +41 -0
  18. package/src/blocks/analytics/analytics.client.ts +125 -0
  19. package/src/blocks/analytics/analytics.css +51 -0
  20. package/src/blocks/analytics/consent.ts +51 -0
  21. package/src/blocks/button/Button.astro +64 -0
  22. package/src/blocks/button/button.css +100 -0
  23. package/src/blocks/carousel/Carousel.astro +140 -0
  24. package/src/blocks/carousel/carousel.client.ts +153 -0
  25. package/src/blocks/carousel/carousel.css +181 -0
  26. package/src/blocks/data/icons.ts +285 -0
  27. package/src/blocks/data/image-shapes.ts +91 -0
  28. package/src/blocks/data/social-icons.ts +41 -0
  29. package/src/blocks/data/social-networks.ts +256 -0
  30. package/src/blocks/divider/Divider.astro +27 -0
  31. package/src/blocks/divider/divider.css +17 -0
  32. package/src/blocks/form/Captcha.astro +27 -0
  33. package/src/blocks/form/Form.astro +250 -0
  34. package/src/blocks/form/FormField.astro +138 -0
  35. package/src/blocks/form/Newsletter.astro +80 -0
  36. package/src/blocks/form/form.client.ts +339 -0
  37. package/src/blocks/form/form.css +271 -0
  38. package/src/blocks/gallery/ImageGallery.astro +126 -0
  39. package/src/blocks/gallery/gallery.css +43 -0
  40. package/src/blocks/gallery/lightbox.client.ts +178 -0
  41. package/src/blocks/gallery/lightbox.css +134 -0
  42. package/src/blocks/icon/Icon.astro +41 -0
  43. package/src/blocks/icon/icon.css +16 -0
  44. package/src/blocks/image/Image.astro +158 -0
  45. package/src/blocks/image/image.css +42 -0
  46. package/src/blocks/images.ts +64 -0
  47. package/src/blocks/in-editor.client.ts +8 -0
  48. package/src/blocks/listing/Listing.astro +288 -0
  49. package/src/blocks/listing/ListingCards.astro +48 -0
  50. package/src/blocks/listing/listing.css +136 -0
  51. package/src/blocks/listing/query.ts +363 -0
  52. package/src/blocks/map/Map.astro +75 -0
  53. package/src/blocks/map/map.css +32 -0
  54. package/src/blocks/schemas/accordion.ts +118 -0
  55. package/src/blocks/schemas/button.ts +78 -0
  56. package/src/blocks/schemas/carousel.ts +133 -0
  57. package/src/blocks/schemas/divider.ts +29 -0
  58. package/src/blocks/schemas/form-field-types.ts +29 -0
  59. package/src/blocks/schemas/form.ts +350 -0
  60. package/src/blocks/schemas/icon.ts +24 -0
  61. package/src/blocks/schemas/image-gallery.ts +54 -0
  62. package/src/blocks/schemas/image.ts +87 -0
  63. package/src/blocks/schemas/index.ts +33 -0
  64. package/src/blocks/schemas/listing.ts +14 -0
  65. package/src/blocks/schemas/map.ts +81 -0
  66. package/src/blocks/schemas/newsletter.ts +324 -0
  67. package/src/blocks/schemas/social-media.ts +348 -0
  68. package/src/blocks/schemas/text.ts +151 -0
  69. package/src/blocks/schemas/video.ts +57 -0
  70. package/src/blocks/search/Search.astro +147 -0
  71. package/src/blocks/search/search.css +69 -0
  72. package/src/blocks/search/state.ts +28 -0
  73. package/src/blocks/settings.ts +94 -0
  74. package/src/blocks/social/SocialMedia.astro +102 -0
  75. package/src/blocks/social/social-links.ts +16 -0
  76. package/src/blocks/social/social.css +31 -0
  77. package/src/blocks/theme.ts +35 -0
  78. package/src/blocks/types.ts +52 -0
  79. package/src/blocks/video/Video.astro +90 -0
  80. package/src/blocks/video/video-source.ts +77 -0
  81. package/src/blocks/video/video.client.ts +43 -0
  82. package/src/blocks/video/video.css +29 -0
  83. package/src/check.ts +1119 -0
  84. package/src/cli.ts +493 -0
  85. package/src/components/Blocks.astro +68 -0
  86. package/src/components/Field.astro +61 -0
  87. package/src/components/Footer.astro +36 -0
  88. package/src/components/Link.astro +18 -0
  89. package/src/components/MobileMenu.astro +77 -0
  90. package/src/components/Navbar.astro +42 -0
  91. package/src/components/RichText.astro +32 -0
  92. package/src/components/Seo.astro +202 -0
  93. package/src/components/Setting.astro +46 -0
  94. package/src/components/Shared.astro +17 -0
  95. package/src/components/Text.astro +91 -0
  96. package/src/components/blocks.css +86 -0
  97. package/src/components/index.ts +27 -0
  98. package/src/components/mobile-menu.client.ts +21 -0
  99. package/src/components/mobile-menu.css +52 -0
  100. package/src/components/text.css +48 -0
  101. package/src/config.ts +413 -0
  102. package/src/content/block-layout.ts +63 -0
  103. package/src/content/block-values.ts +48 -0
  104. package/src/content/content-check.ts +174 -0
  105. package/src/content/content-types.ts +408 -0
  106. package/src/content/drafts.ts +115 -0
  107. package/src/content/feed.ts +237 -0
  108. package/src/content/field-types.ts +107 -0
  109. package/src/content/history.ts +140 -0
  110. package/src/content/ids.ts +50 -0
  111. package/src/content/image-size.ts +212 -0
  112. package/src/content/image-sizes.ts +126 -0
  113. package/src/content/item-fields.ts +110 -0
  114. package/src/content/item-head.ts +126 -0
  115. package/src/content/item-image.ts +26 -0
  116. package/src/content/item-path.ts +122 -0
  117. package/src/content/items.ts +580 -0
  118. package/src/content/language-scopes.ts +40 -0
  119. package/src/content/media.ts +271 -0
  120. package/src/content/menus.ts +51 -0
  121. package/src/content/page-templates.ts +52 -0
  122. package/src/content/redirects.ts +112 -0
  123. package/src/content/references.ts +165 -0
  124. package/src/content/rich-text.ts +63 -0
  125. package/src/content/search.ts +167 -0
  126. package/src/content/seed.ts +229 -0
  127. package/src/content/site-settings.ts +111 -0
  128. package/src/content/sitemap.ts +143 -0
  129. package/src/content/store.ts +225 -0
  130. package/src/content/tags.ts +67 -0
  131. package/src/content/text-default.ts +139 -0
  132. package/src/content/types.ts +137 -0
  133. package/src/content/validate.ts +253 -0
  134. package/src/content/validation-error.ts +2 -0
  135. package/src/db/cached.ts +140 -0
  136. package/src/db/database.ts +15 -0
  137. package/src/db/libsql.ts +29 -0
  138. package/src/db/schema.ts +189 -0
  139. package/src/db/url.ts +44 -0
  140. package/src/editor/client/BlockSettings.tsx +1063 -0
  141. package/src/editor/client/Chrome.tsx +284 -0
  142. package/src/editor/client/ContentBrowser.tsx +1299 -0
  143. package/src/editor/client/Editor.tsx +1756 -0
  144. package/src/editor/client/HistoryPanel.tsx +114 -0
  145. package/src/editor/client/ImagesWidget.tsx +113 -0
  146. package/src/editor/client/Inspector.tsx +127 -0
  147. package/src/editor/client/ItemForm.tsx +535 -0
  148. package/src/editor/client/LinkWidget.tsx +440 -0
  149. package/src/editor/client/ListingPanel.tsx +99 -0
  150. package/src/editor/client/Login.tsx +338 -0
  151. package/src/editor/client/Menu.tsx +64 -0
  152. package/src/editor/client/PageSettings.tsx +270 -0
  153. package/src/editor/client/RedirectsSettings.tsx +130 -0
  154. package/src/editor/client/Resize.tsx +204 -0
  155. package/src/editor/client/Sidebar.tsx +51 -0
  156. package/src/editor/client/SiteMap.tsx +568 -0
  157. package/src/editor/client/SiteSettings.tsx +409 -0
  158. package/src/editor/client/TextTools.tsx +391 -0
  159. package/src/editor/client/Toolbar.tsx +449 -0
  160. package/src/editor/client/VideoUpload.tsx +251 -0
  161. package/src/editor/client/api.ts +417 -0
  162. package/src/editor/client/brand.ts +20 -0
  163. package/src/editor/client/connection.ts +98 -0
  164. package/src/editor/client/context.ts +19 -0
  165. package/src/editor/client/css.d.ts +2 -0
  166. package/src/editor/client/editor.css +4656 -0
  167. package/src/editor/client/fields.tsx +812 -0
  168. package/src/editor/client/icons.tsx +174 -0
  169. package/src/editor/client/keys.ts +15 -0
  170. package/src/editor/client/kinds.ts +289 -0
  171. package/src/editor/client/languages.ts +32 -0
  172. package/src/editor/client/main.tsx +100 -0
  173. package/src/editor/client/responses.ts +26 -0
  174. package/src/editor/client/rich-text.ts +326 -0
  175. package/src/editor/client/site-tree.ts +239 -0
  176. package/src/editor/client/theme.ts +55 -0
  177. package/src/editor/client/tsconfig.json +18 -0
  178. package/src/editor/client/tus.ts +137 -0
  179. package/src/editor/client/use-rect.ts +50 -0
  180. package/src/editor/client/widgets.tsx +1218 -0
  181. package/src/forms/captcha.ts +83 -0
  182. package/src/forms/define.ts +166 -0
  183. package/src/forms/fields.ts +197 -0
  184. package/src/forms/file-types.ts +108 -0
  185. package/src/forms/files.ts +216 -0
  186. package/src/forms/form-page.ts +9 -0
  187. package/src/forms/handler.ts +622 -0
  188. package/src/forms/spec.ts +89 -0
  189. package/src/forms/store.ts +96 -0
  190. package/src/forms/work.ts +50 -0
  191. package/src/icons/library.ts +144 -0
  192. package/src/icons/load.ts +63 -0
  193. package/src/index.ts +99 -0
  194. package/src/init.ts +257 -0
  195. package/src/integration.ts +469 -0
  196. package/src/mail/mailer.ts +197 -0
  197. package/src/mail/notify.ts +272 -0
  198. package/src/mail/settings.ts +173 -0
  199. package/src/mail/templates.ts +191 -0
  200. package/src/mcp/page-nodes.ts +209 -0
  201. package/src/mcp/server.ts +111 -0
  202. package/src/mcp/tools.ts +637 -0
  203. package/src/runtime/TemplatePage.astro +39 -0
  204. package/src/runtime/TemplatePageStatic.astro +13 -0
  205. package/src/runtime/admin-route.ts +80 -0
  206. package/src/runtime/connect.ts +53 -0
  207. package/src/runtime/content.ts +188 -0
  208. package/src/runtime/context.ts +131 -0
  209. package/src/runtime/form-files.ts +18 -0
  210. package/src/runtime/forms-route.ts +33 -0
  211. package/src/runtime/forms.ts +28 -0
  212. package/src/runtime/icons.ts +5 -0
  213. package/src/runtime/media.ts +175 -0
  214. package/src/runtime/middleware.ts +186 -0
  215. package/src/runtime/nav.ts +13 -0
  216. package/src/runtime/query-reads.ts +49 -0
  217. package/src/runtime/query-store.ts +16 -0
  218. package/src/runtime/request-state.ts +69 -0
  219. package/src/runtime/robots.ts +29 -0
  220. package/src/runtime/rss-static.ts +16 -0
  221. package/src/runtime/rss.ts +29 -0
  222. package/src/runtime/server.ts +29 -0
  223. package/src/runtime/sitemap.ts +34 -0
  224. package/src/runtime/template-paths.ts +34 -0
  225. package/src/runtime/uploads-route.ts +13 -0
  226. package/src/seed-cli.ts +253 -0
  227. package/src/server/auth.ts +31 -0
  228. package/src/server/fetch-image.ts +219 -0
  229. package/src/server/handler.ts +2106 -0
  230. package/src/server/http.ts +162 -0
  231. package/src/server/locales.ts +73 -0
  232. package/src/server/node.ts +57 -0
  233. package/src/server/query-params.ts +249 -0
  234. package/src/server/rate-limit.ts +72 -0
  235. package/src/server/video-host.ts +162 -0
  236. package/src/starter.ts +70 -0
  237. package/src/version.ts +4 -0
  238. package/src/virtual.d.ts +65 -0
@@ -0,0 +1,417 @@
1
+ import type { Icon, IconSearch, IconSetInfo } from "../../icons/library.ts";
2
+ import type { ContentType as DeclaredType } from "../../content/content-types.ts";
3
+
4
+ import type { PageTemplateInfo } from "../../content/page-templates.ts";
5
+
6
+ import { patientFetch } from "./connection.ts";
7
+
8
+ export type { ContentField } from "../../content/content-types.ts";
9
+
10
+ /** A content type as the editor gets it: its template stays on the server, `hasPage` says whether it has one. */
11
+ export type ContentType = Omit<DeclaredType, "component"> & { hasPage: boolean };
12
+
13
+ /** The site's own settings as the API answers them. */
14
+ export interface SiteSettingsView {
15
+ fields: import("../../content/content-types.ts").SiteSettingField[];
16
+ values: Record<string, unknown>;
17
+ }
18
+ export type { PageTemplateInfo } from "../../content/page-templates.ts";
19
+
20
+ export class ApiError extends Error {
21
+ readonly status: number;
22
+
23
+ constructor(status: number, message: string) {
24
+ super(message);
25
+ this.status = status;
26
+ }
27
+ }
28
+
29
+ /** What the site says about itself at /admin/api/info. */
30
+ export interface SiteInfo {
31
+ capabilities: string[];
32
+ /** The brand's colors from the site's config: offered first in color pickers, not changed in the editor. */
33
+ brandColors?: { name: string; value: string }[];
34
+ /** The site's languages, from Astro's i18n in its code; `null` for a site with one language. */
35
+ locales?: SiteLocales | null;
36
+ /** The site's name and what a page falls back to in search results and shared links. */
37
+ identity?: SiteIdentityInfo;
38
+ /** The host's own sign-in, offered on the sign-in form beside the password; `null` when the host has none. */
39
+ hostSignIn?: { url: string; name: string } | null;
40
+ }
41
+
42
+ export interface SiteIdentityInfo {
43
+ name: string | null;
44
+ /** e.g. `%s — Acme Studio`. */
45
+ titleTemplate: string | null;
46
+ description: string | null;
47
+ image: string | null;
48
+ }
49
+
50
+ export interface SiteLocales {
51
+ defaultLocale: string;
52
+ locales: string[];
53
+ prefixDefaultLocale?: boolean;
54
+ }
55
+
56
+ let siteInfo: Promise<SiteInfo> | undefined;
57
+ /** Asked once per editor session; a failure counts as a site that offers nothing extra. */
58
+ export function loadSiteInfo(): Promise<SiteInfo> {
59
+ siteInfo ??= api.info().catch(() => ({ capabilities: [] }));
60
+ return siteInfo;
61
+ }
62
+
63
+ export interface User {
64
+ email: string;
65
+ role: "owner" | "editor";
66
+ /** What the role allows, as the server lists it (see `auth/permissions.ts`); the server checks each request. */
67
+ permissions: Permission[];
68
+ }
69
+
70
+ export type Permission = "content" | "publish" | "pages" | "templates" | "responses" | "settings" | "users";
71
+
72
+ /** A change in the site's history, as the History panel lists it. */
73
+ export interface HistoryEntry {
74
+ id: string;
75
+ target: "node" | "item" | "page";
76
+ action: "changed" | "reset" | "deleted";
77
+ page: string;
78
+ title: string;
79
+ user: string;
80
+ at: string;
81
+ }
82
+
83
+ type Session = { user: Omit<User, "permissions">; permissions?: Permission[] };
84
+ /** The signed-in user with what they may do; a server from before roles were checked allows everything it did. */
85
+ const withPermissions = ({ user, permissions }: Session): { user: User } => ({
86
+ user: { ...user, permissions: permissions ?? ["content", "publish", "pages", "templates", "responses"] },
87
+ });
88
+
89
+ export type Visibility = "private" | "published";
90
+
91
+ export interface SeoSettings {
92
+ title?: string;
93
+ description?: string;
94
+ image?: string;
95
+ shareTitle?: string;
96
+ shareDescription?: string;
97
+ canonical?: string;
98
+ noindex?: boolean;
99
+ nofollow?: boolean;
100
+ }
101
+
102
+ export interface SitePage {
103
+ path: string;
104
+ visibility: Visibility;
105
+ seo: SeoSettings;
106
+ /** Set on pages added from a template, which the owner can rename and delete. */
107
+ template?: string;
108
+ title?: string;
109
+ }
110
+
111
+ /** An old address that sends visitors to another: a path of the site or a full address. */
112
+ export interface Redirect {
113
+ from: string;
114
+ to: string;
115
+ /** 302 instead of 301: search engines keep the old address. */
116
+ temporary?: boolean;
117
+ }
118
+
119
+ export interface NewPage {
120
+ template: string;
121
+ title: string;
122
+ path?: string;
123
+ }
124
+
125
+ export interface Item {
126
+ id: string;
127
+ type: string;
128
+ slug: string;
129
+ title: string;
130
+ visibility: Visibility;
131
+ data: Record<string, unknown>;
132
+ /** "" for the site's default language, else the language's code. */
133
+ locale: string;
134
+ /** The item this one translates; `null` for one written first. */
135
+ translationOf: string | null;
136
+ updatedAt: string;
137
+ }
138
+
139
+ export interface FormResponse {
140
+ id: string;
141
+ form: string;
142
+ title: string;
143
+ answers: {
144
+ label: string;
145
+ value: string;
146
+ choices?: { label: string; icon?: string; image?: string }[];
147
+ picked?: string[];
148
+ }[];
149
+ /** The files the visitor attached; each is downloaded from `/admin/api/responses/<id>/files/<file id>`. */
150
+ files?: { id: string; label: string; name: string; mime: string; size: number }[];
151
+ createdAt: string;
152
+ }
153
+
154
+ export interface MediaFile {
155
+ id: string;
156
+ url: string;
157
+ name: string;
158
+ /** "" for the gallery, or the key of the content type whose folder holds the image. */
159
+ folder: string;
160
+ /** A small copy for the picker, when the site's CDN makes them (`media.resize`). */
161
+ thumbnail?: string;
162
+ }
163
+
164
+ /** What the site's video host answers when asked for a place to upload a video. */
165
+ export interface VideoUploadTicket {
166
+ id: string;
167
+ upload: { protocol: string; endpoint: string; headers?: Record<string, string>; metadata?: Record<string, string> };
168
+ url: string;
169
+ posterUrl: string | null;
170
+ }
171
+
172
+ export interface VideoStatus {
173
+ id: string;
174
+ status: "processing" | "ready" | "failed";
175
+ progress: number;
176
+ url: string;
177
+ posterUrl: string | null;
178
+ }
179
+
180
+ /** One video already on the site's video host. */
181
+ export interface UploadedVideo {
182
+ id: string;
183
+ name: string;
184
+ /** In bytes. */
185
+ size: number;
186
+ status: "processing" | "ready" | "failed";
187
+ url: string;
188
+ posterUrl: string | null;
189
+ createdAt: string;
190
+ }
191
+
192
+ export type ItemDraft = Pick<Item, "slug" | "title" | "visibility" | "data">;
193
+
194
+ /**
195
+ * One change held in the draft, as the server answers it: the draft of one thing before and after it, `null` being
196
+ * no draft (what is saved). Undo writes `before` back, redo `after`.
197
+ */
198
+ export interface DraftChange {
199
+ target: "node" | "item" | "seo";
200
+ key: string;
201
+ page: string;
202
+ before: unknown;
203
+ after: unknown;
204
+ }
205
+
206
+ /** What every draft write answers: the change, and how many changes nobody has saved yet. */
207
+ export interface Drafted {
208
+ change: DraftChange;
209
+ drafts: number;
210
+ }
211
+
212
+ /** Identifies one editable node on the page being edited. */
213
+ export interface NodeRef {
214
+ path: string;
215
+ /** `template` on the page of an item: the node belongs to its type's template, shared by every item. */
216
+ scope: "page" | "site" | "template";
217
+ nodeId: string;
218
+ /** Set when the element shows a field of a content item: saving it changes the item. */
219
+ item?: string;
220
+ field?: string;
221
+ }
222
+
223
+ /** What the server said, or why it could not be understood (a proxy's page instead of the server's answer). */
224
+ async function answer<T>(response: Response, fallback: string): Promise<T> {
225
+ const payload = (await response.json().catch(() => null)) as (T & { error?: string }) | null;
226
+ if (!response.ok || payload === null) {
227
+ const away = payload === null && response.status >= 502 && response.status <= 504;
228
+ throw new ApiError(
229
+ response.status,
230
+ payload?.error ?? (away ? "The editor is not answering. Reload the page to try again." : fallback),
231
+ );
232
+ }
233
+ return payload;
234
+ }
235
+
236
+ /** Set while someone is editing: it asks them to sign in again and resolves once they have. */
237
+ let signInAgain: (() => Promise<void>) | null = null;
238
+
239
+ /**
240
+ * Called by the editor with a way to sign in again without leaving it, or `null` once nobody is editing. A session
241
+ * that runs out in the middle of a change then keeps the change: the request waits and is sent again after.
242
+ */
243
+ export function whenSignedOut(handler: (() => Promise<void>) | null): void {
244
+ signInAgain = handler;
245
+ }
246
+
247
+ /**
248
+ * `patientFetch`, sent again after signing in when the session ran out. A 401 means the server refused the request
249
+ * before doing anything, so sending it again cannot do it twice.
250
+ */
251
+ async function send(url: string, init: () => RequestInit): Promise<Response> {
252
+ for (;;) {
253
+ const response = await patientFetch(url, init);
254
+ if (response.status !== 401 || !signInAgain) return response;
255
+ await response.body?.cancel();
256
+ await signInAgain();
257
+ }
258
+ }
259
+
260
+ async function request<T>(method: string, route: string, body?: unknown): Promise<T> {
261
+ const init = (): RequestInit => ({
262
+ method,
263
+ ...(body !== undefined && { headers: { "content-type": "application/json" }, body: JSON.stringify(body) }),
264
+ });
265
+ // Signing in and out answer for themselves: a wrong password is a 401 too.
266
+ const url = `/admin/api${route}`;
267
+ const response = route === "/session" ? await patientFetch(url, init) : await send(url, init);
268
+ return answer<T>(response, "Something went wrong.");
269
+ }
270
+
271
+ /** The owner's own email server as the editor sees it: the password is only "saved" or not. */
272
+ export interface SmtpServerView {
273
+ host: string;
274
+ port: number;
275
+ secure: boolean;
276
+ user: string;
277
+ from: string;
278
+ hasPassword: boolean; // betterleaks:allow
279
+ }
280
+
281
+ /** The site's email settings, and who sends: the site's own server, the server's setup, the host, or nobody. */
282
+ export interface MailSettings {
283
+ /** The roles whose users all get every form message: owners, editors. */
284
+ notifyRoles: ("owner" | "editor")[];
285
+ /** Whether owners are among them; for clients from before roles could be chosen. */
286
+ notifyOwners: boolean;
287
+ notify: string[];
288
+ senderName: string;
289
+ smtp: SmtpServerView | null;
290
+ delivery: "site" | "server" | "service" | "none";
291
+ }
292
+
293
+ export interface MailSettingsUpdate {
294
+ notifyRoles: ("owner" | "editor")[];
295
+ notify: string[] | string;
296
+ senderName: string;
297
+ /** An empty password keeps the saved one. */
298
+ smtp: (Omit<SmtpServerView, "hasPassword"> & { password: string }) | null; // betterleaks:allow
299
+ }
300
+
301
+ export const api = {
302
+ session: () => request<Session>("GET", "/session").then(withPermissions),
303
+ // betterleaks:allow (a parameter named after what it carries, not a secret)
304
+ signIn: (email: string, password: string) => request<Session>("POST", "/session", { email, password }).then(withPermissions), // betterleaks:allow
305
+ signOut: () => request<object>("DELETE", "/session"),
306
+ /** "Forgot password": the answer is the same whether the email has an account or not. */
307
+ forgotPassword: (email: string) => // betterleaks:allow
308
+ request<{ sent: boolean; message: string }>("POST", "/password/forgot", { email }),
309
+ /** A new password with the emailed link's token; signs this browser in. */
310
+ resetPassword: (token: string, password: string) => // betterleaks:allow
311
+ request<Session>("POST", "/password/reset", { token, password }).then(withPermissions), // betterleaks:allow
312
+ /** A signed-in user's new password, given the current one; other sessions end, this one goes on. */
313
+ changePassword: (current: string, password: string) => // betterleaks:allow
314
+ request<{ user: User }>("PUT", "/password", { current, password }), // betterleaks:allow
315
+ /** With the SEO settings the editor's preview shows, drafts included. */
316
+ pages: () => request<{ pages: SitePage[] }>("GET", "/pages?draft"),
317
+ setVisibility: (path: string, visibility: Visibility) => request<SitePage>("PUT", "/pages", { path, visibility }),
318
+ /** Held in the draft until saved. */
319
+ setSeo: (path: string, seo: SeoSettings) => request<SitePage & Drafted>("PUT", "/pages", { path, seo, draft: true }),
320
+ movePage: (path: string, to: string) => request<{ page: SitePage }>("POST", "/pages/move", { path, to }),
321
+ redirects: () => request<{ redirects: Redirect[] }>("GET", "/redirects"),
322
+ setRedirects: (redirects: Redirect[]) => request<{ redirects: Redirect[] }>("PUT", "/redirects", { redirects }),
323
+ templates: () => request<{ templates: PageTemplateInfo[] }>("GET", "/templates"),
324
+ createPage: (page: NewPage) => request<{ page: SitePage }>("POST", "/pages", page),
325
+ deletePage: (path: string) => request<object>("DELETE", "/pages", { path }),
326
+ responses: () => request<{ responses: FormResponse[] }>("GET", "/responses"),
327
+ deleteResponse: (id: string) => request<object>("DELETE", "/responses", { id }),
328
+ media: (query: { search?: string; folder?: string; after?: string } = {}) => {
329
+ const params = new URLSearchParams();
330
+ if (query.search) params.set("search", query.search);
331
+ if (query.folder !== undefined) params.set("folder", query.folder);
332
+ if (query.after) params.set("after", query.after);
333
+ const search = params.toString();
334
+ return request<{ files: MediaFile[]; next?: string }>("GET", `/media${search ? `?${search}` : ""}`);
335
+ },
336
+ upload: async (file: File, folder = ""): Promise<MediaFile> => {
337
+ const response = await send("/admin/api/media", () => ({
338
+ method: "POST",
339
+ headers: { "x-file-name": encodeURIComponent(file.name), "x-media-folder": encodeURIComponent(folder) },
340
+ body: file,
341
+ }));
342
+ const payload = await answer<{ file?: MediaFile }>(response, "Could not upload the image.");
343
+ if (!payload.file) throw new ApiError(response.status, "Could not upload the image.");
344
+ return payload.file;
345
+ },
346
+ types: () => request<{ types: ContentType[] }>("GET", "/types"),
347
+ /** As the editor's preview shows them, drafts included. */
348
+ items: (type: string) => request<{ items: Item[] }>("GET", `/items?type=${encodeURIComponent(type)}&draft`),
349
+ createItem: (type: string, draft: ItemDraft, locale?: string) =>
350
+ request<{ item: Item }>("POST", "/items", { type, ...draft, ...(locale && { locale }) }),
351
+ /** A private copy of the item in another language, linked to it. */
352
+ translateItem: (id: string, locale: string) => request<{ item: Item }>("POST", "/items/translate", { id, locale }),
353
+ /** The page in another language, filled with this page's content where it has none yet. */
354
+ translatePage: (path: string, locale: string) =>
355
+ request<{ path: string; created: boolean; copied: number }>("POST", "/pages/translate", { path, locale }),
356
+ /** Saved at once, as from the item's form: whatever was drafted of the item is settled with it. */
357
+ updateItem: (id: string, draft: ItemDraft) => request<{ item: Item }>("PUT", "/items", { id, ...draft }),
358
+ /** The item's content held in the draft until saved; `path` is the page it was changed on. */
359
+ draftItem: (id: string, draft: ItemDraft, path: string) =>
360
+ request<{ item: Item } & Drafted>("PUT", "/items", { id, ...draft, path, draft: true }),
361
+ /** Who can see an item changes at once, never with the draft. */
362
+ setItemVisibility: (id: string, visibility: Visibility) =>
363
+ request<{ item: Item }>("PUT", "/items/visibility", { id, visibility }),
364
+ deleteItem: (id: string) => request<object>("DELETE", "/items", { id }),
365
+ /** The order of an `ordered` type's items written first, first to last. */
366
+ reorderItems: (type: string, ids: string[]) =>
367
+ request<{ items: { id: string; position: number }[] }>("PUT", "/items/order", { type, ids }),
368
+ /** Answers with the item when the node shows one of its fields. */
369
+ saveNode: (node: NodeRef, kind: string, value: unknown) =>
370
+ request<{ item?: Item } & Drafted>("PUT", "/nodes", { ...node, kind, value, draft: true }),
371
+ resetNode: (node: NodeRef) => request<Drafted>("DELETE", "/nodes", { ...node, draft: true }),
372
+ /** How many changes nobody has saved yet, and the pages they are on. */
373
+ drafts: () => request<{ drafts: number; pages: string[] }>("GET", "/drafts"),
374
+ /** Undo or redo: one thing's draft put back; answers with the item when it is one. */
375
+ putDraft: (change: Pick<DraftChange, "target" | "key" | "page">, value: unknown) =>
376
+ request<Drafted & { item?: Item }>("PUT", "/drafts", {
377
+ target: change.target,
378
+ key: change.key,
379
+ path: change.page,
380
+ value,
381
+ }),
382
+ saveDrafts: () =>
383
+ request<{ saved: number; failed: { page: string; error: string }[]; drafts: number }>("POST", "/drafts/save"),
384
+ discardDrafts: () => request<{ drafts: number }>("DELETE", "/drafts"),
385
+ /** The latest changes, on one page or (without a path) on the whole site. */
386
+ history: (path?: string) =>
387
+ request<{ history: HistoryEntry[] }>(
388
+ "GET",
389
+ path === undefined ? "/history" : `/history?path=${encodeURIComponent(path)}`,
390
+ ),
391
+ restoreHistory: (id: string) => request<object>("POST", "/history/restore", { id }),
392
+ /** The site's own settings (src/site-settings.ts): its fields and their values in one language. */
393
+ siteSettings: (locale?: string) =>
394
+ request<SiteSettingsView>("GET", `/site-settings${locale ? `?locale=${encodeURIComponent(locale)}` : ""}`),
395
+ saveSiteSettings: (values: Record<string, unknown>, locale?: string) =>
396
+ request<SiteSettingsView>("PUT", "/site-settings", { values, ...(locale && { locale }) }),
397
+ mail: () => request<MailSettings>("GET", "/mail"),
398
+ saveMail: (settings: MailSettingsUpdate) => request<MailSettings>("PUT", "/mail", settings),
399
+ testMail: () => request<{ sentTo: string }>("POST", "/mail/test"),
400
+ /** The icon sets this site offers and, with a value, the icon a block has now (`null` when it is unknown). */
401
+ icons: (value?: string) =>
402
+ request<{ sets: IconSetInfo[]; icon?: Icon | null }>(
403
+ "GET",
404
+ value === undefined ? "/icons" : `/icons?value=${encodeURIComponent(value)}`,
405
+ ),
406
+ /** The icons of one set whose name contains the search, the first of them. */
407
+ searchIcons: (set: string, search: string) =>
408
+ request<IconSearch>("GET", `/icons/${encodeURIComponent(set)}?q=${encodeURIComponent(search)}`),
409
+ /** What this site can do; `video-uploads` is there when a video host is set up. */
410
+ info: () => request<SiteInfo>("GET", "/info"),
411
+ createVideo: (file: { name: string; size: number; type: string }) =>
412
+ request<VideoUploadTicket>("POST", "/videos", file),
413
+ videoStatus: (id: string) => request<VideoStatus>("GET", `/videos/${encodeURIComponent(id)}`),
414
+ /** The videos on the site's video host, newest first; `supported` is false when the host does not list them. */
415
+ listVideos: () => request<{ supported: boolean; videos: UploadedVideo[] }>("GET", "/videos"),
416
+ deleteVideo: (id: string) => request<{ deleted: true }>("DELETE", `/videos/${encodeURIComponent(id)}`),
417
+ };
@@ -0,0 +1,20 @@
1
+ import { useEffect, useState } from "react";
2
+ import { loadSiteInfo } from "./api.ts";
3
+
4
+ export interface BrandColor {
5
+ name: string;
6
+ value: string;
7
+ }
8
+
9
+ /** The brand colors the site's config names; empty until known, and for sites that name none. */
10
+ export function useBrandColors(): BrandColor[] {
11
+ const [colors, setColors] = useState<BrandColor[]>([]);
12
+ useEffect(() => {
13
+ let current = true;
14
+ void loadSiteInfo().then((info) => current && setColors(info.brandColors ?? []));
15
+ return () => {
16
+ current = false;
17
+ };
18
+ }, []);
19
+ return colors;
20
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Keeps the editor working while its server is away for a moment — restarting, or started again by a host that
3
+ * stops it while nobody edits. A request that finds no server is asked again until one answers, and the editor
4
+ * shows that it is waiting instead of failing.
5
+ */
6
+
7
+ /** A proxy in front of the server answers these while the server itself is not there. */
8
+ const AWAY = new Set([502, 503, 504]);
9
+ /**
10
+ * A proxy answers these when it could not reach the server at all. A 504 is different: the server may have taken
11
+ * the request and been too slow to answer, so a request that adds something could be done twice.
12
+ */
13
+ const NEVER_REACHED = new Set([502, 503]);
14
+ /** Asking twice changes nothing more than asking once, so these are safe to repeat after a lost connection. */
15
+ const REPEATABLE = new Set(["GET", "HEAD", "PUT", "DELETE"]);
16
+
17
+ export interface Waiting {
18
+ /** How long to keep asking before giving up. */
19
+ patienceMs?: number;
20
+ /** The pause between two tries when the answer does not name one. */
21
+ pauseMs?: number;
22
+ fetch?: typeof fetch;
23
+ sleep?: (ms: number) => Promise<void>;
24
+ now?: () => number;
25
+ }
26
+
27
+ let waiting = 0;
28
+ const listeners = new Set<() => void>();
29
+
30
+ function change(by: number): void {
31
+ const before = waiting > 0;
32
+ waiting += by;
33
+ if (before !== waiting > 0) for (const listener of listeners) listener();
34
+ }
35
+
36
+ /** For `useSyncExternalStore`: true while a request waits for the server to come back. */
37
+ export const connection = {
38
+ subscribe(listener: () => void): () => void {
39
+ listeners.add(listener);
40
+ return () => listeners.delete(listener);
41
+ },
42
+ away: (): boolean => waiting > 0,
43
+ };
44
+
45
+ function pauseFrom(response: Response, fallback: number): number {
46
+ const seconds = Number(response.headers.get("retry-after"));
47
+ return Number.isFinite(seconds) && seconds > 0 ? Math.min(seconds * 1000, 10_000) : fallback;
48
+ }
49
+
50
+ /**
51
+ * `fetch`, patient with a server that is away: it asks again until the server answers or patience runs out, and
52
+ * then hands back the last answer (or the last failure). `init()` builds the request anew for each try.
53
+ *
54
+ * Only a proxy's "not there" answer is asked again. The server's own errors are JSON (a mail server that refused,
55
+ * a picture that could not be drawn) and are handed back as they are. A request that is safe to repeat is asked
56
+ * again after a 502, 503 or 504 and after a broken connection. A request that would add something twice (a POST)
57
+ * is asked again only after a 502 or 503, which the server never saw.
58
+ */
59
+ export async function patientFetch(
60
+ url: string,
61
+ init: () => RequestInit = () => ({}),
62
+ { patienceMs = 180_000, pauseMs = 2000, fetch: send = fetch, sleep = wait, now = Date.now }: Waiting = {},
63
+ ): Promise<Response> {
64
+ const deadline = now() + patienceMs;
65
+ let marked = false;
66
+ try {
67
+ for (;;) {
68
+ const request = init();
69
+ const repeatable = REPEATABLE.has((request.method ?? "GET").toUpperCase());
70
+ let pause = pauseMs;
71
+ try {
72
+ const response = await send(url, request);
73
+ if (!fromProxy(response, repeatable) || now() >= deadline) return response;
74
+ pause = pauseFrom(response, pauseMs);
75
+ await response.body?.cancel();
76
+ } catch (failure) {
77
+ if (!repeatable || now() >= deadline) throw failure;
78
+ }
79
+ if (!marked) {
80
+ marked = true;
81
+ change(1);
82
+ }
83
+ await sleep(pause);
84
+ }
85
+ } finally {
86
+ if (marked) change(-1);
87
+ }
88
+ }
89
+
90
+ /** A proxy's answer that the server is not there, which is worth asking again for this request. */
91
+ function fromProxy(response: Response, repeatable: boolean): boolean {
92
+ if (!(repeatable ? AWAY : NEVER_REACHED).has(response.status)) return false;
93
+ return !(response.headers.get("content-type") ?? "").includes("application/json");
94
+ }
95
+
96
+ function wait(ms: number): Promise<void> {
97
+ return new Promise((resolve) => setTimeout(resolve, ms));
98
+ }
@@ -0,0 +1,19 @@
1
+ import { createContext, useContext } from "react";
2
+ import type { SitePage } from "./api.ts";
3
+ import type { Viewport } from "./Toolbar.tsx";
4
+
5
+ /** What widgets need to know about the editor around them. */
6
+ export interface EditorEnvironment {
7
+ /** The site's pages, offered when a link is chosen. */
8
+ pages: SitePage[];
9
+ /** The preview size in use; per-breakpoint settings follow it. */
10
+ viewport: Viewport;
11
+ }
12
+
13
+ const EditorContext = createContext<EditorEnvironment>({ pages: [], viewport: "desktop" });
14
+
15
+ export const EditorProvider = EditorContext.Provider;
16
+
17
+ export function useEditor(): EditorEnvironment {
18
+ return useContext(EditorContext);
19
+ }
@@ -0,0 +1,2 @@
1
+ /** Stylesheets are bundled by the editor build; they have no exports. */
2
+ declare module "*.css";