@crombolo/server 0.30.3 → 0.33.0

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/server",
3
- "version": "0.30.3",
3
+ "version": "0.33.0",
4
4
  "description": "The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -30,17 +30,17 @@
30
30
  "access": "public"
31
31
  },
32
32
  "dependencies": {
33
- "@crombolo/api-delivery": "0.30.3",
34
- "@crombolo/api-management": "0.30.3",
35
- "@crombolo/auth": "0.30.3",
36
- "@crombolo/backoffice-host": "0.30.3",
37
- "@crombolo/content": "0.30.3",
38
- "@crombolo/contracts": "0.30.3",
39
- "@crombolo/core": "0.30.3",
40
- "@crombolo/data": "0.30.3",
41
- "@crombolo/render": "0.30.3",
42
- "@crombolo/schema": "0.30.3",
43
- "@crombolo/transfer": "0.30.3",
33
+ "@crombolo/api-delivery": "0.33.0",
34
+ "@crombolo/api-management": "0.33.0",
35
+ "@crombolo/auth": "0.33.0",
36
+ "@crombolo/backoffice-host": "0.33.0",
37
+ "@crombolo/content": "0.33.0",
38
+ "@crombolo/contracts": "0.33.0",
39
+ "@crombolo/core": "0.33.0",
40
+ "@crombolo/data": "0.33.0",
41
+ "@crombolo/render": "0.33.0",
42
+ "@crombolo/schema": "0.33.0",
43
+ "@crombolo/transfer": "0.33.0",
44
44
  "@logtape/logtape": "^2.3.8",
45
45
  "jose": "^6.2.12"
46
46
  }
@@ -8,7 +8,15 @@
8
8
  import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
9
9
  import { tmpdir } from 'node:os'
10
10
  import { join, resolve } from 'node:path'
11
- import { type BundleFile, bundleIdFor, writeBundle, writeBundlePackage } from '@crombolo/transfer'
11
+ import {
12
+ type BundleFile,
13
+ bundleIdFor,
14
+ codePatternsOf,
15
+ readCodeFiles,
16
+ selectCodeFiles,
17
+ writeBundle,
18
+ writeBundlePackage,
19
+ } from '@crombolo/transfer'
12
20
  import { createFileSystemPort } from './adapters/file-system.ts'
13
21
  import { createTemplateFileStore } from './adapters/template-files.ts'
14
22
  import { loadConfig, VERSION } from './config.ts'
@@ -22,6 +30,11 @@ export interface BundleBuildOptions {
22
30
  name?: string
23
31
  /** What a person calls it; default, the site's name. */
24
32
  label?: string
33
+ /**
34
+ * Globs naming the site's own code, in place of `crombolo.code` in its
35
+ * `package.json` (story 192). Neither: the bundle carries no code.
36
+ */
37
+ code?: readonly string[]
25
38
  }
26
39
 
27
40
  export interface BundleBuildResult {
@@ -30,6 +43,8 @@ export interface BundleBuildResult {
30
43
  seed?: SeedBuild
31
44
  files?: BundleFile[]
32
45
  name: string
46
+ /** The site's code the bundle carries, by path; absent when it carries none. */
47
+ code?: string[]
33
48
  }
34
49
 
35
50
  /** What a directory calls its site: `site.json`, then `package.json`, then its folder. */
@@ -60,6 +75,10 @@ export async function buildBundleFromDirectory(
60
75
  const name = options.name ?? identity.name
61
76
  if (!existsSync(join(dir, 'schema')))
62
77
  return { problems: [`${dir} has no schema/ directory, so it is not a site`], name }
78
+ const patterns = options.code ?? codePatternsOf(dir)
79
+ const code = patterns ? selectCodeFiles(dir, patterns) : undefined
80
+ if (code && code.problems.length > 0)
81
+ return { problems: code.problems.map((problem) => `its code: ${problem}`), name }
63
82
  const work = mkdtempSync(join(tmpdir(), 'crombolo-bundle-build-'))
64
83
  try {
65
84
  const config = loadConfig(
@@ -120,16 +139,22 @@ export async function buildBundleFromDirectory(
120
139
  createdBy: 'crombolo bundle build',
121
140
  },
122
141
  }
123
- const files = writeBundlePackage(writeBundle(set, seed.blobs, sections), {
124
- name,
125
- version: '1.0.0',
126
- id: bundleIdFor(name),
127
- label: config.siteName,
128
- private: true,
129
- // As `release:version` writes it into every committed bundle.
130
- peerRange: `>=${VERSION}`,
131
- })
132
- return { problems: [], seed, files, name }
142
+ const files = writeBundlePackage(
143
+ writeBundle(set, seed.blobs, [
144
+ ...sections,
145
+ ...(code ? readCodeFiles(dir, code.paths) : []),
146
+ ]),
147
+ {
148
+ name,
149
+ version: '1.0.0',
150
+ id: bundleIdFor(name),
151
+ label: config.siteName,
152
+ private: true,
153
+ // As `release:version` writes it into every committed bundle.
154
+ peerRange: `>=${VERSION}`,
155
+ },
156
+ )
157
+ return { problems: [], seed, files, name, ...(code ? { code: code.paths } : {}) }
133
158
  } finally {
134
159
  await db.close()
135
160
  }
@@ -0,0 +1,266 @@
1
+ /**
2
+ * A site's code from its bundle (story 192): checked against this CMS, and
3
+ * installed into a directory a host starts. The `@crombolo/*` packages are the
4
+ * host's to provide, so neither ever installs one: the site lists them as peers
5
+ * and the install omits peers. `docs/bundles.md`, "A site's bundle with code".
6
+ */
7
+ import {
8
+ cpSync,
9
+ existsSync,
10
+ mkdirSync,
11
+ mkdtempSync,
12
+ readdirSync,
13
+ readFileSync,
14
+ rmSync,
15
+ symlinkSync,
16
+ writeFileSync,
17
+ } from 'node:fs'
18
+ import { tmpdir } from 'node:os'
19
+ import { dirname, join, relative } from 'node:path'
20
+ import {
21
+ discoverBundles,
22
+ isSemverRange,
23
+ type PackageJson,
24
+ peerRangeProblem,
25
+ resolvePackageDir,
26
+ } from '@crombolo/backoffice-host'
27
+ import { loadBundleCode } from '@crombolo/transfer'
28
+ import { type ServerBundle, validateServerBundles } from './bundles.ts'
29
+ import { VERSION } from './config.ts'
30
+
31
+ const SCOPE = '@crombolo/'
32
+ const CORE_PACKAGE = '@crombolo/crombolo'
33
+
34
+ /** How long reading a site's config may take before it is taken to have hung. */
35
+ const CONFIG_TIMEOUT_MS = 60_000
36
+
37
+ export interface BundleCodeOptions {
38
+ /** The CMS version the code is checked against; this one by default. */
39
+ coreVersion?: string
40
+ }
41
+
42
+ export interface BundleCodeCheck {
43
+ /** Every reason the code cannot run here; empty when it can. */
44
+ problems: string[]
45
+ /** The bundle ids `crombolo.config.ts` wires. */
46
+ wired: string[]
47
+ /** How many files the bundle's code is. */
48
+ files: number
49
+ }
50
+
51
+ export interface BundleCodeInstall {
52
+ problems: string[]
53
+ dir: string
54
+ files: number
55
+ }
56
+
57
+ /** `bun install` exactly as the lockfile says: no lifecycle scripts, and no peers. */
58
+ async function frozenInstall(dir: string): Promise<string | undefined> {
59
+ const run = Bun.spawn(
60
+ [process.execPath, 'install', '--frozen-lockfile', '--ignore-scripts', '--omit', 'peer'],
61
+ { cwd: dir, stdout: 'pipe', stderr: 'pipe' },
62
+ )
63
+ const [out, err, code] = await Promise.all([
64
+ new Response(run.stdout).text(),
65
+ new Response(run.stderr).text(),
66
+ run.exited,
67
+ ])
68
+ if (code === 0) return undefined
69
+ const tail = `${err}\n${out}`.trim().split('\n').slice(-5).join(' / ')
70
+ return `the install from its bun.lock failed: ${tail}`
71
+ }
72
+
73
+ /** Every `@crombolo/*` package an install put anywhere under `node_modules`. */
74
+ function cromboloCopies(root: string): string[] {
75
+ const found: string[] = []
76
+ const walk = (modules: string): void => {
77
+ if (!existsSync(modules)) return
78
+ for (const entry of readdirSync(modules, { withFileTypes: true })) {
79
+ if (!entry.isDirectory() || entry.name === '.bin') continue
80
+ const at = join(modules, entry.name)
81
+ if (entry.name === SCOPE.slice(0, -1)) {
82
+ for (const pkg of readdirSync(at)) found.push(relative(root, join(at, pkg)))
83
+ continue
84
+ }
85
+ const packages = entry.name.startsWith('@')
86
+ ? readdirSync(at).map((name) => join(at, name))
87
+ : [at]
88
+ for (const pkg of packages) walk(join(pkg, 'node_modules'))
89
+ }
90
+ }
91
+ walk(join(root, 'node_modules'))
92
+ return found.sort()
93
+ }
94
+
95
+ /** What the site's `package.json` declares wrongly for a host that provides the CMS. */
96
+ function declarationProblems(json: PackageJson, coreVersion: string): string[] {
97
+ const problems: string[] = []
98
+ for (const name of Object.keys(json.dependencies ?? {}).sort())
99
+ if (name.startsWith(SCOPE))
100
+ problems.push(
101
+ `package.json lists ${name} under dependencies; the CMS that runs the site provides it, so it belongs under peerDependencies`,
102
+ )
103
+ const range = json.peerDependencies?.[CORE_PACKAGE]
104
+ if (range && isSemverRange(range) && !Bun.semver.satisfies(coreVersion, range))
105
+ problems.push(
106
+ `the site is written for ${CORE_PACKAGE} ${range}, and this CMS is ${coreVersion}`,
107
+ )
108
+ return problems
109
+ }
110
+
111
+ /**
112
+ * The `@crombolo/*` packages the site peers on, linked from this CMS, as a host
113
+ * provides them; a name this CMS cannot provide is a problem.
114
+ */
115
+ function linkCms(json: PackageJson, dir: string): string[] {
116
+ const problems: string[] = []
117
+ for (const name of Object.keys(json.peerDependencies ?? {}).sort()) {
118
+ if (!name.startsWith(SCOPE)) continue
119
+ const provided = resolvePackageDir(import.meta.dir, name)
120
+ if (!provided) {
121
+ problems.push(`the site needs ${name}, and this CMS does not provide it`)
122
+ continue
123
+ }
124
+ const target = join(dir, 'node_modules', name)
125
+ mkdirSync(dirname(target), { recursive: true })
126
+ symlinkSync(provided, target, 'dir')
127
+ }
128
+ return problems
129
+ }
130
+
131
+ const MARKER = '@@crombolo-bundles@@'
132
+
133
+ /** Run in a process of its own: the wired bundles, as data, after a marker line. */
134
+ const READ_CONFIG = `const config = (await import(process.argv[2])).default ?? {}
135
+ const bundles = (config.bundles ?? []).map((b) => ({
136
+ id: b.id,
137
+ section: b.section,
138
+ capabilities: b.capabilities ?? [],
139
+ routes: (b.routes ?? []).map((r) => ({ method: r.method, path: r.path })),
140
+ ...(b.tables ? { tables: b.tables } : {}),
141
+ }))
142
+ process.stdout.write('\\n${MARKER}' + JSON.stringify(bundles) + '\\n')
143
+ `
144
+
145
+ /**
146
+ * The bundles `crombolo.config.ts` wires, read in a `bun` process given none
147
+ * of the caller's environment, so a config that reads a secret finds none and
148
+ * one that hangs is stopped.
149
+ */
150
+ async function wiredBundles(dir: string): Promise<{ bundles: ServerBundle[]; problem?: string }> {
151
+ const config = join(dir, 'crombolo.config.ts')
152
+ if (!existsSync(config)) return { bundles: [] }
153
+ const scratch = mkdtempSync(join(tmpdir(), 'crombolo-read-config-'))
154
+ try {
155
+ const script = join(scratch, 'read-config.ts')
156
+ writeFileSync(script, READ_CONFIG)
157
+ const run = Bun.spawn([process.execPath, script, config], {
158
+ cwd: dir,
159
+ env: {},
160
+ stdout: 'pipe',
161
+ stderr: 'pipe',
162
+ })
163
+ const timer = setTimeout(() => run.kill(), CONFIG_TIMEOUT_MS)
164
+ const [out, err, code] = await Promise.all([
165
+ new Response(run.stdout).text(),
166
+ new Response(run.stderr).text(),
167
+ run.exited,
168
+ ])
169
+ clearTimeout(timer)
170
+ const marker = out.split('\n').find((line) => line.startsWith(MARKER))
171
+ if (code !== 0 || !marker) {
172
+ const tail = err.trim().split('\n').slice(-5).join(' / ')
173
+ return {
174
+ bundles: [],
175
+ problem: `crombolo.config.ts could not be read: ${tail || `exit ${code}`}`,
176
+ }
177
+ }
178
+ return { bundles: JSON.parse(marker.slice(MARKER.length)) as ServerBundle[] }
179
+ } finally {
180
+ rmSync(scratch, { recursive: true, force: true })
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Every reason a bundle's code cannot run on this CMS: its hash, a frozen
186
+ * install, `@crombolo/*` installed beside it, and the server bundles its config
187
+ * wires, by the rules the boot applies. All of them, not the first.
188
+ */
189
+ export async function checkBundleCode(
190
+ packageDir: string,
191
+ options: BundleCodeOptions = {},
192
+ ): Promise<BundleCodeCheck> {
193
+ const coreVersion = options.coreVersion ?? VERSION
194
+ const loaded = loadBundleCode(packageDir)
195
+ if (!loaded.dir) return { problems: loaded.problems, wired: [], files: 0 }
196
+ const result: BundleCodeCheck = {
197
+ problems: [...loaded.problems],
198
+ wired: [],
199
+ files: loaded.paths.length,
200
+ }
201
+ const json = JSON.parse(readFileSync(join(loaded.dir, 'package.json'), 'utf8')) as PackageJson
202
+ result.problems.push(...declarationProblems(json, coreVersion))
203
+
204
+ const work = mkdtempSync(join(tmpdir(), 'crombolo-bundle-code-'))
205
+ try {
206
+ cpSync(loaded.dir, work, { recursive: true })
207
+ const failed = await frozenInstall(work)
208
+ if (failed) {
209
+ result.problems.push(failed)
210
+ return result
211
+ }
212
+ for (const copy of cromboloCopies(work))
213
+ result.problems.push(
214
+ `${copy} is installed with the code; the CMS provides @crombolo packages, so nothing the site installs may depend on one directly`,
215
+ )
216
+ result.problems.push(...linkCms(json, work))
217
+
218
+ const read = await wiredBundles(work)
219
+ if (read.problem) result.problems.push(read.problem)
220
+ result.wired = read.bundles.map((bundle) => bundle.id)
221
+
222
+ const discovered = discoverBundles(work)
223
+ for (const entry of discovered.problems)
224
+ for (const problem of entry.problems) result.problems.push(`${entry.packageName}: ${problem}`)
225
+ const wired = new Set(result.wired)
226
+ for (const bundle of discovered.bundles) {
227
+ if (wired.has(bundle.id)) continue
228
+ const peer = peerRangeProblem(bundle, coreVersion)
229
+ if (peer) result.problems.push(peer)
230
+ }
231
+ result.problems.push(...validateServerBundles(read.bundles, discovered.bundles, coreVersion))
232
+ return result
233
+ } finally {
234
+ rmSync(work, { recursive: true, force: true })
235
+ }
236
+ }
237
+
238
+ /**
239
+ * The bundle's code installed into `dir`, ready for a host to start once it
240
+ * provides the `@crombolo/*` packages. Refuses a directory that already holds
241
+ * files, rather than mixing two sites' code.
242
+ */
243
+ export async function installBundleCode(
244
+ packageDir: string,
245
+ dir: string,
246
+ ): Promise<BundleCodeInstall> {
247
+ const loaded = loadBundleCode(packageDir)
248
+ if (!loaded.dir || loaded.problems.length > 0) return { problems: loaded.problems, dir, files: 0 }
249
+ if (existsSync(dir) && readdirSync(dir).length > 0)
250
+ return {
251
+ problems: [`${dir} already holds files; install into an empty directory`],
252
+ dir,
253
+ files: 0,
254
+ }
255
+ mkdirSync(dir, { recursive: true })
256
+ cpSync(loaded.dir, dir, { recursive: true })
257
+ const problems: string[] = []
258
+ const failed = await frozenInstall(dir)
259
+ if (failed) problems.push(failed)
260
+ else
261
+ for (const copy of cromboloCopies(dir))
262
+ problems.push(
263
+ `${copy} was installed with the code; the CMS provides @crombolo packages, so nothing the site installs may depend on one directly`,
264
+ )
265
+ return { problems, dir, files: loaded.paths.length }
266
+ }
@@ -120,6 +120,8 @@ export interface BundleSummary {
120
120
  blobBytes: number
121
121
  /** The package the payload came in. */
122
122
  package: { name: string; version: string }
123
+ /** The site's code the package carries, which an import leaves alone (story 192). */
124
+ carriesCode: boolean
123
125
  }
124
126
 
125
127
  /** A bundle found and read: its package, and the payload inside it. */
@@ -257,6 +259,7 @@ function summarise(bundle: ResolvedBundle): BundleSummary {
257
259
  blobsCarried: carried.length,
258
260
  blobBytes: carried.reduce((total, blob) => total + (blob.size ?? 0), 0),
259
261
  package: { name: bundle.package.packageName, version: bundle.package.version },
262
+ carriesCode: (set.manifest.carries?.code?.length ?? 0) > 0,
260
263
  }
261
264
  }
262
265
 
package/src/config.ts CHANGED
@@ -829,7 +829,7 @@ export function describeDatabase(
829
829
  }
830
830
  }
831
831
 
832
- export const VERSION = '0.30.3'
832
+ export const VERSION = '0.33.0'
833
833
 
834
834
  /** A whole number of seconds from the environment; undefined when unset or not one. */
835
835
  function numberSetting(name: Parameters<typeof setting>[0]): number | undefined {
package/src/index.ts CHANGED
@@ -19,6 +19,7 @@ export * from './atomic-write.ts'
19
19
  export * from './backup.ts'
20
20
  export * from './boot-failure.ts'
21
21
  export * from './bundle-build.ts'
22
+ export * from './bundle-code.ts'
22
23
  export * from './bundle-install.ts'
23
24
  export * from './bundle-reload.ts'
24
25
  export * from './bundle-sections.ts'
@@ -200,8 +200,9 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
200
200
  try {
201
201
  const json = (await Bun.file(join(options.siteDir, 'package.json')).json()) as {
202
202
  dependencies?: Record<string, string>
203
+ peerDependencies?: Record<string, string>
203
204
  }
204
- return json.dependencies?.[name]
205
+ return json.dependencies?.[name] ?? json.peerDependencies?.[name]
205
206
  } catch {
206
207
  return undefined
207
208
  }
@@ -228,12 +229,12 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
228
229
  if (!version || validateBundlePackage(version).length > 0) return undefined
229
230
  const field = version.crombolo as {
230
231
  extensions?: unknown[]
231
- content?: string
232
+ content?: boolean
232
233
  server?: string
233
234
  }
234
235
  return {
235
236
  extensions: Array.isArray(field.extensions) && field.extensions.length > 0,
236
- content: field.content !== undefined,
237
+ content: field.content === true,
237
238
  server: field.server !== undefined,
238
239
  }
239
240
  } catch {
package/src/site-file.ts CHANGED
@@ -23,7 +23,6 @@ import {
23
23
  exportPeople,
24
24
  MANIFEST_FILE,
25
25
  newSeal,
26
- PAYLOAD_DIR,
27
26
  packageNameFor,
28
27
  planStreamedBundle,
29
28
  sanitise,
@@ -252,14 +251,14 @@ export async function exportSite(
252
251
  if (file) {
253
252
  const body = file.bytes ?? encoder.encode(file.text ?? '')
254
253
  hasher.update(body)
255
- await writer.add(`${PAYLOAD_DIR}/${path}`, body)
254
+ await writer.add(path, body)
256
255
  } else {
257
256
  const media = stored.get(blobs.get(path) as string) as StoredFile
258
257
  if (planned.sealing && seal) {
259
258
  const sealed = sealBytes(seal.key, path, await media.bytes())
260
259
  hasher.update(sealed)
261
260
  hasher.update('\n')
262
- await writer.add(`${PAYLOAD_DIR}/${path}`, sealed)
261
+ await writer.add(path, sealed)
263
262
  bytes += media.size
264
263
  continue
265
264
  }
@@ -269,16 +268,16 @@ export async function exportSite(
269
268
  yield chunk
270
269
  }
271
270
  }
272
- await writer.addStream(`${PAYLOAD_DIR}/${path}`, media.size, hashed())
271
+ await writer.addStream(path, media.size, hashed())
273
272
  bytes += media.size
274
273
  }
275
274
  hasher.update('\n')
276
275
  }
277
276
  const manifest = { ...planned.manifest, integrity: `sha256-${hasher.digest('hex')}` }
278
- await writer.add(`${PAYLOAD_DIR}/${MANIFEST_FILE}`, encoder.encode(writeManifest(manifest)))
277
+ await writer.add(MANIFEST_FILE, encoder.encode(writeManifest(manifest)))
279
278
  await writer.add(
280
279
  'package.json',
281
- encoder.encode(`${JSON.stringify(bundlePackageJson(info), null, 2)}\n`),
280
+ encoder.encode(`${JSON.stringify(bundlePackageJson(info, paths), null, 2)}\n`),
282
281
  )
283
282
  await writer.close()
284
283
  await rename(partial, options.out)