@cloudhal/mcp-server 0.4.0 → 0.6.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.
@@ -4,7 +4,7 @@
4
4
  * settings in every mode (a new collection widens what agents may write). `requireRegistered` is
5
5
  * the precheck of every tool that creates an entry: no entries in a collection nobody approved.
6
6
  */
7
-
7
+
8
8
  import {
9
9
 
10
10
  collectionSettings,
@@ -12,6 +12,19 @@ import {
12
12
  MAX_COLLECTIONS,
13
13
  } from "@cloudhal/core-ts/collections";
14
14
  import { collectionPermalink } from "@cloudhal/core-ts/permalinks";
15
+ import {
16
+ describeFieldEdits,
17
+ FIELD_DEFINITIONS_INPUT,
18
+ fieldsView,
19
+ withFields,
20
+ } from "./collection-fields.js";
21
+ import {
22
+ describeListings,
23
+ LISTINGS_INPUT,
24
+ listingsView,
25
+ presetWarnings,
26
+ withListings,
27
+ } from "./collection-listings.js";
15
28
  import {
16
29
  autoSnapshot,
17
30
  id,
@@ -27,6 +40,7 @@ import {
27
40
  } from "./common.js";
28
41
  import { SITE, SNAPSHOT } from "./content-shared.js";
29
42
  import { PERMALINK_PATTERN } from "./permalink-tools.js";
43
+ import { previewStructuredDataTool } from "./structured-data-tools.js";
30
44
 
31
45
  const ICONS = [
32
46
  "article",
@@ -92,7 +106,10 @@ function settingsOf(a , current )
92
106
  for (const k of ["icon", "feed", "sitemap", "sort"] )
93
107
  if (a[k] !== undefined) (next )[k] = a[k];
94
108
  if (typeof a.permalink === "string") next.permalink = a.permalink;
95
- return next;
109
+ const fielded = Array.isArray(a.fields)
110
+ ? withFields(current, next, a.fields )
111
+ : next;
112
+ return withListings(fielded, a);
96
113
  }
97
114
 
98
115
  function withCollection(site , key , settings ) {
@@ -153,7 +170,7 @@ async function check(p , ctx ) {
153
170
  }
154
171
 
155
172
  /** What a person decides on. */
156
- function describe(p , mode ) {
173
+ async function describe(p , mode , ctx ) {
157
174
  const label = p.settings.labels?.[p.site.defaultLocale];
158
175
  const name = label ? `"${label.plural}" (one: "${label.singular}")` : `"${p.key}"`;
159
176
  const s = collectionSettings({ collections: { [p.key]: p.settings } }, p.key);
@@ -167,6 +184,13 @@ function describe(p , mode ) {
167
184
  ];
168
185
  const other = Object.keys(p.settings.labels ?? {}).filter((l) => l !== p.site.defaultLocale);
169
186
  if (other.length) lines.push(` also named in: ${other.join(", ")}`);
187
+ const fields = describeFieldEdits(
188
+ p.existing?.settings?.fields ?? [],
189
+ p.settings.fields ?? [],
190
+ p.site.defaultLocale,
191
+ );
192
+ if (fields) lines.push(fields);
193
+ lines.push(...(await describeListings(ctx, p.next, p.key, p.existing?.settings)));
170
194
  return `${head}\n${lines.join("\n")}`;
171
195
  }
172
196
 
@@ -178,6 +202,10 @@ const COLLECTION_OUT = obj(
178
202
  counts: { type: "object" },
179
203
  permalink: { type: "string" },
180
204
  taxonomies: { type: "array", items: { type: "string" } },
205
+ fields: { type: "array", items: { type: "object" } },
206
+ fieldsSchema: { type: "object" },
207
+ listFields: { type: "array", items: { type: "object" } },
208
+ structuredData: { type: "object" },
181
209
  },
182
210
  ["key", "declared", "settings", "counts", "permalink", "taxonomies"],
183
211
  );
@@ -186,8 +214,11 @@ const listCollectionsTool = {
186
214
  name: "list_collections",
187
215
  title: "List collections",
188
216
  description:
189
- "The site's collections (RFC-0040): declared ones, ones that already have entries, and posts. Each with its names per locale, icon, entry counts by status, its permalink template, feed/sitemap/sort settings (defaults filled in) and the taxonomies that apply. Entries may only be created in these collections; call create_collection for a new one.",
190
- inputSchema: obj({ siteId: id }, ["siteId"]),
217
+ "The site's collections (RFC-0040): declared ones, ones that already have entries, and posts. Each with its names per locale, icon, entry counts by status, its permalink template, feed/sitemap/sort settings (defaults filled in) and the taxonomies that apply. A collection with typed custom fields (RFC-0041) also has `fields` (the definitions) and `fieldsSchema`, the JSON Schema of an entry's `fields` with labels and help in `locale` (default: the site's default locale): read it before create_entry or update_entry with fields. RFC-0042: `listFields` names the fields list_entries and contentList sections may filter (`where`) and sort (`orderBy`) by, each with its operators (`ops`) and whether it sorts; settings.expiry is the collection's date-driven expiry; `structuredData` is the JSON-LD preset's type with every path it offers (required ones, defaults, the sources and vocabulary each takes) and its warnings. Entries may only be created in these collections; call create_collection for a new one.",
218
+ inputSchema: obj(
219
+ { siteId: id, locale: str("BCP 47 locale of field labels and help; default the site's") },
220
+ ["siteId"],
221
+ ),
191
222
  outputSchema: obj({ collections: { type: "array", items: COLLECTION_OUT } }, ["collections"]),
192
223
  annotations: {
193
224
  readOnlyHint: true,
@@ -202,9 +233,12 @@ const listCollectionsTool = {
202
233
  ctx.store.listCollections(site.id),
203
234
  ctx.store.listTaxonomies(site.id),
204
235
  ]);
236
+ const locale = (a.locale ) ?? site.defaultLocale;
205
237
  return {
206
238
  collections: registry.map((c) => ({
207
239
  ...c,
240
+ ...fieldsView(site, c.key, locale),
241
+ ...listingsView(site, c.key),
208
242
  settings: collectionSettings(site, c.key),
209
243
  permalink: collectionPermalink(site, c.key),
210
244
  taxonomies: taxonomies
@@ -223,7 +257,7 @@ function writeTool(mode ) {
223
257
  description:
224
258
  mode === "create"
225
259
  ? "Declare a new collection (RFC-0040), e.g. events, team or jobs, with its names in the site's default locale (labels), an optional icon, permalink (/<prefix>/{slug}, default /<key>/{slug}), feed, sitemap and default sort. Its address may not overlap a page, archive, another collection, /search or a locale prefix. A person who may change site settings approves it in every mode; dryRun: true checks without asking. Then create_entry with this collection. Declaring a collection that already has entries names it."
226
- : "Change a collection's names (merged per locale), icon, feed, sitemap or default sort (RFC-0040). The permalink changes only through set_collection_permalink (it moves URLs). A person who may change site settings approves it; dryRun: true checks without asking.",
260
+ : "Change a collection's names (merged per locale), icon, feed, sitemap, default sort (RFC-0040) or its typed custom fields (`fields`, the whole list; RFC-0041), list fields, date-driven expiry and JSON-LD preset (`listFields`, `expiry`, `structuredData`; RFC-0042; null removes one). Field edits that keep every stored value are free here; renaming a key, changing a type, localization or multiple, and dropping a key or option still in use are refused (field_change_needs_operation) and go through rename_field, change_field_type, set_field_localized or remove_field. The permalink changes only through set_collection_permalink (it moves URLs). A person who may change site settings approves it; dryRun: true checks without asking.",
227
261
  inputSchema: obj(
228
262
  {
229
263
  siteId: id,
@@ -232,6 +266,7 @@ function writeTool(mode ) {
232
266
  maxLength: 64,
233
267
  }),
234
268
  ...SETTINGS_INPUT,
269
+ ...(mode === "update" ? { fields: FIELD_DEFINITIONS_INPUT, ...LISTINGS_INPUT } : {}),
235
270
  ...(mode === "create"
236
271
  ? {
237
272
  permalink: str("Template, e.g. /etkinlik/{slug}; default /<key>/{slug}", {
@@ -247,7 +282,13 @@ function writeTool(mode ) {
247
282
  mode === "create" ? ["siteId", "collection", "labels"] : ["siteId", "collection"],
248
283
  ),
249
284
  outputSchema: obj(
250
- { prompt: { type: "string" }, dryRun: { type: "boolean" }, site: SITE, snapshot: SNAPSHOT },
285
+ {
286
+ prompt: { type: "string" },
287
+ dryRun: { type: "boolean" },
288
+ site: SITE,
289
+ snapshot: SNAPSHOT,
290
+ warnings: { type: "array", items: { type: "object" } },
291
+ },
251
292
  ["prompt", "dryRun"],
252
293
  ),
253
294
  annotations: {
@@ -262,13 +303,15 @@ function writeTool(mode ) {
262
303
  requiresApproval: true,
263
304
  classify: (a) => (a.dryRun === true ? "read" : "person"),
264
305
  precheck: async (a, ctx) => check(await planFor(a, ctx, mode), ctx),
265
- approvalPrompt: async (a, ctx) => describe(await planFor(a, ctx, mode), mode),
306
+ approvalPrompt: async (a, ctx) => describe(await planFor(a, ctx, mode), mode, ctx),
266
307
  handler: async (a, ctx) => {
267
308
  const p = await planFor(a, ctx, mode);
268
- const prompt = describe(p, mode);
309
+ const prompt = await describe(p, mode, ctx);
310
+ const warnings = presetWarnings(p.next, p.key);
311
+ const warned = warnings.length ? { warnings } : {};
269
312
  if (a.dryRun === true) {
270
313
  await check(p, ctx);
271
- return { prompt, dryRun: true };
314
+ return { prompt, dryRun: true, ...warned };
272
315
  }
273
316
  let site ;
274
317
  try {
@@ -277,11 +320,11 @@ function writeTool(mode ) {
277
320
  throw toToolError(e);
278
321
  }
279
322
  const snapshot = await autoSnapshot(ctx, site.id, name);
280
- return { prompt, dryRun: false, site, snapshot };
323
+ return { prompt, dryRun: false, site, snapshot, ...warned };
281
324
  },
282
325
  };
283
326
  }
284
327
 
285
328
  export function collectionTools() {
286
- return [listCollectionsTool, writeTool("create"), writeTool("update")];
329
+ return [listCollectionsTool, writeTool("create"), writeTool("update"), previewStructuredDataTool];
287
330
  }
@@ -31,6 +31,7 @@ import {
31
31
 
32
32
  import { ScheduleConflictError, ScheduleError } from "@cloudhal/schedules";
33
33
 
34
+ import { fieldHint } from "./field-hints.js";
34
35
 
35
36
  import { ScheduleRequestError, } from "./schedules.js";
36
37
 
@@ -374,6 +375,8 @@ export async function autoSnapshot(
374
375
 
375
376
  /** What to do next, per invariant (RFC-0002 §3). */
376
377
  function invariantHint(e ) {
378
+ const field = fieldHint(e.code, e.details);
379
+ if (field) return field;
377
380
  const key = typeof e.details.taxonomy === "string" ? e.details.taxonomy : undefined;
378
381
  switch (e.code) {
379
382
  case "required_term":
@@ -0,0 +1,35 @@
1
+ /**
2
+ * RFC-0041 §3, §8: typed custom field values over MCP. `create_entry` and `update_entry` check
3
+ * them in `precheck` with the store's own checker (changed keys only, unknown keys, a translation's
4
+ * copy of a non-localized value, `requiredToPublish` for review and published, image and `asset:`
5
+ * references), so a call that the store would refuse never reaches a person. `update_entry` takes
6
+ * `fields` as a merge patch (`null` removes a key), and its approval prompt names each typed change
7
+ * readably: labels, option labels, dates in their zone, values quoted and truncated.
8
+ */
9
+ import type { ContentEntry, FieldDefinition, Site } from "@cloudhal/core-contracts";
10
+ import { type JsonSchema, type ToolContext } from "./common.js";
11
+ type Values = Record<string, unknown>;
12
+ /** `create_entry`'s `fields`: a static schema cannot vary by site, so it points to list_collections. */
13
+ export declare const FIELDS_INPUT: JsonSchema;
14
+ /** `update_entry`'s `fields`: a merge patch. */
15
+ export declare const FIELDS_PATCH: JsonSchema;
16
+ /** The stored `fields` with `patch` applied: `null` removes a key. */
17
+ export declare function mergeFields(current: Values | undefined, patch: Values): Values;
18
+ /** What an entry write would store, for the check. */
19
+ export interface FieldsCheck {
20
+ site: Site;
21
+ /** The entry as it would be written (its `fields` after the patch). */
22
+ next: Pick<ContentEntry, "id" | "siteId" | "collection" | "fields" | "status" | "translation">;
23
+ /** The stored entry (absent for a new one). */
24
+ stored?: Pick<ContentEntry, "collection" | "fields"> | undefined;
25
+ }
26
+ /**
27
+ * The store's field checks, run before anyone is asked: throws `invalid_fields`, `unknown_field`,
28
+ * `field_not_localized`, `required_field` or `too_large` with every issue at its path.
29
+ */
30
+ export declare function checkEntryFields(ctx: ToolContext, check: FieldsCheck): Promise<void>;
31
+ /** A value as a person reads it in an approval prompt (agent text quoted and truncated). */
32
+ export declare function describeFieldValue(def: FieldDefinition | undefined, value: unknown, locale: string): string;
33
+ /** "startsAt → 5 Nov 2026 19:30 Istanbul, format → Talk, Workshop, notes removed". */
34
+ export declare function describeFieldPatch(site: Site, collection: string, patch: Values): string;
35
+ export {};
@@ -0,0 +1,188 @@
1
+ /**
2
+ * RFC-0041 §3, §8: typed custom field values over MCP. `create_entry` and `update_entry` check
3
+ * them in `precheck` with the store's own checker (changed keys only, unknown keys, a translation's
4
+ * copy of a non-localized value, `requiredToPublish` for review and published, image and `asset:`
5
+ * references), so a call that the store would refuse never reaches a person. `update_entry` takes
6
+ * `fields` as a merge patch (`null` removes a key), and its approval prompt names each typed change
7
+ * readably: labels, option labels, dates in their zone, values quoted and truncated.
8
+ */
9
+
10
+ import {
11
+ checkFieldValues,
12
+ checkRequiredToPublish,
13
+ convertContext,
14
+ fieldDefinitions,
15
+ fieldLabel,
16
+ normalizeThroughMarkers,
17
+ optionLabel,
18
+ refuseFieldIssues,
19
+ } from "@cloudhal/core-ts/fields";
20
+ import { fieldAssetIssues, fieldAssetRefs } from "@cloudhal/core-ts/media";
21
+ import { quote, } from "./common.js";
22
+
23
+
24
+
25
+ /** `create_entry`'s `fields`: a static schema cannot vary by site, so it points to list_collections. */
26
+ export const FIELDS_INPUT = {
27
+ type: "object",
28
+ description:
29
+ "Typed custom fields of the collection: read its fieldsSchema from list_collections first (keys, types, allowed values, limits). A collection without field definitions takes any JSON here.",
30
+ };
31
+
32
+ /** `update_entry`'s `fields`: a merge patch. */
33
+ export const FIELDS_PATCH = {
34
+ type: "object",
35
+ description:
36
+ "Typed custom fields to change, as a merge patch: given keys are set, null removes a key, others stay. The collection's fieldsSchema (list_collections) lists the keys and allowed values.",
37
+ };
38
+
39
+ /** The stored `fields` with `patch` applied: `null` removes a key. */
40
+ export function mergeFields(current , patch ) {
41
+ const next = { ...(current ?? {}) };
42
+ for (const [key, value] of Object.entries(patch)) {
43
+ if (value === null) delete next[key];
44
+ else next[key] = value;
45
+ }
46
+ return next;
47
+ }
48
+
49
+ const isTranslation = (e ) =>
50
+ !!e.translation && e.translation.group !== e.id && e.translation.source?.siteId === undefined;
51
+
52
+ /** The same-site original of a translation (as the store reads it). */
53
+ async function originalOf(
54
+ ctx ,
55
+ entry ,
56
+ ) {
57
+ if (!isTranslation(entry)) return undefined;
58
+ const original = await ctx.store.getContentEntry(entry.translation?.group );
59
+ return original?.siteId === entry.siteId ? original : undefined;
60
+ }
61
+
62
+ /** What an entry write would store, for the check. */
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+ /**
72
+ * The store's field checks, run before anyone is asked: throws `invalid_fields`, `unknown_field`,
73
+ * `field_not_localized`, `required_field` or `too_large` with every issue at its path.
74
+ */
75
+ export async function checkEntryFields(ctx , check ) {
76
+ const { site, stored } = check;
77
+ let next = check.next;
78
+ const defs = fieldDefinitions(site, next.collection);
79
+ // While a field operation runs, a write goes through its marker (as the store normalizes it).
80
+ if (defs.some((d) => d.migration)) {
81
+ const fields = normalizeThroughMarkers(defs, next.fields, {
82
+ convert: convertContext(site),
83
+ translation: isTranslation(next),
84
+ });
85
+ if (fields) next = { ...next, fields };
86
+ }
87
+ const values = next.fields ?? {};
88
+ const previous = stored?.collection === next.collection ? (stored.fields ?? {}) : undefined;
89
+ if (defs.length === 0) {
90
+ if (!previous || JSON.stringify(previous) !== JSON.stringify(values))
91
+ refuseFieldIssues(checkFieldValues([], { values }));
92
+ return;
93
+ }
94
+ const original = await originalOf(ctx, next);
95
+ const issues = checkFieldValues(defs, {
96
+ values,
97
+ previous,
98
+ original: original ? { id: original.id, values: original.fields ?? {} } : undefined,
99
+ blocks: ctx.store.blocks,
100
+ });
101
+ // The store's asset check: new references name usable files of the site.
102
+ issues.push(
103
+ ...(await fieldAssetIssues({
104
+ defs,
105
+ refs: fieldAssetRefs(defs, values),
106
+ kept: stored ? fieldAssetRefs(fieldDefinitions(site, stored.collection), stored.fields) : [],
107
+ lookup: (ids) => ctx.store.getAssets(site.id, ids),
108
+ skip: new Set(issues.map((i) => i.path.split("/").slice(0, 2).join("/"))),
109
+ })),
110
+ );
111
+ issues.push(...checkRequiredToPublish(site, { ...next, fields: values }, original));
112
+ refuseFieldIssues(issues);
113
+ }
114
+
115
+ /** "5 Nov 2026" (a calendar day: no zone). */
116
+ function day(value ) {
117
+ const d = new Date(`${value}T00:00:00Z`);
118
+ if (Number.isNaN(d.getTime())) return quote(value);
119
+ return new Intl.DateTimeFormat("en-GB", {
120
+ day: "numeric",
121
+ month: "short",
122
+ year: "numeric",
123
+ timeZone: "UTC",
124
+ }).format(d);
125
+ }
126
+
127
+ /** "5 Nov 2026 19:30 Istanbul" (the wall clock in the value's own zone). */
128
+ function instant(value ) {
129
+ const v = value ;
130
+ if (typeof v?.at !== "string" || typeof v.timeZone !== "string") return quote(JSON.stringify(v));
131
+ const at = new Date(v.at);
132
+ if (Number.isNaN(at.getTime())) return quote(v.at);
133
+ try {
134
+ const parts = new Intl.DateTimeFormat("en-GB", {
135
+ day: "numeric",
136
+ month: "short",
137
+ year: "numeric",
138
+ hour: "2-digit",
139
+ minute: "2-digit",
140
+ hourCycle: "h23",
141
+ timeZone: v.timeZone,
142
+ }).format(at);
143
+ const city = (v.timeZone.split("/").pop() ?? v.timeZone).replace(/_/g, " ");
144
+ return `${parts.replace(",", "")} ${city}`;
145
+ } catch {
146
+ return `${quote(v.at)} ${quote(v.timeZone)}`;
147
+ }
148
+ }
149
+
150
+ /** A value as a person reads it in an approval prompt (agent text quoted and truncated). */
151
+ export function describeFieldValue(
152
+ def ,
153
+ value ,
154
+ locale ,
155
+ ) {
156
+ if (!def) return `"${quote(JSON.stringify(value) ?? "")}"`;
157
+ switch (def.type) {
158
+ case "number":
159
+ return typeof value === "number" ? String(value) : `"${quote(String(value))}"`;
160
+ case "boolean":
161
+ return value === true ? "yes" : "no";
162
+ case "date":
163
+ return typeof value === "string" ? day(value) : `"${quote(String(value))}"`;
164
+ case "datetime":
165
+ return instant(value);
166
+ case "select": {
167
+ const list = Array.isArray(value) ? value : [value];
168
+ return list.map((v) => quote(optionLabel(def, String(v), locale, locale))).join(", ");
169
+ }
170
+ default:
171
+ return `"${quote(typeof value === "string" ? value : JSON.stringify(value))}"`;
172
+ }
173
+ }
174
+
175
+ /** "startsAt → 5 Nov 2026 19:30 Istanbul, format → Talk, Workshop, notes removed". */
176
+ export function describeFieldPatch(site , collection , patch ) {
177
+ const defs = new Map(fieldDefinitions(site, collection).map((d) => [d.key, d]));
178
+ const locale = site.defaultLocale;
179
+ return Object.entries(patch)
180
+ .map(([key, value]) => {
181
+ const def = defs.get(key);
182
+ const name = def ? `"${quote(fieldLabel(def, locale, locale), 40)}" (${key})` : key;
183
+ return value === null
184
+ ? `${name} removed`
185
+ : `${name} → ${describeFieldValue(def, value, locale)}`;
186
+ })
187
+ .join(", ");
188
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * RFC-0042 §4 "API and MCP" for `list_entries`: `where` and `orderBy` over a collection's list
3
+ * fields, run by core-ts's shared evaluator (`queryContentEntries`), and `limit`/`cursor` paging.
4
+ * Without `orderBy` the list keeps its order (last updated first); without `limit` it is unpaged,
5
+ * as before. Problems are refused as `invalid_query` with their paths (`where/0/value`).
6
+ */
7
+ import type { ContentEntry } from "@cloudhal/core-contracts";
8
+ import { type EntryQuery } from "@cloudhal/core-ts";
9
+ import type { JsonSchema, ToolContext } from "./common.js";
10
+ export declare const ENTRY_QUERY_INPUT: Record<string, JsonSchema>;
11
+ export interface EntryListAnswer {
12
+ entries: ContentEntry[];
13
+ total?: number;
14
+ nextCursor?: string;
15
+ }
16
+ /** The entries of `base` matching the call's field query, ordered and paged. */
17
+ export declare function listEntries(ctx: ToolContext, siteId: string, base: EntryQuery, a: Record<string, unknown>): Promise<EntryListAnswer>;
@@ -0,0 +1,98 @@
1
+ /**
2
+ * RFC-0042 §4 "API and MCP" for `list_entries`: `where` and `orderBy` over a collection's list
3
+ * fields, run by core-ts's shared evaluator (`queryContentEntries`), and `limit`/`cursor` paging.
4
+ * Without `orderBy` the list keeps its order (last updated first); without `limit` it is unpaged,
5
+ * as before. Problems are refused as `invalid_query` with their paths (`where/0/value`).
6
+ */
7
+
8
+ import { SiteSchema } from "@cloudhal/core-contracts";
9
+ import { InvariantError, queryContentEntries } from "@cloudhal/core-ts";
10
+
11
+
12
+ const DEFS = SiteSchema.$defs ;
13
+
14
+ export const ENTRY_QUERY_INPUT = {
15
+ where: {
16
+ type: "array",
17
+ minItems: 1,
18
+ maxItems: 4,
19
+ items: { $ref: "#/$defs/FieldCondition" },
20
+ description:
21
+ 'Conditions on the collection\'s list fields (list_collections → listFields, with each field\'s ops), ANDed, e.g. [{"field":"startsAt","op":"gte","value":"now"},{"field":"format","op":"in","values":["talk"]}]. Values are strings read by the field\'s type: a number, YYYY-MM-DD, an RFC 3339 instant, true/false, an option value, or now',
22
+ $defs: { FieldCondition: DEFS.FieldCondition },
23
+ },
24
+ orderBy: {
25
+ $ref: "#/$defs/FieldOrder",
26
+ description:
27
+ 'Order by a number, date or datetime list field, e.g. {"field":"startsAt","direction":"asc"}; entries without a value come last',
28
+ $defs: { FieldOrder: DEFS.FieldOrder },
29
+ },
30
+ limit: {
31
+ type: "integer",
32
+ minimum: 1,
33
+ maximum: 100,
34
+ description: "Page size; the answer then has total and, when more follow, nextCursor",
35
+ },
36
+ cursor: {
37
+ type: "string",
38
+ minLength: 1,
39
+ maxLength: 32,
40
+ description: "nextCursor from the previous page (same arguments otherwise)",
41
+ },
42
+ };
43
+
44
+ const refuse = (path , message ) => {
45
+ throw new InvariantError("invalid_query", `${path}: ${message}`, {
46
+ issues: [{ path, code: "invalid_query", message }],
47
+ });
48
+ };
49
+
50
+ /** An opaque cursor: the offset of the next page (the API's form). */
51
+ const encodeCursor = (offset ) => btoa(`o:${offset}`).replace(/=+$/, "");
52
+ function decodeCursor(raw ) {
53
+ let text = "";
54
+ try {
55
+ text = atob(raw);
56
+ } catch {
57
+ // refused below
58
+ }
59
+ const m = /^o:(\d{1,9})$/.exec(text);
60
+ return m ? Number(m[1]) : refuse("cursor", "not a cursor this list returned");
61
+ }
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+ const byUpdated = (x , y ) => y.updatedAt.localeCompare(x.updatedAt);
70
+
71
+ /** The entries of `base` matching the call's field query, ordered and paged. */
72
+ export async function listEntries(
73
+ ctx ,
74
+ siteId ,
75
+ base ,
76
+ a ,
77
+ ) {
78
+ const where = a.where ;
79
+ const orderBy = a.orderBy ;
80
+ const limit = a.limit ;
81
+ if (a.cursor !== undefined && limit === undefined) refuse("cursor", "a cursor needs limit");
82
+ const offset = a.cursor === undefined ? 0 : decodeCursor(a.cursor );
83
+ const { entries } = await queryContentEntries(ctx.store, siteId, {
84
+ ...base,
85
+ ...(where ? { where } : {}),
86
+ ...(orderBy ? { orderBy } : {}),
87
+ now: (ctx.now?.() ?? new Date()).getTime(),
88
+ });
89
+ const ordered = orderBy ? entries : entries.sort(byUpdated);
90
+ if (limit === undefined) return { entries: ordered };
91
+ const page = ordered.slice(offset, offset + limit);
92
+ const next = offset + page.length;
93
+ return {
94
+ entries: page,
95
+ total: ordered.length,
96
+ ...(next < ordered.length ? { nextCursor: encodeCursor(next) } : {}),
97
+ };
98
+ }