bearminion 1.9.3 → 1.10.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,11 @@
1
1
  # bearminion
2
2
 
3
+ ## 1.10.0
4
+
5
+ ### Minor Changes
6
+
7
+ - a10e4a7: New command `npx bearminion check form`. It reads the site's files and environment and names what keeps the Contact form from working: a missing handler or glue file, an import without `.js`, a Netlify function in the wrong folder or without a path, a Wrangler config without `main`, with the placeholder name or without `CONTACT_FROM` and `CONTACT_TO` under `vars`. Each problem comes with its fix. It writes nothing and cannot see the host's own settings. `--host` and `--json` work as for `add form`.
8
+
3
9
  ## 1.9.3
4
10
 
5
11
  ### Patch Changes
package/dist/astro.js CHANGED
@@ -2,14 +2,16 @@ import { a as imageFields, c as ContentReadError, l as ContentValidationError, r
2
2
  import { t as defaultTheme } from "./theme-Dv7_7B56.js";
3
3
  import { i as isSystemPage, n as createPageSchema$1, r as createTolerantPageSchema, s as withoutOrphanSections, u as isOrphanSection } from "./page-X-WnOu7-.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-Dkp3xC0l.js";
5
+ import { a as isInside, c as resolveDir, i as asDirectory, l as resolveInside, n as JSON_BODY_LIMIT, o as isLocalRequest, r as MULTIPART_BODY_LIMIT, s as readSlug, t as IMAGE_BYTE_LIMIT } from "./security-DOvoYZuQ.js";
6
+ import { a as resolveFormsConfig, n as formFile, r as formsAreLive, t as createFormsMiddleware } from "./forms-dev-CaxRmLhl.js";
6
7
  import { S as isAssetPath, b as describeSiteRef, c as projectId, v as assetRefs, y as describePageRef } from "./draft-store-1Y4-sn45.js";
8
+ import { n as contentReloadPlugin, r as dropEarlyReloadAfterSave } from "./reload-DA07O8cA.js";
7
9
  import { i as syncSections, r as staleSectionsMessage } from "./sections-manifest-CO9QfJPG.js";
8
10
  import { z } from "zod";
9
11
  import fs from "node:fs";
10
12
  import path from "node:path";
11
13
  import { fileURLToPath } from "node:url";
12
- import { parseEnv, promisify } from "node:util";
14
+ import { promisify } from "node:util";
13
15
  import { randomBytes } from "node:crypto";
14
16
  import { access, mkdir, readFile, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
15
17
  import { execFile } from "node:child_process";
@@ -36,134 +38,6 @@ function editorClientPlugin() {
36
38
  };
37
39
  }
38
40
  //#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
167
41
  //#region src/videos.ts
168
42
  const EXTENSION$1 = {
169
43
  mp4: ".mp4",
package/dist/cli.js CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { i as readDotEnv } from "./forms-dev-CaxRmLhl.js";
2
3
  import { i as syncSections, r as staleSectionsMessage, t as SectionsError } from "./sections-manifest-CO9QfJPG.js";
3
4
  import { i as writeLock, n as readLock, r as recordFiles, t as hashContent } from "./hash-BeBymBO1.js";
4
5
  import fs from "node:fs";
@@ -317,6 +318,245 @@ function applyForm(root, plan, version, lock) {
317
318
  };
318
319
  }
319
320
  //#endregion
321
+ //#region src/add/check-form.ts
322
+ const SECRET_NAME = /KEY|SECRET|TOKEN|PASSWORD/;
323
+ const HOSTS_TEXT = GLUE.map((glue) => glue.name).join(", ");
324
+ function read(root, file) {
325
+ try {
326
+ return fs.readFileSync(path.join(root, file), "utf8");
327
+ } catch {
328
+ return;
329
+ }
330
+ }
331
+ /** The first of `candidates` that exists in `dir` (relative to `root`), as a path relative to `root`. */
332
+ function firstExisting(root, dir, base, extensions) {
333
+ return extensions.map((extension) => path.posix.join(dir, `${base}${extension}`)).find((file) => fs.existsSync(path.join(root, file)));
334
+ }
335
+ /** JSON with comments and trailing commas, the way Wrangler reads `wrangler.jsonc`. Undefined when it does not parse. */
336
+ function parseJsonc(text) {
337
+ const clean = scan(scan(text, (source, i) => {
338
+ if (source[i] === "/" && source[i + 1] === "/") {
339
+ const end = source.indexOf("\n", i);
340
+ return {
341
+ text: "",
342
+ resume: end === -1 ? source.length : end
343
+ };
344
+ }
345
+ if (source[i] === "/" && source[i + 1] === "*") {
346
+ const end = source.indexOf("*/", i + 2);
347
+ return {
348
+ text: "",
349
+ resume: end === -1 ? source.length : end + 2
350
+ };
351
+ }
352
+ }), (source, i) => {
353
+ if (source[i] !== ",") return void 0;
354
+ const next = /\S/.exec(source.slice(i + 1));
355
+ const following = next === null ? void 0 : source[i + 1 + next.index];
356
+ return following === "}" || following === "]" ? {
357
+ text: "",
358
+ resume: i + 1
359
+ } : void 0;
360
+ });
361
+ try {
362
+ const value = JSON.parse(clean);
363
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
364
+ } catch {
365
+ return;
366
+ }
367
+ }
368
+ /**
369
+ * Walks `text` outside of string literals. `replace` may answer a replacement and the index to carry on from; strings
370
+ * and everything it leaves alone are copied as they are.
371
+ */
372
+ function scan(text, replace) {
373
+ let out = "";
374
+ let inString = false;
375
+ let i = 0;
376
+ while (i < text.length) {
377
+ const c = text[i];
378
+ if (inString) {
379
+ out += c;
380
+ if (c === "\\") out += text[i + 1] ?? "";
381
+ else if (c === "\"") inString = false;
382
+ i += c === "\\" ? 2 : 1;
383
+ continue;
384
+ }
385
+ if (c === "\"") inString = true;
386
+ const replacement = c === "\"" ? void 0 : replace(text, i);
387
+ out += replacement?.text ?? c;
388
+ i = replacement?.resume ?? i + 1;
389
+ }
390
+ return out;
391
+ }
392
+ /** The environment names a handler reads from `env`. */
393
+ function envNamesOf(source) {
394
+ const names = /* @__PURE__ */ new Set();
395
+ for (const match of source.matchAll(/\benv\.([A-Z][A-Z0-9_]*)/g)) names.add(match[1]);
396
+ for (const match of source.matchAll(/\benv\[\s*['"]([A-Z][A-Z0-9_]*)['"]\s*\]/g)) names.add(match[1]);
397
+ return [...names];
398
+ }
399
+ /** What a glue file imports from `src/forms/contact`, and whether the specifier will resolve as an ES module. */
400
+ function checkImport(add, file, source) {
401
+ const specifier = /from\s+['"]([^'"]*forms\/contact[^'"]*)['"]/.exec(source)?.[1];
402
+ if (specifier === void 0) add("problem", `${file} does not import ${HANDLER_PATH}, so the request never reaches your handler.`, "Run `npx bearminion add form <service> --overwrite` (git keeps your version).");
403
+ else if (specifier.endsWith(".js")) add("ok", `${file} imports the handler with the ".js" an ES module needs.`);
404
+ else if (/\.[cm]?ts$/.test(specifier)) add("note", `${file} imports "${specifier}". The recipe uses ".js" (the file is contact.ts), which every host here ran; this has not been tried.`);
405
+ else add("problem", `${file} imports "${specifier}" without an extension. The host runs it as an ES module, which does not guess extensions (ERR_MODULE_NOT_FOUND).`, `Write "${specifier}.js". The file is contact.ts; the ".js" is what the module resolver needs.`);
406
+ }
407
+ function checkVercel(root, add) {
408
+ const file = firstExisting(root, "api", "contact", [
409
+ ".ts",
410
+ ".mts",
411
+ ".js",
412
+ ".mjs"
413
+ ]);
414
+ if (file === void 0) {
415
+ add("problem", "api/contact.ts is missing, so /api/contact has no function on Vercel.", "npx bearminion add form <service> --host vercel");
416
+ return;
417
+ }
418
+ const source = read(root, file) ?? "";
419
+ add("ok", `${file} exists.`);
420
+ checkImport(add, file, source);
421
+ if (/export\s+(const|function|async function)\s+POST\b|export\s+default\b/.test(source)) add("ok", `${file} exports the function Vercel calls.`);
422
+ else add("problem", `${file} exports neither POST nor a default function, so Vercel has nothing to call.`, "export const POST = (request: Request) => form.fetch(request, process.env)");
423
+ }
424
+ function checkNetlify(root, add) {
425
+ const toml = read(root, "netlify.toml");
426
+ const dir = ((toml === void 0 ? void 0 : /\[functions\][^[]*?\bdirectory\s*=\s*"([^"]+)"/.exec(toml)?.[1]) ?? "netlify/functions").replace(/^\.?\//, "").replace(/\/$/, "");
427
+ const file = firstExisting(root, dir, "contact", [
428
+ ".mts",
429
+ ".ts",
430
+ ".mjs",
431
+ ".js"
432
+ ]);
433
+ if (file === void 0) {
434
+ const elsewhere = readDirs(root, "netlify").filter((other) => other !== dir).map((other) => firstExisting(root, other, "contact", [
435
+ ".mts",
436
+ ".ts",
437
+ ".mjs",
438
+ ".js"
439
+ ])).find((found) => found !== void 0);
440
+ if (elsewhere !== void 0) add("problem", `The function is at ${elsewhere}, but Netlify reads ${dir}/. It is not deployed (the deploy log says "0 new function(s) to upload").`, `Move it to ${dir}/contact${path.extname(elsewhere)}.`);
441
+ else add("problem", `${dir}/contact.mts is missing, so /api/contact has no function on Netlify.`, "npx bearminion add form <service> --host netlify");
442
+ return;
443
+ }
444
+ const source = read(root, file) ?? "";
445
+ add("ok", `${file} exists in the folder Netlify reads.`);
446
+ checkImport(add, file, source);
447
+ if (/export\s+default\b/.test(source)) add("ok", `${file} has the default export Netlify calls.`);
448
+ else add("problem", `${file} has no default export, so Netlify has nothing to call.`, "export default (request: Request) => form.fetch(request, process.env)");
449
+ if (/\bpath\s*:\s*['"]\/api\/contact['"]/.test(source)) add("ok", `${file} answers at /api/contact.`);
450
+ else add("problem", `${file} does not set path "/api/contact". Netlify then serves it at /.netlify/functions/contact, and the form posts to /api/contact (404).`, "export const config = { path: '/api/contact' }");
451
+ }
452
+ function readDirs(root, dir) {
453
+ try {
454
+ return fs.readdirSync(path.join(root, dir), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => path.posix.join(dir, entry.name));
455
+ } catch {
456
+ return [];
457
+ }
458
+ }
459
+ function checkCloudflare(root, add, plainNames, secretNames) {
460
+ const configFile = [
461
+ "wrangler.jsonc",
462
+ "wrangler.json",
463
+ "wrangler.toml"
464
+ ].find((name) => fs.existsSync(path.join(root, name)));
465
+ if (configFile === void 0) {
466
+ add("problem", "There is no wrangler.jsonc, so there is nothing to deploy as a Worker.", "npx bearminion add form <service> --host cloudflare");
467
+ return;
468
+ }
469
+ const text = read(root, configFile) ?? "";
470
+ let main;
471
+ let name;
472
+ let binding;
473
+ let vars = {};
474
+ let logs;
475
+ if (configFile.endsWith(".toml")) {
476
+ main = /^\s*main\s*=\s*"([^"]+)"/m.exec(text)?.[1];
477
+ name = /^\s*name\s*=\s*"([^"]+)"/m.exec(text)?.[1];
478
+ binding = /^\s*binding\s*=\s*"([^"]+)"/m.exec(text)?.[1];
479
+ vars = Object.fromEntries(plainNames.map((variable) => [variable, new RegExp(`^\\s*${variable}\\s*=\\s*"([^"]*)"`, "m").exec(text)?.[1]]).filter(([, value]) => value !== void 0));
480
+ logs = /^\s*\[observability\]/m.test(text) ? /^\s*enabled\s*=\s*true/m.test(text) : void 0;
481
+ } else {
482
+ const config = parseJsonc(text);
483
+ if (config === void 0) {
484
+ add("problem", `${configFile} does not parse as JSON with comments, so I cannot read it.`);
485
+ return;
486
+ }
487
+ main = typeof config.main === "string" ? config.main : void 0;
488
+ name = typeof config.name === "string" ? config.name : void 0;
489
+ const assets = config.assets;
490
+ binding = typeof assets?.binding === "string" ? assets.binding : void 0;
491
+ vars = config.vars ?? {};
492
+ const observability = config.observability;
493
+ logs = observability === void 0 ? void 0 : observability.enabled === true || observability.logs?.enabled === true;
494
+ }
495
+ add("ok", `${configFile} exists.`);
496
+ if (name === "my-site") add("problem", `${configFile} still has the placeholder name "my-site". The deploy would create a Worker with that name.`, "Set \"name\" to the name of your Worker in Cloudflare.");
497
+ if (main === void 0) add("problem", `${configFile} has no "main", so no Worker runs and /api/contact is a 404.`, "Set \"main\": \"./worker.ts\".");
498
+ else if (!fs.existsSync(path.join(root, main))) add("problem", `"main" is ${main}, which does not exist.`, "Point \"main\" at your Worker file, or run `npx bearminion add form <service> --host cloudflare`.");
499
+ else {
500
+ const source = read(root, main) ?? "";
501
+ add("ok", `${main} is the Worker.`);
502
+ checkImport(add, main, source);
503
+ if (source.includes("/api/contact")) add("ok", `${main} routes /api/contact.`);
504
+ else add("problem", `${main} does not mention /api/contact, so the form's request goes to the static files.`);
505
+ if (/\benv\.ASSETS\b/.test(source) && binding !== "ASSETS") add("problem", `${main} serves the site through env.ASSETS, but ${configFile} has no assets binding named "ASSETS".`, "Add \"binding\": \"ASSETS\" to \"assets\".");
506
+ }
507
+ for (const variable of plainNames) {
508
+ const value = vars[variable];
509
+ if (typeof value === "string" && value.trim() !== "") add("ok", `${variable} is set under "vars".`);
510
+ else add("problem", `${variable} is not set under "vars" in ${configFile}. A variable that exists only in the dashboard is replaced on the next deploy.`, `Put ${variable} under "vars" (plain values, so keep the repository private if they should not be public).`);
511
+ }
512
+ if (secretNames.length > 0) add("note", `Set ${secretNames.join(", ")} as Secrets in the Worker's Settings. I cannot read them from here.`);
513
+ if (logs !== true) add("note", "Logs are not turned on in the Wrangler config (\"observability\"), so a failing handler leaves no trace in the dashboard.");
514
+ }
515
+ /**
516
+ * Looks at the files and environment that make the Contact form work and says what is missing. It reads the project and
517
+ * writes nothing; the host's own settings (Vercel and Netlify environment variables, Cloudflare secrets) are out of
518
+ * reach, and the result says so.
519
+ */
520
+ function checkForm(root, requestedHost) {
521
+ const findings = [];
522
+ const add = (level, message, fix) => findings.push({
523
+ level,
524
+ message,
525
+ ...fix === void 0 ? {} : { fix }
526
+ });
527
+ const host = requestedHost ?? detectHost(root);
528
+ const known = GLUE.some((glue) => glue.name === host);
529
+ const handler = read(root, HANDLER_PATH);
530
+ let names = [];
531
+ if (handler === void 0) add("problem", `${HANDLER_PATH} is missing. The Contact form posts to /api/contact and nothing answers.`, "npx bearminion add form resend --host <host>");
532
+ else if (/\bdefineForm\b/.test(handler) && /export\s+default\b/.test(handler)) {
533
+ add("ok", `${HANDLER_PATH} exports a defineForm handler.`);
534
+ names = envNamesOf(handler);
535
+ } else {
536
+ add("problem", `${HANDLER_PATH} must \`export default defineForm(...)\` from 'bearminion/forms'.`);
537
+ names = envNamesOf(handler);
538
+ }
539
+ const plainNames = names.filter((variable) => !SECRET_NAME.test(variable));
540
+ const secretNames = names.filter((variable) => SECRET_NAME.test(variable));
541
+ if (host === void 0) add("note", `I cannot tell where this site runs. Name the host to check its glue: --host ${GLUE.map((glue) => glue.name).join(" | ")}.`);
542
+ else if (host === "astro") add("note", "This site has an Astro adapter, so the endpoint is an Astro route. I only check the glue for the hosts the command writes.");
543
+ else if (!known) add("problem", `There is no host called "${host}". The hosts are: ${HOSTS_TEXT}.`);
544
+ else if (host === "vercel") checkVercel(root, add);
545
+ else if (host === "netlify") checkNetlify(root, add);
546
+ else if (host === "cloudflare") checkCloudflare(root, add, plainNames, secretNames);
547
+ if (host === "vercel" || host === "netlify") {
548
+ if (names.length > 0) add("note", `Set ${names.join(", ")} in ${host === "vercel" ? "the project's Environment Variables" : "the site's Environment variables"} (Production and Preview). I cannot read them from here.`);
549
+ }
550
+ const dotEnv = { ...readDotEnv(root) };
551
+ const missingLocally = names.filter((variable) => dotEnv[variable] === void 0 && process.env[variable] === void 0);
552
+ if (missingLocally.length > 0) add("note", `Not in .env: ${missingLocally.join(", ")}. \`astro dev\` with BEARMINION_FORMS_LIVE=on needs them; without it the form is a dry run.`);
553
+ if ((dotEnv.PUBLIC_TURNSTILE_SITE_KEY ?? process.env.PUBLIC_TURNSTILE_SITE_KEY) !== void 0 && dotEnv.TURNSTILE_SECRET_KEY === void 0 && process.env.TURNSTILE_SECRET_KEY === void 0) add("note", "PUBLIC_TURNSTILE_SITE_KEY shows the widget. The server checks the token only where TURNSTILE_SECRET_KEY is set, so set it on the host too.");
554
+ return {
555
+ host,
556
+ findings
557
+ };
558
+ }
559
+ //#endregion
320
560
  //#region src/add/status.ts
321
561
  /** Decides the state of one file from its hash in the site, in the release, and in the lock. */
322
562
  function classify(siteHash, release, lockHash) {
@@ -381,11 +621,13 @@ Usage
381
621
  npx bearminion add --list
382
622
  npx bearminion add form [<service>] [--host <host>]
383
623
  npx bearminion status [--json]
624
+ npx bearminion check form [--host <host>] [--json]
384
625
  npx bearminion sync [options]
385
626
 
386
627
  Commands
387
628
  add Copy sections into this site, with the files they need
388
629
  status Show which sections are in this site and whether their files match this release
630
+ check form Look for what keeps the Contact form from working: missing files, wrong names, unset variables
389
631
  sync Rewrite sections/definitions.gen.ts and components.gen.ts from the section directories
390
632
 
391
633
  Options for add
@@ -401,6 +643,10 @@ Options for add form
401
643
  --host <host> Where the site runs (found from the project when omitted). See --list
402
644
  --list List the services and hosts
403
645
 
646
+ Options for check form
647
+ --host <host> Where the site runs (found from the project when omitted)
648
+ --json Print one JSON document instead of text
649
+
404
650
  Options for sync
405
651
  --check Write nothing; exit 1 when the generated files are stale
406
652
  --sections <dir> The sections folder (default: ${DEFAULT_SECTIONS_DIR})
@@ -434,6 +680,7 @@ async function run(argv, io = {}) {
434
680
  const root = path.resolve(values.cwd ?? process.cwd());
435
681
  if (command === "sync" && rest.length === 0) return runSync(root, values, log);
436
682
  if (command === "add") return runAdd(root, rest, values, surroundings);
683
+ if (command === "check" && rest[0] === "form" && rest.length === 1) return runCheckForm(root, values, surroundings);
437
684
  if (command === "status" && rest.length === 0) return runStatus(root, values, surroundings);
438
685
  log(`I do not know "${positionals.join(" ")}". Run \`npx bearminion --help\` for the commands.`);
439
686
  return 2;
@@ -684,6 +931,32 @@ async function runAdd(root, names, values, io) {
684
931
  }
685
932
  return installed === "failed" ? 1 : 0;
686
933
  }
934
+ const LEVEL_TEXT = {
935
+ ok: "ok",
936
+ problem: "problem",
937
+ note: "note"
938
+ };
939
+ function runCheckForm(root, values, io) {
940
+ const { host, findings } = checkForm(root, values.host);
941
+ const problems = findings.filter((finding) => finding.level === "problem").length;
942
+ if (values.json) {
943
+ io.log(JSON.stringify({
944
+ ok: problems === 0,
945
+ host: host ?? null,
946
+ findings
947
+ }, null, 2));
948
+ return problems === 0 ? 0 : 1;
949
+ }
950
+ io.log(`Checking the Contact form${host === void 0 ? "" : ` (host: ${host})`}`);
951
+ io.log("");
952
+ for (const finding of findings) {
953
+ io.log(` ${LEVEL_TEXT[finding.level].padEnd(8)} ${finding.message}`);
954
+ if (finding.fix !== void 0) io.log(` ${"".padEnd(8)} fix: ${finding.fix}`);
955
+ }
956
+ io.log("");
957
+ io.log(problems === 0 ? "No problems found in the files. The host's own settings and a real message are still yours to check." : `${problems} problem${problems === 1 ? "" : "s"} found.`);
958
+ return problems === 0 ? 0 : 1;
959
+ }
687
960
  const STATE_TEXT = {
688
961
  current: "current",
689
962
  outdated: "outdated (you did not change it; `add` replaces it)",
package/dist/content.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { n as createPageSchema, r as createTolerantPageSchema } from "./page-X-WnOu7-.js";
2
2
  import { n as createMigrator } from "./migrate-b408EaLp.js";
3
- import { t as CONTENT_COLLECTIONS_MARKER } from "./reload-Dkp3xC0l.js";
3
+ import { t as CONTENT_COLLECTIONS_MARKER } from "./reload-DA07O8cA.js";
4
4
  import { z } from "zod";
5
5
  import path from "node:path";
6
6
  import { pathToFileURL } from "node:url";
@@ -0,0 +1,133 @@
1
+ import { c as resolveDir } from "./security-DOvoYZuQ.js";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { parseEnv } from "node:util";
5
+ //#region src/forms-dev.ts
6
+ /** Where the forms are and under which path, or `null` when the option turns them off. */
7
+ function resolveFormsConfig(option, root) {
8
+ if (option === false) return null;
9
+ const prefix = (option?.prefix ?? "/api").replace(/\/+$/, "");
10
+ return {
11
+ dir: resolveDir(root, option?.dir, "src/forms"),
12
+ prefix: prefix.startsWith("/") ? prefix : `/${prefix}`
13
+ };
14
+ }
15
+ const FORM_FILE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
16
+ const EXTENSIONS = [
17
+ ".ts",
18
+ ".mts",
19
+ ".js",
20
+ ".mjs"
21
+ ];
22
+ const BODY_LIMIT = 1048576;
23
+ /** The file behind `name`, or `null` when there is none. `name` is checked, so it cannot leave the folder. */
24
+ function formFile(dir, name) {
25
+ if (!FORM_FILE.test(name)) return null;
26
+ for (const extension of EXTENSIONS) {
27
+ const file = path.join(dir, `${name}${extension}`);
28
+ if (fs.existsSync(file)) return file;
29
+ }
30
+ return null;
31
+ }
32
+ /** `.env`, `.env.local`, `.env.development` and `.env.development.local` of the project, later ones winning. */
33
+ function readDotEnv(root) {
34
+ const merged = {};
35
+ for (const name of [
36
+ ".env",
37
+ ".env.local",
38
+ ".env.development",
39
+ ".env.development.local"
40
+ ]) try {
41
+ Object.assign(merged, parseEnv(fs.readFileSync(path.join(root, name), "utf8")));
42
+ } catch {}
43
+ return merged;
44
+ }
45
+ /** True when `BEARMINION_FORMS_LIVE=on` is in the environment or in the project's `.env` files. */
46
+ function formsAreLive(root) {
47
+ return (process.env.BEARMINION_FORMS_LIVE ?? readDotEnv(root).BEARMINION_FORMS_LIVE) === "on";
48
+ }
49
+ function isForm(value) {
50
+ return typeof value === "object" && value !== null && typeof value.fetch === "function";
51
+ }
52
+ function createFormsMiddleware(options) {
53
+ return (req, res, next) => {
54
+ const pathname = (req.url ?? "/").split("?")[0]?.replace(/\/+$/, "") ?? "";
55
+ if (!pathname.startsWith(`${options.prefix}/`)) {
56
+ next();
57
+ return;
58
+ }
59
+ const name = pathname.slice(options.prefix.length + 1);
60
+ const file = formFile(options.dir, name);
61
+ if (!file) {
62
+ next();
63
+ return;
64
+ }
65
+ answer(req, res, options, name, file).catch((error) => {
66
+ options.log.error(`/${name}: ${error instanceof Error ? error.stack ?? error.message : String(error)}`);
67
+ if (!res.headersSent) fail(res, 500, error instanceof Error ? error.message : "The form failed.");
68
+ });
69
+ };
70
+ }
71
+ function fail(res, status, error) {
72
+ res.statusCode = status;
73
+ res.setHeader("content-type", "application/json; charset=utf-8");
74
+ res.end(JSON.stringify({
75
+ ok: false,
76
+ error
77
+ }));
78
+ }
79
+ async function answer(req, res, options, name, file) {
80
+ const form = (await options.load(file))?.default;
81
+ if (!isForm(form)) {
82
+ const relative = path.relative(options.root, file).split(path.sep).join("/");
83
+ options.log.error(`${relative} must \`export default defineForm(...)\` from 'bearminion/forms'.`);
84
+ return fail(res, 500, `${relative} must export default defineForm(...).`);
85
+ }
86
+ const headers = new Headers();
87
+ for (const [key, value] of Object.entries(req.headers)) {
88
+ if (value === void 0) continue;
89
+ for (const item of Array.isArray(value) ? value : [value]) headers.append(key, item);
90
+ }
91
+ const method = (req.method ?? "GET").toUpperCase();
92
+ const body = method === "GET" || method === "HEAD" ? void 0 : await readLimited(req, BODY_LIMIT);
93
+ if (body === null) return fail(res, 413, "The message is too large.");
94
+ const request = new Request(`http://${req.headers.host ?? "localhost"}${req.url ?? "/"}`, {
95
+ method,
96
+ headers,
97
+ ...body ? { body } : {}
98
+ });
99
+ const env = {
100
+ ...readDotEnv(options.root),
101
+ ...process.env
102
+ };
103
+ const response = await form.fetch(request, env, {
104
+ dev: true,
105
+ ...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)}`) }
106
+ });
107
+ res.statusCode = response.status;
108
+ response.headers.forEach((value, key) => {
109
+ res.setHeader(key, value);
110
+ });
111
+ res.end(Buffer.from(await response.arrayBuffer()));
112
+ }
113
+ /** The body of the request, or `null` once it is over `limit` bytes. */
114
+ function readLimited(req, limit) {
115
+ return new Promise((resolve, reject) => {
116
+ const chunks = [];
117
+ let size = 0;
118
+ req.on("data", (chunk) => {
119
+ const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
120
+ size += buffer.length;
121
+ if (size > limit) {
122
+ resolve(null);
123
+ req.resume();
124
+ return;
125
+ }
126
+ chunks.push(buffer);
127
+ });
128
+ req.on("end", () => resolve(new Uint8Array(Buffer.concat(chunks))));
129
+ req.on("error", reject);
130
+ });
131
+ }
132
+ //#endregion
133
+ export { resolveFormsConfig as a, readDotEnv as i, formFile as n, formsAreLive as r, createFormsMiddleware as t };
@@ -1,95 +1,5 @@
1
- import { o as slugSchema } from "./page-X-WnOu7-.js";
1
+ import { a as isInside } from "./security-DOvoYZuQ.js";
2
2
  import path from "node:path";
3
- import { fileURLToPath } from "node:url";
4
- //#region src/security.ts
5
- const JSON_BODY_LIMIT = 1048576;
6
- const IMAGE_BYTE_LIMIT = 5242880;
7
- /** Room for multipart boundaries around a max-size image. */
8
- const MULTIPART_BODY_LIMIT = 5505024;
9
- const LOCAL_HOSTS = /* @__PURE__ */ new Set([
10
- "localhost",
11
- "127.0.0.1",
12
- "::1"
13
- ]);
14
- function asDirectory(root) {
15
- if (root instanceof URL) return fileURLToPath(root);
16
- if (root.startsWith("file:")) return fileURLToPath(root);
17
- return path.resolve(root);
18
- }
19
- function resolveDir(root, value, fallback) {
20
- const chosen = value ?? fallback;
21
- return path.isAbsolute(chosen) ? path.resolve(chosen) : path.resolve(root, chosen);
22
- }
23
- /** True when `candidate` is `root` or a path inside it. */
24
- function isInside(root, candidate) {
25
- const relative = path.relative(path.resolve(root), path.resolve(candidate));
26
- return relative === "" || !relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative);
27
- }
28
- /** Resolve `parts` under `root`, or return null when the result escapes `root`. */
29
- function resolveInside(root, ...parts) {
30
- const target = path.resolve(root, ...parts);
31
- return isInside(root, target) ? target : null;
32
- }
33
- function hostnameFromHostHeader(host) {
34
- if (host === null) return null;
35
- const trimmed = host.trim().toLowerCase();
36
- if (trimmed === "") return null;
37
- if (trimmed.startsWith("[")) {
38
- const end = trimmed.indexOf("]");
39
- if (end <= 1) return null;
40
- return trimmed.slice(1, end);
41
- }
42
- const colon = trimmed.lastIndexOf(":");
43
- if (colon === -1) return trimmed;
44
- const maybePort = trimmed.slice(colon + 1);
45
- if (/^\d+$/.test(maybePort)) return trimmed.slice(0, colon);
46
- return trimmed;
47
- }
48
- function isLocalHostname(hostname) {
49
- return hostname !== null && LOCAL_HOSTS.has(hostname);
50
- }
51
- function isLocalAddress(address) {
52
- if (!address) return false;
53
- const normalized = address.toLowerCase().replace(/^::ffff:/, "");
54
- return normalized === "127.0.0.1" || normalized === "::1";
55
- }
56
- /**
57
- * Allow the request when Host is local and, if Origin is present, its host is local. When the browser sends
58
- * `Sec-Fetch-Site`, it must be `same-origin` or `none` (typed in, or a tool such as curl), so a page on another
59
- * site cannot even read-probe the API with a no-cors GET, which carries no Origin.
60
- * When `remoteAddress` is provided it must be a loopback address. Omit it only in tests
61
- * that do not model a socket; the dev middleware always passes it.
62
- */
63
- function isLocalRequest(headers, remoteAddress) {
64
- if (!isLocalHostname(hostnameFromHostHeader(headers.get("host")))) return false;
65
- const site = headers.get("sec-fetch-site");
66
- if (site !== null && site !== "same-origin" && site !== "none") return false;
67
- const origin = headers.get("origin");
68
- if (origin !== null) {
69
- let hostname;
70
- try {
71
- hostname = new URL(origin).hostname.toLowerCase();
72
- } catch {
73
- return false;
74
- }
75
- if (!isLocalHostname(hostname)) return false;
76
- }
77
- if (remoteAddress !== void 0 && !isLocalAddress(remoteAddress)) return false;
78
- return true;
79
- }
80
- /** Decode one URL segment and accept it only when it is a content slug. */
81
- function readSlug(segment) {
82
- let decoded;
83
- try {
84
- decoded = decodeURIComponent(segment);
85
- } catch {
86
- return null;
87
- }
88
- if (decoded.includes("\0") || decoded.includes("/") || decoded.includes("\\") || decoded.includes("..")) return null;
89
- const parsed = slugSchema.safeParse(decoded);
90
- return parsed.success ? parsed.data : null;
91
- }
92
- //#endregion
93
3
  //#region src/reload.ts
94
4
  const RELOAD_DELAY_MS = 50;
95
5
  /** Ignore the watcher's initial scan so opening `astro dev` does not reload immediately. */
@@ -198,4 +108,4 @@ function evaluatedModules(environment) {
198
108
  return modules;
199
109
  }
200
110
  //#endregion
201
- export { JSON_BODY_LIMIT as a, isInside as c, resolveDir as d, resolveInside as f, IMAGE_BYTE_LIMIT as i, isLocalRequest as l, contentReloadPlugin as n, MULTIPART_BODY_LIMIT as o, dropEarlyReloadAfterSave as r, asDirectory as s, CONTENT_COLLECTIONS_MARKER as t, readSlug as u };
111
+ export { contentReloadPlugin as n, dropEarlyReloadAfterSave as r, CONTENT_COLLECTIONS_MARKER as t };
@@ -0,0 +1,93 @@
1
+ import { o as slugSchema } from "./page-X-WnOu7-.js";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ //#region src/security.ts
5
+ const JSON_BODY_LIMIT = 1048576;
6
+ const IMAGE_BYTE_LIMIT = 5242880;
7
+ /** Room for multipart boundaries around a max-size image. */
8
+ const MULTIPART_BODY_LIMIT = 5505024;
9
+ const LOCAL_HOSTS = /* @__PURE__ */ new Set([
10
+ "localhost",
11
+ "127.0.0.1",
12
+ "::1"
13
+ ]);
14
+ function asDirectory(root) {
15
+ if (root instanceof URL) return fileURLToPath(root);
16
+ if (root.startsWith("file:")) return fileURLToPath(root);
17
+ return path.resolve(root);
18
+ }
19
+ function resolveDir(root, value, fallback) {
20
+ const chosen = value ?? fallback;
21
+ return path.isAbsolute(chosen) ? path.resolve(chosen) : path.resolve(root, chosen);
22
+ }
23
+ /** True when `candidate` is `root` or a path inside it. */
24
+ function isInside(root, candidate) {
25
+ const relative = path.relative(path.resolve(root), path.resolve(candidate));
26
+ return relative === "" || !relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative);
27
+ }
28
+ /** Resolve `parts` under `root`, or return null when the result escapes `root`. */
29
+ function resolveInside(root, ...parts) {
30
+ const target = path.resolve(root, ...parts);
31
+ return isInside(root, target) ? target : null;
32
+ }
33
+ function hostnameFromHostHeader(host) {
34
+ if (host === null) return null;
35
+ const trimmed = host.trim().toLowerCase();
36
+ if (trimmed === "") return null;
37
+ if (trimmed.startsWith("[")) {
38
+ const end = trimmed.indexOf("]");
39
+ if (end <= 1) return null;
40
+ return trimmed.slice(1, end);
41
+ }
42
+ const colon = trimmed.lastIndexOf(":");
43
+ if (colon === -1) return trimmed;
44
+ const maybePort = trimmed.slice(colon + 1);
45
+ if (/^\d+$/.test(maybePort)) return trimmed.slice(0, colon);
46
+ return trimmed;
47
+ }
48
+ function isLocalHostname(hostname) {
49
+ return hostname !== null && LOCAL_HOSTS.has(hostname);
50
+ }
51
+ function isLocalAddress(address) {
52
+ if (!address) return false;
53
+ const normalized = address.toLowerCase().replace(/^::ffff:/, "");
54
+ return normalized === "127.0.0.1" || normalized === "::1";
55
+ }
56
+ /**
57
+ * Allow the request when Host is local and, if Origin is present, its host is local. When the browser sends
58
+ * `Sec-Fetch-Site`, it must be `same-origin` or `none` (typed in, or a tool such as curl), so a page on another
59
+ * site cannot even read-probe the API with a no-cors GET, which carries no Origin.
60
+ * When `remoteAddress` is provided it must be a loopback address. Omit it only in tests
61
+ * that do not model a socket; the dev middleware always passes it.
62
+ */
63
+ function isLocalRequest(headers, remoteAddress) {
64
+ if (!isLocalHostname(hostnameFromHostHeader(headers.get("host")))) return false;
65
+ const site = headers.get("sec-fetch-site");
66
+ if (site !== null && site !== "same-origin" && site !== "none") return false;
67
+ const origin = headers.get("origin");
68
+ if (origin !== null) {
69
+ let hostname;
70
+ try {
71
+ hostname = new URL(origin).hostname.toLowerCase();
72
+ } catch {
73
+ return false;
74
+ }
75
+ if (!isLocalHostname(hostname)) return false;
76
+ }
77
+ if (remoteAddress !== void 0 && !isLocalAddress(remoteAddress)) return false;
78
+ return true;
79
+ }
80
+ /** Decode one URL segment and accept it only when it is a content slug. */
81
+ function readSlug(segment) {
82
+ let decoded;
83
+ try {
84
+ decoded = decodeURIComponent(segment);
85
+ } catch {
86
+ return null;
87
+ }
88
+ if (decoded.includes("\0") || decoded.includes("/") || decoded.includes("\\") || decoded.includes("..")) return null;
89
+ const parsed = slugSchema.safeParse(decoded);
90
+ return parsed.success ? parsed.data : null;
91
+ }
92
+ //#endregion
93
+ export { isInside as a, resolveDir as c, asDirectory as i, resolveInside as l, JSON_BODY_LIMIT as n, isLocalRequest as o, MULTIPART_BODY_LIMIT as r, readSlug as s, IMAGE_BYTE_LIMIT as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bearminion",
3
- "version": "1.9.3",
3
+ "version": "1.10.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",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "template": "default",
4
- "version": "1.9.3",
4
+ "version": "1.10.0",
5
5
  "files": {
6
6
  "src/components/atoms/Button.astro": {
7
7
  "hash": "7be42b3dc3a3b59bec169de32a9d801904689e2705473d1945724658dc799043",