@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/src/site.ts ADDED
@@ -0,0 +1,106 @@
1
+ /**
2
+ * The site's own services, acting as whoever the page is rendering for
3
+ * (story 206). Each returns a `Result`; a component ends the chain with
4
+ * `unwrap()`. Reading anything personal makes the page personal.
5
+ */
6
+ import { Outcome, type Result } from '@crombolo/core'
7
+ import { currentSite } from './context.ts'
8
+ import type { PublishedMedia } from './media.ts'
9
+ import type { RequestMember } from './model.ts'
10
+
11
+ /** Media this visitor may read; anything else answers `notFound`, as `/media/` does. */
12
+ export interface SiteMedia {
13
+ get(key: string): Promise<Result<PublishedMedia, 404>>
14
+ /** A folder's items this visitor may read, in their order. */
15
+ children(folderKey: string): Promise<Result<PublishedMedia[], 404>>
16
+ }
17
+
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
26
+ }
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
+
61
+ /** Members, acting as the caller; filled by story 207. */
62
+ export interface SiteMembers {
63
+ // biome-ignore lint/suspicious/noExplicitAny: a slot story 207 will type.
64
+ [operation: string]: (...args: any[]) => Promise<Result<any>>
65
+ }
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
+
86
+ export interface SiteServices {
87
+ media: SiteMedia
88
+ queries: SiteQueries
89
+ members: SiteMembers
90
+ jobs: SiteJobs
91
+ }
92
+
93
+ /** The site's services as the visitor; only while a page renders. */
94
+ export function site(): SiteServices {
95
+ return currentSite('site()') as SiteServices
96
+ }
97
+
98
+ /** A slot not filled yet: every call answers `notFound`, saying what is missing. */
99
+ export function unavailableServices<T extends object>(name: string): T {
100
+ return new Proxy({} as T, {
101
+ get: (_target, property) =>
102
+ typeof property === 'string' && property !== 'then'
103
+ ? async () => Outcome.notFound(`site().${name}.${property} is not available on this site.`)
104
+ : undefined,
105
+ })
106
+ }
package/src/snapshots.ts CHANGED
@@ -98,9 +98,24 @@ export interface SnapshotOptions {
98
98
  * which is every boot and not an event worth reporting.
99
99
  */
100
100
  onSwap?: (hash: string, previous: string | undefined) => void
101
+ /**
102
+ * What a file is written as instead of its own bytes, or undefined for those:
103
+ * a `'use client'` module becomes its island stub (story 209). The hash still
104
+ * covers the source, and the source is kept under `.islands/src/`.
105
+ */
106
+ transform?: (key: string, bytes: Uint8Array) => Uint8Array | undefined
107
+ /**
108
+ * A generation is in place and about to be rendered: its browser code is
109
+ * built here, from the files the transform rewrote. A failure is reported,
110
+ * and the generation still serves.
111
+ */
112
+ beforeSwap?: (generation: { dir: string; hash: string; transformed: string[] }) => Promise<void>
101
113
  now?: () => number
102
114
  }
103
115
 
116
+ /** Beside a generation's views: the client sources and their built browser code. */
117
+ export const ISLANDS_DIR = '.islands'
118
+
104
119
  interface FileEntry {
105
120
  /** Path relative to the source root, `/`-separated so a hash is portable. */
106
121
  key: string
@@ -137,6 +152,8 @@ export class ViewSnapshots {
137
152
  #limits: SnapshotLimits
138
153
  #onProblem: (message: string) => void
139
154
  #onSwap: (hash: string, previous: string | undefined) => void
155
+ #transform: SnapshotOptions['transform']
156
+ #beforeSwap: SnapshotOptions['beforeSwap']
140
157
  #now: () => number
141
158
 
142
159
  #current: { hash: string; dir: string } | undefined
@@ -159,6 +176,8 @@ export class ViewSnapshots {
159
176
  this.#limits = { ...SNAPSHOT_LIMITS, ...options.limits }
160
177
  this.#onProblem = options.onProblem ?? (() => {})
161
178
  this.#onSwap = options.onSwap ?? (() => {})
179
+ this.#transform = options.transform
180
+ this.#beforeSwap = options.beforeSwap
162
181
  this.#now = options.now ?? Date.now
163
182
  if (!relative(this.#sourceDir, this.#cacheDir).startsWith('..')) {
164
183
  throw new Error(
@@ -324,6 +343,7 @@ export class ViewSnapshots {
324
343
  async #materialise(files: FileEntry[]): Promise<void> {
325
344
  const partial = join(this.#cacheDir, `${PARTIAL}${crypto.randomUUID().slice(0, 8)}`)
326
345
  const hasher = createHash('sha256')
346
+ const transformed: string[] = []
327
347
  try {
328
348
  mkdirSync(partial, { recursive: true })
329
349
  for (const file of files) {
@@ -333,7 +353,14 @@ export class ViewSnapshots {
333
353
  hasher.update('\n')
334
354
  const target = join(partial, ...file.key.split('/'))
335
355
  mkdirSync(join(target, '..'), { recursive: true })
336
- writeFileSync(target, bytes)
356
+ const written = this.#transform?.(file.key, bytes)
357
+ if (written) {
358
+ transformed.push(file.key)
359
+ const kept = join(partial, ISLANDS_DIR, 'src', ...file.key.split('/'))
360
+ mkdirSync(join(kept, '..'), { recursive: true })
361
+ writeFileSync(kept, bytes)
362
+ }
363
+ writeFileSync(target, written ?? bytes)
337
364
  }
338
365
  const hash = hasher.digest('hex').slice(0, 16)
339
366
 
@@ -357,6 +384,10 @@ export class ViewSnapshots {
357
384
  const dir = join(this.#cacheDir, hash)
358
385
  if (existsSync(dir)) rmSync(partial, { recursive: true, force: true })
359
386
  else renameSync(partial, dir)
387
+ if (this.#beforeSwap)
388
+ await this.#beforeSwap({ dir, hash, transformed }).catch((error: unknown) =>
389
+ this.#problem(`Could not build the islands for these views: ${String(error)}`),
390
+ )
360
391
 
361
392
  const previous = this.#current?.hash
362
393
  this.#current = { hash, dir }
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