@micacms/astro 0.5.0 → 0.6.0-rc.2

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/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @micacms/astro
2
2
 
3
- > **Experimental.** Pre-1.0: the API and the content format can still change
4
- > without notice. Use it at your own risk.
3
+ > **Public.** From 1.0, semver covers this package. Pre-1.0: the API and the
4
+ > content format can still change in a minor release.
5
5
 
6
6
  Reads a Mica content repository as Astro Content Collections, through the
7
7
  Content Layer API — and publishes the content model for Mica to read back.
@@ -68,6 +68,17 @@ Astro hands a loader exactly what they require:
68
68
  loader watches its own directory and coalesces the burst of writes that saving
69
69
  one entry produces (`debounceMs`, 100 ms by default).
70
70
 
71
+ Image fields reach Astro as Astro images: a `media({ accept: "image" })` field
72
+ is `ImageMetadata`, optimised like Astro's own `image()`, and with `alt` it is
73
+ `{ src, alt }` — `<Image {...entry.data.cover} />` needs no helper. Other media
74
+ stay paths from the content root.
75
+
76
+ The loaders also check references: a relation to a missing entry, or a missing
77
+ file of a media field that is not an image, is a warning in the build log.
78
+ `strict: true` makes it fail the build. A missing image file always fails the
79
+ build, as with Astro's own `image()`. An entry in the other layout always fails the build, with the
80
+ files and `npx mica migrate-layout`.
81
+
71
82
  ## Mixing with your own collections
72
83
 
73
84
  The return value is a plain object:
@@ -97,7 +108,8 @@ collections. They ship with the package, so they match the installed version.
97
108
  ## Install
98
109
 
99
110
  ```bash
100
- npm install @micacms/astro
111
+ npm install @micacms/astro @micacms/core
101
112
  ```
102
113
 
103
- Astro 6 or 7 is a peer dependency. Requires Node 22.12 or newer. Licence: MIT.
114
+ Astro 7, `@micacms/core` and zod 4 are peer dependencies. npm installs zod. ESM only. Requires Node 24 or newer.
115
+ Licence: MIT.
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Image fields reach Astro through its own `image()`, which resolves a path
3
+ * against the entry's file, optimizes the image and gives `ImageMetadata`. A
4
+ * site then needs no helper: `<Image {...entry.data.cover} />`.
5
+ */
6
+ import type { FieldMap } from "@micacms/core";
7
+ /**
8
+ * Rewrites the paths of `media({ accept: "image" })` fields, which the reader
9
+ * gives from the content root, to paths from the entry's data file.
10
+ */
11
+ export declare function imagePathsFromEntry(fields: FieldMap, data: Record<string, unknown>, dataFile: string): Record<string, unknown>;
12
+ //# sourceMappingURL=images.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"images.d.ts","sourceRoot":"","sources":["../src/images.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAE9C;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,QAAQ,EAChB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7B,QAAQ,EAAE,MAAM,GACf,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CA0BzB"}
package/dist/images.js ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Image fields reach Astro through its own `image()`, which resolves a path
3
+ * against the entry's file, optimizes the image and gives `ImageMetadata`. A
4
+ * site then needs no helper: `<Image {...entry.data.cover} />`.
5
+ */
6
+ import { posix } from "node:path";
7
+ /**
8
+ * Rewrites the paths of `media({ accept: "image" })` fields, which the reader
9
+ * gives from the content root, to paths from the entry's data file.
10
+ */
11
+ export function imagePathsFromEntry(fields, data, dataFile) {
12
+ const from = posix.dirname(dataFile);
13
+ const relative = (path) => {
14
+ if (typeof path !== "string" || path === "")
15
+ return path;
16
+ const result = posix.relative(from, path);
17
+ return result.startsWith(".") ? result : `./${result}`;
18
+ };
19
+ const one = (value) => isRecord(value) ? { ...value, path: relative(value["path"]) } : relative(value);
20
+ const visit = (map, record) => {
21
+ const result = { ...record };
22
+ for (const [key, field] of Object.entries(map)) {
23
+ const value = record[key];
24
+ if (field.kind === "media" && field.accept === "image") {
25
+ result[key] = Array.isArray(value) ? value.map(one) : one(value);
26
+ }
27
+ else if (field.kind === "object" && isRecord(value)) {
28
+ result[key] = visit(field.fields, value);
29
+ }
30
+ else if (field.kind === "repeater" && Array.isArray(value)) {
31
+ result[key] = value.map((row) => (isRecord(row) ? visit(field.fields, row) : row));
32
+ }
33
+ }
34
+ return result;
35
+ };
36
+ return visit(fields, data);
37
+ }
38
+ function isRecord(value) {
39
+ return value !== null && typeof value === "object" && !Array.isArray(value);
40
+ }
41
+ //# sourceMappingURL=images.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"images.js","sourceRoot":"","sources":["../src/images.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAIlC;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CACjC,MAAgB,EAChB,IAA6B,EAC7B,QAAgB;IAEhB,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACrC,MAAM,QAAQ,GAAG,CAAC,IAAa,EAAW,EAAE;QAC1C,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,EAAE;YAAE,OAAO,IAAI,CAAC;QACzD,MAAM,MAAM,GAAG,KAAK,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QAC1C,OAAO,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,MAAM,EAAE,CAAC;IACzD,CAAC,CAAC;IACF,MAAM,GAAG,GAAG,CAAC,KAAc,EAAW,EAAE,CACtC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,QAAQ,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IAElF,MAAM,KAAK,GAAG,CAAC,GAAa,EAAE,MAA+B,EAA2B,EAAE;QACx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,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["/**\n * Image fields reach Astro through its own `image()`, which resolves a path\n * against the entry's file, optimizes the image and gives `ImageMetadata`. A\n * site then needs no helper: `<Image {...entry.data.cover} />`.\n */\n\nimport { posix } from \"node:path\";\n\nimport type { FieldMap } from \"@micacms/core\";\n\n/**\n * Rewrites the paths of `media({ accept: \"image\" })` fields, which the reader\n * gives from the content root, to paths from the entry's data file.\n */\nexport function imagePathsFromEntry(\n fields: FieldMap,\n data: Record<string, unknown>,\n dataFile: string,\n): Record<string, unknown> {\n const from = posix.dirname(dataFile);\n const relative = (path: unknown): unknown => {\n if (typeof path !== \"string\" || path === \"\") return path;\n const result = posix.relative(from, path);\n return result.startsWith(\".\") ? result : `./${result}`;\n };\n const one = (value: unknown): unknown =>\n isRecord(value) ? { ...value, path: relative(value[\"path\"]) } : relative(value);\n\n const visit = (map: FieldMap, record: Record<string, unknown>): Record<string, unknown> => {\n const result = { ...record };\n for (const [key, field] of Object.entries(map)) {\n const value = record[key];\n if (field.kind === \"media\" && field.accept === \"image\") {\n result[key] = Array.isArray(value) ? value.map(one) : one(value);\n } else if (field.kind === \"object\" && isRecord(value)) {\n result[key] = visit(field.fields, value);\n } else if (field.kind === \"repeater\" && Array.isArray(value)) {\n result[key] = value.map((row) => (isRecord(row) ? visit(field.fields, row) : row));\n }\n }\n return result;\n };\n\n return visit(fields, data);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -16,6 +16,7 @@
16
16
  * Publishing is a commit, and CI builds the commit.
17
17
  */
18
18
  import { type ContentSource, type InferCollection, type InferSingleton, type Site } from "@micacms/core";
19
+ import type { ImageMetadata } from "astro";
19
20
  import { z } from "zod";
20
21
  import { DEFAULT_CONTENT_ROOT, resolveContentRoot } from "./root.js";
21
22
  export interface MicaCollectionsOptions {
@@ -45,6 +46,12 @@ export interface MicaCollectionsOptions {
45
46
  * after the burst is both faster and less confusing than one per file.
46
47
  */
47
48
  debounceMs?: number;
49
+ /**
50
+ * Fails the build on a relation to a missing entry or a missing media file.
51
+ * Without it, the build logs a warning for each and goes on; a missing image
52
+ * file fails the build either way, because Astro cannot import it.
53
+ */
54
+ strict?: boolean;
48
55
  }
49
56
  /**
50
57
  * Entry metadata attached to every collection document.
@@ -80,12 +87,15 @@ export interface AstroCollectionConfig<T = unknown> {
80
87
  type: "content_layer";
81
88
  loader: ContentLoader;
82
89
  /**
83
- * Typed as `ZodType<T>` rather than a bare `ZodObject`, because Astro derives
84
- * `CollectionEntry<"projects">["data"]` from `z.infer` of whatever this is.
85
- * Left generic, every field in every template would degrade to `any` — and
86
- * the point of the shared model is that renaming a field breaks the build.
90
+ * A function, so that Astro hands in its `image()`. Its result is typed as
91
+ * `ZodType<T>` because Astro derives `CollectionEntry<"projects">["data"]`
92
+ * from it: left generic, every field in every template would degrade to
93
+ * `any`, and the point of the shared model is that renaming a field breaks
94
+ * the build.
87
95
  */
88
- schema: z.ZodType<T>;
96
+ schema: (context: {
97
+ image: () => z.ZodType;
98
+ }) => z.ZodType<T>;
89
99
  }
90
100
  /** The subset of Astro's `Loader` contract this package uses. */
91
101
  export interface ContentLoader {
@@ -99,6 +109,7 @@ export interface LoaderContext {
99
109
  id: string;
100
110
  data: Record<string, unknown>;
101
111
  digest?: string;
112
+ filePath?: string;
102
113
  }): boolean;
103
114
  keys(): string[];
104
115
  };
@@ -133,27 +144,22 @@ export interface LoaderContext {
133
144
  parseData(input: {
134
145
  id: string;
135
146
  data: Record<string, unknown>;
147
+ /** The entry's file, from the project root: Astro's `image()` resolves paths against it. */
148
+ filePath?: string;
136
149
  }): Promise<Record<string, unknown>>;
137
150
  generateDigest(data: Record<string, unknown> | string): string;
138
151
  }
139
152
  export type MicaCollections<S extends Site> = {
140
- [K in keyof S["collections"]]: AstroCollectionConfig<AstroDocument<InferCollection<S["collections"][K]>>>;
153
+ [K in keyof S["collections"]]: AstroCollectionConfig<CollectionDocument<S, K>>;
141
154
  } & {
142
- [K in keyof S["singletons"]]: AstroCollectionConfig<InferSingleton<S["singletons"][K]>>;
155
+ [K in keyof S["singletons"]]: AstroCollectionConfig<SingletonDocument<S, K>>;
143
156
  };
144
157
  export declare function micaCollections<S extends Site>(site: S, options?: MicaCollectionsOptions): MicaCollections<S>;
145
158
  /** The document type for one collection, as it appears in Astro. */
146
- export type CollectionDocument<S extends Site, K extends keyof S["collections"]> = AstroDocument<InferCollection<S["collections"][K]>>;
159
+ export type CollectionDocument<S extends Site, K extends keyof S["collections"]> = AstroDocument<InferCollection<S["collections"][K], ImageMetadata>>;
147
160
  /** The document type for one singleton. */
148
- export type SingletonDocument<S extends Site, K extends keyof S["singletons"]> = InferSingleton<S["singletons"][K]>;
161
+ export type SingletonDocument<S extends Site, K extends keyof S["singletons"]> = InferSingleton<S["singletons"][K], ImageMetadata>;
149
162
  export { manifestFor } from "./manifest.js";
150
163
  export { DEFAULT_CONTENT_ROOT, resolveContentRoot };
151
164
  export { renderRichText, transformRichText, validateRichText, type RichTextOptions, } from "./richtext.js";
152
- /**
153
- * Re-exported for convenience, so a project that only depends on this package
154
- * can still build a source or read a collection. They are defined in
155
- * `@micacms/core`, where the Mica server can reach them too.
156
- */
157
- export { ContentReadError, ContentSourceError, ORDER_FILE, memorySource, readCollection, readSingleton, type ContentSource, type DirectoryEntry, } from "@micacms/core";
158
- export { fileSystemSource } from "@micacms/core/node";
159
165
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAKH,OAAO,EAOL,KAAK,aAAa,EAElB,KAAK,eAAe,EACpB,KAAK,cAAc,EAEnB,KAAK,IAAI,EACV,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,CAAC,EAAE,MAA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AE,oBAAoB,EAAE,kBAAkB,EAAE,CAAC;AACpD,OAAO,EACL,cAAc,EACd,iBAAiB,EACjB,gBAAgB,EAChB,KAAK,eAAe,GACrB,MAAM,eAAe,CAAC"}
package/dist/index.js CHANGED
@@ -17,9 +17,11 @@
17
17
  */
18
18
  import { mkdir, readFile, writeFile } from "node:fs/promises";
19
19
  import { dirname, join, relative, sep } from "node:path";
20
- import { fieldsSchema, isFieldKind, MANIFEST_PATH, readCollection, readSingleton, } from "@micacms/core";
20
+ import { fileURLToPath } from "node:url";
21
+ import { collectionEntryPath, createReferenceCheck, entryLayout, fieldsSchema, INDEX_FILE, singletonPath, isFieldKind, MANIFEST_PATH, readCollection, readSingleton, } from "@micacms/core";
21
22
  import { fileSystemSource } from "@micacms/core/node";
22
23
  import { z } from "zod";
24
+ import { imagePathsFromEntry } from "./images.js";
23
25
  import { manifestFor } from "./manifest.js";
24
26
  import { DEFAULT_CONTENT_ROOT, resolveContentRoot } from "./root.js";
25
27
  const metaSchema = z.object({
@@ -46,6 +48,31 @@ export function micaCollections(site, options = {}) {
46
48
  options.publishModel === false || options.source
47
49
  ? Promise.resolve()
48
50
  : publishModel(site, rootFor(context), context.logger));
51
+ /** An entry's data file, from the content root and, outside tests, from the project root. */
52
+ const entryFile = (context, fields, name, slug) => {
53
+ const base = slug === undefined ? singletonPath(fields, name) : collectionEntryPath(fields, name, slug);
54
+ const inContent = entryLayout(fields) === "directory" ? `${base}/${INDEX_FILE}` : base;
55
+ const project = context.config?.root;
56
+ const inProject = project && !options.source
57
+ ? relative(fileURLToPath(project), join(rootFor(context), inContent)).split(sep).join("/")
58
+ : undefined;
59
+ return { inContent, inProject };
60
+ };
61
+ /** Warns about broken relations and missing files, or fails the build with `strict`. */
62
+ const checkReferences = async (context, source, documents) => {
63
+ const check = createReferenceCheck(site, source);
64
+ const problems = [];
65
+ for (const { label, fields, data } of documents) {
66
+ for (const issue of await check.issues(fields, data))
67
+ problems.push(`${label}: ${issue.path}: ${issue.message}`);
68
+ }
69
+ if (problems.length === 0)
70
+ return;
71
+ if (options.strict)
72
+ throw new Error(`Broken references:\n ${problems.join("\n ")}`);
73
+ for (const problem of problems)
74
+ context.logger.warn(problem);
75
+ };
49
76
  /** Collections whose watcher is already registered, so a reload adds none. */
50
77
  const watching = new Set();
51
78
  const watch = (context, name, reload) => {
@@ -87,10 +114,7 @@ export function micaCollections(site, options = {}) {
87
114
  for (const [name, def] of Object.entries(site.collections)) {
88
115
  collections[name] = {
89
116
  type: "content_layer",
90
- // `storage` rather than `output`: a media reference is a path into the
91
- // repository at rest and a path into the repository once loaded. There
92
- // is no expansion step left to tell the two apart.
93
- schema: fieldsSchema(def.fields, "storage").extend({ _mica: metaSchema }),
117
+ schema: ({ image }) => fieldsSchema(def.fields, { image }).extend({ _mica: metaSchema }),
94
118
  loader: {
95
119
  name: `mica:${name}`,
96
120
  load: async (context) => {
@@ -107,12 +131,20 @@ export function micaCollections(site, options = {}) {
107
131
  collection: name,
108
132
  position: entry.position,
109
133
  };
134
+ const file = entryFile(context, def.fields, name, entry.slug);
110
135
  const data = await context.parseData({
111
136
  id: entry.slug,
112
- data: { ...entry.data, _mica: meta },
137
+ data: { ...imagePathsFromEntry(def.fields, entry.data, file.inContent), _mica: meta },
138
+ ...(file.inProject ? { filePath: file.inProject } : {}),
139
+ });
140
+ context.store.set({
141
+ id: entry.slug,
142
+ data,
143
+ digest: context.generateDigest(data),
144
+ ...(file.inProject ? { filePath: file.inProject } : {}),
113
145
  });
114
- context.store.set({ id: entry.slug, data, digest: context.generateDigest(data) });
115
146
  }
147
+ await checkReferences(context, source, entries.map((entry) => ({ label: `${name}/${entry.slug}`, fields: def.fields, data: entry.data })));
116
148
  context.logger.info(`Loaded ${entries.length} ${entries.length === 1 ? "entry" : "entries"} of "${def.label}"`);
117
149
  };
118
150
  await publish(context);
@@ -127,7 +159,7 @@ export function micaCollections(site, options = {}) {
127
159
  for (const [name, def] of Object.entries(site.singletons)) {
128
160
  collections[name] = {
129
161
  type: "content_layer",
130
- schema: fieldsSchema(def.fields, "storage"),
162
+ schema: ({ image }) => fieldsSchema(def.fields, { image }),
131
163
  loader: {
132
164
  name: `mica:${name}`,
133
165
  load: async (context) => {
@@ -142,8 +174,19 @@ export function micaCollections(site, options = {}) {
142
174
  context.logger.warn(`No content for "${def.label}" yet.`);
143
175
  return;
144
176
  }
145
- const parsed = await context.parseData({ id: name, data });
146
- context.store.set({ id: name, data: parsed, digest: context.generateDigest(parsed) });
177
+ await checkReferences(context, source, [{ label: name, fields: def.fields, data }]);
178
+ const file = entryFile(context, def.fields, name);
179
+ const parsed = await context.parseData({
180
+ id: name,
181
+ data: imagePathsFromEntry(def.fields, data, file.inContent),
182
+ ...(file.inProject ? { filePath: file.inProject } : {}),
183
+ });
184
+ context.store.set({
185
+ id: name,
186
+ data: parsed,
187
+ digest: context.generateDigest(parsed),
188
+ ...(file.inProject ? { filePath: file.inProject } : {}),
189
+ });
147
190
  };
148
191
  await publish(context);
149
192
  await read();
@@ -231,11 +274,4 @@ async function guard(context, source, read) {
231
274
  export { manifestFor } from "./manifest.js";
232
275
  export { DEFAULT_CONTENT_ROOT, resolveContentRoot };
233
276
  export { renderRichText, transformRichText, validateRichText, } from "./richtext.js";
234
- /**
235
- * Re-exported for convenience, so a project that only depends on this package
236
- * can still build a source or read a collection. They are defined in
237
- * `@micacms/core`, where the Mica server can reach them too.
238
- */
239
- export { ContentReadError, ContentSourceError, ORDER_FILE, memorySource, readCollection, readSingleton, } from "@micacms/core";
240
- export { fileSystemSource } from "@micacms/core/node";
241
277
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC9D,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,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,CAAC,+BAA+B,MAAM,CAAC,MAAM,QAAQ,MAAM,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IAClG,CAAC;AACH,CAAC;AAkBD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,CAAC;AACpD,OAAO,EACL,cAAc,EACd,iBAAiB,EACjB,gBAAgB,GAEjB,MAAM,eAAe,CAAC;AAEvB;;;;GAIG;AACH,OAAO,EACL,gBAAgB,EAChB,kBAAkB,EAClB,UAAU,EACV,YAAY,EACZ,cAAc,EACd,aAAa,GAGd,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC","sourcesContent":["/**\n * @micacms/astro — a Git repository as an Astro content source.\n *\n * // src/content.config.ts — the model is in src/mica.ts\n * import { micaCollections } from \"@micacms/astro\";\n * import { site } from \"./mica\";\n *\n * export const collections = micaCollections(site);\n *\n * From there the website uses ordinary Astro APIs — `getCollection(\"projects\")`\n * — and knows nothing about how the content arrived.\n *\n * There is no CMS in this path. The loaders read files that are already in the\n * working tree, so a build needs a checkout and nothing else: no running\n * server, no token, no network. That is the point of the Git-native design.\n * Publishing is a commit, and CI builds the commit.\n */\n\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname, join, relative, sep } from \"node:path\";\n\nimport {\n fieldsSchema,\n isFieldKind,\n MANIFEST_PATH,\n readCollection,\n readSingleton,\n type Collection,\n type ContentSource,\n type FieldMap,\n type InferCollection,\n type InferSingleton,\n type Singleton,\n type Site,\n} from \"@micacms/core\";\nimport { fileSystemSource } from \"@micacms/core/node\";\nimport { z } from \"zod\";\n\nimport { manifestFor } from \"./manifest.js\";\nimport { DEFAULT_CONTENT_ROOT, resolveContentRoot } from \"./root.js\";\n\nexport interface MicaCollectionsOptions {\n /**\n * Overrides `defineSite({ root })`, which is where the content root belongs.\n *\n * Relative paths resolve against the Astro project root, like Astro's own\n * `glob({ base })`. An absolute path is used as given — which is what a\n * project whose content is a separate repository, checked out by CI\n * somewhere else, wants.\n */\n root?: string;\n /** Overrides `root` entirely. Used by tests, and by a non-filesystem source. */\n source?: ContentSource;\n /**\n * Turns off publishing the model to `<root>/.mica/schema.json`.\n *\n * Only for a project that is not edited through Mica at all: without that\n * file in the repository, Mica has no model and refuses to start.\n */\n publishModel?: false;\n /**\n * How long to wait after a content change before reloading, in dev.\n *\n * Saving one entry touches several files — `index.json` and every `.mdoc`\n * beside it — and a Git checkout touches all of them at once. One reload\n * after the burst is both faster and less confusing than one per file.\n */\n debounceMs?: number;\n}\n\n/**\n * Entry metadata attached to every collection document.\n *\n * No timestamps: in Git they are commit metadata, which a static build cannot\n * read cheaply. A date an editor cares about belongs in the model as a `date()` field.\n *\n * Namespaced because these keys share a namespace with the customer's own\n * fields, and `position` is a plausible field name.\n */\nexport interface MicaMeta {\n /** The entry slug, which is its identity in the repository. */\n id: string;\n slug: string;\n collection: string;\n /** Index in the collection's order, manual when `_order.json` says so. */\n position: number;\n}\n\nconst metaSchema = z.object({\n id: z.string(),\n slug: z.string(),\n collection: z.string(),\n position: z.number(),\n});\n\n/** What a document looks like inside Astro: the payload plus `_mica`. */\nexport type AstroDocument<T> = T & { _mica: MicaMeta };\n\n/**\n * The shape Astro's config loader expects.\n *\n * Deliberately not built with `defineCollection` from `astro:content`: that is a\n * virtual module, resolvable only inside an Astro app's module graph, and this\n * package is pre-compiled. `defineCollection` does nothing more than stamp this\n * `type`, so producing the object directly keeps the package importable\n * anywhere — including from a plain unit test.\n */\nexport interface AstroCollectionConfig<T = unknown> {\n type: \"content_layer\";\n loader: ContentLoader;\n /**\n * Typed as `ZodType<T>` rather than a bare `ZodObject`, because Astro derives\n * `CollectionEntry<\"projects\">[\"data\"]` from `z.infer` of whatever this is.\n * Left generic, every field in every template would degrade to `any` — and\n * the point of the shared model is that renaming a field breaks the build.\n */\n schema: z.ZodType<T>;\n}\n\n/** The subset of Astro's `Loader` contract this package uses. */\nexport interface ContentLoader {\n name: string;\n load(context: LoaderContext): Promise<void>;\n}\n\nexport interface LoaderContext {\n store: {\n clear(): void;\n set(entry: { id: string; data: Record<string, unknown>; digest?: string }): boolean;\n keys(): string[];\n };\n logger: {\n info(message: string): void;\n warn(message: string): void;\n error(message: string): void;\n debug(message: string): void;\n };\n meta: { get(key: string): string | undefined; set(key: string, value: string): void };\n /**\n * Astro's resolved config. Optional because this interface is a hand-written\n * subset and the tests build a context by hand; `config.root` is what turns a\n * relative content root into a path.\n */\n config?: { root: URL };\n /**\n * Present only while `astro dev` runs. Astro's watcher follows the module\n * graph, and content files are not in it — no page imports\n * `projects/haus-a/index.json` — so each loader watches its own directory\n * here, exactly as Astro's own `glob` loader does.\n */\n watcher?: {\n add(path: string): void;\n on(event: \"add\" | \"change\" | \"unlink\", handler: (path: string) => void): void;\n };\n parseData(input: {\n id: string;\n data: Record<string, unknown>;\n }): Promise<Record<string, unknown>>;\n generateDigest(data: Record<string, unknown> | string): string;\n}\n\nexport type MicaCollections<S extends Site> = {\n [K in keyof S[\"collections\"]]: AstroCollectionConfig<\n AstroDocument<InferCollection<S[\"collections\"][K]>>\n >;\n} & {\n [K in keyof S[\"singletons\"]]: AstroCollectionConfig<InferSingleton<S[\"singletons\"][K]>>;\n};\n\nexport function micaCollections<S extends Site>(\n site: S,\n options: MicaCollectionsOptions = {},\n): MicaCollections<S> {\n assertKnownKinds(site);\n\n /**\n * Everything below is resolved on first load rather than here, because the\n * Astro project root is something only a loader is told — and it is what\n * turns `./content` into a directory. Memoised: one root and one source,\n * however many collections and however many reloads.\n */\n let root: string | undefined;\n let source: ContentSource | undefined;\n\n const rootFor = (context: LoaderContext): string =>\n (root ??= resolveContentRoot(options.root ?? site.root, context.config?.root));\n\n const sourceFor = (context: LoaderContext): ContentSource =>\n (source ??= options.source ?? fileSystemSource(rootFor(context)));\n\n /** Published once per process; a model change restarts the dev server. */\n let publishing: Promise<void> | undefined;\n\n const publish = (context: LoaderContext): Promise<void> =>\n (publishing ??=\n options.publishModel === false || options.source\n ? Promise.resolve()\n : publishModel(site, rootFor(context), context.logger));\n\n /** Collections whose watcher is already registered, so a reload adds none. */\n const watching = new Set<string>();\n\n const watch = (context: LoaderContext, name: string, reload: () => Promise<void>): void => {\n const watcher = context.watcher;\n if (!watcher || options.source || watching.has(name)) return;\n watching.add(name);\n\n const base = rootFor(context);\n watcher.add(base);\n\n // A collection lives in `<root>/<name>/`; a singleton is either\n // `<root>/<name>.json` or `<root>/<name>/…`. Both are covered by this\n // prefix, and nothing outside it can concern this loader — which is what\n // keeps one collection's save from re-reading every other one.\n const prefix = join(base, name);\n const mine = (path: string): boolean =>\n path === `${prefix}.json` || path.startsWith(prefix + sep);\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const onChange = (path: string): void => {\n // The manifest is this package's own output; reloading content because\n // the model was written is a loop waiting to happen.\n if (path.endsWith(MANIFEST_PATH) || !mine(path)) return;\n\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => {\n // Content that fails its own schema lands here. The dev server has to\n // survive it: the next save is very likely the fix.\n void reload().catch((error: unknown) => {\n context.logger.error(`Could not reload content: ${describe(error)}`);\n });\n }, options.debounceMs ?? 100);\n // A pending reload is never a reason to keep the process alive.\n timer.unref?.();\n };\n\n watcher.on(\"change\", onChange);\n watcher.on(\"add\", onChange);\n watcher.on(\"unlink\", onChange);\n };\n\n const collections = {} as Record<string, AstroCollectionConfig<unknown>>;\n\n for (const [name, def] of Object.entries(site.collections) as [string, Collection][]) {\n collections[name] = {\n type: \"content_layer\",\n // `storage` rather than `output`: a media reference is a path into the\n // repository at rest and a path into the repository once loaded. There\n // is no expansion step left to tell the two apart.\n schema: fieldsSchema(def.fields, \"storage\").extend({ _mica: metaSchema }),\n loader: {\n name: `mica:${name}`,\n load: async (context) => {\n const read = async (): Promise<void> => {\n const source = sourceFor(context);\n const entries = await guard(context, source, () => readCollection(source, def, name));\n\n // A full replace, not a merge: an entry deleted from the repository\n // has to disappear from the build.\n context.store.clear();\n\n for (const entry of entries) {\n const meta: MicaMeta = {\n id: entry.slug,\n slug: entry.slug,\n collection: name,\n position: entry.position,\n };\n\n const data = await context.parseData({\n id: entry.slug,\n data: { ...entry.data, _mica: meta },\n });\n context.store.set({ id: entry.slug, data, digest: context.generateDigest(data) });\n }\n\n context.logger.info(`Loaded ${entries.length} ${entries.length === 1 ? \"entry\" : \"entries\"} of \"${def.label}\"`);\n };\n\n await publish(context);\n await read();\n watch(context, name, read);\n },\n },\n };\n }\n\n // A singleton becomes a one-entry collection whose id is its name, so the\n // website reaches it with the same `getEntry` it uses for everything else.\n for (const [name, def] of Object.entries(site.singletons) as [string, Singleton][]) {\n collections[name] = {\n type: \"content_layer\",\n schema: fieldsSchema(def.fields, \"storage\"),\n loader: {\n name: `mica:${name}`,\n load: async (context) => {\n const read = async (): Promise<void> => {\n const source = sourceFor(context);\n const data = await guard(context, source, () => readSingleton(source, def, name));\n\n context.store.clear();\n if (data === null) {\n // Not fatal. A site is normally deployed before every settings\n // form has been filled in, and the page that reads this singleton\n // reports the absence far better than the loader can.\n context.logger.warn(`No content for \"${def.label}\" yet.`);\n return;\n }\n\n const parsed = await context.parseData({ id: name, data });\n context.store.set({ id: name, data: parsed, digest: context.generateDigest(parsed) });\n };\n\n await publish(context);\n await read();\n watch(context, name, read);\n },\n },\n };\n }\n\n return collections as MicaCollections<S>;\n}\n\n/**\n * The site's own model must use only kinds this package knows. Mica reads an\n * unknown kind as one from a newer version and makes its collection read-only,\n * so a typo would otherwise pass the build and lock the collection.\n */\nfunction assertKnownKinds(site: Site): void {\n const check = (fields: FieldMap, at: string) => {\n for (const [key, field] of Object.entries(fields)) {\n if (!isFieldKind(field.kind)) {\n throw new Error(`Field \"${at}.${key}\" has the unknown kind \"${String(field.kind)}\". Use the field functions from @micacms/core.`);\n }\n if (field.kind === \"object\" || field.kind === \"repeater\") check(field.fields, `${at}.${key}`);\n }\n };\n for (const [name, def] of Object.entries(site.collections)) check(def.fields, `collections.${name}`);\n for (const [name, def] of Object.entries(site.singletons)) check(def.fields, `singletons.${name}`);\n}\n\n/**\n * Writes the model into the content root, for Mica to read back.\n *\n * Mica holds no content model: the Astro project is the only place a collection\n * is defined, and this is how it says so. The file goes *inside the content\n * root* so that it travels to Mica the way content does — through Git and the\n * repository connector — with nothing to mount and no second channel to keep in\n * step. Commit it.\n *\n * Done from a loader rather than an integration because this is the moment both\n * facts are in hand: the model, and the project root that turns `./content`\n * into a directory. It also means `astro.config` needs no Mica in it, which is\n * what lets a project define Mica collections and ordinary Astro ones in the\n * same `content.config.ts`.\n */\nasync function publishModel(\n site: Site,\n root: string,\n logger: LoaderContext[\"logger\"],\n): Promise<void> {\n const target = join(root, MANIFEST_PATH);\n const contents = `${JSON.stringify(manifestFor(site), null, 2)}\\n`;\n\n try {\n // Only when it differs. The content root is watched in dev, and rewriting\n // an identical file on every start would ask for a reload for no reason.\n if ((await readFile(target, \"utf8\").catch(() => null)) === contents) return;\n\n await mkdir(dirname(target), { recursive: true });\n await writeFile(target, contents, \"utf8\");\n logger.info(`Wrote the content model to ${relative(process.cwd(), target)} — commit it for Mica to read.`);\n } catch (error) {\n // A site that builds correctly should not fail over this, and a read-only\n // checkout is a normal way to build one in CI. Mica reports a missing model\n // itself, and far more usefully.\n logger.warn(`Could not write the content model: ${describe(error)}`);\n }\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Reports a read failure against the content root that produced it.\n *\n * A build failing on unreadable content is correct — publishing a half-empty\n * site would be worse — but the message has to name the directory that was\n * read, because the usual cause is a content root pointing at the wrong place.\n */\nasync function guard<T>(\n context: LoaderContext,\n source: ContentSource,\n read: () => Promise<T>,\n): Promise<T> {\n try {\n return await read();\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n context.logger.error(detail);\n\n throw new Error(`Could not read content from ${source.origin}.\\n ${detail}`, { cause: error });\n }\n}\n\n/* ------------------------------------------------------------------ *\n * Types for the website\n * ------------------------------------------------------------------ */\n\n/** The document type for one collection, as it appears in Astro. */\nexport type CollectionDocument<\n S extends Site,\n K extends keyof S[\"collections\"],\n> = AstroDocument<InferCollection<S[\"collections\"][K]>>;\n\n/** The document type for one singleton. */\nexport type SingletonDocument<\n S extends Site,\n K extends keyof S[\"singletons\"],\n> = InferSingleton<S[\"singletons\"][K]>;\n\nexport { manifestFor } from \"./manifest.js\";\nexport { DEFAULT_CONTENT_ROOT, resolveContentRoot };\nexport {\n renderRichText,\n transformRichText,\n validateRichText,\n type RichTextOptions,\n} from \"./richtext.js\";\n\n/**\n * Re-exported for convenience, so a project that only depends on this package\n * can still build a source or read a collection. They are defined in\n * `@micacms/core`, where the Mica server can reach them too.\n */\nexport {\n ContentReadError,\n ContentSourceError,\n ORDER_FILE,\n memorySource,\n readCollection,\n readSingleton,\n type ContentSource,\n type DirectoryEntry,\n} from \"@micacms/core\";\nexport { fileSystemSource } from \"@micacms/core/node\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC9D,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,OAAO,EACL,mBAAmB,EACnB,oBAAoB,EACpB,WAAW,EACX,YAAY,EACZ,UAAU,EACV,aAAa,EACb,WAAW,EACX,aAAa,EACb,cAAc,EACd,aAAa,GAQd,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAClD,OA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AC;IACtB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,MAAM,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACtE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QAE7B,MAAM,IAAI,KAAK,CAAC,+BAA+B,MAAM,CAAC,MAAM,QAAQ,MAAM,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IAClG,CAAC;AACH,CAAC;AAkBD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,CAAC;AACpD,OAAO,EACL,cAAc,EACd,iBAAiB,EACjB,gBAAgB,GAEjB,MAAM,eAAe,CAAC","sourcesContent":["/**\n * @micacms/astro — a Git repository as an Astro content source.\n *\n * // src/content.config.ts — the model is in src/mica.ts\n * import { micaCollections } from \"@micacms/astro\";\n * import { site } from \"./mica\";\n *\n * export const collections = micaCollections(site);\n *\n * From there the website uses ordinary Astro APIs — `getCollection(\"projects\")`\n * — and knows nothing about how the content arrived.\n *\n * There is no CMS in this path. The loaders read files that are already in the\n * working tree, so a build needs a checkout and nothing else: no running\n * server, no token, no network. That is the point of the Git-native design.\n * Publishing is a commit, and CI builds the commit.\n */\n\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname, join, relative, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport {\n collectionEntryPath,\n createReferenceCheck,\n entryLayout,\n fieldsSchema,\n INDEX_FILE,\n singletonPath,\n isFieldKind,\n MANIFEST_PATH,\n readCollection,\n readSingleton,\n type Collection,\n type ContentSource,\n type FieldMap,\n type InferCollection,\n type InferSingleton,\n type Singleton,\n type Site,\n} from \"@micacms/core\";\nimport { fileSystemSource } from \"@micacms/core/node\";\nimport type { ImageMetadata } from \"astro\";\nimport { z } from \"zod\";\n\nimport { imagePathsFromEntry } from \"./images.js\";\nimport { manifestFor } from \"./manifest.js\";\nimport { DEFAULT_CONTENT_ROOT, resolveContentRoot } from \"./root.js\";\n\nexport interface MicaCollectionsOptions {\n /**\n * Overrides `defineSite({ root })`, which is where the content root belongs.\n *\n * Relative paths resolve against the Astro project root, like Astro's own\n * `glob({ base })`. An absolute path is used as given — which is what a\n * project whose content is a separate repository, checked out by CI\n * somewhere else, wants.\n */\n root?: string;\n /** Overrides `root` entirely. Used by tests, and by a non-filesystem source. */\n source?: ContentSource;\n /**\n * Turns off publishing the model to `<root>/.mica/schema.json`.\n *\n * Only for a project that is not edited through Mica at all: without that\n * file in the repository, Mica has no model and refuses to start.\n */\n publishModel?: false;\n /**\n * How long to wait after a content change before reloading, in dev.\n *\n * Saving one entry touches several files — `index.json` and every `.mdoc`\n * beside it — and a Git checkout touches all of them at once. One reload\n * after the burst is both faster and less confusing than one per file.\n */\n debounceMs?: number;\n /**\n * Fails the build on a relation to a missing entry or a missing media file.\n * Without it, the build logs a warning for each and goes on; a missing image\n * file fails the build either way, because Astro cannot import it.\n */\n strict?: boolean;\n}\n\n/**\n * Entry metadata attached to every collection document.\n *\n * No timestamps: in Git they are commit metadata, which a static build cannot\n * read cheaply. A date an editor cares about belongs in the model as a `date()` field.\n *\n * Namespaced because these keys share a namespace with the customer's own\n * fields, and `position` is a plausible field name.\n */\nexport interface MicaMeta {\n /** The entry slug, which is its identity in the repository. */\n id: string;\n slug: string;\n collection: string;\n /** Index in the collection's order, manual when `_order.json` says so. */\n position: number;\n}\n\nconst metaSchema = z.object({\n id: z.string(),\n slug: z.string(),\n collection: z.string(),\n position: z.number(),\n});\n\n/** What a document looks like inside Astro: the payload plus `_mica`. */\nexport type AstroDocument<T> = T & { _mica: MicaMeta };\n\n/**\n * The shape Astro's config loader expects.\n *\n * Deliberately not built with `defineCollection` from `astro:content`: that is a\n * virtual module, resolvable only inside an Astro app's module graph, and this\n * package is pre-compiled. `defineCollection` does nothing more than stamp this\n * `type`, so producing the object directly keeps the package importable\n * anywhere — including from a plain unit test.\n */\nexport interface AstroCollectionConfig<T = unknown> {\n type: \"content_layer\";\n loader: ContentLoader;\n /**\n * A function, so that Astro hands in its `image()`. Its result is typed as\n * `ZodType<T>` because Astro derives `CollectionEntry<\"projects\">[\"data\"]`\n * from it: left generic, every field in every template would degrade to\n * `any`, and the point of the shared model is that renaming a field breaks\n * the build.\n */\n schema: (context: { image: () => z.ZodType }) => z.ZodType<T>;\n}\n\n/** The subset of Astro's `Loader` contract this package uses. */\nexport interface ContentLoader {\n name: string;\n load(context: LoaderContext): Promise<void>;\n}\n\nexport interface LoaderContext {\n store: {\n clear(): void;\n set(entry: { id: string; data: Record<string, unknown>; digest?: string; filePath?: string }): boolean;\n keys(): string[];\n };\n logger: {\n info(message: string): void;\n warn(message: string): void;\n error(message: string): void;\n debug(message: string): void;\n };\n meta: { get(key: string): string | undefined; set(key: string, value: string): void };\n /**\n * Astro's resolved config. Optional because this interface is a hand-written\n * subset and the tests build a context by hand; `config.root` is what turns a\n * relative content root into a path.\n */\n config?: { root: URL };\n /**\n * Present only while `astro dev` runs. Astro's watcher follows the module\n * graph, and content files are not in it — no page imports\n * `projects/haus-a/index.json` — so each loader watches its own directory\n * here, exactly as Astro's own `glob` loader does.\n */\n watcher?: {\n add(path: string): void;\n on(event: \"add\" | \"change\" | \"unlink\", handler: (path: string) => void): void;\n };\n parseData(input: {\n id: string;\n data: Record<string, unknown>;\n /** The entry's file, from the project root: Astro's `image()` resolves paths against it. */\n filePath?: string;\n }): Promise<Record<string, unknown>>;\n generateDigest(data: Record<string, unknown> | string): string;\n}\n\nexport type MicaCollections<S extends Site> = {\n [K in keyof S[\"collections\"]]: AstroCollectionConfig<CollectionDocument<S, K>>;\n} & {\n [K in keyof S[\"singletons\"]]: AstroCollectionConfig<SingletonDocument<S, K>>;\n};\n\nexport function micaCollections<S extends Site>(\n site: S,\n options: MicaCollectionsOptions = {},\n): MicaCollections<S> {\n assertKnownKinds(site);\n\n /**\n * Everything below is resolved on first load rather than here, because the\n * Astro project root is something only a loader is told — and it is what\n * turns `./content` into a directory. Memoised: one root and one source,\n * however many collections and however many reloads.\n */\n let root: string | undefined;\n let source: ContentSource | undefined;\n\n const rootFor = (context: LoaderContext): string =>\n (root ??= resolveContentRoot(options.root ?? site.root, context.config?.root));\n\n const sourceFor = (context: LoaderContext): ContentSource =>\n (source ??= options.source ?? fileSystemSource(rootFor(context)));\n\n /** Published once per process; a model change restarts the dev server. */\n let publishing: Promise<void> | undefined;\n\n const publish = (context: LoaderContext): Promise<void> =>\n (publishing ??=\n options.publishModel === false || options.source\n ? Promise.resolve()\n : publishModel(site, rootFor(context), context.logger));\n\n /** An entry's data file, from the content root and, outside tests, from the project root. */\n const entryFile = (context: LoaderContext, fields: FieldMap, name: string, slug?: string) => {\n const base = slug === undefined ? singletonPath(fields, name) : collectionEntryPath(fields, name, slug);\n const inContent = entryLayout(fields) === \"directory\" ? `${base}/${INDEX_FILE}` : base;\n const project = context.config?.root;\n const inProject =\n project && !options.source\n ? relative(fileURLToPath(project), join(rootFor(context), inContent)).split(sep).join(\"/\")\n : undefined;\n return { inContent, inProject };\n };\n\n /** Warns about broken relations and missing files, or fails the build with `strict`. */\n const checkReferences = async (\n context: LoaderContext,\n source: ContentSource,\n documents: Array<{ label: string; fields: FieldMap; data: Record<string, unknown> }>,\n ): Promise<void> => {\n const check = createReferenceCheck(site, source);\n const problems: string[] = [];\n for (const { label, fields, data } of documents) {\n for (const issue of await check.issues(fields, data)) problems.push(`${label}: ${issue.path}: ${issue.message}`);\n }\n if (problems.length === 0) return;\n if (options.strict) throw new Error(`Broken references:\\n ${problems.join(\"\\n \")}`);\n for (const problem of problems) context.logger.warn(problem);\n };\n\n /** Collections whose watcher is already registered, so a reload adds none. */\n const watching = new Set<string>();\n\n const watch = (context: LoaderContext, name: string, reload: () => Promise<void>): void => {\n const watcher = context.watcher;\n if (!watcher || options.source || watching.has(name)) return;\n watching.add(name);\n\n const base = rootFor(context);\n watcher.add(base);\n\n // A collection lives in `<root>/<name>/`; a singleton is either\n // `<root>/<name>.json` or `<root>/<name>/…`. Both are covered by this\n // prefix, and nothing outside it can concern this loader — which is what\n // keeps one collection's save from re-reading every other one.\n const prefix = join(base, name);\n const mine = (path: string): boolean =>\n path === `${prefix}.json` || path.startsWith(prefix + sep);\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const onChange = (path: string): void => {\n // The manifest is this package's own output; reloading content because\n // the model was written is a loop waiting to happen.\n if (path.endsWith(MANIFEST_PATH) || !mine(path)) return;\n\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => {\n // Content that fails its own schema lands here. The dev server has to\n // survive it: the next save is very likely the fix.\n void reload().catch((error: unknown) => {\n context.logger.error(`Could not reload content: ${describe(error)}`);\n });\n }, options.debounceMs ?? 100);\n // A pending reload is never a reason to keep the process alive.\n timer.unref?.();\n };\n\n watcher.on(\"change\", onChange);\n watcher.on(\"add\", onChange);\n watcher.on(\"unlink\", onChange);\n };\n\n const collections = {} as Record<string, AstroCollectionConfig<unknown>>;\n\n for (const [name, def] of Object.entries(site.collections) as [string, Collection][]) {\n collections[name] = {\n type: \"content_layer\",\n schema: ({ image }) => fieldsSchema(def.fields, { image }).extend({ _mica: metaSchema }),\n loader: {\n name: `mica:${name}`,\n load: async (context) => {\n const read = async (): Promise<void> => {\n const source = sourceFor(context);\n const entries = await guard(context, source, () => readCollection(source, def, name));\n\n // A full replace, not a merge: an entry deleted from the repository\n // has to disappear from the build.\n context.store.clear();\n\n for (const entry of entries) {\n const meta: MicaMeta = {\n id: entry.slug,\n slug: entry.slug,\n collection: name,\n position: entry.position,\n };\n\n const file = entryFile(context, def.fields, name, entry.slug);\n const data = await context.parseData({\n id: entry.slug,\n data: { ...imagePathsFromEntry(def.fields, entry.data, file.inContent), _mica: meta },\n ...(file.inProject ? { filePath: file.inProject } : {}),\n });\n context.store.set({\n id: entry.slug,\n data,\n digest: context.generateDigest(data),\n ...(file.inProject ? { filePath: file.inProject } : {}),\n });\n }\n\n await checkReferences(\n context,\n source,\n entries.map((entry) => ({ label: `${name}/${entry.slug}`, fields: def.fields, data: entry.data })),\n );\n context.logger.info(`Loaded ${entries.length} ${entries.length === 1 ? \"entry\" : \"entries\"} of \"${def.label}\"`);\n };\n\n await publish(context);\n await read();\n watch(context, name, read);\n },\n },\n };\n }\n\n // A singleton becomes a one-entry collection whose id is its name, so the\n // website reaches it with the same `getEntry` it uses for everything else.\n for (const [name, def] of Object.entries(site.singletons) as [string, Singleton][]) {\n collections[name] = {\n type: \"content_layer\",\n schema: ({ image }) => fieldsSchema(def.fields, { image }),\n loader: {\n name: `mica:${name}`,\n load: async (context) => {\n const read = async (): Promise<void> => {\n const source = sourceFor(context);\n const data = await guard(context, source, () => readSingleton(source, def, name));\n\n context.store.clear();\n if (data === null) {\n // Not fatal. A site is normally deployed before every settings\n // form has been filled in, and the page that reads this singleton\n // reports the absence far better than the loader can.\n context.logger.warn(`No content for \"${def.label}\" yet.`);\n return;\n }\n\n await checkReferences(context, source, [{ label: name, fields: def.fields, data }]);\n const file = entryFile(context, def.fields, name);\n const parsed = await context.parseData({\n id: name,\n data: imagePathsFromEntry(def.fields, data, file.inContent),\n ...(file.inProject ? { filePath: file.inProject } : {}),\n });\n context.store.set({\n id: name,\n data: parsed,\n digest: context.generateDigest(parsed),\n ...(file.inProject ? { filePath: file.inProject } : {}),\n });\n };\n\n await publish(context);\n await read();\n watch(context, name, read);\n },\n },\n };\n }\n\n return collections as MicaCollections<S>;\n}\n\n/**\n * The site's own model must use only kinds this package knows. Mica reads an\n * unknown kind as one from a newer version and makes its collection read-only,\n * so a typo would otherwise pass the build and lock the collection.\n */\nfunction assertKnownKinds(site: Site): void {\n const check = (fields: FieldMap, at: string) => {\n for (const [key, field] of Object.entries(fields)) {\n if (!isFieldKind(field.kind)) {\n throw new Error(`Field \"${at}.${key}\" has the unknown kind \"${String(field.kind)}\". Use the field functions from @micacms/core.`);\n }\n if (field.kind === \"object\" || field.kind === \"repeater\") check(field.fields, `${at}.${key}`);\n }\n };\n for (const [name, def] of Object.entries(site.collections)) check(def.fields, `collections.${name}`);\n for (const [name, def] of Object.entries(site.singletons)) check(def.fields, `singletons.${name}`);\n}\n\n/**\n * Writes the model into the content root, for Mica to read back.\n *\n * Mica holds no content model: the Astro project is the only place a collection\n * is defined, and this is how it says so. The file goes *inside the content\n * root* so that it travels to Mica the way content does — through Git and the\n * repository connector — with nothing to mount and no second channel to keep in\n * step. Commit it.\n *\n * Done from a loader rather than an integration because this is the moment both\n * facts are in hand: the model, and the project root that turns `./content`\n * into a directory. It also means `astro.config` needs no Mica in it, which is\n * what lets a project define Mica collections and ordinary Astro ones in the\n * same `content.config.ts`.\n */\nasync function publishModel(\n site: Site,\n root: string,\n logger: LoaderContext[\"logger\"],\n): Promise<void> {\n const target = join(root, MANIFEST_PATH);\n const contents = `${JSON.stringify(manifestFor(site), null, 2)}\\n`;\n\n try {\n // Only when it differs. The content root is watched in dev, and rewriting\n // an identical file on every start would ask for a reload for no reason.\n if ((await readFile(target, \"utf8\").catch(() => null)) === contents) return;\n\n await mkdir(dirname(target), { recursive: true });\n await writeFile(target, contents, \"utf8\");\n logger.info(`Wrote the content model to ${relative(process.cwd(), target)} — commit it for Mica to read.`);\n } catch (error) {\n // A site that builds correctly should not fail over this, and a read-only\n // checkout is a normal way to build one in CI. Mica reports a missing model\n // itself, and far more usefully.\n logger.warn(`Could not write the content model: ${describe(error)}`);\n }\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Reports a read failure against the content root that produced it.\n *\n * A build failing on unreadable content is correct — publishing a half-empty\n * site would be worse — but the message has to name the directory that was\n * read, because the usual cause is a content root pointing at the wrong place.\n */\nasync function guard<T>(\n context: LoaderContext,\n source: ContentSource,\n read: () => Promise<T>,\n): Promise<T> {\n try {\n return await read();\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n context.logger.error(detail);\n\n throw new Error(`Could not read content from ${source.origin}.\\n ${detail}`, { cause: error });\n }\n}\n\n/* ------------------------------------------------------------------ *\n * Types for the website\n * ------------------------------------------------------------------ */\n\n/** The document type for one collection, as it appears in Astro. */\nexport type CollectionDocument<\n S extends Site,\n K extends keyof S[\"collections\"],\n> = AstroDocument<InferCollection<S[\"collections\"][K], ImageMetadata>>;\n\n/** The document type for one singleton. */\nexport type SingletonDocument<\n S extends Site,\n K extends keyof S[\"singletons\"],\n> = InferSingleton<S[\"singletons\"][K], ImageMetadata>;\n\nexport { manifestFor } from \"./manifest.js\";\nexport { DEFAULT_CONTENT_ROOT, resolveContentRoot };\nexport {\n renderRichText,\n transformRichText,\n validateRichText,\n type RichTextOptions,\n} from \"./richtext.js\";\n"]}
package/package.json CHANGED
@@ -1,9 +1,19 @@
1
1
  {
2
2
  "name": "@micacms/astro",
3
- "version": "0.5.0",
3
+ "version": "0.6.0-rc.2",
4
4
  "type": "module",
5
5
  "description": "Reads a Mica content repository as Astro Content Collections via the Content Layer API.",
6
6
  "license": "MIT",
7
+ "homepage": "https://micacms.com",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/micacms/mica.git",
11
+ "directory": "packages/astro"
12
+ },
13
+ "bugs": "https://github.com/micacms/mica/issues",
14
+ "engines": {
15
+ "node": ">=24"
16
+ },
7
17
  "author": "Alexander Müdespacher",
8
18
  "keywords": [
9
19
  "mica",
@@ -25,20 +35,23 @@
25
35
  },
26
36
  "files": [
27
37
  "dist",
28
- "setup"
38
+ "setup",
39
+ "src"
29
40
  ],
30
41
  "dependencies": {
31
- "@markdoc/markdoc": "^0.5.9",
32
- "zod": "^4.3.6",
33
- "@micacms/core": "0.5.0"
42
+ "@markdoc/markdoc": "^0.5.9"
34
43
  },
35
44
  "peerDependencies": {
36
- "astro": "^6.0.0 || ^7.0.0"
45
+ "astro": "^7.0.0",
46
+ "zod": "^4.3.6",
47
+ "@micacms/core": "^0.6.0-rc.2"
37
48
  },
38
49
  "devDependencies": {
39
50
  "@types/node": "^22.20.1",
40
51
  "astro": "^7.2.2",
41
- "typescript": "^5.7.3"
52
+ "typescript": "^5.7.3",
53
+ "zod": "^4.3.6",
54
+ "@micacms/core": "0.6.0-rc.2"
42
55
  },
43
56
  "scripts": {
44
57
  "build": "tsc -p tsconfig.json",