create-ailk 0.46.2 → 0.46.3

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,317 @@
1
+ /**
2
+ * The magnets this site serves at an owner-chosen address (#12204, spec
3
+ * docs/specs/12204-an-owner-chosen-address-a-spec.md D5, D6, D8, D9) — the
4
+ * only site code that reads the hub's address table.
5
+ *
6
+ * - `readAddressTable()` reads `GET /v1/flow-addresses` (`flows.addresses()`),
7
+ * shared per instance for 15 seconds (the `/contact` window, #8731) by
8
+ * holding the read's promise, so concurrent reads share one call and a
9
+ * failed read is held for the same window (SEC-12204-6). Every item is
10
+ * re-parsed and dropped when it fails (NFR-4). A failed read answers the
11
+ * last good table, else `[]`; an older hub's 404 is `[]`. A site that does
12
+ * not carry the signal-collectors package (keyless, or module-less) makes
13
+ * no read.
14
+ * - `servedAddresses(locale)` is the table less every address something on the
15
+ * site claims first (D5 a–d): a static route, a reserved segment, an enabled
16
+ * locale, the docs or services base, a renamed family, a `LandingPage` or
17
+ * `BlogList` source at the first segment, or a recorded page redirect. It is
18
+ * computed once per table refresh per locale, probing only the table's
19
+ * distinct first segments — never the requested path (SEC-12204-6).
20
+ * - `magnetPageAt` / `magnetMetadataAt` serve an address and its children
21
+ * through the package's `renderMagnetAt` / `magnetMetadataAt`;
22
+ * `servedAddressOf` is what the `/flows/<slug>` pages forward by.
23
+ *
24
+ * Every consumer reads the served set, so the catch-all, the forward, the
25
+ * sitemap, `llms.txt` and the back arrow agree. Nothing here throws: a hub
26
+ * outage serves no address, never a 500 (NFR-3).
27
+ */
28
+ import { flows, pages } from "@working-theory/api-client";
29
+ import { resolvedAdapterKind } from "@working-theory/content-adapters";
30
+ import { getMdxSource } from "@working-theory/page-renderer";
31
+ import { routeRenames } from "@working-theory/templates/routes";
32
+ import {
33
+ FLOW_ADDRESS_MAX,
34
+ flowAddressItemSchema,
35
+ MAGNET_ADDRESS_RESERVED_SEGMENTS,
36
+ type FlowAddressItem,
37
+ } from "@working-theory/validation";
38
+ import { readLocales } from "@working-theory/web-i18n";
39
+ import type { Metadata } from "next";
40
+ import type { ReactElement } from "react";
41
+
42
+ import { resolveBaseUrl } from "../src/lib/routes";
43
+
44
+ import { DOCS_PATH } from "./docs-path";
45
+ import { loadUiSignalCollectors } from "./paid-sections.generated";
46
+ import { staticFirstSegments } from "./served-pages";
47
+ import { SERVICES_PATH } from "./services-path";
48
+
49
+ /** How long one table read is shared (#8731's window). */
50
+ export const ADDRESS_TABLE_TTL_MS = 15_000;
51
+
52
+ /**
53
+ * How long one table read may take before it counts as failed: the site's
54
+ * hub-read deadline (`HUB_READ_DEADLINE_MS`, `lib/in-page-magnet.ts`), since
55
+ * the layout, every `[slug]` miss and every `/flows/<slug>` page await it. Not
56
+ * imported: that module pulls the in-page server actions into every page.
57
+ */
58
+ export const ADDRESS_TABLE_DEADLINE_MS = 2_000;
59
+
60
+ interface Table {
61
+ items: readonly FlowAddressItem[];
62
+ /** The served set per locale, computed once per table. */
63
+ served: Map<string, Promise<readonly FlowAddressItem[]>>;
64
+ }
65
+
66
+ let current: { at: number; table: Promise<Table> } | undefined;
67
+ let lastGood: readonly FlowAddressItem[] | undefined;
68
+
69
+ const LATE = Symbol("late");
70
+
71
+ function withDeadline<T>(read: Promise<T>): Promise<T | typeof LATE> {
72
+ let timer: ReturnType<typeof setTimeout> | undefined;
73
+ const late = new Promise<typeof LATE>((resolve) => {
74
+ timer = setTimeout(() => resolve(LATE), ADDRESS_TABLE_DEADLINE_MS);
75
+ });
76
+ return Promise.race([read, late]).finally(() => clearTimeout(timer));
77
+ }
78
+
79
+ /** Each item that parses, the first per path, at most `FLOW_ADDRESS_MAX`. */
80
+ function parseItems(raw: unknown): FlowAddressItem[] | null {
81
+ if (!Array.isArray(raw)) return null;
82
+ const items: FlowAddressItem[] = [];
83
+ const paths = new Set<string>();
84
+ for (const entry of raw.slice(0, FLOW_ADDRESS_MAX)) {
85
+ const parsed = flowAddressItemSchema.safeParse(entry);
86
+ if (!parsed.success || paths.has(parsed.data.path)) continue;
87
+ paths.add(parsed.data.path);
88
+ items.push(parsed.data);
89
+ }
90
+ return items;
91
+ }
92
+
93
+ async function fetchItems(): Promise<readonly FlowAddressItem[]> {
94
+ try {
95
+ if ((await loadUiSignalCollectors()) === null) return [];
96
+ const res = await withDeadline(flows.addresses());
97
+ if (res === LATE) return lastGood ?? [];
98
+ if (!res.ok) {
99
+ // An older hub serves no table (D14): that is an empty answer.
100
+ if (res.status === 404) return (lastGood = []);
101
+ return lastGood ?? [];
102
+ }
103
+ const body: unknown = res.body;
104
+ const items = parseItems(
105
+ typeof body === "object" && body !== null
106
+ ? (body as { addresses?: unknown }).addresses
107
+ : undefined,
108
+ );
109
+ if (items === null) return lastGood ?? [];
110
+ return (lastGood = items);
111
+ } catch {
112
+ return lastGood ?? [];
113
+ }
114
+ }
115
+
116
+ function readTable(): Promise<Table> {
117
+ const now = Date.now();
118
+ if (current && now - current.at < ADDRESS_TABLE_TTL_MS) return current.table;
119
+ const table = fetchItems().then((items): Table => ({
120
+ items,
121
+ served: new Map(),
122
+ }));
123
+ current = { at: now, table };
124
+ return table;
125
+ }
126
+
127
+ /** The hub's address table, re-parsed; `[]` when there is none to read. */
128
+ export async function readAddressTable(): Promise<readonly FlowAddressItem[]> {
129
+ return (await readTable()).items;
130
+ }
131
+
132
+ const RESERVED = new Set(MAGNET_ADDRESS_RESERVED_SEGMENTS);
133
+
134
+ function firstSegment(path: string): string {
135
+ return path.slice(1).split("/")[0] ?? "";
136
+ }
137
+
138
+ /** D5 (b) — first segments the site holds by configuration. */
139
+ function configuredSegments(): Set<string> {
140
+ const held = new Set<string>([
141
+ firstSegment(DOCS_PATH),
142
+ firstSegment(SERVICES_PATH),
143
+ ]);
144
+ try {
145
+ for (const [from, to] of Object.entries(routeRenames())) {
146
+ held.add(from);
147
+ held.add(to);
148
+ }
149
+ } catch {
150
+ // A malformed bake fails the build; nothing more to hold here.
151
+ }
152
+ return held;
153
+ }
154
+
155
+ function enabledLocales(): string[] {
156
+ try {
157
+ return readLocales();
158
+ } catch {
159
+ return (process.env.NEXT_PUBLIC_ENABLED_LOCALES ?? "en")
160
+ .split(",")
161
+ .map((l) => l.trim());
162
+ }
163
+ }
164
+
165
+ /** D5 (c) — a content page the `[slug]` route reads first; a failed probe counts as one. */
166
+ async function contentAt(segment: string, locale: string): Promise<boolean> {
167
+ try {
168
+ if ((await getMdxSource("LandingPage", segment, locale)) !== null)
169
+ return true;
170
+ return (await getMdxSource("BlogList", segment, locale)) !== null;
171
+ } catch {
172
+ return true;
173
+ }
174
+ }
175
+
176
+ /** D5 (d) — a moved page's old address, recorded only by the database adapter (#10202). */
177
+ async function redirectAt(path: string, locale: string): Promise<boolean> {
178
+ if (resolvedAdapterKind() !== "database") return false;
179
+ try {
180
+ const res = await pages.redirect(path, { locale });
181
+ return res.ok;
182
+ } catch {
183
+ return false;
184
+ }
185
+ }
186
+
187
+ async function computeServed(
188
+ items: readonly FlowAddressItem[],
189
+ locale: string,
190
+ ): Promise<readonly FlowAddressItem[]> {
191
+ if (items.length === 0) return [];
192
+ const statics = new Set(staticFirstSegments());
193
+ const configured = configuredSegments();
194
+ const locales = new Set(enabledLocales());
195
+ const firsts = [...new Set(items.map((item) => firstSegment(item.path)))];
196
+ const shadowedFirsts = new Set<string>();
197
+ await Promise.all(
198
+ firsts.map(async (first) => {
199
+ if (
200
+ statics.has(first) ||
201
+ RESERVED.has(first) ||
202
+ locales.has(first) ||
203
+ configured.has(first) ||
204
+ (await contentAt(first, locale))
205
+ ) {
206
+ shadowedFirsts.add(first);
207
+ }
208
+ }),
209
+ );
210
+ const kept = items.filter(
211
+ (item) => !shadowedFirsts.has(firstSegment(item.path)),
212
+ );
213
+ const redirected = await Promise.all(
214
+ kept.map((item) => redirectAt(item.path, locale)),
215
+ );
216
+ return kept.filter((_, i) => !redirected[i]);
217
+ }
218
+
219
+ /**
220
+ * The addresses this site serves in `locale`: the table less every shadowed
221
+ * address (D5). Never rejects.
222
+ */
223
+ export async function servedAddresses(
224
+ locale: string,
225
+ ): Promise<readonly FlowAddressItem[]> {
226
+ // A dotted path reaches `[locale]` with any segment, and `generateMetadata`
227
+ // runs before the layout's locale check: only an enabled locale keys a
228
+ // computation, so a crafted one costs no hub read.
229
+ if (!enabledLocales().includes(locale)) return [];
230
+ try {
231
+ const table = await readTable();
232
+ let served = table.served.get(locale);
233
+ if (served === undefined) {
234
+ served = computeServed(table.items, locale).catch(() => []);
235
+ table.served.set(locale, served);
236
+ }
237
+ return await served;
238
+ } catch {
239
+ return [];
240
+ }
241
+ }
242
+
243
+ /** The address this site serves `slug` at in `locale`, or `null` (D7's forward). */
244
+ export async function servedAddressOf(
245
+ slug: string,
246
+ locale: string,
247
+ ): Promise<string | null> {
248
+ const served = await servedAddresses(locale);
249
+ return served.find((item) => item.slug === slug)?.path ?? null;
250
+ }
251
+
252
+ /** D6 — the children an address serves: the cover, `start`, `verify`, `results/<payload>`. */
253
+ function isChild(rest: readonly string[]): boolean {
254
+ if (rest.length === 0) return true;
255
+ if (rest.length === 1) return rest[0] === "start" || rest[0] === "verify";
256
+ return rest.length === 2 && rest[0] === "results" && (rest[1] ?? "") !== "";
257
+ }
258
+
259
+ async function matchAt(
260
+ segments: readonly string[],
261
+ locale: string,
262
+ ): Promise<{ item: FlowAddressItem; rest: string[] } | null> {
263
+ for (const item of await servedAddresses(locale)) {
264
+ const base = item.path.slice(1).split("/");
265
+ if (
266
+ base.length > segments.length ||
267
+ !base.every((s, i) => s === segments[i])
268
+ )
269
+ continue;
270
+ const rest = segments.slice(base.length);
271
+ if (isChild(rest)) return { item, rest };
272
+ }
273
+ return null;
274
+ }
275
+
276
+ /** D8 — the address's canonical URL, with the locale prefix the sitemap uses. */
277
+ function canonicalOf(locale: string, path: string): string {
278
+ const defaultLocale = process.env.NEXT_PUBLIC_DEFAULT_LOCALE ?? "en";
279
+ return `${resolveBaseUrl()}${locale === defaultLocale ? "" : `/${locale}`}${path}`;
280
+ }
281
+
282
+ /** The magnet page at `segments` (an address or a child of one), or `null`. */
283
+ export async function magnetPageAt(
284
+ segments: string[],
285
+ locale: string,
286
+ searchParams: Record<string, string | string[] | undefined>,
287
+ ): Promise<ReactElement | null> {
288
+ const match = await matchAt(segments, locale);
289
+ if (match === null) return null;
290
+ const pkg = await loadUiSignalCollectors();
291
+ if (pkg === null) return null;
292
+ return (await pkg.renderMagnetAt({
293
+ slug: match.item.slug,
294
+ base: match.item.path,
295
+ rest: match.rest,
296
+ locale,
297
+ searchParams,
298
+ })) as ReactElement | null;
299
+ }
300
+
301
+ /** The metadata of the magnet page at `segments`, or `null`. */
302
+ export async function magnetMetadataAt(
303
+ segments: string[],
304
+ locale: string,
305
+ ): Promise<Metadata | null> {
306
+ const match = await matchAt(segments, locale);
307
+ if (match === null) return null;
308
+ const pkg = await loadUiSignalCollectors();
309
+ if (pkg === null) return null;
310
+ return (await pkg.magnetMetadataAt({
311
+ slug: match.item.slug,
312
+ base: match.item.path,
313
+ rest: match.rest,
314
+ locale,
315
+ canonical: canonicalOf(locale, match.item.path),
316
+ })) as Metadata | null;
317
+ }