astronaut-cms 0.0.1 → 1.1.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 (120) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +84 -3
  3. package/dist/admin/THIRD_PARTY_LICENSES.md +7646 -0
  4. package/dist/admin/assets/assistant-DTlSNidc.js +235 -0
  5. package/dist/admin/assets/badge-BfN73-be.js +1 -0
  6. package/dist/admin/assets/changes-h1lmD7AA.js +1 -0
  7. package/dist/admin/assets/client-B4PWCmC4.js +5 -0
  8. package/dist/admin/assets/clsx-DB0hHKMi.js +1 -0
  9. package/dist/admin/assets/collapsible-item-zlnNAUdM.js +1 -0
  10. package/dist/admin/assets/collapsible-mcJ6G3X4.js +1 -0
  11. package/dist/admin/assets/collections._collection-D-rC9E9v.js +1 -0
  12. package/dist/admin/assets/collections._collection._entry-UD8hLmC1.js +52 -0
  13. package/dist/admin/assets/collections._collection.index-Cgc93hCD.js +1 -0
  14. package/dist/admin/assets/component-lookup-8lVQh8pl.js +4 -0
  15. package/dist/admin/assets/config-Pm_BHLNT.js +1 -0
  16. package/dist/admin/assets/copy-DxuErr3x.js +1 -0
  17. package/dist/admin/assets/css-BGIxQoYs.js +1 -0
  18. package/dist/admin/assets/css-DgaLhXQH.js +1 -0
  19. package/dist/admin/assets/diff-woXpYk--.js +1 -0
  20. package/dist/admin/assets/dist-DVv3ALC7.js +1 -0
  21. package/dist/admin/assets/dist-Dpyc1riS.js +1 -0
  22. package/dist/admin/assets/docx-BctAmX91.js +56 -0
  23. package/dist/admin/assets/editor-BauN0yXd.js +2 -0
  24. package/dist/admin/assets/empty-DAOUBpWb.js +1 -0
  25. package/dist/admin/assets/entry-link-DhcL6M5c.js +158 -0
  26. package/dist/admin/assets/error-banner-CNWZU5u_.js +161 -0
  27. package/dist/admin/assets/errors-DkJ5E_ak.js +1 -0
  28. package/dist/admin/assets/field-CbbZZGxO.js +41 -0
  29. package/dist/admin/assets/field-schema-CacrjSYw.js +1 -0
  30. package/dist/admin/assets/file-text-Ciz5Mr4S.js +1 -0
  31. package/dist/admin/assets/github-dark-C-LZuMrd.js +1 -0
  32. package/dist/admin/assets/github-light-EUqPIrTm.js +1 -0
  33. package/dist/admin/assets/highlighted-body-JLMTFACH-D1bycIV3.js +1 -0
  34. package/dist/admin/assets/html-CvFb5cGI.js +1 -0
  35. package/dist/admin/assets/javascript-BzbQS41l.js +1 -0
  36. package/dist/admin/assets/javascript-CpIGwZ_Y.js +1 -0
  37. package/dist/admin/assets/json-qhed-kSA.js +1 -0
  38. package/dist/admin/assets/jsx-Bz0zcwM4.js +1 -0
  39. package/dist/admin/assets/lib-CC_S4yjQ.js +21 -0
  40. package/dist/admin/assets/library-Da82FNwp.js +1 -0
  41. package/dist/admin/assets/list-skeleton-BXLP4Fak.js +1 -0
  42. package/dist/admin/assets/markdown-BYOwaDjH.js +1 -0
  43. package/dist/admin/assets/matchContext-BjW1F-Cq.js +2 -0
  44. package/dist/admin/assets/media-browser-DeKpWCUD.js +1 -0
  45. package/dist/admin/assets/media._library-DGnXJc0I.js +1 -0
  46. package/dist/admin/assets/mermaid-WFAXDIZX-CqFnahFh.js +1 -0
  47. package/dist/admin/assets/page-header-C2Uwa_yv.js +1 -0
  48. package/dist/admin/assets/pdf-BSEX-sd8.js +106 -0
  49. package/dist/admin/assets/python-gzcpVVnB.js +1 -0
  50. package/dist/admin/assets/react-CXnqG51l.js +1 -0
  51. package/dist/admin/assets/rolldown-runtime-BWaJ3C7D.js +1 -0
  52. package/dist/admin/assets/routes-Bx9rPcHA.js +1 -0
  53. package/dist/admin/assets/routes-D7tEdYGV.js +1 -0
  54. package/dist/admin/assets/save-actions-DrVgh3KH.js +32 -0
  55. package/dist/admin/assets/select-CMV39q80.js +1 -0
  56. package/dist/admin/assets/separator-C9bNKNSU.js +3 -0
  57. package/dist/admin/assets/shell-DBEiq06l.js +1 -0
  58. package/dist/admin/assets/shellscript-CLZ0U2zV.js +1 -0
  59. package/dist/admin/assets/skeleton-DTwTUSqm.js +1 -0
  60. package/dist/admin/assets/sql-CEbI0hMM.js +1 -0
  61. package/dist/admin/assets/syntax-DDPd1mQn.js +8 -0
  62. package/dist/admin/assets/toggle-B6ASf-kL.js +1 -0
  63. package/dist/admin/assets/toml-BPTmHmyx.js +1 -0
  64. package/dist/admin/assets/tsx-udAQXfEw.js +1 -0
  65. package/dist/admin/assets/typescript-bsJCZSQ-.js +1 -0
  66. package/dist/admin/assets/ui.module.css-BdAmwQeM.js +56 -0
  67. package/dist/admin/assets/use-entries-CrNqaMfa.js +1 -0
  68. package/dist/admin/assets/useSelector-Cs39W18m.js +1 -0
  69. package/dist/admin/assets/yaml-rwi0_p6S.js +1 -0
  70. package/dist/admin/assets/zwitch-Wwuax-dJ.js +1 -0
  71. package/dist/admin/bootstrap.d.ts +1 -0
  72. package/dist/admin/bootstrap.js +1 -0
  73. package/dist/admin/editor.d.ts +1065 -0
  74. package/dist/admin/editor.js +1 -0
  75. package/dist/server/THIRD_PARTY_LICENSES.md +49 -0
  76. package/dist/server/assets.d.ts +30 -0
  77. package/dist/server/assets.js +30 -0
  78. package/dist/server/chunks/anchors-DuZ1fokt.js +86 -0
  79. package/dist/server/chunks/auth-DJP9ryVd.js +44 -0
  80. package/dist/server/chunks/cms-markers-CUqrOnfA.js +78 -0
  81. package/dist/server/chunks/component-lookup-DAFg_Qg8.js +128 -0
  82. package/dist/server/chunks/config-BsOYly9a.d.ts +1210 -0
  83. package/dist/server/chunks/digest-tkKu_Wj5.js +753 -0
  84. package/dist/server/chunks/entry-checks-3SxhoHwH.js +608 -0
  85. package/dist/server/chunks/field-schema-CfdN75jT.js +48 -0
  86. package/dist/server/chunks/http-BnsNh57m.d.ts +35 -0
  87. package/dist/server/chunks/i18n-BPmx7ESy.d.ts +15 -0
  88. package/dist/server/chunks/index-CYbkNvu5.d.ts +22 -0
  89. package/dist/server/chunks/media-BhqUVVYY.js +223 -0
  90. package/dist/server/chunks/paths-CEW9fvg8.js +17 -0
  91. package/dist/server/chunks/paths-Dztx2eUw.js +13 -0
  92. package/dist/server/chunks/types-DkkewFTT.js +418 -0
  93. package/dist/server/chunks/types-Dkx4Xovf.d.ts +359 -0
  94. package/dist/server/chunks/types-Jew_-Qpp.d.ts +273 -0
  95. package/dist/server/chunks/user-config-CqNK-Ebs.js +292 -0
  96. package/dist/server/chunks/xml-D8qPILJU.js +81 -0
  97. package/dist/server/config.d.ts +3 -0
  98. package/dist/server/config.js +22 -0
  99. package/dist/server/content.d.ts +58 -0
  100. package/dist/server/content.js +83 -0
  101. package/dist/server/endpoint.d.ts +16 -0
  102. package/dist/server/endpoint.js +2726 -0
  103. package/dist/server/integration.d.ts +7 -0
  104. package/dist/server/integration.js +1187 -0
  105. package/dist/server/internal.d.ts +100 -0
  106. package/dist/server/internal.js +30 -0
  107. package/dist/server/server-local.d.ts +453 -0
  108. package/dist/server/server-local.js +336 -0
  109. package/dist/styles/THIRD_PARTY_LICENSES.md +193 -0
  110. package/dist/styles/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  111. package/dist/styles/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  112. package/dist/styles/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  113. package/dist/styles/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  114. package/dist/styles/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  115. package/dist/styles/styles.css +3 -0
  116. package/package.json +151 -5
  117. package/src/astro/Image.astro +28 -0
  118. package/src/astro/Video.astro +44 -0
  119. package/src/astro/admin.astro +137 -0
  120. package/src/astro/licenses.ts +5 -0
@@ -0,0 +1,608 @@
1
+ import { l as isLibraryFile } from "./media-BhqUVVYY.js";
2
+ import { c as isRequired, d as diagnostic, l as objectShape, s as isRecord } from "./field-schema-CfdN75jT.js";
3
+ import { a as collectionBase, c as globEntry, f as loaderPatterns, l as globEntryId } from "./types-DkkewFTT.js";
4
+ import { r as findComponent, t as childComponents } from "./component-lookup-DAFg_Qg8.js";
5
+ import { a as LINK_MESSAGE, c as containsLink, i as LINK_DESCRIPTION, l as isAllowedLink, n as anchorIds, o as PLAIN_TEXT_MESSAGE, r as checkAnchors, s as allowedLinks, t as ANCHOR_DESCRIPTION, u as isLinkLike } from "./anchors-DuZ1fokt.js";
6
+ import { z } from "zod";
7
+ import { fromMarkdown } from "mdast-util-from-markdown";
8
+ import GithubSlugger from "github-slugger";
9
+ import { mdxjs } from "micromark-extension-mdxjs";
10
+ import { mdxFromMarkdown } from "mdast-util-mdx";
11
+ import { parseExpressionAt } from "acorn";
12
+ // src/shared/errors.ts
13
+ /**
14
+ * What a thrown value says, or `fallback` when it is no error. `Error.isError`
15
+ * also recognizes an error from another realm, such as Vite's module runner.
16
+ */
17
+ var errorMessage = (err, fallback = String(err)) => Error.isError(err) ? err.message : fallback;
18
+ // src/shared/mdx-attributes.ts
19
+ /**
20
+ * Reading and writing the value of an MDX component prop.
21
+ *
22
+ * An attribute is either a string literal (`title="x"`) or a braced JavaScript
23
+ * expression (`title={'x'}`, `items={['a', 'b']}`). The second form is ordinary
24
+ * JS, not JSON. Single quotes, unquoted keys and trailing commas are all valid,
25
+ * so it is parsed as such. Everything that reads a prop goes through here: the
26
+ * schema-driven walk that validates a body and collects its assets, and the prop
27
+ * editor in the admin, so the two cannot disagree about what a body says.
28
+ *
29
+ * Only literal data is evaluated. An expression that needs a runtime, such as
30
+ * an identifier, a call or a template with substitutions,
31
+ * is reported as unknown, which is what lets a caller leave it unchecked instead of guessing.
32
+ */
33
+ var UNKNOWN$1 = { known: false };
34
+ /** What an attribute is worth, with a bare `<C flag />` reading as `true`. */
35
+ function attributeValue(attr) {
36
+ const value = attr.value;
37
+ if (value === null || value === void 0) return {
38
+ known: true,
39
+ value: true
40
+ };
41
+ if (typeof value === "string") return {
42
+ known: true,
43
+ value
44
+ };
45
+ try {
46
+ return evaluate(parseExpressionAt(value.value, 0, { ecmaVersion: "latest" }));
47
+ } catch {
48
+ return UNKNOWN$1;
49
+ }
50
+ }
51
+ function evaluate(node) {
52
+ switch (node.type) {
53
+ case "Literal": return node.value instanceof RegExp ? UNKNOWN$1 : {
54
+ known: true,
55
+ value: node.value
56
+ };
57
+ case "UnaryExpression": {
58
+ const argument = evaluate(node.argument);
59
+ if (!argument.known) return UNKNOWN$1;
60
+ if (node.operator === "-") return {
61
+ known: true,
62
+ value: -argument.value
63
+ };
64
+ if (node.operator === "!") return {
65
+ known: true,
66
+ value: !argument.value
67
+ };
68
+ return UNKNOWN$1;
69
+ }
70
+ case "TemplateLiteral": return node.expressions.length === 0 ? {
71
+ known: true,
72
+ value: node.quasis[0]?.value.cooked
73
+ } : UNKNOWN$1;
74
+ case "ArrayExpression": {
75
+ const items = [];
76
+ for (const element of node.elements) {
77
+ if (!element || element.type === "SpreadElement") return UNKNOWN$1;
78
+ const item = evaluate(element);
79
+ if (!item.known) return UNKNOWN$1;
80
+ items.push(item.value);
81
+ }
82
+ return {
83
+ known: true,
84
+ value: items
85
+ };
86
+ }
87
+ case "ObjectExpression": {
88
+ const object = {};
89
+ for (const property of node.properties) {
90
+ if (property.type !== "Property" || property.computed) return UNKNOWN$1;
91
+ const key = propertyKey(property);
92
+ const item = evaluate(property.value);
93
+ if (key === null || !item.known) return UNKNOWN$1;
94
+ object[key] = item.value;
95
+ }
96
+ return {
97
+ known: true,
98
+ value: object
99
+ };
100
+ }
101
+ default: return UNKNOWN$1;
102
+ }
103
+ }
104
+ function propertyKey(property) {
105
+ if (property.key.type === "Identifier") return property.key.name;
106
+ if (property.key.type === "Literal") return String(property.key.value);
107
+ return null;
108
+ }
109
+ // src/shared/field-to-zod.ts
110
+ var EMAIL = z.email();
111
+ var UNKNOWN = z.unknown().refine((value) => !containsLink(value), PLAIN_TEXT_MESSAGE);
112
+ /**
113
+ * Rebuilds a live Zod validator from a serialized {@link FieldSchema}, the inverse
114
+ * of `zodToFieldSchema`. The integration lowers each collection's schema in Node
115
+ * and ships it in the manifest; here the browser reconstructs the schema so the
116
+ * per-collection entry tools expose the real content model to the model as JSON
117
+ * Schema and validate the agent's writes natively.
118
+ *
119
+ * Details the lowering could not capture (refinements, transforms) collapse to
120
+ * their base type, so the reconstruction is a faithful view of the original
121
+ * schema, stricter only by the link policy of `links.ts` that every string is
122
+ * held to, and by a `localized()` value taking no language the site lacks.
123
+ */
124
+ function base(field) {
125
+ switch (field.type) {
126
+ case "string": {
127
+ let s = field.format === "url" ? z.url() : z.string();
128
+ if (typeof field.minLength === "number") s = s.min(field.minLength);
129
+ if (typeof field.maxLength === "number") s = s.max(field.maxLength);
130
+ if (field.pattern) s = s.regex(new RegExp(field.pattern));
131
+ if (field.format === "email") return s.refine((value) => EMAIL.safeParse(value).success, "Expected an email address.").describe("Email address.");
132
+ if (field.format === "url") return allowedLinks(s);
133
+ if (field.format === "link") return allowedLinks(s).describe(LINK_DESCRIPTION);
134
+ const text = s.refine((value) => !isLinkLike(value), PLAIN_TEXT_MESSAGE);
135
+ return field.format === "anchor" ? anchorIds(text).describe(ANCHOR_DESCRIPTION) : text;
136
+ }
137
+ case "number": {
138
+ let n = field.integer ? z.int() : z.number();
139
+ if (typeof field.min === "number") n = n.min(field.min);
140
+ if (typeof field.max === "number") n = n.max(field.max);
141
+ if (typeof field.exclusiveMin === "number") n = n.gt(field.exclusiveMin);
142
+ if (typeof field.exclusiveMax === "number") n = n.lt(field.exclusiveMax);
143
+ if (typeof field.multipleOf === "number") n = n.multipleOf(field.multipleOf);
144
+ return n;
145
+ }
146
+ case "boolean": return z.boolean();
147
+ case "date": return z.string().refine((value) => !Number.isNaN(Date.parse(value)), "Expected a date.").describe("ISO date, e.g. \"2026-01-31\".");
148
+ case "enum":
149
+ if (field.options.length === 0) return z.never();
150
+ if (field.options.every((option) => typeof option === "string")) return z.enum(field.options);
151
+ return z.literal(field.options);
152
+ case "literal": return z.literal(field.value);
153
+ case "image":
154
+ case "file": return z.string().describe(field.type === "image" && field.repoOnly ? "The `ref` of a repository media file, as listMedia reports it." : "The `ref` of a media file, as listMedia reports it.");
155
+ case "reference": return z.string().describe(`Id of an entry in the "${field.collection}" collection.`);
156
+ case "array": {
157
+ let a = z.array(fieldSchemaToZod(field.element));
158
+ if (typeof field.minItems === "number") a = a.min(field.minItems);
159
+ if (typeof field.maxItems === "number") a = a.max(field.maxItems);
160
+ return a;
161
+ }
162
+ case "tuple": return field.items.length ? z.tuple(field.items.map(fieldSchemaToZod)) : z.array(UNKNOWN);
163
+ case "object": {
164
+ const shape = {};
165
+ for (const [key, value] of Object.entries(field.shape)) shape[key] = fieldSchemaToZod(value);
166
+ return field.strict ? z.strictObject(shape) : z.object(shape);
167
+ }
168
+ case "record": return z.record(z.string(), fieldSchemaToZod(field.value));
169
+ case "union": {
170
+ const variants = field.variants.map(fieldSchemaToZod);
171
+ if (variants.length < 2) return variants[0] ?? z.unknown();
172
+ if (field.discriminator !== void 0) return z.discriminatedUnion(field.discriminator, variants);
173
+ return z.union(variants);
174
+ }
175
+ case "unknown": return UNKNOWN;
176
+ }
177
+ }
178
+ function withMeta(schema, { label, description }) {
179
+ const meta = {};
180
+ if (label !== void 0) meta.title = label;
181
+ if (description !== void 0) meta.description = [description, schema.description].filter(Boolean).join("\n");
182
+ return Object.keys(meta).length ? schema.meta(meta) : schema;
183
+ }
184
+ var cache = /* @__PURE__ */ new WeakMap();
185
+ /** Reconstructs a Zod schema for a single field, applying its modifier flags. */
186
+ function fieldSchemaToZod(field) {
187
+ const cached = cache.get(field);
188
+ if (cached) return cached;
189
+ let schema = withMeta(base(field), field);
190
+ if (field.nullable) schema = schema.nullable();
191
+ if (field.optional) schema = schema.optional();
192
+ if (field.default !== void 0) schema = schema.default(field.default);
193
+ if (field.catch) schema = schema.catch(void 0);
194
+ cache.set(field, schema);
195
+ return schema;
196
+ }
197
+ /**
198
+ * The variant of `schema` that `value` belongs to.
199
+ * A discriminated union is resolved by its tag alone,
200
+ * a plain union by the first variant that validates.
201
+ */
202
+ function activeVariant(schema, value) {
203
+ const { discriminator, variants } = schema;
204
+ if (discriminator) {
205
+ if (!isRecord(value)) return void 0;
206
+ return variants.find((variant) => {
207
+ const tag = variant.type === "object" ? variant.shape[discriminator] : void 0;
208
+ return tag !== void 0 && fieldSchemaToZod(tag).safeParse(value[discriminator]).success;
209
+ });
210
+ }
211
+ return variants.find((variant) => fieldSchemaToZod(variant).safeParse(value).success);
212
+ }
213
+ // src/shared/resolvable-leaves.ts
214
+ /** Whether a leaf names a file of a media library. */
215
+ var isAsset = (leaf) => leaf.kind === "image" || leaf.kind === "file";
216
+ function child(path, key) {
217
+ if (typeof key === "number") return `${path}[${key}]`;
218
+ return path ? `${path}.${key}` : key;
219
+ }
220
+ function collectResolvableLeaves(schema, value, path = "") {
221
+ if (value === null || value === void 0) return [];
222
+ switch (schema.type) {
223
+ case "reference": return typeof value === "string" && value !== "" ? [{
224
+ kind: "reference",
225
+ collection: schema.collection,
226
+ value,
227
+ path
228
+ }] : [];
229
+ case "image": return typeof value === "string" && value !== "" ? [{
230
+ kind: "image",
231
+ value,
232
+ path,
233
+ ...schema.repoOnly && { repoOnly: true }
234
+ }] : [];
235
+ case "file": return typeof value === "string" && value !== "" ? [{
236
+ kind: "file",
237
+ value,
238
+ path
239
+ }] : [];
240
+ case "string": return (schema.format === "link" || schema.format === "anchor") && typeof value === "string" && value !== "" ? [{
241
+ kind: schema.format,
242
+ value,
243
+ path
244
+ }] : [];
245
+ case "object": return isRecord(value) ? Object.entries(schema.shape).flatMap(([key, field]) => collectResolvableLeaves(field, value[key], child(path, key))) : [];
246
+ case "array": return Array.isArray(value) ? value.flatMap((item, i) => collectResolvableLeaves(schema.element, item, child(path, i))) : [];
247
+ case "tuple": return Array.isArray(value) ? schema.items.flatMap((field, i) => collectResolvableLeaves(field, value[i], child(path, i))) : [];
248
+ case "record": return isRecord(value) ? Object.entries(value).flatMap(([key, item]) => collectResolvableLeaves(schema.value, item, child(path, key))) : [];
249
+ case "union": {
250
+ const variant = activeVariant(schema, value);
251
+ return variant ? collectResolvableLeaves(variant, value, path) : [];
252
+ }
253
+ default: return [];
254
+ }
255
+ }
256
+ /**
257
+ * The assets and references an entry's data points at. A schema that is not an
258
+ * object holds no fields to walk, which is the only shape a collection's data
259
+ * can take.
260
+ */
261
+ function dataLeaves(schema, data) {
262
+ return schema?.type === "object" ? collectResolvableLeaves(schema, data) : [];
263
+ }
264
+ // src/shared/markdown-images.ts
265
+ /**
266
+ * The URLs a parsed body embeds as markdown images, inline (`![alt](url)`) or
267
+ * through a definition (`![alt][id]`). Read off the tree rather than matched, so
268
+ * an image in a code block is not one.
269
+ */
270
+ function imageUrls(tree) {
271
+ const urls = [];
272
+ const referenced = /* @__PURE__ */ new Set();
273
+ const definitions = /* @__PURE__ */ new Map();
274
+ const visit = (node) => {
275
+ if (node.type === "image") urls.push(node.url);
276
+ if (node.type === "imageReference") referenced.add(node.identifier);
277
+ if (node.type === "definition") definitions.set(node.identifier, node.url);
278
+ if ("children" in node) node.children.forEach(visit);
279
+ };
280
+ visit(tree);
281
+ return [...urls, ...referenced.values().flatMap((id) => definitions.get(id) ?? [])];
282
+ }
283
+ // src/shared/body-validation.ts
284
+ var HTML_ELEMENTS = /* @__PURE__ */ new Set(["div", "span"]);
285
+ var HTML_ATTRIBUTES = /* @__PURE__ */ new Set(["class"]);
286
+ function isComponentName(name) {
287
+ return /^[A-Z]/.test(name);
288
+ }
289
+ function textOf(node) {
290
+ if (node.type === "text" || node.type === "inlineCode") return node.value ?? "";
291
+ return (node.children ?? []).map(textOf).join("");
292
+ }
293
+ function markdownLeaf(ctx, node) {
294
+ switch (node.type) {
295
+ case "heading": {
296
+ const text = textOf(node);
297
+ return {
298
+ kind: "anchor",
299
+ value: ctx.slugger.slug(text),
300
+ path: `heading "${text}"`
301
+ };
302
+ }
303
+ case "link":
304
+ case "definition": return node.url ? {
305
+ kind: "link",
306
+ value: node.url,
307
+ path: "Markdown link"
308
+ } : null;
309
+ default: return null;
310
+ }
311
+ }
312
+ function nodeViolation(node) {
313
+ switch (node.type) {
314
+ case "mdxjsEsm": return "Imports and exports are not allowed, every component of cms.config is available by name.";
315
+ case "mdxFlowExpression":
316
+ case "mdxTextExpression": return node.data?.estree?.body.length === 0 ? null : "JavaScript expressions in braces are not allowed, only {/* comments */}.";
317
+ case "html": return "Raw HTML is not allowed, use a registered component instead.";
318
+ case "link":
319
+ case "image":
320
+ case "definition": return isAllowedLink(node.url ?? "") ? null : `The URL "${node.url}" is not allowed. ${LINK_MESSAGE}`;
321
+ default: return null;
322
+ }
323
+ }
324
+ function readAttributes(ctx, name, attributes) {
325
+ const values = /* @__PURE__ */ new Map();
326
+ for (const attr of attributes) {
327
+ if (attr.type === "mdxJsxExpressionAttribute") {
328
+ ctx.diagnostics.push(diagnostic(`<${name}> spreads props, which is not allowed.`));
329
+ continue;
330
+ }
331
+ const value = attributeValue(attr);
332
+ if (!value.known) ctx.diagnostics.push(diagnostic(`<${name}> prop "${attr.name}" must be a literal value, not an expression.`));
333
+ values.set(attr.name, value);
334
+ }
335
+ return values;
336
+ }
337
+ function validateHtml(ctx, name, values) {
338
+ if (!HTML_ELEMENTS.has(name)) {
339
+ ctx.diagnostics.push(diagnostic(`<${name}> is not allowed, only ${[...HTML_ELEMENTS].map((e) => `<${e}>`).join(", ")}. Use a registered component instead.`));
340
+ return;
341
+ }
342
+ for (const attr of new Set(values.keys()).difference(HTML_ATTRIBUTES)) ctx.diagnostics.push(diagnostic(`<${name}> attribute "${attr}" is not allowed, only ${[...HTML_ATTRIBUTES].join(", ")}.`));
343
+ }
344
+ function validateProps(ctx, name, def, values) {
345
+ const shape = objectShape(def.props) ?? {};
346
+ for (const [prop, field] of Object.entries(shape)) if (isRequired(field) && !values.has(prop)) ctx.diagnostics.push(diagnostic(`<${name}> is missing required prop "${prop}".`));
347
+ for (const [prop, attr] of values) {
348
+ const field = shape[prop];
349
+ if (!field) {
350
+ ctx.diagnostics.push(diagnostic(`<${name}> has an unknown prop "${prop}".`));
351
+ continue;
352
+ }
353
+ if (!attr.known) continue;
354
+ ctx.leaves.push(...collectResolvableLeaves(field, attr.value, `<${name}> prop "${prop}"`));
355
+ const result = fieldSchemaToZod(field).safeParse(attr.value);
356
+ if (!result.success) {
357
+ const reason = result.error.issues[0]?.message ?? "type mismatch";
358
+ ctx.diagnostics.push(diagnostic(`<${name}> prop "${prop}" is invalid: ${reason.endsWith(".") ? reason : `${reason}.`}`));
359
+ }
360
+ }
361
+ }
362
+ function allowedChildren(ctx, parent) {
363
+ return parent ? new Set(Object.keys(childComponents(parent.def, ctx.components))) : ctx.topLevel;
364
+ }
365
+ function placementMessage(name, parent, allowed) {
366
+ if (!parent) return `<${name}> is not a top-level component and cannot be used here.`;
367
+ const list = allowed.size ? `; allowed children: ${[...allowed].join(", ")}` : "";
368
+ return `<${name}> is not allowed inside <${parent.name}>${list}.`;
369
+ }
370
+ function walk(ctx, nodes, parent) {
371
+ const allowed = allowedChildren(ctx, parent);
372
+ for (const node of nodes) {
373
+ const violation = nodeViolation(node);
374
+ if (violation) ctx.diagnostics.push(diagnostic(violation));
375
+ const leaf = markdownLeaf(ctx, node);
376
+ if (leaf) ctx.leaves.push(leaf);
377
+ const name = node.type === "mdxJsxFlowElement" || node.type === "mdxJsxTextElement" ? node.name : null;
378
+ if (name) {
379
+ const values = readAttributes(ctx, name, node.attributes ?? []);
380
+ const def = findComponent(name, ctx.components);
381
+ if (def) {
382
+ if (!allowed.has(name)) ctx.diagnostics.push(diagnostic(placementMessage(name, parent, allowed)));
383
+ validateProps(ctx, name, def, values);
384
+ if (node.children) walk(ctx, node.children, {
385
+ name,
386
+ def
387
+ });
388
+ continue;
389
+ }
390
+ if (isComponentName(name)) ctx.diagnostics.push(diagnostic(`Unknown component <${name}>: it is not defined in this project.`));
391
+ else validateHtml(ctx, name, values);
392
+ }
393
+ if (node.children) walk(ctx, node.children, parent);
394
+ }
395
+ }
396
+ function parseBody(body, format) {
397
+ if (format === "mdx") return fromMarkdown(body, {
398
+ extensions: [mdxjs()],
399
+ mdastExtensions: [mdxFromMarkdown()]
400
+ });
401
+ return format === "md" || format === "mdoc" ? fromMarkdown(body) : null;
402
+ }
403
+ /**
404
+ * Validates an entry body against the subset the CMS allows: registered MDX
405
+ * components with well-typed props where their parent allows them, a few plain
406
+ * HTML wrappers, and links and images with a safe URL. The props that name
407
+ * another resource come back as {@link ResolvableLeaf}s for the caller to check.
408
+ * A data format has no body, so it yields nothing.
409
+ */
410
+ function validateBody(body, format, components) {
411
+ const empty = (diagnostics = []) => ({
412
+ diagnostics,
413
+ leaves: [],
414
+ images: []
415
+ });
416
+ let root;
417
+ try {
418
+ root = parseBody(body, format);
419
+ } catch (err) {
420
+ const message = errorMessage(err);
421
+ return empty([diagnostic(`Failed to parse the body: ${message}`)]);
422
+ }
423
+ if (!root) return empty();
424
+ const ctx = {
425
+ components,
426
+ topLevel: new Set(Object.keys(components)),
427
+ slugger: new GithubSlugger(),
428
+ diagnostics: [],
429
+ leaves: []
430
+ };
431
+ walk(ctx, root.children, null);
432
+ return {
433
+ diagnostics: ctx.diagnostics,
434
+ leaves: ctx.leaves,
435
+ images: imageUrls(root)
436
+ };
437
+ }
438
+ // src/shared/validation.ts
439
+ var ALLOWED_SEGMENT_CHARS = /^[\p{L}\p{M}\p{N}_-]+$/u;
440
+ /**
441
+ * Why a value is not an entry id, or null when it is one. A nested id may
442
+ * contain forward slashes ("sub/entry"), and each segment between them must
443
+ * contain only letters, digits, hyphens, and underscores.
444
+ */
445
+ function idIssue(value, nested = true) {
446
+ if (!value) return "empty";
447
+ if ((nested ? value.split("/") : [value]).every((segment) => ALLOWED_SEGMENT_CHARS.test(segment))) return null;
448
+ return nested ? "nestedCharacters" : "characters";
449
+ }
450
+ /**
451
+ * Validates a path that may contain forward slashes (e.g., nested entry IDs like "sub/entry").
452
+ * Rejects: empty segments, backslashes, "..", null bytes, special characters.
453
+ */
454
+ function validatePath(value, name) {
455
+ const issue = idIssue(value);
456
+ if (issue === "empty") throw new Error(`${name} must not be empty`);
457
+ if (issue) throw new Error(`Invalid ${name} "${value}": each path segment must contain only letters, digits, hyphens, and underscores`);
458
+ }
459
+ /**
460
+ * Why a value is not a media library path, or null when it is one. Unlike an
461
+ * entry id, a file name carries an extension and often a dot or a space, so
462
+ * this is a rejection list rather than an allowlist: no absolute path, no
463
+ * traversal, no backslash or control character, no empty segment.
464
+ */
465
+ function mediaPathIssue(value) {
466
+ if (!value) return "empty";
467
+ if (value.startsWith("/") || /\\|\p{Cc}/u.test(value)) return "absolute";
468
+ if (value.split("/").some((segment) => segment === "" || segment === "." || segment === "..")) return "segments";
469
+ return null;
470
+ }
471
+ /**
472
+ * Why a value is not a media library path, or null when it is one. It runs in
473
+ * the admin before a write and again in the media route before a key is built from it.
474
+ */
475
+ function mediaPathError(value, name = "media path") {
476
+ switch (mediaPathIssue(value)) {
477
+ case "empty": return `${name} must not be empty`;
478
+ case "absolute": return `Invalid ${name} "${value}": must be a relative path without backslashes`;
479
+ case "segments": return `Invalid ${name} "${value}": must not contain empty or traversing segments`;
480
+ case null: return null;
481
+ }
482
+ }
483
+ /** Why a path is not a file a media library admits, or null when it is one. */
484
+ function libraryPathError(path, extensions) {
485
+ return mediaPathError(path) ?? (isLibraryFile(path, extensions) ? null : `"${path}" is hidden or not of an allowed media type.`);
486
+ }
487
+ // src/shared/collection-schema.ts
488
+ /**
489
+ * Collection-shaped Zod schemas, built on the shared {@link fieldSchemaToZod}
490
+ * reconstruction: the full frontmatter schema for an overwrite, the all-optional
491
+ * one for a patch, and the small helpers the editor and the agent tools need
492
+ * around them.
493
+ */
494
+ /**
495
+ * The names a collection may be called, as a schema. The set is fixed at build
496
+ * time, so an unknown name is refused wherever one is accepted, at the server's
497
+ * operation boundary, where it used to resolve to the conventional directory for
498
+ * that name and quietly read somebody else's files, and in the tools an agent
499
+ * sees, where it is also the list of what exists.
500
+ *
501
+ * Takes the manifest rather than importing it, because this module is reached
502
+ * from the integration, which runs before the virtual module exists.
503
+ */
504
+ function collectionEnum(manifest) {
505
+ const names = Object.keys(manifest);
506
+ return names.length ? z.enum(names) : z.never();
507
+ }
508
+ function patchField(field) {
509
+ return fieldSchemaToZod({
510
+ ...field,
511
+ default: void 0
512
+ }).nullable().optional();
513
+ }
514
+ var UNTYPED_DATA = {
515
+ type: "record",
516
+ value: { type: "unknown" }
517
+ };
518
+ /**
519
+ * Full data/frontmatter schema for a collection, for a complete overwrite. Falls
520
+ * back to a free record, still link-checked, only when the collection declares
521
+ * no schema.
522
+ */
523
+ function collectionDataSchema(col) {
524
+ return fieldSchemaToZod(col.schema ?? UNTYPED_DATA);
525
+ }
526
+ /**
527
+ * Patch schema for a collection, for a partial update: every top-level field is
528
+ * optional and nullable. Falls back to a free record when the collection has no
529
+ * object schema to derive fields from.
530
+ */
531
+ function collectionPatchSchema(col) {
532
+ if (col.schema?.type === "object") {
533
+ const shape = {};
534
+ for (const [key, field] of Object.entries(col.schema.shape)) shape[key] = patchField(field);
535
+ return z.object(shape);
536
+ }
537
+ return fieldSchemaToZod(UNTYPED_DATA);
538
+ }
539
+ /**
540
+ * Recursively replaces `Date` instances with ISO strings, the form the parsers
541
+ * produce for every other format. Only TOML yields real dates, so an entry read
542
+ * back from storage has to be normalized before it can be checked against the
543
+ * reconstructed (string-based) schema.
544
+ */
545
+ function normalizeDates(value) {
546
+ if (value instanceof Date) return value.toISOString();
547
+ if (Array.isArray(value)) return value.map(normalizeDates);
548
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, v]) => [key, normalizeDates(v)]));
549
+ return value;
550
+ }
551
+ /**
552
+ * The data must satisfy the collection's own schema. Writing an entry that does
553
+ * not is the one CMS mistake the site cannot survive: Astro's content sync
554
+ * throws on it, and the full sync it runs at startup is uncaught, so the dev
555
+ * server exits and will not come back until the file is fixed by hand.
556
+ *
557
+ * The reconstructed schema is never stricter than the original (see
558
+ * `fieldSchemaToZod`) except for the link policy of `links.ts`, so this catches
559
+ * every structural violation while blocking nothing else the real schema would
560
+ * have accepted.
561
+ */
562
+ function validateAgainstSchema(col, data) {
563
+ const result = collectionDataSchema(col).safeParse(normalizeDates(data));
564
+ if (result.success) return [];
565
+ return result.error.issues.map((issue) => diagnostic(issue.message, issue.path.join(".") || void 0));
566
+ }
567
+ // src/shared/entry-checks.ts
568
+ /**
569
+ * The rules an entry has to satisfy that need nothing but the entry itself,
570
+ * shared by the build, which refuses what is on disk, and a save, which refuses
571
+ * what would be written, so that both hold content to the same rules.
572
+ */
573
+ /**
574
+ * A glob loader reads only the files its pattern matches, each under the id
575
+ * astro derives from it. A write anywhere else, or to a file astro names
576
+ * differently, adds an entry the site never sees under this id. A `slug` that
577
+ * renames the entry is refused too, since the CMS lists entries by their files
578
+ * without reading each and would know it under an id astro does not.
579
+ */
580
+ function checkLoaded(col, path, data, id) {
581
+ if (col.loaderType !== "glob") return [];
582
+ const loaded = globEntry(col, path);
583
+ if (!loaded) return [diagnostic(`The "${col.name}" collection loads only files matching "${loaderPatterns(col).join(", ")}" in "${collectionBase(col) || "."}", which "${path}" does not. Use an id and format the pattern matches.`)];
584
+ if (id !== void 0 && loaded.id !== id) return [diagnostic(`Astro names the file "${path}" "${loaded.id}" rather than "${id}". Use "${loaded.id}" as the id.`)];
585
+ if (!data.slug) return [];
586
+ const astroId = globEntryId(col, path, data);
587
+ return astroId === loaded.id ? [] : [diagnostic(`Its "slug" field makes astro name this entry "${astroId}" rather than "${loaded.id}". Remove the field or set it to "${loaded.id}".`)];
588
+ }
589
+ /**
590
+ * Every finding about an entry that its own content decides: data matching the
591
+ * collection's schema, a body within the allowed subset, every link to `#id`
592
+ * naming an anchor of the entry, and a file astro loads under its id. `id` is
593
+ * the one a save names the entry by, omitted for a file read from disk.
594
+ */
595
+ function checkEntry(col, entry) {
596
+ const { path, data, body, id } = entry;
597
+ const leaves = [...dataLeaves(col.schema, data), ...body?.leaves ?? []];
598
+ return {
599
+ diagnostics: [
600
+ ...checkLoaded(col, path, data, id),
601
+ ...validateAgainstSchema(col, data),
602
+ ...body?.diagnostics ?? [],
603
+ ...checkAnchors(leaves)
604
+ ],
605
+ leaves
606
+ };
607
+ }
608
+ export { libraryPathError as a, validateBody as c, activeVariant as d, errorMessage as f, collectionPatchSchema as i, dataLeaves as l, collectionDataSchema as n, mediaPathError as o, collectionEnum as r, validatePath as s, checkEntry as t, isAsset as u };
@@ -0,0 +1,48 @@
1
+ // src/shared/diagnostics.ts
2
+ var diagnostic = (message, path) => ({
3
+ message,
4
+ path
5
+ });
6
+ /** A diagnostic as one line, led by the path to the offending value. */
7
+ var formatDiagnostic = (d) => d.path ? `${d.path}: ${d.message}` : d.message;
8
+ function report(diagnostics) {
9
+ return `Validation failed:\n${diagnostics.map((d) => `- ${formatDiagnostic(d)}`).join("\n")}`;
10
+ }
11
+ /**
12
+ * Refusal of a write that would leave content the site cannot build. Distinct
13
+ * from an ordinary failure so callers can tell "this content is wrong" (worth
14
+ * reporting back for correction) from "the write did not go through".
15
+ */
16
+ var ContentValidationError = class extends Error {
17
+ diagnostics;
18
+ constructor(diagnostics) {
19
+ super(report(diagnostics));
20
+ this.name = "ContentValidationError";
21
+ this.diagnostics = diagnostics;
22
+ }
23
+ };
24
+ // src/shared/field-schema.ts
25
+ /**
26
+ * Whether a value has to be written for this field. Every modifier that supplies
27
+ * one of its own answers no: an absent optional, an explicit null, a `.default()`
28
+ * and a `.catch()` fallback all satisfy the real schema, so demanding a value
29
+ * would refuse content the site itself accepts.
30
+ */
31
+ function isRequired(field) {
32
+ return !field.optional && !field.nullable && field.default === void 0 && !field.catch;
33
+ }
34
+ /** A plain object, as opposed to an array, a date or a primitive. */
35
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date);
36
+ /** Returns the field map of an object schema, or `undefined` for any other type. */
37
+ function objectShape(schema) {
38
+ return schema?.type === "object" ? schema.shape : void 0;
39
+ }
40
+ /** `true` for an image from either library, `"repo"` for one from the repository alone. */
41
+ var CMS_IMAGE = "x-cms-image";
42
+ var CMS_FILE = "x-cms-file";
43
+ var CMS_REFERENCE = "x-cms-reference";
44
+ var CMS_LINK = "x-cms-link";
45
+ var CMS_ANCHOR = "x-cms-anchor";
46
+ /** Tags a record as one value per content language, see `localized()`. */
47
+ var CMS_LOCALIZED = "x-cms-localized";
48
+ export { CMS_LOCALIZED as a, isRequired as c, diagnostic as d, formatDiagnostic as f, CMS_LINK as i, objectShape as l, CMS_FILE as n, CMS_REFERENCE as o, CMS_IMAGE as r, isRecord as s, CMS_ANCHOR as t, ContentValidationError as u };
@@ -0,0 +1,35 @@
1
+ /**
2
+ * What every CMS-owned response and every CMS-owned request body has in common,
3
+ * so no injected route has to restate it.
4
+ */
5
+ /**
6
+ * Hardening headers carried by every response the CMS serves. `nosniff` keeps a
7
+ * body from being interpreted as something other than the type it declares, and
8
+ * `no-referrer` keeps repository, entry and media paths out of the `Referer` of
9
+ * everything the admin reaches. The cross-origin policies keep other sites from
10
+ * embedding what the CMS serves or holding a handle on the admin's window, which
11
+ * the admin needs neither of, since it opens nothing it talks back to.
12
+ *
13
+ * Deliberately no `Permissions-Policy`: WebMCP is gated by the `tools` feature,
14
+ * which is allowed for a document's own origin only while nothing says
15
+ * otherwise. Adding a policy here has to name `tools=(self)`, or the admin's
16
+ * tool registration starts failing with `NotAllowedError`.
17
+ */
18
+ declare const HARDENING_HEADERS: Record<string, string>;
19
+ /** One `bytes=` range as a request spells it, a suffix when `start` is absent. */
20
+ interface ByteRange {
21
+ start?: number;
22
+ end?: number;
23
+ }
24
+ /** How a range of a file is answered: 206 with its bytes, or 416 when none lie inside. */
25
+ interface PartialContent {
26
+ status: 206 | 416;
27
+ /** Absent only for a 416 relayed from a source that did not name the size. */
28
+ contentRange?: string;
29
+ /** Inclusive offsets of the bytes to send, absent for a 416. */
30
+ span?: {
31
+ start: number;
32
+ end: number;
33
+ };
34
+ }
35
+ export { HARDENING_HEADERS as n, PartialContent as r, ByteRange as t };