@cloudhal/astro-renderer 0.8.0 → 0.9.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.
@@ -0,0 +1,346 @@
1
+ /**
2
+ * RFC-0045 §4 in the renderer: reference cards, and the indexes both sources answer
3
+ * `groupMembers` and `referencedBy` from.
4
+ *
5
+ * - **Cards** (`referenceCards`): breadth-first over the groups a page's values name, one
6
+ * `groupMembers` call per level (the live source: one store read; the snapshot: none). The member
7
+ * shown is `pickMember`'s, among the members the source's *view* shows (gates applied at its
8
+ * instant). Depth 1 (default) yields cards; depth 2 adds each card's own fields, whose references
9
+ * are cards without fields. Groups are fetched once (the visited set), so cycles cost nothing.
10
+ * Every card spends one of the request's 200 targets (`PlaceholderBudget.references`); past it
11
+ * the rest resolve to nothing, with one `console.warn` per request.
12
+ * - **Indexes** (`ReferenceIndex`, snapshot only): members by group and referrers by group over the
13
+ * snapshot's published entries, gate-independent and built once per snapshot and isolate; every
14
+ * lookup then filters through the asking view.
15
+ * - **`referencedBy`** equals the resolved values: a referrer is an entry whose `resolveFields`
16
+ * names the group, with its same-site original while the view shows it and without it otherwise
17
+ * (exactly what its page reads), the running conversions' maps included. The live source finds candidates in
18
+ * `entry_refs` and resolves them the same way (`referrerRecords`), so both answer alike.
19
+ */
20
+
21
+ import {
22
+
23
+ isReferenceFieldType,
24
+ membersByGroup,
25
+ originalsOf,
26
+ pickMember,
27
+
28
+
29
+ referenceUses,
30
+ resolveFields,
31
+ } from "@cloudhal/core-ts/fields";
32
+ import { itemUrl } from "@cloudhal/core-ts/locale-paths";
33
+ import { entryPath } from "@cloudhal/core-ts/permalinks";
34
+
35
+ import { REFERENCE_BUDGET } from "./media.js";
36
+ import { conversionsFor } from "./reference-conversions.js";
37
+ import { byNewest } from "./source-helpers.js";
38
+
39
+ /** A referenced entry as a theme draws it: a card of the member the page's view shows. */
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+ /** `referencedBy`'s filters. */
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+
73
+
74
+ export const REFERENCED_BY_LIMIT = 100;
75
+
76
+ /** What `referenceCards` needs from `entryFields`: the page, its budget and its media. */
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+
91
+
92
+
93
+ /** The reference values under resolved fields, top-level and inside repeater items, in order. */
94
+ export function usesOf(resolved ) {
95
+ return Object.entries(resolved).flatMap(([key, f]) =>
96
+ isReferenceFieldType(f.def.type) ? referenceUses(f.def, f.value, `fields/${key}`) : [],
97
+ );
98
+ }
99
+
100
+ /** One target spent; false (logged once per budget) when none are left. */
101
+ function spend(budget ) {
102
+ budget.references ??= REFERENCE_BUDGET;
103
+ if (budget.references > 0) {
104
+ budget.references--;
105
+ return true;
106
+ }
107
+ if (!budget.referencesWarned) {
108
+ budget.referencesWarned = true;
109
+ console.warn(
110
+ `cloudhal: more than ${REFERENCE_BUDGET} reference targets on one page; the rest render nothing`,
111
+ );
112
+ }
113
+ return false;
114
+ }
115
+
116
+
117
+
118
+
119
+
120
+
121
+
122
+ /** Fetches the groups not fetched yet, in one `groupMembers` call. */
123
+ async function visit(level , uses ) {
124
+ const missing = [...new Set(uses.map((u) => u.groupId))].filter((g) => !level.members.has(g));
125
+ const groupMembers = level.input.source.groupMembers;
126
+ if (missing.length === 0 || !groupMembers) return;
127
+ const got = await groupMembers.call(level.input.source, missing);
128
+ for (const g of missing) level.members.set(g, got.get(g) ?? []);
129
+ }
130
+
131
+
132
+
133
+ /** The cards of `uses` (spending the budget in order); unresolved uses get none. */
134
+ async function cardsOf(level , uses ) {
135
+ const { site, locale, budget, cover } = level.input;
136
+ const out = [];
137
+ for (const use of uses) {
138
+ const picked = pickMember(use.groupId, level.members.get(use.groupId) ?? [], {
139
+ locale,
140
+ defaultLocale: site.defaultLocale,
141
+ fallback: site.localization?.fallback,
142
+ collections: use.collections,
143
+ });
144
+ if (!picked || !spend(budget)) continue;
145
+ const m = picked.member;
146
+ const image = await cover(m);
147
+ const card = {
148
+ groupId: use.groupId,
149
+ id: m.id,
150
+ collection: m.collection,
151
+ locale: m.locale,
152
+ slug: m.slug,
153
+ title: m.title,
154
+ ...(m.summary ? { summary: m.summary } : {}),
155
+ path: entryPath(site, m),
156
+ url: itemUrl(site, undefined, m),
157
+ ...(image ? { image } : {}),
158
+ fromFallbackLocale: picked.fromFallbackLocale,
159
+ };
160
+ out.push({ use, member: m, card });
161
+ }
162
+ return out;
163
+ }
164
+
165
+ /** A member's same-site original among the members the view shows (RFC-0041 §5). */
166
+ function originalIn(level , member ) {
167
+ const g = member.translation?.group;
168
+ if (!g || g === member.id || member.translation?.source?.siteId !== undefined) return undefined;
169
+ return level.members.get(g)?.find((m) => m.id === g);
170
+ }
171
+
172
+ /**
173
+ * The cards of an entry's resolved values, by value path (`fields/venue`, `fields/speakers/0/
174
+ * person`). Without `groupMembers` (sources from before RFC-0045) nothing resolves.
175
+ */
176
+ export async function referenceCards(
177
+ input ,
178
+ resolved ,
179
+ ) {
180
+ const out = new Map ();
181
+ const uses = usesOf(resolved);
182
+ if (uses.length === 0 || !input.source.groupMembers) return out;
183
+ const level = { input, members: new Map() };
184
+ await visit(level, uses);
185
+ const first = await cardsOf(level, uses);
186
+ for (const p of first) out.set(p.use.path, p.card);
187
+ if (input.depth !== 2 || first.length === 0) return out;
188
+ // Level 2: each shown member's own fields, its references as cards without fields.
189
+ const members = [...new Map(first.map((p) => [p.member.id, p.member])).values()];
190
+ const resolvedOf = new Map ();
191
+ for (const m of members) {
192
+ const entries = await conversionsFor(input.source, input.site, m.collection);
193
+ const r = resolveFields(input.site, m, originalIn(level, m), entries ? { entries } : undefined);
194
+ resolvedOf.set(m.id, r);
195
+ }
196
+ await visit(level, [...resolvedOf.values()].flatMap(usesOf));
197
+ const fieldsOf = new Map ();
198
+ for (const m of members) {
199
+ const r = resolvedOf.get(m.id) ?? {};
200
+ const inner = await cardsOf(level, usesOf(r));
201
+ fieldsOf.set(m.id, await input.render(r, new Map(inner.map((p) => [p.use.path, p.card]))));
202
+ }
203
+ for (const p of first) {
204
+ const fields = fieldsOf.get(p.member.id);
205
+ if (fields) p.card.fields = fields;
206
+ }
207
+ return out;
208
+ }
209
+
210
+ /**
211
+ * One referrer of a group: the entry and the field whose resolved value names it. A same-site
212
+ * translation resolves through its original only while the view shows that original (its page
213
+ * reads it through the gated `entryById`), so its records carry which way they hold.
214
+ */
215
+
216
+
217
+
218
+
219
+
220
+
221
+
222
+
223
+
224
+
225
+ /** The conversion maps by collection, for collections that run a conversion (§7). */
226
+
227
+
228
+ /**
229
+ * Referrers by group from `entries`' resolved values, with `only` just that group's; the snapshot
230
+ * index and the live source share it. An entry with an original in `originalOf`'s pool is
231
+ * resolved both with it and without it, so `referrersIn` can follow the view's choice.
232
+ */
233
+ export function referrerRecords(
234
+ site ,
235
+ entries ,
236
+ input
237
+
238
+
239
+
240
+ ,
241
+ ) {
242
+ const out = new Map ();
243
+ const add = (entry , original , cond ) => {
244
+ const maps = input.maps?.get(entry.collection);
245
+ const resolved = resolveFields(site, entry, original, maps ? { entries: maps } : undefined);
246
+ for (const [key, f] of Object.entries(resolved)) {
247
+ if (!isReferenceFieldType(f.def.type)) continue;
248
+ for (const g of new Set(referenceUses(f.def, f.value, "").map((u) => u.groupId))) {
249
+ if (input.only !== undefined && g !== input.only) continue;
250
+ const list = out.get(g) ?? [];
251
+ list.push({ entry, field: key, ...cond });
252
+ out.set(g, list);
253
+ }
254
+ }
255
+ };
256
+ for (const entry of entries) {
257
+ const original = input.originalOf(entry);
258
+ if (!original) add(entry, undefined, {});
259
+ else {
260
+ add(entry, original, { withOriginal: original.id });
261
+ add(entry, undefined, { withoutOriginal: original.id });
262
+ }
263
+ }
264
+ return out;
265
+ }
266
+
267
+ const idSets = new WeakMap ();
268
+ /** The ids of a view's entry list, built once per list. */
269
+ function idsOf(list ) {
270
+ let ids = idSets.get(list);
271
+ if (!ids) {
272
+ ids = new Set(list.map((e) => e.id));
273
+ idSets.set(list, ids);
274
+ }
275
+ return ids;
276
+ }
277
+
278
+ /** What a view shows: `listed` for "used by" lists, `reachable` for resolution and originals. */
279
+
280
+
281
+
282
+
283
+
284
+ /** `referencedBy` over records: shown referrers, filtered, newest first, at most 100. */
285
+ export function referrersIn(
286
+ records ,
287
+ q ,
288
+ view ,
289
+ ) {
290
+ const listed = idsOf(view.listed);
291
+ const reachable = idsOf(view.reachable);
292
+ const out = new Map ();
293
+ for (const r of records) {
294
+ const e = r.entry;
295
+ if (q.collection !== undefined && e.collection !== q.collection) continue;
296
+ if (q.field !== undefined && r.field !== q.field) continue;
297
+ if (q.locale !== undefined && e.locale !== q.locale) continue;
298
+ if (!listed.has(e.id)) continue;
299
+ if (r.withOriginal !== undefined && !reachable.has(r.withOriginal)) continue;
300
+ if (r.withoutOriginal !== undefined && reachable.has(r.withoutOriginal)) continue;
301
+ out.set(e.id, e);
302
+ }
303
+ const limit = Math.max(0, Math.min(q.limit ?? REFERENCED_BY_LIMIT, REFERENCED_BY_LIMIT));
304
+ // A total order, so both sources agree on order and on what `limit` keeps.
305
+ return [...out.values()]
306
+ .sort((a, b) => byNewest(a, b) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
307
+ .slice(0, limit);
308
+ }
309
+
310
+ /** The members of `ids` among a view's reachable entries (every id gets a list). */
311
+ export function membersIn(
312
+ all ,
313
+ ids ,
314
+ view ,
315
+ ) {
316
+ const reachable = idsOf(view.reachable);
317
+ return new Map(ids.map((g) => [g, (all.get(g) ?? []).filter((m) => reachable.has(m.id))]));
318
+ }
319
+
320
+ /** A snapshot's gate-independent indexes over its published entries, each built on first use. */
321
+ export class ReferenceIndex {
322
+ #site ;
323
+ #published ;
324
+ #maps ;
325
+ #members ;
326
+ #referrers ;
327
+
328
+ constructor(site , published , maps ) {
329
+ this.#site = site;
330
+ this.#published = published;
331
+ this.#maps = maps;
332
+ }
333
+
334
+ members() {
335
+ this.#members ??= membersByGroup(this.#published);
336
+ return this.#members;
337
+ }
338
+
339
+ referrers(group ) {
340
+ this.#referrers ??= referrerRecords(this.#site, this.#published, {
341
+ originalOf: originalsOf(this.#published),
342
+ maps: this.#maps,
343
+ });
344
+ return this.#referrers.get(group) ?? [];
345
+ }
346
+ }
@@ -1,10 +1,12 @@
1
1
  import type { Asset, ContentEntry, Menu, Page, Redirect, Site, Snapshot, Taxonomy, Term } from "@cloudhal/core-contracts";
2
2
  import type { RedirectMatch, SearchKind, SearchResults, SiteGraphStore } from "@cloudhal/core-ts";
3
- import { type DerivedGate, type ResolvedFields } from "@cloudhal/core-ts/fields";
3
+ import { type ConversionEntries, type DerivedGate, type ResolvedFields } from "@cloudhal/core-ts/fields";
4
4
  import { type FieldEntryQuery, type FieldEntryResult } from "./entry-query.js";
5
5
  import { type EntryFieldsOptions, type RenderedFields } from "./fields.js";
6
6
  import { type Navigation, type NavigationOptions } from "./navigation.js";
7
+ import { type ReferencedByQuery, ReferenceIndex } from "./references.js";
7
8
  export { LiveSource } from "./live-source.js";
9
+ export type { ReferencedByQuery } from "./references.js";
8
10
  /**
9
11
  * What a renderer needs from a site, independent of whether it reads live nodes (dev) or a
10
12
  * published snapshot (build/production).
@@ -104,6 +106,19 @@ export interface GraphSource {
104
106
  * with the standalone `entryFields(source, entry)`.
105
107
  */
106
108
  entryFields?(entry: ContentEntry, options?: EntryFieldsOptions): Promise<RenderedFields>;
109
+ /**
110
+ * RFC-0045 §4: the members of these translation groups that this view shows, in this site, by
111
+ * group (one call per resolution level; the live source reads the store once, a snapshot never).
112
+ * Optional for sources that predate references: their references resolve to nothing.
113
+ */
114
+ groupMembers?(groupIds: readonly string[]): Promise<Map<string, ContentEntry[]>>;
115
+ /**
116
+ * RFC-0045 §4 "who references me": entries this view lists whose resolved values name the
117
+ * group (a translation inheriting its original's value included), newest first, at most 100.
118
+ */
119
+ referencedBy?(groupId: string, q?: ReferencedByQuery): Promise<ContentEntry[]>;
120
+ /** RFC-0045 §7: the entry maps of a running text ↔ reference conversion in a collection. */
121
+ conversionEntries?(collection: string): Promise<ConversionEntries | undefined>;
107
122
  }
108
123
  export interface SourceSearchOptions {
109
124
  page?: number;
@@ -123,6 +138,11 @@ interface Loaded {
123
138
  published: ContentEntry[];
124
139
  /** Published entries with a public URL (unlisted ones too); `entries` holds the listed. */
125
140
  reachable: ContentEntry[];
141
+ /**
142
+ * RFC-0045 §7: every entry, drafts and archived ones included (`conversionEntries` filters what
143
+ * matches text itself); kept only while a conversion runs.
144
+ */
145
+ current: ContentEntry[];
126
146
  /** Every published entry's derived gate (RFC-0042 §3), computed once per snapshot. */
127
147
  derived: ReadonlyMap<string, DerivedGate>;
128
148
  /** Resolved field values by entry id, filled as queries need them (the snapshot is immutable). */
@@ -149,6 +169,10 @@ interface Shared {
149
169
  bundle?: "present" | "missing" | "persisting";
150
170
  /** Bodies read node by node (no bundle), as stored JSON text, kept to write the bundle. */
151
171
  fetched?: Map<string, string> | undefined;
172
+ /** RFC-0045 §4: members and referrers by group over the published entries, gates aside. */
173
+ references?: ReferenceIndex;
174
+ /** RFC-0045 §7: conversion maps by collection, while a text ↔ reference conversion runs. */
175
+ conversions?: Map<string, Promise<ConversionEntries | undefined>>;
152
176
  }
153
177
  /**
154
178
  * Reads exactly the node bodies captured in a snapshot (immutable; only published nodes are
@@ -199,6 +223,10 @@ export declare class SnapshotSource implements GraphSource {
199
223
  /** A published entry of this snapshot by id (any locale), if its gates are open. */
200
224
  entryById(id: string): Promise<ContentEntry | undefined>;
201
225
  entryFields(entry: ContentEntry, options?: EntryFieldsOptions): Promise<RenderedFields>;
226
+ /** RFC-0045 §4: in memory, through this view's gates (`reachable`: unlisted targets resolve). */
227
+ groupMembers(groupIds: readonly string[]): Promise<Map<string, ContentEntry[]>>;
228
+ referencedBy(groupId: string, q?: ReferencedByQuery): Promise<ContentEntry[]>;
229
+ conversionEntries(collection: string): Promise<ConversionEntries | undefined>;
202
230
  taxonomies(): Promise<Taxonomy[]>;
203
231
  terms(key: string): Promise<Term[]>;
204
232
  termBySlug(key: string, slug: string): Promise<Term | undefined>;
@@ -13,7 +13,12 @@
13
13
 
14
14
  import { matchRedirect, redirectLocale } from "@cloudhal/core-ts";
15
15
  import { hasGates, inheritedGate, isAvailable, nextInstant } from "@cloudhal/core-ts/availability";
16
- import { derivedGates, } from "@cloudhal/core-ts/fields";
16
+ import {
17
+
18
+
19
+ derivedGates,
20
+
21
+ } from "@cloudhal/core-ts/fields";
17
22
  import { matches } from "@cloudhal/core-ts/filter";
18
23
  import { assetRefsOf } from "@cloudhal/core-ts/media";
19
24
  import {
@@ -25,9 +30,12 @@ import {
25
30
  import { gateIndex, splitEntries } from "./entry-views.js";
26
31
  import { entryFields, } from "./fields.js";
27
32
  import { navigationFor } from "./navigation.js";
33
+ import { cachedConversionMaps, conversionMapsOf, siteConverts } from "./reference-conversions.js";
34
+ import { membersIn, ReferenceIndex, referrersIn } from "./references.js";
28
35
  import { byNewest, byPosition, compile, shown, termFilter, visible } from "./source-helpers.js";
29
36
 
30
37
  export { LiveSource } from "./live-source.js";
38
+
31
39
 
32
40
  /**
33
41
  * What a renderer needs from a site, independent of whether it reads live nodes (dev) or a
@@ -132,6 +140,19 @@ export { LiveSource } from "./live-source.js";
132
140
 
133
141
 
134
142
 
143
+
144
+  
145
+
146
+
147
+
148
+
149
+
150
+  
151
+
152
+
153
+
154
+    
155
+
135
156
 
136
157
 
137
158
 
@@ -153,6 +174,11 @@ export { LiveSource } from "./live-source.js";
153
174
 
154
175
 
155
176
 
177
+
178
+  
179
+
180
+
181
+
156
182
   
157
183
 
158
184
 
@@ -200,6 +226,10 @@ export { LiveSource } from "./live-source.js";
200
226
 
201
227
 
202
228
 
229
+  
230
+
231
+    
232
+
203
233
 
204
234
 
205
235
  /** Who may see the nodes of a snapshot: the clock gates are checked against, or nobody (previews). */
@@ -358,6 +388,7 @@ export class SnapshotSource {
358
388
  entries: shownEntries,
359
389
  published: shownEntries,
360
390
  reachable: shownEntries,
391
+ current: siteConverts(site ) ? entries : [],
361
392
  derived,
362
393
  resolved: new Map(),
363
394
  taxonomies,
@@ -516,6 +547,45 @@ export class SnapshotSource {
516
547
  return entryFields(this, entry, options);
517
548
  }
518
549
 
550
+ async #references() {
551
+ const loaded = await this.#load();
552
+ if (this.#shared.references) return this.#shared.references;
553
+ const { site } = loaded;
554
+ const maps = await conversionMapsOf(site, Object.keys(site.collections ?? {}), (c) =>
555
+ this.conversionEntries(c),
556
+ );
557
+ this.#shared.references ??= new ReferenceIndex(site, loaded.published, maps);
558
+ return this.#shared.references;
559
+ }
560
+
561
+ /** RFC-0045 §4: in memory, through this view's gates (`reachable`: unlisted targets resolve). */
562
+ async groupMembers(groupIds ) {
563
+ const [index, view] = [await this.#references(), await this.#current()];
564
+ return membersIn(index.members(), groupIds, {
565
+ listed: view.entries,
566
+ reachable: view.reachable,
567
+ });
568
+ }
569
+
570
+ async referencedBy(groupId , q = {}) {
571
+ const [index, view] = [await this.#references(), await this.#current()];
572
+ return referrersIn(index.referrers(groupId), q, {
573
+ listed: view.entries,
574
+ reachable: view.reachable,
575
+ });
576
+ }
577
+
578
+ async conversionEntries(collection ) {
579
+ const loaded = await this.#load();
580
+ this.#shared.conversions ??= new Map();
581
+ return cachedConversionMaps(
582
+ this.#shared.conversions,
583
+ loaded.site,
584
+ collection,
585
+ () => loaded.current,
586
+ );
587
+ }
588
+
519
589
  async taxonomies() {
520
590
  return (await this.#current()).taxonomies;
521
591
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudhal/astro-renderer",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Render a Cloudhal Site Graph with Astro: data sources (live/snapshot), section components and the cloudhal() integration",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://cloudhal.dev",
@@ -223,14 +223,14 @@
223
223
  "README.md"
224
224
  ],
225
225
  "dependencies": {
226
- "@cloudhal/core-contracts": "0.8.0",
227
- "@cloudhal/core-ts": "0.8.0",
228
- "@cloudhal/storage": "0.8.0",
226
+ "@cloudhal/core-contracts": "0.9.0",
227
+ "@cloudhal/core-ts": "0.9.0",
228
+ "@cloudhal/storage": "0.9.0",
229
229
  "marked": "^18.1.1",
230
230
  "parse5": "8.1.0",
231
- "@cloudhal/analytics": "0.8.0",
231
+ "@cloudhal/analytics": "0.9.0",
232
232
  "vite": "^8.3.5",
233
- "@cloudhal/comments": "0.8.0"
233
+ "@cloudhal/comments": "0.9.0"
234
234
  },
235
235
  "peerDependencies": {
236
236
  "astro": "^7.4.0",