@cloudhal/astro-renderer 0.5.0 → 0.6.1

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,227 @@
1
+ /**
2
+ * RFC-0042 §4: listings by field for themes. `queryEntries(source, q)` lists a collection's entries
3
+ * filtered by its list fields (`where`), ordered by one (`orderBy`), on top of the RFC-0002 term
4
+ * filter and the collection's `sort`, paged. Both published sources run the same evaluator
5
+ * (`evaluateEntryQuery`) over what they show, with core-ts's `fields/query.ts` deciding each
6
+ * condition, so live and snapshot answer alike. Pure, Worker-safe; `now` is the source's clock.
7
+ *
8
+ * On a published site an invalid query matches nothing and is logged ("a published snapshot must
9
+ * keep rendering", like unknown terms in `entriesByFilter`): writers refuse invalid queries, so it
10
+ * only happens after a definition changed.
11
+ */
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+ import {
23
+ compareByField,
24
+ matchesFieldQuery,
25
+ originalsOf,
26
+ parseFieldQuery,
27
+
28
+ resolveFields,
29
+ } from "@cloudhal/core-ts/fields";
30
+ import { matches } from "@cloudhal/core-ts/filter";
31
+
32
+ import { compile } from "./source-helpers.js";
33
+
34
+ /** A theme's listing by field (RFC-0042 §4). */
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+  
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+
57
+
58
+ export const QUERY_DEFAULT_LIMIT = 20;
59
+ export const QUERY_MAX_LIMIT = 100;
60
+
61
+ /** What a source hands the evaluator. */
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+ const published = (e ) => e.publishedAt ?? e.createdAt;
78
+
79
+ /** The listing order of RFC-0040's `sort`, as `ContentList` has always drawn it. */
80
+ function bySort(sort ) {
81
+ if (sort === "title") return (a, b) => a.title.localeCompare(b.title);
82
+ if (sort === "oldest") return (a, b) => published(a).localeCompare(published(b));
83
+ return (a, b) => published(b).localeCompare(published(a));
84
+ }
85
+
86
+ const byId = (a , b ) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
87
+
88
+ const clampInt = (n , min , max , fallback ) =>
89
+ n === undefined || !Number.isFinite(n) ? fallback : Math.min(max, Math.max(min, Math.trunc(n)));
90
+
91
+ /** The term filter as a predicate; an invalid one matches nothing (logged). */
92
+ function termPredicate(input ) {
93
+ const { filter } = input.query;
94
+ if (!filter) return undefined;
95
+ try {
96
+ const f = compile(filter, [...input.taxonomies], [...input.terms]);
97
+ return (e) => matches(f, e);
98
+ } catch (err) {
99
+ console.warn(`cloudhal: query filter "${filter}" is invalid: ${String(err)}`);
100
+ return () => false;
101
+ }
102
+ }
103
+
104
+ /** Runs a query over what a source shows. Pure. */
105
+ export function evaluateEntryQuery(input ) {
106
+ const { site, query: q } = input;
107
+ const limit = clampInt(q.limit, 1, QUERY_MAX_LIMIT, QUERY_DEFAULT_LIMIT);
108
+ const offset = clampInt(q.offset, 0, Number.MAX_SAFE_INTEGER, 0);
109
+ const sort = bySort(q.sort ?? site.collections?.[q.collection]?.sort ?? "newest");
110
+ const byTerms = termPredicate(input);
111
+ let rows = input.candidates.filter((e) => !byTerms || byTerms(e));
112
+ if (q.where?.length || q.orderBy) {
113
+ const parsed = parseFieldQuery(site, q.collection, { where: q.where, orderBy: q.orderBy });
114
+ if (!parsed.ok) {
115
+ const shown = parsed.issues.map((i) => `${i.path}: ${i.message}`).join("; ");
116
+ console.warn(`cloudhal: query on ${q.collection} matches nothing: ${shown}`);
117
+ return { entries: [], total: 0 };
118
+ }
119
+ const originalOf = originalsOf(input.published);
120
+ const cache = input.cache ?? new Map ();
121
+ const values = (e ) => {
122
+ const known = cache.get(e.id);
123
+ if (known) return known;
124
+ const v = resolveFields(site, e, originalOf(e));
125
+ cache.set(e.id, v);
126
+ return v;
127
+ };
128
+ rows = rows.filter((e) => matchesFieldQuery(values(e), parsed.query, input.now));
129
+ rows.sort(
130
+ (a, b) => compareByField(values(a), values(b), parsed.query) || sort(a, b) || byId(a, b),
131
+ );
132
+ } else rows = [...rows].sort((a, b) => sort(a, b) || byId(a, b));
133
+ return { entries: rows.slice(offset, offset + limit), total: rows.length };
134
+ }
135
+
136
+ /** What a list handed to a theme came from: its source and locale, or a query already run. */
137
+
138
+ const origins = new WeakMap ();
139
+
140
+ /**
141
+ * Marks a list a source returned (`entries`, `entriesByFilter`) so `ContentList` can apply a
142
+ * section's `where`/`orderBy` even for theme copies from before RFC-0042, which pass the
143
+ * collection's list as it is. Returns the list.
144
+ */
145
+ export function rememberList (list , origin ) {
146
+ origins.set(list, origin);
147
+ return list;
148
+ }
149
+
150
+ /** Where a list came from, if a source or `queryEntries` made it. */
151
+ export function listOrigin(list ) {
152
+ return origins.get(list);
153
+ }
154
+
155
+ /**
156
+ * Lists `q.collection` by its list fields on any source: the source's own `queryEntries`, or, on
157
+ * sources from before RFC-0042, the same evaluator over `entries()` (no `includeExpired` there).
158
+ */
159
+ export async function queryEntries(
160
+ source ,
161
+ q ,
162
+ ) {
163
+ const result = source.queryEntries
164
+ ? await source.queryEntries(q)
165
+ : await (async () => {
166
+ const site = await source.site();
167
+ const candidates = await source.entries(q.collection, q.locale);
168
+ const [taxonomies, terms] = q.filter
169
+ ? await Promise.all([source.taxonomies(), source.vocabulary()])
170
+ : [[], []];
171
+ return evaluateEntryQuery({
172
+ site,
173
+ candidates,
174
+ published: candidates,
175
+ taxonomies,
176
+ terms,
177
+ query: q,
178
+ now: Date.now(),
179
+ });
180
+ })();
181
+ rememberList(result.entries, "queried");
182
+ return result;
183
+ }
184
+
185
+ /** The query a `contentList` section with `where`/`orderBy` runs (its own `limit`, at most 100). */
186
+ export function sectionQuery(section , locale ) {
187
+ return {
188
+ collection: section.collection,
189
+ locale,
190
+ sort: section.sort,
191
+ limit: Math.min(section.limit, QUERY_MAX_LIMIT),
192
+ ...(section.where ? { where: section.where } : {}),
193
+ ...(section.orderBy ? { orderBy: section.orderBy } : {}),
194
+ ...(section.filter ? { filter: section.filter } : {}),
195
+ };
196
+ }
197
+
198
+ /** True when a section lists by field (RFC-0042). */
199
+ export const listsByField = (section ) =>
200
+ section.where !== undefined || section.orderBy !== undefined;
201
+
202
+ /**
203
+ * The entries a page's `contentList` sections draw, keyed as `Sections` reads them: by collection
204
+ * (the collection's newest listed entries), by section id for a section with a term `filter`
205
+ * (RFC-0002), and by section id for a section with `where`/`orderBy` (RFC-0042, through
206
+ * `queryEntries`). An invalid filter lists nothing and is logged.
207
+ */
208
+ export async function contentListEntries(
209
+ source ,
210
+ sections ,
211
+ locale ,
212
+ ) {
213
+ const lists = sections.filter((s) => s.kind === "contentList");
214
+ const out = {};
215
+ for (const c of new Set(lists.map((s) => s.collection))) out[c] = await source.entries(c, locale);
216
+ for (const s of lists) {
217
+ if (listsByField(s)) out[s.id] = (await queryEntries(source, sectionQuery(s, locale))).entries;
218
+ else if (s.filter)
219
+ out[s.id] = await source
220
+ .entriesByFilter(`collection:${s.collection}+${s.filter}`, locale ? { locale } : {})
221
+ .catch((err ) => {
222
+ console.warn(`cloudhal: section ${s.id} has an invalid filter: ${String(err)}`);
223
+ return [];
224
+ });
225
+ }
226
+ return out;
227
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * RFC-0042 §3 in the published sources: an entry's derived gate (its collection's `expiry`) next to
3
+ * its own `availability` (RFC-0008). `unlist` keeps the entry's page (and comments, menus,
4
+ * alternates) but leaves it out of every listing, feed, the sitemap and search; `hide` answers 404
5
+ * like an expired `availability`. The gate index gets every derived instant and, for `now`
6
+ * conditions on list fields (§4), every value instant, so the edge cache expires at each one.
7
+ * Pure helpers shared by the live and snapshot sources; previews never call them.
8
+ */
9
+ import type { ContentEntry, Page, Site } from "@cloudhal/core-contracts";
10
+ import { type DerivedGate } from "@cloudhal/core-ts/fields";
11
+ import type { GraphSource } from "./source.js";
12
+ /** What the public sees of a set of entries at one instant. */
13
+ export interface EntrySplit {
14
+ /** Shown entries: every listing, feed, sitemap and search. */
15
+ readonly listed: ContentEntry[];
16
+ /** Shown and unlisted entries: everything with a public URL (routes, comments, menus). */
17
+ readonly reachable: ContentEntry[];
18
+ }
19
+ /**
20
+ * Splits `entries` at `now` by status, `availability` and their derived gates (`derivedGates` over
21
+ * every published entry a translation may read from; a snapshot computes it once). The snapshot
22
+ * and the live source pass the same sets, so they agree.
23
+ */
24
+ export declare function splitEntries(entries: readonly ContentEntry[], now: number, derived: ReadonlyMap<string, DerivedGate>): EntrySplit;
25
+ /**
26
+ * The gate index of published nodes (RFC-0008 §7.4, RFC-0042 §3.4 and §4): every `from`/`until`,
27
+ * every derived gate, and every instant a `now` condition on a list field may flip at; sorted,
28
+ * unique. Empty for a site that schedules nothing and has no such settings.
29
+ */
30
+ export declare function gateIndex(site: Site, pages: readonly Page[], entries: readonly ContentEntry[], gates?: ReadonlyMap<string, DerivedGate>): number[];
31
+ /**
32
+ * Every entry of a locale with a public URL (unlisted ones included), newest first: what routes,
33
+ * static builds and language alternates need. Sources from before RFC-0042 list all of them in
34
+ * `allEntries`.
35
+ */
36
+ export declare function routableEntries(source: GraphSource, locale?: string): Promise<ContentEntry[]>;
@@ -0,0 +1,73 @@
1
+ /**
2
+ * RFC-0042 §3 in the published sources: an entry's derived gate (its collection's `expiry`) next to
3
+ * its own `availability` (RFC-0008). `unlist` keeps the entry's page (and comments, menus,
4
+ * alternates) but leaves it out of every listing, feed, the sitemap and search; `hide` answers 404
5
+ * like an expired `availability`. The gate index gets every derived instant and, for `now`
6
+ * conditions on list fields (§4), every value instant, so the edge cache expires at each one.
7
+ * Pure helpers shared by the live and snapshot sources; previews never call them.
8
+ */
9
+
10
+ import { gateInstants } from "@cloudhal/core-ts/availability";
11
+ import {
12
+
13
+ derivedGates,
14
+ entryVisibility,
15
+ listFieldInstants,
16
+ } from "@cloudhal/core-ts/fields";
17
+
18
+
19
+ /** What the public sees of a set of entries at one instant. */
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+ /**
28
+ * Splits `entries` at `now` by status, `availability` and their derived gates (`derivedGates` over
29
+ * every published entry a translation may read from; a snapshot computes it once). The snapshot
30
+ * and the live source pass the same sets, so they agree.
31
+ */
32
+ export function splitEntries(
33
+ entries ,
34
+ now ,
35
+ derived ,
36
+ ) {
37
+ const listed = [];
38
+ const reachable = [];
39
+ for (const e of entries) {
40
+ const v = entryVisibility(e, derived.get(e.id), now);
41
+ if (v === "hidden") continue;
42
+ reachable.push(e);
43
+ if (v === "shown") listed.push(e);
44
+ }
45
+ return { listed, reachable };
46
+ }
47
+
48
+ /**
49
+ * The gate index of published nodes (RFC-0008 §7.4, RFC-0042 §3.4 and §4): every `from`/`until`,
50
+ * every derived gate, and every instant a `now` condition on a list field may flip at; sorted,
51
+ * unique. Empty for a site that schedules nothing and has no such settings.
52
+ */
53
+ export function gateIndex(
54
+ site ,
55
+ pages ,
56
+ entries ,
57
+ gates = derivedGates(site, entries),
58
+ ) {
59
+ const own = gateInstants([...pages, ...entries]);
60
+ const derived = [...gates.values()].map((g) => g.at);
61
+ const lists = listFieldInstants(site, entries);
62
+ if (derived.length === 0 && lists.length === 0) return own;
63
+ return [...new Set([...own, ...derived, ...lists])].sort((a, b) => a - b);
64
+ }
65
+
66
+ /**
67
+ * Every entry of a locale with a public URL (unlisted ones included), newest first: what routes,
68
+ * static builds and language alternates need. Sources from before RFC-0042 list all of them in
69
+ * `allEntries`.
70
+ */
71
+ export function routableEntries(source , locale ) {
72
+ return source.routableEntries ? source.routableEntries(locale) : source.allEntries(locale);
73
+ }
@@ -8,6 +8,8 @@
8
8
  */
9
9
  export * from "./archive.js";
10
10
  export * from "./cache-tags.js";
11
+ export * from "./collection-feeds.js";
12
+ export * from "./entry-query.js";
11
13
  export * from "./fields.js";
12
14
  export * from "./gates.js";
13
15
  export { type CloudhalRendererConfig, cloudhal } from "./integration.js";
@@ -16,4 +18,5 @@ export * from "./navigation.js";
16
18
  export * from "./preview.js";
17
19
  export { getSource, resetSource } from "./runtime.js";
18
20
  export * from "./source.js";
21
+ export { entryStructuredData, type StructuredDataOptions, withStructuredData, } from "./structured-data.js";
19
22
  export * from "./taxonomy.js";
package/dist/src/index.js CHANGED
@@ -8,6 +8,8 @@
8
8
  */
9
9
  export * from "./archive.js";
10
10
  export * from "./cache-tags.js";
11
+ export * from "./collection-feeds.js";
12
+ export * from "./entry-query.js";
11
13
  export * from "./fields.js";
12
14
  export * from "./gates.js";
13
15
  export { cloudhal } from "./integration.js";
@@ -16,4 +18,9 @@ export * from "./navigation.js";
16
18
  export * from "./preview.js";
17
19
  export { getSource, resetSource } from "./runtime.js";
18
20
  export * from "./source.js";
21
+ export {
22
+ entryStructuredData,
23
+
24
+ withStructuredData,
25
+ } from "./structured-data.js";
19
26
  export * from "./taxonomy.js";
@@ -1,6 +1,7 @@
1
1
 
2
2
 
3
3
 
4
+ import { scriptsNotInlined } from "./csp.js";
4
5
 
5
6
  /** Options for the `cloudhal()` integration; made available to pages via `virtual:cloudhal/config`. */
6
7
 
@@ -61,6 +62,37 @@ const RESOLVED_CLIENT_ID = `\0${CLIENT_ID}`;
61
62
  const COMMENTS_CLIENT_ID = "virtual:cloudhal/comments-client";
62
63
  const RESOLVED_COMMENTS_CLIENT_ID = `\0${COMMENTS_CLIENT_ID}`;
63
64
 
65
+ /** The virtual modules: the project config, and in dev the built analytics and comments clients. */
66
+ function configPlugin(modules ) {
67
+ const ids = {
68
+ [VIRTUAL_ID]: RESOLVED_ID,
69
+ [CLIENT_ID]: RESOLVED_CLIENT_ID,
70
+ [COMMENTS_CLIENT_ID]: RESOLVED_COMMENTS_CLIENT_ID,
71
+ };
72
+ const bodies = {
73
+ [RESOLVED_ID]: modules.config,
74
+ [RESOLVED_CLIENT_ID]: modules.client,
75
+ [RESOLVED_COMMENTS_CLIENT_ID]: modules.comments,
76
+ };
77
+ return {
78
+ name: "cloudhal-config",
79
+ resolveId: (id ) => (Object.hasOwn(ids, id) ? ids[id] : undefined),
80
+ load: (id ) =>
81
+ Object.hasOwn(bodies, id) ? `export default ${JSON.stringify(bodies[id])};` : undefined,
82
+ };
83
+ }
84
+
85
+ /**
86
+ * What only `cloudhal dev` runs as middleware (the Site Worker's entry and builds do these jobs):
87
+ * the analytics beacon (RFC-0006 §5.1); the click-to-load video player (RFC-0015 §4) and the
88
+ * interaction runtime (RFC-0020 §4), which builds write as files; and the Site Worker's CSP sent
89
+ * report-only, so the console shows what a deploy would block.
90
+ */
91
+ const DEV_MIDDLEWARE = ["analytics-middleware", "embed-middleware", "csp-middleware"].map((m) => ({
92
+ entrypoint: `@cloudhal/astro-renderer/${m}`,
93
+ order: "pre" ,
94
+ }));
95
+
64
96
  export function cloudhal(config ) {
65
97
  let resolved = config;
66
98
  let client ;
@@ -95,15 +127,7 @@ export function cloudhal(config ) {
95
127
  client = await buildAnalyticsClient();
96
128
  resolved = { ...resolved, analyticsScript: client.script.path };
97
129
  }
98
- if (!cloudflare && command === "dev")
99
- addMiddleware({
100
- entrypoint: "@cloudhal/astro-renderer/analytics-middleware",
101
- order: "pre",
102
- });
103
- // The click-to-load video player (RFC-0015 §4) and the interaction runtime (RFC-0020 §4):
104
- // served here in dev, written by builds.
105
- if (!cloudflare && command === "dev")
106
- addMiddleware({ entrypoint: "@cloudhal/astro-renderer/embed-middleware", order: "pre" });
130
+ if (!cloudflare && command === "dev") for (const m of DEV_MIDDLEWARE) addMiddleware(m);
107
131
  // Reader comments (RFC-0007 §8.2, §15.2), on the same targets: the Site Worker build ships
108
132
  // the module and its proof-of-work worker as hashed static assets and its entry answers the
109
133
  // endpoints; `cloudhal dev` serves both and answers them from a middleware on SQLite.
@@ -120,29 +144,24 @@ export function cloudhal(config ) {
120
144
  order: "pre",
121
145
  });
122
146
  }
147
+ // RFC-0042 §5: a collection's feed where the theme's routes answer 404, on every target.
148
+ addMiddleware({
149
+ entrypoint: "@cloudhal/astro-renderer/collection-feed-middleware",
150
+ order: "pre",
151
+ });
123
152
  updateConfig({
124
153
  vite: {
125
154
  plugins: [
126
- {
127
- name: "cloudhal-config",
128
- resolveId: (id ) =>
129
- id === VIRTUAL_ID
130
- ? RESOLVED_ID
131
- : id === CLIENT_ID
132
- ? RESOLVED_CLIENT_ID
133
- : id === COMMENTS_CLIENT_ID
134
- ? RESOLVED_COMMENTS_CLIENT_ID
135
- : undefined,
136
- load: (id ) =>
137
- id === RESOLVED_ID
138
- ? `export default ${JSON.stringify(resolved)};`
139
- : id === RESOLVED_CLIENT_ID
140
- ? `export default ${JSON.stringify(cloudflare ? null : (client ?? null))};`
141
- : id === RESOLVED_COMMENTS_CLIENT_ID
142
- ? `export default ${JSON.stringify(cloudflare ? null : (comments ?? null))};`
143
- : undefined,
144
- },
155
+ configPlugin({
156
+ config: resolved,
157
+ client: cloudflare ? null : (client ?? null),
158
+ comments: cloudflare ? null : (comments ?? null),
159
+ }),
145
160
  ],
161
+ // `SITE_CSP` allows no inline script, so theme `<script>`s ship as files (any size).
162
+ build: {
163
+ assetsInlineLimit: scriptsNotInlined(astroConfig.vite?.build?.assetsInlineLimit),
164
+ },
146
165
  // Native module must stay external in Node SSR; workerd never loads it.
147
166
  ...(cloudflare ? {} : { ssr: { external: ["better-sqlite3"] } }),
148
167
  },
@@ -0,0 +1,53 @@
1
+ import type { Asset, ContentEntry, Menu, Page, Redirect, Site, Taxonomy, Term } from "@cloudhal/core-contracts";
2
+ import type { RedirectMatch, SearchResults, SiteGraphStore } from "@cloudhal/core-ts";
3
+ import { type FieldEntryQuery, type FieldEntryResult } from "./entry-query.js";
4
+ import { type EntryFieldsOptions, type RenderedFields } from "./fields.js";
5
+ import { type Navigation, type NavigationOptions } from "./navigation.js";
6
+ import type { GraphSource, SourceSearchOptions } from "./source.js";
7
+ /**
8
+ * Reads the current nodes on every call. Drafts are included so authors can preview them in dev,
9
+ * and so are gated nodes (a preview shows embargoed and expired content, RFC-0008 §7.3). Without
10
+ * drafts it serves what the public would see: published nodes whose gates are open at `now`.
11
+ */
12
+ export declare class LiveSource implements GraphSource {
13
+ #private;
14
+ readonly mode = "live";
15
+ constructor(store: SiteGraphStore, siteId: string, options?: {
16
+ includeDrafts?: boolean;
17
+ now?: () => number;
18
+ });
19
+ nextGate(): Promise<number | undefined>;
20
+ site(): Promise<Site>;
21
+ pages(): Promise<Page[]>;
22
+ pageByPath(path: string, locale?: string): Promise<Page | undefined>;
23
+ entries(collection: string, locale?: string): Promise<ContentEntry[]>;
24
+ entryBySlug(collection: string, slug: string, locale?: string): Promise<ContentEntry | undefined>;
25
+ allEntries(locale?: string): Promise<ContentEntry[]>;
26
+ /** Every entry of a locale with a public URL, unlisted ones included (RFC-0042 §3). */
27
+ routableEntries(locale?: string): Promise<ContentEntry[]>;
28
+ /** RFC-0042 §4: a collection by its list fields (`queryEntries`). */
29
+ queryEntries(q: FieldEntryQuery): Promise<FieldEntryResult>;
30
+ search(query: string, options?: SourceSearchOptions): Promise<SearchResults>;
31
+ entryById(id: string): Promise<ContentEntry | undefined>;
32
+ entryFields(entry: ContentEntry, options?: EntryFieldsOptions): Promise<RenderedFields>;
33
+ taxonomies(): Promise<Taxonomy[]>;
34
+ terms(key: string): Promise<Term[]>;
35
+ termBySlug(key: string, slug: string): Promise<Term | undefined>;
36
+ vocabulary(key?: string): Promise<Term[]>;
37
+ entriesByFilter(filter: string, options?: {
38
+ locale?: string;
39
+ limit?: number;
40
+ }): Promise<ContentEntry[]>;
41
+ entriesByTerm(key: string, slug: string, options?: {
42
+ locale?: string;
43
+ limit?: number;
44
+ descendants?: boolean;
45
+ }): Promise<ContentEntry[]>;
46
+ redirectFor(path: string, locale?: string): Promise<RedirectMatch | undefined>;
47
+ redirects(): Promise<Redirect[]>;
48
+ menu(key: string): Promise<Menu | undefined>;
49
+ navigation(key: string, locale?: string, options?: NavigationOptions): Promise<Navigation | undefined>;
50
+ assets(): Promise<Asset[]>;
51
+ asset(id: string): Promise<Asset | undefined>;
52
+ assetByPrefix(prefix16: string): Promise<Asset | undefined>;
53
+ }