@crombolo/server 0.58.1 → 0.60.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.58.1",
3
+ "version": "0.60.0",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -31,19 +31,19 @@
31
31
  "access": "public"
32
32
  },
33
33
  "dependencies": {
34
- "@crombolo/api-delivery": "0.58.1",
35
- "@crombolo/api-management": "0.58.1",
36
- "@crombolo/auth": "0.58.1",
37
- "@crombolo/backoffice-host": "0.58.1",
38
- "@crombolo/common": "0.58.1",
39
- "@crombolo/content": "0.58.1",
40
- "@crombolo/contracts": "0.58.1",
41
- "@crombolo/core": "0.58.1",
42
- "@crombolo/data": "0.58.1",
43
- "@crombolo/extension": "0.58.1",
44
- "@crombolo/render": "0.58.1",
45
- "@crombolo/schema": "0.58.1",
46
- "@crombolo/transfer": "0.58.1",
34
+ "@crombolo/api-delivery": "0.60.0",
35
+ "@crombolo/api-management": "0.60.0",
36
+ "@crombolo/auth": "0.60.0",
37
+ "@crombolo/backoffice-host": "0.60.0",
38
+ "@crombolo/common": "0.60.0",
39
+ "@crombolo/content": "0.60.0",
40
+ "@crombolo/contracts": "0.60.0",
41
+ "@crombolo/core": "0.60.0",
42
+ "@crombolo/data": "0.60.0",
43
+ "@crombolo/extension": "0.60.0",
44
+ "@crombolo/render": "0.60.0",
45
+ "@crombolo/schema": "0.60.0",
46
+ "@crombolo/transfer": "0.60.0",
47
47
  "@logtape/logtape": "^2.3.8",
48
48
  "@opentelemetry/api": "1.10.0",
49
49
  "@opentelemetry/context-async-hooks": "3.0.0",
@@ -35,6 +35,10 @@ const DECLARATION_PERMISSIONS: ReadonlySet<string> = new Set([
35
35
  'actAs',
36
36
  'templates',
37
37
  'member.delegate',
38
+ // What the screens need, not the server half (story 320).
39
+ 'backoffice.code',
40
+ // Checked against the tables it declares, not a capability (story 321).
41
+ 'data.tables',
38
42
  ])
39
43
 
40
44
  /** The permission each capability method needs. */
@@ -95,6 +99,8 @@ export function permissionProblems(
95
99
  declared: readonly string[],
96
100
  /** It has back-office screens, which `http.outbound` lets reach its origins too (story 313). */
97
101
  screens = false,
102
+ /** It handles events, whose `fetch` `http.outbound` is for too (story 301). */
103
+ options: { events?: boolean } = {},
98
104
  ): string[] {
99
105
  const problems: string[] = []
100
106
  const has = new Set(declared)
@@ -113,7 +119,7 @@ export function permissionProblems(
113
119
  }
114
120
  for (const permission of declared) {
115
121
  if (DECLARATION_PERMISSIONS.has(permission)) continue
116
- if (permission === 'http.outbound' && screens) continue
122
+ if (permission === 'http.outbound' && (screens || options.events)) continue
117
123
  const used = capabilities.some((c) => CAPABILITY_PERMISSIONS[c]?.includes(permission as never))
118
124
  if (!used)
119
125
  problems.push(
package/src/bundles.ts CHANGED
@@ -50,7 +50,7 @@ import { hasCultureAccess, hasSection, type Principal } from '@crombolo/api-mana
50
50
  import {
51
51
  BUNDLE_ID,
52
52
  type BundlePackage,
53
- OLDEST_BUNDLE_SCHEMA_VERSION,
53
+ OLDEST_WIRED_SCHEMA_VERSION,
54
54
  peerRangeProblem,
55
55
  schemaProblem,
56
56
  } from '@crombolo/backoffice-host/registry'
@@ -457,7 +457,9 @@ export function validateServerBundles(
457
457
  if (pkg?.carries.server && pkg.field.permissions !== undefined) {
458
458
  const declared = declaredPermissions(pkg)
459
459
  problems.push(
460
- ...permissionProblems(label, bundle.capabilities, declared, pkg.carries.extensions),
460
+ ...permissionProblems(label, bundle.capabilities, declared, pkg.carries.extensions, {
461
+ events: Object.keys(bundle.events ?? {}).length > 0,
462
+ }),
461
463
  )
462
464
  // Schema 4 asks for what it does as well as what it calls (story 308).
463
465
  if (!isSchema3(pkg)) {
@@ -476,12 +478,22 @@ export function validateServerBundles(
476
478
  problems.push(
477
479
  `Bundle "${label}" answers routes on the site, and so needs "routes.public" in "crombolo.permissions".`,
478
480
  )
481
+ if (bundle.tables && !declared.includes('data.tables'))
482
+ problems.push(
483
+ `Bundle "${label}" declares tables, and so needs "data.tables" in "crombolo.permissions".`,
484
+ )
485
+ if (!bundle.tables && declared.includes('data.tables'))
486
+ problems.push(
487
+ `Bundle "${label}" declares "data.tables" but no tables; take it out of "crombolo.permissions".`,
488
+ )
479
489
  }
480
490
  }
481
491
  }
482
492
  const owner = packages.find((pkg) => pkg.id === bundle.id)
483
- if (owner?.carries.server && (owner.field.schemaVersion ?? 1) < OLDEST_BUNDLE_SCHEMA_VERSION)
484
- problems.push(`Bundle "${label}": ${schemaProblem(owner.field.schemaVersion ?? 1)}.`)
493
+ if (owner?.carries.server && (owner.field.schemaVersion ?? 1) < OLDEST_WIRED_SCHEMA_VERSION)
494
+ problems.push(
495
+ `Bundle "${label}": ${schemaProblem(owner.field.schemaVersion ?? 1, { wired: true })}.`,
496
+ )
485
497
  const routes = new Set<string>()
486
498
  for (const route of bundle.routes ?? []) {
487
499
  if (!route || typeof route !== 'object' || !route.handlers || !route.options) {
package/src/config.ts CHANGED
@@ -1144,7 +1144,7 @@ export function describeDatabase(
1144
1144
  }
1145
1145
  }
1146
1146
 
1147
- export const VERSION = '0.58.1'
1147
+ export const VERSION = '0.60.0'
1148
1148
 
1149
1149
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1150
1150
  /** A positive number from a setting, else the default. */
package/src/core.ts CHANGED
@@ -5,7 +5,13 @@
5
5
  * "Running a cluster".
6
6
  */
7
7
  import type { ServerEvent } from '@crombolo/api-management/domain'
8
- import { createBackOfficePaths, createExtensionRegistry } from '@crombolo/backoffice-host/registry'
8
+ import {
9
+ BACKOFFICE_CODE,
10
+ BACKOFFICE_CODE_WARNING,
11
+ BUNDLE_PERMISSIONS,
12
+ createBackOfficePaths,
13
+ createExtensionRegistry,
14
+ } from '@crombolo/backoffice-host/registry'
9
15
  import { mediaJobHandlers } from '@crombolo/content'
10
16
  import { ObjectTypes } from '@crombolo/core'
11
17
  import {
@@ -284,6 +290,16 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
284
290
  // import wires; anything else waits for a grant recorded here.
285
291
  const byCode = wiredByImport.has(pkg.id) || entryCovers(pkg, entry)
286
292
  if (!byCode) continue
293
+ // The one grant that is not confined, said each boot (story 320).
294
+ if (declaredPermissions(pkg).includes(BACKOFFICE_CODE))
295
+ log.warning(
296
+ "{package} is granted back-office code by the site's code: {permission}. {warning}",
297
+ {
298
+ package: pkg.packageName,
299
+ permission: BUNDLE_PERMISSIONS[BACKOFFICE_CODE],
300
+ warning: BACKOFFICE_CODE_WARNING,
301
+ },
302
+ )
287
303
  const bundle = { id: pkg.id }
288
304
  // Recorded where the database is written, and audited when it changes.
289
305
  if (
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * A Bundle Editor definition built as an extension for other sites (story 312):
3
- * the templates and partial views it picks are its code, under `src/components/`
3
+ * the templates and partial views it picks are its code, under `src/server/components/`
4
4
  * with a factory that declares them, and render in its own process where it is
5
5
  * installed. Its schema and pages name them by its id, `<id>/<alias>`. The rest
6
6
  * is its payload, as data. docs/bundles.md, "The Bundle Editor".
@@ -87,14 +87,14 @@ export function createdExtension(
87
87
  payload,
88
88
  set: renamedSet,
89
89
  code: {
90
- entry: 'src/index.ts',
90
+ entry: 'src/server/index.ts',
91
91
  server: CREATED_EXTENSION_FACTORY,
92
92
  permissions: {
93
93
  templates: 'Renders the templates and partial views it brings in your pages',
94
94
  },
95
95
  files: [
96
- { path: 'src/index.ts', text: entry },
97
- ...components.map((file) => ({ ...file, path: `src/${file.path}` })),
96
+ { path: 'src/server/index.ts', text: entry },
97
+ ...components.map((file) => ({ ...file, path: `src/server/${file.path}` })),
98
98
  ],
99
99
  },
100
100
  }
@@ -0,0 +1,162 @@
1
+ /**
2
+ * An extension's back-office code, built (story 320). Each module its manifest
3
+ * names under `src/backoffice/` is built for the browser, TypeScript and the npm
4
+ * packages it imports included, into `.crombolo/extensions/<id>/backoffice/`,
5
+ * and that build is all that is served of the package. The back office's own
6
+ * modules stay imports, for its import map to resolve. Built when first asked
7
+ * for, and again when its files change. docs/extensions.md.
8
+ */
9
+ import {
10
+ existsSync,
11
+ mkdirSync,
12
+ readdirSync,
13
+ realpathSync,
14
+ renameSync,
15
+ rmSync,
16
+ statSync,
17
+ } from 'node:fs'
18
+ import { join, relative, sep } from 'node:path'
19
+ import {
20
+ BACKOFFICE_DIR,
21
+ type BundlePackage,
22
+ backOfficeModules,
23
+ type InstalledExtension,
24
+ SERVER_DIR,
25
+ } from '@crombolo/backoffice-host/registry'
26
+ import type { BundleLog } from './bundles.ts'
27
+
28
+ const SOURCE = /\.(m?[jt]s|[jt]sx)$/
29
+
30
+ /** Builds a package's back-office modules into `outDir`, or throws saying why. */
31
+ export async function buildBackOffice(pkg: BundlePackage, outDir: string): Promise<void> {
32
+ const root = join(pkg.directory, BACKOFFICE_DIR)
33
+ // As the build sees it: a workspace link resolves to its real place.
34
+ const server = `${join(realpathSync(pkg.directory), SERVER_DIR)}${sep}`
35
+ const entrypoints = backOfficeModules(pkg.field).map((module) =>
36
+ join(pkg.directory, module.replace(/^\.\//, '')),
37
+ )
38
+ const next = `${outDir}.next`
39
+ rmSync(next, { recursive: true, force: true })
40
+ const result = await Bun.build({
41
+ entrypoints,
42
+ root,
43
+ outdir: next,
44
+ target: 'browser',
45
+ format: 'esm',
46
+ splitting: true,
47
+ naming: { entry: '[dir]/[name].[ext]', chunk: 'chunks/[name]-[hash].[ext]' },
48
+ external: ['@umbraco-cms/*'],
49
+ throw: false,
50
+ plugins: [
51
+ {
52
+ name: 'crombolo-backoffice',
53
+ setup(build) {
54
+ build.onLoad({ filter: SOURCE }, async (args) => {
55
+ // Each half is kept from the other's folder: the server's code is never in the browser.
56
+ if (args.path.startsWith(server))
57
+ throw new Error(
58
+ `${relative(pkg.directory, args.path)} is the server half's, which back-office code never imports.`,
59
+ )
60
+ const ext = args.path.match(SOURCE)?.[1] ?? 'js'
61
+ const loader = ext.endsWith('ts')
62
+ ? 'ts'
63
+ : ext === 'tsx'
64
+ ? 'tsx'
65
+ : ext === 'jsx'
66
+ ? 'jsx'
67
+ : 'js'
68
+ return { contents: await Bun.file(args.path).text(), loader }
69
+ })
70
+ },
71
+ },
72
+ ],
73
+ })
74
+ if (!result.success) {
75
+ rmSync(next, { recursive: true, force: true })
76
+ throw new Error(
77
+ `Its back-office code could not be built: ${result.logs.map((log) => log.message).join('; ')}`,
78
+ )
79
+ }
80
+ rmSync(outDir, { recursive: true, force: true })
81
+ renameSync(next, outDir)
82
+ }
83
+
84
+ /** When a package's back-office code last changed: its version, and its files' times. */
85
+ function stamp(pkg: BundlePackage): string {
86
+ let latest = 0
87
+ const walk = (dir: string) => {
88
+ for (const name of readdirSync(dir)) {
89
+ const path = join(dir, name)
90
+ const stat = statSync(path)
91
+ if (stat.isDirectory()) walk(path)
92
+ else latest = Math.max(latest, stat.mtimeMs)
93
+ }
94
+ }
95
+ const root = join(pkg.directory, BACKOFFICE_DIR)
96
+ if (existsSync(root)) walk(root)
97
+ return `${pkg.version}:${latest}`
98
+ }
99
+
100
+ export interface BackOfficeBuilds {
101
+ /** The extensions given, each with its build to serve; one whose code cannot be built is left out. */
102
+ ready(extensions: readonly InstalledExtension[]): Promise<InstalledExtension[]>
103
+ /** The extensions whose back-office code could not be built, and why. */
104
+ failed(): Array<{ id: string; reason: string }>
105
+ }
106
+
107
+ export function createBackOfficeBuilds(
108
+ siteDir: string,
109
+ log: (id: string) => BundleLog,
110
+ ): BackOfficeBuilds {
111
+ const built = new Map<string, { stamp: string; dir: string }>()
112
+ const failures = new Map<string, { stamp: string; reason: string }>()
113
+ const building = new Map<string, Promise<void>>()
114
+
115
+ const ensure = async (pkg: BundlePackage): Promise<string | undefined> => {
116
+ const now = stamp(pkg)
117
+ const done = built.get(pkg.id)
118
+ if (done?.stamp === now) return done.dir
119
+ if (failures.get(pkg.id)?.stamp === now) return undefined
120
+ const key = `${pkg.id}@${now}`
121
+ let pending = building.get(key)
122
+ if (!pending) {
123
+ const dir = join(siteDir, '.crombolo', 'extensions', pkg.id, 'backoffice')
124
+ mkdirSync(join(dir, '..'), { recursive: true })
125
+ pending = buildBackOffice(pkg, dir).then(
126
+ () => {
127
+ built.set(pkg.id, { stamp: now, dir })
128
+ failures.delete(pkg.id)
129
+ },
130
+ (error: unknown) => {
131
+ const reason = error instanceof Error ? error.message : String(error)
132
+ failures.set(pkg.id, { stamp: now, reason })
133
+ log(pkg.id).error(
134
+ '{package} is left out of the back office, as its screens could not be built: {reason}',
135
+ { package: pkg.packageName, reason },
136
+ )
137
+ },
138
+ )
139
+ building.set(key, pending)
140
+ void pending.finally(() => building.delete(key))
141
+ }
142
+ await pending
143
+ return built.get(pkg.id)?.stamp === now ? built.get(pkg.id)?.dir : undefined
144
+ }
145
+
146
+ return {
147
+ async ready(extensions) {
148
+ const out: InstalledExtension[] = []
149
+ for (const extension of extensions) {
150
+ // Entries that name no module, a label and an icon, need nothing built.
151
+ if (backOfficeModules(extension.bundle.field).length === 0) {
152
+ out.push(extension)
153
+ continue
154
+ }
155
+ const dir = await ensure(extension.bundle)
156
+ if (dir) out.push({ ...extension, servedDir: dir })
157
+ }
158
+ return out
159
+ },
160
+ failed: () => [...failures].map(([id, failure]) => ({ id, reason: failure.reason })),
161
+ }
162
+ }
@@ -11,9 +11,9 @@
11
11
  * connection that reaches only them. docs/extensions.md.
12
12
  */
13
13
  import { AsyncResource } from 'node:async_hooks'
14
- import { mkdirSync } from 'node:fs'
15
- import { dirname, extname, join } from 'node:path'
16
- import type { BundlePackage } from '@crombolo/backoffice-host/registry'
14
+ import { mkdirSync, realpathSync } from 'node:fs'
15
+ import { dirname, extname, join, sep } from 'node:path'
16
+ import { BACKOFFICE_DIR, type BundlePackage, SERVER_DIR } from '@crombolo/backoffice-host/registry'
17
17
  import {
18
18
  CHUNK_BYTES,
19
19
  decode,
@@ -67,6 +67,8 @@ export async function buildExtension(
67
67
  outDir: string,
68
68
  ): Promise<string> {
69
69
  const entryFile = Bun.resolveSync(pkg.packageName, siteDir)
70
+ // As the build sees it: a workspace link resolves to its real place.
71
+ const backOffice = `${join(realpathSync(pkg.directory), BACKOFFICE_DIR)}${sep}`
70
72
  mkdirSync(outDir, { recursive: true })
71
73
  const wrapper = join(outDir, 'entry.ts')
72
74
  const runner = Bun.resolveSync('@crombolo/extension/runner', import.meta.dir)
@@ -103,6 +105,10 @@ export async function buildExtension(
103
105
  )
104
106
  })
105
107
  build.onLoad({ filter: SOURCE }, async (args) => {
108
+ if (args.path.startsWith(backOffice))
109
+ throw new Error(
110
+ `${args.path} is the back-office code's, which the server half never imports.`,
111
+ )
106
112
  const contents = await Bun.file(args.path).text()
107
113
  if (MACRO.test(contents))
108
114
  throw new Error(`${args.path} imports a Bun macro, which would run in the CMS.`)
@@ -126,6 +132,15 @@ export async function buildExtension(
126
132
  return join(outDir, 'server.js')
127
133
  }
128
134
 
135
+ /** What its process may read: its own server half and its build, never its back-office code (story 320). */
136
+ export function processReads(
137
+ pkg: Pick<BundlePackage, 'directory'>,
138
+ build: string,
139
+ extra: readonly string[] = [],
140
+ ): string[] {
141
+ return [join(pkg.directory, SERVER_DIR), build, ...extra]
142
+ }
143
+
129
144
  /** `--allow-net`'s hosts for a set of origins: host, and port where one is named. */
130
145
  export function netHosts(origins: readonly string[]): string[] {
131
146
  return [
@@ -288,7 +303,7 @@ export class ExtensionProcess {
288
303
  denoBinary(),
289
304
  ...denoArguments({
290
305
  serverFile: this.#serverFile,
291
- reads: [pkg.directory, build, ...(this.#options.reads ?? [])],
306
+ reads: processReads(pkg, build, this.#options.reads),
292
307
  dataDir: data,
293
308
  origins: this.#options.origins,
294
309
  memoryMb: this.#options.memoryMb ?? 256,
package/src/index.ts CHANGED
@@ -66,7 +66,7 @@ export {
66
66
  extensionEntryProblems,
67
67
  settingsOf,
68
68
  } from './extension-discovery.ts'
69
- export { denoArguments, netHosts } from './extension-process.ts'
69
+ export { denoArguments, netHosts, processReads } from './extension-process.ts'
70
70
  export { extensionSqlProblem } from './extension-sql.ts'
71
71
  export * from './extensions-notice.ts'
72
72
  export * from './external-sign-in.ts'
@@ -91,6 +91,8 @@ export interface InstalledListing {
91
91
  contentApplied: string | null
92
92
  /** What the package says it is, from its `package.json`; empty when it says nothing. */
93
93
  description: string
94
+ /** Who made it, as its `author` says; null when it does not say (story 320). */
95
+ publisher: string | null
94
96
  /** The crombolo releases it is written for. */
95
97
  peerRange: string
96
98
  /** What its server half may do with the site, each with what it allows (story 222). */
@@ -169,7 +171,14 @@ export interface InstallOutcome {
169
171
  */
170
172
  needsGrant?: boolean
171
173
  /** With `needsGrant`: what it asks for, each with its sentence, its reason and its origins. */
172
- permissions?: { permission: string; allows: string; reason: string | null; origins?: string[] }[]
174
+ permissions?: {
175
+ permission: string
176
+ allows: string
177
+ reason: string | null
178
+ origins?: string[]
179
+ /** What the install says before it is granted: only back-office code has one (story 320). */
180
+ warning?: string
181
+ }[]
173
182
  /** With `needsGrant`: it asks to act for a user, so the grant names whom (story 308). */
174
183
  asksActAs?: boolean
175
184
  /**
@@ -396,6 +405,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
396
405
  dist?: Dist
397
406
  })
398
407
  | 'not-a-bundle'
408
+ | { refused: string[] }
399
409
  | 'site-package'
400
410
  | 'schema-3'
401
411
  | 'unreachable'
@@ -424,7 +434,10 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
424
434
  // A site package is never installed, whatever a registry offers (story 306).
425
435
  if ((version?.crombolo as { bundleType?: unknown } | undefined)?.bundleType === 'site')
426
436
  return 'site-package'
427
- if (!resolved || !version || validateBundlePackage(version).length > 0) return 'not-a-bundle'
437
+ if (!resolved || !version) return 'not-a-bundle'
438
+ // Why it is not one, so its author knows what to change: a layout before 0.59 among them (story 320).
439
+ const problems = validateBundlePackage(version)
440
+ if (problems.length > 0) return { refused: problems }
428
441
  const dist = (version as { dist?: Dist }).dist
429
442
  const field = version.crombolo as {
430
443
  extensions?: unknown[]
@@ -525,7 +538,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
525
538
  /** What the registry says this package's latest version carries, when it is a valid bundle. */
526
539
  const declares = async (name: string): Promise<BundlePackage['carries'] | undefined> => {
527
540
  const declared = await declaresAt(name)
528
- if (typeof declared === 'string') return undefined
541
+ if (typeof declared === 'string' || 'refused' in declared) return undefined
529
542
  const { permissions: _, version: _version, dist: _dist, ...carries } = declared
530
543
  return carries
531
544
  }
@@ -638,6 +651,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
638
651
  wired: wired.has(bundle.id),
639
652
  contentApplied: (await options.contentApplied?.(bundle.packageName)) ?? null,
640
653
  description: descriptionOf(bundle.directory),
654
+ publisher: authorOf(bundle.directory),
641
655
  peerRange: bundle.peerRange,
642
656
  ...grantOf(bundle),
643
657
  provenance: await provenanceOfInstalled(bundle),
@@ -668,6 +682,11 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
668
682
  }
669
683
  if (declared === 'site-package') return sitePackageRefused(name)
670
684
  if (declared === 'schema-3') return schema3Refused(name)
685
+ if ('refused' in declared)
686
+ return {
687
+ ok: false,
688
+ message: `${name} is not an extension this site takes, so it was not installed: ${declared.refused.join('; ')}.`,
689
+ }
671
690
  if (!consented(request, declared.permissions))
672
691
  return grantNeeded(name, declared.permissions, '', layoutChoice(declared.layout))
673
692
  const provenance = await provenanceAt(name, declared.dist)
@@ -694,6 +713,11 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
694
713
  return { ok: false, message: `${name} is not an extension for this site.` }
695
714
  if (declared === 'site-package') return sitePackageRefused(name)
696
715
  if (declared === 'schema-3') return schema3Refused(name)
716
+ if ('refused' in declared)
717
+ return {
718
+ ok: false,
719
+ message: `${name} is not an extension this site takes: ${declared.refused.join('; ')}.`,
720
+ }
697
721
  const { dist, permissions, ...carries } = declared
698
722
  return {
699
723
  ok: true,
@@ -909,6 +933,26 @@ async function declaresIn(file: string): Promise<
909
933
  }
910
934
 
911
935
  /** A package's own description, read leniently: anything unreadable is none. */
936
+ /** Who made an installed package, as its `author` says: npm's publisher is not kept with it. */
937
+ function authorOf(directory: string): string | null {
938
+ try {
939
+ const json = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8')) as {
940
+ author?: unknown
941
+ }
942
+ const author = json.author
943
+ if (typeof author === 'string') return author.replace(/\s*[<(].*$/, '').trim() || null
944
+ if (
945
+ author &&
946
+ typeof author === 'object' &&
947
+ typeof (author as { name?: unknown }).name === 'string'
948
+ )
949
+ return (author as { name: string }).name
950
+ return null
951
+ } catch {
952
+ return null
953
+ }
954
+ }
955
+
912
956
  function descriptionOf(directory: string): string {
913
957
  try {
914
958
  const json = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8')) as {
package/src/ports.ts CHANGED
@@ -22,6 +22,7 @@ import {
22
22
  type BackOfficePaths,
23
23
  collectManifests,
24
24
  type ExtensionRegistry,
25
+ type InstalledExtension,
25
26
  toResponseModels,
26
27
  } from '@crombolo/backoffice-host'
27
28
  import type { EventSink } from '@crombolo/content'
@@ -142,13 +143,13 @@ function createPreviewPort(config: CromboloConfig, inApp?: PreviewPort['inApp'])
142
143
 
143
144
  function createManifestPort(
144
145
  paths: BackOfficePaths,
145
- extensions: ExtensionRegistry,
146
+ extensions: () => Promise<readonly InstalledExtension[]>,
146
147
  omit: readonly string[],
147
148
  ): ManifestPort {
148
149
  return {
149
- list: (visibility) =>
150
+ list: async (visibility) =>
150
151
  toResponseModels(
151
- collectManifests(paths, extensions.list(), { omit }).all,
152
+ collectManifests(paths, await extensions(), { omit }).all,
152
153
  paths.cacheBustHash,
153
154
  visibility,
154
155
  ),
@@ -368,6 +369,8 @@ export interface DepsOptions {
368
369
  paths: BackOfficePaths
369
370
  /** The site's installed npm extensions, which contribute their manifests. */
370
371
  extensions: ExtensionRegistry
372
+ /** Those extensions with their back-office code built (story 320); `extensions.list()` when absent. */
373
+ readyExtensions?: () => Promise<readonly InstalledExtension[]>
371
374
  /** Omitted only by tests that exercise the contract without a database. */
372
375
  db?: Db
373
376
  /** Where document operations announce what they did; nothing hears them when absent. */
@@ -433,7 +436,7 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
433
436
  // Without an app to preview in, Preview in app contributes no extension.
434
437
  manifests: createManifestPort(
435
438
  options.paths,
436
- options.extensions,
439
+ options.readyExtensions ?? (async () => options.extensions.list()),
437
440
  options.previewInApp ? [] : [APP_PREVIEW_MANIFEST_ID],
438
441
  ),
439
442
  localization: createLocalizationPort(
package/src/remote.ts CHANGED
@@ -17,6 +17,7 @@ import { tmpdir } from 'node:os'
17
17
  import { join, sep } from 'node:path'
18
18
  import { hasSection, type Principal } from '@crombolo/api-management/domain'
19
19
  import { DEVICE_CODE_GRANT, REMOTE_CLIENT_ID } from '@crombolo/auth'
20
+ import { BACKOFFICE_CODE, BACKOFFICE_CODE_WARNING } from '@crombolo/backoffice-host/registry'
20
21
  import {
21
22
  EXPLICIT_PERMISSIONS,
22
23
  managementApiPath,
@@ -988,6 +989,10 @@ export function createRemote(options: RemoteOptions): Remote {
988
989
  items: [
989
990
  ...missing.map((p) => `not granted: ${p}`),
990
991
  ...extra.map((p) => `not asked for: ${p}`),
992
+ // The one that is not confined, said wherever it is asked for (story 320).
993
+ ...(asked.includes(BACKOFFICE_CODE)
994
+ ? [`${BACKOFFICE_CODE}: ${BACKOFFICE_CODE_WARNING}`]
995
+ : []),
991
996
  ],
992
997
  })
993
998
  }
package/src/server.ts CHANGED
@@ -50,6 +50,7 @@ import {
50
50
  backOfficePolicy,
51
51
  collectManifests,
52
52
  type createBackOfficePaths,
53
+ EXTENSION_PATH,
53
54
  isSpaRoute,
54
55
  newNonce,
55
56
  renderBackOfficeShell,
@@ -193,6 +194,7 @@ import { syncDomainsFile } from './domains.ts'
193
194
  import { editorTypeLibs, siteJsxImportSource } from './editor-types.ts'
194
195
  import { emailAvailability } from './email.ts'
195
196
  import { noticeAboutEmail } from './email-notice.ts'
197
+ import { createBackOfficeBuilds } from './extension-backoffice.ts'
196
198
  import { warnAboutAppPlugins } from './extensions-notice.ts'
197
199
  import { coerceForm, deleteForm, saveForm } from './form-files.ts'
198
200
  import {
@@ -458,6 +460,16 @@ export async function createServer(
458
460
  /** The extensions that are on: granted, and not turned off (story 309). */
459
461
  const onExtensions = () =>
460
462
  extensions.list().filter((extension) => bundleGrants.isOn(extension.bundle.id))
463
+ // Their back-office code, built when first asked for (story 320).
464
+ const backOfficeBuilds = createBackOfficeBuilds(config.siteDir, (id) => {
465
+ const named = logger('bundle', id)
466
+ return {
467
+ info: (message, properties) => named.info(message, properties),
468
+ warn: (message, properties) => named.warn(message, properties),
469
+ error: (message, properties) => named.error(message, properties),
470
+ }
471
+ })
472
+ const readyExtensions = () => backOfficeBuilds.ready(onExtensions())
461
473
  // What this process answers: only `web` serves no back office.
462
474
  const servesBackOffice = config.role !== 'web'
463
475
  // A host that installs packages itself calls `reloadBundles()` (story 181); the
@@ -833,7 +845,7 @@ export async function createServer(
833
845
  marketplace,
834
846
  extensions,
835
847
  bundleGrants,
836
- failed: () => core.failedExtensions,
848
+ failed: () => [...core.failedExtensions, ...backOfficeBuilds.failed()],
837
849
  })
838
850
  const actorOf = (principal: Principal, request: Request): BundleActor => ({
839
851
  id: principal.id,
@@ -1350,6 +1362,7 @@ export async function createServer(
1350
1362
  },
1351
1363
  // An extension's screens show only while it is on: granted, and not turned off (story 309).
1352
1364
  extensions: { ...extensions, list: onExtensions },
1365
+ readyExtensions,
1353
1366
  db,
1354
1367
  webhooks,
1355
1368
  contentEvents,
@@ -2993,7 +3006,7 @@ export async function createServer(
2993
3006
 
2994
3007
  // Nor are its files served while it is off (story 309).
2995
3008
  const staticMatch = resolveStaticFile(paths, pathname, {
2996
- extensions: onExtensions(),
3009
+ extensions: pathname.startsWith(`${EXTENSION_PATH}/`) ? await readyExtensions() : [],
2997
3010
  immutable: config.immutableAssets ?? !config.development,
2998
3011
  })
2999
3012
  if (staticMatch) {
@@ -3044,7 +3057,7 @@ export async function createServer(
3044
3057
  },
3045
3058
  })
3046
3059
  }
3047
- const { importmap } = collectManifests(paths, onExtensions())
3060
+ const { importmap } = collectManifests(paths, await readyExtensions())
3048
3061
  return backOfficePage(
3049
3062
  renderDeviceShell(paths, importmap, {
3050
3063
  title: config.siteName,
@@ -3068,7 +3081,7 @@ export async function createServer(
3068
3081
  location: `${paths.backOfficePath}/login?returnUrl=${encodeURIComponent(`${pathname}${url.search}`)}`,
3069
3082
  },
3070
3083
  })
3071
- const { importmap } = collectManifests(paths, onExtensions())
3084
+ const { importmap } = collectManifests(paths, await readyExtensions())
3072
3085
  return backOfficePage(
3073
3086
  renderRemoteApprovalShell(paths, importmap, {
3074
3087
  title: config.siteName,
@@ -3078,7 +3091,7 @@ export async function createServer(
3078
3091
  }
3079
3092
 
3080
3093
  if (pathname === `${paths.backOfficePath}/login`) {
3081
- const { importmap } = collectManifests(paths, onExtensions())
3094
+ const { importmap } = collectManifests(paths, await readyExtensions())
3082
3095
  return backOfficePage(
3083
3096
  renderLoginShell(paths, importmap, {
3084
3097
  defaultUiLanguage: config.defaultUiLanguage,
@@ -3108,7 +3121,7 @@ export async function createServer(
3108
3121
  }
3109
3122
 
3110
3123
  if (isSpaRoute(paths.backOfficePath, pathname)) {
3111
- const { importmap } = collectManifests(paths, onExtensions())
3124
+ const { importmap } = collectManifests(paths, await readyExtensions())
3112
3125
  return backOfficePage(
3113
3126
  renderBackOfficeShell(paths, importmap, {
3114
3127
  defaultUiLanguage: config.defaultUiLanguage,