@crombolo/render 0.36.2 → 0.38.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.
- package/package.json +5 -2
- package/src/bundle-script.ts +4 -7
- package/src/component-stack.ts +53 -0
- package/src/context.ts +68 -7
- package/src/headers.ts +86 -0
- package/src/index.ts +5 -0
- package/src/islands-loader.ts +152 -0
- package/src/islands.ts +220 -0
- package/src/jsx-runtime.ts +40 -2
- package/src/live-reload.ts +78 -0
- package/src/media.ts +101 -22
- package/src/model.ts +39 -3
- package/src/navigation.ts +70 -0
- package/src/published-cache.ts +41 -3
- package/src/renderer.ts +225 -41
- package/src/seo.ts +63 -1
- package/src/site.ts +106 -0
- package/src/snapshots.ts +32 -1
- package/src/values.ts +49 -5
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ending a page early, as `next/navigation` does: each function throws an
|
|
3
|
+
* outcome from any component, layout or block, and the page answers its status
|
|
4
|
+
* (story 206). The page renders whole before it answers, so a throw at any
|
|
5
|
+
* depth never meets a half-sent response.
|
|
6
|
+
*/
|
|
7
|
+
import { type FieldError, isOutcome, Outcome } from '@crombolo/core'
|
|
8
|
+
|
|
9
|
+
/** 307: sends the visitor on, keeping the request's method. */
|
|
10
|
+
export function redirect(url: string): never {
|
|
11
|
+
throw Outcome.redirect(url)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** 308: the page has moved for good. */
|
|
15
|
+
export function permanentRedirect(url: string): never {
|
|
16
|
+
throw Outcome.permanentRedirect(url)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** 404, rendered by the site's not-found page with `message` in `usePage().outcome`. */
|
|
20
|
+
export function notFound(message?: string): never {
|
|
21
|
+
throw Outcome.notFound(message)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** 403, rendered by the site's error page. */
|
|
25
|
+
export function forbidden(message?: string): never {
|
|
26
|
+
throw Outcome.forbidden(message)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** 401, rendered by the site's unauthorized page. */
|
|
30
|
+
export function unauthorized(message?: string): never {
|
|
31
|
+
throw Outcome.unauthorized(message)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 302: the everyday redirect, as `umbracoRedirect` answers. */
|
|
35
|
+
export function foundAt(url: string): never {
|
|
36
|
+
throw Outcome.foundAt(url)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 301: the page has moved for good. */
|
|
40
|
+
export function movedPermanentlyTo(url: string): never {
|
|
41
|
+
throw Outcome.movedPermanentlyTo(url)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 303: after a POST, look at this address. */
|
|
45
|
+
export function seeOther(url: string): never {
|
|
46
|
+
throw Outcome.seeOther(url)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 400: a request the page cannot use. */
|
|
50
|
+
export function badRequest(message?: string, errors?: readonly FieldError[]): never {
|
|
51
|
+
throw Outcome.badRequest(message, errors)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 410: the page is gone for good. */
|
|
55
|
+
export function gone(message?: string): never {
|
|
56
|
+
throw Outcome.gone(message)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 422: well-formed input that failed validation. */
|
|
60
|
+
export function unprocessableContent(errors: readonly FieldError[], message?: string): never {
|
|
61
|
+
throw Outcome.unprocessableContent(errors, message)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* For code that catches errors for its own reasons: rethrows an outcome so the
|
|
66
|
+
* page still answers it, and returns for anything else.
|
|
67
|
+
*/
|
|
68
|
+
export function rethrow(error: unknown): void {
|
|
69
|
+
if (isOutcome(error)) throw error
|
|
70
|
+
}
|
package/src/published-cache.ts
CHANGED
|
@@ -350,6 +350,17 @@ export async function menusIn(
|
|
|
350
350
|
return out
|
|
351
351
|
}
|
|
352
352
|
|
|
353
|
+
/**
|
|
354
|
+
* Lets waiting requests in every few hundred nodes: a rebuild is long, and on
|
|
355
|
+
* SQLite nothing else in it ever gives the thread up (story 175).
|
|
356
|
+
*/
|
|
357
|
+
function pacer(every = 250): () => Promise<void> {
|
|
358
|
+
let count = 0
|
|
359
|
+
return async () => {
|
|
360
|
+
if (++count % every === 0) await new Promise<void>((resolve) => setImmediate(resolve))
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
353
364
|
export class PublishedCache {
|
|
354
365
|
#source: PublishedContentSource
|
|
355
366
|
#snapshot: CacheSnapshot = EMPTY
|
|
@@ -375,14 +386,37 @@ export class PublishedCache {
|
|
|
375
386
|
}
|
|
376
387
|
|
|
377
388
|
/**
|
|
378
|
-
* The current snapshot, building it if it was dropped.
|
|
379
|
-
*
|
|
380
|
-
*
|
|
389
|
+
* The current snapshot, building it if it was dropped. The reader that starts
|
|
390
|
+
* a build waits for it; readers arriving while it builds are answered from
|
|
391
|
+
* the previous snapshot rather than waiting (story 175). Before the first
|
|
392
|
+
* build there is none, so they share the build.
|
|
381
393
|
*/
|
|
382
394
|
async snapshot(): Promise<CacheSnapshot> {
|
|
395
|
+
if (this.#loaded) return this.#snapshot
|
|
396
|
+
const generation = this.#generation
|
|
397
|
+
if (this.#building?.generation === generation)
|
|
398
|
+
return this.#snapshotGeneration >= 0 ? this.#snapshot : this.#building.done
|
|
399
|
+
return this.#start(generation)
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** Whether readers are being answered from a snapshot older than the latest change. */
|
|
403
|
+
get stale(): boolean {
|
|
404
|
+
return !this.#loaded && this.#snapshotGeneration >= 0
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** The snapshot holding every change made so far, waiting for a build in flight. */
|
|
408
|
+
async fresh(): Promise<CacheSnapshot> {
|
|
383
409
|
if (this.#loaded) return this.#snapshot
|
|
384
410
|
const generation = this.#generation
|
|
385
411
|
if (this.#building?.generation === generation) return this.#building.done
|
|
412
|
+
return this.#start(generation)
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* Builds for `generation`. A build an invalidation overtook still answers,
|
|
417
|
+
* but the next read builds again.
|
|
418
|
+
*/
|
|
419
|
+
#start(generation: number): Promise<CacheSnapshot> {
|
|
386
420
|
const done = this.#build().then((snapshot) => {
|
|
387
421
|
// A slower, older build must not replace a newer one that finished first,
|
|
388
422
|
// nor a snapshot of older data one of newer data.
|
|
@@ -715,6 +749,7 @@ export class PublishedCache {
|
|
|
715
749
|
checkpoint: number | undefined,
|
|
716
750
|
): Promise<CacheSnapshot> {
|
|
717
751
|
const builtAt = new Date()
|
|
752
|
+
const pace = pacer()
|
|
718
753
|
const nodes = await source.loadPublished()
|
|
719
754
|
const domains = (await source.loadDomains?.()) ?? []
|
|
720
755
|
const languages = (await source.loadLanguages?.()) ?? []
|
|
@@ -787,6 +822,7 @@ export class PublishedCache {
|
|
|
787
822
|
}
|
|
788
823
|
const segmentOf = new Map<number, string>()
|
|
789
824
|
for (const node of nodes) {
|
|
825
|
+
await pace()
|
|
790
826
|
if (!inCulture(node)) continue
|
|
791
827
|
const override =
|
|
792
828
|
node.properties.find(
|
|
@@ -863,6 +899,7 @@ export class PublishedCache {
|
|
|
863
899
|
.filter(inCulture)
|
|
864
900
|
.sort((a, b) => a.level - b.level || a.sortOrder - b.sortOrder)
|
|
865
901
|
for (const node of ordered) {
|
|
902
|
+
await pace()
|
|
866
903
|
const route = routeOf(node)
|
|
867
904
|
if (route === undefined) continue
|
|
868
905
|
const domainRoute = domainRouteOf(node)
|
|
@@ -976,6 +1013,7 @@ export class PublishedCache {
|
|
|
976
1013
|
}
|
|
977
1014
|
|
|
978
1015
|
for (const content of view.byId.values()) {
|
|
1016
|
+
await pace()
|
|
979
1017
|
content.withValueContext(context)
|
|
980
1018
|
// Ancestors are wired after every node exists, for the `ancestors` fallback.
|
|
981
1019
|
const ancestors: PublishedContent[] = []
|
package/src/renderer.ts
CHANGED
|
@@ -6,24 +6,41 @@
|
|
|
6
6
|
* `export const layout = 'alias'` names the layout template, which is how Umbraco
|
|
7
7
|
* declares it too — in the file, not the database.
|
|
8
8
|
*/
|
|
9
|
-
import { existsSync } from 'node:fs'
|
|
9
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
10
10
|
import { basename, join, resolve, sep } from 'node:path'
|
|
11
11
|
import { pathToFileURL } from 'node:url'
|
|
12
|
-
import type
|
|
13
|
-
import {
|
|
12
|
+
import { type FormSubmissionState, isOutcome, type Outcome } from '@crombolo/core'
|
|
13
|
+
import { componentStackOf, trackComponent } from './component-stack.ts'
|
|
14
|
+
import { emailScope, markPersonal, renderScope } from './context.ts'
|
|
14
15
|
import type { EmailProps, EmailRenderResult } from './email.ts'
|
|
15
16
|
import { RawHtml } from './html.ts'
|
|
17
|
+
import { ISLANDS_PATH, withIslandTags } from './islands.ts'
|
|
16
18
|
import { type Child, renderToString } from './jsx-runtime.ts'
|
|
17
|
-
import type {
|
|
19
|
+
import type {
|
|
20
|
+
PageOutcome,
|
|
21
|
+
PageProps,
|
|
22
|
+
PublishedContent,
|
|
23
|
+
RequestMember,
|
|
24
|
+
SearchParams,
|
|
25
|
+
} from './model.ts'
|
|
18
26
|
import { type PublishedCache, translate, urlsIn } from './published-cache.ts'
|
|
19
27
|
import type { SiteSearchPort } from './search.ts'
|
|
20
|
-
import { absoluteUrl, type SeoSiteDefaults } from './seo.ts'
|
|
28
|
+
import { absoluteUrl, type Metadata, type SeoSiteDefaults } from './seo.ts'
|
|
21
29
|
import type { ViewSnapshots } from './snapshots.ts'
|
|
22
30
|
|
|
23
31
|
export interface ComponentModule {
|
|
24
32
|
default: (props: PageProps) => Child | Promise<Child>
|
|
25
33
|
/** Alias of the layout template to wrap this one in. */
|
|
26
34
|
layout?: string
|
|
35
|
+
/**
|
|
36
|
+
* As Next.js's route segment config: `force-dynamic` is always personal;
|
|
37
|
+
* `force-static` empties the request's values so the page can be shared.
|
|
38
|
+
*/
|
|
39
|
+
dynamic?: 'auto' | 'force-dynamic' | 'force-static'
|
|
40
|
+
/** Seconds copies of the page may be kept, or false for as long as it is unchanged. */
|
|
41
|
+
revalidate?: number | false
|
|
42
|
+
/** Search and sharing values worked out per request, laid over the page's own. */
|
|
43
|
+
generateMetadata?: (props: PageProps) => Metadata | Promise<Metadata>
|
|
27
44
|
}
|
|
28
45
|
|
|
29
46
|
// biome-ignore lint/suspicious/noExplicitAny: an untyped page, as `PageProps` defaults to.
|
|
@@ -44,12 +61,27 @@ export interface RenderOptions {
|
|
|
44
61
|
snapshots?: ViewSnapshots
|
|
45
62
|
/** How long a page may take to render, layouts included; 0 for no limit. */
|
|
46
63
|
renderTimeoutMs?: number
|
|
64
|
+
/**
|
|
65
|
+
* Where a page's island code is described, for the generation it rendered
|
|
66
|
+
* with (story 209); by default the generation's own build.
|
|
67
|
+
*/
|
|
68
|
+
islandsManifest?: (generation: string | undefined) => string | undefined
|
|
47
69
|
}
|
|
48
70
|
|
|
49
71
|
export const DEFAULT_RENDER_TIMEOUT_MS = 10_000
|
|
50
72
|
|
|
73
|
+
/** What a rendered page says about how its answer may be kept. */
|
|
74
|
+
export interface RenderedCaching {
|
|
75
|
+
/** It read something that depends on who is asking, so it is never shared. */
|
|
76
|
+
personal: boolean
|
|
77
|
+
/** The template's own `revalidate`, overriding its type's and the site's lifetime. */
|
|
78
|
+
revalidate?: number | false
|
|
79
|
+
}
|
|
80
|
+
|
|
51
81
|
export type RenderResult =
|
|
52
|
-
| { status: 'ok'; html: string; content: PublishedContent }
|
|
82
|
+
| ({ status: 'ok'; html: string; content: PublishedContent } & RenderedCaching)
|
|
83
|
+
/** A component threw a redirect or a refusal (story 206). */
|
|
84
|
+
| ({ status: 'outcome'; outcome: Outcome; content: PublishedContent } & RenderedCaching)
|
|
53
85
|
| { status: 'notFound' }
|
|
54
86
|
/** The page names another to send its visitors to (`umbracoRedirect`). */
|
|
55
87
|
| { status: 'redirect'; location: string; content: PublishedContent }
|
|
@@ -58,6 +90,9 @@ export type RenderResult =
|
|
|
58
90
|
|
|
59
91
|
const MAX_LAYOUT_DEPTH = 10
|
|
60
92
|
|
|
93
|
+
/** Why a finished render's signal is aborted: whatever still listens can let go. */
|
|
94
|
+
const RENDERED = new Error('The page has rendered.')
|
|
95
|
+
|
|
61
96
|
/**
|
|
62
97
|
* A whole document gets `<!DOCTYPE html>`, which JSX has no way to write and
|
|
63
98
|
* without which a browser renders in quirks mode. A page that writes its own,
|
|
@@ -103,6 +138,52 @@ export interface RenderRequest {
|
|
|
103
138
|
preview?: boolean
|
|
104
139
|
/** The signed-in member's anti-forgery token, written by `<AntiforgeryMeta />` (story 186). */
|
|
105
140
|
antiforgery?: string
|
|
141
|
+
/** The request's headers, cookies among them, for `cookies()` and `headers()` (story 206). */
|
|
142
|
+
headers?: Headers
|
|
143
|
+
/** The site's services as whoever is asking, for `site()`. */
|
|
144
|
+
site?: () => unknown
|
|
145
|
+
/** On a status page, the outcome it is answering, for `usePage().outcome`. */
|
|
146
|
+
outcome?: PageOutcome
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** The query string as Next.js hands it to a page: a name given twice becomes an array. */
|
|
150
|
+
function queryOf(url: string): SearchParams {
|
|
151
|
+
const query: SearchParams = {}
|
|
152
|
+
let params: URLSearchParams
|
|
153
|
+
try {
|
|
154
|
+
params = new URL(url).searchParams
|
|
155
|
+
} catch {
|
|
156
|
+
return query
|
|
157
|
+
}
|
|
158
|
+
for (const [name, value] of params) {
|
|
159
|
+
const seen = query[name]
|
|
160
|
+
query[name] =
|
|
161
|
+
seen === undefined ? value : Array.isArray(seen) ? [...seen, value] : [seen, value]
|
|
162
|
+
}
|
|
163
|
+
return query
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* The query as a promise that marks the page personal once anything awaits it.
|
|
168
|
+
* Handing the promise on, as spreading a page's props does, marks nothing. A
|
|
169
|
+
* subclass, because `await` on a plain promise never calls its own `then`.
|
|
170
|
+
*/
|
|
171
|
+
class PersonalPromise<T> extends Promise<T> {
|
|
172
|
+
static override get [Symbol.species]() {
|
|
173
|
+
return Promise
|
|
174
|
+
}
|
|
175
|
+
// biome-ignore lint/suspicious/noThenProperty: marking the read is the point of it.
|
|
176
|
+
override then<A = T, B = never>(
|
|
177
|
+
onFulfilled?: ((value: T) => A | PromiseLike<A>) | null,
|
|
178
|
+
onRejected?: ((reason: unknown) => B | PromiseLike<B>) | null,
|
|
179
|
+
): Promise<A | B> {
|
|
180
|
+
markPersonal()
|
|
181
|
+
return super.then(onFulfilled, onRejected)
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function personalPromise(query: SearchParams): Promise<SearchParams> {
|
|
186
|
+
return new PersonalPromise<SearchParams>((resolve) => resolve(query))
|
|
106
187
|
}
|
|
107
188
|
|
|
108
189
|
/**
|
|
@@ -126,6 +207,7 @@ export class Renderer {
|
|
|
126
207
|
#modules = new Map<string, ComponentModule>()
|
|
127
208
|
#importedFrom: string | undefined
|
|
128
209
|
#renderTimeoutMs: number
|
|
210
|
+
#islandsManifest: (generation: string | undefined) => string | undefined
|
|
129
211
|
|
|
130
212
|
constructor(options: RenderOptions) {
|
|
131
213
|
this.#cache = options.cache
|
|
@@ -134,6 +216,9 @@ export class Renderer {
|
|
|
134
216
|
this.#componentsDir = resolve(options.componentsDir)
|
|
135
217
|
this.#snapshots = options.snapshots
|
|
136
218
|
this.#renderTimeoutMs = options.renderTimeoutMs ?? DEFAULT_RENDER_TIMEOUT_MS
|
|
219
|
+
this.#islandsManifest =
|
|
220
|
+
options.islandsManifest ??
|
|
221
|
+
((generation) => (generation ? `${ISLANDS_PATH}/${generation}/manifest.json` : undefined))
|
|
137
222
|
}
|
|
138
223
|
|
|
139
224
|
/**
|
|
@@ -177,8 +262,11 @@ export class Renderer {
|
|
|
177
262
|
// `..`, an absolute path and a drive letter are all refused while
|
|
178
263
|
// `pages/homePage` resolves.
|
|
179
264
|
if (!isSafeComponentAlias(alias)) return undefined
|
|
180
|
-
const
|
|
181
|
-
|
|
265
|
+
const dir = this.#importDir()
|
|
266
|
+
// A template may be a folder, as a Next.js route is, so its partials sit beside it.
|
|
267
|
+
for (const file of [join(dir, `${alias}.tsx`), join(dir, alias, 'page.tsx')])
|
|
268
|
+
if (existsSync(file)) return file
|
|
269
|
+
return undefined
|
|
182
270
|
}
|
|
183
271
|
|
|
184
272
|
/**
|
|
@@ -209,14 +297,7 @@ export class Renderer {
|
|
|
209
297
|
const content = permitted
|
|
210
298
|
if (!content.componentAlias) return { status: 'noTemplate', content }
|
|
211
299
|
|
|
212
|
-
|
|
213
|
-
const html = await this.#renderContent(content, content.componentAlias, culture, request)
|
|
214
|
-
return html === undefined
|
|
215
|
-
? { status: 'noTemplate', content }
|
|
216
|
-
: { status: 'ok', html, content }
|
|
217
|
-
} catch (error) {
|
|
218
|
-
return { status: 'error', error: error as Error, content }
|
|
219
|
-
}
|
|
300
|
+
return this.#renderPage(content, content.componentAlias, culture, request)
|
|
220
301
|
}
|
|
221
302
|
|
|
222
303
|
/**
|
|
@@ -252,12 +333,25 @@ export class Renderer {
|
|
|
252
333
|
request: RenderRequest = {},
|
|
253
334
|
): Promise<RenderResult> {
|
|
254
335
|
if (!content.componentAlias) return { status: 'noTemplate', content }
|
|
336
|
+
return this.#renderPage(content, content.componentAlias, culture, request)
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
async #renderPage(
|
|
340
|
+
content: PublishedContent,
|
|
341
|
+
alias: string,
|
|
342
|
+
culture: string | null,
|
|
343
|
+
request: RenderRequest,
|
|
344
|
+
): Promise<RenderResult> {
|
|
345
|
+
const caching: RenderedCaching = { personal: false }
|
|
255
346
|
try {
|
|
256
|
-
const html = await this.#
|
|
347
|
+
const html = await this.#withDeadline(alias, request.signal, (signal, rendering) =>
|
|
348
|
+
this.#renderChain(content, alias, culture, request, signal, rendering, caching),
|
|
349
|
+
)
|
|
257
350
|
return html === undefined
|
|
258
351
|
? { status: 'noTemplate', content }
|
|
259
|
-
: { status: 'ok', html, content }
|
|
352
|
+
: { status: 'ok', html, content, ...caching }
|
|
260
353
|
} catch (error) {
|
|
354
|
+
if (isOutcome(error)) return { status: 'outcome', outcome: error, content, ...caching }
|
|
261
355
|
return { status: 'error', error: error as Error, content }
|
|
262
356
|
}
|
|
263
357
|
}
|
|
@@ -283,25 +377,32 @@ export class Renderer {
|
|
|
283
377
|
|
|
284
378
|
/** `The e-mail template 'x' failed at components/x.tsx:12: <what it threw>`. */
|
|
285
379
|
#emailFailure(alias: string, error: unknown): string {
|
|
380
|
+
const { message, location } = this.describeError(error)
|
|
381
|
+
return `The e-mail template '${alias}' failed${location ? ` at ${location}` : ''}: ${message}`
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* What a template threw, for a person to act on: its message, the first line
|
|
386
|
+
* under `components/` it failed on with the code around it, the component
|
|
387
|
+
* stack where one was recorded, and the stack, all naming files somebody can
|
|
388
|
+
* open.
|
|
389
|
+
*/
|
|
390
|
+
describeError(error: unknown): ErrorDescription {
|
|
286
391
|
const root = `${this.#componentsDir}${sep}`
|
|
287
392
|
const shown = `${basename(this.#componentsDir)}/`
|
|
288
393
|
const readable = (text: string) => this.inSource(text).replaceAll(root, shown)
|
|
289
394
|
const message = readable(error instanceof Error ? error.message : String(error)).trim()
|
|
290
395
|
const stack = error instanceof Error ? readable(error.stack ?? '') : ''
|
|
291
396
|
const escaped = shown.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
292
|
-
const frame = new RegExp(`${escaped}[^\\s:()]+\\.[jt]sx
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
): Promise<string | undefined> {
|
|
302
|
-
return this.#withDeadline(alias, request.signal, (signal, rendering) =>
|
|
303
|
-
this.#renderChain(content, alias, culture, request, signal, rendering),
|
|
304
|
-
)
|
|
397
|
+
const frame = new RegExp(`${escaped}([^\\s:()]+\\.[jt]sx?):(\\d+)`).exec(stack)
|
|
398
|
+
const components = componentStackOf(error)
|
|
399
|
+
return {
|
|
400
|
+
message,
|
|
401
|
+
stack,
|
|
402
|
+
...(frame ? { location: frame[0] } : {}),
|
|
403
|
+
...(frame ? codeAround(this.#componentsDir, frame[1] as string, Number(frame[2])) : {}),
|
|
404
|
+
...(components ? { components } : {}),
|
|
405
|
+
}
|
|
305
406
|
}
|
|
306
407
|
|
|
307
408
|
/** Runs a render under the time limit; the signal it hands on aborts when that runs out. */
|
|
@@ -325,8 +426,9 @@ export class Renderer {
|
|
|
325
426
|
this.#renderTimeoutMs,
|
|
326
427
|
)
|
|
327
428
|
: undefined
|
|
429
|
+
let fail = () => {}
|
|
328
430
|
const stopped = new Promise<never>((_, reject) => {
|
|
329
|
-
|
|
431
|
+
fail = () => reject(signal.reason)
|
|
330
432
|
if (signal.aborted) fail()
|
|
331
433
|
else signal.addEventListener('abort', fail, { once: true })
|
|
332
434
|
})
|
|
@@ -338,6 +440,10 @@ export class Renderer {
|
|
|
338
440
|
return await Promise.race([work, stopped])
|
|
339
441
|
} finally {
|
|
340
442
|
clearTimeout(timer)
|
|
443
|
+
// Bun keeps an `AbortSignal.any` signal, its sources and all they reach
|
|
444
|
+
// alive while anything listens to it, so every render would be kept.
|
|
445
|
+
signal.removeEventListener('abort', fail)
|
|
446
|
+
deadline.abort(RENDERED)
|
|
341
447
|
}
|
|
342
448
|
}
|
|
343
449
|
|
|
@@ -348,7 +454,17 @@ export class Renderer {
|
|
|
348
454
|
request: RenderRequest,
|
|
349
455
|
signal: AbortSignal,
|
|
350
456
|
rendering: { alias: string },
|
|
457
|
+
caching: RenderedCaching,
|
|
351
458
|
): Promise<string | undefined> {
|
|
459
|
+
const page = await this.#load(alias)
|
|
460
|
+
if (!page) return undefined
|
|
461
|
+
const dynamic = page.dynamic ?? 'auto'
|
|
462
|
+
const shared = dynamic === 'force-static'
|
|
463
|
+
if (typeof page.revalidate === 'number' || page.revalidate === false)
|
|
464
|
+
caching.revalidate = page.revalidate
|
|
465
|
+
// A static page reads nothing of the request, so what it marks is thrown away.
|
|
466
|
+
const personal = { value: dynamic === 'force-dynamic' }
|
|
467
|
+
const member = shared ? undefined : request.member
|
|
352
468
|
const nav = await this.#cache.navigation(culture)
|
|
353
469
|
const snapshot = await this.#cache.snapshot()
|
|
354
470
|
const dictionary = (key: string) => translate(snapshot, key, culture)
|
|
@@ -363,9 +479,13 @@ export class Renderer {
|
|
|
363
479
|
culture,
|
|
364
480
|
dictionary,
|
|
365
481
|
menu,
|
|
366
|
-
member
|
|
482
|
+
member,
|
|
367
483
|
submission: request.submission,
|
|
368
484
|
request: { origin, url: request.url ?? `${origin}/` },
|
|
485
|
+
searchParams: shared
|
|
486
|
+
? Promise.resolve({})
|
|
487
|
+
: personalPromise(queryOf(request.url ?? `${origin}/`)),
|
|
488
|
+
outcome: request.outcome,
|
|
369
489
|
urls: {
|
|
370
490
|
absolute: (target) => absoluteUrl(target.url, origin),
|
|
371
491
|
alternates: (target) => urlsIn(snapshot, target.key),
|
|
@@ -374,13 +494,37 @@ export class Renderer {
|
|
|
374
494
|
signal,
|
|
375
495
|
}
|
|
376
496
|
|
|
497
|
+
const metadata: { value?: Metadata } = {}
|
|
498
|
+
const islands = { used: false }
|
|
377
499
|
// Inside the page's scope, so any component can ask for it with `usePage()`.
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
500
|
+
try {
|
|
501
|
+
const html = await renderScope(
|
|
502
|
+
props,
|
|
503
|
+
async () => {
|
|
504
|
+
if (page.generateMetadata) metadata.value = await page.generateMetadata(props)
|
|
505
|
+
return this.#renderLayouts(alias, props, rendering)
|
|
506
|
+
},
|
|
507
|
+
{
|
|
508
|
+
search: request.search,
|
|
509
|
+
preview: request.preview,
|
|
510
|
+
antiforgery: request.antiforgery,
|
|
511
|
+
blockComponent: (blockAlias) => this.blockComponent(blockAlias),
|
|
512
|
+
request: { headers: shared ? new Headers() : (request.headers ?? new Headers()) },
|
|
513
|
+
site: request.site,
|
|
514
|
+
personal: shared ? { value: false } : personal,
|
|
515
|
+
metadata,
|
|
516
|
+
islands,
|
|
517
|
+
},
|
|
518
|
+
)
|
|
519
|
+
if (html === undefined || !islands.used) return html
|
|
520
|
+
// The generation the views were imported from, so the page loads the code built with them.
|
|
521
|
+
const manifest = this.#islandsManifest(
|
|
522
|
+
this.#importedFrom && this.#snapshots ? basename(this.#importedFrom) : undefined,
|
|
523
|
+
)
|
|
524
|
+
return manifest ? withIslandTags(html, manifest) : html
|
|
525
|
+
} finally {
|
|
526
|
+
caching.personal = !shared && (personal.value || member !== undefined)
|
|
527
|
+
}
|
|
384
528
|
}
|
|
385
529
|
|
|
386
530
|
/** Generic over its props: a page's, or an e-mail's. */
|
|
@@ -400,8 +544,10 @@ export class Renderer {
|
|
|
400
544
|
const module = await this.#load(currentAlias)
|
|
401
545
|
if (!module) return depth === 0 || body === undefined ? undefined : withDoctype(body.value)
|
|
402
546
|
const render = module.default as unknown as (props: object) => Child | Promise<Child>
|
|
403
|
-
const
|
|
404
|
-
body = new RawHtml(
|
|
547
|
+
const layoutProps = body === undefined ? props : { ...props, children: body }
|
|
548
|
+
body = new RawHtml(
|
|
549
|
+
await trackComponent(currentAlias, () => renderToString(render(layoutProps) as Child)),
|
|
550
|
+
)
|
|
405
551
|
currentAlias = module.layout
|
|
406
552
|
depth += 1
|
|
407
553
|
}
|
|
@@ -440,3 +586,41 @@ export class Renderer {
|
|
|
440
586
|
return module
|
|
441
587
|
}
|
|
442
588
|
}
|
|
589
|
+
|
|
590
|
+
/** What a template threw, for a person to act on (`Renderer.describeError`). */
|
|
591
|
+
export interface ErrorDescription {
|
|
592
|
+
message: string
|
|
593
|
+
/** The first line under `components/` it failed on: `components/card.tsx:12`. */
|
|
594
|
+
location?: string
|
|
595
|
+
stack: string
|
|
596
|
+
/** The lines around that one (story 214). */
|
|
597
|
+
code?: { line: number; lines: Array<{ number: number; text: string }> }
|
|
598
|
+
/** The components rendering when it was thrown, outermost first (story 214). */
|
|
599
|
+
components?: readonly string[]
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
const CODE_CONTEXT = 5
|
|
603
|
+
|
|
604
|
+
/** The lines either side of `line` in a file under `components/`, or nothing when it can't be read. */
|
|
605
|
+
function codeAround(
|
|
606
|
+
componentsDir: string,
|
|
607
|
+
file: string,
|
|
608
|
+
line: number,
|
|
609
|
+
): Pick<ErrorDescription, 'code'> {
|
|
610
|
+
const path = resolve(componentsDir, file)
|
|
611
|
+
if (!path.startsWith(`${resolve(componentsDir)}${sep}`)) return {}
|
|
612
|
+
let text: string
|
|
613
|
+
try {
|
|
614
|
+
text = readFileSync(path, 'utf8')
|
|
615
|
+
} catch {
|
|
616
|
+
return {}
|
|
617
|
+
}
|
|
618
|
+
const all = text.split('\n')
|
|
619
|
+
if (line < 1 || line > all.length) return {}
|
|
620
|
+
const from = Math.max(1, line - CODE_CONTEXT)
|
|
621
|
+
const to = Math.min(all.length, line + CODE_CONTEXT)
|
|
622
|
+
const lines = []
|
|
623
|
+
for (let number = from; number <= to; number++)
|
|
624
|
+
lines.push({ number, text: all[number - 1] as string })
|
|
625
|
+
return { code: { line, lines } }
|
|
626
|
+
}
|
package/src/seo.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* editor's preview both call it, so what an editor is shown is what is served.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
+
import { currentMetadata } from './context.ts'
|
|
9
10
|
import { RawHtml } from './html.ts'
|
|
10
11
|
import { element } from './jsx-runtime.ts'
|
|
11
12
|
import type { PublishedContent } from './model.ts'
|
|
@@ -43,8 +44,24 @@ export interface SeoOverrides {
|
|
|
43
44
|
noindex?: boolean
|
|
44
45
|
}
|
|
45
46
|
|
|
47
|
+
/**
|
|
48
|
+
* What a page's `generateMetadata` returns (story 206): the part of Next.js's
|
|
49
|
+
* `Metadata` that `<SeoHead>` writes. Each value given wins over the page's own.
|
|
50
|
+
*/
|
|
51
|
+
export interface Metadata {
|
|
52
|
+
title?: string
|
|
53
|
+
description?: string
|
|
54
|
+
alternates?: {
|
|
55
|
+
canonical?: string
|
|
56
|
+
/** Addresses by culture, replacing the page's language versions. */
|
|
57
|
+
languages?: Record<string, string>
|
|
58
|
+
}
|
|
59
|
+
robots?: string | { index?: boolean }
|
|
60
|
+
openGraph?: { images?: string | { url: string } | Array<string | { url: string }> }
|
|
61
|
+
}
|
|
62
|
+
|
|
46
63
|
/** Where a value came from: the page's own field, the template, the site, or the page name. */
|
|
47
|
-
export type MetaSource = 'page' | 'template' | 'site' | 'name' | 'none'
|
|
64
|
+
export type MetaSource = 'page' | 'metadata' | 'template' | 'site' | 'name' | 'none'
|
|
48
65
|
|
|
49
66
|
export interface MetaValue<T> {
|
|
50
67
|
value: T
|
|
@@ -103,6 +120,50 @@ export async function effectiveMeta(
|
|
|
103
120
|
content: PublishedContent,
|
|
104
121
|
context: MetaContext,
|
|
105
122
|
overrides: SeoOverrides = {},
|
|
123
|
+
metadata: Metadata = {},
|
|
124
|
+
): Promise<EffectiveMeta> {
|
|
125
|
+
const meta = await pageMeta(content, context, overrides)
|
|
126
|
+
return withMetadata(meta, metadata, context.origin)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function firstImage(images: NonNullable<Metadata['openGraph']>['images']): string | undefined {
|
|
130
|
+
const first = Array.isArray(images) ? images[0] : images
|
|
131
|
+
return typeof first === 'string' ? first : first?.url
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** A page's values with what its `generateMetadata` returned laid over them. Pure. */
|
|
135
|
+
function withMetadata(meta: EffectiveMeta, metadata: Metadata, origin: string): EffectiveMeta {
|
|
136
|
+
const out = { ...meta }
|
|
137
|
+
if (filled(metadata.title)) {
|
|
138
|
+
const suffix = meta.fullTitle.slice(meta.title.value.length)
|
|
139
|
+
out.title = { value: metadata.title, source: 'metadata' }
|
|
140
|
+
out.fullTitle = `${metadata.title}${suffix}`
|
|
141
|
+
}
|
|
142
|
+
if (filled(metadata.description))
|
|
143
|
+
out.description = { value: metadata.description, source: 'metadata' }
|
|
144
|
+
const canonical = metadata.alternates?.canonical
|
|
145
|
+
if (filled(canonical))
|
|
146
|
+
out.canonical = { value: absoluteUrl(canonical, origin), source: 'metadata' }
|
|
147
|
+
const image = firstImage(metadata.openGraph?.images)
|
|
148
|
+
if (filled(image)) out.image = { value: absoluteUrl(image, origin), source: 'metadata' }
|
|
149
|
+
const robots = metadata.robots
|
|
150
|
+
const noindex = typeof robots === 'string' ? /\bnoindex\b/i.test(robots) : robots?.index === false
|
|
151
|
+
if (noindex && !meta.noindex.value) out.noindex = { value: true, source: 'metadata' }
|
|
152
|
+
const languages = metadata.alternates?.languages
|
|
153
|
+
if (languages) {
|
|
154
|
+
out.alternates = Object.entries(languages).flatMap(([culture, url]) => {
|
|
155
|
+
const absolute = absoluteUrl(url, origin)
|
|
156
|
+
return absolute && culture !== 'x-default' ? [{ culture, url: absolute }] : []
|
|
157
|
+
})
|
|
158
|
+
out.xDefault = languages['x-default'] ? absoluteUrl(languages['x-default'], origin) : undefined
|
|
159
|
+
}
|
|
160
|
+
return out
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function pageMeta(
|
|
164
|
+
content: PublishedContent,
|
|
165
|
+
context: MetaContext,
|
|
166
|
+
overrides: SeoOverrides,
|
|
106
167
|
): Promise<EffectiveMeta> {
|
|
107
168
|
const { origin, site } = context
|
|
108
169
|
const own = (alias: string) => content.text(alias).trim()
|
|
@@ -181,6 +242,7 @@ export async function SeoHead(props: SeoHeadProps): Promise<RawHtml> {
|
|
|
181
242
|
model,
|
|
182
243
|
{ origin: request.origin, alternates: urls.alternates(model), site: seo },
|
|
183
244
|
overrides,
|
|
245
|
+
currentMetadata(),
|
|
184
246
|
)
|
|
185
247
|
const tag = (name: string, attributes: Record<string, string | undefined>) =>
|
|
186
248
|
Object.values(attributes).some((v) => v === undefined) ? '' : element(name, attributes).value
|