bearminion 1.6.0 → 1.8.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 CHANGED
@@ -1,5 +1,26 @@
1
1
  # bearminion
2
2
 
3
+ ## 1.8.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 305d094: A section type is now a directory, and nothing else has to be edited. `npx bearminion sync` (new command) writes `definitions.gen.ts` and `components.gen.ts` from the directories under `sections/`; the starter's hand-written `registry.ts` and the `case` per section in `SectionList.astro` are gone. The new `sectionsDir` option makes `astro build`, `astro check` and `astro sync` stop when the generated files are stale, and `astro dev` warn. `npx bearminion sync --check` is the same test for CI.
8
+
9
+ Sites created before this release keep working as they are. To move one over, copy `definitions.ts`, `SectionList.astro` and `astro.config.ts` from a new site, delete `registry.ts`, run `npx bearminion sync`, and read [Add a section type](https://github.com/langehelp-software/bearminion/blob/main/templates/default/README.md#add-a-section-type).
10
+
11
+ ## 1.7.0
12
+
13
+ ### Minor Changes
14
+
15
+ - 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.
16
+ - 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.
17
+
18
+ ### Patch Changes
19
+
20
+ - 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.
21
+ - 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.
22
+ - 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).
23
+
3
24
  ## 1.6.0
4
25
 
5
26
  ### 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-BFuPEq6Q.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-DdCyRbPs.js";
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-CA4iyFDS.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-4HWVEj9O.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,17 @@ 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-D0vwI0OT.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-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
+ import { n as staleSectionsMessage, r as syncSections } from "./sections-manifest-CU-xBjMi.js";
7
8
  import { z } from "zod";
8
9
  import fs from "node:fs";
9
- import { fileURLToPath } from "node:url";
10
10
  import path from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+ import { parseEnv, promisify } from "node:util";
11
13
  import { randomBytes } from "node:crypto";
12
14
  import { access, mkdir, readFile, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
13
15
  import { execFile } from "node:child_process";
14
- import { promisify } from "node:util";
15
16
  //#region src/editor-client.ts
16
17
  const VIRTUAL_ID = "virtual:bearminion-editor";
17
18
  const RESOLVED_ID = `\0${VIRTUAL_ID}`;
@@ -35,6 +36,134 @@ function editorClientPlugin() {
35
36
  };
36
37
  }
37
38
  //#endregion
39
+ //#region src/forms-dev.ts
40
+ /** Where the forms are and under which path, or `null` when the option turns them off. */
41
+ function resolveFormsConfig(option, root) {
42
+ if (option === false) return null;
43
+ const prefix = (option?.prefix ?? "/api").replace(/\/+$/, "");
44
+ return {
45
+ dir: resolveDir(root, option?.dir, "src/forms"),
46
+ prefix: prefix.startsWith("/") ? prefix : `/${prefix}`
47
+ };
48
+ }
49
+ const FORM_FILE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
50
+ const EXTENSIONS = [
51
+ ".ts",
52
+ ".mts",
53
+ ".js",
54
+ ".mjs"
55
+ ];
56
+ const BODY_LIMIT = 1048576;
57
+ /** The file behind `name`, or `null` when there is none. `name` is checked, so it cannot leave the folder. */
58
+ function formFile(dir, name) {
59
+ if (!FORM_FILE.test(name)) return null;
60
+ for (const extension of EXTENSIONS) {
61
+ const file = path.join(dir, `${name}${extension}`);
62
+ if (fs.existsSync(file)) return file;
63
+ }
64
+ return null;
65
+ }
66
+ /** `.env`, `.env.local`, `.env.development` and `.env.development.local` of the project, later ones winning. */
67
+ function readDotEnv(root) {
68
+ const merged = {};
69
+ for (const name of [
70
+ ".env",
71
+ ".env.local",
72
+ ".env.development",
73
+ ".env.development.local"
74
+ ]) try {
75
+ Object.assign(merged, parseEnv(fs.readFileSync(path.join(root, name), "utf8")));
76
+ } catch {}
77
+ return merged;
78
+ }
79
+ /** True when `BEARMINION_FORMS_LIVE=on` is in the environment or in the project's `.env` files. */
80
+ function formsAreLive(root) {
81
+ return (process.env.BEARMINION_FORMS_LIVE ?? readDotEnv(root).BEARMINION_FORMS_LIVE) === "on";
82
+ }
83
+ function isForm(value) {
84
+ return typeof value === "object" && value !== null && typeof value.fetch === "function";
85
+ }
86
+ function createFormsMiddleware(options) {
87
+ return (req, res, next) => {
88
+ const pathname = (req.url ?? "/").split("?")[0]?.replace(/\/+$/, "") ?? "";
89
+ if (!pathname.startsWith(`${options.prefix}/`)) {
90
+ next();
91
+ return;
92
+ }
93
+ const name = pathname.slice(options.prefix.length + 1);
94
+ const file = formFile(options.dir, name);
95
+ if (!file) {
96
+ next();
97
+ return;
98
+ }
99
+ answer(req, res, options, name, file).catch((error) => {
100
+ options.log.error(`/${name}: ${error instanceof Error ? error.stack ?? error.message : String(error)}`);
101
+ if (!res.headersSent) fail(res, 500, error instanceof Error ? error.message : "The form failed.");
102
+ });
103
+ };
104
+ }
105
+ function fail(res, status, error) {
106
+ res.statusCode = status;
107
+ res.setHeader("content-type", "application/json; charset=utf-8");
108
+ res.end(JSON.stringify({
109
+ ok: false,
110
+ error
111
+ }));
112
+ }
113
+ async function answer(req, res, options, name, file) {
114
+ const form = (await options.load(file))?.default;
115
+ if (!isForm(form)) {
116
+ const relative = path.relative(options.root, file).split(path.sep).join("/");
117
+ options.log.error(`${relative} must \`export default defineForm(...)\` from 'bearminion/forms'.`);
118
+ return fail(res, 500, `${relative} must export default defineForm(...).`);
119
+ }
120
+ const headers = new Headers();
121
+ for (const [key, value] of Object.entries(req.headers)) {
122
+ if (value === void 0) continue;
123
+ for (const item of Array.isArray(value) ? value : [value]) headers.append(key, item);
124
+ }
125
+ const method = (req.method ?? "GET").toUpperCase();
126
+ const body = method === "GET" || method === "HEAD" ? void 0 : await readLimited(req, BODY_LIMIT);
127
+ if (body === null) return fail(res, 413, "The message is too large.");
128
+ const request = new Request(`http://${req.headers.host ?? "localhost"}${req.url ?? "/"}`, {
129
+ method,
130
+ headers,
131
+ ...body ? { body } : {}
132
+ });
133
+ const env = {
134
+ ...readDotEnv(options.root),
135
+ ...process.env
136
+ };
137
+ const response = await form.fetch(request, env, {
138
+ dev: true,
139
+ ...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)}`) }
140
+ });
141
+ res.statusCode = response.status;
142
+ response.headers.forEach((value, key) => {
143
+ res.setHeader(key, value);
144
+ });
145
+ res.end(Buffer.from(await response.arrayBuffer()));
146
+ }
147
+ /** The body of the request, or `null` once it is over `limit` bytes. */
148
+ function readLimited(req, limit) {
149
+ return new Promise((resolve, reject) => {
150
+ const chunks = [];
151
+ let size = 0;
152
+ req.on("data", (chunk) => {
153
+ const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
154
+ size += buffer.length;
155
+ if (size > limit) {
156
+ resolve(null);
157
+ req.resume();
158
+ return;
159
+ }
160
+ chunks.push(buffer);
161
+ });
162
+ req.on("end", () => resolve(new Uint8Array(Buffer.concat(chunks))));
163
+ req.on("error", reject);
164
+ });
165
+ }
166
+ //#endregion
38
167
  //#region src/videos.ts
39
168
  const EXTENSION$1 = {
40
169
  mp4: ".mp4",
@@ -446,7 +575,8 @@ function resolveEditorContext(options, rootInput) {
446
575
  videosDir
447
576
  }),
448
577
  migrator: createMigrator(options),
449
- git: options?.git === true
578
+ git: options?.git === true,
579
+ formsDir: resolveFormsConfig(options?.forms, root)?.dir ?? null
450
580
  };
451
581
  }
452
582
  //#endregion
@@ -714,6 +844,10 @@ async function handleEditorRequest(request, context, meta = {}) {
714
844
  if (method === "POST") return createPage(request, context);
715
845
  return methodNotAllowed(["GET", "POST"]);
716
846
  }
847
+ if (parts.length === 1 && parts[0] === "forms") {
848
+ if (method === "GET") return getForms(context);
849
+ return methodNotAllowed(["GET"]);
850
+ }
717
851
  if (parts.length === 1 && parts[0] === "git") {
718
852
  if (method === "GET") return getGit(context);
719
853
  return methodNotAllowed(["GET"]);
@@ -783,6 +917,27 @@ async function handleEditorRequest(request, context, meta = {}) {
783
917
  }
784
918
  return problem(404, "not_found", "Unknown editor API route.");
785
919
  }
920
+ /**
921
+ * Which form handlers the sections post to, and whether their files exist right now. Read on every call, so a handler
922
+ * created while `astro dev` runs shows up at once.
923
+ */
924
+ async function getForms(context) {
925
+ const handlers = {};
926
+ for (const definition of Object.values(context.sections)) {
927
+ const name = definition.form;
928
+ if (!name || handlers[name]) continue;
929
+ const file = context.formsDir ? formFile(context.formsDir, name) : null;
930
+ handlers[name] = { file: file ? relativeTo(context.root, file) : null };
931
+ }
932
+ return json(200, {
933
+ enabled: context.formsDir != null,
934
+ handlers
935
+ });
936
+ }
937
+ function relativeTo(root, file) {
938
+ const prefix = root.endsWith("/") || root.endsWith("\\") ? root : `${root}/`;
939
+ return file.startsWith(prefix) ? file.slice(prefix.length).replaceAll("\\", "/") : file;
940
+ }
786
941
  async function getSchema(context) {
787
942
  const sectionDefaults = {};
788
943
  const sectionLabels = {};
@@ -795,8 +950,10 @@ async function getSchema(context) {
795
950
  const fieldIcons = {};
796
951
  const showWhen = {};
797
952
  const fieldImages = {};
953
+ const sectionForms = {};
798
954
  for (const definition of Object.values(context.sections)) {
799
955
  const type = definition.type;
956
+ if (definition.form) sectionForms[type] = definition.form;
800
957
  sectionDefaults[type] = definition.defaults;
801
958
  sectionLabels[type] = definition.label;
802
959
  sectionDescriptions[type] = definition.description;
@@ -821,6 +978,7 @@ async function getSchema(context) {
821
978
  fieldIcons,
822
979
  fieldImages,
823
980
  showWhen,
981
+ sectionForms,
824
982
  sectionDefaults,
825
983
  sectionLabels,
826
984
  sectionDescriptions,
@@ -1840,7 +1998,14 @@ function bearminion(options) {
1840
1998
  return {
1841
1999
  name: "bearminion",
1842
2000
  hooks: {
1843
- "astro:config:setup"({ command, config, updateConfig, injectScript }) {
2001
+ "astro:config:setup"({ command, config, updateConfig, injectScript, logger }) {
2002
+ if (options.sectionsDir !== void 0) {
2003
+ const { changed } = syncSections(path.resolve(rootPath(config.root), options.sectionsDir), { check: true });
2004
+ if (changed.length > 0) {
2005
+ if (command !== "dev") throw new Error(staleSectionsMessage(changed));
2006
+ logger.warn(staleSectionsMessage(changed));
2007
+ }
2008
+ }
1844
2009
  if (command !== "dev") return;
1845
2010
  const context = resolveEditorContext(options, rootInput(config.root));
1846
2011
  updateConfig({ vite: {
@@ -1853,10 +2018,22 @@ function bearminion(options) {
1853
2018
  } });
1854
2019
  injectScript("page", "import \"virtual:bearminion-editor\"");
1855
2020
  },
1856
- "astro:server:setup"({ server }) {
2021
+ "astro:server:setup"({ server, logger }) {
1857
2022
  const context = resolveEditorContext(options, server.config.root);
1858
2023
  const previewModule = options.previewModule ?? "/src/lib/render-preview.ts";
1859
2024
  const reloads = dropEarlyReloadAfterSave(server);
2025
+ server.middlewares.use(announceVideoChanges(server, context.videosDir));
2026
+ const forms = resolveFormsConfig(options.forms, context.root);
2027
+ if (forms) server.middlewares.use(createFormsMiddleware({
2028
+ ...forms,
2029
+ root: context.root,
2030
+ live: formsAreLive(context.root),
2031
+ load: (file) => loadModule(server.environments.ssr, file),
2032
+ log: {
2033
+ info: (message) => logger.info(message),
2034
+ error: (message) => logger.error(message)
2035
+ }
2036
+ }));
1860
2037
  server.middlewares.use((req, _res, next) => {
1861
2038
  if (req.method === "POST" && (req.url ?? "").split("?")[0]?.replace(/\/$/, "") === `/__bearminion/api/save`) reloads.saving();
1862
2039
  next();
@@ -1869,6 +2046,39 @@ function bearminion(options) {
1869
2046
  }
1870
2047
  };
1871
2048
  }
2049
+ /**
2050
+ * The videos folder is ignored by the file watcher (see above), but Vite learns which files `public/` holds from that
2051
+ * watcher, and answers 404 for any other path. So a video uploaded in the editor would not play in the dev site until
2052
+ * the server restarted. After an upload or delete, tell Vite about exactly the files that appeared or went away.
2053
+ * The event only refreshes Vite's list of public files; it does not reload the page, so the draft stays.
2054
+ */
2055
+ function announceVideoChanges(server, videosDir) {
2056
+ const list = () => {
2057
+ try {
2058
+ return new Set(fs.readdirSync(videosDir));
2059
+ } catch {
2060
+ return /* @__PURE__ */ new Set();
2061
+ }
2062
+ };
2063
+ return (req, res, next) => {
2064
+ const route = (req.url ?? "").split("?")[0]?.replace(/\/$/, "") ?? "";
2065
+ if ((req.method === "POST" || req.method === "DELETE") && (route === `/__bearminion/api/videos` || route.startsWith(`/__bearminion/api/videos/`))) {
2066
+ const before = list();
2067
+ res.once("finish", () => {
2068
+ const after = list();
2069
+ for (const name of after) if (!before.has(name)) server.watcher.emit("add", path.join(videosDir, name));
2070
+ for (const name of before) if (!after.has(name)) server.watcher.emit("unlink", path.join(videosDir, name));
2071
+ });
2072
+ }
2073
+ next();
2074
+ };
2075
+ }
2076
+ /** Loads a module through the dev server's SSR runner, so TypeScript works and an edit is picked up on the next call. */
2077
+ async function loadModule(environment, file) {
2078
+ const runner = environment.runner;
2079
+ if (!runner?.import) throw new Error("The SSR dev environment cannot load a form.");
2080
+ return runner.import(file);
2081
+ }
1872
2082
  async function renderPreview(environment, previewModule, page, motion) {
1873
2083
  const preview = await loadThemePreview(environment, previewModule);
1874
2084
  const sections = typeof page === "object" && page !== null && "sections" in page && Array.isArray(page.sections) ? page.sections : [];
@@ -1885,6 +2095,10 @@ async function renderSitePreview(environment, previewModule, site, pathname) {
1885
2095
  pathname
1886
2096
  });
1887
2097
  }
2098
+ function rootPath(root) {
2099
+ const input = rootInput(root);
2100
+ return input instanceof URL ? fileURLToPath(input) : input;
2101
+ }
1888
2102
  function rootInput(root) {
1889
2103
  if (typeof root === "string" || root instanceof URL) return root;
1890
2104
  return process.cwd();
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {}
package/dist/cli.js ADDED
@@ -0,0 +1,83 @@
1
+ #!/usr/bin/env node
2
+ import { n as staleSectionsMessage, r as syncSections, t as SectionsError } from "./sections-manifest-CU-xBjMi.js";
3
+ import path from "node:path";
4
+ import { parseArgs } from "node:util";
5
+ //#region src/command.ts
6
+ const DEFAULT_SECTIONS_DIR = "src/components/sections";
7
+ const HELP = `The bearminion command line.
8
+
9
+ Usage
10
+ npx bearminion sync [options]
11
+
12
+ Commands
13
+ sync Rewrite sections/definitions.gen.ts and components.gen.ts from the section directories
14
+
15
+ Options
16
+ --check Write nothing; exit 1 when the generated files are stale
17
+ --sections <dir> The sections folder (default: ${DEFAULT_SECTIONS_DIR})
18
+ --cwd <dir> Run as if started in this folder
19
+ -h, --help Show this help
20
+ `;
21
+ /** Runs the command line and returns the exit code. */
22
+ function run(argv, log = console.log) {
23
+ let parsed;
24
+ try {
25
+ parsed = parse(argv);
26
+ } catch (error) {
27
+ log(error instanceof Error ? error.message : String(error));
28
+ log("Run `npx bearminion --help` for the options.");
29
+ return 2;
30
+ }
31
+ const { values, positionals } = parsed;
32
+ const [command, ...rest] = positionals;
33
+ if (values.help || command === void 0) {
34
+ log(HELP);
35
+ return command === void 0 && !values.help ? 2 : 0;
36
+ }
37
+ if (command !== "sync" || rest.length > 0) {
38
+ log(`I do not know "${positionals.join(" ")}". Run \`npx bearminion --help\` for the commands.`);
39
+ return 2;
40
+ }
41
+ const root = path.resolve(values.cwd ?? process.cwd());
42
+ const sectionsDir = path.resolve(root, values.sections ?? DEFAULT_SECTIONS_DIR);
43
+ try {
44
+ const { changed, entries } = syncSections(sectionsDir, { check: values.check === true });
45
+ if (values.check) {
46
+ if (changed.length > 0) {
47
+ log(staleSectionsMessage(changed));
48
+ return 1;
49
+ }
50
+ log(`${entries.length} sections, generated files up to date.`);
51
+ return 0;
52
+ }
53
+ log(changed.length > 0 ? `Wrote ${changed.join(" and ")} (${entries.length} sections).` : `Already in sync (${entries.length} sections).`);
54
+ return 0;
55
+ } catch (error) {
56
+ if (!(error instanceof SectionsError)) throw error;
57
+ log(error.message);
58
+ return 1;
59
+ }
60
+ }
61
+ function parse(argv) {
62
+ return parseArgs({
63
+ args: [...argv],
64
+ allowPositionals: true,
65
+ options: {
66
+ check: {
67
+ type: "boolean",
68
+ default: false
69
+ },
70
+ sections: { type: "string" },
71
+ cwd: { type: "string" },
72
+ help: {
73
+ type: "boolean",
74
+ short: "h",
75
+ default: false
76
+ }
77
+ }
78
+ });
79
+ }
80
+ //#endregion
81
+ //#region src/cli.ts
82
+ process.exitCode = run(process.argv.slice(2));
83
+ //#endregion
package/dist/content.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { k as ContentModel, t as Page, u as SectionOf } from "./page-BFuPEq6Q.js";
1
+ import { k as ContentModel, t as Page, u as SectionOf } from "./page-CA4iyFDS.js";
2
2
  import { z } from "zod";
3
3
  //#region src/content.d.ts
4
4
  export interface ContentCollectionsOptions {
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-D0vwI0OT.js";
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 };
@@ -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 };