@caelo-cms/shared 0.11.7 → 0.11.9

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 (60) hide show
  1. package/dist/ai-tools.d.ts +2 -2
  2. package/dist/build-page.d.ts +4 -4
  3. package/dist/change-journal.d.ts.map +1 -1
  4. package/dist/change-journal.js +2 -0
  5. package/dist/change-journal.js.map +1 -1
  6. package/dist/content.d.ts +6 -6
  7. package/dist/content.d.ts.map +1 -1
  8. package/dist/content.js +8 -1
  9. package/dist/content.js.map +1 -1
  10. package/dist/lists/fields.d.ts +6 -0
  11. package/dist/lists/fields.d.ts.map +1 -1
  12. package/dist/lists/fields.js +70 -7
  13. package/dist/lists/fields.js.map +1 -1
  14. package/dist/lists/index.d.ts +1 -0
  15. package/dist/lists/index.d.ts.map +1 -1
  16. package/dist/lists/index.js +1 -0
  17. package/dist/lists/index.js.map +1 -1
  18. package/dist/lists/list-type.d.ts +28 -6
  19. package/dist/lists/list-type.d.ts.map +1 -1
  20. package/dist/lists/list-type.js +43 -15
  21. package/dist/lists/list-type.js.map +1 -1
  22. package/dist/lists/overlay-scope.d.ts +68 -0
  23. package/dist/lists/overlay-scope.d.ts.map +1 -0
  24. package/dist/lists/overlay-scope.js +56 -0
  25. package/dist/lists/overlay-scope.js.map +1 -0
  26. package/dist/lists/query-merge.d.ts +27 -0
  27. package/dist/lists/query-merge.d.ts.map +1 -0
  28. package/dist/lists/query-merge.js +53 -0
  29. package/dist/lists/query-merge.js.map +1 -0
  30. package/dist/lists/resolve.d.ts +1 -0
  31. package/dist/lists/resolve.d.ts.map +1 -1
  32. package/dist/lists/resolve.js +11 -25
  33. package/dist/lists/resolve.js.map +1 -1
  34. package/dist/lists/scope.d.ts +4 -1
  35. package/dist/lists/scope.d.ts.map +1 -1
  36. package/dist/template-engine.d.ts +23 -0
  37. package/dist/template-engine.d.ts.map +1 -1
  38. package/dist/template-engine.js +69 -3
  39. package/dist/template-engine.js.map +1 -1
  40. package/dist/version.d.ts +2 -2
  41. package/dist/version.js +1 -1
  42. package/package.json +1 -1
  43. package/src/change-journal.ts +3 -0
  44. package/src/content.test.ts +54 -0
  45. package/src/content.ts +10 -1
  46. package/src/lists/fields.ts +88 -7
  47. package/src/lists/index.ts +1 -0
  48. package/src/lists/list-type.ts +53 -18
  49. package/src/lists/lists.test.ts +70 -0
  50. package/src/lists/overlay-scope.test.ts +140 -0
  51. package/src/lists/overlay-scope.ts +120 -0
  52. package/src/lists/pagination.test.ts +15 -0
  53. package/src/lists/query-merge.ts +84 -0
  54. package/src/lists/resolve.test.ts +24 -4
  55. package/src/lists/resolve.ts +12 -33
  56. package/src/lists/scope.ts +4 -2
  57. package/src/template-engine-lists.test.ts +27 -1
  58. package/src/template-engine-memory.test.ts +129 -0
  59. package/src/template-engine.ts +72 -3
  60. package/src/version.ts +1 -1
@@ -197,8 +197,20 @@ export function validateFieldValue(field: FieldDef, value: unknown, path: string
197
197
  ? [{ path, message: `"${field.name}" is required (${field.type}) — set a value.` }]
198
198
  : [];
199
199
  }
200
- const bad = (expected: string): ListIssue[] => [
201
- { path, message: `"${field.name}" must be ${expected}, got ${describe(value)}.` },
200
+ // #1265 — for an object-shaped value, say WHAT is wrong in it (the Zod
201
+ // issues) instead of "got object", which names nothing to fix.
202
+ const bad = (
203
+ expected: string,
204
+ error?: z.ZodError,
205
+ keyHints?: Readonly<Record<string, string>>,
206
+ ): ListIssue[] => [
207
+ {
208
+ path,
209
+ message:
210
+ error !== undefined && isPlainObject(value)
211
+ ? `"${field.name}" must be ${expected} — ${describeObjectIssues(error, value, keyHints)}.`
212
+ : `"${field.name}" must be ${expected}, got ${describe(value)}.`,
213
+ },
202
214
  ];
203
215
  switch (field.type) {
204
216
  case "text":
@@ -212,7 +224,9 @@ export function validateFieldValue(field: FieldDef, value: unknown, path: string
212
224
  }
213
225
  case "link": {
214
226
  const r = linkValueSchema.safeParse(value);
215
- return r.success ? [] : bad('{ href, target? } (href like "/about" or "https://…")');
227
+ return r.success
228
+ ? []
229
+ : bad('{ href, target? } (href like "/about" or "https://…")', r.error, LINK_KEY_HINTS);
216
230
  }
217
231
  case "media":
218
232
  return typeof value === "string" && MEDIA_REF_RE.test(value)
@@ -238,10 +252,10 @@ export function validateFieldValue(field: FieldDef, value: unknown, path: string
238
252
  : bad("an ISO date YYYY-MM-DD");
239
253
  case "icon":
240
254
  return typeof value === "string" && ICON_RE.test(value) ? [] : bad("an icon name");
241
- case "module":
242
- return embeddedModuleValueSchema.safeParse(value).success
243
- ? []
244
- : bad("{ moduleId, contentInstanceId }");
255
+ case "module": {
256
+ const r = embeddedModuleValueSchema.safeParse(value);
257
+ return r.success ? [] : bad("{ moduleId, contentInstanceId }", r.error);
258
+ }
245
259
  case "term": {
246
260
  if (
247
261
  !Array.isArray(value) ||
@@ -285,6 +299,73 @@ export function checkFieldDef(field: FieldDef, path: string): ListIssue[] {
285
299
  return issues;
286
300
  }
287
301
 
302
+ /** Keys a link value is often written with instead of `href`. */
303
+ const LINK_KEY_HINTS: Readonly<Record<string, string>> = {
304
+ url: "put the address in href",
305
+ link: "put the address in href",
306
+ path: "put the address in href",
307
+ to: "put the address in href",
308
+ label: "the link text is its own field, not part of the link value",
309
+ text: "the link text is its own field, not part of the link value",
310
+ };
311
+
312
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
313
+ return typeof value === "object" && value !== null && !Array.isArray(value);
314
+ }
315
+
316
+ /**
317
+ * The Zod issues of an object value, in the caller's terms: `unknown key
318
+ * "url" (put the address in href), href missing, target must be "_self" |
319
+ * "_blank" (got "new")`.
320
+ */
321
+ export function describeObjectIssues(
322
+ error: z.ZodError,
323
+ value: Record<string, unknown>,
324
+ keyHints: Readonly<Record<string, string>> = {},
325
+ ): string {
326
+ const parts: string[] = [];
327
+ for (const issue of error.issues) {
328
+ const key = issue.path.map(String).join(".");
329
+ const got = issue.path.length > 0 ? value[String(issue.path[0])] : value;
330
+ switch (issue.code) {
331
+ case "unrecognized_keys":
332
+ for (const k of issue.keys) {
333
+ const hint = keyHints[k];
334
+ parts.push(`unknown key "${k}"${hint ? ` (${hint})` : ""}`);
335
+ }
336
+ break;
337
+ case "invalid_type":
338
+ parts.push(
339
+ got === undefined
340
+ ? `${key} missing`
341
+ : `${key} must be a ${issue.expected}, got ${describe(got)}`,
342
+ );
343
+ break;
344
+ case "invalid_value":
345
+ parts.push(
346
+ `${key} must be ${issue.values.map((v) => JSON.stringify(v)).join(" | ")} (got ${describe(got)})`,
347
+ );
348
+ break;
349
+ case "too_small":
350
+ parts.push(
351
+ typeof got === "string" && got.length === 0
352
+ ? `${key} is empty`
353
+ : `${key} must have at least ${String(issue.minimum)} characters`,
354
+ );
355
+ break;
356
+ case "too_big":
357
+ parts.push(`${key} must have at most ${String(issue.maximum)} characters`);
358
+ break;
359
+ case "invalid_format":
360
+ parts.push(`${key} must be a ${issue.format} (got ${describe(got)})`);
361
+ break;
362
+ default:
363
+ parts.push(key.length > 0 ? `${key}: ${issue.message}` : issue.message);
364
+ }
365
+ }
366
+ return parts.length > 0 ? parts.join(", ") : "an object of another shape";
367
+ }
368
+
288
369
  function describe(value: unknown): string {
289
370
  if (Array.isArray(value)) return "an array";
290
371
  if (value === null) return "null";
@@ -8,6 +8,7 @@ export * from "./fields.js";
8
8
  export * from "./item-attr.js";
9
9
  export * from "./items.js";
10
10
  export * from "./list-type.js";
11
+ export * from "./overlay-scope.js";
11
12
  export * from "./page-type.js";
12
13
  export * from "./paginated-render.js";
13
14
  export * from "./pagination.js";
@@ -82,12 +82,60 @@ export type PageQuery = z.infer<typeof pageQuerySchema>;
82
82
  /** Partial query: defaults on a node, or the knobs an entry overrides. */
83
83
  export const pageQueryPartialSchema = pageQuerySchema.partial();
84
84
 
85
+ /** A complete query source, as the AI-facing examples and refusals show it. */
86
+ export const QUERY_SOURCE_EXAMPLE =
87
+ '{kind:"query", defaults:{page_type:"<slug>", order:"published_desc", limit:10}}';
88
+
89
+ /**
90
+ * The same for a paginated field: no `limit` — `paginate.per_page` is the
91
+ * page size, and a limit next to paginate is refused.
92
+ */
93
+ export const PAGINATED_QUERY_SOURCE_EXAMPLE =
94
+ '{kind:"query", defaults:{page_type:"<slug>", order:"published_desc"}} with paginate:{} on the field (no limit; paginate.per_page is the page size)';
95
+
96
+ /**
97
+ * #1281 — the knobs a query source's `defaults` must carry so it renders
98
+ * without any placement value: `order` always, `limit` unless the field
99
+ * is paginated (its page size is the limit). An editable knob is only an
100
+ * override, never a substitute: a placement that does not set it would
101
+ * leave the query incomplete. Returns the AI-actionable refusal, or null.
102
+ *
103
+ * @param where `"paginated"` — a module list field with `paginate`;
104
+ * `"field"` — any other module list field (may opt into paginate);
105
+ * `"node"` — a list-type node (never paginated).
106
+ */
107
+ export function missingQueryDefaults(
108
+ defaults: { readonly order?: unknown; readonly limit?: unknown },
109
+ where: "paginated" | "field" | "node",
110
+ ): string | null {
111
+ const missing: string[] = [];
112
+ if (defaults.order === undefined) {
113
+ missing.push(
114
+ 'order ("published_desc", "published_asc", "title_asc", or "prop_desc:<property>" / "prop_asc:<property>")',
115
+ );
116
+ }
117
+ if (where !== "paginated" && defaults.limit === undefined) {
118
+ missing.push(
119
+ where === "field"
120
+ ? "limit (1–50; for an overview of every matching page instead: no limit and `paginate:{}` on the list field)"
121
+ : "limit (1–50)",
122
+ );
123
+ }
124
+ if (missing.length === 0) return null;
125
+ const example = where === "paginated" ? PAGINATED_QUERY_SOURCE_EXAMPLE : QUERY_SOURCE_EXAMPLE;
126
+ return `a query source needs ${missing.join(" and ")} in source.defaults — e.g. ${example}.`;
127
+ }
128
+
85
129
  export const sourceDefSchema = z.discriminatedUnion("kind", [
86
130
  z
87
131
  .object({
88
132
  kind: z.literal("query"),
89
- /** Which query parts an editor (or the AI) may set per entry/placement. */
90
- editable: z.array(z.enum(QUERY_KNOBS)).max(QUERY_KNOBS.length),
133
+ /**
134
+ * Which query parts an editor (or the AI) may set per entry/placement.
135
+ * Optional, default none (#1304): most sources fix every knob, and a
136
+ * required empty array only produced refused tool calls.
137
+ */
138
+ editable: z.array(z.enum(QUERY_KNOBS)).max(QUERY_KNOBS.length).default([]),
91
139
  defaults: pageQueryPartialSchema,
92
140
  })
93
141
  .strict(),
@@ -227,22 +275,9 @@ export function checkListTypeDef(def: ListTypeDef): ListIssue[] {
227
275
  const q = pageQueryPartialSchema.safeParse(node.source.defaults);
228
276
  if (!q.success) {
229
277
  issues.push({ path: `${at}.source.defaults`, message: "query defaults are invalid." });
230
- } else if (
231
- node.source.defaults.order === undefined &&
232
- !node.source.editable.includes("order")
233
- ) {
234
- issues.push({
235
- path: `${at}.source`,
236
- message: 'a query source needs a default "order" or "order" in editable.',
237
- });
238
- } else if (
239
- node.source.defaults.limit === undefined &&
240
- !node.source.editable.includes("limit")
241
- ) {
242
- issues.push({
243
- path: `${at}.source`,
244
- message: 'a query source needs a default "limit" or "limit" in editable.',
245
- });
278
+ } else {
279
+ const missing = missingQueryDefaults(node.source.defaults, "node");
280
+ if (missing !== null) issues.push({ path: `${at}.source.defaults`, message: missing });
246
281
  }
247
282
  }
248
283
  }
@@ -112,6 +112,44 @@ describe("field values", () => {
112
112
  expect(validateFieldValue(f, v, "p").length === 0).toBe(ok);
113
113
  }
114
114
  });
115
+ // #1265 — an object value that does not fit says what is wrong in it,
116
+ // not just "got object".
117
+ describe("object-shaped values name the problem", () => {
118
+ const link: FieldDef = { name: "link", label: "Link", type: "link" };
119
+ const mod: FieldDef = { name: "cta", label: "CTA", type: "module" };
120
+ const msg = (f: FieldDef, v: unknown) => validateFieldValue(f, v, "p")[0]?.message ?? "";
121
+
122
+ it("unknown key", () => {
123
+ const m = msg(link, { url: "/about" });
124
+ expect(m).toContain('unknown key "url" (put the address in href)');
125
+ expect(m).toContain("href missing");
126
+ expect(m).not.toContain("got object");
127
+ });
128
+ it("href missing", () => {
129
+ expect(msg(link, { target: "_blank" })).toContain("href missing");
130
+ });
131
+ it("target outside the enum", () => {
132
+ expect(msg(link, { href: "/a", target: "new" })).toContain(
133
+ 'target must be "_self" | "_blank" (got "new")',
134
+ );
135
+ });
136
+ it("href of the wrong type or empty", () => {
137
+ expect(msg(link, { href: 5 })).toContain("href must be a string, got number");
138
+ expect(msg(link, { href: "" })).toContain("href is empty");
139
+ });
140
+ it("a non-object still says what it got", () => {
141
+ expect(msg(link, "/about")).toContain('got "/about"');
142
+ });
143
+ it("module value", () => {
144
+ const m = msg(mod, { moduleId: "x" });
145
+ expect(m).toContain("moduleId must be a uuid");
146
+ expect(m).toContain("contentInstanceId missing");
147
+ expect(msg(mod, { moduleId: PAGE, contentInstanceId: ITEM, extra: 1 })).toContain(
148
+ 'unknown key "extra"',
149
+ );
150
+ });
151
+ });
152
+
115
153
  it("rejects reserved names and invalid defaults", () => {
116
154
  expect(checkFieldDef({ name: "is_open", label: "x", type: "boolean" }, "f")).toHaveLength(1);
117
155
  expect(checkFieldDef({ name: "depth", label: "x", type: "number" }, "f")).toHaveLength(1);
@@ -150,6 +188,34 @@ describe("list type definitions", () => {
150
188
  expect(paths).toContain("nodes.column.current_from");
151
189
  expect(paths).toContain("nodes.column");
152
190
  });
191
+ // #1281 — an editable knob is an override, not a default: an entry that
192
+ // does not set it would leave the query incomplete.
193
+ it("requires order and limit in a query node's defaults, naming the fix", () => {
194
+ const withSource = (source: unknown): ListTypeDef =>
195
+ listTypeDefSchema.parse({
196
+ slug: "teasers",
197
+ name: "Teasers",
198
+ purpose: "p",
199
+ role: "content",
200
+ root: { allow: ["news"] },
201
+ nodes: { news: { label: "News", fields: [], source } },
202
+ });
203
+ const issues = checkListTypeDef(
204
+ withSource({ kind: "query", editable: ["order", "limit"], defaults: { page_type: "news" } }),
205
+ );
206
+ expect(issues).toHaveLength(1);
207
+ expect(issues[0]?.path).toBe("nodes.news.source.defaults");
208
+ expect(issues[0]?.message).toContain("needs order");
209
+ expect(issues[0]?.message).toContain("and limit (1–50) in source.defaults");
210
+ expect(
211
+ checkListTypeDef(
212
+ withSource({
213
+ kind: "query",
214
+ defaults: { page_type: "news", order: "published_desc", limit: 3 },
215
+ }),
216
+ ),
217
+ ).toEqual([]);
218
+ });
153
219
  it("requires name+slug on vocabulary entries", () => {
154
220
  const t: ListTypeDef = {
155
221
  slug: "v",
@@ -318,6 +384,10 @@ describe("page types and addresses", () => {
318
384
  });
319
385
 
320
386
  describe("source definitions", () => {
387
+ it("a query source's editable is optional and means none (#1304)", () => {
388
+ const r = sourceDefSchema.parse({ kind: "query", defaults: { order: "title_asc", limit: 5 } });
389
+ expect(r).toEqual({ kind: "query", editable: [], defaults: { order: "title_asc", limit: 5 } });
390
+ });
321
391
  it("a plugin source written as a system source is refused with the plugin form (PR #1121 e2e)", () => {
322
392
  const r = sourceDefSchema.safeParse({ kind: "system", name: "consent_categories" });
323
393
  expect(r.success).toBe(false);
@@ -0,0 +1,140 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * #1223 — what one previewed page can show from lists: the scope of its
5
+ * `list-resolve` call, or null when it shows nothing an overlay changes.
6
+ */
7
+
8
+ import { describe, expect, it } from "bun:test";
9
+ import type { TemplateField } from "../template-engine.js";
10
+ import type { ListTypeDef } from "./list-type.js";
11
+ import { pageListOverlayScope, type ScopedModule } from "./overlay-scope.js";
12
+ import type { ListPageRecord, ListRenderData } from "./render-data.js";
13
+
14
+ const P = (n: number): string => `00000000-0000-4000-8000-${String(n).padStart(12, "0")}`;
15
+ const CI = "00000000-0000-4000-9000-000000000001";
16
+
17
+ function page(id: string, pageTypeSlug: string): ListPageRecord {
18
+ return {
19
+ id,
20
+ title: id,
21
+ shortTitle: id,
22
+ parentId: null,
23
+ pageTypeSlug,
24
+ properties: {},
25
+ terms: [],
26
+ firstPublishedAt: null,
27
+ updatedAt: "2026-10-01T00:00:00.000Z",
28
+ summary: null,
29
+ image: null,
30
+ inBuild: true,
31
+ } as ListPageRecord;
32
+ }
33
+
34
+ function listType(slug: string, source?: { kind: string; name?: string }): ListTypeDef {
35
+ return {
36
+ slug,
37
+ name: slug,
38
+ purpose: slug,
39
+ role: "content",
40
+ root: { allow: ["entry"] },
41
+ nodes: {
42
+ entry: { label: "Entry", fields: [{ name: "label", label: "Label", type: "text" }] },
43
+ ...(source ? { feed: { label: "Feed", fields: [], source } } : {}),
44
+ },
45
+ } as ListTypeDef;
46
+ }
47
+
48
+ /** P(1) en (product), P(2) de (product), P(3) de (plain), P(4) de (product). */
49
+ const data = {
50
+ listTypes: new Map([
51
+ ["nav", { id: "t1", def: listType("nav") }],
52
+ ["feed", { id: "t2", def: listType("feed", { kind: "query" }) }],
53
+ ["langs", { id: "t3", def: listType("langs", { kind: "plugin", name: "language_links" }) }],
54
+ ]),
55
+ lists: new Map([
56
+ ["l2", { id: "l2", slug: "footer", name: "Footer", typeSlug: "nav", items: [] }],
57
+ ["l1", { id: "l1", slug: "menu", name: "Menu", typeSlug: "nav", items: [] }],
58
+ ]),
59
+ pageTypes: new Map([
60
+ [
61
+ "product",
62
+ {
63
+ id: "pt1",
64
+ def: { slug: "product", properties: [{ name: "tagline", label: "T", type: "text" }] },
65
+ },
66
+ ],
67
+ ["plain", { id: "pt2", def: { slug: "plain", properties: [] } }],
68
+ ]),
69
+ pages: new Map([
70
+ [P(1), page(P(1), "product")],
71
+ [P(2), page(P(2), "product")],
72
+ [P(3), page(P(3), "plain")],
73
+ [P(4), page(P(4), "product")],
74
+ ]),
75
+ media: new Map(),
76
+ pageVariants: new Map([
77
+ [P(1), { variant: "en", group: "g1" }],
78
+ [P(2), { variant: "de", group: "g1" }],
79
+ [P(3), { variant: "de", group: null }],
80
+ [P(4), { variant: "de", group: "g2" }],
81
+ ]),
82
+ siteLanguage: "en",
83
+ homePageId: null,
84
+ } as unknown as ListRenderData;
85
+
86
+ const field = (f: Partial<TemplateField> & { name: string }): TemplateField =>
87
+ ({ kind: "text", ...f }) as TemplateField;
88
+ const mod = (fields: TemplateField[], html = ""): ScopedModule => ({ fields, html });
89
+
90
+ function scopeOf(modules: ScopedModule[], markup: string[] = []) {
91
+ return pageListOverlayScope({
92
+ pageId: P(2),
93
+ data,
94
+ modules,
95
+ markup,
96
+ contentInstanceIds: [CI, CI],
97
+ });
98
+ }
99
+
100
+ describe("pageListOverlayScope (#1223)", () => {
101
+ it("is null for a page that shows no list, no page value and no site text", () => {
102
+ expect(scopeOf([mod([field({ name: "title" })], "<h1>{{title}}</h1>")])).toBeNull();
103
+ });
104
+
105
+ it("covers every shared list, the page's instances and the page itself", () => {
106
+ expect(scopeOf([mod([field({ name: "items", kind: "list", listType: "nav" })])])).toEqual({
107
+ listIds: ["l1", "l2"],
108
+ contentInstanceIds: [CI],
109
+ pageIds: [P(2)],
110
+ });
111
+ });
112
+
113
+ it("counts `page.*` and `site_text.*` in any markup as a list read", () => {
114
+ const plain = [mod([field({ name: "title" })], "<h1>{{title}}</h1>")];
115
+ expect(scopeOf([mod([], "<p>{{ PAGE.props.tagline }}</p>")])?.pageIds).toEqual([P(2)]);
116
+ expect(scopeOf(plain, ["<footer>{{site_text.copyright}}</footer>"])).not.toBeNull();
117
+ });
118
+
119
+ it("adds the variant's pages with properties when a list generates page entries", () => {
120
+ const query = scopeOf([mod([field({ name: "news", kind: "list", listType: "feed" })])]);
121
+ // P(3) has no properties, P(1) is in another variant.
122
+ expect(query?.pageIds).toEqual([P(2), P(4)]);
123
+ const bound = scopeOf([
124
+ mod([
125
+ field({
126
+ name: "kids",
127
+ kind: "list",
128
+ bind: "source",
129
+ source: { kind: "system", name: "children" },
130
+ } as never),
131
+ ]),
132
+ ]);
133
+ expect(bound?.pageIds).toEqual([P(2), P(4)]);
134
+ });
135
+
136
+ it("a plugin source generates no pages", () => {
137
+ const langs = scopeOf([mod([field({ name: "langs", kind: "list", listType: "langs" })])]);
138
+ expect(langs?.pageIds).toEqual([P(2)]);
139
+ });
140
+ });
@@ -0,0 +1,120 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * #1223 — what one page's render can show from lists, so the editor
5
+ * preview asks `list-resolve` for that page's overlay instead of the whole
6
+ * site's (the plugin's answer then costs what the page costs).
7
+ *
8
+ * An overlay is keyed by value address (`list/<listId>/…`,
9
+ * `instance/<ciId>/…`, `page/<pageId>/props/…`, docs/lists.md §9.3). The
10
+ * resolver reads it lazily while the page renders, so the scope has to be
11
+ * known before the render and has to be a SUPERSET of what the render
12
+ * reads; anything more only costs a few rows:
13
+ *
14
+ * - lists: every shared list. A list renders as a whole wherever it is
15
+ * bound (a menu, the site texts, a vocabulary's terms), and their
16
+ * number does not grow with the pages.
17
+ * - content instances: the instances the page renders (its placements
18
+ * and the instances nested in them), whose local lists the overlay
19
+ * translates.
20
+ * - pages: the rendered page (`{{page.props.*}}`) and, when a list on
21
+ * the page generates page entries (a query or a system source:
22
+ * latest news, children, breadcrumbs), every page of the page's
23
+ * variant that has properties. A props overlay only exists for pages
24
+ * of the variant the page renders, and only for page types that
25
+ * declare properties, so no other page can show one.
26
+ *
27
+ * Null when the page shows nothing a list overlay can change: no module
28
+ * on it (placed, chrome, nested or a content variant) has a list field,
29
+ * and no markup reads `page.*` or `site_text.*`. The preview then skips
30
+ * `list-resolve` entirely.
31
+ *
32
+ * The static build asks per page batch with the union of its pages'
33
+ * scopes (#1307, the generator's `list-overlay-batches.ts`), so a build's
34
+ * `list-resolve` reads cost what the batch costs, not the site.
35
+ */
36
+
37
+ import type { TemplateField } from "../template-engine.js";
38
+ import type { ListRenderData } from "./render-data.js";
39
+
40
+ /** The `scope` of a scoped `list-resolve` call (plugin-sdk `listResolveScope`). */
41
+ export interface ListOverlayScope {
42
+ readonly listIds: string[];
43
+ readonly contentInstanceIds: string[];
44
+ readonly pageIds: string[];
45
+ }
46
+
47
+ /** A module field as far as the scope cares (a build's fields may leave `kind` out: text). */
48
+ export type ScopedField = Omit<TemplateField, "kind"> & { readonly kind?: string };
49
+
50
+ /** A module as far as the scope cares: its fields and its markup. */
51
+ export interface ScopedModule {
52
+ readonly fields: readonly ScopedField[];
53
+ readonly html: string;
54
+ }
55
+
56
+ /** What {@link pageListOverlayScope} reads the page from. */
57
+ export interface PageListOverlayInput {
58
+ readonly pageId: string;
59
+ /** The page's list render data before overlays (pages, lists, types, partition). */
60
+ readonly data: ListRenderData;
61
+ /** Every module the page renders: placed, chrome, nested, content variants. */
62
+ readonly modules: Iterable<ScopedModule>;
63
+ /** Markup outside the modules: the template's and the layout's HTML. */
64
+ readonly markup: Iterable<string>;
65
+ /** The stored content instances the page renders (render-local aliases excluded). */
66
+ readonly contentInstanceIds: Iterable<string>;
67
+ }
68
+
69
+ /**
70
+ * `{{page.…}}` / `{{site_text.…}}` (any case, any section operator). A
71
+ * loose match on purpose: a false hit costs one scoped plugin call, a
72
+ * miss would show the page untranslated.
73
+ */
74
+ const LIST_SCOPE_READ_RE = /\b(?:page|site_text)\./i;
75
+
76
+ /** True when the module's markup or fields can read list data. */
77
+ function readsLists(m: ScopedModule): boolean {
78
+ return m.fields.some((f) => f.kind === "list") || LIST_SCOPE_READ_RE.test(m.html);
79
+ }
80
+
81
+ /** True when one of `fields` can generate page entries (a query or system source). */
82
+ function generatesPages(fields: readonly ScopedField[], data: ListRenderData): boolean {
83
+ for (const f of fields) {
84
+ if (f.kind !== "list") continue;
85
+ if (f.bind === "source" && f.source?.kind !== "plugin") return true;
86
+ const type = f.listType === undefined ? undefined : data.listTypes.get(f.listType);
87
+ if (!type) continue;
88
+ for (const node of Object.values(type.def.nodes)) {
89
+ if (node.source && node.source.kind !== "plugin") return true;
90
+ }
91
+ }
92
+ return false;
93
+ }
94
+
95
+ /**
96
+ * The scope of one page's `list-resolve` call, or null when the page
97
+ * shows nothing an overlay can change (see the file header).
98
+ */
99
+ export function pageListOverlayScope(input: PageListOverlayInput): ListOverlayScope | null {
100
+ const { data, pageId } = input;
101
+ const modules = [...input.modules];
102
+ const usesLists =
103
+ modules.some(readsLists) || [...input.markup].some((html) => LIST_SCOPE_READ_RE.test(html));
104
+ if (!usesLists) return null;
105
+
106
+ const pageIds = new Set<string>([pageId]);
107
+ const variant = data.pageVariants?.get(pageId)?.variant;
108
+ if (variant !== undefined && modules.some((m) => generatesPages(m.fields, data))) {
109
+ for (const p of data.pages.values()) {
110
+ if (data.pageVariants?.get(p.id)?.variant !== variant) continue;
111
+ if ((data.pageTypes.get(p.pageTypeSlug)?.def.properties.length ?? 0) === 0) continue;
112
+ pageIds.add(p.id);
113
+ }
114
+ }
115
+ return {
116
+ listIds: [...data.lists.keys()].sort(),
117
+ contentInstanceIds: [...new Set(input.contentInstanceIds)].sort(),
118
+ pageIds: [...pageIds].sort(),
119
+ };
120
+ }
@@ -226,6 +226,21 @@ describe("module field schema", () => {
226
226
  });
227
227
 
228
228
  describe("resolver", () => {
229
+ // #1281 review — a paginated query without order must not be told to add
230
+ // a limit: paginateIssues refuses a limit next to paginate.
231
+ it("a paginated query without order names order, never a limit", () => {
232
+ const noOrder: ListFieldSpec = {
233
+ ...GUIDES,
234
+ source: { kind: "query", editable: [], defaults: { page_type: "guide" } },
235
+ };
236
+ const r = ctxFor(3).resolveField(noOrder, undefined, { contentInstanceId: null });
237
+ expect(r).toMatchObject({ ok: false, marker: "list-malformed:guides[query.order]" });
238
+ const detail = r.ok ? "" : (r.detail ?? "");
239
+ expect(detail).toContain('the query has no "order"');
240
+ expect(detail).toContain("paginate:{}");
241
+ expect(detail).not.toContain("limit:");
242
+ });
243
+
229
244
  it("shows 50 per page by default and records the sequence", () => {
230
245
  const ctx = ctxFor(63);
231
246
  const page1 = resolve(ctx, GUIDES);
@@ -0,0 +1,84 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * Merging a query source's defaults with the knobs an entry or placement
5
+ * sets (`docs/lists.md` §6). A query that does not come out complete is
6
+ * never guessed (CLAUDE.md §2): the render reports
7
+ * `list-malformed:<field>[<path>.<knob>]`, the marker names the failing
8
+ * knob, and `detail` says how to fix it — `preview_list_source` hands it to
9
+ * the AI verbatim (#1281).
10
+ */
11
+
12
+ import {
13
+ PAGINATED_QUERY_SOURCE_EXAMPLE,
14
+ type PageQuery,
15
+ pageQuerySchema,
16
+ QUERY_SOURCE_EXAMPLE,
17
+ type QueryKnob,
18
+ type SourceDef,
19
+ } from "./list-type.js";
20
+
21
+ /** Why a merged query failed: the marker the render reports + the fix. */
22
+ export interface QueryMergeFailure {
23
+ readonly marker: string;
24
+ readonly detail: string;
25
+ }
26
+
27
+ const ORDER_VALUES =
28
+ '"published_desc", "published_asc", "title_asc", "prop_desc:<property>" or "prop_asc:<property>"';
29
+
30
+ /**
31
+ * Merge `source.defaults` with `overrides` (an entry's / placement's knobs)
32
+ * and parse the result as a complete page query.
33
+ *
34
+ * @param field The list field the source belongs to (marker prefix).
35
+ * @param path Where the overrides live (`query`, `<itemId>.query`).
36
+ * @param paginated The field is paginated: its page size is the limit, so
37
+ * the fix never suggests one (a limit next to paginate is refused).
38
+ */
39
+ export function mergeQuerySource(
40
+ source: Extract<SourceDef, { kind: "query" }>,
41
+ overrides: unknown,
42
+ field: string,
43
+ path: string,
44
+ paginated = false,
45
+ ): PageQuery | QueryMergeFailure {
46
+ const fail = (at: string, detail: string): QueryMergeFailure => ({
47
+ marker: `list-malformed:${field}[${at}]`,
48
+ detail,
49
+ });
50
+ const merged: Record<string, unknown> = { ...source.defaults };
51
+ const editable: readonly string[] = source.editable;
52
+ if (overrides !== undefined && overrides !== null) {
53
+ if (typeof overrides !== "object" || Array.isArray(overrides)) {
54
+ return fail(path, "the value of a query field is an object of query knobs, e.g. {limit:3}.");
55
+ }
56
+ for (const [k, v] of Object.entries(overrides)) {
57
+ if (!editable.includes(k as QueryKnob)) {
58
+ return fail(
59
+ `${path}.${k}`,
60
+ `"${k}" cannot be set per entry or placement — the source's editable list is ${editable.length > 0 ? editable.join(", ") : "empty"}. Remove "${k}" from the value, or add it to source.editable.`,
61
+ );
62
+ }
63
+ merged[k] = v;
64
+ }
65
+ }
66
+ const parsed = pageQuerySchema.safeParse(merged);
67
+ if (parsed.success) return parsed.data;
68
+ const issue = parsed.error.issues[0];
69
+ const knob = issue?.path.map(String).join(".") ?? "";
70
+ const at = knob === "" ? path : `${path}.${knob}`;
71
+ if (knob === "order" && merged.order === undefined) {
72
+ return fail(
73
+ at,
74
+ `the query has no "order" — add order (${ORDER_VALUES}) to source.defaults, e.g. ${paginated ? PAGINATED_QUERY_SOURCE_EXAMPLE : QUERY_SOURCE_EXAMPLE}.`,
75
+ );
76
+ }
77
+ if (knob === "limit" && merged.limit === undefined) {
78
+ return fail(
79
+ at,
80
+ `the query has no "limit" — add limit (1–50) to source.defaults, e.g. ${QUERY_SOURCE_EXAMPLE}; for an overview of every matching page, give the list field paginate:{} instead.`,
81
+ );
82
+ }
83
+ return fail(at, `query knob "${knob}" is invalid: ${issue?.message ?? "invalid value"}.`);
84
+ }