bearminion 1.19.0 → 1.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +4 -2
  3. package/dist/astro.d.ts +23 -7
  4. package/dist/astro.js +221 -94
  5. package/dist/cli.js +903 -4
  6. package/dist/content-types-POybRzMX.js +504 -0
  7. package/dist/content.d.ts +24 -3
  8. package/dist/content.js +83 -6
  9. package/dist/{editor-context-DzRwKENi.d.ts → editor-context-BwQzdSow.d.ts} +76 -7
  10. package/dist/{github-store-D3LEUhcM.js → github-store-4-Y4ERBF.js} +513 -200
  11. package/dist/{github-store-DsLCe5MR.d.ts → github-store-BVQY4d-Q.d.ts} +1 -1
  12. package/dist/hosted-astro.js +6 -3
  13. package/dist/{hosted-middleware-CedN9WNM.js → hosted-middleware-D6cd62SL.js} +3 -2
  14. package/dist/hosted-overlay.js +1 -1
  15. package/dist/hosted.d.ts +22 -4
  16. package/dist/hosted.js +79 -11
  17. package/dist/index.d.ts +4 -41
  18. package/dist/index.js +6 -5
  19. package/dist/{migrate-b408EaLp.js → migrate-Cm30puW8.js} +2 -2
  20. package/dist/{page-wlcQJAA-.js → page-CcC5RRMj.js} +1 -1
  21. package/dist/{page-BGSTL63-.d.ts → page-aWKWqoh4.d.ts} +184 -44
  22. package/dist/{request-guards-BcSUj8Gc.js → request-guards-6WtQV3-a.js} +1 -1
  23. package/dist/{collections-BbL4_4jt.js → routing-BWuJlNud.js} +245 -57
  24. package/dist/routing-DimIRnjk.d.ts +133 -0
  25. package/dist/{theme-BvqJ8UnS.js → theme-DVMi1524.js} +1 -1
  26. package/dist/ui/mount.js +625 -271
  27. package/package.json +1 -1
  28. package/registry/default/files/src/components/organisms/EntryList.astro +83 -0
  29. package/registry/default/files/src/components/organisms/Pagination.astro +56 -0
  30. package/registry/default/files/src/components/sections/contact/definition.ts +6 -2
  31. package/registry/default/files/src/components/sections/faq/definition.ts +2 -2
  32. package/registry/default/files/src/components/sections/media/Media.astro +2 -2
  33. package/registry/default/files/src/components/sections/media/MediaPlayer.astro +2 -2
  34. package/registry/default/files/src/components/sections/pricing/definition.ts +16 -1
  35. package/registry/default/files/src/components/sections/shared.ts +3 -0
  36. package/registry/default/files/src/components/sections/stats/definition.ts +6 -1
  37. package/registry/default/files/src/components/sections/testimonials/definition.ts +13 -1
  38. package/registry/default/files/src/components/sections/text-image/definition.ts +1 -1
  39. package/registry/default/files/src/content.config.ts +21 -0
  40. package/registry/default/files/src/env.d.ts +2 -0
  41. package/registry/default/files/src/lib/content.ts +81 -0
  42. package/registry/default/files/src/lib/editing.ts +6 -0
  43. package/registry/default/files/src/lib/sitemap.ts +48 -0
  44. package/registry/default/files/src/pages/[...slug].astro +32 -13
  45. package/registry/default/registry.json +76 -20
package/dist/cli.js CHANGED
@@ -1,7 +1,10 @@
1
1
  #!/usr/bin/env node
2
+ import { k as imageSchema } from "./page-CcC5RRMj.js";
3
+ import { _ as multi, b as single, d as defineTypes } from "./content-types-POybRzMX.js";
2
4
  import { i as readDotEnv } from "./forms-dev-CzUHR7oS.js";
3
5
  import { i as syncSections, r as staleSectionsMessage, t as SectionsError } from "./sections-manifest-CO9QfJPG.js";
4
6
  import { i as writeLock, n as readLock, r as recordFiles, t as hashContent } from "./hash-BeBymBO1.js";
7
+ import { z } from "zod";
5
8
  import fs from "node:fs";
6
9
  import path from "node:path";
7
10
  import { fileURLToPath } from "node:url";
@@ -790,6 +793,590 @@ function checklist(manager, base) {
790
793
  ];
791
794
  }
792
795
  //#endregion
796
+ //#region src/add/type.ts
797
+ const CONTENT_MODEL_PATH = "src/lib/content-model.ts";
798
+ const TYPES_DIR = "src/lib/types";
799
+ const TYPES_INDEX = `${TYPES_DIR}/index.ts`;
800
+ const TYPES_GUIDE = "https://docs.bearminion.com/content-types/";
801
+ /** The kinds of field this command writes: one for each control the editor draws for a type's fields. */
802
+ const FIELD_KINDS = [
803
+ "text",
804
+ "long-text",
805
+ "date",
806
+ "number",
807
+ "switch",
808
+ "choice",
809
+ "image",
810
+ "list"
811
+ ];
812
+ const FIELD_KIND_LABELS = {
813
+ text: "Text, one line",
814
+ "long-text": "Text, a paragraph",
815
+ date: "Date",
816
+ number: "Number",
817
+ switch: "Switch, on or off (off to start)",
818
+ choice: "Choice from a list",
819
+ image: "Image (always optional)",
820
+ list: "List of words, such as tags (empty to start)"
821
+ };
822
+ /** Kinds that always hold a value, so whether they are required is never asked. */
823
+ const ALWAYS_SET = /* @__PURE__ */ new Set(["switch", "list"]);
824
+ /** An image cannot be given a first value when an entry is created, so it is always optional. */
825
+ const NEVER_REQUIRED = /* @__PURE__ */ new Set(["image"]);
826
+ /** Kinds whose values have an order. Lists and images do not. */
827
+ const SORTABLE = /* @__PURE__ */ new Set([
828
+ "text",
829
+ "long-text",
830
+ "date",
831
+ "number",
832
+ "switch",
833
+ "choice"
834
+ ]);
835
+ const DEFAULT_MAX = {
836
+ text: 120,
837
+ "long-text": 1e3
838
+ };
839
+ /** Types this command can write without asking anything. `add blog` is `add type` with the `blog` preset. */
840
+ const PRESETS = { blog: {
841
+ id: "blog",
842
+ kind: "multi",
843
+ path: "/blog/{slug}",
844
+ fields: [
845
+ {
846
+ name: "date",
847
+ kind: "date",
848
+ required: true
849
+ },
850
+ {
851
+ name: "excerpt",
852
+ kind: "long-text",
853
+ required: false,
854
+ max: 200
855
+ },
856
+ {
857
+ name: "cover",
858
+ kind: "image",
859
+ required: false
860
+ },
861
+ {
862
+ name: "draft",
863
+ kind: "switch",
864
+ required: true
865
+ }
866
+ ],
867
+ sort: {
868
+ by: "date",
869
+ order: "desc"
870
+ },
871
+ listing: { perPage: 10 }
872
+ } };
873
+ const FIELD_NAME = /^[a-z][a-zA-Z0-9]*$/;
874
+ /** `title` is what a sort by title means; a field of that name could never be told apart from it. */
875
+ const RESERVED_FIELDS = /* @__PURE__ */ new Set(["title"]);
876
+ /** Why `name` cannot be a field name, or undefined when it can. */
877
+ function fieldNameProblem(name, taken) {
878
+ if (!FIELD_NAME.test(name)) return `"${name}" must be camelCase letters and digits, starting with a letter: date, publishDate, readingTime.`;
879
+ if (RESERVED_FIELDS.has(name)) return `"${name}" is taken: every entry already has a title.`;
880
+ if (taken.includes(name)) return `There is already a field named "${name}".`;
881
+ }
882
+ /** The field as the command writes it: an image is never required, a switch or a list always is. */
883
+ function normalizeField(field) {
884
+ const required = ALWAYS_SET.has(field.kind) ? true : NEVER_REQUIRED.has(field.kind) ? false : field.required;
885
+ return {
886
+ ...field,
887
+ required
888
+ };
889
+ }
890
+ /** Whether the field may be what entries are sorted by: a value every entry has, of a kind with an order. */
891
+ function isSortable(field) {
892
+ const normalized = normalizeField(field);
893
+ return normalized.required && SORTABLE.has(normalized.kind);
894
+ }
895
+ /** `/news/{slug}` from `news`, `/news`, `news/{slug}` or `/news/{slug}`; `/about` from `about` or `/about`. */
896
+ function normalizePath(kind, input) {
897
+ const segment = input.trim().replace(/^\/+/, "").replace(/\/\{slug\}$/, "").replace(/\/+$/, "");
898
+ return kind === "multi" ? `/${segment}/{slug}` : `/${segment}`;
899
+ }
900
+ function defaultPath(kind, id) {
901
+ return kind === "multi" ? `/${id}/{slug}` : `/${id}`;
902
+ }
903
+ /** `case-studies` → `caseStudies`; an id starting with a digit gets `type` in front, so it is a valid name. */
904
+ function variableName(id) {
905
+ const camel = id.replace(/-([a-z0-9])/g, (_, char) => char.toUpperCase());
906
+ return /^[0-9]/.test(camel) ? `type${camel.charAt(0).toUpperCase()}${camel.slice(1)}` : camel;
907
+ }
908
+ const quote = (value) => `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
909
+ function fieldExpression(field) {
910
+ const max = field.max ?? DEFAULT_MAX[field.kind];
911
+ return `${{
912
+ text: `z.string().max(${max})`,
913
+ "long-text": `z.string().max(${max})`,
914
+ date: "z.iso.date()",
915
+ number: "z.number()",
916
+ switch: "z.boolean().default(false)",
917
+ choice: `z.enum([${(field.choices ?? []).map(quote).join(", ")}])`,
918
+ image: "imageSchema",
919
+ list: "z.array(z.string()).default([])"
920
+ }[field.kind]}${field.required ? "" : ".optional()"}`;
921
+ }
922
+ function fieldSchema(field) {
923
+ const max = field.max ?? DEFAULT_MAX[field.kind] ?? 0;
924
+ const schema = {
925
+ text: () => z.string().max(max),
926
+ "long-text": () => z.string().max(max),
927
+ date: () => z.iso.date(),
928
+ number: () => z.number(),
929
+ switch: () => z.boolean().default(false),
930
+ choice: () => z.enum(field.choices ?? []),
931
+ image: () => imageSchema,
932
+ list: () => z.array(z.string()).default([])
933
+ }[field.kind]();
934
+ return field.required ? schema : schema.optional();
935
+ }
936
+ /** The options `spec` declares, with real schemas, as `multi()` and `single()` take them. */
937
+ function options(spec) {
938
+ const fields = spec.fields.length > 0 ? z.object(Object.fromEntries(spec.fields.map((field) => [field.name, fieldSchema(field)]))) : void 0;
939
+ const shared = {
940
+ ...spec.label ? { label: spec.label } : {},
941
+ ...fields ? { fields } : {}
942
+ };
943
+ if (spec.kind === "single") return single({
944
+ path: spec.path,
945
+ ...shared
946
+ });
947
+ return multi({
948
+ path: spec.path,
949
+ ...shared,
950
+ ...spec.sort ? { sort: spec.sort } : {},
951
+ ...spec.listing ? { listing: { perPage: spec.listing.perPage } } : {}
952
+ });
953
+ }
954
+ /**
955
+ * Why `spec` would not make a working type, or undefined. The type is declared with the package's own `multi()`,
956
+ * `single()` and `defineTypes()`, so the answer is the one `astro dev` would give. Other types of the site are not
957
+ * known here: an address two types share is still caught by `astro dev`.
958
+ */
959
+ function specProblem(spec) {
960
+ const names = [];
961
+ for (const field of spec.fields) {
962
+ const problem = fieldNameProblem(field.name, names);
963
+ if (problem) return problem;
964
+ names.push(field.name);
965
+ if (field.kind === "choice") {
966
+ const choices = field.choices ?? [];
967
+ if (choices.length === 0) return `The choice "${field.name}" needs at least one option.`;
968
+ if (choices.some((choice) => choice.trim() === "")) return `The choice "${field.name}" has an empty option.`;
969
+ if (new Set(choices).size !== choices.length) return `The choice "${field.name}" lists an option twice.`;
970
+ }
971
+ }
972
+ if (spec.kind === "single" && (spec.sort || spec.listing)) return "A single has one document: it takes no sort and no listing.";
973
+ try {
974
+ defineTypes({ [spec.id]: options(spec) });
975
+ } catch (error) {
976
+ return error instanceof Error ? error.message.replace(/^Content types: /, "") : String(error);
977
+ }
978
+ }
979
+ /** One line on what the type is, for the file's comment and the command's report. */
980
+ function describeSpec(spec) {
981
+ const label = spec.label ?? spec.id.charAt(0).toUpperCase() + spec.id.slice(1).replaceAll("-", " ");
982
+ if (spec.kind === "single") return `${label}: one page at ${spec.path}.`;
983
+ const prefix = spec.path.replace("/{slug}", "");
984
+ const sortField = spec.fields.find((field) => field.name === spec.sort?.by);
985
+ const direction = sortField?.kind === "date" ? {
986
+ asc: "oldest first",
987
+ desc: "newest first"
988
+ } : sortField?.kind === "number" ? {
989
+ asc: "lowest first",
990
+ desc: "highest first"
991
+ } : {
992
+ asc: "A to Z",
993
+ desc: "Z to A"
994
+ };
995
+ const order = spec.sort ? `by ${spec.sort.by}, ${direction[spec.sort.order]}` : "by title, A to Z";
996
+ return `${label}: entries at ${prefix}/<slug>, ${spec.listing ? `listed at ${prefix}, ${spec.listing.perPage} to a page` : "no listing page"}, ordered ${order}.`;
997
+ }
998
+ /** `src/lib/types/<id>.ts`: the type, declared. */
999
+ function typeFileSource(spec) {
1000
+ const fields = spec.fields.map(normalizeField);
1001
+ const fromBearminion = [spec.kind === "single" ? "single" : "multi", ...fields.some((field) => field.kind === "image") ? ["imageSchema"] : []];
1002
+ const usesZod = fields.length > 0;
1003
+ const lines = [`import { ${fromBearminion.sort((a, b) => a.localeCompare(b)).join(", ")} } from 'bearminion'`];
1004
+ if (usesZod) lines.push("import { z } from 'zod'");
1005
+ lines.push("", "/**", ` * ${describeSpec(spec)}`, " * Made by `npx bearminion add type`, and yours from here: add or change fields, and the editor draws a control for each.", ` * Guide: ${TYPES_GUIDE}`, " */", `export const ${variableName(spec.id)} = ${spec.kind}({`, ` path: ${quote(spec.path)},`);
1006
+ if (spec.label) lines.push(` label: ${quote(spec.label)},`);
1007
+ if (fields.length > 0) {
1008
+ lines.push(" fields: z.object({");
1009
+ for (const field of fields) lines.push(` ${field.name}: ${fieldExpression(field)},`);
1010
+ lines.push(" }),");
1011
+ }
1012
+ if (spec.kind === "multi") {
1013
+ if (spec.sort) lines.push(` sort: { by: ${quote(spec.sort.by)}, order: ${quote(spec.sort.order)} },`);
1014
+ if (spec.listing) lines.push(` listing: { perPage: ${spec.listing.perPage} },`);
1015
+ }
1016
+ lines.push("})", "");
1017
+ return lines.join("\n");
1018
+ }
1019
+ const entryLine = (id) => {
1020
+ const name = variableName(id);
1021
+ return name === id ? ` ${id},` : ` ${quote(id)}: ${name},`;
1022
+ };
1023
+ const importLine = (id) => `import { ${variableName(id)} } from './${id}'`;
1024
+ /** `src/lib/types/index.ts` for a site whose first type is `id`. */
1025
+ function typesIndexSource(id) {
1026
+ return [
1027
+ "import { defineTypes } from 'bearminion'",
1028
+ importLine(id),
1029
+ "",
1030
+ "/**",
1031
+ " * The site's own content types, next to the built-in home page, 404 page and pages. `npx bearminion add type` adds a",
1032
+ ` * file to this folder and a line here. Guide: ${TYPES_GUIDE}`,
1033
+ " */",
1034
+ "export const siteTypes = defineTypes({",
1035
+ entryLine(id),
1036
+ "})",
1037
+ ""
1038
+ ].join("\n");
1039
+ }
1040
+ const INDEX_BLOCK = /^export const siteTypes = defineTypes\(\{(\}\)|\n[\s\S]*?\n\}\))[ \t]*$/m;
1041
+ function afterLastImport(source, line) {
1042
+ const imports = [...source.matchAll(/^import [^\n]*\n/gm)];
1043
+ const last = imports[imports.length - 1];
1044
+ const at = last ? (last.index ?? 0) + last[0].length : 0;
1045
+ return `${source.slice(0, at)}${line}\n${source.slice(at)}`;
1046
+ }
1047
+ /** `source` with `line` among its imports: before the first `./` import that sorts after it, as Biome orders them. */
1048
+ function insertImport(source, line, id) {
1049
+ const next = [...source.matchAll(/^import [^\n]* from '\.\/([^']+)'[^\n]*\n/gm)].find((match) => (match[1] ?? "").localeCompare(id) > 0);
1050
+ if (next === void 0) return afterLastImport(source, line);
1051
+ const at = next.index ?? 0;
1052
+ return `${source.slice(0, at)}${line}\n${source.slice(at)}`;
1053
+ }
1054
+ /** The index with `id` added to `siteTypes`. */
1055
+ function registerType(source, id) {
1056
+ const name = variableName(id);
1057
+ if (source.includes(`from './${id}'`) || new RegExp(`^\\s*(?:${name}|'${id}'\\s*:[^\\n]*),\\s*$`, "m").test(source)) return { action: "present" };
1058
+ const block = INDEX_BLOCK.exec(source);
1059
+ if (!block) return { action: "manual" };
1060
+ const replaced = `export const siteTypes = defineTypes({${block[1] === "})" ? "" : (block[1] ?? "").slice(0, -3)}\n${entryLine(id)}\n})`;
1061
+ return {
1062
+ action: "update",
1063
+ source: insertImport(source.slice(0, block.index) + replaced + source.slice(block.index + block[0].length), importLine(id), id)
1064
+ };
1065
+ }
1066
+ const SITE_LINE = /^([ \t]*)site: siteDefinition,[ \t]*$/m;
1067
+ /** The content model with `types: siteTypes` passed, or why it was left as it is. */
1068
+ function linkContentModel(source) {
1069
+ if (/^\s*types\s*:\s*siteTypes\s*,?\s*$/m.test(source)) return { action: "linked" };
1070
+ if (/^\s*types\s*:/m.test(source)) return { action: "other" };
1071
+ const site = SITE_LINE.exec(source);
1072
+ if (!site || !/^import /m.test(source)) return { action: "manual" };
1073
+ return {
1074
+ action: "link",
1075
+ source: afterLastImport(source.replace(SITE_LINE, (line) => `${line}\n${site[1] ?? " "}types: siteTypes,`), "import { siteTypes } from './types'")
1076
+ };
1077
+ }
1078
+ /** What the person does by hand when a file was left alone. */
1079
+ function manualSteps(index, model, id) {
1080
+ const lines = [];
1081
+ if (index === "manual") lines.push(`${TYPES_INDEX} is not shaped like the one this command writes, so it was left as it is. Add the type to it:`, "", ` ${importLine(id)}`, ` ${entryLine(id).trim()} (inside defineTypes({ ... }))`, "");
1082
+ if (model === "other") lines.push(`${CONTENT_MODEL_PATH} already declares types, so it was left as it is. Pass the ones in ${TYPES_DIR} too:`, "", " import { siteTypes } from './types'", " types: defineTypes({ ...siteTypes, /* the types declared here */ }),", "");
1083
+ if (model === "manual") lines.push(`${CONTENT_MODEL_PATH} is not shaped like the starter's, so it was left as it is. Pass the types to your content model:`, "", " import { siteTypes } from './types'", " types: siteTypes,", "");
1084
+ return lines;
1085
+ }
1086
+ /** What comes next once the type is declared. */
1087
+ function typeNextSteps(spec) {
1088
+ const label = spec.label ?? spec.id.charAt(0).toUpperCase() + spec.id.slice(1).replaceAll("-", " ");
1089
+ const lines = [`Next: start the site, open the editor, and find it under ${spec.kind === "single" ? `Pages > ${label}` : `Pages > ${label} > New entry`}.`];
1090
+ if (spec.kind === "multi" && spec.listing) lines.push(`Link to ${spec.path.replace("/{slug}", "")} from the header (Navigation tab) when there is something to read.`);
1091
+ if (spec.fields.some((field) => ![
1092
+ "date",
1093
+ "excerpt",
1094
+ "cover",
1095
+ "draft"
1096
+ ].includes(field.name)) && spec.kind === "multi" && spec.listing) lines.push("The listing shows each entry's title, date, excerpt and cover. For other fields, change src/components/organisms/EntryList.astro.");
1097
+ lines.push(`To change the type later, edit ${TYPES_DIR}/${spec.id}.ts. More: ${TYPES_GUIDE}`);
1098
+ return lines;
1099
+ }
1100
+ /** True when the flags say what the type is, so nothing about its shape is asked. */
1101
+ function hasShapeFlags(flags) {
1102
+ return [
1103
+ flags.kind,
1104
+ flags.path,
1105
+ flags.label,
1106
+ flags.sort,
1107
+ flags.listing
1108
+ ].some((value) => value !== void 0) || (flags.field?.length ?? 0) > 0;
1109
+ }
1110
+ const FIELD_FLAG = /^([^:?=]+)(\?)?:([a-z-]+)(?:=(.*))?$/;
1111
+ /** `date:date`, `excerpt?:long-text`, `level:choice=easy|medium|hard`. A `?` after the name makes the field optional. */
1112
+ function parseFieldFlag(text) {
1113
+ const match = FIELD_FLAG.exec(text.trim());
1114
+ if (!match) return `--field "${text}" should look like name:kind, name?:kind for an optional field, or name:choice=a|b|c.`;
1115
+ const [, name = "", optional, kind = "", rest] = match;
1116
+ if (!FIELD_KINDS.includes(kind)) return `--field "${text}": the kind must be one of ${FIELD_KINDS.join(", ")}.`;
1117
+ if (kind === "choice") {
1118
+ const choices = (rest ?? "").split("|").map((choice) => choice.trim());
1119
+ return normalizeField({
1120
+ name,
1121
+ kind,
1122
+ required: optional === void 0,
1123
+ choices
1124
+ });
1125
+ }
1126
+ if (rest !== void 0) return `--field "${text}": only a choice takes options after =.`;
1127
+ return normalizeField({
1128
+ name,
1129
+ kind,
1130
+ required: optional === void 0
1131
+ });
1132
+ }
1133
+ /** The type the flags describe. Missing flags take the defaults: entries, at /<id>/<slug>, with a listing page. */
1134
+ function specFromFlags(id, flags) {
1135
+ const kind = flags.kind ?? "multi";
1136
+ if (kind !== "multi" && kind !== "single") return "--kind must be multi (many entries) or single (one page).";
1137
+ const fields = [];
1138
+ for (const text of flags.field ?? []) {
1139
+ const field = parseFieldFlag(text);
1140
+ if (typeof field === "string") return field;
1141
+ fields.push(field);
1142
+ }
1143
+ const spec = {
1144
+ id,
1145
+ kind,
1146
+ path: flags.path === void 0 ? defaultPath(kind, id) : normalizePath(kind, flags.path),
1147
+ ...flags.label ? { label: flags.label } : {},
1148
+ fields,
1149
+ listing: false
1150
+ };
1151
+ if (kind === "single") {
1152
+ if (flags.sort !== void 0 || flags.listing !== void 0) return "A single has one page: --sort and --listing are for --kind multi.";
1153
+ return spec;
1154
+ }
1155
+ const listing = flags.listing ?? String(10);
1156
+ if (listing !== "none") {
1157
+ const perPage = Number(listing);
1158
+ if (!Number.isInteger(perPage)) return "--listing takes the number of entries on a listing page, or none.";
1159
+ spec.listing = { perPage };
1160
+ }
1161
+ if (flags.sort !== void 0) {
1162
+ const [by = "", order = "asc"] = flags.sort.split(":");
1163
+ if (order !== "asc" && order !== "desc") return "--sort takes a field and an order: date:desc, title:asc.";
1164
+ spec.sort = {
1165
+ by,
1166
+ order
1167
+ };
1168
+ }
1169
+ return spec;
1170
+ }
1171
+ /** Why `id` cannot be a new type of the site at `root`, or undefined. */
1172
+ function idProblem(root, id) {
1173
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id)) return `The type id "${id}" must be lowercase kebab-case: news, case-studies.`;
1174
+ const file = `${TYPES_DIR}/${id}.ts`;
1175
+ const problem = specProblem({
1176
+ id,
1177
+ kind: "single",
1178
+ path: `/${id}`,
1179
+ fields: [],
1180
+ listing: false
1181
+ });
1182
+ if (problem) return problem;
1183
+ if (fs.existsSync(path.join(root, file))) return `${file} already exists. Edit it to change that type.`;
1184
+ }
1185
+ /** Where pages are stored, as the starter keeps them. A site that moved its content keeps the check in `astro dev`. */
1186
+ const PAGES_STORE = "content/pages";
1187
+ /**
1188
+ * Why the type's address is already taken in the site at `root`, or undefined: by a page (`/about` and
1189
+ * `content/pages/about.json`), or by another type in src/lib/types. `astro dev` would stop on both.
1190
+ */
1191
+ function addressProblem(root, spec) {
1192
+ const segment = spec.path.split("/")[1] ?? "";
1193
+ const page = `${PAGES_STORE}/${segment}.json`;
1194
+ if (fs.existsSync(path.join(root, page))) return `/${segment} is already a page (${page}). Pick another address, or rename that page first.`;
1195
+ const dir = path.join(root, TYPES_DIR);
1196
+ if (!fs.existsSync(dir)) return void 0;
1197
+ for (const name of fs.readdirSync(dir)) {
1198
+ if (!name.endsWith(".ts") || name === "index.ts" || name === `${spec.id}.ts`) continue;
1199
+ if (/^\s*path:\s*'\/([a-z0-9-]+)/m.exec(fs.readFileSync(path.join(dir, name), "utf8"))?.[1] === segment) return `/${segment} is already the address of the type in ${TYPES_DIR}/${name}. Pick another address.`;
1200
+ }
1201
+ }
1202
+ /** Asks until `check` passes. An empty answer with no default gives up. */
1203
+ async function askUntil(io, question, initial, check) {
1204
+ const ask = io.ask;
1205
+ if (!ask) return void 0;
1206
+ for (;;) {
1207
+ const answer = (await ask(question, initial)).trim();
1208
+ if (answer === "") return void 0;
1209
+ const problem = check(answer);
1210
+ if (problem === void 0) return answer;
1211
+ io.log(problem);
1212
+ }
1213
+ }
1214
+ async function askField(io, taken) {
1215
+ const name = await askUntil(io, "Field name, camelCase (Enter to stop):", void 0, (answer) => fieldNameProblem(answer, taken));
1216
+ if (name === void 0 || !io.choose) return void 0;
1217
+ const kind = await io.choose(`What kind of field is ${name}?`, FIELD_KINDS.map((value) => ({
1218
+ value,
1219
+ label: FIELD_KIND_LABELS[value]
1220
+ })));
1221
+ if (kind === void 0) return void 0;
1222
+ let choices;
1223
+ if (kind === "choice") {
1224
+ const answer = await askUntil(io, "Its options, separated by commas:", void 0, (text) => {
1225
+ const list = text.split(",").map((choice) => choice.trim());
1226
+ if (list.some((choice) => choice === "")) return "An option is empty. Try again, like: draft, review, done.";
1227
+ return new Set(list).size === list.length ? void 0 : "An option is there twice.";
1228
+ });
1229
+ if (answer === void 0) return void 0;
1230
+ choices = answer.split(",").map((choice) => choice.trim());
1231
+ }
1232
+ const asked = normalizeField({
1233
+ name,
1234
+ kind,
1235
+ required: true
1236
+ });
1237
+ return normalizeField({
1238
+ name,
1239
+ kind,
1240
+ required: asked.kind === "switch" || asked.kind === "list" || asked.kind === "image" ? asked.required : io.confirm ? await io.confirm(`Must every entry have ${name}?`) : false,
1241
+ ...choices ? { choices } : {}
1242
+ });
1243
+ }
1244
+ /** Asks for the type in a terminal. Undefined when there is no terminal or the person stopped. */
1245
+ async function askSpec(io, root, givenId) {
1246
+ if (!io.ask || !io.confirm || !io.choose) return void 0;
1247
+ const id = givenId ?? await askUntil(io, "Type id, lowercase (news, case-studies):", void 0, (answer) => idProblem(root, answer));
1248
+ if (id === void 0) return void 0;
1249
+ const kind = await io.choose("What is it?", [{
1250
+ value: "multi",
1251
+ label: "Many entries, like posts, projects or events"
1252
+ }, {
1253
+ value: "single",
1254
+ label: "One page at a fixed address, like About, that nobody renames or deletes"
1255
+ }]) ?? "multi";
1256
+ const spec = {
1257
+ id,
1258
+ kind,
1259
+ path: normalizePath(kind, await askUntil(io, `Address, ${kind === "multi" ? "the start of each entry address" : "its address"}:`, defaultPath(kind, id), (answer) => {
1260
+ const candidate = {
1261
+ id,
1262
+ kind,
1263
+ path: normalizePath(kind, answer),
1264
+ fields: [],
1265
+ listing: false
1266
+ };
1267
+ return specProblem(candidate) ?? addressProblem(root, candidate);
1268
+ }) ?? defaultPath(kind, id)),
1269
+ fields: [],
1270
+ listing: false
1271
+ };
1272
+ io.log("Every entry already has a title, SEO and sections. Add the fields it needs besides those.");
1273
+ while (await io.confirm(spec.fields.length === 0 ? "Add a field?" : "Add another field?")) {
1274
+ const field = await askField(io, spec.fields.map((existing) => existing.name));
1275
+ if (field === void 0) break;
1276
+ spec.fields.push(field);
1277
+ }
1278
+ if (kind === "single") return spec;
1279
+ const prefix = spec.path.replace("/{slug}", "");
1280
+ if (await io.confirm(`A listing page at ${prefix}, with pages of entries?`)) {
1281
+ const perPage = await askUntil(io, "Entries on one listing page:", String(10), (answer) => /^\d+$/.test(answer) && Number(answer) >= 1 && Number(answer) <= 100 ? void 0 : "A whole number from 1 to 100.");
1282
+ spec.listing = { perPage: Number(perPage ?? 10) };
1283
+ }
1284
+ const sortable = spec.fields.filter(isSortable);
1285
+ if (sortable.length > 0) {
1286
+ const options = [{
1287
+ value: "title:asc",
1288
+ label: "Title, A to Z"
1289
+ }, ...sortable.flatMap((field) => field.kind === "date" ? [{
1290
+ value: `${field.name}:desc`,
1291
+ label: `${field.name}, newest first`
1292
+ }, {
1293
+ value: `${field.name}:asc`,
1294
+ label: `${field.name}, oldest first`
1295
+ }] : [{
1296
+ value: `${field.name}:asc`,
1297
+ label: `${field.name}, A to Z or lowest first`
1298
+ }, {
1299
+ value: `${field.name}:desc`,
1300
+ label: `${field.name}, Z to A or highest first`
1301
+ }])];
1302
+ const picked = await io.choose("Order entries by:", options);
1303
+ if (picked !== void 0 && picked !== "title:asc") {
1304
+ const [by = "title", order = "asc"] = picked.split(":");
1305
+ spec.sort = {
1306
+ by,
1307
+ order
1308
+ };
1309
+ }
1310
+ }
1311
+ return spec;
1312
+ }
1313
+ //#endregion
1314
+ //#region src/add/types.ts
1315
+ const CONFIG_FILES = [
1316
+ "astro.config.ts",
1317
+ "astro.config.mts",
1318
+ "astro.config.mjs",
1319
+ "astro.config.js"
1320
+ ];
1321
+ const TYPES_DOCS = "https://docs.bearminion.com/content-types/";
1322
+ function planTypes(root, registry, lock, overwrite) {
1323
+ const group = registry.groups?.types;
1324
+ if (group === void 0) throw new Error("This copy of bearminion has no content type files. Reinstall the package.");
1325
+ const files = [];
1326
+ for (const file of group.files) {
1327
+ const entry = registry.files[file];
1328
+ if (entry === void 0) throw new Error(`The registry lists ${file} for content types but holds no copy of it.`);
1329
+ const target = path.join(root, file);
1330
+ let action;
1331
+ if (!fs.existsSync(target)) action = "create";
1332
+ else {
1333
+ const hash = hashContent(file, fs.readFileSync(target));
1334
+ if (hash === entry.hash) action = "same";
1335
+ else if (entry.history.includes(hash) || lock.files[file]?.hash === hash) action = "update";
1336
+ else action = overwrite ? "overwrite" : "conflict";
1337
+ }
1338
+ files.push({
1339
+ path: file,
1340
+ action
1341
+ });
1342
+ }
1343
+ const notes = [];
1344
+ const config = CONFIG_FILES.find((name) => fs.existsSync(path.join(root, name)));
1345
+ if (config !== void 0 && !fs.readFileSync(path.join(root, config), "utf8").includes("siteRoutes")) notes.push(`${config} is yours and was not changed. It filters the sitemap by the site's pages only, so entries and listing pages would be left out of it. Pass the routes instead: ${TYPES_DOCS}#the-sitemap`);
1346
+ return {
1347
+ files,
1348
+ dirty: [],
1349
+ notes
1350
+ };
1351
+ }
1352
+ const writesTypes = (action) => action === "create" || action === "update" || action === "overwrite";
1353
+ /** Writes what the plan says and notes the files in the lock. Returns the paths written. A plan with conflicts is never applied. */
1354
+ function applyTypes(root, registryDir, registry, plan, lock) {
1355
+ if (plan.files.some((file) => file.action === "conflict")) throw new Error("The plan has conflicts. Nothing was written.");
1356
+ const written = [];
1357
+ for (const file of plan.files) {
1358
+ if (!writesTypes(file.action)) continue;
1359
+ const target = path.join(root, file.path);
1360
+ fs.mkdirSync(path.dirname(target), { recursive: true });
1361
+ fs.copyFileSync(path.join(registryDir, "files", file.path), target);
1362
+ written.push(file.path);
1363
+ }
1364
+ return {
1365
+ written,
1366
+ lock: recordFiles(lock, registry, plan.files.map((file) => file.path))
1367
+ };
1368
+ }
1369
+ /** What is left for the person to do: declaring a type. */
1370
+ function nextSteps() {
1371
+ return [
1372
+ "The site can now publish content types. To declare one, run:",
1373
+ "",
1374
+ " npx bearminion add type",
1375
+ "",
1376
+ `It asks what the type is and writes it to src/lib/types. More: ${TYPES_DOCS}`
1377
+ ];
1378
+ }
1379
+ //#endregion
793
1380
  //#region src/add/status.ts
794
1381
  /** Decides the state of one file from its hash in the site, in the release, and in the lock. */
795
1382
  function classify(siteHash, release, lockHash) {
@@ -854,6 +1441,9 @@ Usage
854
1441
  npx bearminion add --list
855
1442
  npx bearminion add form [<service>] [--host <host>]
856
1443
  npx bearminion add hosted [--host vercel]
1444
+ npx bearminion add type [<id>] [--kind multi|single] [--field name:kind ...]
1445
+ npx bearminion add type --files-only
1446
+ npx bearminion add blog
857
1447
  npx bearminion status [--json]
858
1448
  npx bearminion check form [--host <host>] [--json]
859
1449
  npx bearminion sync [options]
@@ -861,6 +1451,9 @@ Usage
861
1451
  Commands
862
1452
  add Copy sections into this site, with the files they need
863
1453
  add hosted Set the site up for the hosted editor: the starter files it needs, the editor module, and a build for the editor deployment
1454
+ add type Declare a content type: posts, projects, an About page. Asks what it is in a terminal, or takes flags.
1455
+ First brings the site's own files up to the ones that publish types (a site made before 1.21 needs that)
1456
+ add blog add type with a ready blog: posts at /blog/<slug> with a date, excerpt, cover and draft switch, newest first
864
1457
  status Show which sections are in this site and whether their files match this release
865
1458
  check form Look for what keeps the Contact form from working: missing files, wrong names, unset variables
866
1459
  sync Rewrite sections/definitions.gen.ts and components.gen.ts from the section directories
@@ -882,6 +1475,20 @@ Options for add hosted
882
1475
  --host <host> Where the editor deployment runs. Only vercel so far (the default)
883
1476
  --dry-run, -y, --overwrite, --install, --json, --diff work as for sections
884
1477
 
1478
+ Options for add type
1479
+ --kind <kind> multi (many entries, the default) or single (one page at a fixed address)
1480
+ --path <path> /news/{slug} for entries, /about for a single. Default: from the id
1481
+ --label <text> The name the editor shows. Default: from the id
1482
+ --field <field> A field, once per field: name:kind, name?:kind when optional, name:choice=a|b|c
1483
+ Kinds: text, long-text, date, number, switch, choice, image, list
1484
+ --sort <field> The order of entries: date:desc, title:asc (the default)
1485
+ --listing <n> Entries on one listing page (default 10), or none for no listing page
1486
+ --files-only Only bring the site's files up to date, and declare nothing: for types you declare by hand
1487
+ Without --kind, --path, --label, --field, --sort or --listing, a terminal asks instead
1488
+
1489
+ Options for add type and add blog
1490
+ --dry-run, -y, --overwrite, --json, --diff work as for sections
1491
+
885
1492
  Options for check form
886
1493
  --host <host> Where the site runs (found from the project when omitted)
887
1494
  --json Print one JSON document instead of text
@@ -965,6 +1572,19 @@ function parse(argv) {
965
1572
  default: false
966
1573
  },
967
1574
  host: { type: "string" },
1575
+ kind: { type: "string" },
1576
+ path: { type: "string" },
1577
+ label: { type: "string" },
1578
+ field: {
1579
+ type: "string",
1580
+ multiple: true
1581
+ },
1582
+ sort: { type: "string" },
1583
+ listing: { type: "string" },
1584
+ "files-only": {
1585
+ type: "boolean",
1586
+ default: false
1587
+ },
968
1588
  help: {
969
1589
  type: "boolean",
970
1590
  short: "h",
@@ -1034,6 +1654,8 @@ function diffAgainstRelease(root, registryDir, file) {
1034
1654
  async function runAdd(root, names, values, io) {
1035
1655
  if (names[0] === "form") return runAddForm(root, names.slice(1), values, io);
1036
1656
  if (names[0] === "hosted") return runAddHosted(root, names.slice(1), values, io);
1657
+ if (names[0] === "type") return runAddTypes(root, names.slice(1), values, io, values["files-only"] ? "files" : "type");
1658
+ if (names[0] === "blog") return runAddTypes(root, names.slice(1), values, io, "blog");
1037
1659
  const { log } = io;
1038
1660
  const json = values.json === true;
1039
1661
  const fail = (message, code = 1, extra = {}) => {
@@ -1305,6 +1927,246 @@ async function runAddHosted(root, names, values, io) {
1305
1927
  for (const line of checklist(plan.packageManager, plan.base)) log(line);
1306
1928
  return installed === "failed" ? 1 : 0;
1307
1929
  }
1930
+ function planDeclaration(root, spec) {
1931
+ const typeFile = `${TYPES_DIR}/${spec.id}.ts`;
1932
+ if (fs.existsSync(path.join(root, typeFile))) return `${typeFile} already exists. Edit it to change that type.`;
1933
+ const writes = [{
1934
+ path: typeFile,
1935
+ action: "create",
1936
+ source: typeFileSource(spec),
1937
+ note: describeSpec(spec)
1938
+ }];
1939
+ const indexFile = path.join(root, TYPES_INDEX);
1940
+ let indexAction = "create";
1941
+ if (fs.existsSync(indexFile)) {
1942
+ const edit = registerType(fs.readFileSync(indexFile, "utf8"), spec.id);
1943
+ indexAction = edit.action;
1944
+ if (edit.action === "update") writes.push({
1945
+ path: TYPES_INDEX,
1946
+ action: "update",
1947
+ source: edit.source,
1948
+ note: `adds ${spec.id} to siteTypes`
1949
+ });
1950
+ } else writes.push({
1951
+ path: TYPES_INDEX,
1952
+ action: "create",
1953
+ source: typesIndexSource(spec.id),
1954
+ note: "gathers the site's types in siteTypes"
1955
+ });
1956
+ const modelFile = path.join(root, CONTENT_MODEL_PATH);
1957
+ const model = fs.existsSync(modelFile) ? linkContentModel(fs.readFileSync(modelFile, "utf8")) : { action: "manual" };
1958
+ if (model.action === "link") writes.push({
1959
+ path: CONTENT_MODEL_PATH,
1960
+ action: "update",
1961
+ source: model.source,
1962
+ note: "passes siteTypes as types; the rest stays as it is"
1963
+ });
1964
+ return {
1965
+ spec,
1966
+ writes,
1967
+ manual: manualSteps(indexAction, model.action, spec.id)
1968
+ };
1969
+ }
1970
+ /** The type `add type` or `add blog` declares: the preset, the flags, the answers in a terminal, or a reason why not. */
1971
+ async function resolveSpec(root, names, values, io, mode) {
1972
+ if (mode === "blog") {
1973
+ if (names.length > 0 || hasShapeFlags(values)) return {
1974
+ error: "`add blog` takes no names or type options. For a blog of another shape: npx bearminion add type blog",
1975
+ code: 2
1976
+ };
1977
+ return PRESETS.blog;
1978
+ }
1979
+ if (names.length > 1) return {
1980
+ error: "`add type` declares one type at a time: npx bearminion add type news",
1981
+ code: 2
1982
+ };
1983
+ const id = names[0];
1984
+ if (id !== void 0) {
1985
+ const problem = idProblem(root, id);
1986
+ if (problem) return {
1987
+ error: problem,
1988
+ code: 2
1989
+ };
1990
+ }
1991
+ const interactive = io.ask !== void 0 && io.confirm !== void 0 && io.choose !== void 0 && values.json !== true;
1992
+ let spec;
1993
+ if (!hasShapeFlags(values) && interactive) {
1994
+ spec = await askSpec(io, root, id);
1995
+ if (spec === void 0) return {
1996
+ error: "Nothing was written.",
1997
+ code: 1
1998
+ };
1999
+ } else if (id === void 0) return {
2000
+ error: "Give the type an id, like npx bearminion add type news --field date:date, or run it in a terminal to be asked. See --help.",
2001
+ code: 2
2002
+ };
2003
+ else spec = specFromFlags(id, values);
2004
+ if (typeof spec === "string") return {
2005
+ error: spec,
2006
+ code: 2
2007
+ };
2008
+ const problem = specProblem(spec) ?? addressProblem(root, spec);
2009
+ return problem ? {
2010
+ error: problem,
2011
+ code: 2
2012
+ } : spec;
2013
+ }
2014
+ /**
2015
+ * `add type --files-only` brings the site's own files up to the ones that publish content types. `add type` does that, then
2016
+ * declares one type: its file in src/lib/types, a line in the index, and `types: siteTypes` in the content model when
2017
+ * that file is shaped like the starter's. `add blog` is `add type` with the blog preset.
2018
+ */
2019
+ async function runAddTypes(root, names, values, io, mode) {
2020
+ const { log } = io;
2021
+ const json = values.json === true;
2022
+ const fail = (message, code = 1, extra = {}) => {
2023
+ log(json ? JSON.stringify({
2024
+ ok: false,
2025
+ error: message,
2026
+ ...extra
2027
+ }, null, 2) : message);
2028
+ return code;
2029
+ };
2030
+ let declaration;
2031
+ if (mode === "blog" && values["files-only"]) return fail("`add blog` declares the blog. For the files alone: npx bearminion add type --files-only", 2);
2032
+ if (mode === "files") {
2033
+ if (names.length > 0 || hasShapeFlags(values)) return fail("--files-only updates the files and declares nothing: leave out the id and the type options.", 2);
2034
+ } else {
2035
+ const spec = await resolveSpec(root, names, values, io, mode);
2036
+ if ("error" in spec) return fail(spec.error, spec.code);
2037
+ const planned = planDeclaration(root, spec);
2038
+ if (typeof planned === "string") return fail(planned);
2039
+ declaration = planned;
2040
+ }
2041
+ let loaded;
2042
+ let plan;
2043
+ let lock;
2044
+ try {
2045
+ loaded = loadRegistry(io.registryDir);
2046
+ lock = readLock(root, loaded.registry.template);
2047
+ plan = planTypes(root, loaded.registry, lock, values.overwrite === true);
2048
+ } catch (error) {
2049
+ return fail(error instanceof Error ? error.message : String(error));
2050
+ }
2051
+ const { registry, dir: registryDir } = loaded;
2052
+ plan.dirty = dirtyFiles(root, [...plan.files.filter((file) => file.action === "update" || file.action === "overwrite").map((file) => file.path), ...declaration?.writes.filter((write) => write.action === "update").map((write) => write.path) ?? []]);
2053
+ const conflicts = plan.files.filter((file) => file.action === "conflict");
2054
+ const changes = plan.files.filter((file) => file.action !== "same");
2055
+ const writes = plan.files.filter((file) => writesTypes(file.action)).length + (declaration?.writes.length ?? 0);
2056
+ const declared = declaration ? {
2057
+ id: declaration.spec.id,
2058
+ files: declaration.writes.map(({ path: file, action }) => ({
2059
+ path: file,
2060
+ action
2061
+ })),
2062
+ manual: declaration.manual
2063
+ } : void 0;
2064
+ const report = (extra) => JSON.stringify({
2065
+ ok: conflicts.length === 0,
2066
+ version: registry.version,
2067
+ files: plan.files,
2068
+ ...declared ? { declared } : {},
2069
+ notes: plan.notes,
2070
+ dirty: plan.dirty,
2071
+ ...extra
2072
+ }, null, 2);
2073
+ const after = () => {
2074
+ for (const note of plan.notes) log(note);
2075
+ log("");
2076
+ if (!declaration) {
2077
+ for (const line of nextSteps()) log(line);
2078
+ return;
2079
+ }
2080
+ for (const line of declaration.manual) log(line);
2081
+ for (const line of typeNextSteps(declaration.spec)) log(line);
2082
+ };
2083
+ if (!json) {
2084
+ const what = declaration ? `the ${declaration.spec.id} type` : "content types";
2085
+ log(`${values["dry-run"] ? "Would add" : "Adding"} ${what} (bearminion ${registry.version})`);
2086
+ log("");
2087
+ for (const file of changes) {
2088
+ const note = NOTES[file.action];
2089
+ log(` ${LABELS[file.action].padEnd(9)} ${file.path}${note ? ` (${note})` : ""}`);
2090
+ }
2091
+ for (const write of declaration?.writes ?? []) log(` ${write.action.padEnd(9)} ${write.path} (${write.note})`);
2092
+ const same = plan.files.length - changes.length;
2093
+ if (same > 0) log(` ${same} of the starter's file${same === 1 ? "" : "s"} already match.`);
2094
+ log("");
2095
+ }
2096
+ if (conflicts.length > 0) {
2097
+ if (values.diff && !json) for (const file of conflicts) {
2098
+ log(diffAgainstRelease(root, registryDir, file.path));
2099
+ log("");
2100
+ }
2101
+ if (json) log(report({
2102
+ error: "Some files differ from this release and were changed by you.",
2103
+ written: []
2104
+ }));
2105
+ else {
2106
+ log(`${conflicts.length} file${conflicts.length === 1 ? "" : "s"} differ${conflicts.length === 1 ? "s" : ""} from this release because you changed ${conflicts.length === 1 ? "it" : "them"}. Nothing was written.`);
2107
+ log("Use --diff to see how, then merge the lines by hand, or use --overwrite to replace them. Commit first: git keeps your version.");
2108
+ }
2109
+ return 1;
2110
+ }
2111
+ if (writes === 0) {
2112
+ if (json) log(report({ written: [] }));
2113
+ else {
2114
+ log("Nothing to write: every file is already in place.");
2115
+ after();
2116
+ }
2117
+ return 0;
2118
+ }
2119
+ if (!json && plan.files.some((file) => file.action === "update")) log("The starter's files that you did not change are replaced by this release. Read the diff and run your build.");
2120
+ if (!json && plan.dirty.length > 0) log(`Uncommitted changes in ${plan.dirty.join(", ")} will be overwritten.`);
2121
+ if (values["dry-run"]) {
2122
+ if (json) log(report({
2123
+ dryRun: true,
2124
+ written: []
2125
+ }));
2126
+ else {
2127
+ if (declaration) {
2128
+ log(`${declaration.writes[0]?.path}:`);
2129
+ log("");
2130
+ for (const line of (declaration.writes[0]?.source ?? "").trimEnd().split("\n")) log(` ${line}`);
2131
+ log("");
2132
+ }
2133
+ for (const note of plan.notes) log(note);
2134
+ log("Dry run: nothing was written.");
2135
+ }
2136
+ return 0;
2137
+ }
2138
+ if (!values.yes) {
2139
+ if (json || io.confirm === void 0) return fail("Not asking in here: pass --yes to write, or --dry-run to look first.", 1, {
2140
+ files: plan.files,
2141
+ ...declared ? { declared } : {}
2142
+ });
2143
+ if (!await io.confirm(`Write ${writes} file${writes === 1 ? "" : "s"}?`)) {
2144
+ log("Nothing was written.");
2145
+ return 1;
2146
+ }
2147
+ }
2148
+ let written;
2149
+ try {
2150
+ const applied = applyTypes(root, registryDir, registry, plan, lock);
2151
+ writeLock(root, applied.lock);
2152
+ written = applied.written;
2153
+ for (const write of declaration?.writes ?? []) {
2154
+ const target = path.join(root, write.path);
2155
+ fs.mkdirSync(path.dirname(target), { recursive: true });
2156
+ fs.writeFileSync(target, write.source);
2157
+ written.push(write.path);
2158
+ }
2159
+ } catch (error) {
2160
+ return fail(error instanceof Error ? error.message : String(error));
2161
+ }
2162
+ if (json) {
2163
+ log(report({ written }));
2164
+ return 0;
2165
+ }
2166
+ log(`Wrote ${written.length} file${written.length === 1 ? "" : "s"}.`);
2167
+ after();
2168
+ return 0;
2169
+ }
1308
2170
  const LEVEL_TEXT = {
1309
2171
  ok: "ok",
1310
2172
  problem: "problem",
@@ -1445,10 +2307,23 @@ async function runAddForm(root, names, values, io) {
1445
2307
  } catch (error) {
1446
2308
  return fail(error instanceof Error ? error.message : String(error));
1447
2309
  }
1448
- const { registry } = loaded;
2310
+ const { registry, dir: registryDir } = loaded;
1449
2311
  const plan = planForm(root, handler, glue, values.overwrite === true);
1450
- const conflicts = plan.files.filter((file) => file.action === "conflict");
1451
- const changes = plan.files.filter((file) => file.action !== "same");
2312
+ const contact = findItem(registry, "contact");
2313
+ const sectionsDir = path.join(root, SECTIONS_PATH);
2314
+ const withSection = contact !== void 0 && !fs.existsSync(path.join(sectionsDir, contact.dir)) && fs.existsSync(path.join(sectionsDir, "definitions.gen.ts"));
2315
+ let sectionPlan;
2316
+ if (withSection && contact !== void 0) try {
2317
+ sectionPlan = planAdd(root, registry, [contact], {
2318
+ overwrite: values.overwrite,
2319
+ lock: readLock(root, registry.template)
2320
+ });
2321
+ } catch (error) {
2322
+ return fail(error instanceof Error ? error.message : String(error));
2323
+ }
2324
+ const sectionFiles = sectionPlan?.files ?? [];
2325
+ const conflicts = [...sectionFiles, ...plan.files].filter((file) => file.action === "conflict");
2326
+ const changes = [...sectionFiles.filter((file) => writesFile(file.action)), ...plan.files.filter((file) => file.action !== "same")];
1452
2327
  const report = (extra) => JSON.stringify({
1453
2328
  ok: conflicts.length === 0,
1454
2329
  version: registry.version,
@@ -1459,12 +2334,20 @@ async function runAddForm(root, names, values, io) {
1459
2334
  path: file,
1460
2335
  action
1461
2336
  })),
2337
+ ...sectionPlan ? { section: {
2338
+ name: "contact",
2339
+ files: sectionFiles.map(({ path: file, action }) => ({
2340
+ path: file,
2341
+ action
2342
+ }))
2343
+ } } : {},
1462
2344
  env: plan.env,
1463
2345
  ...extra
1464
2346
  }, null, 2);
1465
2347
  if (!json) {
1466
2348
  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}` : ""}`);
1467
2349
  log("");
2350
+ if (sectionPlan) log(" The Contact section, which this site does not have yet:");
1468
2351
  for (const file of changes) log(` ${LABELS[file.action].padEnd(9)} ${file.path}`);
1469
2352
  const same = plan.files.length - changes.length;
1470
2353
  if (same > 0) log(` ${same} file${same === 1 ? "" : "s"} already match the recipe.`);
@@ -1504,9 +2387,10 @@ async function runAddForm(root, names, values, io) {
1504
2387
  }
1505
2388
  let written;
1506
2389
  try {
2390
+ const sectionWritten = sectionPlan ? applyPlan(root, registryDir, registry, sectionPlan) : [];
1507
2391
  const applied = applyForm(root, plan, registry.version, readLock(root, registry.template));
1508
2392
  writeLock(root, applied.lock);
1509
- written = applied.written;
2393
+ written = [...sectionWritten, ...applied.written];
1510
2394
  } catch (error) {
1511
2395
  return fail(error instanceof Error ? error.message : String(error));
1512
2396
  }
@@ -1515,6 +2399,7 @@ async function runAddForm(root, names, values, io) {
1515
2399
  return 0;
1516
2400
  }
1517
2401
  log(`Wrote ${written.length} file${written.length === 1 ? "" : "s"} and noted them in bearminion.lock.json.`);
2402
+ if (sectionPlan) log("Add the Contact section to a page in the editor: Add section, Contact.");
1518
2403
  if (plan.env.length > 0) {
1519
2404
  log(`Set ${plan.env.join(", ")} in your host's settings, and in .env for \`astro dev\`.`);
1520
2405
  if (plan.env.includes("CONTACT_FROM")) log("CONTACT_FROM has to be an address on a domain you verified with Resend; CONTACT_TO is where the messages arrive. Until both are set the form refuses to send.");
@@ -1530,6 +2415,19 @@ async function runAddForm(root, names, values, io) {
1530
2415
  //#region src/cli.ts
1531
2416
  /** `npx bearminion`. The registry sits next to `dist/` in the installed package. */
1532
2417
  const registryDir = fileURLToPath(new URL("../registry/default", import.meta.url));
2418
+ /** A line of text; Enter keeps `initial`, shown in brackets. */
2419
+ async function ask(question, initial) {
2420
+ const rl = createInterface({
2421
+ input: process.stdin,
2422
+ output: process.stdout
2423
+ });
2424
+ try {
2425
+ const answer = (await rl.question(initial ? `${question} [${initial}] ` : `${question} `)).trim();
2426
+ return answer === "" ? initial ?? "" : answer;
2427
+ } finally {
2428
+ rl.close();
2429
+ }
2430
+ }
1533
2431
  async function confirm(question) {
1534
2432
  const rl = createInterface({
1535
2433
  input: process.stdin,
@@ -1559,6 +2457,7 @@ async function choose(question, options) {
1559
2457
  process.exitCode = await run(process.argv.slice(2), {
1560
2458
  registryDir,
1561
2459
  ...process.stdin.isTTY ? {
2460
+ ask,
1562
2461
  confirm,
1563
2462
  choose
1564
2463
  } : {}