bearminion 1.6.0 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/dist/astro.d.ts +2 -2
- package/dist/astro.js +207 -5
- package/dist/content.d.ts +1 -1
- package/dist/content.js +2 -2
- package/dist/form-contract-BURSJP3Y.d.ts +48 -0
- package/dist/form-contract-CIDTNab-.js +7 -0
- package/dist/forms.d.ts +119 -0
- package/dist/forms.js +358 -0
- package/dist/index.d.ts +4 -3
- package/dist/index.js +3 -1
- package/dist/{options-DdCyRbPs.d.ts → options-BeJQnsZM.d.ts} +13 -1
- package/dist/{page-BFuPEq6Q.d.ts → page-BfI9cD8g.d.ts} +11 -7
- package/dist/ui/mount.js +54 -1
- package/package.json +5 -1
- package/dist/{reload-D0vwI0OT.js → reload-BPkPoQ-P.js} +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# bearminion
|
|
2
2
|
|
|
3
|
+
## 1.7.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 2978aaf: Run your own code behind the Contact form, with its keys on the server and in the environment. The new `bearminion/forms` entry has `defineForm(handler, options)`: put it in `src/forms/contact.ts` and add a few lines of glue for Vercel, Netlify, Cloudflare or an Astro endpoint (all in the Forms guide). The form always posts to `/api/contact`; nothing about it is stored in the content files. The handler receives the message and your environment, and returns nothing, `{ ok: true, message }`, `{ ok: false, error, fieldErrors }`, or throws a `FormError`; any other error becomes a plain "could not be delivered" for the visitor and goes to your log. It answers `POST` only, reads JSON, multipart and urlencoded posts, refuses posts over 64 KB and posts from other sites (`origins` lists the exceptions), and drops a filled trap field on the server too. It uses only `Request` and `Response`, so one file runs on every host. `astro dev` serves each file in `src/forms` at `/api/<name>`: a dry run that prints the message by default, and your handler for real with `BEARMINION_FORMS_LIVE=on` in `.env.local` (turn the route off with the `forms: false` option). Cloudflare Turnstile: set the public site key as `PUBLIC_TURNSTILE_SITE_KEY` where the site is built, and `defineForm(handler, { turnstile: true })` checks the token with `TURNSTILE_SECRET_KEY`; `verifyTurnstile` is exported too. A failed send now shows its error in a message at the bottom of the screen that stays until the visitor closes it. A handler's `{ ok: true, message }` replaces the thank-you text. The starter gets a `.env.example` listing those variables. The Forms guide is rewritten so you can set all of it up yourself.
|
|
8
|
+
- 2978aaf: The Contact form no longer says "Message sent." for a message that went nowhere. It posts with `fetch` to `/api/contact` and shows the states: sending, sent, an error from the handler, field errors under their fields, and no connection. A trap field and a 1.5 second minimum time drop what a script sends. While `src/forms/contact.ts` does not exist, `astro dev` and `astro build` print a warning (never an error), the section's settings in the editor show the same warning, and a visitor who sends the form gets an error. `bearminion` exports the types `FormSubmission` and `FormResult` for handlers you write yourself. `defineSection` takes a `form` option: the handler a section posts to, which the editor's sidebar reports on, and a new editor route `GET /forms` says whether its file exists. **Breaking for sites that set an endpoint:** the Contact section no longer has an `action` prop. Content version 3 drops `action` (and `format` and `turnstile`) from every Contact section, and the file is rewritten the next time it is saved. Copy a form service's address into a handler first: the Forms guide has complete files for Formspree and Web3Forms. New guide: Forms.
|
|
9
|
+
|
|
10
|
+
### Patch Changes
|
|
11
|
+
|
|
12
|
+
- 2978aaf: Fixed an error in the browser console, "Cannot read properties of undefined (reading 'toLowerCase')", when the browser autofilled a form on a page with the editor. Autofill sends key events without a `key`, and the editor's keyboard shortcuts assumed one.
|
|
13
|
+
- 60cfb70: The Contact form works with JavaScript off. A browser that posts the form itself is no longer left on the raw JSON answer: `defineForm` redirects it back to the page, to a "Message sent." block or a "not sent" line (only when the `Referer` is on the same site; otherwise the JSON answer stays). Pages with section motion were also invisible without JavaScript, because sections start transparent and a script reveals them; they now show.
|
|
14
|
+
- 2978aaf: Fix: a video uploaded in the editor now plays in the dev site straight away. Vite learns which files `public/` holds from its file watcher, and the editor keeps the videos folder out of that watcher so uploads do not reload the page, so a new video answered 404 until `astro dev` was restarted. The editor now tells Vite about the one file that was added or removed. The template's `astro.config.ts` also reads `BEARMINION_VIDEOS_DIR` (used by the tests, like the content and uploads overrides).
|
|
15
|
+
|
|
3
16
|
## 1.6.0
|
|
4
17
|
|
|
5
18
|
### Minor Changes
|
package/dist/astro.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as SectionRegistry, J as SiteDefinition, Y as SiteOf, Yt as ContentMigrator, k as ContentModel, t as Page, u as SectionOf } from "./page-
|
|
2
|
-
import { a as StoreKeyError, c as createFileStore, i as FileStoreOptions, n as EditorContext, o as StoreOperation, r as ContentStore, s as UploadStore, t as BearminionOptions } from "./options-
|
|
1
|
+
import { A as SectionRegistry, J as SiteDefinition, Y as SiteOf, Yt as ContentMigrator, k as ContentModel, t as Page, u as SectionOf } from "./page-BfI9cD8g.js";
|
|
2
|
+
import { a as StoreKeyError, c as createFileStore, i as FileStoreOptions, n as EditorContext, o as StoreOperation, r as ContentStore, s as UploadStore, t as BearminionOptions } from "./options-BeJQnsZM.js";
|
|
3
3
|
import { AstroIntegration } from "astro";
|
|
4
4
|
//#region src/integration.d.ts
|
|
5
5
|
interface BearminionIntegration extends AstroIntegration {
|
package/dist/astro.js
CHANGED
|
@@ -2,16 +2,16 @@ import { a as imageFields, c as ContentReadError, l as ContentValidationError, r
|
|
|
2
2
|
import { t as defaultTheme } from "./theme-DFjHjgFO.js";
|
|
3
3
|
import { i as isSystemPage, n as createPageSchema$1, r as createTolerantPageSchema, s as withoutOrphanSections, u as isOrphanSection } from "./page-NOFVEqn1.js";
|
|
4
4
|
import { a as DEFAULT_UPLOADS_DIR, i as DEFAULT_CONTENT_DIR, n as createMigrator, o as DEFAULT_VIDEOS_DIR, r as API_PREFIX, t as SCHEMA_VERSION_KEY } from "./migrate-b408EaLp.js";
|
|
5
|
-
import { a as JSON_BODY_LIMIT, c as isInside, d as resolveDir, f as resolveInside, i as IMAGE_BYTE_LIMIT, l as isLocalRequest, n as contentReloadPlugin, o as MULTIPART_BODY_LIMIT, r as dropEarlyReloadAfterSave, s as asDirectory, u as readSlug } from "./reload-
|
|
5
|
+
import { a as JSON_BODY_LIMIT, c as isInside, d as resolveDir, f as resolveInside, i as IMAGE_BYTE_LIMIT, l as isLocalRequest, n as contentReloadPlugin, o as MULTIPART_BODY_LIMIT, r as dropEarlyReloadAfterSave, s as asDirectory, u as readSlug } from "./reload-BPkPoQ-P.js";
|
|
6
6
|
import { S as isAssetPath, b as describeSiteRef, c as projectId, v as assetRefs, y as describePageRef } from "./draft-store-1Y4-sn45.js";
|
|
7
7
|
import { z } from "zod";
|
|
8
8
|
import fs from "node:fs";
|
|
9
|
-
import { fileURLToPath } from "node:url";
|
|
10
9
|
import path from "node:path";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
import { parseEnv, promisify } from "node:util";
|
|
11
12
|
import { randomBytes } from "node:crypto";
|
|
12
13
|
import { access, mkdir, readFile, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
|
|
13
14
|
import { execFile } from "node:child_process";
|
|
14
|
-
import { promisify } from "node:util";
|
|
15
15
|
//#region src/editor-client.ts
|
|
16
16
|
const VIRTUAL_ID = "virtual:bearminion-editor";
|
|
17
17
|
const RESOLVED_ID = `\0${VIRTUAL_ID}`;
|
|
@@ -35,6 +35,134 @@ function editorClientPlugin() {
|
|
|
35
35
|
};
|
|
36
36
|
}
|
|
37
37
|
//#endregion
|
|
38
|
+
//#region src/forms-dev.ts
|
|
39
|
+
/** Where the forms are and under which path, or `null` when the option turns them off. */
|
|
40
|
+
function resolveFormsConfig(option, root) {
|
|
41
|
+
if (option === false) return null;
|
|
42
|
+
const prefix = (option?.prefix ?? "/api").replace(/\/+$/, "");
|
|
43
|
+
return {
|
|
44
|
+
dir: resolveDir(root, option?.dir, "src/forms"),
|
|
45
|
+
prefix: prefix.startsWith("/") ? prefix : `/${prefix}`
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
const FORM_FILE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
|
|
49
|
+
const EXTENSIONS = [
|
|
50
|
+
".ts",
|
|
51
|
+
".mts",
|
|
52
|
+
".js",
|
|
53
|
+
".mjs"
|
|
54
|
+
];
|
|
55
|
+
const BODY_LIMIT = 1048576;
|
|
56
|
+
/** The file behind `name`, or `null` when there is none. `name` is checked, so it cannot leave the folder. */
|
|
57
|
+
function formFile(dir, name) {
|
|
58
|
+
if (!FORM_FILE.test(name)) return null;
|
|
59
|
+
for (const extension of EXTENSIONS) {
|
|
60
|
+
const file = path.join(dir, `${name}${extension}`);
|
|
61
|
+
if (fs.existsSync(file)) return file;
|
|
62
|
+
}
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
/** `.env`, `.env.local`, `.env.development` and `.env.development.local` of the project, later ones winning. */
|
|
66
|
+
function readDotEnv(root) {
|
|
67
|
+
const merged = {};
|
|
68
|
+
for (const name of [
|
|
69
|
+
".env",
|
|
70
|
+
".env.local",
|
|
71
|
+
".env.development",
|
|
72
|
+
".env.development.local"
|
|
73
|
+
]) try {
|
|
74
|
+
Object.assign(merged, parseEnv(fs.readFileSync(path.join(root, name), "utf8")));
|
|
75
|
+
} catch {}
|
|
76
|
+
return merged;
|
|
77
|
+
}
|
|
78
|
+
/** True when `BEARMINION_FORMS_LIVE=on` is in the environment or in the project's `.env` files. */
|
|
79
|
+
function formsAreLive(root) {
|
|
80
|
+
return (process.env.BEARMINION_FORMS_LIVE ?? readDotEnv(root).BEARMINION_FORMS_LIVE) === "on";
|
|
81
|
+
}
|
|
82
|
+
function isForm(value) {
|
|
83
|
+
return typeof value === "object" && value !== null && typeof value.fetch === "function";
|
|
84
|
+
}
|
|
85
|
+
function createFormsMiddleware(options) {
|
|
86
|
+
return (req, res, next) => {
|
|
87
|
+
const pathname = (req.url ?? "/").split("?")[0]?.replace(/\/+$/, "") ?? "";
|
|
88
|
+
if (!pathname.startsWith(`${options.prefix}/`)) {
|
|
89
|
+
next();
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
const name = pathname.slice(options.prefix.length + 1);
|
|
93
|
+
const file = formFile(options.dir, name);
|
|
94
|
+
if (!file) {
|
|
95
|
+
next();
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
answer(req, res, options, name, file).catch((error) => {
|
|
99
|
+
options.log.error(`/${name}: ${error instanceof Error ? error.stack ?? error.message : String(error)}`);
|
|
100
|
+
if (!res.headersSent) fail(res, 500, error instanceof Error ? error.message : "The form failed.");
|
|
101
|
+
});
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
function fail(res, status, error) {
|
|
105
|
+
res.statusCode = status;
|
|
106
|
+
res.setHeader("content-type", "application/json; charset=utf-8");
|
|
107
|
+
res.end(JSON.stringify({
|
|
108
|
+
ok: false,
|
|
109
|
+
error
|
|
110
|
+
}));
|
|
111
|
+
}
|
|
112
|
+
async function answer(req, res, options, name, file) {
|
|
113
|
+
const form = (await options.load(file))?.default;
|
|
114
|
+
if (!isForm(form)) {
|
|
115
|
+
const relative = path.relative(options.root, file).split(path.sep).join("/");
|
|
116
|
+
options.log.error(`${relative} must \`export default defineForm(...)\` from 'bearminion/forms'.`);
|
|
117
|
+
return fail(res, 500, `${relative} must export default defineForm(...).`);
|
|
118
|
+
}
|
|
119
|
+
const headers = new Headers();
|
|
120
|
+
for (const [key, value] of Object.entries(req.headers)) {
|
|
121
|
+
if (value === void 0) continue;
|
|
122
|
+
for (const item of Array.isArray(value) ? value : [value]) headers.append(key, item);
|
|
123
|
+
}
|
|
124
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
125
|
+
const body = method === "GET" || method === "HEAD" ? void 0 : await readLimited(req, BODY_LIMIT);
|
|
126
|
+
if (body === null) return fail(res, 413, "The message is too large.");
|
|
127
|
+
const request = new Request(`http://${req.headers.host ?? "localhost"}${req.url ?? "/"}`, {
|
|
128
|
+
method,
|
|
129
|
+
headers,
|
|
130
|
+
...body ? { body } : {}
|
|
131
|
+
});
|
|
132
|
+
const env = {
|
|
133
|
+
...readDotEnv(options.root),
|
|
134
|
+
...process.env
|
|
135
|
+
};
|
|
136
|
+
const response = await form.fetch(request, env, {
|
|
137
|
+
dev: true,
|
|
138
|
+
...options.live ? {} : { dryRun: (submission) => options.log.info(`/${name} received a message. Dry run: nothing was sent. Start the dev server with BEARMINION_FORMS_LIVE=on to run your handler.\n${JSON.stringify(submission, null, 2)}`) }
|
|
139
|
+
});
|
|
140
|
+
res.statusCode = response.status;
|
|
141
|
+
response.headers.forEach((value, key) => {
|
|
142
|
+
res.setHeader(key, value);
|
|
143
|
+
});
|
|
144
|
+
res.end(Buffer.from(await response.arrayBuffer()));
|
|
145
|
+
}
|
|
146
|
+
/** The body of the request, or `null` once it is over `limit` bytes. */
|
|
147
|
+
function readLimited(req, limit) {
|
|
148
|
+
return new Promise((resolve, reject) => {
|
|
149
|
+
const chunks = [];
|
|
150
|
+
let size = 0;
|
|
151
|
+
req.on("data", (chunk) => {
|
|
152
|
+
const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
|
|
153
|
+
size += buffer.length;
|
|
154
|
+
if (size > limit) {
|
|
155
|
+
resolve(null);
|
|
156
|
+
req.resume();
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
chunks.push(buffer);
|
|
160
|
+
});
|
|
161
|
+
req.on("end", () => resolve(new Uint8Array(Buffer.concat(chunks))));
|
|
162
|
+
req.on("error", reject);
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
//#endregion
|
|
38
166
|
//#region src/videos.ts
|
|
39
167
|
const EXTENSION$1 = {
|
|
40
168
|
mp4: ".mp4",
|
|
@@ -446,7 +574,8 @@ function resolveEditorContext(options, rootInput) {
|
|
|
446
574
|
videosDir
|
|
447
575
|
}),
|
|
448
576
|
migrator: createMigrator(options),
|
|
449
|
-
git: options?.git === true
|
|
577
|
+
git: options?.git === true,
|
|
578
|
+
formsDir: resolveFormsConfig(options?.forms, root)?.dir ?? null
|
|
450
579
|
};
|
|
451
580
|
}
|
|
452
581
|
//#endregion
|
|
@@ -714,6 +843,10 @@ async function handleEditorRequest(request, context, meta = {}) {
|
|
|
714
843
|
if (method === "POST") return createPage(request, context);
|
|
715
844
|
return methodNotAllowed(["GET", "POST"]);
|
|
716
845
|
}
|
|
846
|
+
if (parts.length === 1 && parts[0] === "forms") {
|
|
847
|
+
if (method === "GET") return getForms(context);
|
|
848
|
+
return methodNotAllowed(["GET"]);
|
|
849
|
+
}
|
|
717
850
|
if (parts.length === 1 && parts[0] === "git") {
|
|
718
851
|
if (method === "GET") return getGit(context);
|
|
719
852
|
return methodNotAllowed(["GET"]);
|
|
@@ -783,6 +916,27 @@ async function handleEditorRequest(request, context, meta = {}) {
|
|
|
783
916
|
}
|
|
784
917
|
return problem(404, "not_found", "Unknown editor API route.");
|
|
785
918
|
}
|
|
919
|
+
/**
|
|
920
|
+
* Which form handlers the sections post to, and whether their files exist right now. Read on every call, so a handler
|
|
921
|
+
* created while `astro dev` runs shows up at once.
|
|
922
|
+
*/
|
|
923
|
+
async function getForms(context) {
|
|
924
|
+
const handlers = {};
|
|
925
|
+
for (const definition of Object.values(context.sections)) {
|
|
926
|
+
const name = definition.form;
|
|
927
|
+
if (!name || handlers[name]) continue;
|
|
928
|
+
const file = context.formsDir ? formFile(context.formsDir, name) : null;
|
|
929
|
+
handlers[name] = { file: file ? relativeTo(context.root, file) : null };
|
|
930
|
+
}
|
|
931
|
+
return json(200, {
|
|
932
|
+
enabled: context.formsDir != null,
|
|
933
|
+
handlers
|
|
934
|
+
});
|
|
935
|
+
}
|
|
936
|
+
function relativeTo(root, file) {
|
|
937
|
+
const prefix = root.endsWith("/") || root.endsWith("\\") ? root : `${root}/`;
|
|
938
|
+
return file.startsWith(prefix) ? file.slice(prefix.length).replaceAll("\\", "/") : file;
|
|
939
|
+
}
|
|
786
940
|
async function getSchema(context) {
|
|
787
941
|
const sectionDefaults = {};
|
|
788
942
|
const sectionLabels = {};
|
|
@@ -795,8 +949,10 @@ async function getSchema(context) {
|
|
|
795
949
|
const fieldIcons = {};
|
|
796
950
|
const showWhen = {};
|
|
797
951
|
const fieldImages = {};
|
|
952
|
+
const sectionForms = {};
|
|
798
953
|
for (const definition of Object.values(context.sections)) {
|
|
799
954
|
const type = definition.type;
|
|
955
|
+
if (definition.form) sectionForms[type] = definition.form;
|
|
800
956
|
sectionDefaults[type] = definition.defaults;
|
|
801
957
|
sectionLabels[type] = definition.label;
|
|
802
958
|
sectionDescriptions[type] = definition.description;
|
|
@@ -821,6 +977,7 @@ async function getSchema(context) {
|
|
|
821
977
|
fieldIcons,
|
|
822
978
|
fieldImages,
|
|
823
979
|
showWhen,
|
|
980
|
+
sectionForms,
|
|
824
981
|
sectionDefaults,
|
|
825
982
|
sectionLabels,
|
|
826
983
|
sectionDescriptions,
|
|
@@ -1853,10 +2010,22 @@ function bearminion(options) {
|
|
|
1853
2010
|
} });
|
|
1854
2011
|
injectScript("page", "import \"virtual:bearminion-editor\"");
|
|
1855
2012
|
},
|
|
1856
|
-
"astro:server:setup"({ server }) {
|
|
2013
|
+
"astro:server:setup"({ server, logger }) {
|
|
1857
2014
|
const context = resolveEditorContext(options, server.config.root);
|
|
1858
2015
|
const previewModule = options.previewModule ?? "/src/lib/render-preview.ts";
|
|
1859
2016
|
const reloads = dropEarlyReloadAfterSave(server);
|
|
2017
|
+
server.middlewares.use(announceVideoChanges(server, context.videosDir));
|
|
2018
|
+
const forms = resolveFormsConfig(options.forms, context.root);
|
|
2019
|
+
if (forms) server.middlewares.use(createFormsMiddleware({
|
|
2020
|
+
...forms,
|
|
2021
|
+
root: context.root,
|
|
2022
|
+
live: formsAreLive(context.root),
|
|
2023
|
+
load: (file) => loadModule(server.environments.ssr, file),
|
|
2024
|
+
log: {
|
|
2025
|
+
info: (message) => logger.info(message),
|
|
2026
|
+
error: (message) => logger.error(message)
|
|
2027
|
+
}
|
|
2028
|
+
}));
|
|
1860
2029
|
server.middlewares.use((req, _res, next) => {
|
|
1861
2030
|
if (req.method === "POST" && (req.url ?? "").split("?")[0]?.replace(/\/$/, "") === `/__bearminion/api/save`) reloads.saving();
|
|
1862
2031
|
next();
|
|
@@ -1869,6 +2038,39 @@ function bearminion(options) {
|
|
|
1869
2038
|
}
|
|
1870
2039
|
};
|
|
1871
2040
|
}
|
|
2041
|
+
/**
|
|
2042
|
+
* The videos folder is ignored by the file watcher (see above), but Vite learns which files `public/` holds from that
|
|
2043
|
+
* watcher, and answers 404 for any other path. So a video uploaded in the editor would not play in the dev site until
|
|
2044
|
+
* the server restarted. After an upload or delete, tell Vite about exactly the files that appeared or went away.
|
|
2045
|
+
* The event only refreshes Vite's list of public files; it does not reload the page, so the draft stays.
|
|
2046
|
+
*/
|
|
2047
|
+
function announceVideoChanges(server, videosDir) {
|
|
2048
|
+
const list = () => {
|
|
2049
|
+
try {
|
|
2050
|
+
return new Set(fs.readdirSync(videosDir));
|
|
2051
|
+
} catch {
|
|
2052
|
+
return /* @__PURE__ */ new Set();
|
|
2053
|
+
}
|
|
2054
|
+
};
|
|
2055
|
+
return (req, res, next) => {
|
|
2056
|
+
const route = (req.url ?? "").split("?")[0]?.replace(/\/$/, "") ?? "";
|
|
2057
|
+
if ((req.method === "POST" || req.method === "DELETE") && (route === `/__bearminion/api/videos` || route.startsWith(`/__bearminion/api/videos/`))) {
|
|
2058
|
+
const before = list();
|
|
2059
|
+
res.once("finish", () => {
|
|
2060
|
+
const after = list();
|
|
2061
|
+
for (const name of after) if (!before.has(name)) server.watcher.emit("add", path.join(videosDir, name));
|
|
2062
|
+
for (const name of before) if (!after.has(name)) server.watcher.emit("unlink", path.join(videosDir, name));
|
|
2063
|
+
});
|
|
2064
|
+
}
|
|
2065
|
+
next();
|
|
2066
|
+
};
|
|
2067
|
+
}
|
|
2068
|
+
/** Loads a module through the dev server's SSR runner, so TypeScript works and an edit is picked up on the next call. */
|
|
2069
|
+
async function loadModule(environment, file) {
|
|
2070
|
+
const runner = environment.runner;
|
|
2071
|
+
if (!runner?.import) throw new Error("The SSR dev environment cannot load a form.");
|
|
2072
|
+
return runner.import(file);
|
|
2073
|
+
}
|
|
1872
2074
|
async function renderPreview(environment, previewModule, page, motion) {
|
|
1873
2075
|
const preview = await loadThemePreview(environment, previewModule);
|
|
1874
2076
|
const sections = typeof page === "object" && page !== null && "sections" in page && Array.isArray(page.sections) ? page.sections : [];
|
package/dist/content.d.ts
CHANGED
package/dist/content.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { n as createPageSchema, r as createTolerantPageSchema } from "./page-NOFVEqn1.js";
|
|
2
2
|
import { n as createMigrator } from "./migrate-b408EaLp.js";
|
|
3
|
-
import { t as CONTENT_COLLECTIONS_MARKER } from "./reload-
|
|
3
|
+
import { t as CONTENT_COLLECTIONS_MARKER } from "./reload-BPkPoQ-P.js";
|
|
4
4
|
import { z } from "zod";
|
|
5
|
-
import { pathToFileURL } from "node:url";
|
|
6
5
|
import path from "node:path";
|
|
6
|
+
import { pathToFileURL } from "node:url";
|
|
7
7
|
import { glob } from "astro/loaders";
|
|
8
8
|
//#region src/content.ts
|
|
9
9
|
/**
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
//#region src/form-contract.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* What a Contact form sends and what it expects back, for anyone who writes the handler behind it (a Vercel,
|
|
4
|
+
* Netlify or Cloudflare function, or a plain Astro endpoint). Types only: nothing here runs in the browser.
|
|
5
|
+
*
|
|
6
|
+
* To run code of your own behind the form, with your keys kept on the server, use `defineForm` from `bearminion/forms`.
|
|
7
|
+
*
|
|
8
|
+
* ```ts
|
|
9
|
+
* import type { FormResult, FormSubmission } from 'bearminion'
|
|
10
|
+
*
|
|
11
|
+
* export async function handle(submission: FormSubmission): Promise<FormResult> {
|
|
12
|
+
* // ...send it somewhere
|
|
13
|
+
* return { ok: true }
|
|
14
|
+
* }
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* The request. The form's fields by name (`name`, `email`, `topic` when the section lists topics, and `message`),
|
|
19
|
+
* plus where it came from. The form posts it to `/api/contact` as a JSON object. The spam trap field is never part of it.
|
|
20
|
+
*/
|
|
21
|
+
interface FormSubmission {
|
|
22
|
+
/** The id of the Contact section that sent it. */
|
|
23
|
+
formId: string;
|
|
24
|
+
/** The path of the page the form is on, such as `/contact`. */
|
|
25
|
+
page: string;
|
|
26
|
+
[field: string]: string;
|
|
27
|
+
}
|
|
28
|
+
/** Field name → what is wrong with it. Shown under that field on the page. */
|
|
29
|
+
type FormFieldErrors = Readonly<Record<string, string>>;
|
|
30
|
+
/**
|
|
31
|
+
* The answer. `{ ok: true }` with a 2xx status shows the thank-you message; an optional `message` (plain text) is shown
|
|
32
|
+
* in its place. `{ ok: false }` needs a matching 4xx or 5xx status; `error` is shown in a message the visitor closes
|
|
33
|
+
* themselves, and `fieldErrors` under the fields they name.
|
|
34
|
+
*/
|
|
35
|
+
type FormResult = {
|
|
36
|
+
ok: true;
|
|
37
|
+
message?: string;
|
|
38
|
+
} | {
|
|
39
|
+
ok: false;
|
|
40
|
+
error: string;
|
|
41
|
+
fieldErrors?: FormFieldErrors;
|
|
42
|
+
};
|
|
43
|
+
/** The spam-trap field. People never see it; many bots fill every field they find. Formspree uses the same name. */
|
|
44
|
+
declare const HONEYPOT_FIELD = "_gotcha";
|
|
45
|
+
/** The field Cloudflare Turnstile's widget fills with its token. The form sends it; `defineForm` checks and removes it. */
|
|
46
|
+
declare const TURNSTILE_FIELD = "cf-turnstile-response";
|
|
47
|
+
//#endregion
|
|
48
|
+
export { TURNSTILE_FIELD as a, HONEYPOT_FIELD as i, FormResult as n, FormSubmission as r, FormFieldErrors as t };
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
//#region src/form-contract.ts
|
|
2
|
+
/** The spam-trap field. People never see it; many bots fill every field they find. Formspree uses the same name. */
|
|
3
|
+
const HONEYPOT_FIELD = "_gotcha";
|
|
4
|
+
/** The field Cloudflare Turnstile's widget fills with its token. The form sends it; `defineForm` checks and removes it. */
|
|
5
|
+
const TURNSTILE_FIELD = "cf-turnstile-response";
|
|
6
|
+
//#endregion
|
|
7
|
+
export { TURNSTILE_FIELD as n, HONEYPOT_FIELD as t };
|
package/dist/forms.d.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { a as TURNSTILE_FIELD, i as HONEYPOT_FIELD, n as FormResult, r as FormSubmission, t as FormFieldErrors } from "./form-contract-BURSJP3Y.js";
|
|
2
|
+
//#region src/forms/define-form.d.ts
|
|
3
|
+
/** Environment variables by name: `process.env`, Cloudflare's `env`, `Netlify.env.toObject()`. */
|
|
4
|
+
type FormEnv = Readonly<Record<string, string | undefined>>;
|
|
5
|
+
/** What a handler is given besides the message. */
|
|
6
|
+
interface FormContext {
|
|
7
|
+
/** Your secrets and settings. Pass the host's environment to `form.fetch`; the glue files in the guide do. */
|
|
8
|
+
env: FormEnv;
|
|
9
|
+
/** The incoming request without its body (already read): its headers and URL, for the visitor's address or language. */
|
|
10
|
+
request: Request;
|
|
11
|
+
/** True while `astro dev` runs the handler. */
|
|
12
|
+
dev: boolean;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* What a handler may return. Nothing, or `{ ok: true }`, is a success; `message` replaces the thank-you text on the
|
|
16
|
+
* page (plain text). `{ ok: false, error }` is a refusal the visitor sees. To fail with another status, throw a `FormError`.
|
|
17
|
+
*/
|
|
18
|
+
type FormHandlerResult = void | FormResult;
|
|
19
|
+
type FormHandler = (submission: FormSubmission, context: FormContext) => FormHandlerResult | Promise<FormHandlerResult>;
|
|
20
|
+
interface FormOptions {
|
|
21
|
+
/**
|
|
22
|
+
* Check a Cloudflare Turnstile token before the handler runs. `true` reads the secret key from the environment
|
|
23
|
+
* variable `TURNSTILE_SECRET_KEY`; `{ secretEnv }` names another one. The page needs the matching site key in the
|
|
24
|
+
* Contact section's settings.
|
|
25
|
+
*/
|
|
26
|
+
turnstile?: boolean | {
|
|
27
|
+
secretEnv?: string;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Other sites allowed to post here, such as `https://www.example.com`, or `'*'` for any. Posts from the form's own
|
|
31
|
+
* site are always allowed. Needed only when the page and the function live on different addresses.
|
|
32
|
+
*/
|
|
33
|
+
origins?: readonly string[];
|
|
34
|
+
/** Largest post accepted, in bytes. Default 64 KB. */
|
|
35
|
+
maxBytes?: number;
|
|
36
|
+
}
|
|
37
|
+
/** How one request is run. The dev server uses this; hosts do not need it. */
|
|
38
|
+
interface FormRunOptions {
|
|
39
|
+
dev?: boolean;
|
|
40
|
+
/** Receive the message and answer success without calling the handler or Turnstile. */
|
|
41
|
+
dryRun?: (submission: FormSubmission) => void;
|
|
42
|
+
}
|
|
43
|
+
interface Form {
|
|
44
|
+
/** Answers one request. Give it the host's environment as `env`. */
|
|
45
|
+
fetch(request: Request, env?: FormEnv, run?: FormRunOptions): Promise<Response>;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Throw this from a handler to refuse the message with a text the visitor sees, instead of the generic "could not be
|
|
49
|
+
* delivered". `fieldErrors` mark fields. The status is 422 with `fieldErrors` and 400 without, unless you give one.
|
|
50
|
+
*/
|
|
51
|
+
export declare class FormError extends Error {
|
|
52
|
+
readonly status: number;
|
|
53
|
+
readonly fieldErrors: FormFieldErrors | undefined;
|
|
54
|
+
constructor(message: string, options?: {
|
|
55
|
+
fieldErrors?: FormFieldErrors;
|
|
56
|
+
status?: number;
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Puts your function behind a form. It runs on your server with your keys, so a service's token never reaches the
|
|
61
|
+
* browser. It gets the message the Contact form sent and returns what the visitor should see.
|
|
62
|
+
*
|
|
63
|
+
* ```ts
|
|
64
|
+
* // src/forms/contact.ts
|
|
65
|
+
* import { defineForm, FormError } from 'bearminion/forms'
|
|
66
|
+
*
|
|
67
|
+
* export default defineForm(async (submission, { env }) => {
|
|
68
|
+
* const response = await fetch('https://api.example.com/send', {
|
|
69
|
+
* method: 'POST',
|
|
70
|
+
* headers: { Authorization: `Bearer ${env.EXAMPLE_API_KEY}` },
|
|
71
|
+
* body: JSON.stringify({ from: submission.email, text: submission.message }),
|
|
72
|
+
* })
|
|
73
|
+
* if (!response.ok) throw new FormError('The message could not be sent.', { status: 502 })
|
|
74
|
+
* })
|
|
75
|
+
* ```
|
|
76
|
+
*
|
|
77
|
+
* What it does around your function, whatever the host: answers only `POST` (and the CORS preflight), accepts JSON,
|
|
78
|
+
* `multipart/form-data` and `application/x-www-form-urlencoded`, refuses a post over `maxBytes` and a post from another
|
|
79
|
+
* site, drops a message whose trap field is filled (without calling you), checks Turnstile when asked, and turns what
|
|
80
|
+
* you return or throw into the `{ ok, error, fieldErrors }` answer the page understands. It does not validate the
|
|
81
|
+
* fields: the Contact form already does in the browser.
|
|
82
|
+
*/
|
|
83
|
+
export declare function defineForm(handler: FormHandler, options?: FormOptions): Form;
|
|
84
|
+
//#endregion
|
|
85
|
+
//#region src/forms/turnstile.d.ts
|
|
86
|
+
/**
|
|
87
|
+
* Server side of Cloudflare Turnstile: the widget in the page gives the visitor a token; this asks Cloudflare whether
|
|
88
|
+
* it is genuine. A token works once, so call it once per submission.
|
|
89
|
+
*/
|
|
90
|
+
export declare const TURNSTILE_VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
|
|
91
|
+
/** Turnstile could not be asked: Cloudflare was unreachable or answered something unreadable. */
|
|
92
|
+
export declare class TurnstileUnavailableError extends Error {
|
|
93
|
+
constructor(message: string, options?: {
|
|
94
|
+
cause?: unknown;
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
type TurnstileOutcome =
|
|
98
|
+
/** The token is genuine. */
|
|
99
|
+
{
|
|
100
|
+
success: true;
|
|
101
|
+
} |
|
|
102
|
+
/** `misconfigured` is true when the secret key is missing or wrong: a mistake on your side, not the visitor's. */
|
|
103
|
+
{
|
|
104
|
+
success: false;
|
|
105
|
+
codes: string[];
|
|
106
|
+
misconfigured: boolean;
|
|
107
|
+
};
|
|
108
|
+
interface VerifyTurnstileInput {
|
|
109
|
+
secret: string;
|
|
110
|
+
token: string;
|
|
111
|
+
/** The visitor's address. Optional; Cloudflare uses it as an extra signal. */
|
|
112
|
+
remoteIp?: string;
|
|
113
|
+
/** For tests. Defaults to the platform's `fetch`. */
|
|
114
|
+
fetch?: typeof fetch;
|
|
115
|
+
}
|
|
116
|
+
/** Asks Cloudflare whether `token` is a genuine, unused Turnstile token for your secret key. */
|
|
117
|
+
export declare function verifyTurnstile({ secret, token, remoteIp, fetch: send }: VerifyTurnstileInput): Promise<TurnstileOutcome>;
|
|
118
|
+
//#endregion
|
|
119
|
+
export { type Form, type FormContext, type FormEnv, type FormFieldErrors, type FormHandler, type FormHandlerResult, type FormOptions, type FormResult, type FormRunOptions, type FormSubmission, HONEYPOT_FIELD, TURNSTILE_FIELD, type TurnstileOutcome, type VerifyTurnstileInput };
|
package/dist/forms.js
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
import { n as TURNSTILE_FIELD, t as HONEYPOT_FIELD } from "./form-contract-CIDTNab-.js";
|
|
2
|
+
/** A post that cannot be used, with the HTTP status that says why. */
|
|
3
|
+
var BodyError = class extends Error {
|
|
4
|
+
status;
|
|
5
|
+
constructor(status, message) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.name = "BodyError";
|
|
8
|
+
this.status = status;
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
/** The request body, or a 413 as soon as it is known to be over `maxBytes`. */
|
|
12
|
+
async function readBody(request, maxBytes) {
|
|
13
|
+
const advertised = Number(request.headers.get("content-length") ?? "");
|
|
14
|
+
if (Number.isFinite(advertised) && advertised > maxBytes) throw new BodyError(413, "The message is too large.");
|
|
15
|
+
const reader = request.body?.getReader();
|
|
16
|
+
if (!reader) return /* @__PURE__ */ new Uint8Array();
|
|
17
|
+
const chunks = [];
|
|
18
|
+
let size = 0;
|
|
19
|
+
for (;;) {
|
|
20
|
+
const { done, value } = await reader.read();
|
|
21
|
+
if (done) break;
|
|
22
|
+
size += value.byteLength;
|
|
23
|
+
if (size > maxBytes) {
|
|
24
|
+
await reader.cancel().catch(() => void 0);
|
|
25
|
+
throw new BodyError(413, "The message is too large.");
|
|
26
|
+
}
|
|
27
|
+
chunks.push(value);
|
|
28
|
+
}
|
|
29
|
+
const bytes = new Uint8Array(size);
|
|
30
|
+
let offset = 0;
|
|
31
|
+
for (const chunk of chunks) {
|
|
32
|
+
bytes.set(chunk, offset);
|
|
33
|
+
offset += chunk.byteLength;
|
|
34
|
+
}
|
|
35
|
+
return bytes;
|
|
36
|
+
}
|
|
37
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
38
|
+
/**
|
|
39
|
+
* The text fields of a post: JSON, `multipart/form-data` or `application/x-www-form-urlencoded`. Anything that is not
|
|
40
|
+
* text (a file, a number, a nested object) is left out, so a handler only ever sees strings.
|
|
41
|
+
*/
|
|
42
|
+
async function parseFields(contentType, bytes) {
|
|
43
|
+
const type = (contentType ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
|
|
44
|
+
const fields = {};
|
|
45
|
+
const add = (name, value) => {
|
|
46
|
+
if (name === "__proto__" || typeof value !== "string") return;
|
|
47
|
+
fields[name] = value;
|
|
48
|
+
};
|
|
49
|
+
if (type === "application/json") {
|
|
50
|
+
let parsed;
|
|
51
|
+
try {
|
|
52
|
+
parsed = JSON.parse(new TextDecoder().decode(bytes));
|
|
53
|
+
} catch {
|
|
54
|
+
throw new BodyError(400, "The message could not be read.");
|
|
55
|
+
}
|
|
56
|
+
if (!isRecord(parsed)) throw new BodyError(400, "The message could not be read.");
|
|
57
|
+
for (const [name, value] of Object.entries(parsed)) add(name, value);
|
|
58
|
+
return fields;
|
|
59
|
+
}
|
|
60
|
+
if (type === "multipart/form-data" || type === "application/x-www-form-urlencoded") {
|
|
61
|
+
let data;
|
|
62
|
+
try {
|
|
63
|
+
data = await new Response(bytes, { headers: { "content-type": contentType ?? type } }).formData();
|
|
64
|
+
} catch {
|
|
65
|
+
throw new BodyError(400, "The message could not be read.");
|
|
66
|
+
}
|
|
67
|
+
for (const [name, value] of data.entries()) add(name, value);
|
|
68
|
+
return fields;
|
|
69
|
+
}
|
|
70
|
+
throw new BodyError(415, "Send the form as JSON or as form data.");
|
|
71
|
+
}
|
|
72
|
+
//#endregion
|
|
73
|
+
//#region src/forms/turnstile.ts
|
|
74
|
+
/**
|
|
75
|
+
* Server side of Cloudflare Turnstile: the widget in the page gives the visitor a token; this asks Cloudflare whether
|
|
76
|
+
* it is genuine. A token works once, so call it once per submission.
|
|
77
|
+
*/
|
|
78
|
+
const TURNSTILE_VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
|
|
79
|
+
/** Turnstile could not be asked: Cloudflare was unreachable or answered something unreadable. */
|
|
80
|
+
var TurnstileUnavailableError = class extends Error {
|
|
81
|
+
constructor(message, options) {
|
|
82
|
+
super(message, options);
|
|
83
|
+
this.name = "TurnstileUnavailableError";
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
/** Asks Cloudflare whether `token` is a genuine, unused Turnstile token for your secret key. */
|
|
87
|
+
async function verifyTurnstile({ secret, token, remoteIp, fetch: send = fetch }) {
|
|
88
|
+
const body = new URLSearchParams({
|
|
89
|
+
secret,
|
|
90
|
+
response: token
|
|
91
|
+
});
|
|
92
|
+
if (remoteIp) body.set("remoteip", remoteIp);
|
|
93
|
+
let answer;
|
|
94
|
+
try {
|
|
95
|
+
answer = await (await send(TURNSTILE_VERIFY_URL, {
|
|
96
|
+
method: "POST",
|
|
97
|
+
body
|
|
98
|
+
})).json();
|
|
99
|
+
} catch (error) {
|
|
100
|
+
throw new TurnstileUnavailableError("Could not reach Cloudflare Turnstile.", { cause: error });
|
|
101
|
+
}
|
|
102
|
+
if (typeof answer !== "object" || answer === null) throw new TurnstileUnavailableError("Turnstile answered something unreadable.");
|
|
103
|
+
const record = answer;
|
|
104
|
+
if (record.success === true) return { success: true };
|
|
105
|
+
const codes = Array.isArray(record["error-codes"]) ? record["error-codes"].filter((code) => typeof code === "string") : [];
|
|
106
|
+
return {
|
|
107
|
+
success: false,
|
|
108
|
+
codes,
|
|
109
|
+
misconfigured: codes.some((code) => code === "missing-input-secret" || code === "invalid-input-secret")
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
//#endregion
|
|
113
|
+
//#region src/forms/define-form.ts
|
|
114
|
+
const FORM_ERROR = Symbol.for("bearminion.form-error");
|
|
115
|
+
/**
|
|
116
|
+
* Throw this from a handler to refuse the message with a text the visitor sees, instead of the generic "could not be
|
|
117
|
+
* delivered". `fieldErrors` mark fields. The status is 422 with `fieldErrors` and 400 without, unless you give one.
|
|
118
|
+
*/
|
|
119
|
+
var FormError = class extends Error {
|
|
120
|
+
status;
|
|
121
|
+
fieldErrors;
|
|
122
|
+
constructor(message, options = {}) {
|
|
123
|
+
super(message);
|
|
124
|
+
this.name = "FormError";
|
|
125
|
+
this.fieldErrors = options.fieldErrors;
|
|
126
|
+
const wanted = options.status ?? (options.fieldErrors ? 422 : 400);
|
|
127
|
+
this.status = Number.isInteger(wanted) && wanted >= 400 && wanted <= 599 ? wanted : 400;
|
|
128
|
+
Object.defineProperty(this, FORM_ERROR, { value: true });
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
function isFormError(error) {
|
|
132
|
+
return typeof error === "object" && error !== null && error[FORM_ERROR] === true;
|
|
133
|
+
}
|
|
134
|
+
const UNDELIVERED = "The message could not be delivered. Try again later.";
|
|
135
|
+
const NOT_SET_UP = "This form is not set up correctly. Please try again later.";
|
|
136
|
+
const SPAM_CHECK_FAILED = "The spam check did not pass. Reload the page and try again.";
|
|
137
|
+
const SPAM_CHECK_UNAVAILABLE = "The spam check could not be completed. Try again in a moment.";
|
|
138
|
+
const jsonHeaders = {
|
|
139
|
+
"content-type": "application/json; charset=utf-8",
|
|
140
|
+
"cache-control": "no-store"
|
|
141
|
+
};
|
|
142
|
+
function reply(status, result, headers = {}) {
|
|
143
|
+
return new Response(JSON.stringify(result), {
|
|
144
|
+
status,
|
|
145
|
+
headers: {
|
|
146
|
+
...jsonHeaders,
|
|
147
|
+
...headers
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
const refuse = (status, error, headers) => reply(status, {
|
|
152
|
+
ok: false,
|
|
153
|
+
error
|
|
154
|
+
}, headers);
|
|
155
|
+
/** A browser posting the form itself (JavaScript off) asks for HTML. The script on the page asks for JSON. */
|
|
156
|
+
function isNavigation(request) {
|
|
157
|
+
if (request.method !== "POST") return false;
|
|
158
|
+
const accept = request.headers.get("accept") ?? "";
|
|
159
|
+
return accept.includes("text/html") && !accept.includes("application/json");
|
|
160
|
+
}
|
|
161
|
+
/** The page the visitor came from, as a path. Only on this host: anything else would be an open redirect. */
|
|
162
|
+
function cameFrom(request) {
|
|
163
|
+
const referer = request.headers.get("referer");
|
|
164
|
+
if (!referer) return null;
|
|
165
|
+
try {
|
|
166
|
+
const from = new URL(referer);
|
|
167
|
+
if (from.host !== new URL(request.url).host) return null;
|
|
168
|
+
return `${from.pathname}${from.search}`;
|
|
169
|
+
} catch {
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/** Who may post, and the CORS headers that go with it. `null` means refuse. */
|
|
174
|
+
function originHeaders(request, allowed) {
|
|
175
|
+
const origin = request.headers.get("origin");
|
|
176
|
+
if (origin === null) return {};
|
|
177
|
+
try {
|
|
178
|
+
if (new URL(origin).host === new URL(request.url).host) return {};
|
|
179
|
+
} catch {
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
182
|
+
const vary = { vary: "Origin" };
|
|
183
|
+
if (allowed.includes("*")) return {
|
|
184
|
+
...vary,
|
|
185
|
+
"access-control-allow-origin": "*"
|
|
186
|
+
};
|
|
187
|
+
if (allowed.includes(origin)) return {
|
|
188
|
+
...vary,
|
|
189
|
+
"access-control-allow-origin": origin
|
|
190
|
+
};
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
const CORS_METHODS = {
|
|
194
|
+
"access-control-allow-methods": "POST, OPTIONS",
|
|
195
|
+
"access-control-allow-headers": "Content-Type",
|
|
196
|
+
"access-control-max-age": "86400"
|
|
197
|
+
};
|
|
198
|
+
function remoteIp(headers) {
|
|
199
|
+
return headers.get("cf-connecting-ip") ?? headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? headers.get("x-real-ip") ?? void 0;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Puts your function behind a form. It runs on your server with your keys, so a service's token never reaches the
|
|
203
|
+
* browser. It gets the message the Contact form sent and returns what the visitor should see.
|
|
204
|
+
*
|
|
205
|
+
* ```ts
|
|
206
|
+
* // src/forms/contact.ts
|
|
207
|
+
* import { defineForm, FormError } from 'bearminion/forms'
|
|
208
|
+
*
|
|
209
|
+
* export default defineForm(async (submission, { env }) => {
|
|
210
|
+
* const response = await fetch('https://api.example.com/send', {
|
|
211
|
+
* method: 'POST',
|
|
212
|
+
* headers: { Authorization: `Bearer ${env.EXAMPLE_API_KEY}` },
|
|
213
|
+
* body: JSON.stringify({ from: submission.email, text: submission.message }),
|
|
214
|
+
* })
|
|
215
|
+
* if (!response.ok) throw new FormError('The message could not be sent.', { status: 502 })
|
|
216
|
+
* })
|
|
217
|
+
* ```
|
|
218
|
+
*
|
|
219
|
+
* What it does around your function, whatever the host: answers only `POST` (and the CORS preflight), accepts JSON,
|
|
220
|
+
* `multipart/form-data` and `application/x-www-form-urlencoded`, refuses a post over `maxBytes` and a post from another
|
|
221
|
+
* site, drops a message whose trap field is filled (without calling you), checks Turnstile when asked, and turns what
|
|
222
|
+
* you return or throw into the `{ ok, error, fieldErrors }` answer the page understands. It does not validate the
|
|
223
|
+
* fields: the Contact form already does in the browser.
|
|
224
|
+
*/
|
|
225
|
+
function defineForm(handler, options = {}) {
|
|
226
|
+
if (typeof handler !== "function") throw new TypeError("defineForm needs a function: defineForm(async (submission, { env }) => { ... }).");
|
|
227
|
+
const maxBytes = options.maxBytes ?? 65536;
|
|
228
|
+
const allowed = options.origins ?? [];
|
|
229
|
+
const secretEnv = options.turnstile === true ? "TURNSTILE_SECRET_KEY" : options.turnstile ? options.turnstile.secretEnv ?? "TURNSTILE_SECRET_KEY" : void 0;
|
|
230
|
+
async function answer(request, env, run, seen) {
|
|
231
|
+
const cors = originHeaders(request, allowed);
|
|
232
|
+
if (cors === null) return refuse(403, "This site is not allowed to send to this form.");
|
|
233
|
+
if (request.method === "OPTIONS") return new Response(null, {
|
|
234
|
+
status: 204,
|
|
235
|
+
headers: {
|
|
236
|
+
...CORS_METHODS,
|
|
237
|
+
...cors
|
|
238
|
+
}
|
|
239
|
+
});
|
|
240
|
+
if (request.method !== "POST") return refuse(405, "Send the form with POST.", {
|
|
241
|
+
allow: "POST, OPTIONS",
|
|
242
|
+
...cors
|
|
243
|
+
});
|
|
244
|
+
let fields;
|
|
245
|
+
try {
|
|
246
|
+
fields = await parseFields(request.headers.get("content-type"), await readBody(request, maxBytes));
|
|
247
|
+
} catch (error) {
|
|
248
|
+
if (error instanceof BodyError) return refuse(error.status, error.message, cors);
|
|
249
|
+
throw error;
|
|
250
|
+
}
|
|
251
|
+
seen.formId = fields.formId ?? "";
|
|
252
|
+
const trap = fields[HONEYPOT_FIELD];
|
|
253
|
+
delete fields[HONEYPOT_FIELD];
|
|
254
|
+
if (trap !== void 0 && trap.trim() !== "") return reply(200, { ok: true }, cors);
|
|
255
|
+
const token = fields[TURNSTILE_FIELD];
|
|
256
|
+
delete fields[TURNSTILE_FIELD];
|
|
257
|
+
const { formId = "", page = cameFrom(request)?.split("?")[0] ?? "", ...rest } = fields;
|
|
258
|
+
const submission = {
|
|
259
|
+
formId,
|
|
260
|
+
page,
|
|
261
|
+
...rest
|
|
262
|
+
};
|
|
263
|
+
if (run.dryRun) {
|
|
264
|
+
run.dryRun(submission);
|
|
265
|
+
return reply(200, { ok: true }, cors);
|
|
266
|
+
}
|
|
267
|
+
if (secretEnv !== void 0) {
|
|
268
|
+
const secret = env[secretEnv];
|
|
269
|
+
if (!secret) {
|
|
270
|
+
console.error(`[bearminion] This form checks Turnstile, but the environment variable ${secretEnv} is not set.`);
|
|
271
|
+
return refuse(500, NOT_SET_UP, cors);
|
|
272
|
+
}
|
|
273
|
+
if (!token) return refuse(422, SPAM_CHECK_FAILED, cors);
|
|
274
|
+
try {
|
|
275
|
+
const ip = remoteIp(request.headers);
|
|
276
|
+
const outcome = await verifyTurnstile({
|
|
277
|
+
secret,
|
|
278
|
+
token,
|
|
279
|
+
...ip ? { remoteIp: ip } : {}
|
|
280
|
+
});
|
|
281
|
+
if (!outcome.success) {
|
|
282
|
+
if (outcome.misconfigured) {
|
|
283
|
+
console.error(`[bearminion] Turnstile refused the secret key in ${secretEnv} (${outcome.codes.join(", ")}). Check it in the Cloudflare dashboard.`);
|
|
284
|
+
return refuse(500, NOT_SET_UP, cors);
|
|
285
|
+
}
|
|
286
|
+
return refuse(422, SPAM_CHECK_FAILED, cors);
|
|
287
|
+
}
|
|
288
|
+
} catch (error) {
|
|
289
|
+
if (error instanceof TurnstileUnavailableError) {
|
|
290
|
+
console.error(`[bearminion] ${error.message}`, error.cause ?? "");
|
|
291
|
+
return refuse(502, SPAM_CHECK_UNAVAILABLE, cors);
|
|
292
|
+
}
|
|
293
|
+
throw error;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
const context = {
|
|
297
|
+
env,
|
|
298
|
+
request: new Request(request.url, {
|
|
299
|
+
method: request.method,
|
|
300
|
+
headers: request.headers
|
|
301
|
+
}),
|
|
302
|
+
dev: run.dev === true
|
|
303
|
+
};
|
|
304
|
+
let outcome;
|
|
305
|
+
try {
|
|
306
|
+
outcome = await handler(submission, context);
|
|
307
|
+
} catch (error) {
|
|
308
|
+
if (isFormError(error)) return reply(error.status, error.fieldErrors ? {
|
|
309
|
+
ok: false,
|
|
310
|
+
error: error.message,
|
|
311
|
+
fieldErrors: error.fieldErrors
|
|
312
|
+
} : {
|
|
313
|
+
ok: false,
|
|
314
|
+
error: error.message
|
|
315
|
+
}, cors);
|
|
316
|
+
console.error("[bearminion] The form handler failed:", error);
|
|
317
|
+
return refuse(502, UNDELIVERED, cors);
|
|
318
|
+
}
|
|
319
|
+
if (outcome === void 0) return reply(200, { ok: true }, cors);
|
|
320
|
+
if (typeof outcome === "object" && outcome !== null && outcome.ok === true) {
|
|
321
|
+
const message = typeof outcome.message === "string" && outcome.message.trim() !== "" ? outcome.message.trim() : void 0;
|
|
322
|
+
return reply(200, message ? {
|
|
323
|
+
ok: true,
|
|
324
|
+
message
|
|
325
|
+
} : { ok: true }, cors);
|
|
326
|
+
}
|
|
327
|
+
if (typeof outcome === "object" && outcome !== null && outcome.ok === false && typeof outcome.error === "string" && outcome.error !== "") {
|
|
328
|
+
const fieldErrors = outcome.fieldErrors && Object.keys(outcome.fieldErrors).length > 0 ? outcome.fieldErrors : void 0;
|
|
329
|
+
return reply(fieldErrors ? 422 : 400, fieldErrors ? {
|
|
330
|
+
ok: false,
|
|
331
|
+
error: outcome.error,
|
|
332
|
+
fieldErrors
|
|
333
|
+
} : {
|
|
334
|
+
ok: false,
|
|
335
|
+
error: outcome.error
|
|
336
|
+
}, cors);
|
|
337
|
+
}
|
|
338
|
+
console.error("[bearminion] The form handler returned something else than nothing, { ok: true } or { ok: false, error }:", outcome);
|
|
339
|
+
return refuse(500, NOT_SET_UP, cors);
|
|
340
|
+
}
|
|
341
|
+
return { async fetch(request, env = {}, run = {}) {
|
|
342
|
+
const seen = { formId: "" };
|
|
343
|
+
const response = await answer(request, env, run, seen);
|
|
344
|
+
if (!isNavigation(request)) return response;
|
|
345
|
+
const back = cameFrom(request);
|
|
346
|
+
if (back === null) return response;
|
|
347
|
+
const fragment = seen.formId ? `#${seen.formId}-${response.status === 200 ? "sent" : "failed"}` : "";
|
|
348
|
+
return new Response(null, {
|
|
349
|
+
status: 303,
|
|
350
|
+
headers: {
|
|
351
|
+
location: `${back}${fragment}`,
|
|
352
|
+
"cache-control": "no-store"
|
|
353
|
+
}
|
|
354
|
+
});
|
|
355
|
+
} };
|
|
356
|
+
}
|
|
357
|
+
//#endregion
|
|
358
|
+
export { FormError, HONEYPOT_FIELD, TURNSTILE_FIELD, TURNSTILE_VERIFY_URL, TurnstileUnavailableError, defineForm, verifyTurnstile };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { $ as brandLogoSchema, $t as createMigrator, A as SectionRegistry, At as wireframeIssues, B as FooterColumn, Bt as themeModes, C as jsonLdWarnings, Ct as SectionDefinition, D as upsertJsonLd, Dt as Wireframe, E as siteJsonLdIds, Et as WireRect, F as defineTheme, Ft as NumberOption, G as SiteAnalytics, Gt as FieldIcons, H as Header, Ht as tones, I as BRAND_LOGO_HEIGHT, It as Option, J as SiteDefinition, Jt as ContentMigration, K as SiteConfig, Kt as ShowCondition, L as DEFAULT_MAX_FOOTER_COLUMNS, Lt as StringOption, M as ThemeDefinition, Mt as BooleanOption, N as ThemeFont, Nt as CountRule, O as API_PREFIX, Ot as defineWireframe, P as defaultTheme, Pt as EnumOption, Q as Theme, Qt as SCHEMA_VERSION_KEY, R as DEFAULT_MAX_HEADER_ACTIONS, Rt as buttonStyles, S as jsonLdSchema, St as SectionConfig, T as parseJsonLdInput, Tt as WireKind, U as HeaderConfig, Ut as variantOption, V as FooterConfig, Vt as toneOption, W as Site, Wt as FieldChoices, X as SiteSeo, Xt as ContentVersioning, Y as SiteOf, Yt as ContentMigrator, Z as SiteWith, Zt as DocumentKind, _ as SiteJsonLdSource, _t as textMarkSchema, a as isSystemPage, at as themeSchema, b as hasJsonLdId, bt as trackingIdSchema, c as BaseSection, ct as Link, d as anchorSchema, dt as Text, et as defineSite, f as createSectionSchema, ft as Tone, g as SiteJsonLdIds, gt as richTextSchema, h as JsonLdResult, ht as linkSchema, i as createPageSchema, it as themeColorsSchema, j as ThemeConfig, jt as OptionalContent, k as ContentModel, kt as wireKinds, l as PropsOf, lt as MAX_NAV_DEPTH, m as JsonLdBlock, mt as imageSchema, n as SYSTEM_PAGES, nt as siteConsentSchema, o as seoSchema, ot as ButtonStyle, p as sectionIdSchema, pt as htmlIdSchema, q as SiteConsent, qt as ShowWhen, r as Seo, rt as siteSeoSchema, s as withoutOrphanSections, st as Image, t as Page, tt as siteAnalyticsSchema, u as SectionOf, ut as RichText, v as formatJsonLd, vt as textSchema, w as mergeJsonLd, wt as defineSection, x as isPlaceholderSiteUrl, xt as withEmphasis, y as generateSiteJsonLd, yt as toneSchema, z as Footer, zt as motionOption } from "./page-
|
|
1
|
+
import { $ as brandLogoSchema, $t as createMigrator, A as SectionRegistry, At as wireframeIssues, B as FooterColumn, Bt as themeModes, C as jsonLdWarnings, Ct as SectionDefinition, D as upsertJsonLd, Dt as Wireframe, E as siteJsonLdIds, Et as WireRect, F as defineTheme, Ft as NumberOption, G as SiteAnalytics, Gt as FieldIcons, H as Header, Ht as tones, I as BRAND_LOGO_HEIGHT, It as Option, J as SiteDefinition, Jt as ContentMigration, K as SiteConfig, Kt as ShowCondition, L as DEFAULT_MAX_FOOTER_COLUMNS, Lt as StringOption, M as ThemeDefinition, Mt as BooleanOption, N as ThemeFont, Nt as CountRule, O as API_PREFIX, Ot as defineWireframe, P as defaultTheme, Pt as EnumOption, Q as Theme, Qt as SCHEMA_VERSION_KEY, R as DEFAULT_MAX_HEADER_ACTIONS, Rt as buttonStyles, S as jsonLdSchema, St as SectionConfig, T as parseJsonLdInput, Tt as WireKind, U as HeaderConfig, Ut as variantOption, V as FooterConfig, Vt as toneOption, W as Site, Wt as FieldChoices, X as SiteSeo, Xt as ContentVersioning, Y as SiteOf, Yt as ContentMigrator, Z as SiteWith, Zt as DocumentKind, _ as SiteJsonLdSource, _t as textMarkSchema, a as isSystemPage, at as themeSchema, b as hasJsonLdId, bt as trackingIdSchema, c as BaseSection, ct as Link, d as anchorSchema, dt as Text, et as defineSite, f as createSectionSchema, ft as Tone, g as SiteJsonLdIds, gt as richTextSchema, h as JsonLdResult, ht as linkSchema, i as createPageSchema, it as themeColorsSchema, j as ThemeConfig, jt as OptionalContent, k as ContentModel, kt as wireKinds, l as PropsOf, lt as MAX_NAV_DEPTH, m as JsonLdBlock, mt as imageSchema, n as SYSTEM_PAGES, nt as siteConsentSchema, o as seoSchema, ot as ButtonStyle, p as sectionIdSchema, pt as htmlIdSchema, q as SiteConsent, qt as ShowWhen, r as Seo, rt as siteSeoSchema, s as withoutOrphanSections, st as Image, t as Page, tt as siteAnalyticsSchema, u as SectionOf, ut as RichText, v as formatJsonLd, vt as textSchema, w as mergeJsonLd, wt as defineSection, x as isPlaceholderSiteUrl, xt as withEmphasis, y as generateSiteJsonLd, yt as toneSchema, z as Footer, zt as motionOption } from "./page-BfI9cD8g.js";
|
|
2
2
|
import { _ as renderMarkedHtml, a as WeightMark, f as markClass, g as reconcileMarks, i as TextRun, l as fontMarks, m as marksFromEmphasis, o as applyTextMark, r as TextMark, t as FontMark, v as splitMarkedText, y as weightMarks } from "./marks-BzLa48Y9.js";
|
|
3
|
-
import "./options-
|
|
3
|
+
import "./options-BeJQnsZM.js";
|
|
4
|
+
import { a as TURNSTILE_FIELD, i as HONEYPOT_FIELD, n as FormResult, r as FormSubmission, t as FormFieldErrors } from "./form-contract-BURSJP3Y.js";
|
|
4
5
|
//#region src/errors.d.ts
|
|
5
6
|
/** One schema problem, addressed by a dot path such as `sections.0.props.heading`. */
|
|
6
7
|
interface ContentIssue {
|
|
@@ -304,4 +305,4 @@ interface ContrastCheck {
|
|
|
304
305
|
/** Text pairs a visitor reads: text on its background, label on the accent fill, link on its background. */
|
|
305
306
|
export declare function contrastChecks(colors: ThemeColors | undefined): ContrastCheck[];
|
|
306
307
|
//#endregion
|
|
307
|
-
export { API_PREFIX, type ApiIssue, type ApiProblem, BRAND_LOGO_HEIGHT, type BaseSection, type BooleanOption, type ButtonStyle, type ChangedFile, type CommitRequest, type CommitResult, type ConsentCopy, type ConsentReopen, type ConsentText, type ConsentTextKey, type ContentIssue, type ContentMigration, type ContentMigrator, type ContentModel, type ContentVersioning, type ContrastCheck, type CountRule, type CreatePageRequest, DEFAULT_MAX_FOOTER_COLUMNS, DEFAULT_MAX_HEADER_ACTIONS, type DocumentKind, type EnumOption, type FieldChoices, type FieldIcons, type FontMark, type Footer, type FooterColumn, type FooterConfig, type GitInfo, type Header, type HeaderConfig, type HistoryEntry, type Image, type ImageFit, type ImagePosition, type JsonLdBlock, type JsonLdResult, type Link, MAX_NAV_DEPTH, type MediaSource, type NumberOption, type Option, type OptionalContent, type Page, type PageListItem, type PropsOf, type RichText, SCHEMA_VERSION_KEY, SYSTEM_PAGES, type SaveRequest, type SaveResponse, type SectionConfig, type SectionDefinition, type SectionOf, type SectionRegistry, type Seo, type ShowCondition, type ShowWhen, type Site, type SiteAnalytics, type SiteConfig, type SiteConsent, type SiteDefinition, type SiteJsonLdIds, type SiteJsonLdSource, type SiteOf, type SitePreview, type SitePreviewHtml, type SiteSeo, type SiteWith, type StringOption, type Text, type TextMark, type TextRun, type Theme, type ThemeColors, type ThemeConfig, type ThemeDefinition, type ThemeFont, type ThemePreview, type Tone, type UploadedImage, type UploadedVideo, type WeightMark, type WireKind, type WireRect, type Wireframe, anchorSchema, applyTextMark, brandLogoSchema, buttonStyles, createMigrator, createPageSchema, createSectionSchema, defaultTheme, defineSection, defineSite, defineTheme, defineWireframe, fontMarks, formatJsonLd, generateSiteJsonLd, hasJsonLdId, htmlIdSchema, imageSchema, isPlaceholderSiteUrl, isSystemPage, jsonLdSchema, jsonLdWarnings, linkSchema, markClass, marksFromEmphasis, mergeJsonLd, motionOption, parseJsonLdInput, reconcileMarks, renderMarkedHtml, richTextSchema, sectionIdSchema, seoSchema, siteAnalyticsSchema, siteConsentSchema, siteJsonLdIds, siteSeoSchema, splitMarkedText, textMarkSchema, textSchema, themeColorsSchema, themeModes, themeSchema, toneOption, toneSchema, tones, trackingIdSchema, upsertJsonLd, variantOption, weightMarks, wireKinds, wireframeIssues, withEmphasis, withoutOrphanSections };
|
|
308
|
+
export { API_PREFIX, type ApiIssue, type ApiProblem, BRAND_LOGO_HEIGHT, type BaseSection, type BooleanOption, type ButtonStyle, type ChangedFile, type CommitRequest, type CommitResult, type ConsentCopy, type ConsentReopen, type ConsentText, type ConsentTextKey, type ContentIssue, type ContentMigration, type ContentMigrator, type ContentModel, type ContentVersioning, type ContrastCheck, type CountRule, type CreatePageRequest, DEFAULT_MAX_FOOTER_COLUMNS, DEFAULT_MAX_HEADER_ACTIONS, type DocumentKind, type EnumOption, type FieldChoices, type FieldIcons, type FontMark, type Footer, type FooterColumn, type FooterConfig, type FormFieldErrors, type FormResult, type FormSubmission, type GitInfo, HONEYPOT_FIELD, type Header, type HeaderConfig, type HistoryEntry, type Image, type ImageFit, type ImagePosition, type JsonLdBlock, type JsonLdResult, type Link, MAX_NAV_DEPTH, type MediaSource, type NumberOption, type Option, type OptionalContent, type Page, type PageListItem, type PropsOf, type RichText, SCHEMA_VERSION_KEY, SYSTEM_PAGES, type SaveRequest, type SaveResponse, type SectionConfig, type SectionDefinition, type SectionOf, type SectionRegistry, type Seo, type ShowCondition, type ShowWhen, type Site, type SiteAnalytics, type SiteConfig, type SiteConsent, type SiteDefinition, type SiteJsonLdIds, type SiteJsonLdSource, type SiteOf, type SitePreview, type SitePreviewHtml, type SiteSeo, type SiteWith, type StringOption, TURNSTILE_FIELD, type Text, type TextMark, type TextRun, type Theme, type ThemeColors, type ThemeConfig, type ThemeDefinition, type ThemeFont, type ThemePreview, type Tone, type UploadedImage, type UploadedVideo, type WeightMark, type WireKind, type WireRect, type Wireframe, anchorSchema, applyTextMark, brandLogoSchema, buttonStyles, createMigrator, createPageSchema, createSectionSchema, defaultTheme, defineSection, defineSite, defineTheme, defineWireframe, fontMarks, formatJsonLd, generateSiteJsonLd, hasJsonLdId, htmlIdSchema, imageSchema, isPlaceholderSiteUrl, isSystemPage, jsonLdSchema, jsonLdWarnings, linkSchema, markClass, marksFromEmphasis, mergeJsonLd, motionOption, parseJsonLdInput, reconcileMarks, renderMarkedHtml, richTextSchema, sectionIdSchema, seoSchema, siteAnalyticsSchema, siteConsentSchema, siteJsonLdIds, siteSeoSchema, splitMarkedText, textMarkSchema, textSchema, themeColorsSchema, themeModes, themeSchema, toneOption, toneSchema, tones, trackingIdSchema, upsertJsonLd, variantOption, weightMarks, wireKinds, wireframeIssues, withEmphasis, withoutOrphanSections };
|
package/dist/index.js
CHANGED
|
@@ -3,6 +3,7 @@ import { n as defineTheme, t as defaultTheme } from "./theme-DFjHjgFO.js";
|
|
|
3
3
|
import { A as textSchema, C as MAX_NAV_DEPTH, D as linkSchema, E as imageSchema, F as DEFAULT_IMAGE_POSITION, G as tones, H as motionOption, I as IMAGE_FITS, K as variantOption, L as IMAGE_POSITIONS, M as trackingIdSchema, N as withEmphasis, O as richTextSchema, P as DEFAULT_IMAGE_FIT, R as isImageFit, S as upsertJsonLd, T as htmlIdSchema, U as themeModes, V as buttonStyles, W as toneOption, _ as jsonLdSchema, a as seoSchema, b as parseJsonLdInput, c as anchorSchema, d as sectionIdSchema, f as walkLinkIds, g as isPlaceholderSiteUrl, h as hasJsonLdId, i as isSystemPage, j as toneSchema, k as textMarkSchema, l as createSectionSchema, m as generateSiteJsonLd, n as createPageSchema, p as formatJsonLd, s as withoutOrphanSections, t as SYSTEM_PAGES, v as jsonLdWarnings, w as addMarkIssues, x as siteJsonLdIds, y as mergeJsonLd, z as isImagePosition } from "./page-NOFVEqn1.js";
|
|
4
4
|
import { applyTextMark, fontMarks, markClass, marksFromEmphasis, reconcileMarks, renderMarkedHtml, splitMarkedText, weightMarks } from "./marks.js";
|
|
5
5
|
import { n as createMigrator, r as API_PREFIX, t as SCHEMA_VERSION_KEY } from "./migrate-b408EaLp.js";
|
|
6
|
+
import { n as TURNSTILE_FIELD, t as HONEYPOT_FIELD } from "./form-contract-CIDTNab-.js";
|
|
6
7
|
import { _ as consentCopy, a as contrastRatio, b as parseMediaSource, c as hasThemeColors, d as tokenToHex, f as CONSENT_COPY, g as CONSENT_REOPEN, h as CONSENT_LIMITS, i as contrastChecks, l as hexToToken, m as CONSENT_HREF_MESSAGE, n as HEX_COLOR, o as derivePalette, p as CONSENT_HREF, s as hasOverrides, u as themeCss, v as consentTextIssues, y as VIDEO_FILE } from "./theme-colors-CHROGZkI.js";
|
|
7
8
|
import { z } from "zod";
|
|
8
9
|
//#region src/wireframe.ts
|
|
@@ -105,6 +106,7 @@ function defineSection(config) {
|
|
|
105
106
|
choices,
|
|
106
107
|
icons,
|
|
107
108
|
showWhen,
|
|
109
|
+
form: config.form,
|
|
108
110
|
refine: config.refine
|
|
109
111
|
});
|
|
110
112
|
}
|
|
@@ -441,4 +443,4 @@ function defineSite(config) {
|
|
|
441
443
|
};
|
|
442
444
|
}
|
|
443
445
|
//#endregion
|
|
444
|
-
export { API_PREFIX, BRAND_LOGO_HEIGHT, CONSENT_COPY, CONSENT_HREF, CONSENT_LIMITS, CONSENT_REOPEN, ContentError, ContentReadError, ContentValidationError, DEFAULT_IMAGE_FIT, DEFAULT_IMAGE_POSITION, DEFAULT_MAX_FOOTER_COLUMNS, DEFAULT_MAX_HEADER_ACTIONS, HEX_COLOR, IMAGE_FITS, IMAGE_POSITIONS, MAX_NAV_DEPTH, SCHEMA_VERSION_KEY, SYSTEM_PAGES, VIDEO_FILE, anchorSchema, applyTextMark, brandLogoSchema, buttonStyles, consentCopy, consentTextIssues, contrastChecks, contrastRatio, createMigrator, createPageSchema, createSectionSchema, defaultTheme, defineSection, defineSite, defineTheme, defineThemePreview, defineWireframe, derivePalette, fontMarks, formatJsonLd, generateSiteJsonLd, hasJsonLdId, hasOverrides, hasThemeColors, hexToToken, htmlIdSchema, imageSchema, isImageFit, isImagePosition, isPlaceholderSiteUrl, isSystemPage, jsonLdSchema, jsonLdWarnings, linkSchema, markClass, marksFromEmphasis, mergeJsonLd, motionOption, parseJsonLdInput, parseMediaSource, reconcileMarks, renderMarkedHtml, richTextSchema, sectionIdSchema, seoSchema, siteAnalyticsSchema, siteConsentSchema, siteJsonLdIds, siteSeoSchema, splitMarkedText, textMarkSchema, textSchema, themeColorsSchema, themeCss, themeModes, themeSchema, tokenToHex, toneOption, toneSchema, tones, trackingIdSchema, upsertJsonLd, variantOption, weightMarks, wireKinds, wireframeIssues, withEmphasis, withoutOrphanSections };
|
|
446
|
+
export { API_PREFIX, BRAND_LOGO_HEIGHT, CONSENT_COPY, CONSENT_HREF, CONSENT_LIMITS, CONSENT_REOPEN, ContentError, ContentReadError, ContentValidationError, DEFAULT_IMAGE_FIT, DEFAULT_IMAGE_POSITION, DEFAULT_MAX_FOOTER_COLUMNS, DEFAULT_MAX_HEADER_ACTIONS, HEX_COLOR, HONEYPOT_FIELD, IMAGE_FITS, IMAGE_POSITIONS, MAX_NAV_DEPTH, SCHEMA_VERSION_KEY, SYSTEM_PAGES, TURNSTILE_FIELD, VIDEO_FILE, anchorSchema, applyTextMark, brandLogoSchema, buttonStyles, consentCopy, consentTextIssues, contrastChecks, contrastRatio, createMigrator, createPageSchema, createSectionSchema, defaultTheme, defineSection, defineSite, defineTheme, defineThemePreview, defineWireframe, derivePalette, fontMarks, formatJsonLd, generateSiteJsonLd, hasJsonLdId, hasOverrides, hasThemeColors, hexToToken, htmlIdSchema, imageSchema, isImageFit, isImagePosition, isPlaceholderSiteUrl, isSystemPage, jsonLdSchema, jsonLdWarnings, linkSchema, markClass, marksFromEmphasis, mergeJsonLd, motionOption, parseJsonLdInput, parseMediaSource, reconcileMarks, renderMarkedHtml, richTextSchema, sectionIdSchema, seoSchema, siteAnalyticsSchema, siteConsentSchema, siteJsonLdIds, siteSeoSchema, splitMarkedText, textMarkSchema, textSchema, themeColorsSchema, themeCss, themeModes, themeSchema, tokenToHex, toneOption, toneSchema, tones, trackingIdSchema, upsertJsonLd, variantOption, weightMarks, wireKinds, wireframeIssues, withEmphasis, withoutOrphanSections };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as SectionRegistry, J as SiteDefinition, M as ThemeDefinition, Yt as ContentMigrator, k as ContentModel } from "./page-
|
|
1
|
+
import { A as SectionRegistry, J as SiteDefinition, M as ThemeDefinition, Yt as ContentMigrator, k as ContentModel } from "./page-BfI9cD8g.js";
|
|
2
2
|
//#region src/images.d.ts
|
|
3
3
|
type ImageKind = 'png' | 'jpeg' | 'webp' | 'gif' | 'avif';
|
|
4
4
|
interface SavedImage {
|
|
@@ -117,6 +117,16 @@ interface BearminionOptions extends ContentModel {
|
|
|
117
117
|
* Default `/src/lib/render-preview.ts`. Preview never writes to disk.
|
|
118
118
|
*/
|
|
119
119
|
previewModule?: string;
|
|
120
|
+
/**
|
|
121
|
+
* The dev route for the forms in your site. A file `src/forms/contact.ts` that default-exports `defineForm(...)`
|
|
122
|
+
* answers at `/api/contact` during `astro dev`, as a dry run unless `BEARMINION_FORMS_LIVE=on`. `dir` is the folder
|
|
123
|
+
* (default `src/forms`) and `prefix` the path (default `/api`). `false` turns the route off, for a site whose
|
|
124
|
+
* Astro adapter serves the endpoint itself.
|
|
125
|
+
*/
|
|
126
|
+
forms?: false | {
|
|
127
|
+
dir?: string;
|
|
128
|
+
prefix?: string;
|
|
129
|
+
};
|
|
120
130
|
/**
|
|
121
131
|
* Show Commit changes in the editor, which commits the changed content and uploads to the local git repository.
|
|
122
132
|
* Off by default. It never pushes, and it does nothing outside a git work tree.
|
|
@@ -143,6 +153,8 @@ interface EditorContext {
|
|
|
143
153
|
migrator: ContentMigrator;
|
|
144
154
|
/** Commit changes is enabled. */
|
|
145
155
|
git: boolean;
|
|
156
|
+
/** The folder with the site's form handlers, or `null` when the `forms` option turns them off. */
|
|
157
|
+
formsDir?: string | null;
|
|
146
158
|
}
|
|
147
159
|
//#endregion
|
|
148
160
|
export { StoreKeyError as a, createFileStore as c, FileStoreOptions as i, EditorContext as n, StoreOperation as o, ContentStore as r, UploadStore as s, BearminionOptions as t };
|
|
@@ -172,6 +172,7 @@ declare function defineWireframe(wireframe: Wireframe): Wireframe;
|
|
|
172
172
|
* - `wireframe` is the thumbnail in the Add section picker.
|
|
173
173
|
* - `choices` lists every string enum in `props` (derived from the schema); the sidebar offers them as choices.
|
|
174
174
|
* - `icons` draws those choices as icons in the sidebar's picker.
|
|
175
|
+
* - `form` names the handler in `src/forms` that receives what the section's form sends. The sidebar says whether it exists.
|
|
175
176
|
* - `showWhen` hides props in the sidebar while the section's options make them unused.
|
|
176
177
|
*/
|
|
177
178
|
interface SectionDefinition<TType extends string = string, TSchema extends z.ZodType = z.ZodType, TVariant extends string = string> {
|
|
@@ -190,6 +191,7 @@ interface SectionDefinition<TType extends string = string, TSchema extends z.Zod
|
|
|
190
191
|
readonly choices: FieldChoices;
|
|
191
192
|
readonly icons: FieldIcons;
|
|
192
193
|
readonly showWhen: ShowWhen;
|
|
194
|
+
readonly form?: string;
|
|
193
195
|
/** Cross-field rules the schema cannot express, such as a variant that needs an exact item count. */
|
|
194
196
|
refine?(section: {
|
|
195
197
|
variant: TVariant;
|
|
@@ -220,6 +222,8 @@ interface SectionConfig<TType extends string, TSchema extends z.ZodType, TVarian
|
|
|
220
222
|
* means any of its values; `variant`, `tone` and `motion` count as options. A hidden prop keeps its value in the file.
|
|
221
223
|
*/
|
|
222
224
|
showWhen?: ShowWhen;
|
|
225
|
+
/** The form handler this section posts to: the file `src/forms/<form>.ts`, answering at `/api/<form>`. */
|
|
226
|
+
form?: string;
|
|
223
227
|
refine?(section: {
|
|
224
228
|
variant: TVariants[number];
|
|
225
229
|
props: z.infer<TSchema>;
|
|
@@ -271,10 +275,10 @@ declare const textMarkSchema: z.ZodObject<{
|
|
|
271
275
|
start: z.ZodNumber;
|
|
272
276
|
end: z.ZodNumber;
|
|
273
277
|
weight: z.ZodOptional<z.ZodEnum<{
|
|
274
|
-
bold: "bold";
|
|
275
278
|
regular: "regular";
|
|
276
279
|
medium: "medium";
|
|
277
280
|
semibold: "semibold";
|
|
281
|
+
bold: "bold";
|
|
278
282
|
}>>;
|
|
279
283
|
italic: z.ZodOptional<z.ZodBoolean>;
|
|
280
284
|
font: z.ZodOptional<z.ZodEnum<{
|
|
@@ -315,10 +319,10 @@ declare function withEmphasis<T extends z.ZodRawShape>(shape: T): z.ZodPipe<z.Zo
|
|
|
315
319
|
start: z.ZodNumber;
|
|
316
320
|
end: z.ZodNumber;
|
|
317
321
|
weight: z.ZodOptional<z.ZodEnum<{
|
|
318
|
-
bold: "bold";
|
|
319
322
|
regular: "regular";
|
|
320
323
|
medium: "medium";
|
|
321
324
|
semibold: "semibold";
|
|
325
|
+
bold: "bold";
|
|
322
326
|
}>>;
|
|
323
327
|
italic: z.ZodOptional<z.ZodBoolean>;
|
|
324
328
|
font: z.ZodOptional<z.ZodEnum<{
|
|
@@ -333,10 +337,10 @@ declare function withEmphasis<T extends z.ZodRawShape>(shape: T): z.ZodPipe<z.Zo
|
|
|
333
337
|
start: z.ZodNumber;
|
|
334
338
|
end: z.ZodNumber;
|
|
335
339
|
weight: z.ZodOptional<z.ZodEnum<{
|
|
336
|
-
bold: "bold";
|
|
337
340
|
regular: "regular";
|
|
338
341
|
medium: "medium";
|
|
339
342
|
semibold: "semibold";
|
|
343
|
+
bold: "bold";
|
|
340
344
|
}>>;
|
|
341
345
|
italic: z.ZodOptional<z.ZodBoolean>;
|
|
342
346
|
font: z.ZodOptional<z.ZodEnum<{
|
|
@@ -353,10 +357,10 @@ declare function withEmphasis<T extends z.ZodRawShape>(shape: T): z.ZodPipe<z.Zo
|
|
|
353
357
|
start: z.ZodNumber;
|
|
354
358
|
end: z.ZodNumber;
|
|
355
359
|
weight: z.ZodOptional<z.ZodEnum<{
|
|
356
|
-
bold: "bold";
|
|
357
360
|
regular: "regular";
|
|
358
361
|
medium: "medium";
|
|
359
362
|
semibold: "semibold";
|
|
363
|
+
bold: "bold";
|
|
360
364
|
}>>;
|
|
361
365
|
italic: z.ZodOptional<z.ZodBoolean>;
|
|
362
366
|
font: z.ZodOptional<z.ZodEnum<{
|
|
@@ -613,10 +617,10 @@ declare function createSiteSchema(header: HeaderParts, footer: FooterParts): z.Z
|
|
|
613
617
|
start: z.ZodNumber;
|
|
614
618
|
end: z.ZodNumber;
|
|
615
619
|
weight: z.ZodOptional<z.ZodEnum<{
|
|
616
|
-
bold: "bold";
|
|
617
620
|
regular: "regular";
|
|
618
621
|
medium: "medium";
|
|
619
622
|
semibold: "semibold";
|
|
623
|
+
bold: "bold";
|
|
620
624
|
}>>;
|
|
621
625
|
italic: z.ZodOptional<z.ZodBoolean>;
|
|
622
626
|
font: z.ZodOptional<z.ZodEnum<{
|
|
@@ -848,7 +852,7 @@ declare function createSiteSchema(header: HeaderParts, footer: FooterParts): z.Z
|
|
|
848
852
|
nameMarks: {
|
|
849
853
|
start: number;
|
|
850
854
|
end: number;
|
|
851
|
-
weight?: "
|
|
855
|
+
weight?: "regular" | "medium" | "semibold" | "bold" | undefined;
|
|
852
856
|
italic?: boolean | undefined;
|
|
853
857
|
font?: "sans" | "serif" | "mono" | undefined;
|
|
854
858
|
}[] | undefined;
|
|
@@ -1106,7 +1110,7 @@ declare function createSiteSchema(header: HeaderParts, footer: FooterParts): z.Z
|
|
|
1106
1110
|
nameMarks?: {
|
|
1107
1111
|
start: number;
|
|
1108
1112
|
end: number;
|
|
1109
|
-
weight?: "
|
|
1113
|
+
weight?: "regular" | "medium" | "semibold" | "bold" | undefined;
|
|
1110
1114
|
italic?: boolean | undefined;
|
|
1111
1115
|
font?: "sans" | "serif" | "mono" | undefined;
|
|
1112
1116
|
}[] | undefined;
|
package/dist/ui/mount.js
CHANGED
|
@@ -14309,7 +14309,7 @@ function attachShortcuts(editor) {
|
|
|
14309
14309
|
if (ui.open.peek() && !isTyping(event.target)) ui.open.value = false;
|
|
14310
14310
|
};
|
|
14311
14311
|
const onKey = (event) => {
|
|
14312
|
-
const key = event.key.toLowerCase();
|
|
14312
|
+
const key = (event.key ?? "").toLowerCase();
|
|
14313
14313
|
const mod = event.metaKey || event.ctrlKey;
|
|
14314
14314
|
if (mod && key === "s") {
|
|
14315
14315
|
event.preventDefault();
|
|
@@ -14711,6 +14711,8 @@ function uploadVideo(file) {
|
|
|
14711
14711
|
});
|
|
14712
14712
|
}
|
|
14713
14713
|
const getGit = () => request("/git");
|
|
14714
|
+
/** Whether the form handlers the sections post to exist in `src/forms`. */
|
|
14715
|
+
const getForms = () => request("/forms");
|
|
14714
14716
|
const commit = (body) => request("/git/commit", sendJson("POST", body));
|
|
14715
14717
|
/** Saved versions of the site (`scope` site) or of one page. */
|
|
14716
14718
|
function historyPath(scope, slug) {
|
|
@@ -22646,6 +22648,56 @@ function PagesForm({ pages, labels, current, homeSlug, onCreated, onNavigate })
|
|
|
22646
22648
|
});
|
|
22647
22649
|
}
|
|
22648
22650
|
//#endregion
|
|
22651
|
+
//#region src/ui/forms/form-handler.tsx
|
|
22652
|
+
const FORMS_DOCS = "https://docs.bearminion.com/forms";
|
|
22653
|
+
/**
|
|
22654
|
+
* What the sidebar says about the code behind a section's form. BearMinion can see that the file exists, not that it
|
|
22655
|
+
* works: its keys, its service and its host are outside the project, so the note says to test it by hand.
|
|
22656
|
+
*/
|
|
22657
|
+
function describeHandler(name, file) {
|
|
22658
|
+
if (file === null) return {
|
|
22659
|
+
tone: "warn",
|
|
22660
|
+
text: `Nothing receives this form yet: there is no src/forms/${name}.ts. A visitor who sends it gets an error. Create the file to connect it.`
|
|
22661
|
+
};
|
|
22662
|
+
return {
|
|
22663
|
+
tone: "hint",
|
|
22664
|
+
text: `This form posts to /api/${name}, handled by your own code in ${file}. BearMinion cannot check that it works: send a test message and see that it arrives.`
|
|
22665
|
+
};
|
|
22666
|
+
}
|
|
22667
|
+
/** Under a section's fields, for a section that posts to a handler of the site. */
|
|
22668
|
+
function FormHandlerNote({ name }) {
|
|
22669
|
+
const [file, setFile] = useState(void 0);
|
|
22670
|
+
useEffect(() => {
|
|
22671
|
+
let current = true;
|
|
22672
|
+
getForms().then((answer) => {
|
|
22673
|
+
if (!current) return;
|
|
22674
|
+
setFile(answer.ok && answer.value.enabled ? answer.value.handlers[name]?.file ?? null : void 0);
|
|
22675
|
+
}, () => {
|
|
22676
|
+
if (current) setFile(void 0);
|
|
22677
|
+
});
|
|
22678
|
+
return () => {
|
|
22679
|
+
current = false;
|
|
22680
|
+
};
|
|
22681
|
+
}, [name]);
|
|
22682
|
+
if (file === void 0) return null;
|
|
22683
|
+
const note = describeHandler(name, file);
|
|
22684
|
+
return /* @__PURE__ */ jsxs("span", {
|
|
22685
|
+
class: note.tone === "warn" ? "bm-error" : "bm-hint",
|
|
22686
|
+
role: note.tone === "warn" ? "alert" : "status",
|
|
22687
|
+
"data-form-handler": name,
|
|
22688
|
+
children: [
|
|
22689
|
+
note.text,
|
|
22690
|
+
" ",
|
|
22691
|
+
/* @__PURE__ */ jsx("a", {
|
|
22692
|
+
href: FORMS_DOCS,
|
|
22693
|
+
target: "_blank",
|
|
22694
|
+
rel: "noopener",
|
|
22695
|
+
children: "How to set up a form"
|
|
22696
|
+
})
|
|
22697
|
+
]
|
|
22698
|
+
});
|
|
22699
|
+
}
|
|
22700
|
+
//#endregion
|
|
22649
22701
|
//#region src/ui/forms/section-form.tsx
|
|
22650
22702
|
const LAYOUT_OPTIONS = [
|
|
22651
22703
|
"variant",
|
|
@@ -22892,6 +22944,7 @@ function SectionForm({ section, index, sections, catalog, siteMotion, taken, ima
|
|
|
22892
22944
|
})
|
|
22893
22945
|
})
|
|
22894
22946
|
}),
|
|
22947
|
+
catalog.sectionForms?.[section.type] && /* @__PURE__ */ jsx(FormHandlerNote, { name: catalog.sectionForms[section.type] }),
|
|
22895
22948
|
/* @__PURE__ */ jsxs("div", {
|
|
22896
22949
|
class: "bm-actions-split",
|
|
22897
22950
|
children: [/* @__PURE__ */ jsx("button", {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bearminion",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.7.0",
|
|
4
4
|
"description": "A git-based CMS for Astro with no database and no server: JSON content in your repo, edited by clicking on the page during astro dev.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Jakub Lange",
|
|
@@ -48,6 +48,10 @@
|
|
|
48
48
|
"types": "./dist/marks.d.ts",
|
|
49
49
|
"import": "./dist/marks.js"
|
|
50
50
|
},
|
|
51
|
+
"./forms": {
|
|
52
|
+
"types": "./dist/forms.d.ts",
|
|
53
|
+
"import": "./dist/forms.js"
|
|
54
|
+
},
|
|
51
55
|
"./package.json": "./package.json"
|
|
52
56
|
},
|
|
53
57
|
"files": [
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { o as slugSchema } from "./page-NOFVEqn1.js";
|
|
2
|
-
import { fileURLToPath } from "node:url";
|
|
3
2
|
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
4
|
//#region src/security.ts
|
|
5
5
|
const JSON_BODY_LIMIT = 1048576;
|
|
6
6
|
const IMAGE_BYTE_LIMIT = 5242880;
|