@crombolo/render 0.37.0 → 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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/render",
3
- "version": "0.37.0",
3
+ "version": "0.38.1",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. TSX server rendering and the published-content model for crombolo.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -34,8 +34,8 @@
34
34
  "access": "public"
35
35
  },
36
36
  "dependencies": {
37
- "@crombolo/common": "0.37.0",
38
- "@crombolo/core": "0.37.0",
37
+ "@crombolo/common": "0.38.1",
38
+ "@crombolo/core": "0.38.1",
39
39
  "@types/react": "^19.3.0"
40
40
  }
41
41
  }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The component stack of a template error (story 214): which components were
3
+ * rendering when it was thrown, outermost first, `homePage › Layout › Card`.
4
+ * Recorded only where error details are shown, by a tracker the JSX runtime
5
+ * calls for each component.
6
+ */
7
+ import { AsyncLocalStorage } from 'node:async_hooks'
8
+ import { type Child, COMPONENT_TRACKER, isPromise } from './jsx-runtime.ts'
9
+
10
+ const STACK = Symbol.for('crombolo.componentStack')
11
+ const owners = new AsyncLocalStorage<readonly string[]>()
12
+
13
+ function tag(error: unknown, chain: readonly string[]): unknown {
14
+ // The innermost component tags it first; the ones around it leave that alone.
15
+ if (error !== null && typeof error === 'object' && !(STACK in error))
16
+ Object.defineProperty(error, STACK, { value: chain })
17
+ return error
18
+ }
19
+
20
+ /** Runs a component's render with its name on the stack, tagging what it throws. */
21
+ export function trackComponent<T>(name: string, call: () => T): T {
22
+ if (!tracking()) return call()
23
+ const chain = [...(owners.getStore() ?? []), name]
24
+ try {
25
+ const result = owners.run(chain, call)
26
+ return (
27
+ isPromise(result)
28
+ ? (result as Promise<unknown>).then(undefined, (error: unknown) => {
29
+ throw tag(error, chain)
30
+ })
31
+ : result
32
+ ) as T
33
+ } catch (error) {
34
+ throw tag(error, chain)
35
+ }
36
+ }
37
+
38
+ /** Starts recording component stacks in this process. */
39
+ export function enableComponentStack(): void {
40
+ ;(globalThis as Record<symbol, unknown>)[COMPONENT_TRACKER] = (name: string, call: () => Child) =>
41
+ trackComponent(name, call)
42
+ }
43
+
44
+ function tracking(): boolean {
45
+ return (globalThis as Record<symbol, unknown>)[COMPONENT_TRACKER] !== undefined
46
+ }
47
+
48
+ /** The components that were rendering when this was thrown, outermost first. */
49
+ export function componentStackOf(error: unknown): readonly string[] | undefined {
50
+ return error !== null && typeof error === 'object'
51
+ ? ((error as Record<symbol, unknown>)[STACK] as readonly string[] | undefined)
52
+ : undefined
53
+ }
package/src/context.ts CHANGED
@@ -218,6 +218,11 @@ export function currentRequest(caller: string): RequestValues {
218
218
  return scope.request ?? { headers: new Headers() }
219
219
  }
220
220
 
221
+ /** The language of the page rendering, or null outside a page. */
222
+ export function currentCulture(): string | null {
223
+ return store.getStore()?.page?.culture ?? null
224
+ }
225
+
221
226
  /** The site's services for this render, built by the server for whoever is asking. */
222
227
  export function currentSite(caller: string): unknown {
223
228
  const scope = within(caller)
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export * from './blocks.ts'
2
2
  export * from './bundle-script.ts'
3
3
  export * from './cache-policy.ts'
4
+ export * from './component-stack.ts'
4
5
  export * from './context.ts'
5
6
  export * from './email.ts'
6
7
  export * from './excerpt.ts'
@@ -11,6 +12,7 @@ export * from './islands.ts'
11
12
  export * from './islands-loader.ts'
12
13
  export * from './jsx-attributes.ts'
13
14
  export * from './jsx-runtime.ts'
15
+ export * from './live-reload.ts'
14
16
  export * from './media.ts'
15
17
  export * from './media-cache.ts'
16
18
  export * from './menus.ts'
@@ -51,6 +51,19 @@ export type Component = (props: ElementProps) => Child
51
51
 
52
52
  export const Fragment = Symbol.for('crombolo.fragment')
53
53
 
54
+ /**
55
+ * Where a development server installs its component tracker (story 214), on the
56
+ * global object so a view generation imported from another path finds it too.
57
+ */
58
+ export const COMPONENT_TRACKER = Symbol.for('crombolo.componentTracker')
59
+
60
+ type ComponentTracker = (name: string, call: () => Child) => Child
61
+
62
+ function callComponent(type: Component, props: ElementProps): Child {
63
+ const track = (globalThis as { [COMPONENT_TRACKER]?: ComponentTracker })[COMPONENT_TRACKER]
64
+ return track ? track(type.name || 'Anonymous', () => type(props)) : type(props)
65
+ }
66
+
54
67
  export function isPromise(value: unknown): value is Promise<unknown> {
55
68
  return typeof (value as { then?: unknown } | null | undefined)?.then === 'function'
56
69
  }
@@ -252,7 +265,7 @@ export function jsx(type: string | Component | typeof Fragment, props: ElementPr
252
265
 
253
266
  if (type === Fragment) return toHtml(renderChild(actual.children))
254
267
 
255
- if (typeof type === 'function') return toHtml(renderChild(type(actual)))
268
+ if (typeof type === 'function') return toHtml(renderChild(callComponent(type, actual)))
256
269
 
257
270
  if (type === 'select' && (actual.value != null || actual.defaultValue != null))
258
271
  return select(actual)
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Live reload in development (story 214): the script a page carries, and where
3
+ * it listens. The server streams a `hello` with its boot id on each connection,
4
+ * `reload` when the views, the schema or the content change, and `types` with
5
+ * the background type check's findings. docs/writing-components.md, "The
6
+ * development loop".
7
+ */
8
+
9
+ export const LIVE_RELOAD_SCRIPT_PATH = '/crombolo/dev/live.js'
10
+ export const LIVE_EVENTS_PATH = '/crombolo/dev/events'
11
+
12
+ /** What changed; a `reload` event carries each in its burst as `reasons`. */
13
+ export type LiveChange = 'views' | 'schema' | 'content'
14
+
15
+ /** The background type check's findings, in a `types` event; no errors clears the banner. */
16
+ export interface LiveTypes {
17
+ count: number
18
+ first?: { file: string; line: number; message: string }
19
+ }
20
+
21
+ /**
22
+ * Reloads the page on a `reload`, or on a `hello` from a server that restarted,
23
+ * and keeps a dismissible banner of type errors. Plain DOM, styled through the
24
+ * CSSOM, so a strict content security policy allows it.
25
+ */
26
+ export const LIVE_RELOAD_SCRIPT = `/* crombolo: live reload in development */
27
+ (function () {
28
+ if (window.__cromboloLive) return
29
+ window.__cromboloLive = true
30
+ var boot = null
31
+ var banner = null
32
+ var events = new EventSource('${LIVE_EVENTS_PATH}')
33
+ events.addEventListener('hello', function (event) {
34
+ var id = JSON.parse(event.data).boot
35
+ if (boot !== null && boot !== id) location.reload()
36
+ boot = id
37
+ })
38
+ events.addEventListener('reload', function () {
39
+ location.reload()
40
+ })
41
+ events.addEventListener('types', function (event) {
42
+ var types = JSON.parse(event.data)
43
+ if (banner) banner.remove()
44
+ banner = null
45
+ if (!types.count) return
46
+ banner = document.createElement('div')
47
+ banner.setAttribute('role', 'status')
48
+ banner.style.cssText = 'position:fixed;left:1rem;right:1rem;bottom:1rem;z-index:2147483647;display:flex;gap:1rem;align-items:flex-start;padding:.75rem 1rem;border-radius:.5rem;background:#3b1219;color:#fff;font:14px/1.4 ui-monospace,monospace;box-shadow:0 4px 16px rgba(0,0,0,.3)'
49
+ var text = document.createElement('div')
50
+ text.style.cssText = 'flex:1;white-space:pre-wrap'
51
+ var first = types.first
52
+ text.textContent = types.count + (types.count === 1 ? ' type error' : ' type errors') +
53
+ (first ? '\\n' + first.file + ':' + first.line + ' ' + first.message : '')
54
+ var close = document.createElement('button')
55
+ close.type = 'button'
56
+ close.textContent = '\\u00d7'
57
+ close.setAttribute('aria-label', 'Dismiss')
58
+ close.style.cssText = 'background:none;border:0;color:inherit;font-size:1.25rem;line-height:1;cursor:pointer'
59
+ close.addEventListener('click', function () {
60
+ if (banner) banner.remove()
61
+ banner = null
62
+ })
63
+ banner.append(text, close)
64
+ document.body.append(banner)
65
+ })
66
+ })()
67
+ `
68
+
69
+ /** The tag that loads the script. */
70
+ export const LIVE_RELOAD_TAG = `<script src="${LIVE_RELOAD_SCRIPT_PATH}" defer></script>`
71
+
72
+ /** A page's HTML with the live-reload script before `</body>`, or at the end when it has none. */
73
+ export function withLiveReload(html: string): string {
74
+ const at = html.toLowerCase().lastIndexOf('</body>')
75
+ return at < 0
76
+ ? `${html}${LIVE_RELOAD_TAG}`
77
+ : `${html.slice(0, at)}${LIVE_RELOAD_TAG}${html.slice(at)}`
78
+ }
package/src/media.ts CHANGED
@@ -19,41 +19,114 @@ export interface FocalPoint {
19
19
  top: number
20
20
  }
21
21
 
22
- /** A crop URL: a named crop, or any size around the focal point. */
23
- export type CropRequest =
24
- | string
25
- | { width?: number; height?: number; mode?: string; format?: string }
22
+ /** Where a crop is cut from when there is no focal point (ImageSharp's `ranchor`). */
23
+ export type CropAnchor =
24
+ | 'center'
25
+ | 'top'
26
+ | 'bottom'
27
+ | 'left'
28
+ | 'right'
29
+ | 'topleft'
30
+ | 'topright'
31
+ | 'bottomleft'
32
+ | 'bottomright'
26
33
 
27
- /** `url` with the query that yields `request`, given the crops and focal point in force. */
34
+ /** The options of Umbraco's `GetCropUrl` (story 199), as one object. */
35
+ export interface CropOptions {
36
+ /** A named crop: its area, at its own size unless a size is given. */
37
+ crop?: string
38
+ width?: number
39
+ height?: number
40
+ /** Width ÷ height: the missing side from the given one. */
41
+ ratio?: number
42
+ /** `crop`, `max`, `stretch`, `pad`, `boxpad` or `min`. */
43
+ mode?: string
44
+ /** `jpg`, `png`, `webp`, or `avif` where the server can encode it (WebP where not). */
45
+ format?: string
46
+ /** 1–100. */
47
+ quality?: number
48
+ /** Where to cut from when there is no focal point. */
49
+ anchor?: CropAnchor
50
+ /** With `crop`: ignore its coordinates and cut around the focal point. */
51
+ preferFocalPoint?: boolean
52
+ /** With `crop`: its own size, whatever size is given. Default: only when none is. */
53
+ useCropDimensions?: boolean
54
+ /**
55
+ * A value that changes when the image does, so browsers and CDNs fetch it
56
+ * afresh: the item's update date by default; `false` for none.
57
+ */
58
+ cacheBuster?: boolean | string
59
+ /** More query, appended as it is: `bgcolor=fff`. */
60
+ furtherOptions?: string
61
+ }
62
+
63
+ /** A crop URL: a named crop (shorthand for `{ crop }`), or the options. */
64
+ export type CropRequest = string | CropOptions
65
+
66
+ /** The cache buster an update date gives. */
67
+ export const cacheBusterOf = (updated: Date): string => updated.getTime().toString(36)
68
+
69
+ /**
70
+ * `url` with the query that yields `request`, given the crops and focal point
71
+ * in force; null for a named crop that is not there. `updated` is when the
72
+ * image last changed, for the cache buster.
73
+ */
28
74
  export function cropUrl(
29
75
  url: string,
30
76
  crops: readonly Crop[],
31
77
  focalPoint: FocalPoint | null,
32
78
  request: CropRequest,
79
+ updated?: Date,
33
80
  ): string | null {
81
+ const options: CropOptions = typeof request === 'string' ? { crop: request } : request
34
82
  const params = new URLSearchParams()
35
- if (typeof request === 'string') {
36
- const crop = crops.find((c) => c.alias === request)
83
+ const focal = () => {
84
+ if (focalPoint) params.set('rxy', `${focalPoint.left},${focalPoint.top}`)
85
+ }
86
+ let width = options.width
87
+ let height = options.height
88
+ if (options.crop !== undefined) {
89
+ const crop = crops.find((c) => c.alias === options.crop)
37
90
  if (!crop) return null
38
- if (crop.coordinates)
91
+ if (crop.coordinates && !options.preferFocalPoint)
39
92
  params.set(
40
93
  'cc',
41
94
  [crop.coordinates.x1, crop.coordinates.y1, crop.coordinates.x2, crop.coordinates.y2].join(
42
95
  ',',
43
96
  ),
44
97
  )
45
- else if (focalPoint) params.set('rxy', `${focalPoint.left},${focalPoint.top}`)
46
- params.set('width', String(crop.width))
47
- params.set('height', String(crop.height))
48
- } else {
49
- if (focalPoint && request.width && request.height)
50
- params.set('rxy', `${focalPoint.left},${focalPoint.top}`)
51
- if (request.width) params.set('width', String(request.width))
52
- if (request.height) params.set('height', String(request.height))
53
- if (request.mode) params.set('rmode', request.mode.toLowerCase())
54
- if (request.format) params.set('format', request.format)
98
+ else focal()
99
+ const sized = width !== undefined || height !== undefined
100
+ if (options.useCropDimensions || !sized) {
101
+ width = crop.width
102
+ height = crop.height
103
+ } else if (crop.width > 0 && crop.height > 0 && options.ratio === undefined) {
104
+ // A named crop at another size keeps its shape.
105
+ if (height === undefined && width) height = Math.round((width * crop.height) / crop.width)
106
+ if (width === undefined && height) width = Math.round((height * crop.width) / crop.height)
107
+ }
108
+ } else if (width && height) focal()
109
+ if (options.ratio && options.ratio > 0) {
110
+ if (width && !height) height = Math.round(width / options.ratio)
111
+ else if (height && !width) width = Math.round(height * options.ratio)
112
+ if (options.crop === undefined && width && height && !params.has('rxy')) focal()
55
113
  }
56
- const query = params.toString()
114
+ if (width) params.set('width', String(width))
115
+ if (height) params.set('height', String(height))
116
+ if (options.mode) params.set('rmode', options.mode.toLowerCase())
117
+ if (options.anchor && !params.has('rxy')) params.set('ranchor', options.anchor.toLowerCase())
118
+ if (options.format) params.set('format', options.format.toLowerCase())
119
+ if (options.quality) params.set('quality', String(Math.round(options.quality)))
120
+ const buster =
121
+ typeof options.cacheBuster === 'string'
122
+ ? options.cacheBuster
123
+ : options.cacheBuster !== false && updated && updated.getTime() > 0
124
+ ? cacheBusterOf(updated)
125
+ : undefined
126
+ if (buster) params.set('rnd', buster)
127
+ let query = params.toString()
128
+ const further = options.furtherOptions?.replace(/^[?&]+/, '')
129
+ if (further) query = query ? `${query}&${further}` : further
57
130
  return query ? `${url}?${query}` : url
58
131
  }
59
132
 
@@ -98,11 +171,14 @@ export class ImageCropperValue {
98
171
  readonly src: string
99
172
  readonly crops: Crop[]
100
173
  readonly focalPoint: FocalPoint | null
174
+ /** When it last changed: the page's, or the media item's, update date. */
175
+ readonly updated: Date | undefined
101
176
 
102
- constructor(value: { src?: unknown; crops?: unknown; focalPoint?: unknown }) {
177
+ constructor(value: { src?: unknown; crops?: unknown; focalPoint?: unknown }, updated?: Date) {
103
178
  this.src = typeof value.src === 'string' ? value.src : ''
104
179
  this.crops = readCrops(value.crops)
105
180
  this.focalPoint = readFocalPoint(value.focalPoint)
181
+ this.updated = updated
106
182
  }
107
183
 
108
184
  get url(): string {
@@ -110,7 +186,7 @@ export class ImageCropperValue {
110
186
  }
111
187
 
112
188
  cropUrl(request: CropRequest): string | null {
113
- return this.src ? cropUrl(this.src, this.crops, this.focalPoint, request) : null
189
+ return this.src ? cropUrl(this.src, this.crops, this.focalPoint, request, this.updated) : null
114
190
  }
115
191
 
116
192
  toString(): string {
@@ -173,6 +249,7 @@ export class PublishedMedia {
173
249
  const file = this.properties.find((p) => p.alias === 'umbracoFile')?.value
174
250
  return new ImageCropperValue(
175
251
  typeof file === 'string' ? { src: file } : ((file as object | null | undefined) ?? {}),
252
+ this.updateDate,
176
253
  )
177
254
  }
178
255
 
@@ -221,6 +298,8 @@ export class MediaWithCrops {
221
298
  }
222
299
 
223
300
  cropUrl(request: CropRequest): string | null {
224
- return this.url ? cropUrl(this.url, this.crops, this.focalPoint, request) : null
301
+ return this.url
302
+ ? cropUrl(this.url, this.crops, this.focalPoint, request, this.media.updateDate)
303
+ : null
225
304
  }
226
305
  }
package/src/model.ts CHANGED
@@ -133,7 +133,8 @@ export class PublishedContent<Properties = any> {
133
133
 
134
134
  /** How pickers, links and blocks resolve what they point at; the cache supplies it. */
135
135
  withValueContext(context: ValueContext<PublishedContent> | undefined): this {
136
- this.#context = context
136
+ // Its own update date, for what its values say about when they changed.
137
+ this.#context = context && { ...context, updated: this.updateDate }
137
138
  return this
138
139
  }
139
140
 
@@ -279,8 +280,17 @@ export interface PageOutcome {
279
280
  errors: readonly FieldError[]
280
281
  /** A 500's reference, which the log line carries too. */
281
282
  reference?: string
282
- /** A 500's message, source and stack, when `errors.showDetails` allows. */
283
- details?: { message: string; location?: string; stack?: string }
283
+ /**
284
+ * A 500's message, source and stack, when `errors.showDetails` allows; for a
285
+ * template error also the code around the line and the component stack.
286
+ */
287
+ details?: {
288
+ message: string
289
+ location?: string
290
+ stack?: string
291
+ code?: { line: number; lines: ReadonlyArray<{ number: number; text: string }> }
292
+ components?: readonly string[]
293
+ }
284
294
  }
285
295
 
286
296
  /**
@@ -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. Readers that arrive
379
- * while it builds share that build rather than each starting one; a build
380
- * an invalidation overtook still answers, but the next read builds again.
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,10 +6,11 @@
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
12
  import { type FormSubmissionState, isOutcome, type Outcome } from '@crombolo/core'
13
+ import { componentStackOf, trackComponent } from './component-stack.ts'
13
14
  import { emailScope, markPersonal, renderScope } from './context.ts'
14
15
  import type { EmailProps, EmailRenderResult } from './email.ts'
15
16
  import { RawHtml } from './html.ts'
@@ -89,6 +90,9 @@ export type RenderResult =
89
90
 
90
91
  const MAX_LAYOUT_DEPTH = 10
91
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
+
92
96
  /**
93
97
  * A whole document gets `<!DOCTYPE html>`, which JSX has no way to write and
94
98
  * without which a browser renders in quirks mode. A page that writes its own,
@@ -379,18 +383,26 @@ export class Renderer {
379
383
 
380
384
  /**
381
385
  * What a template threw, for a person to act on: its message, the first line
382
- * under `components/` it failed on, and the stack, all naming files somebody
383
- * can open.
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.
384
389
  */
385
- describeError(error: unknown): { message: string; location?: string; stack: string } {
390
+ describeError(error: unknown): ErrorDescription {
386
391
  const root = `${this.#componentsDir}${sep}`
387
392
  const shown = `${basename(this.#componentsDir)}/`
388
393
  const readable = (text: string) => this.inSource(text).replaceAll(root, shown)
389
394
  const message = readable(error instanceof Error ? error.message : String(error)).trim()
390
395
  const stack = error instanceof Error ? readable(error.stack ?? '') : ''
391
396
  const escaped = shown.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
392
- const frame = new RegExp(`${escaped}[^\\s:()]+\\.[jt]sx?:\\d+`).exec(stack)
393
- return frame ? { message, location: frame[0], stack } : { message, stack }
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
+ }
394
406
  }
395
407
 
396
408
  /** Runs a render under the time limit; the signal it hands on aborts when that runs out. */
@@ -414,8 +426,9 @@ export class Renderer {
414
426
  this.#renderTimeoutMs,
415
427
  )
416
428
  : undefined
429
+ let fail = () => {}
417
430
  const stopped = new Promise<never>((_, reject) => {
418
- const fail = () => reject(signal.reason)
431
+ fail = () => reject(signal.reason)
419
432
  if (signal.aborted) fail()
420
433
  else signal.addEventListener('abort', fail, { once: true })
421
434
  })
@@ -427,6 +440,10 @@ export class Renderer {
427
440
  return await Promise.race([work, stopped])
428
441
  } finally {
429
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)
430
447
  }
431
448
  }
432
449
 
@@ -527,8 +544,10 @@ export class Renderer {
527
544
  const module = await this.#load(currentAlias)
528
545
  if (!module) return depth === 0 || body === undefined ? undefined : withDoctype(body.value)
529
546
  const render = module.default as unknown as (props: object) => Child | Promise<Child>
530
- const rendered = body === undefined ? render(props) : render({ ...props, children: body })
531
- body = new RawHtml(await renderToString(rendered as Child))
547
+ const layoutProps = body === undefined ? props : { ...props, children: body }
548
+ body = new RawHtml(
549
+ await trackComponent(currentAlias, () => renderToString(render(layoutProps) as Child)),
550
+ )
532
551
  currentAlias = module.layout
533
552
  depth += 1
534
553
  }
@@ -567,3 +586,41 @@ export class Renderer {
567
586
  return module
568
587
  }
569
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/site.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  import { Outcome, type Result } from '@crombolo/core'
7
7
  import { currentSite } from './context.ts'
8
8
  import type { PublishedMedia } from './media.ts'
9
+ import type { RequestMember } from './model.ts'
9
10
 
10
11
  /** Media this visitor may read; anything else answers `notFound`, as `/media/` does. */
11
12
  export interface SiteMedia {
@@ -14,22 +15,79 @@ export interface SiteMedia {
14
15
  children(folderKey: string): Promise<Result<PublishedMedia[], 404>>
15
16
  }
16
17
 
17
- /** The site's own schema; filled by story 189. */
18
- export interface SiteSql {
19
- // biome-ignore lint/suspicious/noExplicitAny: a slot each site's own queries will type.
20
- [query: string]: (...args: any[]) => Promise<Result<any>>
18
+ /** Who a named query runs for (story 189). */
19
+ export interface QueryCaller {
20
+ /** The signed-in member, if any; asking makes the page personal. */
21
+ member(): Promise<
22
+ Pick<RequestMember, 'key' | 'name' | 'username' | 'email' | 'roles'> | undefined
23
+ >
24
+ /** The language the page renders in, when there is a page. */
25
+ locale: string | null
21
26
  }
22
27
 
28
+ /**
29
+ * A named query: `db` is the site's own tables and `caller` who is asking; the
30
+ * rest are what `site().queries.<module>.<name>(…)` is called with.
31
+ */
32
+ // biome-ignore lint/suspicious/noExplicitAny: any handle, any arguments, any result
33
+ export type NamedQuery = (db: any, caller: QueryCaller, ...args: any[]) => any
34
+
35
+ type Bound<F> = F extends (db: never, caller: QueryCaller, ...args: infer A) => infer R
36
+ ? (...args: A) => Promise<Awaited<R>>
37
+ : never
38
+
39
+ /** The modules `queries` lists, as `site().queries` calls them. */
40
+ export type QueriesOf<M> = {
41
+ readonly [K in keyof M]: { readonly [N in keyof M[K]]: Bound<M[K][N]> }
42
+ }
43
+
44
+ /**
45
+ * Where a site registers its config's types, so `site().queries` is typed:
46
+ * `declare module '@crombolo/crombolo/server' { interface Register { queries: typeof queries } }`.
47
+ */
48
+ // biome-ignore lint/suspicious/noEmptyInterface: filled by the site's declaration
49
+ export interface Register {}
50
+
51
+ /** The site's named queries (story 189), typed from what `Register` says the config lists. */
52
+ export type SiteQueries = Register extends { queries: infer Q }
53
+ ? QueriesOf<Q>
54
+ : {
55
+ readonly [module: string]: {
56
+ // biome-ignore lint/suspicious/noExplicitAny: untyped until the site registers its queries
57
+ readonly [query: string]: (...args: any[]) => Promise<Result<any>>
58
+ }
59
+ }
60
+
23
61
  /** Members, acting as the caller; filled by story 207. */
24
62
  export interface SiteMembers {
25
63
  // biome-ignore lint/suspicious/noExplicitAny: a slot story 207 will type.
26
64
  [operation: string]: (...args: any[]) => Promise<Result<any>>
27
65
  }
28
66
 
67
+ /** A background job as the site's code reads it (story 187). */
68
+ export interface SiteJobStatus {
69
+ id: string
70
+ name: string
71
+ state: 'queued' | 'running' | 'succeeded' | 'failed'
72
+ attempts: number
73
+ progress: { done: number; total?: number; note?: string } | null
74
+ error: string | null
75
+ queuedBy: string | null
76
+ createdAt: string
77
+ finishedAt: string | null
78
+ }
79
+
80
+ /** The site's background jobs: queue one by `module.export`, and read how one is going. */
81
+ export interface SiteJobs {
82
+ enqueue(name: string, payload?: unknown): Promise<string>
83
+ status(id: string): Promise<SiteJobStatus | undefined>
84
+ }
85
+
29
86
  export interface SiteServices {
30
87
  media: SiteMedia
31
- sql: SiteSql
88
+ queries: SiteQueries
32
89
  members: SiteMembers
90
+ jobs: SiteJobs
33
91
  }
34
92
 
35
93
  /** The site's services as the visitor; only while a page renders. */
package/src/values.ts CHANGED
@@ -26,6 +26,8 @@ export interface ValueContext<Content = unknown, Media = unknown> {
26
26
  element?(key: string): PublishedElement | undefined
27
27
  /** A content type's alias by key, which is all a block records of its element type. */
28
28
  contentTypeAlias?(key: string): string | undefined
29
+ /** When the item whose values these are last changed: an Image Cropper's cache buster. */
30
+ updated?: Date
29
31
  /** A content URL, for links. */
30
32
  urlOf(content: Content): string
31
33
  mediaUrlOf?(media: Media): string
@@ -141,6 +143,31 @@ export function htmlOf(value: unknown): RawHtml | Promise<RawHtml> {
141
143
  return Promise.resolve(value).then((resolved) => new RawHtml(textOf(resolved)))
142
144
  }
143
145
 
146
+ /**
147
+ * Rich text with blocks, as the back office stores it (`{ markup, blocks }`):
148
+ * the markup with its links resolved, the markup as stored, and the blocks it
149
+ * places. Printed, it is its markup.
150
+ */
151
+ export class RichTextValue {
152
+ constructor(
153
+ readonly markup: string,
154
+ /** As stored: links still `{localLink:…}`, blocks still placeholders (story 216). */
155
+ readonly source: string,
156
+ readonly blocks: readonly BlockItem[],
157
+ ) {}
158
+
159
+ toString(): string {
160
+ return this.markup
161
+ }
162
+ }
163
+
164
+ /** The markup a stored rich-text value holds, whichever shape it was saved in. */
165
+ export function richTextSource(value: unknown): string {
166
+ if (typeof value === 'string') return value
167
+ const markup = (value as { markup?: unknown } | null | undefined)?.markup
168
+ return typeof markup === 'string' ? markup : ''
169
+ }
170
+
144
171
  /** A media picker's value as a list of picks. */
145
172
  export function picksOf(value: unknown): MediaWithCrops[] {
146
173
  if (Array.isArray(value))
@@ -303,9 +330,11 @@ export function convertValueNow(
303
330
  ): unknown {
304
331
  if (value === null || value === undefined) return value
305
332
  if (editorAlias === 'Umbraco.RichText') {
306
- if (typeof value !== 'string') return value
307
333
  const { media: _, ...pagesOnly } = context ?? ({} as ValueContext)
308
- return resolveLocalLinks(value, context ? (pagesOnly as ValueContext) : undefined)
334
+ return resolveLocalLinks(
335
+ richTextSource(value),
336
+ context ? (pagesOnly as ValueContext) : undefined,
337
+ )
309
338
  }
310
339
  if (ASYNC_EDITORS.has(editorAlias)) return null
311
340
  return convertValue(editorAlias, value, context, config)
@@ -339,11 +368,26 @@ export function convertValue(
339
368
  const picks = found.filter((pick): pick is MediaWithCrops => pick !== undefined)
340
369
  return config.multiple === false ? (picks[0] ?? null) : picks
341
370
  })
342
- case 'Umbraco.RichText':
343
- return typeof value === 'string' ? resolveLocalLinks(value, context) : value
371
+ case 'Umbraco.RichText': {
372
+ if (typeof value === 'string') return resolveLocalLinks(value, context)
373
+ const source = richTextSource(value)
374
+ const blocks = blockItems<BlockItem>(
375
+ (value as { blocks?: unknown }).blocks,
376
+ 'Umbraco.RichText',
377
+ context,
378
+ (_, item) => item,
379
+ )
380
+ const markup = resolveLocalLinks(source, context)
381
+ return typeof markup === 'string'
382
+ ? new RichTextValue(markup, source, blocks)
383
+ : markup.then((resolved) => new RichTextValue(resolved, source, blocks))
384
+ }
344
385
  case 'Umbraco.ImageCropper':
345
386
  return typeof value === 'object' || typeof value === 'string'
346
- ? new ImageCropperValue(typeof value === 'string' ? { src: value } : (value as object))
387
+ ? new ImageCropperValue(
388
+ typeof value === 'string' ? { src: value } : (value as object),
389
+ context?.updated,
390
+ )
347
391
  : value
348
392
  // A form definition is a file, so there is nothing in the content cache to
349
393
  // resolve against: the lookup reads `schema/forms/`. Without one the raw key