bearminion 1.10.0 → 1.11.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,20 @@
1
1
  # bearminion
2
2
 
3
+ ## 1.11.0
4
+
5
+ ### Minor Changes
6
+
7
+ - a5d09d9: Upload rules for images. `maxImageBytes` sets the largest image the editor accepts (default 5 MB, as before); the editor now checks it in the browser and names the file size and the limit before anything is uploaded. `imageConvert: { to: 'webp', maxWidth, quality }` makes the editor scale and re-encode images as WebP in the browser before they are uploaded, which keeps large phone photos out of the repository and drops their metadata. It is off by default, an image that would come out larger is kept as it is, and GIFs are never converted. `GET /images` also returns the rules as `limits`.
8
+
9
+ ## 1.10.1
10
+
11
+ ### Patch Changes
12
+
13
+ - 23f9084: New sites include an `AGENTS.md` (and a `CLAUDE.md` pointing to it) for AI assistants. It leads with the rules that keep secrets out of the chat and out of git, then walks through the Contact form: write the files with `add form`, run `check form`, and ask the person to confirm each step the assistant cannot see (the variables on the host, a verified domain, a redeploy, a real message).
14
+ - 88fae9e: `check form` now says when a `PUBLIC_` value such as the Turnstile site key sits under `vars` in the Wrangler config: that reaches the running Worker only, so the page has no widget; it has to be a Build variable. The Cloudflare guide adds the Turnstile secret to its settings and says a build variable needs a new build.
15
+ - 62e89bc: `npx bearminion add form <service>` now asks which host the site runs on, in a terminal, when nothing in the project names one (or two hosts do). It offers Vercel, Netlify and Cloudflare, and Enter writes the handler alone, as before. With `--host`, with `--json`, or without a terminal it does not ask.
16
+ - 88fae9e: The Cloudflare Wrangler config that `add form --host cloudflare` writes now uses `"run_worker_first": ["/api/*"]` instead of `true`, so page views are served from the built site without running the Worker, and only `/api/*` reaches the handler. A site that already has `true` keeps working. Tried on a real deploy: pages load, `/api/contact` answers, and a message arrives.
17
+
3
18
  ## 1.10.0
4
19
 
5
20
  ### Minor Changes
package/dist/astro.d.ts CHANGED
@@ -1,5 +1,5 @@
1
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-gXystJjG.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-NdG2XQv4.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,10 +2,11 @@ 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 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";
5
+ import { i as resolveMaxImageBytes, n as formatBytes, r as resolveConvert } from "./upload-rules-Cao9uY5K.js";
6
+ import { a as isLocalRequest, c as resolveInside, i as isInside, n as JSON_BODY_LIMIT, o as readSlug, r as asDirectory, s as resolveDir, t as IMAGE_BYTE_LIMIT } from "./security-BA9KzK-2.js";
7
+ import { a as resolveFormsConfig, n as formFile, r as formsAreLive, t as createFormsMiddleware } from "./forms-dev-DQoWfcMA.js";
7
8
  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";
9
+ import { n as contentReloadPlugin, r as dropEarlyReloadAfterSave } from "./reload-CU0U52ja.js";
9
10
  import { i as syncSections, r as staleSectionsMessage } from "./sections-manifest-CO9QfJPG.js";
10
11
  import { z } from "zod";
11
12
  import fs from "node:fs";
@@ -295,8 +296,12 @@ async function deleteImage(uploadsDir, filename) {
295
296
  return false;
296
297
  }
297
298
  }
298
- function imageTooLarge(size) {
299
- return size > IMAGE_BYTE_LIMIT;
299
+ function imageTooLarge(size, maxBytes = IMAGE_BYTE_LIMIT) {
300
+ return size > maxBytes;
301
+ }
302
+ /** The largest request body an image upload may have: the file plus room for the multipart boundaries. */
303
+ function imageBodyLimit(maxBytes) {
304
+ return maxBytes + 262144;
300
305
  }
301
306
  function safeStem(originalName) {
302
307
  return path.win32.basename(path.basename(originalName)).replace(/\.[^.]+$/, "").normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "image";
@@ -439,6 +444,8 @@ function resolveEditorContext(options, rootInput) {
439
444
  uploadsDir,
440
445
  videosDir,
441
446
  maxVideoBytes: options?.maxVideoBytes ?? 52428800,
447
+ maxImageBytes: resolveMaxImageBytes(options?.maxImageBytes),
448
+ imageConvert: resolveConvert(options?.imageConvert),
442
449
  sections: options.sections,
443
450
  site: options.site,
444
451
  theme: options.theme ?? defaultTheme,
@@ -1262,7 +1269,14 @@ async function postSitePreview(request, context, meta) {
1262
1269
  }
1263
1270
  }
1264
1271
  async function getImages(context) {
1265
- return json(200, { images: await context.store.uploads.list() });
1272
+ const limits = {
1273
+ maxBytes: context.maxImageBytes,
1274
+ convert: context.imageConvert
1275
+ };
1276
+ return json(200, {
1277
+ images: await context.store.uploads.list(),
1278
+ limits
1279
+ });
1266
1280
  }
1267
1281
  function decodeSegment(segment) {
1268
1282
  try {
@@ -1397,8 +1411,9 @@ async function postVideo(request, context) {
1397
1411
  }
1398
1412
  }
1399
1413
  async function postImage(request, context) {
1414
+ const tooLarge = () => problem(413, "too_large", `Images must be ${formatBytes(context.maxImageBytes)} or smaller.`);
1400
1415
  const length = contentLength(request);
1401
- if (length !== null && length > 5505024) return problem(413, "too_large", "Upload exceeds the 5MB image limit.");
1416
+ if (length !== null && length > imageBodyLimit(context.maxImageBytes)) return tooLarge();
1402
1417
  if (!(request.headers.get("content-type") ?? "").toLowerCase().includes("multipart/form-data")) return problem(415, "unsupported_media_type", "Upload the image as multipart/form-data.");
1403
1418
  let form;
1404
1419
  try {
@@ -1408,9 +1423,9 @@ async function postImage(request, context) {
1408
1423
  }
1409
1424
  const entry = form.get("file");
1410
1425
  if (!(entry instanceof File)) return problem(400, "invalid_upload", "Expected a multipart file field named \"file\".");
1411
- if (imageTooLarge(entry.size)) return problem(413, "too_large", "Images must be 5MB or smaller.");
1426
+ if (imageTooLarge(entry.size, context.maxImageBytes)) return tooLarge();
1412
1427
  const bytes = new Uint8Array(await entry.arrayBuffer());
1413
- if (imageTooLarge(bytes.byteLength)) return problem(413, "too_large", "Images must be 5MB or smaller.");
1428
+ if (imageTooLarge(bytes.byteLength, context.maxImageBytes)) return tooLarge();
1414
1429
  const declared = kindFromMime(entry.type);
1415
1430
  const sniffed = sniffImage(bytes);
1416
1431
  if (declared === null || sniffed === null || declared !== sniffed) return problem(415, "unsupported_media_type", "Upload a png, jpeg, webp, gif, or avif file whose contents match the declared type.");
@@ -1698,8 +1713,8 @@ async function dispatch(req, res, context, rawUrl, hooks) {
1698
1713
  const method = (req.method ?? "GET").toUpperCase();
1699
1714
  const multipart = (headers.get("content-type") ?? "").toLowerCase().includes("multipart/form-data");
1700
1715
  const videoUpload = multipart && stripTrailingSlash(rawUrl.split("?")[0] ?? "") === `/__bearminion/api/videos`;
1701
- const limit = videoUpload ? videoBodyLimit(context.maxVideoBytes) : multipart ? MULTIPART_BODY_LIMIT : JSON_BODY_LIMIT;
1702
- const tooLargeMessage = videoUpload ? "Upload exceeds the video size limit." : multipart ? "Upload exceeds the 5MB image limit." : "JSON body exceeds 1MB.";
1716
+ const limit = videoUpload ? videoBodyLimit(context.maxVideoBytes) : multipart ? imageBodyLimit(context.maxImageBytes) : JSON_BODY_LIMIT;
1717
+ const tooLargeMessage = videoUpload ? "Upload exceeds the video size limit." : multipart ? `Upload exceeds the ${formatBytes(context.maxImageBytes)} image limit.` : "JSON body exceeds 1MB.";
1703
1718
  const advertised = Number(headers.get("content-length") ?? "");
1704
1719
  if (Number.isFinite(advertised) && advertised > limit) {
1705
1720
  await send(res, jsonProblem(413, "too_large", tooLargeMessage));
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { i as readDotEnv } from "./forms-dev-CaxRmLhl.js";
2
+ import { i as readDotEnv } from "./forms-dev-DQoWfcMA.js";
3
3
  import { i as syncSections, r as staleSectionsMessage, t as SectionsError } from "./sections-manifest-CO9QfJPG.js";
4
4
  import { i as writeLock, n as readLock, r as recordFiles, t as hashContent } from "./hash-BeBymBO1.js";
5
5
  import fs from "node:fs";
@@ -216,7 +216,7 @@ export default {
216
216
  "wrangler.json",
217
217
  "wrangler.toml"
218
218
  ],
219
- skipNote: "This site already has a Wrangler config, so it was left alone. It needs \"main\": \"./worker.ts\", \"assets\" with \"binding\": \"ASSETS\" and \"run_worker_first\": true, and CONTACT_FROM and CONTACT_TO under \"vars\". See the Forms guide.",
219
+ skipNote: "This site already has a Wrangler config, so it was left alone. It needs \"main\": \"./worker.ts\", \"assets\" with \"binding\": \"ASSETS\" and \"run_worker_first\": [\"/api/*\"], and CONTACT_FROM and CONTACT_TO under \"vars\". See the Forms guide.",
220
220
  source: `// "name" has to be the name of your Worker in Cloudflare.
221
221
  // RESEND_API_KEY is a secret: set it in the Worker's Settings, not here. CONTACT_FROM and CONTACT_TO are plain values and
222
222
  // live under "vars", because a deploy replaces variables that exist only in the dashboard. Fill them in, and keep this
@@ -225,7 +225,7 @@ export default {
225
225
  "name": "my-site",
226
226
  "compatibility_date": "2026-10-27",
227
227
  "main": "./worker.ts",
228
- "assets": { "directory": "./dist", "binding": "ASSETS", "run_worker_first": true },
228
+ "assets": { "directory": "./dist", "binding": "ASSETS", "run_worker_first": ["/api/*"] },
229
229
  "observability": { "logs": { "enabled": true, "invocation_logs": true, "persist": true } },
230
230
  "vars": { "CONTACT_FROM": "", "CONTACT_TO": "" }
231
231
  }
@@ -509,7 +509,15 @@ function checkCloudflare(root, add, plainNames, secretNames) {
509
509
  if (typeof value === "string" && value.trim() !== "") add("ok", `${variable} is set under "vars".`);
510
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
511
  }
512
- if (secretNames.length > 0) add("note", `Set ${secretNames.join(", ")} as Secrets in the Worker's Settings. I cannot read them from here.`);
512
+ const publicNames = configFile.endsWith(".toml") ? [...text.matchAll(/^\s*(PUBLIC_[A-Z0-9_]+)\s*=/gm)].map((match) => match[1]) : Object.keys(vars).filter((variable) => variable.startsWith("PUBLIC_"));
513
+ if (publicNames.length > 0) {
514
+ const one = publicNames.length === 1;
515
+ add("note", `${publicNames.join(", ")} ${one ? "is" : "are"} in ${configFile}. Those reach the running Worker only; Astro reads PUBLIC_ values when the site is built, so set ${one ? "it" : "them"} as Build variables in the dashboard (then push or retry the build). Under "vars" the page has no Turnstile widget.`);
516
+ }
517
+ if (secretNames.length > 0) {
518
+ const many = secretNames.length > 1;
519
+ add("note", `Set ${secretNames.join(", ")} as ${many ? "Secrets" : "a Secret"} in the Worker's Settings. I cannot read ${many ? "them" : "it"} from here.`);
520
+ }
513
521
  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
522
  }
515
523
  /**
@@ -1050,7 +1058,18 @@ async function runAddForm(root, names, values, io) {
1050
1058
  const handler = names[0] === void 0 ? void 0 : HANDLERS.find((candidate) => candidate.name === names[0]);
1051
1059
  if (names[0] !== void 0 && handler === void 0) return fail(`There is no form service called "${names[0]}". The services are: ${HANDLERS.map((candidate) => candidate.name).join(", ")}.`);
1052
1060
  const detected = values.host === void 0 ? detectHost(root) : void 0;
1053
- const hostName = values.host ?? detected;
1061
+ let chosen;
1062
+ if (values.host === void 0 && detected === void 0 && handler !== void 0 && !json && io.choose !== void 0) {
1063
+ chosen = await io.choose("Where does this site run? The project does not say.", [...GLUE.map((candidate) => ({
1064
+ value: candidate.name,
1065
+ label: candidate.description
1066
+ })), {
1067
+ value: "",
1068
+ label: "Somewhere else: write the handler only"
1069
+ }]);
1070
+ if (chosen === "") chosen = void 0;
1071
+ }
1072
+ const hostName = values.host ?? detected ?? chosen;
1054
1073
  const glue = hostName === void 0 ? void 0 : GLUE.find((candidate) => candidate.name === hostName);
1055
1074
  if (values.host !== void 0 && glue === void 0) return fail(`There is no host called "${hostName}". The hosts are: ${GLUE.map((candidate) => candidate.name).join(", ")}.`);
1056
1075
  if (handler === void 0 && glue === void 0) return fail("Name a service, a host, or both. For example: npx bearminion add form resend --host vercel. Use --list to see them.", 2);
@@ -1078,7 +1097,7 @@ async function runAddForm(root, names, values, io) {
1078
1097
  ...extra
1079
1098
  }, null, 2);
1080
1099
  if (!json) {
1081
- log(`${values["dry-run"] ? "Would add" : "Adding"} the form recipe${glue ? ` for ${glue.name}${detected ? " (found from the project)" : ""}` : ""}${handler ? ` with ${handler.name}` : ""}`);
1100
+ log(`${values["dry-run"] ? "Would add" : "Adding"} the form recipe${glue ? ` for ${glue.name}${detected ? " (found from the project)" : chosen ? " (your choice)" : ""}` : ""}${handler ? ` with ${handler.name}` : ""}`);
1082
1101
  log("");
1083
1102
  for (const file of changes) log(` ${LABELS[file.action].padEnd(9)} ${file.path}`);
1084
1103
  const same = plan.files.length - changes.length;
@@ -1156,8 +1175,26 @@ async function confirm(question) {
1156
1175
  rl.close();
1157
1176
  }
1158
1177
  }
1178
+ /** A numbered list; Enter, or a number that is not on the list, picks nothing. */
1179
+ async function choose(question, options) {
1180
+ const rl = createInterface({
1181
+ input: process.stdin,
1182
+ output: process.stdout
1183
+ });
1184
+ try {
1185
+ console.log(question);
1186
+ for (const [index, option] of options.entries()) console.log(` ${index + 1}. ${option.label}`);
1187
+ const answer = Number((await rl.question("Number: ")).trim());
1188
+ return Number.isInteger(answer) ? options[answer - 1]?.value : void 0;
1189
+ } finally {
1190
+ rl.close();
1191
+ }
1192
+ }
1159
1193
  process.exitCode = await run(process.argv.slice(2), {
1160
1194
  registryDir,
1161
- ...process.stdin.isTTY ? { confirm } : {}
1195
+ ...process.stdin.isTTY ? {
1196
+ confirm,
1197
+ choose
1198
+ } : {}
1162
1199
  });
1163
1200
  //#endregion
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-DA07O8cA.js";
3
+ import { t as CONTENT_COLLECTIONS_MARKER } from "./reload-CU0U52ja.js";
4
4
  import { z } from "zod";
5
5
  import path from "node:path";
6
6
  import { pathToFileURL } from "node:url";
@@ -1,4 +1,4 @@
1
- import { c as resolveDir } from "./security-DOvoYZuQ.js";
1
+ import { s as resolveDir } from "./security-BA9KzK-2.js";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { parseEnv } from "node:util";
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
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-gXystJjG.js";
3
+ import "./options-NdG2XQv4.js";
4
4
  import { a as TURNSTILE_FIELD, i as HONEYPOT_FIELD, n as FormResult, r as FormSubmission, t as FormFieldErrors } from "./form-contract-BURSJP3Y.js";
5
5
  //#region src/errors.d.ts
6
6
  /** One schema problem, addressed by a dot path such as `sections.0.props.heading`. */
@@ -102,6 +102,25 @@ interface FileStoreOptions {
102
102
  /** The content store for a local project: content as JSON files, uploads in a folder. */
103
103
  declare function createFileStore({ root, contentDir, uploadsDir, videosDir }: FileStoreOptions): ContentStore;
104
104
  //#endregion
105
+ //#region src/upload-rules.d.ts
106
+ /** Re-encode uploads in the browser before they are sent. */
107
+ interface ImageConvertOptions {
108
+ to: 'webp';
109
+ /** Wider images are scaled down to this width, never up. Default: no width cap. */
110
+ maxWidth?: number;
111
+ /** WebP quality, 0.1 to 1. Default 0.82. */
112
+ quality?: number;
113
+ }
114
+ /** What the browser needs to know before it sends a file. */
115
+ interface UploadRules {
116
+ maxBytes: number;
117
+ convert: {
118
+ to: 'webp';
119
+ maxWidth: number | null;
120
+ quality: number;
121
+ } | null;
122
+ }
123
+ //#endregion
105
124
  //#region src/options.d.ts
106
125
  interface BearminionOptions extends ContentModel {
107
126
  /** Directory that contains `site.json` and `pages/`. Default `content`. */
@@ -112,6 +131,17 @@ interface BearminionOptions extends ContentModel {
112
131
  videosDir?: string;
113
132
  /** Largest video the editor accepts, in bytes. Default 50 MB. */
114
133
  maxVideoBytes?: number;
134
+ /**
135
+ * Largest image the editor accepts, in bytes. Default 5 MB. The editor checks it in the browser before it uploads,
136
+ * and the server checks it again.
137
+ */
138
+ maxImageBytes?: number;
139
+ /**
140
+ * Re-encode images in the browser before they are uploaded, so phone photos stay out of the repository:
141
+ * `{ to: 'webp', maxWidth: 2400, quality: 0.82 }`. Animated GIFs are never converted, and an image that would come
142
+ * out larger is kept as it is. Default: off, images are uploaded as they are.
143
+ */
144
+ imageConvert?: false | ImageConvertOptions;
115
145
  /**
116
146
  * Vite module id loaded by the dev server to render a draft page.
117
147
  * Default `/src/lib/render-preview.ts`. Preview never writes to disk.
@@ -151,6 +181,9 @@ interface EditorContext {
151
181
  uploadsDir: string;
152
182
  videosDir: string;
153
183
  maxVideoBytes: number;
184
+ maxImageBytes: number;
185
+ /** `imageConvert`, validated and with its defaults filled in. `null` when conversion is off. */
186
+ imageConvert: UploadRules['convert'];
154
187
  sections: SectionRegistry;
155
188
  site: SiteDefinition;
156
189
  theme: ThemeDefinition;
@@ -1,4 +1,4 @@
1
- import { a as isInside } from "./security-DOvoYZuQ.js";
1
+ import { i as isInside } from "./security-BA9KzK-2.js";
2
2
  import path from "node:path";
3
3
  //#region src/reload.ts
4
4
  const RELOAD_DELAY_MS = 50;
@@ -1,11 +1,11 @@
1
1
  import { o as slugSchema } from "./page-X-WnOu7-.js";
2
+ import { t as DEFAULT_IMAGE_BYTE_LIMIT } from "./upload-rules-Cao9uY5K.js";
2
3
  import path from "node:path";
3
4
  import { fileURLToPath } from "node:url";
4
5
  //#region src/security.ts
5
6
  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;
7
+ const IMAGE_BYTE_LIMIT = DEFAULT_IMAGE_BYTE_LIMIT;
8
+ IMAGE_BYTE_LIMIT + 262144;
9
9
  const LOCAL_HOSTS = /* @__PURE__ */ new Set([
10
10
  "localhost",
11
11
  "127.0.0.1",
@@ -90,4 +90,4 @@ function readSlug(segment) {
90
90
  return parsed.success ? parsed.data : null;
91
91
  }
92
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 };
93
+ export { isLocalRequest as a, resolveInside as c, isInside as i, JSON_BODY_LIMIT as n, readSlug as o, asDirectory as r, resolveDir as s, IMAGE_BYTE_LIMIT as t };
package/dist/ui/mount.js CHANGED
@@ -2,6 +2,7 @@ import { a as sectionFieldKey, i as isPropShown, t as defaultTheme } from "../th
2
2
  import { B as withImageLayout, F as DEFAULT_IMAGE_POSITION, I as IMAGE_FITS, L as IMAGE_POSITIONS, P as DEFAULT_IMAGE_FIT, R as isImageFit, S as upsertJsonLd, b as parseJsonLdInput, g as isPlaceholderSiteUrl, i as isSystemPage, m as generateSiteJsonLd, p as formatJsonLd, v as jsonLdWarnings, z as isImagePosition } from "../page-X-WnOu7-.js";
3
3
  import { d as reconcileMarks, f as renderMarkedHtml, i as fontMarks, l as marksFromEmphasis, t as applyTextMark } from "../marks-DPBilumg.js";
4
4
  import { _ as consentCopy, b as parseMediaSource, c as hasThemeColors, d as tokenToHex, f as CONSENT_COPY, h as CONSENT_LIMITS, i as contrastChecks, n as HEX_COLOR, o as derivePalette, r as OVERRIDE_TOKENS, s as hasOverrides, t as DEFAULT_BRAND, u as themeCss, v as consentTextIssues } from "../theme-colors-CHROGZkI.js";
5
+ import { n as formatBytes, t as DEFAULT_IMAGE_BYTE_LIMIT } from "../upload-rules-Cao9uY5K.js";
5
6
  import { _ as writeSaveNotice, a as localDraftStorage, d as removeDraft, f as savedNoticeFor, g as writeDraftRecord, h as sweepExpiredDrafts, i as isForeignSave, l as readDraftRecord, m as siteSavedKey, n as draftBannerText, o as pageDraftKey, p as siteDraftKey, r as hashText, s as pageSavedKey, t as assessStoredDraft, u as reloadDecision, x as draftImageUsages } from "../draft-store-1Y4-sn45.js";
6
7
  import { a as richLinkAt, c as updateRichLink, i as renderRichText, n as isSafeHref, o as sanitizeRichHtml, r as markdownFromHtml, s as stripPlainRich } from "../rich-text-70hddxMC.js";
7
8
  import { Component, Fragment, createContext, isValidElement, options, render } from "preact";
@@ -15435,6 +15436,110 @@ function createSectionActions(doc, ui, edits) {
15435
15436
  };
15436
15437
  }
15437
15438
  //#endregion
15439
+ //#region src/ui/prepare-image.ts
15440
+ /** Still images the browser can decode and re-encode. GIFs may be animated, so they are never converted. */
15441
+ const CONVERTIBLE = /* @__PURE__ */ new Set([
15442
+ "image/png",
15443
+ "image/jpeg",
15444
+ "image/webp",
15445
+ "image/avif"
15446
+ ]);
15447
+ let current = {
15448
+ maxBytes: DEFAULT_IMAGE_BYTE_LIMIT,
15449
+ convert: null
15450
+ };
15451
+ /** The rules the dev server reported. Until they arrive the defaults apply, and the server checks again anyway. */
15452
+ function setUploadRules(rules) {
15453
+ current = rules;
15454
+ }
15455
+ function getUploadRules() {
15456
+ return current;
15457
+ }
15458
+ function tooLarge(file, rules, converted) {
15459
+ const hint = converted ? "" : " Use a smaller image.";
15460
+ return {
15461
+ ok: false,
15462
+ error: `${file.name} is ${formatBytes(file.size)}. Images must be ${formatBytes(rules.maxBytes)} or smaller.${hint}`
15463
+ };
15464
+ }
15465
+ function webpName(original) {
15466
+ return `${original.replace(/\.[^.]+$/, "") || "image"}.webp`;
15467
+ }
15468
+ /**
15469
+ * Apply the site's upload rules to a file before it is sent: scale and re-encode it when conversion is on, keep the
15470
+ * original when conversion would not help, and refuse a file that is still over the size limit. The server enforces
15471
+ * the limit again; this check only saves the round trip and gives a clear message.
15472
+ */
15473
+ async function prepareImage(file, rules, codec = browserCodec) {
15474
+ const keep = () => file.size > rules.maxBytes ? tooLarge(file, rules, false) : {
15475
+ ok: true,
15476
+ file
15477
+ };
15478
+ if (rules.convert === null || !CONVERTIBLE.has(file.type)) return keep();
15479
+ let converted;
15480
+ try {
15481
+ converted = await codec.toWebp(file, {
15482
+ maxWidth: rules.convert.maxWidth,
15483
+ quality: rules.convert.quality
15484
+ });
15485
+ } catch {
15486
+ converted = null;
15487
+ }
15488
+ if (converted === null || converted.blob.type !== "image/webp") return keep();
15489
+ if (!converted.resized && converted.blob.size >= file.size) return keep();
15490
+ const result = new File([converted.blob], webpName(file.name), {
15491
+ type: "image/webp",
15492
+ lastModified: file.lastModified
15493
+ });
15494
+ return result.size > rules.maxBytes ? tooLarge(result, rules, true) : {
15495
+ ok: true,
15496
+ file: result
15497
+ };
15498
+ }
15499
+ async function encodeWebp(bitmap, width, height, quality) {
15500
+ if (typeof OffscreenCanvas === "function") {
15501
+ const canvas = new OffscreenCanvas(width, height);
15502
+ const context = canvas.getContext("2d");
15503
+ if (context === null) return null;
15504
+ context.imageSmoothingQuality = "high";
15505
+ context.drawImage(bitmap, 0, 0, width, height);
15506
+ return canvas.convertToBlob({
15507
+ type: "image/webp",
15508
+ quality
15509
+ });
15510
+ }
15511
+ const canvas = document.createElement("canvas");
15512
+ canvas.width = width;
15513
+ canvas.height = height;
15514
+ const context = canvas.getContext("2d");
15515
+ if (context === null) return null;
15516
+ context.imageSmoothingQuality = "high";
15517
+ context.drawImage(bitmap, 0, 0, width, height);
15518
+ return new Promise((resolve) => canvas.toBlob(resolve, "image/webp", quality));
15519
+ }
15520
+ /** The real codec. `from-image` applies the photo's EXIF rotation; re-encoding drops the metadata, GPS included. */
15521
+ const browserCodec = { async toWebp(file, { maxWidth, quality }) {
15522
+ if (typeof createImageBitmap !== "function") return null;
15523
+ let bitmap;
15524
+ try {
15525
+ bitmap = await createImageBitmap(file, { imageOrientation: "from-image" });
15526
+ } catch {
15527
+ return null;
15528
+ }
15529
+ try {
15530
+ const capped = maxWidth !== null && bitmap.width > maxWidth ? maxWidth : null;
15531
+ const width = capped ?? bitmap.width;
15532
+ const height = Math.max(1, Math.round(bitmap.height * (width / bitmap.width)));
15533
+ const blob = await encodeWebp(bitmap, width, height, quality);
15534
+ return blob === null ? null : {
15535
+ blob,
15536
+ resized: capped !== null
15537
+ };
15538
+ } finally {
15539
+ bitmap.close();
15540
+ }
15541
+ } };
15542
+ //#endregion
15438
15543
  //#region src/ui/state/session.ts
15439
15544
  /** How long a save waits for the first load before giving up. */
15440
15545
  const READY_TIMEOUT_MS = 8e3;
@@ -15485,7 +15590,10 @@ function createSession(doc, ui, edits, drafts) {
15485
15590
  if (typeof projectId === "string" && projectId !== "") doc.projectId.value = projectId;
15486
15591
  }
15487
15592
  if (listRes.ok) doc.pages.value = listRes.value.pages;
15488
- if (imageRes.ok) doc.images.value = imageRes.value.images;
15593
+ if (imageRes.ok) {
15594
+ doc.images.value = imageRes.value.images;
15595
+ if (imageRes.value.limits) setUploadRules(imageRes.value.limits);
15596
+ }
15489
15597
  if (nextSite) {
15490
15598
  doc.site.value = nextSite;
15491
15599
  doc.savedSiteJson.value = savedSiteJson;
@@ -17054,7 +17162,9 @@ function ImageField({ label, path, value, images, withAlt = true, layout = true,
17054
17162
  });
17055
17163
  }
17056
17164
  async function uploadFile(file) {
17057
- const result = await uploadImage(file);
17165
+ const prepared = await prepareImage(file, getUploadRules());
17166
+ if (!prepared.ok) return { error: prepared.error };
17167
+ const result = await uploadImage(prepared.file);
17058
17168
  if (!result.ok) return { error: result.status === 0 ? "Upload failed." : result.message };
17059
17169
  return { image: result.value };
17060
17170
  }
@@ -17237,9 +17347,9 @@ function ImagePickerModal({ src, images, onPick, onUploaded, onDeleted, onClose
17237
17347
  class: "bm-slot-title",
17238
17348
  children: busy ? "Uploading…" : "Drag an image here"
17239
17349
  }),
17240
- /* @__PURE__ */ jsx("span", {
17350
+ /* @__PURE__ */ jsxs("span", {
17241
17351
  class: "bm-slot-hint",
17242
- children: "or click to browse · png, jpeg, webp, gif, avif · up to 5MB"
17352
+ children: ["or click to browse · png, jpeg, webp, gif, avif · up to ", formatBytes(getUploadRules().maxBytes)]
17243
17353
  }),
17244
17354
  /* @__PURE__ */ jsx("input", {
17245
17355
  class: "bm-visually-hidden",
@@ -0,0 +1,36 @@
1
+ //#region src/upload-rules.ts
2
+ /**
3
+ * Image upload rules shared by the dev server and the editor in the browser. No Node imports: the browser bundle
4
+ * uses it too.
5
+ */
6
+ /** The default largest image the editor accepts: 5 MB. */
7
+ const DEFAULT_IMAGE_BYTE_LIMIT = 5242880;
8
+ const DEFAULT_CONVERT_QUALITY = .82;
9
+ const MAX_CONVERT_WIDTH = 16384;
10
+ /** Check `imageConvert` and fill in its defaults. `false` and `undefined` mean no conversion. */
11
+ function resolveConvert(input) {
12
+ if (input === void 0 || input === false) return null;
13
+ if (input.to !== "webp") throw new Error(`bearminion(): imageConvert.to must be "webp", got "${String(input.to)}".`);
14
+ const { maxWidth, quality = DEFAULT_CONVERT_QUALITY } = input;
15
+ if (maxWidth !== void 0 && (!Number.isInteger(maxWidth) || maxWidth < 16 || maxWidth > 16384)) throw new Error(`bearminion(): imageConvert.maxWidth must be a whole number from 16 to ${MAX_CONVERT_WIDTH}.`);
16
+ if (!Number.isFinite(quality) || quality < .1 || quality > 1) throw new Error("bearminion(): imageConvert.quality must be a number from 0.1 to 1.");
17
+ return {
18
+ to: "webp",
19
+ maxWidth: maxWidth ?? null,
20
+ quality
21
+ };
22
+ }
23
+ /** Check `maxImageBytes`. */
24
+ function resolveMaxImageBytes(input) {
25
+ if (input === void 0) return DEFAULT_IMAGE_BYTE_LIMIT;
26
+ if (!Number.isInteger(input) || input < 1024) throw new Error("bearminion(): maxImageBytes must be a whole number of bytes, at least 1024.");
27
+ return input;
28
+ }
29
+ /** "4.2 MB", "310 KB", "512 B". */
30
+ function formatBytes(bytes) {
31
+ if (bytes >= 1048576) return `${(bytes / 1048576).toFixed(1).replace(/\.0$/, "")} MB`;
32
+ if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`;
33
+ return `${bytes} B`;
34
+ }
35
+ //#endregion
36
+ export { resolveMaxImageBytes as i, formatBytes as n, resolveConvert as r, DEFAULT_IMAGE_BYTE_LIMIT as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bearminion",
3
- "version": "1.10.0",
3
+ "version": "1.11.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.10.0",
4
+ "version": "1.11.0",
5
5
  "files": {
6
6
  "src/components/atoms/Button.astro": {
7
7
  "hash": "7be42b3dc3a3b59bec169de32a9d801904689e2705473d1945724658dc799043",