@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,83 @@
1
+ /**
2
+ * An optional challenge on the site's forms, from Cloudflare Turnstile or hCaptcha. The trap field, the time it
3
+ * takes to fill a form and the token stop scripts that post; a challenge also stops a script that drives a real
4
+ * browser. The site key is public and set in the config; the secret key only ever comes from the server's
5
+ * environment (`BRIM_CAPTCHA_SECRET`), never from the code or the page.
6
+ */
7
+ export type CaptchaProvider = "turnstile" | "hcaptcha";
8
+
9
+ export interface CaptchaOptions {
10
+ provider: CaptchaProvider;
11
+ /** The public key the provider gives the site; the secret goes in `BRIM_CAPTCHA_SECRET`. */
12
+ siteKey: string;
13
+ }
14
+
15
+ interface Provider {
16
+ /** The provider's script, which draws a widget into every element with `widgetClass`. */
17
+ script: string;
18
+ widgetClass: string;
19
+ /** The hidden field the widget fills with its answer, inside the form. */
20
+ responseField: string;
21
+ verifyUrl: string;
22
+ }
23
+
24
+ export const CAPTCHA_PROVIDERS: Record<CaptchaProvider, Provider> = {
25
+ turnstile: {
26
+ script: "https://challenges.cloudflare.com/turnstile/v0/api.js",
27
+ widgetClass: "cf-turnstile",
28
+ responseField: "cf-turnstile-response",
29
+ verifyUrl: "https://challenges.cloudflare.com/turnstile/v0/siteverify",
30
+ },
31
+ hcaptcha: {
32
+ script: "https://js.hcaptcha.com/1/api.js",
33
+ widgetClass: "h-captcha",
34
+ responseField: "h-captcha-response",
35
+ verifyUrl: "https://api.hcaptcha.com/siteverify",
36
+ },
37
+ };
38
+
39
+ /** The challenge as the config names it, checked when the site starts; `undefined` when forms have none. */
40
+ export function resolveCaptcha(options: CaptchaOptions | undefined): CaptchaOptions | undefined {
41
+ if (!options) return undefined;
42
+ if (!Object.hasOwn(CAPTCHA_PROVIDERS, options.provider)) {
43
+ throw new Error(`brim({ forms: { captcha } }): provider must be "turnstile" or "hcaptcha".`);
44
+ }
45
+ const siteKey = typeof options.siteKey === "string" ? options.siteKey.trim() : "";
46
+ if (siteKey === "") throw new Error("brim({ forms: { captcha } }): siteKey is required (the provider's public key).");
47
+ return { provider: options.provider, siteKey };
48
+ }
49
+
50
+ /** What the forms handler checks a challenge with: the provider, and the secret read from the environment. */
51
+ export interface CaptchaCheck {
52
+ provider: CaptchaProvider;
53
+ secret: string | undefined;
54
+ }
55
+
56
+ export function captchaCheck(options: CaptchaOptions | undefined): CaptchaCheck | undefined {
57
+ return options && { provider: options.provider, secret: process.env.BRIM_CAPTCHA_SECRET?.trim() || undefined };
58
+ }
59
+
60
+ /**
61
+ * Asks the provider whether the answer a visitor's widget gave is genuine, and fresh: each answer is good once.
62
+ * A provider that does not answer in time counts as a failed check, so a form is never sent unchecked.
63
+ */
64
+ export async function verifyCaptcha(
65
+ check: CaptchaCheck & { secret: string },
66
+ answer: string,
67
+ remoteip: string,
68
+ fetcher: typeof fetch = fetch,
69
+ ): Promise<boolean> {
70
+ const body = new URLSearchParams({ secret: check.secret, response: answer, remoteip });
71
+ try {
72
+ const response = await fetcher(CAPTCHA_PROVIDERS[check.provider].verifyUrl, {
73
+ method: "POST",
74
+ body,
75
+ signal: AbortSignal.timeout(5_000),
76
+ });
77
+ if (!response.ok) return false;
78
+ const result = (await response.json()) as { success?: unknown };
79
+ return result.success === true;
80
+ } catch {
81
+ return false;
82
+ }
83
+ }
@@ -0,0 +1,166 @@
1
+ import { FILE_TYPES } from "./file-types.ts";
2
+ import {
3
+ CHOICE_TYPES,
4
+ FIELD_TYPES,
5
+ type FieldDisplay,
6
+ type FieldType,
7
+ type FieldWidth,
8
+ type FormChoice,
9
+ STEP,
10
+ } from "./fields.ts";
11
+
12
+ /**
13
+ * A form declared once and placed wherever the site needs it: the contact form of the footer, of the contact page
14
+ * and of a product's enquiry box are one form, instead of copies that drift apart.
15
+ *
16
+ * // src/forms.ts
17
+ * export const contact = defineForm({
18
+ * key: "contact",
19
+ * name: "Contact",
20
+ * fields: [
21
+ * { name: "name", label: "Nume", type: "text", required: true },
22
+ * { name: "email", label: "E-mail", type: "email", required: true },
23
+ * { name: "message", label: "Mesaj", type: "textarea", required: true },
24
+ * ],
25
+ * buttonText: "Trimite",
26
+ * successMessage: "Mulțumim! Revenim în curând.",
27
+ * });
28
+ *
29
+ * <Form form={contact} />
30
+ *
31
+ * A long form is asked in steps: an entry `{ type: "step", label: "Your home", help: "…" }` starts a step, with the
32
+ * fields written after it. Form draws the steps' tabs, the Back and Continue buttons, and checks each step before the
33
+ * next.
34
+ *
35
+ * Every place shows the same form and the owner edits it once (its fields, button, messages): it is the site's
36
+ * shared content, under the node id `form-<key>`. Its responses are listed under its name. A mistake in the
37
+ * declaration (an unknown field type, a name used twice) stops the site when it starts.
38
+ */
39
+ export interface FormFieldInput {
40
+ /** Letters, digits and `_`, starting with a letter: the key of the answer in each response. */
41
+ name: string;
42
+ label: string;
43
+ type: FieldType;
44
+ required?: boolean;
45
+ placeholder?: string;
46
+ /** Choices of a `select`, `radio` or `checkboxes` field: text, or `{ label, image, icon, description }` for a card. */
47
+ options?: (string | FormChoice)[];
48
+ /** `cards` shows a `radio` or `checkboxes` field's choices as boxes to click. */
49
+ display?: FieldDisplay;
50
+ /** `half` puts the field next to another half on a wide screen. */
51
+ width?: FieldWidth;
52
+ /** A line under the question. */
53
+ help?: string;
54
+ /** Asked only when another field has one of these answers: `{ field: "city", equals: "Other" }`. */
55
+ showWhen?: { field: string; equals: string | string[] };
56
+ /**
57
+ * Of a `file` field: the kinds of file it takes, out of `pdf`, `jpg`, `png`, `webp` and `gif`. Without it: PDF,
58
+ * JPEG, PNG and WebP. A file is recognised by its bytes, never by its name.
59
+ */
60
+ accept?: (keyof typeof FILE_TYPES)[];
61
+ /** Of a `file` field: several files (five at most) instead of one. */
62
+ multiple?: boolean;
63
+ }
64
+
65
+ /** Starts a step: the fields written after it, up to the next step, are asked together. */
66
+ export interface FormStepInput {
67
+ type: typeof STEP;
68
+ /** The step's title, on its tab. */
69
+ label: string;
70
+ /** A line under the title. */
71
+ help?: string;
72
+ }
73
+
74
+ export interface FormInput {
75
+ /** Lowercase letters, digits and dashes: names the form for good, so it never changes. */
76
+ key: string;
77
+ /** What the owner reads in the list of responses, and the form's heading unless `heading` is false. */
78
+ name: string;
79
+ /** `false` keeps `name` out of the page, for a form whose section already has a heading. */
80
+ heading?: boolean;
81
+ infoText?: string;
82
+ fields: (FormFieldInput | FormStepInput)[];
83
+ buttonText?: string;
84
+ /** The buttons between steps, in the site's language. */
85
+ nextText?: string;
86
+ backText?: string;
87
+ showConsent?: boolean;
88
+ consentText?: string;
89
+ consentLinkText?: string;
90
+ consentLinkUrl?: string;
91
+ consentRequired?: boolean;
92
+ successMessage?: string;
93
+ /**
94
+ * Starts the form with its confirmation on: once a message is kept, the visitor is emailed `confirmationSubject`
95
+ * and `confirmationMessage` at the address they wrote in the email field `confirmationField` (the form's first
96
+ * email field without it). The owner can turn it off, or change the words, in the editor.
97
+ */
98
+ confirmationEmail?: boolean;
99
+ confirmationField?: string;
100
+ confirmationSubject?: string;
101
+ confirmationMessage?: string;
102
+ /** The confirmation also lists the visitor's answers (text, shortened). Off by default: see the README. */
103
+ confirmationAnswers?: boolean;
104
+ }
105
+
106
+ export interface FormDefinition {
107
+ key: string;
108
+ /** The node the form's content is kept as, in the site's shared content. */
109
+ nodeId: string;
110
+ /** What the Form component starts from: the declaration, in the settings the owner edits. */
111
+ settings: Record<string, unknown>;
112
+ }
113
+
114
+ const KEY = /^[a-z][a-z0-9-]{0,40}$/;
115
+ const NAME = /^[a-z][a-z0-9_]{0,40}$/i;
116
+
117
+ export function defineForm(input: FormInput): FormDefinition {
118
+ const fail = (why: string): never => {
119
+ throw new Error(`Form "${input.key}" ${why}`);
120
+ };
121
+ if (!KEY.test(input.key)) fail("needs a key of lowercase letters, digits and dashes, starting with a letter.");
122
+ if (!input.name?.trim()) fail("needs a name: what the owner reads in the list of responses.");
123
+ if (!Array.isArray(input.fields) || !input.fields.some((field) => field.type !== STEP)) {
124
+ fail("needs at least one field.");
125
+ }
126
+ const names = new Set<string>();
127
+ for (const field of input.fields) {
128
+ if (field.type === STEP) {
129
+ if (!field.label?.trim()) fail("has a step without a label: the title on its tab.");
130
+ continue;
131
+ }
132
+ if (!NAME.test(field.name)) fail(`has a field named "${field.name}": use letters, digits and _ only.`);
133
+ if (names.has(field.name)) fail(`has two fields named "${field.name}".`);
134
+ names.add(field.name);
135
+ if (!FIELD_TYPES.includes(field.type)) {
136
+ fail(`has the field "${field.name}" of type "${field.type}": use one of ${FIELD_TYPES.join(", ")}.`);
137
+ }
138
+ if (CHOICE_TYPES.includes(field.type) && !field.options?.length) {
139
+ fail(`has the ${field.type} field "${field.name}" without options.`);
140
+ }
141
+ const unknown = field.type === "file" ? field.accept?.find((type) => !Object.hasOwn(FILE_TYPES, type)) : undefined;
142
+ if (unknown) {
143
+ fail(`has the file field "${field.name}" taking "${unknown}": use ${Object.keys(FILE_TYPES).join(", ")}.`);
144
+ }
145
+ }
146
+ if (input.confirmationEmail) {
147
+ const emails = input.fields
148
+ .filter((field) => field.type === "email")
149
+ .map((field) => (field as FormFieldInput).name);
150
+ if (emails.length === 0) fail("sends a confirmation but has no email field to send it to.");
151
+ if (input.confirmationField && !emails.includes(input.confirmationField)) {
152
+ fail(`sends its confirmation to "${input.confirmationField}", which is not one of its email fields.`);
153
+ }
154
+ }
155
+ const { key, name, heading, ...rest } = input;
156
+ return {
157
+ key,
158
+ nodeId: `form-${key}`,
159
+ settings: {
160
+ ...rest,
161
+ // The heading is the form's name unless the site leaves it out; responses keep the name either way.
162
+ formName: heading === false ? "" : name,
163
+ responsesName: name,
164
+ },
165
+ };
166
+ }
@@ -0,0 +1,197 @@
1
+ import { type FileType, fileTypes } from "./file-types.ts";
2
+
3
+ /** Kinds of field a form can show. BrimCMS had more; these are the ones that work without extra services. */
4
+ export const FIELD_TYPES = [
5
+ "text",
6
+ "name",
7
+ "email",
8
+ "tel",
9
+ "url",
10
+ "number",
11
+ "date",
12
+ "textarea",
13
+ "select",
14
+ "radio",
15
+ "checkboxes",
16
+ "checkbox",
17
+ // Files the visitor attaches: see `forms/files.ts` for what is taken and where it is kept.
18
+ "file",
19
+ ] as const;
20
+
21
+ /** Kinds of field whose answer is picked among `options`: one (`select`, `radio`) or several (`checkboxes`). */
22
+ export const CHOICE_TYPES: readonly FieldType[] = ["select", "radio", "checkboxes"];
23
+
24
+ export type FieldType = (typeof FIELD_TYPES)[number];
25
+
26
+ /**
27
+ * An entry of a form's fields that is not a question: it starts a step of a form asked in steps. Its `label` is the
28
+ * step's title and its `help` the line under it. Fields before the first step are the first step, untitled.
29
+ */
30
+ export const STEP = "step";
31
+
32
+ /** How much of the form's row a field takes: all of it, or half, next to another half. */
33
+ export const FIELD_WIDTHS = ["full", "half"] as const;
34
+ export type FieldWidth = (typeof FIELD_WIDTHS)[number];
35
+
36
+ export interface FormField {
37
+ name: string;
38
+ label: string;
39
+ type: FieldType;
40
+ required: boolean;
41
+ placeholder?: string;
42
+ /** Choices of a `select`, `radio` or `checkboxes` field. */
43
+ options?: string[];
44
+ /**
45
+ * The same choices with what a card shows besides the words: an `image` (a photo filling the card's top), an `icon`
46
+ * (a picture's address, or a short text such as an emoji) and a `description`. As long as `options`, in order.
47
+ */
48
+ choices?: FormChoice[];
49
+ /** How a `radio` or `checkboxes` field shows its choices: a plain list, or `cards` (boxes to click). */
50
+ display?: FieldDisplay;
51
+ /** `half` puts the field next to another half on a wide screen; on a phone every field takes the whole row. */
52
+ width?: FieldWidth;
53
+ /** A line under the question, telling what to write or why it is asked. */
54
+ help?: string;
55
+ /**
56
+ * Asked only when another field of the form has one of these answers (`{ field: "city", equals: ["Other"] }`):
57
+ * hidden, not checked and not sent otherwise. For a field of several choices, one of them ticked is enough.
58
+ */
59
+ showWhen?: FieldCondition;
60
+ /** Of a `file` field: the kinds of file it takes (`pdf`, `jpg`, `png`, `webp`, `gif`). Always set on one. */
61
+ accept?: FileType[];
62
+ /** Of a `file` field: it takes several files (five at most) instead of one. */
63
+ multiple?: boolean;
64
+ }
65
+
66
+ /** When a field is asked: another field's name and the answers that bring it. */
67
+ export interface FieldCondition {
68
+ field: string;
69
+ equals: string[];
70
+ }
71
+
72
+ /** Whether a field is asked, given the answers sent (a field of several choices answers with a list). */
73
+ export function fieldShown(field: Pick<FormField, "showWhen">, values: Record<string, unknown>): boolean {
74
+ if (!field.showWhen) return true;
75
+ const answer = values[field.showWhen.field];
76
+ const given = (Array.isArray(answer) ? answer : [answer]).filter((item): item is string => typeof item === "string");
77
+ return given.some((item) => field.showWhen?.equals.includes(item.trim()));
78
+ }
79
+
80
+ /** How a field with choices shows them. */
81
+ export const FIELD_DISPLAYS = ["list", "cards"] as const;
82
+ export type FieldDisplay = (typeof FIELD_DISPLAYS)[number];
83
+
84
+ /** One choice of a field, with what a card shows besides its words. */
85
+ export interface FormChoice {
86
+ label: string;
87
+ image?: string;
88
+ icon?: string;
89
+ description?: string;
90
+ }
91
+
92
+ /** A step of a form asked in steps: its title and line, and the fields it asks. */
93
+ export interface FormStep {
94
+ title: string;
95
+ intro?: string;
96
+ fields: FormField[];
97
+ }
98
+
99
+ /** A field as a site's own form markup gets it: with the `id` its input takes. */
100
+ export type ShownField = FormField & { id: string };
101
+
102
+ /** What a Form's function child gets: the steps and the fields, and `Field`, the component that draws one. */
103
+ export interface FormValue<FieldComponent = unknown> {
104
+ steps: (Omit<FormStep, "fields"> & { fields: ShownField[] })[];
105
+ fields: ShownField[];
106
+ Field: FieldComponent;
107
+ }
108
+
109
+ const NAME = /^[a-z][a-z0-9_]{0,40}$/i;
110
+
111
+ /** Keeps the fields this version can render and gives each a safe, unique name. */
112
+ export function formFields(input: unknown): FormField[] {
113
+ const fields: FormField[] = [];
114
+ const names = new Set<string>();
115
+
116
+ for (const entry of Array.isArray(input) ? input : []) {
117
+ if (typeof entry !== "object" || entry === null) continue;
118
+ const raw = entry as Record<string, unknown>;
119
+ const type = FIELD_TYPES.find((candidate) => candidate === raw.type);
120
+ const name = typeof raw.name === "string" && NAME.test(raw.name) ? raw.name : undefined;
121
+ if (!type || !name || names.has(name)) continue;
122
+ names.add(name);
123
+
124
+ const showWhen = condition(raw.showWhen, name);
125
+ const choices = Array.isArray(raw.options)
126
+ ? raw.options.map((option) => formChoice(option)).filter((choice) => choice !== undefined)
127
+ : undefined;
128
+ fields.push({
129
+ name,
130
+ type,
131
+ label: typeof raw.label === "string" && raw.label ? raw.label : name,
132
+ required: raw.required === true,
133
+ ...(typeof raw.placeholder === "string" && raw.placeholder && { placeholder: raw.placeholder }),
134
+ ...(choices?.length && { options: choices.map((choice) => choice.label), choices }),
135
+ ...(raw.display === "cards" && (type === "radio" || type === "checkboxes") && { display: "cards" as const }),
136
+ ...(raw.width === "half" && { width: "half" as const }),
137
+ ...(typeof raw.help === "string" && raw.help.trim() && { help: raw.help.trim() }),
138
+ ...(showWhen && { showWhen }),
139
+ ...(type === "file" && { accept: fileTypes(raw.accept), ...(raw.multiple === true && { multiple: true }) }),
140
+ });
141
+ }
142
+ return fields;
143
+ }
144
+
145
+ /**
146
+ * The form's fields in their steps. A form without step entries is one untitled step; a step without fields is
147
+ * left out, so a step the owner has just added does not show an empty page.
148
+ */
149
+ export function formSteps(input: unknown): FormStep[] {
150
+ const steps: FormStep[] = [];
151
+ let current: FormStep = { title: "", fields: [] };
152
+ const names = new Set<string>();
153
+ for (const entry of Array.isArray(input) ? input : []) {
154
+ if (typeof entry !== "object" || entry === null) continue;
155
+ const raw = entry as Record<string, unknown>;
156
+ if (raw.type === STEP) {
157
+ if (current.fields.length > 0) steps.push(current);
158
+ const intro = typeof raw.help === "string" ? raw.help.trim() : "";
159
+ current = { title: typeof raw.label === "string" ? raw.label.trim() : "", ...(intro && { intro }), fields: [] };
160
+ continue;
161
+ }
162
+ // Each field once, as formFields keeps it, in the step it is written under.
163
+ const [field] = formFields([raw]);
164
+ if (!field || names.has(field.name)) continue;
165
+ names.add(field.name);
166
+ current.fields.push(field);
167
+ }
168
+ if (current.fields.length > 0) steps.push(current);
169
+ return steps;
170
+ }
171
+
172
+ /** `{ field, equals }` with a field name other than the field's own, and one answer or several. */
173
+ function condition(input: unknown, own: string): FieldCondition | undefined {
174
+ if (typeof input !== "object" || input === null) return undefined;
175
+ const { field, equals } = input as Record<string, unknown>;
176
+ if (typeof field !== "string" || !NAME.test(field) || field === own) return undefined;
177
+ const answers = (Array.isArray(equals) ? equals : [equals])
178
+ .filter((item): item is string => typeof item === "string")
179
+ .map((item) => item.trim())
180
+ .filter(Boolean);
181
+ return answers.length ? { field, equals: answers } : undefined;
182
+ }
183
+
184
+ /** A choice is text, or `{ label, image?, icon?, description? }` (BrimCMS stored `{ value, label }`). */
185
+ function formChoice(option: unknown): FormChoice | undefined {
186
+ if (typeof option === "string") return option.trim() ? { label: option.trim() } : undefined;
187
+ if (typeof option !== "object" || option === null) return undefined;
188
+ const { label, value, image, icon, description } = option as Record<string, unknown>;
189
+ const text = String(label ?? value ?? "").trim();
190
+ if (!text) return undefined;
191
+ return {
192
+ label: text,
193
+ ...(typeof image === "string" && image.trim() && { image: image.trim() }),
194
+ ...(typeof icon === "string" && icon.trim() && { icon: icon.trim() }),
195
+ ...(typeof description === "string" && description.trim() && { description: description.trim() }),
196
+ };
197
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Files visitors attach to a form's message. Forms are the one place where anyone at all writes to the site, so
3
+ * every choice here is the narrow one:
4
+ * - a file is what its first bytes say it is, never what its name or declared type says, and only kinds that a
5
+ * browser cannot run are taken (no SVG, HTML, scripts, archives, office documents or executables);
6
+ * - its stored name is generated; the name the visitor gave is kept only as text, cleaned;
7
+ * - it is kept outside everything the site serves (never under `/uploads`, never in the media library), sealed with
8
+ * a key of the site's database, and read back only through the editor's API by a role that may read messages.
9
+ */
10
+ export const FILE_TYPES = {
11
+ pdf: { mime: "application/pdf", extension: "pdf", label: "PDF" },
12
+ jpg: { mime: "image/jpeg", extension: "jpg", label: "JPEG" },
13
+ png: { mime: "image/png", extension: "png", label: "PNG" },
14
+ webp: { mime: "image/webp", extension: "webp", label: "WebP" },
15
+ gif: { mime: "image/gif", extension: "gif", label: "GIF" },
16
+ } as const;
17
+
18
+ export type FileType = keyof typeof FILE_TYPES;
19
+
20
+ /** What a file field takes when it does not say: documents and photos. A GIF is taken only when the field asks. */
21
+ export const DEFAULT_FILE_TYPES: FileType[] = ["pdf", "jpg", "png", "webp"];
22
+
23
+ /** One file, at most. A phone's photo is 3 to 6 MB. */
24
+ export const MAX_FILE_BYTES = 8 * 1024 * 1024;
25
+ /**
26
+ * All the files of one message. The server refuses any request above a little over 10 MB (the adapter's
27
+ * `bodySizeLimit`), so a message cannot be allowed more than that.
28
+ */
29
+ export const MAX_MESSAGE_BYTES = 10 * 1024 * 1024;
30
+ /** The files of one message, over all its file fields; one field takes 1, or this many when it is `multiple`. */
31
+ export const MAX_FILES = 5;
32
+ /** What the other fields of a message may weigh beside its files: the spec, the answers, the multipart framing. */
33
+ export const MAX_FIELDS_BYTES = 512 * 1024;
34
+
35
+ const startsWith = (bytes: Uint8Array, signature: number[], at = 0): boolean =>
36
+ signature.every((byte, index) => bytes[at + index] === byte);
37
+ const ascii = (bytes: Uint8Array, start: number, end: number): string =>
38
+ String.fromCharCode(...bytes.subarray(start, end));
39
+
40
+ const SIGNATURES: Record<FileType, (bytes: Uint8Array) => boolean> = {
41
+ // "%PDF-" at the very start: readers accept it a little further in, which is how a file is two things at once.
42
+ pdf: (bytes) => ascii(bytes, 0, 5) === "%PDF-",
43
+ jpg: (bytes) => startsWith(bytes, [0xff, 0xd8, 0xff]),
44
+ png: (bytes) => startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
45
+ webp: (bytes) => ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 12) === "WEBP",
46
+ gif: (bytes) => ascii(bytes, 0, 6) === "GIF87a" || ascii(bytes, 0, 6) === "GIF89a",
47
+ };
48
+
49
+ /** The kind of file these bytes are, by how they start; `undefined` for anything Brim does not take. */
50
+ export function sniffFileType(bytes: Uint8Array): FileType | undefined {
51
+ return (Object.keys(SIGNATURES) as FileType[]).find((type) => SIGNATURES[type](bytes));
52
+ }
53
+
54
+ /**
55
+ * The kinds a field takes, from what its author wrote (`["pdf", "jpg"]`, or `"pdf, .jpg, image/png"` as BrimCMS
56
+ * kept it). Anything that is not one of Brim's kinds is dropped; a field left with none takes the default ones, so
57
+ * a mistake can only ever narrow what is taken, never widen it.
58
+ */
59
+ export function fileTypes(accept: unknown): FileType[] {
60
+ const words = (Array.isArray(accept) ? accept : typeof accept === "string" ? accept.split(/[\s,]+/) : [])
61
+ .filter((word): word is string => typeof word === "string")
62
+ .map((word) => word.trim().toLowerCase().replace(/^\./, ""));
63
+ const known = (Object.keys(FILE_TYPES) as FileType[]).filter(
64
+ (type) =>
65
+ words.includes(type) || words.includes(FILE_TYPES[type].mime) || (type === "jpg" && words.includes("jpeg")),
66
+ );
67
+ return known.length > 0 ? known : DEFAULT_FILE_TYPES;
68
+ }
69
+
70
+ /** The `accept` of the field's input: a hint for the visitor's file picker; the server checks the bytes. */
71
+ export function acceptAttribute(types: FileType[]): string {
72
+ return types.map((type) => `.${FILE_TYPES[type].extension}`).join(",");
73
+ }
74
+
75
+ /**
76
+ * The name a visitor's file had, as text safe to keep and show: no folders, no control characters, nothing a
77
+ * header or a file system reads as more than a name, and the extension of what the file really is. It is never
78
+ * used to store the file.
79
+ */
80
+ export function safeFileName(name: string, type: FileType): string {
81
+ const base = (name.split(/[\\/]/).pop() ?? "")
82
+ .normalize("NFC")
83
+ // Control characters, and the ones that end a header value or a path, or flip the reading direction.
84
+ .replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069"<>:|?*%;]/g, "")
85
+ .replace(/\.[^.]*$/, "")
86
+ .replace(/^[.\s]+/, "")
87
+ .trim()
88
+ .slice(0, 100);
89
+ return `${base || "file"}.${FILE_TYPES[type].extension}`;
90
+ }
91
+
92
+ /** A file kept with a message: what the editor lists. Its bytes are read through the API, by its ids. */
93
+ export interface FormFile {
94
+ id: string;
95
+ /** The label of the field it answers. */
96
+ label: string;
97
+ /** The name it had on the visitor's computer, cleaned (`safeFileName`). */
98
+ name: string;
99
+ mime: string;
100
+ size: number;
101
+ }
102
+
103
+ /** `1.4 MB`, `320 KB`: a file's size as people read it. */
104
+ export function fileSize(bytes: number): string {
105
+ return bytes >= 1024 * 1024
106
+ ? `${(bytes / (1024 * 1024)).toFixed(1)} MB`
107
+ : `${Math.max(1, Math.round(bytes / 1024))} KB`;
108
+ }