@dokebi/app 0.1.2 → 0.4.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/dist/index.js CHANGED
@@ -2,10 +2,17 @@ import { stat } from 'node:fs/promises';
2
2
  import { fileURLToPath } from 'node:url';
3
3
  import { types } from 'node:util';
4
4
  import { createControllers, } from '@dokebi/controller';
5
- import { definePlugin, dependencyOf, optionalDependency, providerDependency, } from '@dokebi/core';
5
+ import { definePlugin, dependencyOf, optionalDependency, } from '@dokebi/core';
6
+ import { dependency as web } from '@dokebi/web/dependency';
7
+ import { realtime, viewEngines, } from '@dokebi/web/points';
8
+ import { AppError } from './errors.js';
9
+ import { options as declaration } from './options.js';
10
+ export { AppError } from './errors.js';
11
+ export { options } from './options.js';
6
12
  const NAME = /^[a-z][a-z0-9-]{0,31}$/;
7
- const HOST = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
8
13
  const DEFAULT_TEMPLATE = 'default';
14
+ // Not `import … from 'node:http'`: its ESM facade loads undici (D-0070 §5); Fastify loaded it already.
15
+ const { STATUS_CODES } = process.getBuiltinModule('node:http');
9
16
  /** A module mount prefix: `/` or `/a/b`. */
10
17
  const PREFIX = /^\/(?:[a-z0-9][a-z0-9._~-]*(?:\/[a-z0-9][a-z0-9._~-]*)*)?$/;
11
18
  /** Read without importing @dokebi/module (see its MODULE_MOUNT). */
@@ -24,10 +31,13 @@ function joinPath(base, path) {
24
31
  /** The Fastify route constraint that selects an app by request host. */
25
32
  export const APP_CONSTRAINT = 'dokebiApp';
26
33
  const defined = new WeakSet();
34
+ function invalidDefinition(message) {
35
+ return new AppError('INVALID_DEFINITION', message);
36
+ }
27
37
  /** Declares one app. Its name is the key under which the generated code registers it. */
28
38
  export function defineApp(definition) {
29
39
  if (definition === null || typeof definition !== 'object' || types.isProxy(definition))
30
- throw new TypeError('Invalid app definition');
40
+ throw invalidDefinition('Invalid app definition');
31
41
  for (const key of Object.keys(definition))
32
42
  if (![
33
43
  'requires',
@@ -38,31 +48,32 @@ export function defineApp(definition) {
38
48
  'shared',
39
49
  'routes',
40
50
  'sockets',
51
+ 'events',
41
52
  'setup',
42
53
  'start',
43
54
  'drain',
44
55
  ].includes(key))
45
- throw new TypeError('Unknown app definition field: ' + key);
56
+ throw invalidDefinition('Unknown app definition field: ' + key);
46
57
  if (definition.requires !== undefined && !Array.isArray(definition.requires))
47
- throw new TypeError('App requires must be an array');
58
+ throw invalidDefinition('App requires must be an array');
48
59
  if (definition.controllers !== undefined && !Array.isArray(definition.controllers))
49
- throw new TypeError('App controllers must be an array');
60
+ throw invalidDefinition('App controllers must be an array');
50
61
  if (definition.views !== undefined &&
51
62
  (!(definition.views instanceof URL) || definition.views.protocol !== 'file:'))
52
- throw new TypeError('App views must be a file: URL');
63
+ throw invalidDefinition('App views must be a file: URL');
53
64
  if (definition.modules !== undefined) {
54
65
  if (!plain(definition.modules))
55
- throw new TypeError('App modules must be a plain object');
66
+ throw invalidDefinition('App modules must be a plain object');
56
67
  for (const [prefix, plugin] of Object.entries(definition.modules)) {
57
68
  if (!PREFIX.test(prefix))
58
- throw new TypeError('Invalid module prefix: ' + prefix);
69
+ throw invalidDefinition('Invalid module prefix: ' + prefix);
59
70
  if (!mountOf(plugin))
60
- throw new TypeError('App modules must be made with defineModule');
71
+ throw invalidDefinition('App modules must be made with defineModule');
61
72
  }
62
73
  }
63
- for (const hook of ['shared', 'routes', 'sockets', 'setup', 'start', 'drain'])
74
+ for (const hook of ['shared', 'routes', 'sockets', 'events', 'setup', 'start', 'drain'])
64
75
  if (definition[hook] !== undefined && typeof definition[hook] !== 'function')
65
- throw new TypeError(`App ${hook} must be a function`);
76
+ throw invalidDefinition(`App ${hook} must be a function`);
66
77
  const frozen = Object.freeze({ ...definition });
67
78
  defined.add(frozen);
68
79
  return frozen;
@@ -74,69 +85,91 @@ function plain(value) {
74
85
  !types.isProxy(value) &&
75
86
  [Object.prototype, null].includes(Object.getPrototypeOf(value)));
76
87
  }
77
- function parseOptions(input) {
78
- if (!plain(input))
79
- throw new TypeError('Invalid dokebi-app options');
80
- const { domains, unknownDomain, ...rest } = input;
81
- if (Object.keys(rest).length || !plain(domains))
82
- throw new TypeError('Invalid dokebi-app options');
83
- const map = new Map();
84
- for (const [host, target] of Object.entries(domains)) {
85
- if (host.length > 253 || !HOST.test(host) || !plain(target))
86
- throw new TypeError('Invalid domain entry');
87
- const { app, template = DEFAULT_TEMPLATE, ...extra } = target;
88
- if (Object.keys(extra).length ||
89
- typeof app !== 'string' ||
90
- !NAME.test(app) ||
91
- typeof template !== 'string' ||
92
- !NAME.test(template))
93
- throw new TypeError('Invalid domain entry');
94
- map.set(host, Object.freeze({ app, template }));
95
- }
96
- if (map.size > 1024)
97
- throw new TypeError('Too many domains');
98
- if (unknownDomain !== undefined && unknownDomain !== 'reject') {
99
- if (typeof unknownDomain !== 'string' || !map.has(unknownDomain))
100
- throw new TypeError('unknownDomain must be reject or a configured domain');
101
- }
88
+ /** The parsed options (checked by the declaration, D-0063 §3) as maps. */
89
+ function settings(parsed) {
90
+ const apps = new Map();
91
+ for (const [app, value] of Object.entries(parsed.apps ?? {}))
92
+ apps.set(app, Object.freeze({ namespaces: value.realtime?.namespaces }));
102
93
  return Object.freeze({
103
- domains: map,
104
- unknownDomain: unknownDomain === 'reject' ? undefined : unknownDomain,
94
+ domains: new Map(Object.entries(parsed.domains)),
95
+ unknownDomain: parsed.unknownDomain === 'reject' ? undefined : parsed.unknownDomain,
96
+ apps,
105
97
  });
106
98
  }
107
99
  function parseEntry(input) {
108
100
  if (input === undefined)
109
101
  return new Map();
110
102
  if (!plain(input) || Object.keys(input).some((key) => key !== 'apps') || !plain(input.apps))
111
- throw new TypeError('Invalid dokebi-app entry');
103
+ throw new AppError('INVALID_ENTRY', 'Invalid dokebi-app entry');
112
104
  const apps = new Map();
113
105
  for (const [name, definition] of Object.entries(input.apps)) {
114
106
  if (!NAME.test(name) || !defined.has(definition))
115
- throw new TypeError('Apps must be made with defineApp and named ' + NAME.source);
107
+ throw new AppError('INVALID_ENTRY', 'Apps must be made with defineApp and named ' + NAME.source);
116
108
  apps.set(name, definition);
117
109
  }
118
110
  return apps;
119
111
  }
120
- const web = providerDependency({
121
- name: 'dokebi-web',
122
- version: '^0.1.0',
123
- packageName: '@dokebi/web',
124
- load: () => import('@dokebi/web'),
125
- });
126
- const ejs = providerDependency({
127
- name: 'dokebi-template-ejs',
128
- version: '^0.1.0',
129
- packageName: '@dokebi/template-ejs',
130
- load: () => import('@dokebi/template-ejs'),
131
- });
132
- const inertia = optionalDependency({
133
- name: 'dokebi-template-inertia',
134
- version: '^0.1.0',
135
- });
136
- const websocket = optionalDependency({
137
- name: 'dokebi-websocket',
138
- version: '^0.1.0 || ^0.2.0',
139
- });
112
+ /**
113
+ * The seal plugin (D-0059 §4, D-0062), looked up by name only: a host with `seal: true` needs it
114
+ * (it serves `/dokebi/seal/*`, seals the sockets through the websocket transport and fills the
115
+ * HTTP seal slot of @dokebi/web).
116
+ */
117
+ const seal = optionalDependency({ name: 'dokebi-seal', version: '^0.4.0' });
118
+ /** Packages that offer an engine or transport, for the fix of a missing one. */
119
+ const PROVIDERS = {
120
+ ejs: '@dokebi/template-ejs',
121
+ inertia: '@dokebi/template-inertia',
122
+ websocket: '@dokebi/websocket',
123
+ sse: '@dokebi/sse',
124
+ };
125
+ /** A realtime target string: 1 to 256 characters. */
126
+ function targetText(value) {
127
+ return typeof value === 'string' && value.length > 0 && value.length <= 256;
128
+ }
129
+ function checkTarget(target) {
130
+ const value = target;
131
+ if (!value ||
132
+ typeof value !== 'object' ||
133
+ (value.tenant !== undefined && !targetText(value.tenant)) ||
134
+ (value.member !== undefined && !targetText(value.member)) ||
135
+ (value.room !== undefined && !targetText(value.room)))
136
+ throw new AppError('INVALID_TARGET', 'A realtime target is { tenant?, member?, room? } with strings of 1 to 256 characters');
137
+ return value;
138
+ }
139
+ function unavailable(app, what, kind) {
140
+ return new AppError('REALTIME_UNAVAILABLE', `App ${app}: ${what} needs ${PROVIDERS[kind]}`, {
141
+ fix: `npx dokebi add ${PROVIDERS[kind]} (it contributes the ${kind} transport to dokebi-web:realtime).`,
142
+ });
143
+ }
144
+ /** The handle of one namespace (D-0061) over the transports' namespace handles. */
145
+ function realtimeHandle(app, namespace, sockets, streams) {
146
+ let socketHandle;
147
+ let streamHandle;
148
+ const websocket = () => {
149
+ if (!sockets)
150
+ throw unavailable(app, 'realtime sockets', 'websocket');
151
+ socketHandle ??= sockets.handle(namespace);
152
+ return socketHandle;
153
+ };
154
+ return Object.freeze({
155
+ namespace,
156
+ list: async (target = {}) => websocket().list(checkTarget(target)),
157
+ send: async (target, type, data) => websocket().send(checkTarget(target), type, data),
158
+ kick: async (target, code, reason) => websocket().kick(checkTarget(target), code, reason),
159
+ onPresence: (listener) => {
160
+ if (typeof listener !== 'function')
161
+ throw new AppError('INVALID_TARGET', 'Invalid presence listener');
162
+ return websocket().onPresence(listener);
163
+ },
164
+ publish: async (target, event, data) => {
165
+ if (!streams)
166
+ throw unavailable(app, 'realtime publish', 'sse');
167
+ const checked = checkTarget(target);
168
+ streamHandle ??= streams.handle(namespace);
169
+ return streamHandle.publish(checked, event, data);
170
+ },
171
+ });
172
+ }
140
173
  const descriptors = new WeakMap();
141
174
  /** Stable descriptor per requirement, so declared and runtime lookups use the same object. */
142
175
  function requirement(value) {
@@ -153,7 +186,7 @@ function requirement(value) {
153
186
  if (value === null ||
154
187
  typeof value !== 'object' ||
155
188
  typeof value.name !== 'string')
156
- throw new TypeError('Invalid app requirement');
189
+ throw new AppError('INVALID_DEFINITION', 'Invalid app requirement');
157
190
  return value;
158
191
  }
159
192
  /** A host without its port, lower case; IPv6 literals keep their brackets. */
@@ -168,6 +201,58 @@ export function withoutPort(host) {
168
201
  export function hostOf(request) {
169
202
  return withoutPort(String(request.headers.host ?? ''));
170
203
  }
204
+ /** The host entry of a request, kept on the raw request: the host is worked out once. */
205
+ const HOST_ENTRY = Symbol('dokebi.app.host');
206
+ /** Hosts that are not configured (answered by `unknownDomain` or refused) kept at most. */
207
+ const UNKNOWN_HOSTS = 256;
208
+ /**
209
+ * The page an app handler receives. Everything but `view` is the host's, shared by every
210
+ * request; `view` is bound to the request (shared data) and built only when a handler reads it.
211
+ */
212
+ class RequestPage {
213
+ app;
214
+ module;
215
+ base;
216
+ inertia;
217
+ sealed;
218
+ #request;
219
+ #view;
220
+ #built;
221
+ constructor(info, sealed, module, base, inertia, request, view) {
222
+ this.app = info;
223
+ this.module = module;
224
+ this.base = base;
225
+ this.inertia = inertia;
226
+ this.sealed = sealed;
227
+ this.#request = request;
228
+ this.#view = view;
229
+ Object.freeze(this);
230
+ }
231
+ get view() {
232
+ this.#built ??= this.#view(this.#request, this.app, this.sealed);
233
+ return this.#built;
234
+ }
235
+ }
236
+ /** The contributions of one point by name (`ejs`, `inertia`) or kind (`websocket`, `sse`). */
237
+ function byKey(context, point, key) {
238
+ const result = new Map();
239
+ for (const { value } of context.collect(point)) {
240
+ const name = value[key];
241
+ // The first contribution of a name wins (setup order); a later one is reported.
242
+ if (typeof name !== 'string')
243
+ continue;
244
+ if (result.has(name)) {
245
+ context.logger.log('warn', 'Second contribution of the same name ignored', {
246
+ code: 'DUPLICATE_CONTRIBUTION',
247
+ point: point.name,
248
+ name,
249
+ });
250
+ continue;
251
+ }
252
+ result.set(name, value);
253
+ }
254
+ return result;
255
+ }
171
256
  class AppRuntime {
172
257
  options;
173
258
  apps;
@@ -182,30 +267,114 @@ class AppRuntime {
182
267
  #declaredFor(name) {
183
268
  const dependency = this.#declared.get(name);
184
269
  if (!dependency)
185
- throw new Error(`Plugin ${name} is not declared by dokebi-app`);
270
+ throw new AppError('NOT_REQUIRED', `Plugin ${name} is not declared by dokebi-app`);
186
271
  return dependency;
187
272
  }
273
+ #hosts = new Map();
274
+ #unknownHosts = 0;
275
+ /** AppInfo and seal flag of a host (without port), cached per host. */
276
+ entry(host) {
277
+ const known = this.#hosts.get(host);
278
+ if (known !== undefined)
279
+ return known;
280
+ const target = this.#target(host);
281
+ const entry = target
282
+ ? Object.freeze({
283
+ info: Object.freeze({ name: target.app, template: target.template, domain: host }),
284
+ sealed: target.seal === true,
285
+ })
286
+ : null;
287
+ // Configured hosts are few; any other Host header is client input, so that part is bounded.
288
+ if (!this.options.domains.has(host)) {
289
+ if (this.#unknownHosts >= UNKNOWN_HOSTS) {
290
+ for (const name of this.#hosts.keys())
291
+ if (!this.options.domains.has(name))
292
+ this.#hosts.delete(name);
293
+ this.#unknownHosts = 0;
294
+ }
295
+ this.#unknownHosts++;
296
+ }
297
+ this.#hosts.set(host, entry);
298
+ return entry;
299
+ }
188
300
  resolve(host) {
301
+ return this.entry(host)?.info;
302
+ }
303
+ #target(host) {
189
304
  const domain = this.options.domains.has(host) ? host : this.options.unknownDomain;
190
- const target = domain === undefined ? undefined : this.options.domains.get(domain);
191
- return target ? { name: target.app, template: target.template, domain: host } : undefined;
305
+ return domain === undefined ? undefined : this.options.domains.get(domain);
306
+ }
307
+ /** The host's `seal` flag (an unknown host answered by `unknownDomain` takes that entry's). */
308
+ sealed(host) {
309
+ return this.entry(host)?.sealed === true;
192
310
  }
193
311
  async setup(context) {
194
312
  for (const [host, target] of this.options.domains)
195
313
  if (!this.apps.has(target.app))
196
- throw new Error(`Domain ${host} points to app ${target.app}, which is not registered`);
314
+ throw new AppError('UNKNOWN_APP', `Domain ${host} points to app ${target.app}, which is not registered`);
315
+ for (const app of this.options.apps.keys())
316
+ if (!this.apps.has(app))
317
+ throw new AppError('UNKNOWN_APP', `dokebi-app apps.${app} names an app that is not defined (defined: ${[...this.apps.keys()].join(', ') || 'none'})`);
197
318
  const http = context.getDependency(web);
198
319
  const logger = context.logger;
320
+ // D-0063 §5: view engines and realtime transports by name, whoever contributes them.
321
+ const engines = byKey(context, viewEngines, 'name');
322
+ const transports = byKey(context, realtime, 'kind');
323
+ const sockets = transports.get('websocket');
324
+ const streams = transports.get('sse');
325
+ const sealedDomains = [...this.options.domains]
326
+ .filter(([, target]) => target.seal)
327
+ .map(([domain]) => domain);
199
328
  logger.log('debug', 'App domains configured', {
200
329
  apps: [...this.apps.keys()],
201
330
  domains: [...this.options.domains]
202
331
  .slice(0, 64)
203
- .map(([domain, target]) => `${domain} -> ${target.app}/${target.template}`),
332
+ .map(([domain, target]) => `${domain} -> ${target.app}/${target.template}${target.seal ? ' (sealed)' : ''}`),
204
333
  count: this.options.domains.size,
205
334
  unknownDomain: this.options.unknownDomain ?? 'reject',
335
+ sealed: sealedDomains.length,
336
+ viewEngines: [...engines.keys()],
337
+ transports: [...transports.keys()],
206
338
  });
339
+ // Fail closed (D-0059 §4): a sealed host without the seal plugin would talk plain text.
340
+ if (sealedDomains.length && context.getOptionalDependency(seal) === undefined)
341
+ throw new AppError('SEAL_PROVIDER_MISSING', `Domains ${sealedDomains.slice(0, 8).join(', ')} set seal: true; register the dokebi-seal plugin`);
342
+ /** The engine an app needs, or VIEW_ENGINE_MISSING naming the package that offers it. */
343
+ const engine = (name, app) => {
344
+ const found = engines.get(name);
345
+ if (!found)
346
+ throw new AppError('VIEW_ENGINE_MISSING', `App ${app} uses the ${name} view engine; add ${PROVIDERS[name]}`, { fix: `npx dokebi add ${PROVIDERS[name]} (it contributes the ${name} view engine).` });
347
+ return found;
348
+ };
207
349
  // Behind a trusted proxy (dokebi-web trustProxy) the forwarded host picks the app.
208
350
  const host = (request) => withoutPort(http.requestHost(request));
351
+ /** The host entry of a raw or Fastify request, worked out once per request. */
352
+ // Raw Host header → entry, so the usual request skips trimming, lower-casing and the port
353
+ // cut. Only when no X-Forwarded-Host is present (with one, trustProxy decides). Client input:
354
+ // bounded like the unknown hosts.
355
+ const byHeader = new Map();
356
+ const hostEntry = (request) => {
357
+ const raw = (request.raw ?? request);
358
+ const known = raw[HOST_ENTRY];
359
+ if (known !== undefined)
360
+ return known;
361
+ const header = raw.headers['x-forwarded-host'] === undefined ? raw.headers.host : undefined;
362
+ let entry = typeof header === 'string' ? byHeader.get(header) : undefined;
363
+ if (entry === undefined) {
364
+ entry = this.entry(host(request));
365
+ if (typeof header === 'string') {
366
+ if (byHeader.size >= UNKNOWN_HOSTS)
367
+ byHeader.clear();
368
+ byHeader.set(header, entry);
369
+ }
370
+ }
371
+ raw[HOST_ENTRY] = entry;
372
+ return entry;
373
+ };
374
+ // D-0062: every HTTP request of a sealed host is sealed by dokebi-web (JSON bodies both ways,
375
+ // the Inertia page, SSE data), except routes with seal: false and dokebi-web sealExclude.
376
+ if (sealedDomains.length)
377
+ http.sealRequests((request) => hostEntry(request)?.sealed === true);
209
378
  http.constraint({
210
379
  name: APP_CONSTRAINT,
211
380
  storage() {
@@ -218,23 +387,61 @@ class AppRuntime {
218
387
  };
219
388
  },
220
389
  deriveConstraint: (request) => {
221
- const requested = host(request);
222
- const name = this.resolve(requested)?.name;
390
+ const name = hostEntry(request)?.info.name;
223
391
  // Per request: only built when debug is on (D-0047).
224
392
  if (name === undefined && logger.isEnabled('debug'))
225
- logger.log('debug', 'App domain not configured', { host: requested.slice(0, 253) });
393
+ logger.log('debug', 'App domain not configured', { host: host(request).slice(0, 253) });
226
394
  return name;
227
395
  },
228
396
  // Requests of a known app may still reach shared (unconstrained) routes.
229
397
  mustMatchWhenDerived: false,
230
398
  });
231
- const pages = context.getOptionalDependency(inertia);
232
- const sockets = context.getOptionalDependency(websocket);
399
+ /** The shared EJS renderer (the engine's own), loaded once on first need. */
400
+ let ejsRoot;
401
+ /** Each app's error answer (D-0074), by app name. */
402
+ const answers = new Map();
233
403
  for (const [name, definition] of this.apps) {
234
404
  context.signal.throwIfAborted();
235
405
  const begin = performance.now();
406
+ // An app answers its own hosts, and unknown ones when it is the unknownDomain target.
407
+ const appSealed = [...this.options.domains.values()].some((target) => target.app === name && target.seal);
236
408
  let routeCount = 0;
237
409
  let socketCount = 0;
410
+ let eventCount = 0;
411
+ // D-0061: hub tenants are `<namespace>:<tenant>`; the first namespace is the default.
412
+ const namespaces = this.options.apps.get(name)?.namespaces ?? [name];
413
+ const handles = new Map();
414
+ /** The namespace an authenticated connection joins, or undefined (401) for one not listed. */
415
+ const namespaceOf = (wanted, kind, path) => {
416
+ if (wanted === undefined)
417
+ return namespaces[0];
418
+ if (typeof wanted === 'string' && namespaces.includes(wanted))
419
+ return wanted;
420
+ logger.log('warn', 'Realtime namespace refused', {
421
+ code: 'NAMESPACE_FORBIDDEN',
422
+ app: name,
423
+ kind,
424
+ path,
425
+ namespace: typeof wanted === 'string' ? wanted.slice(0, 64) : null,
426
+ allowed: [...namespaces],
427
+ });
428
+ return undefined;
429
+ };
430
+ /** `identity` in the chosen namespace: tenant prefixed, `namespace` removed. */
431
+ const scoped = (kind, path) => (identity) => {
432
+ const chosen = namespaceOf(identity.namespace, kind, path);
433
+ if (chosen === undefined)
434
+ return undefined;
435
+ const { namespace: _namespace, ...rest } = identity;
436
+ if (logger.isEnabled('debug'))
437
+ logger.log('debug', 'Realtime namespace chosen', {
438
+ app: name,
439
+ kind,
440
+ path,
441
+ namespace: chosen,
442
+ });
443
+ return { ...rest, tenant: `${chosen}:${identity.tenant}` };
444
+ };
238
445
  const allowed = new Set([...(definition.requires ?? []), ...Object.values(definition.modules ?? {})].map((item) => requirement(item).name));
239
446
  let controllers;
240
447
  const appContext = Object.freeze({
@@ -243,25 +450,41 @@ class AppRuntime {
243
450
  signal: context.signal,
244
451
  get: (plugin) => {
245
452
  if (!allowed.has(plugin.metadata.name))
246
- throw new Error(`App ${name} does not list ${plugin.metadata.name} in requires`);
453
+ throw new AppError('NOT_REQUIRED', `App ${name} does not list ${plugin.metadata.name} in requires`);
247
454
  return context.get(plugin);
248
455
  },
249
456
  getDependency: (dependency) => {
250
457
  if (!allowed.has(dependency.name))
251
- throw new Error(`App ${name} does not list ${dependency.name} in requires`);
458
+ throw new AppError('NOT_REQUIRED', `App ${name} does not list ${dependency.name} in requires`);
252
459
  return context.getDependency(this.#declaredFor(dependency.name));
253
460
  },
254
461
  getOptionalDependency: (dependency) => {
255
462
  if (!allowed.has(dependency.name))
256
- throw new Error(`App ${name} does not list ${dependency.name} in requires`);
463
+ throw new AppError('NOT_REQUIRED', `App ${name} does not list ${dependency.name} in requires`);
257
464
  return context.getOptionalDependency(this.#declaredFor(dependency.name));
258
465
  },
259
466
  controller: (token) => {
260
467
  if (!controllers)
261
- throw new Error(`App ${name} has no controllers yet`);
468
+ throw new AppError('NOT_READY', `App ${name} has no controllers yet`);
262
469
  return controllers.get(token);
263
470
  },
264
471
  defer: (cleanup) => context.defer(cleanup),
472
+ realtime: (namespace = namespaces[0]) => {
473
+ let handle = handles.get(namespace);
474
+ if (handle)
475
+ return handle;
476
+ if (!namespaces.includes(namespace))
477
+ throw new AppError('NAMESPACE_FORBIDDEN', `App ${name} may use realtime namespaces ${namespaces.join(', ')}, not ${String(namespace).slice(0, 64)}`);
478
+ handle = realtimeHandle(name, namespace, sockets, streams);
479
+ handles.set(namespace, handle);
480
+ logger.log('debug', 'App realtime handle created', {
481
+ app: name,
482
+ namespace,
483
+ websocket: sockets !== undefined,
484
+ sse: streams !== undefined,
485
+ });
486
+ return handle;
487
+ },
265
488
  });
266
489
  // Controller factories read plugins through the same restricted view.
267
490
  const factoryContext = Object.freeze({
@@ -277,21 +500,26 @@ class AppRuntime {
277
500
  });
278
501
  controllers = await createControllers(factoryContext, definition.controllers ?? []);
279
502
  const templates = new Set();
280
- let templateApi;
503
+ const hasModuleViews = Object.values(definition.modules ?? {}).some((module) => mountOf(module)?.views);
281
504
  if (definition.views) {
282
- templateApi = context.getDependency(ejs);
283
- await templateApi.addDirectory(definition.views, name);
505
+ // The app's folder is loaded as `<app>/…`; the engine's root renderer serves every scope.
506
+ ejsRoot = await engine('ejs', name).scope({
507
+ directory: definition.views,
508
+ prefix: name,
509
+ });
284
510
  await this.#checkTemplates(name, definition.views, templates);
285
511
  }
512
+ else if (hasModuleViews && !ejsRoot)
513
+ ejsRoot = await engine('ejs', name).scope({});
286
514
  let inertiaApi;
287
515
  if (definition.inertia) {
288
- if (!pages)
289
- throw new Error(`App ${name} uses Inertia; add @dokebi/template-inertia`);
290
- inertiaApi = await pages.scope({
516
+ inertiaApi = await engine('inertia', name).scope({
291
517
  ...definition.inertia,
518
+ // SSR would write the props of a sealed host as plain HTML: refused (D-0062).
519
+ ...(appSealed ? { sealed: true } : {}),
292
520
  shared: (request) => {
293
- const info = this.resolve(host(request));
294
- return { app: info ? { ...info } : null };
521
+ const entry = hostEntry(request);
522
+ return { app: entry ? { ...entry.info } : null, sealed: entry?.sealed === true };
295
523
  },
296
524
  });
297
525
  }
@@ -314,9 +542,10 @@ class AppRuntime {
314
542
  ...appChain(template),
315
543
  ];
316
544
  };
317
- // The app's shared data under the page data, computed once per render call.
318
- const withShared = (view, request, info) => {
545
+ // `sealed` and the app's shared data under the page data, computed once per render call.
546
+ const withShared = (view, request, info, sealed) => {
319
547
  const data = async (own) => ({
548
+ sealed,
320
549
  ...(await definition.shared?.(request, { app: info })),
321
550
  ...own,
322
551
  });
@@ -324,47 +553,52 @@ class AppRuntime {
324
553
  render: async (name, own, options) => view.render(name, await data(own), options),
325
554
  reply: async (reply, name, own, options) => view.reply(reply, name, await data(own), options),
326
555
  scope: (prefixes) => view.scope(prefixes),
556
+ has: (template) => view.has(template),
327
557
  });
328
558
  };
329
559
  const pageFor = (module) => {
330
560
  const scopes = new Map();
331
561
  const hasViews = Boolean(definition.views || module?.views);
332
- return (request) => {
333
- const info = this.resolve(host(request)) ?? {
334
- name,
335
- template: DEFAULT_TEMPLATE,
336
- domain: host(request),
337
- };
562
+ // Built on the first `page.view` read of a request (D-0068): most JSON routes never do.
563
+ const viewOf = (request, info, sealed) => {
338
564
  let view = scopes.get(info.template);
339
565
  if (!view) {
340
- templateApi ??= hasViews ? context.getDependency(ejs) : undefined;
341
566
  view =
342
- templateApi && hasViews
343
- ? templateApi.scope(chain(info.template, module))
567
+ ejsRoot && hasViews
568
+ ? ejsRoot.scope(chain(info.template, module))
344
569
  : missingViews(name);
345
570
  scopes.set(info.template, view);
346
571
  }
347
- return Object.freeze({
348
- app: info,
349
- module: module?.name,
350
- base: module?.base ?? '',
351
- view: definition.shared ? withShared(view, request, info) : view,
352
- inertia: inertiaApi,
353
- });
572
+ return withShared(view, request, info, sealed);
573
+ };
574
+ const moduleName = module?.name;
575
+ const base = module?.base ?? '';
576
+ return (request) => {
577
+ const entry = hostEntry(request);
578
+ // An app route is only reached through its own host (route constraint); the fallback
579
+ // covers a host whose entry went away in between.
580
+ const info = entry?.info ?? { name, template: DEFAULT_TEMPLATE, domain: host(request) };
581
+ return new RequestPage(info, entry?.sealed === true, moduleName, base, inertiaApi, request, viewOf);
354
582
  };
355
583
  };
356
584
  const routerFor = (page, base) => {
357
585
  const add = (options) => {
358
586
  const { handler, ...rest } = options;
359
587
  routeCount++;
360
- http.route({
588
+ const url = joinPath(base, rest.url);
589
+ const register = (path) => http.route({
361
590
  ...rest,
362
- url: joinPath(base, rest.url),
591
+ url: path,
363
592
  constraints: { [APP_CONSTRAINT]: name },
364
593
  handler(request, reply) {
365
594
  return handler(request, reply, page(request));
366
595
  },
367
596
  });
597
+ register(url);
598
+ // The root of a prefixed mount answers `/board/` as well as `/board`: links and form
599
+ // actions written with a trailing slash would otherwise be 404 (AI-M03).
600
+ if (base && url === base)
601
+ register(base + '/');
368
602
  };
369
603
  const method = (verb) => (url, handler, options = {}) => add({ ...options, method: verb, url, handler });
370
604
  return Object.freeze({
@@ -376,27 +610,83 @@ class AppRuntime {
376
610
  delete: method('DELETE'),
377
611
  });
378
612
  };
613
+ /** The scope of one realtime route: the full path, the app constraint and tenant rule. */
614
+ const scopeOf = (path, kind) => Object.freeze({
615
+ path,
616
+ constraints: Object.freeze({ [APP_CONSTRAINT]: name }),
617
+ identity: scoped(kind, path),
618
+ // The request's host decides (D-0059 §4); only when a host of this app seals.
619
+ ...(appSealed
620
+ ? { seal: (request) => hostEntry(request)?.sealed === true }
621
+ : {}),
622
+ });
379
623
  const mountSockets = (routes, base, owner) => {
380
624
  for (const route of routes) {
381
625
  if (!sockets)
382
- throw new Error(`${owner} has sockets; add @dokebi/websocket`);
626
+ throw new AppError('REALTIME_UNAVAILABLE', `${owner} has sockets; add @dokebi/websocket`);
383
627
  socketCount++;
384
- sockets.route({
385
- ...route,
386
- path: joinPath(base, route.path),
387
- constraints: { ...(route.constraints ?? {}), [APP_CONSTRAINT]: name },
388
- // Each app is its own tenant space in the hub: presence and broadcasts stay inside.
389
- authenticate: async (request) => {
390
- const identity = await route.authenticate(request);
391
- return identity ? { ...identity, tenant: `${name}:${identity.tenant}` } : undefined;
392
- },
393
- });
628
+ sockets.mount(route, scopeOf(joinPath(base, route.path), 'socket'));
629
+ }
630
+ };
631
+ const mountEvents = (routes, base, owner) => {
632
+ for (const route of routes) {
633
+ if (!streams)
634
+ throw new AppError('REALTIME_UNAVAILABLE', `${owner} has event streams; add @dokebi/sse`);
635
+ eventCount++;
636
+ streams.mount(route, scopeOf(joinPath(base, route.path), 'stream'));
394
637
  }
395
638
  };
639
+ // D-0074 §3-4: the error answers of this app's hosts. Inertia first (the validation
640
+ // redirect, the app's error page component), then for an HTML answer the app's error view:
641
+ // `errors/<status>` → `errors/error` in <app>/<template> → <app>/default → shared views.
642
+ const errorViews = new Map();
643
+ answers.set(name, async (response, entry) => {
644
+ if (inertiaApi && typeof inertiaApi.answerError === 'function') {
645
+ if (await inertiaApi.answerError(response))
646
+ return true;
647
+ }
648
+ if (response.format !== 'html' || !ejsRoot)
649
+ return false;
650
+ const { info, sealed } = entry;
651
+ let view = errorViews.get(info.template);
652
+ if (!view) {
653
+ view = ejsRoot.scope(appChain(info.template));
654
+ errorViews.set(info.template, view);
655
+ }
656
+ const { status, body, request, reply, production, error } = response;
657
+ const page = view.has(`errors/${status}`)
658
+ ? `errors/${status}`
659
+ : view.has('errors/error')
660
+ ? 'errors/error'
661
+ : undefined;
662
+ if (!page)
663
+ return false;
664
+ const fields = Array.isArray(body.fields) ? body.fields : [];
665
+ await withShared(view, request, info, sealed).reply(reply, page, {
666
+ status,
667
+ title: `${status} ${STATUS_CODES[status] ?? 'Error'}`,
668
+ error: body.error,
669
+ message: typeof body.message === 'string' ? body.message : null,
670
+ hint: typeof body.hint === 'string' ? body.hint : null,
671
+ fields,
672
+ // Development only (dokebi-web already cut `fix` from a production body).
673
+ fix: typeof body.fix === 'string' ? body.fix : null,
674
+ stack: !production && status >= 500 && error instanceof Error ? (error.stack ?? null) : null,
675
+ });
676
+ if (logger.isEnabled('debug'))
677
+ logger.log('debug', 'App error view rendered', {
678
+ app: name,
679
+ template: info.template,
680
+ view: page,
681
+ status,
682
+ });
683
+ return true;
684
+ });
396
685
  await definition.setup?.(appContext);
397
686
  await definition.routes?.(routerFor(pageFor(), ''), appContext);
398
687
  mountSockets((await definition.sockets?.(appContext)) ?? [], '', `App ${name}`);
399
- // Mounted modules (D-0032): their routes and sockets under the prefix, on this app only.
688
+ mountEvents((await definition.events?.(appContext)) ?? [], '', `App ${name}`);
689
+ // Mounted modules (D-0032): their routes, sockets and SSE routes under the prefix, here only.
400
690
  for (const [prefix, plugin] of Object.entries(definition.modules ?? {})) {
401
691
  const mount = mountOf(plugin);
402
692
  const base = prefix === '/' ? '' : prefix;
@@ -406,6 +696,8 @@ class AppRuntime {
406
696
  mountSockets(
407
697
  // defineSocket results; the module types them by shape only.
408
698
  ((await mount.sockets?.(module)) ?? []), base, `Module ${mount.name} (app ${name})`);
699
+ // SSE routes of the module (@dokebi/module 0.1.3; older modules have no `events`).
700
+ mountEvents(((await mount.events?.(module)) ?? []), base, `Module ${mount.name} (app ${name})`);
409
701
  }
410
702
  this.#mounted.push({ name, definition, context: appContext });
411
703
  logger.log('debug', 'App set up', {
@@ -417,12 +709,22 @@ class AppRuntime {
417
709
  modules: Object.entries(definition.modules ?? {}).map(([prefix, plugin]) => `${prefix} -> ${mountOf(plugin).name}`),
418
710
  routes: routeCount,
419
711
  sockets: socketCount,
712
+ events: eventCount,
713
+ namespaces: [...namespaces],
714
+ sealed: appSealed,
420
715
  ms: Math.round(performance.now() - begin),
421
716
  });
422
717
  }
718
+ // D-0074: errors on an app's hosts (unknown routes included) are answered by that app.
719
+ // Added after the template plugins' responders, so dokebi-web asks this one first.
720
+ http.errorResponder((response) => {
721
+ const entry = hostEntry(response.request);
722
+ const answer = entry ? answers.get(entry.info.name) : undefined;
723
+ return entry && answer ? answer(response, entry) : false;
724
+ });
423
725
  return Object.freeze({
424
726
  names: Object.freeze([...this.apps.keys()]),
425
- resolve: (request) => this.resolve(host(request)),
727
+ resolve: (request) => hostEntry(request)?.info,
426
728
  });
427
729
  }
428
730
  /** Every template a domain selects must exist as a folder, and `default` always must. */
@@ -440,7 +742,7 @@ class AppRuntime {
440
742
  return undefined;
441
743
  });
442
744
  if (!info?.isDirectory())
443
- throw new Error(`App ${name} has no views/${template}/ folder`, failure === undefined ? undefined : { cause: failure });
745
+ throw new AppError('VIEWS_MISSING', `App ${name} has no views/${template}/ folder`, failure === undefined ? {} : { cause: failure });
444
746
  found.add(template);
445
747
  }
446
748
  }
@@ -471,23 +773,27 @@ class AppRuntime {
471
773
  }
472
774
  function missingViews(name) {
473
775
  const fail = async () => {
474
- throw new Error(`App ${name} has no views folder`);
776
+ throw new AppError('VIEWS_MISSING', `App ${name} has no views folder`);
475
777
  };
476
- const api = Object.freeze({ render: fail, reply: fail, scope: () => api });
778
+ const api = Object.freeze({
779
+ render: fail,
780
+ reply: fail,
781
+ scope: () => api,
782
+ has: () => false,
783
+ });
477
784
  return api;
478
785
  }
479
786
  export const createPlugin = definePlugin({
480
787
  name: 'dokebi-app',
481
- version: '0.1.2',
482
- core: '^0.2.0',
483
- options: parseOptions,
788
+ version: '0.4.0',
789
+ core: '^0.4.0',
790
+ options: declaration,
484
791
  entry: parseEntry,
792
+ // Template and realtime plugins are found through these points, not by name (D-0063 §5).
793
+ collects: [viewEngines, realtime],
485
794
  dependencies: ({ entry }) => {
486
795
  const apps = [...(entry ?? new Map()).values()];
487
- const list = [web];
488
- if (apps.some((app) => app.views || Object.values(app.modules ?? {}).some((module) => mountOf(module)?.views)))
489
- list.push(ejs);
490
- list.push(inertia, websocket);
796
+ const list = [web, seal];
491
797
  for (const app of apps)
492
798
  for (const item of [...(app.requires ?? []), ...Object.values(app.modules ?? {})]) {
493
799
  const dependency = requirement(item);
@@ -496,5 +802,5 @@ export const createPlugin = definePlugin({
496
802
  }
497
803
  return list;
498
804
  },
499
- instance: ({ options, entry, dependencies }) => new AppRuntime(options, entry ?? new Map(), dependencies),
805
+ instance: ({ options, entry, dependencies }) => new AppRuntime(settings(options), entry ?? new Map(), dependencies),
500
806
  });