@realadvisor-sites/kit-astro 0.0.0-stage → 0.4.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,26 @@
1
+ ---
2
+ /**
3
+ * Text-like input with its label. Same height and look as Select/Combobox/Button.
4
+ * <Input label="E-Mail" name="email" type="email" required autocomplete="email" />
5
+ * <Input label="Max. Preis" name="maxPrice" type="number" hideLabel placeholder="Max. Preis" />
6
+ * Pass `multiline` for a textarea.
7
+ */
8
+ import '@realadvisor/sites-kit-core/styles/form.css';
9
+ import type { HTMLAttributes } from 'astro/types';
10
+
11
+ type Props = Omit<HTMLAttributes<'input'>, 'class'> & {
12
+ label: string;
13
+ name: string;
14
+ hideLabel?: boolean;
15
+ multiline?: boolean;
16
+ class?: string;
17
+ };
18
+ const { label, hideLabel, multiline, class: cls, id, type = 'text', ...rest } = Astro.props;
19
+ const fieldId = id ?? `f-${rest.name}`;
20
+ ---
21
+ <div class:list={['field', cls]}>
22
+ <label for={fieldId} class:list={['field-label', { 'sr-only': hideLabel }]}>{label}</label>
23
+ {multiline
24
+ ? <textarea id={fieldId} class="control" {...(rest as HTMLAttributes<'textarea'>)}>{rest.value}</textarea>
25
+ : <input id={fieldId} class="control" type={type} {...rest} />}
26
+ </div>
@@ -0,0 +1,35 @@
1
+ ---
2
+ /**
3
+ * Styled native select (up to ~12 options). Works without JS, inside GET filter forms.
4
+ * <Select label="Angebot" name="offerType" value={offerType}
5
+ * placeholder="Alle" options={[{ value: 'buy', label: 'Kaufen' }, { value: 'rent', label: 'Mieten' }]} />
6
+ * `placeholder` adds a first option with value "" (= no filter).
7
+ */
8
+ import '@realadvisor/sites-kit-core/styles/form.css';
9
+
10
+ export type Option = { value: string; label: string };
11
+ interface Props {
12
+ label: string;
13
+ name: string;
14
+ options: Option[];
15
+ value?: string | null;
16
+ placeholder?: string;
17
+ hideLabel?: boolean;
18
+ disabled?: boolean;
19
+ required?: boolean;
20
+ 'aria-describedby'?: string;
21
+ id?: string;
22
+ class?: string;
23
+ }
24
+ const { label, name, options, value, placeholder, hideLabel, disabled, required, id, class: cls, 'aria-describedby': describedBy } = Astro.props;
25
+ const fieldId = id ?? `f-${name}`;
26
+ ---
27
+ <div class:list={['field', cls]}>
28
+ <label for={fieldId} class:list={['field-label', { 'sr-only': hideLabel }]}>{label}</label>
29
+ <span class="select">
30
+ <select id={fieldId} name={name} class="control" disabled={disabled} required={required} aria-describedby={describedBy}>
31
+ {placeholder !== undefined && <option value="" selected={!value}>{placeholder}</option>}
32
+ {options.map((o) => <option value={o.value} selected={o.value === value}>{o.label}</option>)}
33
+ </select>
34
+ </span>
35
+ </div>
package/lib/ra.ts ADDED
@@ -0,0 +1,145 @@
1
+ /**
2
+ * The only way this site reads data. Every page imports `ra` from here: the
3
+ * `@realadvisor/sites-sdk` SitesClient (records as the API sends them, in
4
+ * snake_case), plus `agency()`.
5
+ *
6
+ * - Production and published previews: SITES_API_URL (var, the rest-api
7
+ * origin) + SITES_API_KEY (Worker secret, the site's api_site key), both set
8
+ * at publish. The Worker calls rest-api /v3/public directly; rest-api caches
9
+ * reads for 60 s. The listings are those of the site's own portal.
10
+ * - Sandbox preview: the same two, set by the runtime in .dev.vars. The key is
11
+ * a placeholder the sandbox firewall fills in. Real data; enquiries are
12
+ * answered by the firewall, never sent.
13
+ * - Local key mode: SITES_API_URL + SITES_API_KEY in .dev.vars / env.
14
+ * - Fixture mode: everything else (pnpm dev, evals, build-time prerender).
15
+ * Reads src/data/<SITES_FIXTURE>.json (default: the first one), plus the
16
+ * developments of every development-<slug>.json there. No network, and
17
+ * enquiries are never sent.
18
+ *
19
+ * On a site with more than one locale, listings and developments come in the
20
+ * page's language (`locale`, from the URL: lib/page-locale.ts) when the CRM
21
+ * has their texts in it; `text_locale` then says so.
22
+ *
23
+ * Pages that show listings, agents or agency data render on request
24
+ * (`export const prerender = false`) so production gets live data.
25
+ *
26
+ * Never import this file from client-side code (<script> tags, framework
27
+ * islands): it runs on the server only.
28
+ */
29
+ import { createClient, createFixtureClient } from '@realadvisor/sites-sdk';
30
+ import type { DevelopmentWithUnits, SitesClient } from '@realadvisor/sites-sdk/types';
31
+ import { SITES_API_KEY, SITES_API_URL, SITES_FIXTURE } from 'astro:env/server';
32
+ import fixtures from 'virtual:sites-kit/fixtures';
33
+ import { previewApi } from '@realadvisor/sites-kit-core/env';
34
+ import { agencyOf, type Agency, type SiteFixture } from '@realadvisor/sites-kit-core/agency';
35
+ import { withTextLocale } from '@realadvisor/sites-kit-core/page-locale';
36
+
37
+ export type { Address, Agent, Development, DevelopmentWithUnits, Listing, Organisation, Photo, Team, Unit } from '@realadvisor/sites-sdk/types';
38
+ export type { Agency, SiteFixture };
39
+
40
+ export type SiteClient = SitesClient & {
41
+ /** The organisation and its office (primary team) as one record: header, legal text, JSON-LD. */
42
+ agency(): Promise<Agency>;
43
+ /** The live SDK client, or null in fixture mode (the enquiry endpoint sends through it). */
44
+ live(): SitesClient | null;
45
+ };
46
+
47
+ const isFixture = (d: unknown): d is SiteFixture =>
48
+ !!d && typeof d === 'object' && 'organisation' in d && Array.isArray((d as SiteFixture).listings);
49
+
50
+ function pickFixture(): SiteFixture {
51
+ // Only files shaped like a fixture count, so other JSON in src/data/ is ignored.
52
+ const entries = Object.entries(fixtures).filter((e): e is [string, { default: SiteFixture }] => isFixture(e[1].default));
53
+ const isDev = ([path]: [string, unknown]) => /\/development-[^/]+\.json$/.test(path);
54
+ const wanted = SITES_FIXTURE
55
+ ? entries.find(([path]) => path.endsWith(`/${SITES_FIXTURE}.json`))
56
+ : (entries.find((e) => !isDev(e)) ?? entries[0]);
57
+ if (!wanted) {
58
+ throw new Error(
59
+ SITES_FIXTURE
60
+ ? `Fixture src/data/${SITES_FIXTURE}.json not found`
61
+ : 'No SITES_API_KEY and no fixture in src/data/. Run `pnpm fixture <name>` or set SITES_API_KEY.',
62
+ );
63
+ }
64
+ const site = wanted[1].default;
65
+ const developments: DevelopmentWithUnits[] = [...(site.developments ?? [])];
66
+ for (const e of entries) {
67
+ if (e === wanted || !isDev(e)) continue;
68
+ for (const d of e[1].default.developments ?? []) if (!developments.some((x) => x.id === d.id)) developments.push(d);
69
+ }
70
+ return { ...site, developments };
71
+ }
72
+
73
+ const access = () => {
74
+ // .dev.vars reach astro:env or locals.runtime.env depending on the server: read both.
75
+ const p = previewApi();
76
+ const url = SITES_API_URL || p.url;
77
+ const key = p.token || SITES_API_KEY;
78
+ return url && key ? { url, key } : null;
79
+ };
80
+
81
+ let live: { id: string; client: SitesClient } | undefined;
82
+ let fixture: { data: SiteFixture; client: SitesClient } | undefined;
83
+
84
+ function liveClient(): SitesClient | null {
85
+ const a = access();
86
+ if (!a) return null;
87
+ const id = `${a.url}\0${a.key}`;
88
+ if (live?.id !== id) live = { id, client: createClient({ url: a.url, key: a.key }) };
89
+ return live.client;
90
+ }
91
+
92
+ function fixtureClient() {
93
+ if (!fixture) {
94
+ const data = pickFixture();
95
+ fixture = { data, client: createFixtureClient(data) };
96
+ }
97
+ return fixture;
98
+ }
99
+
100
+ const client = () => liveClient() ?? fixtureClient().client;
101
+
102
+ /** True when data comes from src/data (no SITES_API_URL + SITES_API_KEY). */
103
+ export const isFixtureMode = () => !access();
104
+
105
+ /** The SDK's SitesClient on live data or the fixture, plus `agency()`. */
106
+ export const ra: SiteClient = {
107
+ organisation: () => client().organisation(),
108
+ teams: () => client().teams(),
109
+ agents: (q) => client().agents(q),
110
+ listings: (q) => client().listings(withTextLocale(q)),
111
+ allListings: (q) => client().allListings(withTextLocale(q)),
112
+ listing: (slugOrId, q) => client().listing(slugOrId, withTextLocale(q)),
113
+ developments: (q) => client().developments(withTextLocale(q)),
114
+ development: (slugOrId, q) => client().development(slugOrId, withTextLocale(q)),
115
+ turnstileSiteKey: () => client().turnstileSiteKey(),
116
+ live: liveClient,
117
+ agency: async () => {
118
+ const c = client();
119
+ const [org, teams] = await Promise.all([c.organisation(), c.teams()]);
120
+ const a = agencyOf(org, teams.find((t) => t.primary) ?? teams[0], liveClient() ? undefined : fixtureClient().data.legal);
121
+ // A team without a phone or email takes the first agent's.
122
+ if (!a.phone || !a.email) {
123
+ const people = await c.agents();
124
+ const phone = a.phone ?? people.find((p) => p.phone)?.phone;
125
+ const email = a.email ?? people.find((p) => p.email)?.email;
126
+ if (phone) a.phone = phone;
127
+ if (email) a.email = email;
128
+ }
129
+ return a;
130
+ },
131
+ };
132
+
133
+ /**
134
+ * Every listing matching `q`, every page read (`ra.allListings`). Use it when
135
+ * you filter or sort in the page (search, agent pages, sitemap); use
136
+ * `ra.listings({ limit, offset })` for paginated lists.
137
+ */
138
+ export const allListings = (q?: Parameters<SitesClient['allListings']>[0]) => ra.allListings(q);
139
+
140
+ /**
141
+ * Public Turnstile site key for <EnquiryForm> (from rest-api, kept 5 min).
142
+ * `null`: no widget. Fixture mode: the SDK's stand-in key, so the form
143
+ * renders a widget that never loads Turnstile.
144
+ */
145
+ export const turnstileSiteKey = (): Promise<string | null> => ra.turnstileSiteKey().catch(() => null);
package/middleware.ts ADDED
@@ -0,0 +1,93 @@
1
+ import { defineMiddleware } from 'astro:middleware';
2
+ import { setRuntimeEnv, siteMode, type SiteEnv } from '@realadvisor/sites-kit-core/env';
3
+ import site from 'virtual:sites-kit/site';
4
+ import { securityHeaders } from '@realadvisor/sites-kit-core/security';
5
+ import { notFoundPage, renderFailed } from '@realadvisor/sites-kit-core/render-error';
6
+ import { localeOfPath } from '@realadvisor/sites-kit-core/i18n';
7
+ import { withPageLocale } from '@realadvisor/sites-kit-core/page-locale';
8
+
9
+ /**
10
+ * Hands the Worker env (SITE_MODE, SITES_API_URL, ...) to lib/env.ts,
11
+ * renders each on-request page fully before answering, and adds the security
12
+ * headers (lib/security.mjs). The kit integration adds it to every site. Not applied in `pnpm dev` (the CRM
13
+ * preview frames it, and the dev error overlay must stay).
14
+ *
15
+ * Why render fully: Astro streams SSR pages, so the 200 status and headers
16
+ * leave before the body is rendered. An error in the markup (one listing with
17
+ * no photos, `l.photos[0].url`) then ends the stream: the visitor gets a 200
18
+ * with an empty or cut body, and caches keep it. Buffering turns that into a
19
+ * logged error and a 500 page.
20
+ *
21
+ * A missing page is not an error: a 404/410 (a route's answer, or a 404 the
22
+ * data API threw) keeps its status and gets the site's /404 page, never a 500.
23
+ */
24
+ /**
25
+ * A component that wraps the layout and has a `<script>` (a ListingDetail
26
+ * that renders `<Layout>…</Layout>` and then its script) makes Astro write
27
+ * the script after `</html>`. Browsers cope, but the page then ends with a
28
+ * script instead of `</html>`: move such trailing tags back before `</body>`.
29
+ */
30
+ function closeDocument(html: string): string {
31
+ const m = /<\/body>\s*<\/html>([\s\S]*)$/i.exec(html);
32
+ if (!m || !m[1]!.trim()) return html;
33
+ return `${html.slice(0, m.index)}${m[1]!.trim()}</body></html>`;
34
+ }
35
+
36
+ const norm = (p: string) => (p.length > 1 ? p.replace(/\/+$/, '') : p).toLowerCase();
37
+ const EXACT = new Map(Object.entries(site.redirects).filter(([k]) => !k.endsWith('*')).map(([k, v]) => [norm(k), v]));
38
+ const PREFIX = Object.entries(site.redirects)
39
+ .filter(([k]) => k.endsWith('*'))
40
+ .map(([k, v]) => [norm(k.slice(0, -1)), v] as const)
41
+ .sort((a, b) => b[0].length - a[0].length);
42
+
43
+ /** 301 target for an old URL (site.json `redirects`), or null. Same-site paths only. */
44
+ function redirectFor(url: URL): string | null {
45
+ const path = norm(url.pathname);
46
+ const to = EXACT.get(path) ?? PREFIX.find(([k]) => path === k || path.startsWith(`${k}/`))?.[1];
47
+ if (!to || !to.startsWith('/') || to.startsWith('//')) return null;
48
+ if (norm(to.split('?')[0]!) === path) return null; // never a loop
49
+ return to.includes('?') || !url.search ? to : `${to}${url.search}`;
50
+ }
51
+
52
+ // Every request renders with its page locale (lib/page-locale.ts): the data helpers read texts in it.
53
+ export const onRequest = defineMiddleware((context, next) => withPageLocale(localeOfPath(context.url.pathname), () => handle(context, next)));
54
+
55
+ const handle: Parameters<typeof defineMiddleware>[0] = async (context, next) => {
56
+ const locals = context.locals as { runtime?: { env?: SiteEnv } };
57
+ setRuntimeEnv(locals.runtime?.env);
58
+ const moved = redirectFor(context.url);
59
+ if (moved) return new Response(null, { status: 301, headers: { location: moved } });
60
+ if (!import.meta.env.PROD || context.isPrerendered) return next();
61
+
62
+ const path = context.url.pathname;
63
+ let res: Response;
64
+ try {
65
+ res = await next();
66
+ if ((res.headers.get('content-type') ?? '').includes('text/html') && res.body) {
67
+ const raw = await res.text(); // throws when rendering fails mid-stream
68
+ if (res.status === 200 && !raw.replace(/<!doctype html>/i, '').trim()) {
69
+ throw new Error('page rendered an empty body');
70
+ }
71
+ if (res.status === 200 && /<html[\s>]/i.test(raw) && !/<\/html>/i.test(raw)) {
72
+ throw new Error('page rendered a cut body (no </html>)');
73
+ }
74
+ const html = closeDocument(raw);
75
+ res = new Response(html, { status: res.status, statusText: res.statusText, headers: res.headers });
76
+ } else if ((res.status === 404 || res.status === 410) && !res.body) {
77
+ res = notFoundPage(path, res.status);
78
+ } else if (res.status >= 500 && !res.body) {
79
+ res = renderFailed(path, new Error(`HTTP ${res.status} with no body`));
80
+ }
81
+ } catch (err) {
82
+ const status = (err as { status?: unknown } | null)?.status;
83
+ res = status === 404 || status === 410 ? notFoundPage(path, status) : renderFailed(path, err);
84
+ }
85
+ try {
86
+ for (const [k, v] of Object.entries(securityHeaders(siteMode() === 'preview'))) {
87
+ if (!res.headers.has(k)) res.headers.set(k, v);
88
+ }
89
+ } catch {
90
+ // immutable headers (Response.redirect): nothing to secure in a redirect
91
+ }
92
+ return res;
93
+ };
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@realadvisor-sites/kit-astro",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.0",
4
+ "description": "The Astro 5 kit for RealAdvisor sites on Cloudflare Workers: the integration (middleware, security headers, data env, site.json), the ra data client, and the components (images, listings search and map, enquiry form, legal, consent). Built on @realadvisor/sites-kit-core.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/realadvisor/sites.git",
9
+ "directory": "kit-astro"
10
+ },
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "provenance": true
14
+ },
15
+ "type": "module",
16
+ "homepage": "https://github.com/realadvisor/sites/tree/main/kit-astro#readme",
17
+ "files": [
18
+ "*.mjs",
19
+ "*.mts",
20
+ "*.ts",
21
+ "README.md",
22
+ "LICENSE",
23
+ "components",
24
+ "lib",
25
+ "tools"
26
+ ],
27
+ "keywords": [
28
+ "astro-component"
29
+ ],
30
+ "exports": {
31
+ ".": {
32
+ "types": "./astro.d.mts",
33
+ "default": "./astro.mjs"
34
+ },
35
+ "./middleware": "./middleware.ts",
36
+ "./ra": "./lib/ra.ts",
37
+ "./components/*": "./components/*",
38
+ "./tools/*": "./tools/*",
39
+ "./package.json": "./package.json"
40
+ },
41
+ "peerDependencies": {
42
+ "@realadvisor/sites-kit-core": "^0.4.0",
43
+ "@realadvisor/sites-sdk": "^0.4.0",
44
+ "astro": "^5.18.2"
45
+ }
46
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Every built file a page or script asks for ships in dist/.
3
+ *
4
+ * Astro deletes a stylesheet it inlines into the page (`build.inlineStylesheets`
5
+ * 'always', or 'auto' under the size limit), but a client script that loads it
6
+ * with a dynamic import (`await import('leaflet/dist/leaflet.css')`) still
7
+ * preloads `/_astro/<name>.css`: on the Worker that is a 404 HTML page,
8
+ * "Refused to apply style ... MIME type text/html", "Unable to preload CSS",
9
+ * and the import (a map, a carousel) never runs.
10
+ *
11
+ * This integration keeps a copy of every asset Vite emits (client and server
12
+ * builds) and, after the build, writes back each one that a built .js / .mjs /
13
+ * .css / .html file references under `_astro/` but that is missing from dist/.
14
+ * Keep it in astro.config.mjs (`integrations`).
15
+ */
16
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
17
+ import { dirname, join } from 'node:path';
18
+ import { fileURLToPath } from 'node:url';
19
+
20
+ const REF = /_astro\/[A-Za-z0-9._@~-]+\.[A-Za-z0-9]+/g;
21
+ const TEXT = /\.(m?js|css|html)$/;
22
+
23
+ const walk = (dir) =>
24
+ existsSync(dir)
25
+ ? readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(join(dir, e.name)) : [join(dir, e.name)]))
26
+ : [];
27
+
28
+ /** `_astro/...` paths referenced by built text files in `dist` and missing from it. */
29
+ export function missingAssets(dist) {
30
+ const missing = new Map(); // path -> first file that references it
31
+ for (const file of walk(dist).filter((f) => TEXT.test(f))) {
32
+ for (const [ref] of readFileSync(file, 'utf8').matchAll(REF)) {
33
+ if (!missing.has(ref) && !existsSync(join(dist, ref))) missing.set(ref, file.slice(dist.length + 1));
34
+ }
35
+ }
36
+ return missing;
37
+ }
38
+
39
+ /** @returns {import('astro').AstroIntegration} */
40
+ export function keepReferencedAssets() {
41
+ const emitted = new Map(); // fileName -> source
42
+ return {
43
+ name: 'ra-keep-referenced-assets',
44
+ hooks: {
45
+ 'astro:config:setup': ({ updateConfig }) => {
46
+ updateConfig({
47
+ vite: {
48
+ plugins: [
49
+ {
50
+ name: 'ra-keep-referenced-assets',
51
+ // Before Astro's inline-stylesheets step deletes them from the bundle.
52
+ generateBundle: {
53
+ order: 'pre',
54
+ handler(_options, bundle) {
55
+ for (const out of Object.values(bundle)) if (out.type === 'asset') emitted.set(out.fileName, out.source);
56
+ },
57
+ },
58
+ },
59
+ ],
60
+ },
61
+ });
62
+ },
63
+ 'astro:build:done': ({ dir, logger }) => {
64
+ const dist = fileURLToPath(dir).replace(/\/$/, '');
65
+ for (const [ref, from] of missingAssets(dist)) {
66
+ const source = emitted.get(ref);
67
+ if (source == null) {
68
+ // The server manifest also names module ids (entryModules) that are no files.
69
+ if (!from.startsWith('_worker.js/')) logger.warn(`${ref} is referenced by ${from} but was not emitted by the build`);
70
+ continue;
71
+ }
72
+ mkdirSync(dirname(join(dist, ref)), { recursive: true });
73
+ writeFileSync(join(dist, ref), source);
74
+ logger.info(`restored ${ref} (inlined by Astro, still loaded by ${from})`);
75
+ }
76
+ },
77
+ },
78
+ };
79
+ }