@crombolo/server 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.
Files changed (83) hide show
  1. package/package.json +15 -13
  2. package/src/access.ts +29 -27
  3. package/src/adapters/audit.ts +1 -1
  4. package/src/adapters/blueprints.ts +22 -13
  5. package/src/adapters/content.ts +1 -1
  6. package/src/adapters/dictionary.ts +1 -1
  7. package/src/adapters/documents.ts +17 -10
  8. package/src/adapters/elements.ts +47 -37
  9. package/src/adapters/file-system.ts +1 -1
  10. package/src/adapters/health.ts +33 -5
  11. package/src/adapters/media.ts +12 -8
  12. package/src/adapters/member-groups.ts +8 -6
  13. package/src/adapters/members.ts +6 -4
  14. package/src/adapters/public-access.ts +7 -5
  15. package/src/adapters/redirects.ts +1 -1
  16. package/src/adapters/references.ts +1 -1
  17. package/src/adapters/relations.ts +1 -1
  18. package/src/adapters/schema-files.ts +33 -1
  19. package/src/adapters/search-index.ts +1 -1
  20. package/src/adapters/template-files.ts +6 -1
  21. package/src/adapters/template-query.ts +1 -1
  22. package/src/adapters/users.ts +13 -13
  23. package/src/adapters/webhooks.ts +1 -1
  24. package/src/anonymise-rules.ts +83 -0
  25. package/src/approvals-api.ts +1 -1
  26. package/src/approvals.ts +75 -38
  27. package/src/back-office-url.ts +20 -0
  28. package/src/backup.ts +26 -2
  29. package/src/bundle-code.ts +1 -1
  30. package/src/bundle-grants.ts +265 -0
  31. package/src/bundle-install.ts +13 -2
  32. package/src/bundle-media.ts +12 -11
  33. package/src/bundles.ts +258 -444
  34. package/src/component-snippets.ts +1 -1
  35. package/src/components.ts +48 -7
  36. package/src/config.ts +141 -4
  37. package/src/content-notifications.ts +13 -9
  38. package/src/content-operations.ts +23 -65
  39. package/src/content-query.ts +1 -1
  40. package/src/core.ts +663 -0
  41. package/src/cron.ts +139 -0
  42. package/src/custom-tables.ts +274 -0
  43. package/src/database.ts +22 -14
  44. package/src/dictionary-transfer.ts +1 -1
  45. package/src/git-routes.ts +1 -1
  46. package/src/identity-provider-overrides.ts +18 -16
  47. package/src/imaging.ts +65 -15
  48. package/src/index.ts +14 -1
  49. package/src/islands.ts +197 -0
  50. package/src/job-wake.ts +23 -0
  51. package/src/live-reload.ts +195 -0
  52. package/src/log-viewer.ts +6 -1
  53. package/src/marketplace.ts +82 -10
  54. package/src/media-access.ts +12 -9
  55. package/src/member-auth.ts +6 -4
  56. package/src/middleware.ts +236 -0
  57. package/src/models-builder.ts +1 -1
  58. package/src/node-operations.ts +122 -0
  59. package/src/owner-jobs.ts +428 -0
  60. package/src/ports.ts +39 -154
  61. package/src/preview-tokens.ts +6 -12
  62. package/src/remote.ts +3 -1
  63. package/src/routes.ts +420 -0
  64. package/src/schema.ts +8 -3
  65. package/src/seed/compile.ts +7 -5
  66. package/src/seed/export.ts +6 -4
  67. package/src/seo.ts +2 -2
  68. package/src/server.ts +866 -483
  69. package/src/settings.ts +49 -2
  70. package/src/site-data.ts +195 -0
  71. package/src/site-file.ts +30 -4
  72. package/src/site-queries.ts +140 -0
  73. package/src/site-replace.ts +25 -19
  74. package/src/site-sections.ts +1 -1
  75. package/src/site-services.ts +116 -0
  76. package/src/status-pages.ts +142 -0
  77. package/src/status.ts +11 -9
  78. package/src/url-settings.ts +1 -2
  79. package/src/webhook-files.ts +18 -1
  80. package/src/webhooks.ts +83 -15
  81. package/src/worker-watch.ts +73 -0
  82. package/src/worker.ts +138 -0
  83. package/src/bundle-tables.ts +0 -161
package/src/imaging.ts CHANGED
@@ -216,7 +216,7 @@ export function padPixels(
216
216
  // ------------------------------------------------------------ the request
217
217
 
218
218
  export type ResizeMode = 'crop' | 'max' | 'stretch' | 'pad' | 'boxpad' | 'min'
219
- export type OutputFormat = 'jpg' | 'png' | 'webp'
219
+ export type OutputFormat = 'jpg' | 'png' | 'webp' | 'avif'
220
220
 
221
221
  export interface ImagingRequest {
222
222
  width?: number
@@ -231,6 +231,20 @@ export interface ImagingRequest {
231
231
  }
232
232
 
233
233
  const MODES: readonly ResizeMode[] = ['crop', 'max', 'stretch', 'pad', 'boxpad', 'min']
234
+ const FORMATS: readonly OutputFormat[] = ['jpg', 'png', 'webp', 'avif']
235
+
236
+ /** ImageSharp's `ranchor`, as the focal point a crop is cut around. */
237
+ const ANCHORS: Record<string, { left: number; top: number }> = {
238
+ center: { left: 0.5, top: 0.5 },
239
+ top: { left: 0.5, top: 0 },
240
+ bottom: { left: 0.5, top: 1 },
241
+ left: { left: 0, top: 0.5 },
242
+ right: { left: 1, top: 0.5 },
243
+ topleft: { left: 0, top: 0 },
244
+ topright: { left: 1, top: 0 },
245
+ bottomleft: { left: 0, top: 1 },
246
+ bottomright: { left: 1, top: 1 },
247
+ }
234
248
  const MAX_SIDE = 5000
235
249
 
236
250
  /** The imaging request a query asks for, or undefined when it asks for the original. */
@@ -253,11 +267,13 @@ export function parseImagingQuery(params: URLSearchParams): ImagingRequest | und
253
267
  const quality = size('quality')
254
268
  if (!width && !height && !cc && !format) return undefined
255
269
  const mode = (params.get('rmode') ?? '').toLowerCase() as ResizeMode
270
+ // A focal point wins over an anchor, as it does in ImageSharp.
271
+ const anchor = ANCHORS[(params.get('ranchor') ?? '').toLowerCase()]
256
272
  return {
257
273
  width,
258
274
  height,
259
275
  mode: MODES.includes(mode) ? mode : 'crop',
260
- focalPoint: rxy ? { left: rxy[0] as number, top: rxy[1] as number } : undefined,
276
+ focalPoint: rxy ? { left: rxy[0] as number, top: rxy[1] as number } : anchor,
261
277
  crop: cc
262
278
  ? {
263
279
  left: cc[0] as number,
@@ -266,11 +282,44 @@ export function parseImagingQuery(params: URLSearchParams): ImagingRequest | und
266
282
  bottom: cc[3] as number,
267
283
  }
268
284
  : undefined,
269
- format: ['jpg', 'png', 'webp'].includes(format) ? (format as OutputFormat) : undefined,
285
+ format: FORMATS.includes(format as OutputFormat) ? (format as OutputFormat) : undefined,
270
286
  quality: quality ? Math.min(quality, 100) : undefined,
271
287
  }
272
288
  }
273
289
 
290
+ let avif: Promise<boolean> | undefined
291
+
292
+ /**
293
+ * Whether this machine can encode AVIF. Bun uses the operating system's codec:
294
+ * macOS has one, the usual Linux image has no AV1 encoder. Asked once.
295
+ */
296
+ export function canEncodeAvif(): Promise<boolean> {
297
+ avif ??= new Bun.Image(encodePng({ width: 1, height: 1, data: new Uint8Array(4) }))
298
+ .avif()
299
+ .bytes()
300
+ .then(
301
+ () => true,
302
+ () => false,
303
+ )
304
+ return avif
305
+ }
306
+
307
+ /** The format written for a request: AVIF only where it can be, WebP where not. */
308
+ export async function outputFormat(
309
+ requested: OutputFormat | undefined,
310
+ source: string,
311
+ ): Promise<OutputFormat> {
312
+ const format = requested ?? formatOf(source)
313
+ return format === 'avif' && !(await canEncodeAvif()) ? 'webp' : format
314
+ }
315
+
316
+ const CONTENT_TYPES: Record<OutputFormat, string> = {
317
+ jpg: 'image/jpeg',
318
+ png: 'image/png',
319
+ webp: 'image/webp',
320
+ avif: 'image/avif',
321
+ }
322
+
274
323
  const formatOf = (source: string): OutputFormat => {
275
324
  const extension = source.split('.').pop()?.toLowerCase()
276
325
  return extension === 'png' || extension === 'gif' ? 'png' : extension === 'webp' ? 'webp' : 'jpg'
@@ -297,7 +346,7 @@ export async function processImage(
297
346
  request: ImagingRequest,
298
347
  sourceName: string,
299
348
  ): Promise<{ bytes: Uint8Array; contentType: string }> {
300
- const format = request.format ?? formatOf(sourceName)
349
+ const format = await outputFormat(request.format, sourceName)
301
350
  let pixels: Pixels | undefined
302
351
  const decode = async () => {
303
352
  pixels ??= decodePng(await new Bun.Image(bytes).png().bytes())
@@ -374,16 +423,16 @@ export async function processImage(
374
423
  let image = new Bun.Image(pixels ? encodePng(pixels) : bytes)
375
424
  if (resize) image = image.resize(resize.width, resize.height, { fit: resize.fit })
376
425
  const quality = request.quality
426
+ const options = quality ? { quality } : undefined
377
427
  const encoded =
378
428
  format === 'png'
379
429
  ? image.png()
380
430
  : format === 'webp'
381
- ? image.webp(quality ? { quality } : undefined)
382
- : image.jpeg(quality ? { quality } : undefined)
383
- return {
384
- bytes: await encoded.bytes(),
385
- contentType: format === 'png' ? 'image/png' : format === 'webp' ? 'image/webp' : 'image/jpeg',
386
- }
431
+ ? image.webp(options)
432
+ : format === 'avif'
433
+ ? image.avif(options)
434
+ : image.jpeg(options)
435
+ return { bytes: await encoded.bytes(), contentType: CONTENT_TYPES[format] }
387
436
  }
388
437
 
389
438
  /**
@@ -405,16 +454,17 @@ export class ImageProcessor {
405
454
  source: StoredFile,
406
455
  request: ImagingRequest,
407
456
  ): Promise<{ key: string; bytes: Uint8Array; contentType: string }> {
408
- const format = request.format ?? formatOf(source.key)
457
+ // Keyed on what is written, so a node without AVIF never serves another's AVIF as WebP.
458
+ const format = await outputFormat(request.format, source.key)
459
+ const written = { ...request, format }
409
460
  const hash = new Bun.CryptoHasher('sha1')
410
- .update(`${source.key}|${source.etag}|${JSON.stringify(request)}`)
461
+ .update(`${source.key}|${source.etag}|${JSON.stringify(written)}`)
411
462
  .digest('hex')
412
463
  const key = `.cache/${hash.slice(0, 2)}/${hash}.${format}`
413
- const contentType =
414
- format === 'png' ? 'image/png' : format === 'webp' ? 'image/webp' : 'image/jpeg'
464
+ const contentType = CONTENT_TYPES[format]
415
465
  const cached = await this.#store.get(key)
416
466
  if (cached) return { key, bytes: await cached.bytes(), contentType }
417
- const result = await processImage(await source.bytes(), request, source.key)
467
+ const result = await processImage(await source.bytes(), written, source.key)
418
468
  await this.#store.put(key, result.bytes, { contentType: result.contentType })
419
469
  return { key, bytes: result.bytes, contentType: result.contentType }
420
470
  }
package/src/index.ts CHANGED
@@ -20,11 +20,11 @@ export * from './backup.ts'
20
20
  export * from './boot-failure.ts'
21
21
  export * from './bundle-build.ts'
22
22
  export * from './bundle-code.ts'
23
+ export * from './bundle-grants.ts'
23
24
  export * from './bundle-install.ts'
24
25
  export * from './bundle-media.ts'
25
26
  export * from './bundle-reload.ts'
26
27
  export * from './bundle-sections.ts'
27
- export * from './bundle-tables.ts'
28
28
  export * from './bundles.ts'
29
29
  export * from './busy.ts'
30
30
  export * from './components.ts'
@@ -35,6 +35,8 @@ export * from './content-notifications.ts'
35
35
  export * from './content-operations.ts'
36
36
  export * from './content-query.ts'
37
37
  export * from './content-type-udt.ts'
38
+ export * from './cron.ts'
39
+ export * from './custom-tables.ts'
38
40
  export * from './database.ts'
39
41
  export * from './diagnostics.ts'
40
42
  export * from './dictionary-transfer.ts'
@@ -63,8 +65,11 @@ export * from './identity-provider-overrides.ts'
63
65
  export * from './identity-providers.ts'
64
66
  export * from './image-metadata.ts'
65
67
  export * from './imaging.ts'
68
+ export * from './islands.ts'
69
+ export * from './job-wake.ts'
66
70
  export * from './jobs.ts'
67
71
  export * from './listen.ts'
72
+ export * from './live-reload.ts'
68
73
  export * from './log-expressions.ts'
69
74
  export * from './log-viewer.ts'
70
75
  export * from './logging.ts'
@@ -75,15 +80,18 @@ export * from './media-store.ts'
75
80
  export * from './media-store-azure.ts'
76
81
  export * from './media-store-s3.ts'
77
82
  export * from './member-auth.ts'
83
+ export * from './middleware.ts'
78
84
  export * from './models-builder.ts'
79
85
  export * from './no-nodes.ts'
80
86
  export * from './oembed.ts'
87
+ export * from './owner-jobs.ts'
81
88
  export * from './ports.ts'
82
89
  export * from './rate-limit.ts'
83
90
  export * from './redirects.ts'
84
91
  export * from './remote.ts'
85
92
  export * from './remote-credentials.ts'
86
93
  export * from './remote-media.ts'
94
+ export * from './routes.ts'
87
95
  export * from './schema.ts'
88
96
  export * from './schema-store.ts'
89
97
  export * from './secrets.ts'
@@ -93,10 +101,13 @@ export * from './server.ts'
93
101
  export * from './server-events.ts'
94
102
  export * from './settings.ts'
95
103
  export * from './setup.ts'
104
+ export * from './site-data.ts'
96
105
  export * from './site-file.ts'
106
+ export * from './site-queries.ts'
97
107
  export * from './site-replace.ts'
98
108
  export * from './site-sections.ts'
99
109
  export * from './status.ts'
110
+ export * from './status-pages.ts'
100
111
  export * from './tar.ts'
101
112
  export * from './transfer-dashboard.ts'
102
113
  export * from './two-factor.ts'
@@ -106,3 +117,5 @@ export * from './url-settings.ts'
106
117
  export * from './view-runtime.ts'
107
118
  export * from './webhook-files.ts'
108
119
  export * from './webhooks.ts'
120
+ export * from './worker.ts'
121
+ export * from './worker-watch.ts'
package/src/islands.ts ADDED
@@ -0,0 +1,197 @@
1
+ /**
2
+ * The browser code for a generation's islands (story 209), built when the
3
+ * generation is taken and served beside it, so a page and its islands always
4
+ * match. Or, with `islands.manifest`, the files a site's own Vite build wrote.
5
+ * docs/rendering.md, "Islands".
6
+ */
7
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
8
+ import { dirname, join, relative, resolve, sep } from 'node:path'
9
+ import { ISLANDS_DIR, ISLANDS_PATH, type IslandManifest } from '@crombolo/render'
10
+
11
+ /** What a client module may not import: code that only runs on the server. */
12
+ const SERVER_ONLY =
13
+ /^(@crombolo\/(crombolo|render|server|core|data|content|auth|schema|transfer|api-delivery|api-management)(\/.*)?|node:.*|bun(:.*)?)$/
14
+ /** Whether a client module importing this would pull server code into the browser. */
15
+ export const isServerOnly = (specifier: string): boolean =>
16
+ SERVER_ONLY.test(specifier) && specifier !== BROWSER_ENTRY
17
+
18
+ /** The one part of `@crombolo/crombolo` a browser runs: React's mount. */
19
+ const BROWSER_ENTRY = '@crombolo/crombolo/islands-react'
20
+
21
+ const toKey = (path: string) => path.split(sep).join('/')
22
+ const scanner = new Bun.Transpiler({ loader: 'tsx' })
23
+
24
+ /** `components/client/<name>.ts`: modules an `<Island>` mounts. */
25
+ function mountModules(dir: string): string[] {
26
+ const root = join(dir, 'client')
27
+ if (!existsSync(root)) return []
28
+ const out: string[] = []
29
+ const walk = (current: string) => {
30
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
31
+ const path = join(current, entry.name)
32
+ if (entry.isDirectory()) walk(path)
33
+ else if (/\.[jt]sx?$/.test(entry.name)) out.push(toKey(relative(dir, path)))
34
+ }
35
+ }
36
+ walk(root)
37
+ return out
38
+ }
39
+
40
+ /** `client/species-map.ts` as an `<Island>` names it: `client/species-map`. */
41
+ const moduleId = (key: string, client: Set<string>) =>
42
+ client.has(key) ? key : key.replace(/\.[jt]sx?$/, '')
43
+
44
+ /**
45
+ * Bundles a generation's client modules and `<Island>` modules with React's
46
+ * mount, into `<generation>/.islands/out/` with `manifest.json`. Throws with
47
+ * every problem, each naming its file, when the build fails.
48
+ */
49
+ export async function buildIslands(generation: {
50
+ dir: string
51
+ hash: string
52
+ transformed: string[]
53
+ development: boolean
54
+ }): Promise<IslandManifest | undefined> {
55
+ const { dir, hash } = generation
56
+ const client = new Set(generation.transformed)
57
+ const mounts = mountModules(dir)
58
+ if (client.size === 0 && mounts.length === 0) return undefined
59
+ const islands = join(dir, ISLANDS_DIR)
60
+ const out = join(islands, 'out')
61
+ if (existsSync(join(out, 'manifest.json')))
62
+ return JSON.parse(readFileSync(join(out, 'manifest.json'), 'utf8')) as IslandManifest
63
+ mkdirSync(islands, { recursive: true })
64
+ const reactEntry = join(islands, 'react-mount.ts')
65
+ if (client.size > 0) writeFileSync(reactEntry, `export { mount } from '${BROWSER_ENTRY}'\n`)
66
+
67
+ const entries = [
68
+ ...[...client].map((key) => join(dir, ...key.split('/'))),
69
+ ...mounts.map((key) => join(dir, ...key.split('/'))),
70
+ ...(client.size > 0 ? [reactEntry] : []),
71
+ ]
72
+ const keyOf = (path: string) => toKey(relative(dir, path))
73
+ const refused: string[] = []
74
+ const result = await Bun.build({
75
+ entrypoints: entries,
76
+ outdir: out,
77
+ root: dir,
78
+ target: 'browser',
79
+ format: 'esm',
80
+ splitting: true,
81
+ minify: !generation.development,
82
+ naming: { entry: '[dir]/[name]-[hash].[ext]', chunk: 'chunks/[name]-[hash].[ext]' },
83
+ define: {
84
+ 'process.env.NODE_ENV': JSON.stringify(generation.development ? 'development' : 'production'),
85
+ },
86
+ throw: false,
87
+ plugins: [
88
+ {
89
+ name: 'crombolo-islands',
90
+ setup(build) {
91
+ // A client module's snapshot copy is its server stub; the browser gets its source.
92
+ build.onLoad({ filter: /\.[jt]sx?$/ }, (args) => {
93
+ const key = keyOf(args.path)
94
+ if (key.startsWith('..') || !client.has(key)) return undefined
95
+ const source = readFileSync(join(islands, 'src', ...key.split('/')), 'utf8')
96
+ // From the source too: the bundler drops an unused import before resolving it.
97
+ for (const specifier of scanner.scanImports(source))
98
+ if (isServerOnly(specifier.path))
99
+ refused.push(
100
+ `components/${key} imports ${specifier.path}, which only runs on the server. A 'use client' component cannot use it.`,
101
+ )
102
+ const pragma = /@jsxImportSource\s/.test(source)
103
+ ? ''
104
+ : '/** @jsxImportSource react */\n'
105
+ return { contents: `${pragma}${source}`, loader: key.endsWith('x') ? 'tsx' : 'ts' }
106
+ })
107
+ build.onResolve({ filter: SERVER_ONLY }, (args) => {
108
+ if (args.path === BROWSER_ENTRY) return undefined
109
+ const from = keyOf(args.importer)
110
+ refused.push(
111
+ `components/${from} imports ${args.path}, which only runs on the server. A 'use client' component cannot use it.`,
112
+ )
113
+ return { path: args.path, external: true }
114
+ })
115
+ },
116
+ },
117
+ ],
118
+ })
119
+ if (refused.length > 0) throw new Error([...new Set(refused)].join('\n'))
120
+ if (!result.success)
121
+ throw new Error(
122
+ result.logs
123
+ .map((log) => String(log.message ?? log).replaceAll(`${dir}${sep}`, 'components/'))
124
+ .join('\n'),
125
+ )
126
+
127
+ const urlOf = (path: string) => `${ISLANDS_PATH}/${hash}/${toKey(relative(out, path))}`
128
+ const manifest: IslandManifest = { modules: {} }
129
+ for (const output of result.outputs) {
130
+ if (output.kind !== 'entry-point') continue
131
+ const built = toKey(relative(out, output.path)).replace(/-[a-z0-9]+\.js$/, '')
132
+ if (built === `${ISLANDS_DIR}/react-mount`) {
133
+ manifest.react = urlOf(output.path)
134
+ continue
135
+ }
136
+ const source = entries.map(keyOf).find((key) => key.replace(/\.[jt]sx?$/, '') === built)
137
+ if (source) manifest.modules[moduleId(source, client)] = urlOf(output.path)
138
+ }
139
+ writeFileSync(join(out, 'manifest.json'), JSON.stringify(manifest))
140
+ return manifest
141
+ }
142
+
143
+ /** Where a generation's built file lives on disk, or undefined for a path outside it. */
144
+ export function builtIslandFile(cacheDir: string, hash: string, path: string): string | undefined {
145
+ if (!/^[0-9a-f]{16}$/.test(hash)) return undefined
146
+ if (!path || path.split('/').some((part) => part === '' || part === '.' || part === '..'))
147
+ return undefined
148
+ const file = join(cacheDir, hash, ISLANDS_DIR, 'out', ...path.split('/'))
149
+ return existsSync(file) ? file : undefined
150
+ }
151
+
152
+ /** A site's Vite manifest, made over into Crombolo's, with files served from `/crombolo/islands/vite/`. */
153
+ export function viteIslandManifest(siteDir: string, manifestPath: string): IslandManifest {
154
+ const file = resolve(siteDir, manifestPath)
155
+ const vite = JSON.parse(readFileSync(file, 'utf8')) as Record<
156
+ string,
157
+ { file: string; src?: string; isEntry?: boolean }
158
+ >
159
+ const manifest: IslandManifest = { modules: {} }
160
+ for (const [key, entry] of Object.entries(vite)) {
161
+ const source = (entry.src ?? key).replace(/^\.\//, '')
162
+ const url = `${ISLANDS_PATH}/vite/${entry.file}`
163
+ if (/islands-react\.[jt]sx?$/.test(source)) manifest.react = url
164
+ else if (source.startsWith('components/client/'))
165
+ manifest.modules[source.slice('components/'.length).replace(/\.[jt]sx?$/, '')] = url
166
+ else if (source.startsWith('components/'))
167
+ manifest.modules[source.slice('components/'.length)] = url
168
+ }
169
+ return manifest
170
+ }
171
+
172
+ /** Where a Vite build's files are: the manifest's own folder, less Vite's `.vite/`. */
173
+ export function viteOutDir(siteDir: string, manifestPath: string): string {
174
+ const folder = dirname(resolve(siteDir, manifestPath))
175
+ return folder.endsWith(`${sep}.vite`) ? dirname(folder) : folder
176
+ }
177
+
178
+ /** A Vite dev server's modules, for development, by source path. */
179
+ export function devServerIslandManifest(devServer: string, componentsDir: string): IslandManifest {
180
+ const base = devServer.replace(/\/+$/, '')
181
+ const manifest: IslandManifest = { react: `${base}/@id/${BROWSER_ENTRY}`, modules: {} }
182
+ const walk = (current: string) => {
183
+ if (!existsSync(current)) return
184
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
185
+ const path = join(current, entry.name)
186
+ if (entry.isDirectory()) walk(path)
187
+ else if (/\.[jt]sx?$/.test(entry.name)) {
188
+ const key = toKey(relative(componentsDir, path))
189
+ const url = `${base}/components/${key}`
190
+ manifest.modules[key] = url
191
+ if (key.startsWith('client/')) manifest.modules[key.replace(/\.[jt]sx?$/, '')] = url
192
+ }
193
+ }
194
+ }
195
+ walk(componentsDir)
196
+ return manifest
197
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Where the background jobs run (story 223): on an owning node unless it is
3
+ * told to leave them (`CROMBOLO_JOBS=off`), and on a worker always. A node that
4
+ * leaves them wakes the worker over `NOTIFY` when a write leaves it work.
5
+ */
6
+ import { type Db, JOBS_CHANNEL, type JobWake } from '@crombolo/data'
7
+ import type { CromboloConfig } from './config.ts'
8
+
9
+ export function runsJobs(config: Pick<CromboloConfig, 'role' | 'runJobs'>): boolean {
10
+ if (config.role === 'worker') return true
11
+ return config.role !== 'web' && config.runJobs
12
+ }
13
+
14
+ /** Calls `onWork` for each wake a writer sends; resolves to the way to stop listening. */
15
+ export async function listenForJobs(
16
+ db: Db,
17
+ onWork: (work: JobWake) => void,
18
+ ): Promise<(() => Promise<void>) | undefined> {
19
+ if (!db.listen) return undefined
20
+ return db.listen(JOBS_CHANNEL, (payload) => {
21
+ if (payload === 'events' || payload === 'search' || payload === 'jobs') onWork(payload)
22
+ })
23
+ }
@@ -0,0 +1,195 @@
1
+ /**
2
+ * Live reload in development (story 214): the event stream open pages listen
3
+ * on, the changes it carries, and the background type check whose findings it
4
+ * shows. docs/writing-components.md, "The development loop".
5
+ */
6
+ import { watch } from 'node:fs'
7
+ import type { LiveChange, LiveTypes } from '@crombolo/render'
8
+
9
+ export interface LiveReloadOptions {
10
+ /** This process's identity; a page that reconnects to a different one reloads. */
11
+ bootId?: string
12
+ /** A burst of changes within this long is one reload. */
13
+ collectMs?: number
14
+ /** A comment this often keeps a quiet stream open through proxies. */
15
+ heartbeatMs?: number
16
+ }
17
+
18
+ export interface LiveReload {
19
+ readonly bootId: string
20
+ /** Something open pages show has changed. */
21
+ changed(what: LiveChange): void
22
+ /** The background type check's latest findings, sent now and to each page that connects. */
23
+ types(findings: LiveTypes): void
24
+ /** The `text/event-stream` answer for a page's `EventSource`. */
25
+ stream(request: Request): Response
26
+ /** How many pages are listening. */
27
+ listeners(): number
28
+ close(): void
29
+ }
30
+
31
+ const encoder = new TextEncoder()
32
+ const frame = (event: string, data: unknown) =>
33
+ encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)
34
+
35
+ export function createLiveReload(options: LiveReloadOptions = {}): LiveReload {
36
+ const bootId = options.bootId ?? crypto.randomUUID()
37
+ const collectMs = options.collectMs ?? 200
38
+ const listeners = new Set<ReadableStreamDefaultController<Uint8Array>>()
39
+ let latestTypes: LiveTypes = { count: 0 }
40
+ const pending = new Set<LiveChange>()
41
+ let timer: ReturnType<typeof setTimeout> | undefined
42
+
43
+ const send = (chunk: Uint8Array) => {
44
+ for (const listener of listeners) {
45
+ try {
46
+ listener.enqueue(chunk)
47
+ } catch {
48
+ listeners.delete(listener)
49
+ }
50
+ }
51
+ }
52
+ const heartbeat = setInterval(
53
+ () => send(encoder.encode(': still here\n\n')),
54
+ options.heartbeatMs ?? 15_000,
55
+ )
56
+ heartbeat.unref?.()
57
+
58
+ return {
59
+ bootId,
60
+ changed(what) {
61
+ pending.add(what)
62
+ if (timer) return
63
+ timer = setTimeout(() => {
64
+ timer = undefined
65
+ const reasons = [...pending]
66
+ pending.clear()
67
+ send(frame('reload', { reasons }))
68
+ }, collectMs)
69
+ },
70
+ types(findings) {
71
+ latestTypes = findings
72
+ send(frame('types', findings))
73
+ },
74
+ stream(request) {
75
+ let self: ReadableStreamDefaultController<Uint8Array> | undefined
76
+ const body = new ReadableStream<Uint8Array>({
77
+ start(controller) {
78
+ self = controller
79
+ listeners.add(controller)
80
+ // A short retry, so a page finds a restarted server quickly.
81
+ controller.enqueue(encoder.encode('retry: 500\n\n'))
82
+ controller.enqueue(frame('hello', { boot: bootId }))
83
+ controller.enqueue(frame('types', latestTypes))
84
+ request.signal.addEventListener('abort', () => {
85
+ listeners.delete(controller)
86
+ try {
87
+ controller.close()
88
+ } catch {}
89
+ })
90
+ },
91
+ cancel() {
92
+ if (self) listeners.delete(self)
93
+ },
94
+ })
95
+ return new Response(body, {
96
+ headers: {
97
+ 'content-type': 'text/event-stream; charset=utf-8',
98
+ 'cache-control': 'no-store',
99
+ connection: 'keep-alive',
100
+ },
101
+ })
102
+ },
103
+ listeners: () => listeners.size,
104
+ close() {
105
+ clearInterval(heartbeat)
106
+ clearTimeout(timer)
107
+ for (const listener of listeners) {
108
+ try {
109
+ listener.close()
110
+ } catch {}
111
+ }
112
+ listeners.clear()
113
+ },
114
+ }
115
+ }
116
+
117
+ export interface TypeWatchOptions {
118
+ /** One check; aborted when a newer change starts another. */
119
+ check(signal: AbortSignal): Promise<{ checked: boolean; problems: string[] }>
120
+ /** A finished check's findings, only when they differ from the last. */
121
+ onFindings(findings: { problems: string[]; types: LiveTypes }): void
122
+ }
123
+
124
+ /**
125
+ * Runs the type check one at a time: a change while one runs stops it and
126
+ * starts again, so the findings are always of the latest files.
127
+ */
128
+ export function createTypeWatch(options: TypeWatchOptions) {
129
+ let running: AbortController | undefined
130
+ let last: string | undefined
131
+
132
+ const run = async () => {
133
+ running?.abort()
134
+ const controller = new AbortController()
135
+ running = controller
136
+ try {
137
+ const result = await options.check(controller.signal)
138
+ if (controller.signal.aborted || !result.checked) return
139
+ const key = result.problems.join('\n')
140
+ if (key === last) return
141
+ last = key
142
+ options.onFindings({ problems: result.problems, types: typesOf(result.problems) })
143
+ } catch (error) {
144
+ if (!controller.signal.aborted) throw error
145
+ } finally {
146
+ if (running === controller) running = undefined
147
+ }
148
+ }
149
+
150
+ return {
151
+ /** Checks again, stopping a check already running. */
152
+ schedule(): Promise<void> {
153
+ return run()
154
+ },
155
+ stop() {
156
+ running?.abort()
157
+ },
158
+ }
159
+ }
160
+
161
+ const TSC_LINE = /^(.+?)\((\d+),\d+\):\s*error\s+TS\d+:\s*(.*)$/
162
+
163
+ /** The banner's summary of `tsc`'s lines: how many errors, and the first. */
164
+ export function typesOf(problems: readonly string[]): LiveTypes {
165
+ const errors = problems.filter((line) => TSC_LINE.test(line))
166
+ const match = errors[0] ? TSC_LINE.exec(errors[0]) : null
167
+ return {
168
+ count: errors.length,
169
+ ...(match
170
+ ? {
171
+ first: {
172
+ file: match[1] as string,
173
+ line: Number(match[2]),
174
+ message: match[3] as string,
175
+ },
176
+ }
177
+ : {}),
178
+ }
179
+ }
180
+
181
+ /** Calls `onChange` once a burst of changes under `dir` has settled; development only. */
182
+ export function watchDirectory(dir: string, onChange: () => void, settleMs = 100) {
183
+ let timer: ReturnType<typeof setTimeout> | undefined
184
+ const watcher = watch(dir, { recursive: true }, () => {
185
+ clearTimeout(timer)
186
+ timer = setTimeout(onChange, settleMs)
187
+ })
188
+ watcher.unref()
189
+ return {
190
+ close() {
191
+ clearTimeout(timer)
192
+ watcher.close()
193
+ },
194
+ }
195
+ }
package/src/log-viewer.ts CHANGED
@@ -7,7 +7,12 @@
7
7
  import { existsSync } from 'node:fs'
8
8
  import { readdir, stat } from 'node:fs/promises'
9
9
  import { join } from 'node:path'
10
- import type { LogEntry, LogLevelName, LogRange, LogViewerPort } from '@crombolo/api-management'
10
+ import type {
11
+ LogEntry,
12
+ LogLevelName,
13
+ LogRange,
14
+ LogViewerPort,
15
+ } from '@crombolo/api-management/domain'
11
16
  import { type Db, LogSearchRepository } from '@crombolo/data'
12
17
  import type { CromboloConfig } from './config.ts'
13
18
  import { type LogEvent, logFilter } from './log-expressions.ts'