@crombolo/server 0.50.0 → 0.51.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.
@@ -11,7 +11,14 @@
11
11
  * the same `.udt` format Umbraco uses, the same upsert by key, and the same rule
12
12
  * that translations for languages this site does not have are skipped.
13
13
  */
14
- import { type Db, DictionaryRepository } from '@crombolo/data'
14
+ import { normaliseUuid, SEED_NAMESPACE, uuidV5 } from '@crombolo/core'
15
+ import {
16
+ appendCacheInstruction,
17
+ type Db,
18
+ type DictionaryItem,
19
+ DictionaryRepository,
20
+ type DictionaryTranslation,
21
+ } from '@crombolo/data'
15
22
  import { readUdt, type UdtItem, writeUdtAll } from './udt.ts'
16
23
 
17
24
  export interface DictionaryImportOutcome {
@@ -56,6 +63,182 @@ export async function dictionaryToUdt(
56
63
 
57
64
  export const writeDictionaryUdt = writeUdtAll
58
65
 
66
+ /** An item as a person writes it: named, with no key of its own. */
67
+ export interface DictionaryEntry {
68
+ name: string
69
+ translations: DictionaryTranslation[]
70
+ children: DictionaryEntry[]
71
+ }
72
+
73
+ /** What applying named items did, or would do. */
74
+ export interface DictionaryChange {
75
+ ok: boolean
76
+ reason?: string
77
+ created: string[]
78
+ updated: string[]
79
+ moved: string[]
80
+ unchanged: number
81
+ /** Translations dropped because this environment has no such language. */
82
+ skipped: string[]
83
+ }
84
+
85
+ /** A new item's key, the same on every site built from one file. */
86
+ export const dictionaryKey = (name: string) => uuidV5(`dictionary/${name}`, SEED_NAMESPACE)
87
+
88
+ /** Carries a dry run's outcome out of the transaction it rolls back. */
89
+ class Undone<T> extends Error {
90
+ constructor(readonly outcome: T) {
91
+ super('undone')
92
+ }
93
+ }
94
+
95
+ /**
96
+ * One dictionary write in a transaction, telling every node when it changed
97
+ * something (story 174). A failure leaves nothing behind, and a dry run is the
98
+ * real write undone, so it reports exactly what would happen.
99
+ */
100
+ export async function writingDictionary<T extends { ok: boolean }>(
101
+ db: Db,
102
+ options: { dryRun?: boolean; by?: string },
103
+ write: (tx: Db) => Promise<T>,
104
+ changed: (outcome: T) => boolean,
105
+ ): Promise<T> {
106
+ try {
107
+ return await db.transaction(async (tx) => {
108
+ const outcome = await write(tx)
109
+ if (options.dryRun || !outcome.ok) throw new Undone(outcome)
110
+ if (changed(outcome))
111
+ await appendCacheInstruction(tx, {
112
+ kind: 'content',
113
+ payload: { dictionary: true },
114
+ by: options.by,
115
+ })
116
+ return outcome
117
+ })
118
+ } catch (error) {
119
+ if (error instanceof Undone) return error.outcome as T
120
+ throw error
121
+ }
122
+ }
123
+
124
+ const sameKey = (a: string | null, b: string | null) =>
125
+ (a ? normaliseUuid(a) : null) === (b ? normaliseUuid(b) : null)
126
+
127
+ /**
128
+ * Applies items by name. It adds and changes and never deletes, and a language
129
+ * an entry does not name is kept. `keepPlace` leaves an existing top-level item
130
+ * under its parent: `dictionary set` names no place, where a file states one.
131
+ */
132
+ export async function applyDictionaryEntries(
133
+ db: Db,
134
+ entries: readonly DictionaryEntry[],
135
+ options: { parentKey?: string | null; keepPlace?: boolean; dryRun?: boolean; by?: string } = {},
136
+ ): Promise<DictionaryChange> {
137
+ return writingDictionary(
138
+ db,
139
+ options,
140
+ async (tx) => {
141
+ const repo = new DictionaryRepository(tx)
142
+ const languages = new Map(
143
+ (await tx.q.selectFrom('language').select('iso_code').execute()).map((row) => [
144
+ String(row.iso_code).toLowerCase(),
145
+ String(row.iso_code),
146
+ ]),
147
+ )
148
+ const skipped = new Set<string>()
149
+ const known = (entry: DictionaryEntry) =>
150
+ entry.translations.flatMap((t) => {
151
+ const isoCode = languages.get(t.isoCode.toLowerCase())
152
+ if (!isoCode) skipped.add(t.isoCode)
153
+ return isoCode ? [{ isoCode, translation: t.translation }] : []
154
+ })
155
+
156
+ const change: DictionaryChange = {
157
+ ok: true,
158
+ created: [],
159
+ updated: [],
160
+ moved: [],
161
+ unchanged: 0,
162
+ skipped: [],
163
+ }
164
+ const failed = (name: string, result: string) => {
165
+ change.ok = false
166
+ change.reason = `"${name}" could not be written: ${result}`
167
+ }
168
+ const update = async (entry: DictionaryEntry, item: DictionaryItem) => {
169
+ const mine = known(entry)
170
+ const differs = mine.some(
171
+ (t) =>
172
+ item.translations.find((o) => o.isoCode.toLowerCase() === t.isoCode.toLowerCase())
173
+ ?.translation !== t.translation,
174
+ )
175
+ if (!differs) return false
176
+ const result = await repo.update(item.key, {
177
+ name: item.name,
178
+ translations: [
179
+ ...item.translations.filter(
180
+ (t) => !mine.some((n) => n.isoCode.toLowerCase() === t.isoCode.toLowerCase()),
181
+ ),
182
+ ...mine,
183
+ ],
184
+ })
185
+ if (result === 'Success') return true
186
+ failed(entry.name, result)
187
+ return false
188
+ }
189
+ const apply = async (
190
+ entry: DictionaryEntry,
191
+ parent: string | null,
192
+ place: boolean,
193
+ ): Promise<void> => {
194
+ const existing = await repo.byName(entry.name)
195
+ let key = existing?.key
196
+ if (existing) {
197
+ const updated = await update(entry, existing)
198
+ const moves = place && !sameKey(existing.parentKey, parent)
199
+ if (moves) {
200
+ const result = await repo.move(existing.key, parent)
201
+ if (result === 'Success') change.moved.push(entry.name)
202
+ else failed(entry.name, result)
203
+ }
204
+ if (updated) change.updated.push(entry.name)
205
+ else if (!moves) change.unchanged += 1
206
+ } else {
207
+ // A site that renamed an item keeps its key; the name now is a new item.
208
+ const wanted = dictionaryKey(entry.name)
209
+ key = (await repo.get(wanted)) ? crypto.randomUUID() : wanted
210
+ const result = await repo.create({
211
+ key,
212
+ name: entry.name,
213
+ parentKey: parent,
214
+ translations: known(entry),
215
+ })
216
+ if (result === 'Success') change.created.push(entry.name)
217
+ else failed(entry.name, result)
218
+ }
219
+ if (!change.ok) return
220
+ for (const child of entry.children) await apply(child, key as string, true)
221
+ }
222
+ for (const entry of entries) {
223
+ await apply(entry, options.parentKey ?? null, !options.keepPlace)
224
+ if (!change.ok) break
225
+ }
226
+ change.skipped = [...skipped]
227
+ return change
228
+ },
229
+ (change) => change.created.length + change.updated.length + change.moved.length > 0,
230
+ )
231
+ }
232
+
233
+ /** Named items as `.udt` items, keyed as `applyDictionaryEntries` would key them. */
234
+ export const keyedEntries = (entries: readonly DictionaryEntry[]): UdtItem[] =>
235
+ entries.map((entry) => ({
236
+ key: dictionaryKey(entry.name),
237
+ name: entry.name,
238
+ translations: entry.translations,
239
+ children: keyedEntries(entry.children),
240
+ }))
241
+
59
242
  /**
60
243
  * Applies a `.udt` file. Items are upserted by key, so running it twice is a
61
244
  * no-op and an item translated here keeps any language the file does not carry.
package/src/index.ts CHANGED
@@ -41,6 +41,7 @@ export * from './cron.ts'
41
41
  export * from './custom-tables.ts'
42
42
  export * from './database.ts'
43
43
  export * from './diagnostics.ts'
44
+ export * from './dictionary-toml.ts'
44
45
  export * from './dictionary-transfer.ts'
45
46
  export * from './domains.ts'
46
47
  export * from './editor-types.ts'
@@ -107,8 +108,10 @@ export * from './server.ts'
107
108
  export * from './server-events.ts'
108
109
  export * from './settings.ts'
109
110
  export * from './setup.ts'
111
+ export * from './site-assets.ts'
110
112
  export * from './site-data.ts'
111
113
  export * from './site-file.ts'
114
+ export * from './site-public.ts'
112
115
  export * from './site-queries.ts'
113
116
  export * from './site-replace.ts'
114
117
  export * from './site-sections.ts'
package/src/remote.ts CHANGED
@@ -58,11 +58,12 @@ import { describeProvenance, provenanceProblem, verifyProvenance } from './prove
58
58
  import { createCiSignIn, readRuleInput, trustedIssuers } from './remote-ci.ts'
59
59
  import { openSecret, sealSecret, usableSecretKey } from './secrets.ts'
60
60
  import { exportSite } from './site-file.ts'
61
+ import { REMOTE_DISCOVERY_PATH } from './site-public.ts'
61
62
  import { replaceSummary } from './site-replace.ts'
62
63
  import { extractTarball } from './tar.ts'
63
64
 
64
65
  export const REMOTE_PROTOCOL_VERSION = '1'
65
- export const REMOTE_DISCOVERY_PATH = '/.well-known/crombolo-remote'
66
+ export { REMOTE_DISCOVERY_PATH }
66
67
  export const REMOTE_API_PATH = '/umbraco/remote/v1'
67
68
 
68
69
  /** How long a finished job's file stays downloadable, and its row with it. */
@@ -1175,6 +1176,7 @@ export function createRemote(options: RemoteOptions): Remote {
1175
1176
  { section: 'components', dir: config.componentsDir },
1176
1177
  { section: 'styles', dir: config.stylesheetsDir },
1177
1178
  { section: 'scripts', dir: config.scriptsDir },
1179
+ { section: 'public', dir: config.publicDir },
1178
1180
  ]
1179
1181
  const summary = await replaceSummary(
1180
1182
  db,
package/src/schema.ts CHANGED
@@ -24,6 +24,7 @@ import {
24
24
  latestCheckpoint,
25
25
  latestLedgerId,
26
26
  type NodeSchemaState,
27
+ oldestCacheInstructionId,
27
28
  readWritesPaused,
28
29
  touchServer,
29
30
  updateSchemaStateHash,
@@ -251,6 +252,11 @@ export interface CachePollerOptions {
251
252
  role?: string
252
253
  /** Called for instructions other nodes appended. */
253
254
  onInstruction(kind: CacheInstructionKind, payload: Record<string, unknown>): void
255
+ /**
256
+ * Instructions this node never read were pruned (story 285). What has a
257
+ * checkpoint catches up by it; what has none has to look again.
258
+ */
259
+ onMissed?(): void
254
260
  /**
255
261
  * The published cache's freshness (story 174). With it, content and schema
256
262
  * instructions only wake the poll: the node compares the latest committed
@@ -392,6 +398,10 @@ export class CacheInstructionPoller {
392
398
  const { db, nodeId, nodeState, onInstruction } = this.#options
393
399
  // Read first: every instruction numbered up to it has committed, and is visible below.
394
400
  const latest = await latestCheckpoint(db)
401
+ // Pruning keeps the newest row, so the log only starts past this node when
402
+ // it lost rows. A gap in ids makes this a false alarm, which costs a look.
403
+ const oldest = await oldestCacheInstructionId(db)
404
+ if (oldest !== undefined && oldest > this.#cursor + 1) this.#options.onMissed?.()
395
405
  // A row can commit after one with a higher id (Postgres hands ids out
396
406
  // before commit), so a short window behind the cursor is read again and
397
407
  // the ids already seen are skipped.
@@ -26,6 +26,7 @@ import {
26
26
  } from '@crombolo/data'
27
27
  import {
28
28
  BUNDLE_FORMAT_VERSION,
29
+ BUNDLE_SECTIONS,
29
30
  type BundleBlob,
30
31
  type BundleFile,
31
32
  type BundleKind,
@@ -38,9 +39,17 @@ import {
38
39
  } from '@crombolo/transfer'
39
40
  import { createMediaPort } from '../adapters/media.ts'
40
41
  import { type CromboloConfig, VERSION } from '../config.ts'
42
+ import { type DictionaryEntry, keyedEntries, writeDictionaryUdt } from '../dictionary-transfer.ts'
41
43
  import { SEED_NAMESPACE, seedKey, uuidV5 } from './keys.ts'
42
44
  import { lineOf } from './lines.ts'
43
- import { kindDir, readSeed, type SeedFinding, type SeedItem } from './read.ts'
45
+ import {
46
+ DICTIONARY_FILE,
47
+ kindDir,
48
+ readSeed,
49
+ readSeedDictionary,
50
+ type SeedFinding,
51
+ type SeedItem,
52
+ } from './read.ts'
44
53
  import { schemaLookup, valueWriter } from './values.ts'
45
54
 
46
55
  export interface SeedBuild {
@@ -52,6 +61,8 @@ export interface SeedBuild {
52
61
  files?: BundleFile[]
53
62
  /** How many items of each kind it holds. */
54
63
  counts: Record<'content' | 'library' | 'media', number>
64
+ /** `content/dictionary.toml`, as the items it holds (story 168). */
65
+ dictionary?: DictionaryEntry[]
55
66
  }
56
67
 
57
68
  /** A word for a file name: `about-us` → `About us`. */
@@ -69,6 +80,15 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
69
80
  const counts = { content: 0, library: 0, media: 0 }
70
81
  for (const item of tree.items) counts[item.kind] += 1
71
82
 
83
+ const dictionary = readSeedDictionary(config.siteDir)
84
+ for (const problem of dictionary?.problems ?? [])
85
+ findings.push({
86
+ file: DICTIONARY_FILE,
87
+ line: problem.path.length > 0 ? lineOf(dictionary?.text ?? '', problem.path) : 1,
88
+ code: 'bad-dictionary',
89
+ message: problem.message,
90
+ })
91
+
72
92
  const state = await currentSchemaState(db)
73
93
  const documentTypes = new ContentTypeRepository(db)
74
94
  const mediaTypes = new ContentTypeRepository(db, { kind: 'media' })
@@ -89,6 +109,21 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
89
109
  message,
90
110
  })
91
111
 
112
+ const checkLanguages = (entries: readonly DictionaryEntry[], path: readonly string[]) => {
113
+ for (const entry of entries) {
114
+ for (const { isoCode } of entry.translations)
115
+ if (!languages.has(isoCode.toLowerCase()))
116
+ findings.push({
117
+ file: DICTIONARY_FILE,
118
+ line: lineOf(dictionary?.text ?? '', [...path, entry.name, isoCode]),
119
+ code: 'unknown-language',
120
+ message: `"${entry.name}" has a translation for ${isoCode}, a language this site has not got`,
121
+ })
122
+ checkLanguages(entry.children, [...path, entry.name])
123
+ }
124
+ }
125
+ checkLanguages(dictionary?.entries ?? [], [])
126
+
92
127
  // ---------------------------------------------------------------- keys
93
128
  const keyOf = new Map<SeedItem, string>()
94
129
  const byKey = new Map<string, SeedItem>()
@@ -453,6 +488,7 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
453
488
  identity.update(`${item.kind}\0${item.path}\0${item.text}\0`)
454
489
  if (item.bytes) identity.update(item.bytes)
455
490
  }
491
+ if (dictionary) identity.update(`dictionary\0${dictionary.text}\0`)
456
492
  const id = uuidV5(`seed:${identity.digest('hex')}`, SEED_NAMESPACE)
457
493
  const tally: Partial<Record<BundleKind, number>> = {}
458
494
  for (const node of bundleNodes) tally[node.kind] = (tally[node.kind] ?? 0) + 1
@@ -491,7 +527,19 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
491
527
  },
492
528
  nodes: bundleNodes,
493
529
  }
494
- const payload = writeBundle(set, blobs)
530
+ const entries = dictionary?.entries ?? []
531
+ const payload = writeBundle(
532
+ set,
533
+ blobs,
534
+ entries.length > 0
535
+ ? [
536
+ {
537
+ path: `${BUNDLE_SECTIONS.dictionary}.udt`,
538
+ text: writeDictionaryUdt(keyedEntries(entries)),
539
+ },
540
+ ]
541
+ : [],
542
+ )
495
543
  const files = writeBundlePackage(payload, {
496
544
  name: 'crombolo-site-seed',
497
545
  version: '0.0.0',
@@ -501,5 +549,5 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
501
549
  private: true,
502
550
  peerRange: `>=${VERSION}`,
503
551
  })
504
- return { findings, set, blobs, files, counts }
552
+ return { findings, set, blobs, files, counts, ...(dictionary ? { dictionary: entries } : {}) }
505
553
  }
package/src/seed/read.ts CHANGED
@@ -8,6 +8,8 @@
8
8
  import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
9
9
  import { join, relative } from 'node:path'
10
10
 
11
+ import { readDictionaryToml } from '../dictionary-toml.ts'
12
+
11
13
  export type SeedKind = 'content' | 'library' | 'media'
12
14
 
13
15
  /** The folder a site's content files are in. */
@@ -200,6 +202,17 @@ export function readSeed(siteDir: string): SeedTree {
200
202
  return { items, findings }
201
203
  }
202
204
 
205
+ /** The dictionary among a site's content files (story 168). */
206
+ export const DICTIONARY_FILE = `${CONTENT_FILES_DIR}/dictionary.toml`
207
+
208
+ /** `content/dictionary.toml`, read, when the site has one. */
209
+ export function readSeedDictionary(siteDir: string) {
210
+ const file = join(siteDir, DICTIONARY_FILE)
211
+ if (!existsSync(file)) return undefined
212
+ const text = readFileSync(file, 'utf8')
213
+ return { text, ...readDictionaryToml(text) }
214
+ }
215
+
203
216
  /** Whether a site has content files at all, where they are or where they were. */
204
217
  export const hasSeed = (siteDir: string) =>
205
218
  existsSync(join(siteDir, CONTENT_FILES_DIR)) || existsSync(join(siteDir, 'seed'))
package/src/server.ts CHANGED
@@ -228,6 +228,7 @@ import { provenanceProblem } from './provenance.ts'
228
228
  import { createRemote, type RestartOutcome } from './remote.ts'
229
229
  import { SiteAssets } from './site-assets.ts'
230
230
  import { unknownHostProvided } from './site-file.ts'
231
+ import { PublicFiles } from './site-public.ts'
231
232
  import {
232
233
  activeSpan,
233
234
  inSpan,
@@ -361,6 +362,8 @@ export interface ServerOptions {
361
362
  * (story 241); absent when nothing supervises this one.
362
363
  */
363
364
  restart?: () => Promise<RestartOutcome>
365
+ /** Off, a node hears of file changes only through instructions, as on a network folder. */
366
+ watchSiteFiles?: boolean
364
367
  }
365
368
 
366
369
  export async function createServer(
@@ -384,7 +387,11 @@ export async function createServer(
384
387
  // and a template error says which components were rendering.
385
388
  const live = config.liveReload ? createLiveReload() : undefined
386
389
  let drafts: { cache: PublishedCache; version: number } | undefined
390
+ // Set once they exist: a Postgres notification can wake the poller before then,
391
+ // and they read the disk as they start anyway.
392
+ let siteFilesChanged: ((change: 'assets' | 'public') => void) | undefined
387
393
  const core = await createCore(config, {
394
+ onSiteFiles: (change) => siteFilesChanged?.(change),
388
395
  onCacheInvalidate: () => {
389
396
  drafts = undefined
390
397
  live?.changed('content')
@@ -861,14 +868,31 @@ export async function createServer(
861
868
  const generatedScripts = new Map(
862
869
  generatedBodies.map(([path, body]) => [generatedPaths.get(path) as string, body]),
863
870
  )
864
- const siteAssets = new SiteAssets([
865
- { prefix: '/css', dir: config.stylesheetsDir, extension: '.css' },
866
- { prefix: '/scripts', dir: config.scriptsDir, extension: '.js' },
867
- ])
871
+ const siteAssets = new SiteAssets(
872
+ [
873
+ { prefix: '/css', dir: config.stylesheetsDir, extension: '.css' },
874
+ { prefix: '/scripts', dir: config.scriptsDir, extension: '.js' },
875
+ ],
876
+ { watch: serverOptions.watchSiteFiles },
877
+ )
868
878
  siteAssets.start()
879
+ const publicFiles = new PublicFiles(config.publicDir, config.backOfficePath, {
880
+ watch: serverOptions.watchSiteFiles,
881
+ })
882
+ publicFiles.start()
883
+ siteFilesChanged = (change) => (change === 'public' ? publicFiles.changed() : siteAssets.rescan())
884
+ // A file wins at its path (story 284), so a page it hides is worth saying once.
885
+ if (config.role !== 'api' && publicFiles.paths().length > 0)
886
+ void publicFiles
887
+ .hiding((path) => cache.byRoute(path))
888
+ .then((paths) => {
889
+ for (const path of paths)
890
+ renderLog.warning('The public file {path} hides the page at that address', { path })
891
+ })
892
+ .catch(() => {})
869
893
  const missingAssets = new Set<string>()
870
894
  setAssetResolver((path) => {
871
- const found = generatedPaths.get(path) ?? siteAssets.address(path)
895
+ const found = generatedPaths.get(path) ?? siteAssets.address(path) ?? publicFiles.address(path)
872
896
  if (found) return found
873
897
  if (config.development && !missingAssets.has(path)) {
874
898
  missingAssets.add(path)
@@ -1585,7 +1609,11 @@ export async function createServer(
1585
1609
  if (pathname === BUNDLE_SCRIPT_PATH) return siteScript(BUNDLE_SCRIPT)
1586
1610
 
1587
1611
  // Not on an `api` node, which serves no public site to describe.
1588
- if ((pathname === '/sitemap.xml' || pathname === '/robots.txt') && config.role !== 'api')
1612
+ if (
1613
+ (pathname === '/sitemap.xml' || pathname === '/robots.txt') &&
1614
+ config.role !== 'api' &&
1615
+ !publicFiles.has(pathname)
1616
+ )
1589
1617
  return pathname === '/sitemap.xml' ? seo.sitemap(request, url.host) : seo.robots(request)
1590
1618
 
1591
1619
  if (pathname.startsWith('/media/')) return serveMedia(request, pathname, url.searchParams)
@@ -1692,8 +1720,13 @@ export async function createServer(
1692
1720
  async function siteFiles(request: Request, run?: ChainRun): Promise<Response> {
1693
1721
  const url = new URL(request.url)
1694
1722
  const pathname = url.pathname
1695
- // A route wins at its path (story 211); an `api` node serves no site.
1723
+ // A public file wins at its path (story 284), then a route (story 211); an
1724
+ // `api` node serves no site.
1696
1725
  if (config.role !== 'api') {
1726
+ if (request.method === 'GET' || request.method === 'HEAD') {
1727
+ const file = await publicFiles.serve(request, pathname)
1728
+ if (file) return file
1729
+ }
1697
1730
  const routed = await siteRoutes.handle(request, url)
1698
1731
  if (routed) return routed
1699
1732
  }
@@ -3838,6 +3871,7 @@ export async function createServer(
3838
3871
  watcher?.close()
3839
3872
  viewWatcher?.close()
3840
3873
  siteAssets.close()
3874
+ publicFiles.close()
3841
3875
  typeWatch?.stop()
3842
3876
  live?.close()
3843
3877
  poller.stop()
package/src/settings.ts CHANGED
@@ -300,6 +300,13 @@ const DECLARED = [
300
300
  section: 'Back office and bundles',
301
301
  description: 'The scripts the Settings section edits, served at `/scripts/`.',
302
302
  },
303
+ {
304
+ env: 'CROMBOLO_PUBLIC_DIR',
305
+ kind: 'string',
306
+ default: 'public',
307
+ section: 'Back office and bundles',
308
+ description: "The site's own files, served at the root of the site at the same paths.",
309
+ },
303
310
  {
304
311
  env: 'CROMBOLO_APPLY_BUNDLE_CONTENT',
305
312
  kind: 'boolean',
@@ -16,18 +16,21 @@ export interface AssetRoot {
16
16
 
17
17
  export class SiteAssets {
18
18
  readonly #roots: readonly AssetRoot[]
19
+ readonly #watch: boolean
19
20
  readonly #hashes = new Map<string, string>()
20
21
  readonly #watchers: FSWatcher[] = []
21
22
 
22
- constructor(roots: readonly AssetRoot[]) {
23
+ constructor(roots: readonly AssetRoot[], options: { watch?: boolean } = {}) {
23
24
  this.#roots = roots
25
+ this.#watch = options.watch !== false
24
26
  }
25
27
 
26
28
  /** Hashes every file, and watches each folder for changes. */
27
29
  start(): void {
30
+ this.rescan()
31
+ if (!this.#watch) return
28
32
  for (const root of this.#roots) {
29
33
  if (!existsSync(root.dir)) continue
30
- for (const file of filesIn(root.dir)) this.#hash(root, file)
31
34
  try {
32
35
  const watcher = watch(root.dir, { recursive: true }, (_event, name) => {
33
36
  if (name) this.#hash(root, join(root.dir, name.toString()))
@@ -40,6 +43,18 @@ export class SiteAssets {
40
43
  }
41
44
  }
42
45
 
46
+ /** Every file hashed again, and one that has gone forgotten: for a change no watcher saw. */
47
+ rescan(): void {
48
+ this.#hashes.clear()
49
+ for (const root of this.#roots) {
50
+ try {
51
+ if (existsSync(root.dir)) for (const file of filesIn(root.dir)) this.#hash(root, file)
52
+ } catch {
53
+ // A file that went while the folder was read: the next change says so.
54
+ }
55
+ }
56
+ }
57
+
43
58
  /** The hashed address of a file the site has, or undefined. */
44
59
  address(path: string): string | undefined {
45
60
  const hash = this.#hashes.get(path)
@@ -52,9 +67,13 @@ export class SiteAssets {
52
67
 
53
68
  #hash(root: AssetRoot, file: string): void {
54
69
  const path = `${root.prefix}/${relative(root.dir, file).split(sep).join('/')}`
55
- if (!file.toLowerCase().endsWith(root.extension)) return
56
70
  try {
57
- if (!statSync(file).isFile()) return
71
+ // A folder moved in reports only its own name.
72
+ if (statSync(file).isDirectory()) {
73
+ for (const inside of filesIn(file)) this.#hash(root, inside)
74
+ return
75
+ }
76
+ if (!file.toLowerCase().endsWith(root.extension)) return
58
77
  this.#hashes.set(path, contentHash(readFileSync(file)))
59
78
  } catch {
60
79
  this.#hashes.delete(path)
package/src/site-file.ts CHANGED
@@ -35,6 +35,7 @@ import { type CromboloConfig, VERSION } from './config.ts'
35
35
  import { mediaStoreFor } from './media-files.ts'
36
36
  import { type StoredFile, streamOf } from './media-store.ts'
37
37
  import { readSiteData } from './site-data.ts'
38
+ import { publicSources } from './site-public.ts'
38
39
  import { siteSections } from './site-sections.ts'
39
40
  import { TarballWriter } from './tar.ts'
40
41
 
@@ -232,6 +233,7 @@ export async function exportSite(
232
233
  requires: requiredPackages(config),
233
234
  },
234
235
  }
236
+ const publicFiles = publicSources(config.publicDir)
235
237
  const seal =
236
238
  (people || siteData || options.sealContent) && options.passphrase
237
239
  ? newSeal(options.passphrase)
@@ -240,7 +242,13 @@ export async function exportSite(
240
242
  site,
241
243
  new Map([...stored].map(([key, file]) => [key, file.size])),
242
244
  sections,
243
- { people, siteData, seal, content: options.sealContent ? 'sealed' : 'open' },
245
+ {
246
+ people,
247
+ siteData,
248
+ seal,
249
+ content: options.sealContent ? 'sealed' : 'open',
250
+ public: publicFiles,
251
+ },
244
252
  )
245
253
 
246
254
  const name = options.package?.name ?? packageNameFor(`${config.siteName}-site`)
@@ -291,11 +299,16 @@ export async function exportSite(
291
299
  }
292
300
  hasher.update('\n')
293
301
  }
302
+ // Outside the bundle's hash: `public.json`, inside it, holds each file's own.
303
+ for (const file of publicFiles)
304
+ await writer.addStream(file.path, file.size, Bun.file(file.source).stream())
294
305
  const manifest = { ...planned.manifest, integrity: `sha256-${hasher.digest('hex')}` }
295
306
  await writer.add(MANIFEST_FILE, encoder.encode(writeManifest(manifest)))
296
307
  await writer.add(
297
308
  'package.json',
298
- encoder.encode(`${JSON.stringify(bundlePackageJson(info, paths), null, 2)}\n`),
309
+ encoder.encode(
310
+ `${JSON.stringify(bundlePackageJson(info, [...paths, ...publicFiles.map((file) => file.path)]), null, 2)}\n`,
311
+ ),
299
312
  )
300
313
  await writer.close()
301
314
  await rename(partial, options.out)
@@ -312,6 +325,7 @@ export async function exportSite(
312
325
  )
313
326
  if (section) counted[section] = (counted[section] ?? 0) + 1
314
327
  }
328
+ if (publicFiles.length > 0) counted.public = publicFiles.length
315
329
  return {
316
330
  out: options.out,
317
331
  bundleId: site.manifest.id,