@dokebi/app 0.4.1 → 0.4.5
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/AI.md +46 -16
- package/README.md +21 -4
- package/dist/describe.d.ts +37 -0
- package/dist/describe.js +79 -0
- package/dist/errors.d.ts +1 -1
- package/dist/errors.js +1 -0
- package/dist/index.d.ts +77 -4
- package/dist/index.js +388 -61
- package/package.json +21 -6
- package/templates/app/controllers/home.ts +7 -3
- package/templates/app/models/site.ts +4 -4
- package/templates/app/services/site.ts +7 -0
- package/templates/app-inertia/controllers/home.ts +7 -3
- package/templates/app-inertia/models/site.ts +4 -4
- package/templates/app-inertia/services/site.ts +7 -0
- package/templates/app-inertia/views/app.js +13 -5
- package/templates/app-inertia/views/default/Layout.vue +21 -1
- package/templates/app-inertia/views/default/Pages/Error.vue +2 -2
- package/templates/app-inertia/views/default/Pages/Home.vue +3 -2
- package/templates/app-inertia-ssr/views/ssr.js +3 -0
- package/templates/inertia-build/build.json +5 -2
- package/templates/inertia-build/page.d.ts +21 -0
- package/templates/inertia-build/tsconfig.vue.json +9 -0
- package/templates/inertia-build/typecheck-vue.mjs +14 -0
- package/templates/inertia-build/vite.config.ts +27 -4
- package/templates/inertia-build/vite.ssr.config.ts +16 -6
package/dist/index.js
CHANGED
|
@@ -4,7 +4,11 @@ import { types } from 'node:util';
|
|
|
4
4
|
import { createControllers, } from '@dokebi/controller';
|
|
5
5
|
import { definePlugin, dependencyOf, optionalDependency, providerDependency, } from '@dokebi/core';
|
|
6
6
|
import { formBackTarget, formFieldErrors, formOldInput, isFormSubmission, } from '@dokebi/web';
|
|
7
|
-
import { realtime, viewEngines, } from '@dokebi/web/points';
|
|
7
|
+
import { collectViewData, realtime, viewData, viewEngines, } from '@dokebi/web/points';
|
|
8
|
+
import Range from 'semver/classes/range.js';
|
|
9
|
+
import minVersion from 'semver/ranges/min-version.js';
|
|
10
|
+
import validRange from 'semver/ranges/valid.js';
|
|
11
|
+
import { appPages, describePoint } from './describe.js';
|
|
8
12
|
import { AppError } from './errors.js';
|
|
9
13
|
import { options as declaration } from './options.js';
|
|
10
14
|
export { AppError } from './errors.js';
|
|
@@ -110,13 +114,14 @@ function parseEntry(input) {
|
|
|
110
114
|
return apps;
|
|
111
115
|
}
|
|
112
116
|
/**
|
|
113
|
-
* dokebi-web 0.4.
|
|
114
|
-
* addendum 1
|
|
117
|
+
* dokebi-web 0.4.3 or later: the HTML form validation redirect uses its form helpers (D-0074
|
|
118
|
+
* addendum 1; 0.4.2 never answers a Referer path that reads as another host, ISSUE-0006 A02) and
|
|
119
|
+
* the view data point (`viewData`, `collectViewData`, D-0076 §5, 0.4.3). A local descriptor instead of '@dokebi/web/dependency' (whose range stays ^0.4.0
|
|
115
120
|
* for the plugins that need nothing newer).
|
|
116
121
|
*/
|
|
117
122
|
const web = providerDependency({
|
|
118
123
|
name: 'dokebi-web',
|
|
119
|
-
version: '^0.4.
|
|
124
|
+
version: '^0.4.3',
|
|
120
125
|
packageName: '@dokebi/web',
|
|
121
126
|
load: () => import('@dokebi/web'),
|
|
122
127
|
});
|
|
@@ -140,6 +145,13 @@ function viewFlash(taken) {
|
|
|
140
145
|
* HTTP seal slot of @dokebi/web).
|
|
141
146
|
*/
|
|
142
147
|
const seal = optionalDependency({ name: 'dokebi-seal', version: '^0.4.0' });
|
|
148
|
+
/** Optional: without it an app's `public/` folder is not served (warn APP_PUBLIC_UNSERVED). */
|
|
149
|
+
const files = optionalDependency({ name: 'dokebi-static', version: '^0.1.0' });
|
|
150
|
+
/** The import map and the forms module of a page on a seal host (served by @dokebi/seal). */
|
|
151
|
+
const SEAL_HEAD = '<script type="importmap">{"imports":{"@dokebi/seal/http":"/dokebi/seal/http.mjs","@dokebi/seal/forms":"/dokebi/seal/forms.mjs"}}</script>' +
|
|
152
|
+
'<script type="module" src="/dokebi/seal/forms.mjs"></script>';
|
|
153
|
+
const SEALED_VIEW = Object.freeze({ head: SEAL_HEAD });
|
|
154
|
+
const PLAIN_VIEW = Object.freeze({ head: '' });
|
|
143
155
|
/** Packages that offer an engine or transport, for the fix of a missing one. */
|
|
144
156
|
const PROVIDERS = {
|
|
145
157
|
ejs: '@dokebi/template-ejs',
|
|
@@ -186,12 +198,14 @@ function realtimeHandle(app, namespace, sockets, streams) {
|
|
|
186
198
|
throw new AppError('INVALID_TARGET', 'Invalid presence listener');
|
|
187
199
|
return websocket().onPresence(listener);
|
|
188
200
|
},
|
|
189
|
-
publish: async (target, event, data) => {
|
|
201
|
+
publish: async (target, event, data, options) => {
|
|
190
202
|
if (!streams)
|
|
191
203
|
throw unavailable(app, 'realtime publish', 'sse');
|
|
192
204
|
const checked = checkTarget(target);
|
|
193
205
|
streamHandle ??= streams.handle(namespace);
|
|
194
|
-
return
|
|
206
|
+
return options === undefined
|
|
207
|
+
? streamHandle.publish(checked, event, data)
|
|
208
|
+
: streamHandle.publish(checked, event, data, options);
|
|
195
209
|
},
|
|
196
210
|
});
|
|
197
211
|
}
|
|
@@ -217,14 +231,35 @@ function requirement(value) {
|
|
|
217
231
|
/** A host without its port, lower case; IPv6 literals keep their brackets. */
|
|
218
232
|
export function withoutPort(host) {
|
|
219
233
|
const raw = host.toLowerCase();
|
|
220
|
-
if (raw.startsWith('['))
|
|
221
|
-
|
|
234
|
+
if (raw.startsWith('[')) {
|
|
235
|
+
// An unclosed bracket is no host: kept as it is, so it never reads as an empty Host.
|
|
236
|
+
const close = raw.indexOf(']');
|
|
237
|
+
return close < 0 ? raw : raw.slice(0, close + 1);
|
|
238
|
+
}
|
|
222
239
|
const colon = raw.lastIndexOf(':');
|
|
223
240
|
return colon === -1 ? raw : raw.slice(0, colon);
|
|
224
241
|
}
|
|
225
|
-
/**
|
|
242
|
+
/**
|
|
243
|
+
* A host as domains are matched: without the port and the one trailing dot of a fully qualified
|
|
244
|
+
* name (`a.com.` is `a.com`, as DNS reads it), lower case.
|
|
245
|
+
*/
|
|
246
|
+
function matchedHost(host) {
|
|
247
|
+
const bare = withoutPort(host);
|
|
248
|
+
return bare.endsWith('.') ? bare.slice(0, -1) : bare;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* What an unknown host must look like to be answered by `unknownDomain`: a host name (letters,
|
|
252
|
+
* digits, `.`, `-`, `_`), an IPv4 or a bracketed IPv6 literal, or nothing (HTTP/1.0). Any other
|
|
253
|
+
* Host header is no host (RFC 9110 §7.2) and never reaches an app as `page.app.domain`.
|
|
254
|
+
*/
|
|
255
|
+
const HOST_SYNTAX = /^(?:[a-z0-9_](?:[a-z0-9_.-]{0,251}[a-z0-9_])?|\[[0-9a-f:.]{2,45}\])?$/;
|
|
256
|
+
/**
|
|
257
|
+
* The Host header without port, or an HTTP/2 request's `:authority`, which stands for it, usually
|
|
258
|
+
* comes without a Host and wins when both are there (RFC 9113 §8.3.1; dokebi-web `requestHost`
|
|
259
|
+
* reads them in this order). Apps use `requestHost`, which honours trustProxy.
|
|
260
|
+
*/
|
|
226
261
|
export function hostOf(request) {
|
|
227
|
-
return withoutPort(String(request.headers.host ?? ''));
|
|
262
|
+
return withoutPort(String(request.headers[':authority'] ?? request.headers.host ?? ''));
|
|
228
263
|
}
|
|
229
264
|
/** The host entry of a request, kept on the raw request: the host is worked out once. */
|
|
230
265
|
const HOST_ENTRY = Symbol('dokebi.app.host');
|
|
@@ -295,6 +330,44 @@ class AppRuntime {
|
|
|
295
330
|
throw new AppError('NOT_REQUIRED', `Plugin ${name} is not declared by dokebi-app`);
|
|
296
331
|
return dependency;
|
|
297
332
|
}
|
|
333
|
+
/**
|
|
334
|
+
* R1 (user instruction 2026-10-28): an app's own browser files (CSS, images, fonts, scripts)
|
|
335
|
+
* live in `src/apps/<app>/public/`, next to its views, and answer `/assets/<path>` on the
|
|
336
|
+
* app's hosts through @dokebi/static (ETag, 304, Range, no listing, never outside the folder).
|
|
337
|
+
* R1 builders put them in views/ and served them with readFile routes of their own.
|
|
338
|
+
*/
|
|
339
|
+
async #servePublic(context, name, views) {
|
|
340
|
+
const base = views.href.endsWith('/') ? views : new URL(`${views.href}/`);
|
|
341
|
+
const folder = new URL('../public/', base);
|
|
342
|
+
try {
|
|
343
|
+
if (!(await stat(folder)).isDirectory())
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
catch (error) {
|
|
347
|
+
if (error?.code === 'ENOENT')
|
|
348
|
+
return;
|
|
349
|
+
throw error;
|
|
350
|
+
}
|
|
351
|
+
const root = fileURLToPath(folder);
|
|
352
|
+
const statics = context.getOptionalDependency(this.#declaredFor(files.name));
|
|
353
|
+
if (!statics) {
|
|
354
|
+
context.logger.log('warn', 'App public folder is not served', {
|
|
355
|
+
code: 'APP_PUBLIC_UNSERVED',
|
|
356
|
+
app: name,
|
|
357
|
+
folder: root,
|
|
358
|
+
fix: 'npx dokebi add @dokebi/static: it serves src/apps/<app>/public/ at /assets/ on the app hosts',
|
|
359
|
+
});
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
// A mount name is a letter, then letters and digits (D-0147).
|
|
363
|
+
const mount = `app${name.replace(/-/g, '')}`.slice(0, 32);
|
|
364
|
+
statics.mount(mount, { prefix: '/assets', root, app: name });
|
|
365
|
+
context.logger.log('debug', 'App public folder served', {
|
|
366
|
+
app: name,
|
|
367
|
+
prefix: '/assets',
|
|
368
|
+
mount,
|
|
369
|
+
});
|
|
370
|
+
}
|
|
298
371
|
#hosts = new Map();
|
|
299
372
|
#unknownHosts = 0;
|
|
300
373
|
/** AppInfo and seal flag of a host (without port), cached per host. */
|
|
@@ -326,8 +399,13 @@ class AppRuntime {
|
|
|
326
399
|
return this.entry(host)?.info;
|
|
327
400
|
}
|
|
328
401
|
#target(host) {
|
|
329
|
-
const
|
|
330
|
-
|
|
402
|
+
const configured = this.options.domains.get(host);
|
|
403
|
+
if (configured)
|
|
404
|
+
return configured;
|
|
405
|
+
const fallback = this.options.unknownDomain;
|
|
406
|
+
return fallback === undefined || !HOST_SYNTAX.test(host)
|
|
407
|
+
? undefined
|
|
408
|
+
: this.options.domains.get(fallback);
|
|
331
409
|
}
|
|
332
410
|
/** The host's `seal` flag (an unknown host answered by `unknownDomain` takes that entry's). */
|
|
333
411
|
sealed(host) {
|
|
@@ -340,7 +418,7 @@ class AppRuntime {
|
|
|
340
418
|
for (const app of this.options.apps.keys())
|
|
341
419
|
if (!this.apps.has(app))
|
|
342
420
|
throw new AppError('UNKNOWN_APP', `dokebi-app apps.${app} names an app that is not defined (defined: ${[...this.apps.keys()].join(', ') || 'none'})`);
|
|
343
|
-
const http = context.getDependency(web);
|
|
421
|
+
const http = context.getDependency(this.#declaredFor(web.name));
|
|
344
422
|
const logger = context.logger;
|
|
345
423
|
const sessions = context.getOptionalDependency(this.#declaredFor(session.name));
|
|
346
424
|
// D-0074 addendum 1: the flash of a request, taken once (every render of the request shares
|
|
@@ -362,17 +440,21 @@ class AppRuntime {
|
|
|
362
440
|
* D-0074 addendum 1: an HTML form (urlencoded or multipart body) refused with 422
|
|
363
441
|
* VALIDATION_FAILED goes back to the page it came from — `errors` and `old` flashed in the
|
|
364
442
|
* session, 303 to the Referer of this host — when the request has a session and a way back.
|
|
443
|
+
* So does any other 4xx whose `data.formErrors` asks for it (D-0076 §2.5: dokebi-csrf's
|
|
444
|
+
* expired token, `errors._form`; `formFieldErrors` of dokebi-web reads both).
|
|
365
445
|
* False otherwise: the error view (errors/422.ejs, errors/error.ejs) or dokebi-web's page.
|
|
366
446
|
*/
|
|
367
447
|
const formBack = async (response, app) => {
|
|
368
448
|
const { request, reply, status, body } = response;
|
|
369
|
-
if (status
|
|
449
|
+
if (status < 400 || status > 499 || !isFormSubmission(request.headers))
|
|
370
450
|
return false;
|
|
371
451
|
const errors = formFieldErrors(body);
|
|
372
452
|
if (!errors)
|
|
373
453
|
return false;
|
|
374
454
|
const current = sessionOf(request);
|
|
375
|
-
const target = current
|
|
455
|
+
const target = current
|
|
456
|
+
? formBackTarget(request, http.requestHost(request), undefined, http.formLimits)
|
|
457
|
+
: undefined;
|
|
376
458
|
if (!current || target === undefined) {
|
|
377
459
|
if (logger.isEnabled('debug'))
|
|
378
460
|
logger.log('debug', 'App form validation answered with the error view', {
|
|
@@ -384,7 +466,7 @@ class AppRuntime {
|
|
|
384
466
|
return false;
|
|
385
467
|
}
|
|
386
468
|
await current.flash('errors', errors);
|
|
387
|
-
const old = formOldInput(request.body);
|
|
469
|
+
const old = formOldInput(request.body, http.formLimits);
|
|
388
470
|
if (old)
|
|
389
471
|
await current.flash('old', old);
|
|
390
472
|
if (logger.isEnabled('debug'))
|
|
@@ -402,6 +484,11 @@ class AppRuntime {
|
|
|
402
484
|
// D-0063 §5: view engines and realtime transports by name, whoever contributes them.
|
|
403
485
|
const engines = byKey(context, viewEngines, 'name');
|
|
404
486
|
const transports = byKey(context, realtime, 'kind');
|
|
487
|
+
// D-0076 §5: what plugins add to every EJS page (dokebi-csrf `csrf`, dokebi-auth `auth`).
|
|
488
|
+
const pageData = collectViewData(context.collect(viewData), {
|
|
489
|
+
plugin: 'dokebi-app',
|
|
490
|
+
reserved: ['sealed', 'seal', 'errors', 'old', 'flash'],
|
|
491
|
+
});
|
|
405
492
|
const sockets = transports.get('websocket');
|
|
406
493
|
const streams = transports.get('sse');
|
|
407
494
|
const sealedDomains = [...this.options.domains]
|
|
@@ -417,6 +504,7 @@ class AppRuntime {
|
|
|
417
504
|
sealed: sealedDomains.length,
|
|
418
505
|
viewEngines: [...engines.keys()],
|
|
419
506
|
transports: [...transports.keys()],
|
|
507
|
+
viewData: pageData.keys,
|
|
420
508
|
});
|
|
421
509
|
// Fail closed (D-0059 §4): a sealed host without the seal plugin would talk plain text.
|
|
422
510
|
if (sealedDomains.length &&
|
|
@@ -430,10 +518,12 @@ class AppRuntime {
|
|
|
430
518
|
return found;
|
|
431
519
|
};
|
|
432
520
|
// Behind a trusted proxy (dokebi-web trustProxy) the forwarded host picks the app.
|
|
433
|
-
const host = (request) =>
|
|
521
|
+
const host = (request) => matchedHost(http.requestHost(request));
|
|
434
522
|
/** The host entry of a raw or Fastify request, worked out once per request. */
|
|
435
|
-
// Raw
|
|
436
|
-
// cut. Only when no X-Forwarded-Host is present (with one, trustProxy decides).
|
|
523
|
+
// Raw host header → entry, so the usual request skips trimming, lower-casing and the port
|
|
524
|
+
// cut. Only when no X-Forwarded-Host is present (with one, trustProxy decides). The key is
|
|
525
|
+
// the header requestHost reads then: `:authority` before Host (an HTTP/2 request may carry
|
|
526
|
+
// both, and a Host that differs must never file another app under its name). Client input:
|
|
437
527
|
// bounded like the unknown hosts.
|
|
438
528
|
const byHeader = new Map();
|
|
439
529
|
const hostEntry = (request) => {
|
|
@@ -441,7 +531,9 @@ class AppRuntime {
|
|
|
441
531
|
const known = raw[HOST_ENTRY];
|
|
442
532
|
if (known !== undefined)
|
|
443
533
|
return known;
|
|
444
|
-
const header = raw.headers['x-forwarded-host'] === undefined
|
|
534
|
+
const header = raw.headers['x-forwarded-host'] === undefined
|
|
535
|
+
? (raw.headers[':authority'] ?? raw.headers.host)
|
|
536
|
+
: undefined;
|
|
445
537
|
let entry = typeof header === 'string' ? byHeader.get(header) : undefined;
|
|
446
538
|
if (entry === undefined) {
|
|
447
539
|
entry = this.entry(host(request));
|
|
@@ -458,14 +550,29 @@ class AppRuntime {
|
|
|
458
550
|
// the Inertia page, SSE data), except routes with seal: false and dokebi-web sealExclude.
|
|
459
551
|
if (sealedDomains.length)
|
|
460
552
|
http.sealRequests((request) => hostEntry(request)?.sealed === true);
|
|
553
|
+
// D-0181: the app of a request's host, for plugins that answer per app (dokebi-i18n layers).
|
|
554
|
+
if (typeof http.requestApps === 'function')
|
|
555
|
+
http.requestApps((request) => hostEntry(request)?.info.name);
|
|
461
556
|
http.constraint({
|
|
462
557
|
name: APP_CONSTRAINT,
|
|
463
558
|
storage() {
|
|
464
559
|
const values = new Map();
|
|
465
560
|
return {
|
|
466
|
-
|
|
561
|
+
// A list (a plugin route bound to several apps, D-0132) is looked up by its apps.
|
|
562
|
+
get: (key) => (typeof key === 'string' ? (values.get(key) ?? null) : null),
|
|
467
563
|
set: (key, value) => {
|
|
468
|
-
|
|
564
|
+
if (typeof key === 'string') {
|
|
565
|
+
values.set(key, value);
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
// find-my-way keeps, per value, the bit mask of the handlers it matches, built by
|
|
569
|
+
// get → OR its bit → set. A list adds its handler's bits to each app's mask.
|
|
570
|
+
if (typeof value !== 'number')
|
|
571
|
+
throw new AppError('INVALID_DEFINITION', 'A route bound to several apps needs the bit mask store of find-my-way 9', {
|
|
572
|
+
fix: 'Report this with the installed fastify and find-my-way versions; bind the route to one app meanwhile.',
|
|
573
|
+
});
|
|
574
|
+
for (const app of key)
|
|
575
|
+
values.set(app, (values.get(app) ?? 0) | value);
|
|
469
576
|
},
|
|
470
577
|
};
|
|
471
578
|
},
|
|
@@ -479,6 +586,26 @@ class AppRuntime {
|
|
|
479
586
|
// Requests of a known app may still reach shared (unconstrained) routes.
|
|
480
587
|
mustMatchWhenDerived: false,
|
|
481
588
|
});
|
|
589
|
+
// D-0132: routes of other plugins bound to apps (`app` of a route, `<plugin>.app`) get this
|
|
590
|
+
// constraint from dokebi-web, checked against these names and hosts.
|
|
591
|
+
const domainsByApp = new Map();
|
|
592
|
+
for (const [domain, target] of this.options.domains) {
|
|
593
|
+
const list = domainsByApp.get(target.app);
|
|
594
|
+
if (list)
|
|
595
|
+
list.push(domain);
|
|
596
|
+
else
|
|
597
|
+
domainsByApp.set(target.app, [domain]);
|
|
598
|
+
}
|
|
599
|
+
const fallback = this.options.unknownDomain === undefined
|
|
600
|
+
? undefined
|
|
601
|
+
: this.options.domains.get(this.options.unknownDomain)?.app;
|
|
602
|
+
http.appRouting(Object.freeze({
|
|
603
|
+
constraint: APP_CONSTRAINT,
|
|
604
|
+
names: Object.freeze([...this.apps.keys()]),
|
|
605
|
+
domainApp: (domain) => this.options.domains.get(domain)?.app,
|
|
606
|
+
domainsOf: (app) => domainsByApp.get(app) ?? [],
|
|
607
|
+
fallback,
|
|
608
|
+
}));
|
|
482
609
|
/** The shared EJS renderer (the engine's own), loaded once on first need. */
|
|
483
610
|
let ejsRoot;
|
|
484
611
|
/** Each app's error answer (D-0074), by app name. */
|
|
@@ -495,7 +622,7 @@ class AppRuntime {
|
|
|
495
622
|
const namespaces = this.options.apps.get(name)?.namespaces ?? [name];
|
|
496
623
|
const handles = new Map();
|
|
497
624
|
/** The namespace an authenticated connection joins, or undefined (401) for one not listed. */
|
|
498
|
-
const namespaceOf = (wanted, kind, path) => {
|
|
625
|
+
const namespaceOf = (wanted, kind, path, routeId) => {
|
|
499
626
|
if (wanted === undefined)
|
|
500
627
|
return namespaces[0];
|
|
501
628
|
if (typeof wanted === 'string' && namespaces.includes(wanted))
|
|
@@ -505,14 +632,15 @@ class AppRuntime {
|
|
|
505
632
|
app: name,
|
|
506
633
|
kind,
|
|
507
634
|
path,
|
|
635
|
+
routeId,
|
|
508
636
|
namespace: typeof wanted === 'string' ? wanted.slice(0, 64) : null,
|
|
509
637
|
allowed: [...namespaces],
|
|
510
638
|
});
|
|
511
639
|
return undefined;
|
|
512
640
|
};
|
|
513
641
|
/** `identity` in the chosen namespace: tenant prefixed, `namespace` removed. */
|
|
514
|
-
const scoped = (kind, path) => (identity) => {
|
|
515
|
-
const chosen = namespaceOf(identity.namespace, kind, path);
|
|
642
|
+
const scoped = (kind, path, routeId) => (identity) => {
|
|
643
|
+
const chosen = namespaceOf(identity.namespace, kind, path, routeId);
|
|
516
644
|
if (chosen === undefined)
|
|
517
645
|
return undefined;
|
|
518
646
|
const { namespace: _namespace, ...rest } = identity;
|
|
@@ -576,6 +704,10 @@ class AppRuntime {
|
|
|
576
704
|
logger: context.logger,
|
|
577
705
|
signal: context.signal,
|
|
578
706
|
drainSignal: context.drainSignal,
|
|
707
|
+
// Set when the drain phase starts (a spread would freeze the value of setup time).
|
|
708
|
+
get drainDeadline() {
|
|
709
|
+
return context.drainDeadline;
|
|
710
|
+
},
|
|
579
711
|
get: appContext.get,
|
|
580
712
|
getDependency: appContext.getDependency,
|
|
581
713
|
getOptionalDependency: appContext.getOptionalDependency,
|
|
@@ -594,10 +726,14 @@ class AppRuntime {
|
|
|
594
726
|
}
|
|
595
727
|
else if (hasModuleViews && !ejsRoot)
|
|
596
728
|
ejsRoot = await engine('ejs', name).scope({});
|
|
729
|
+
if (definition.views)
|
|
730
|
+
await this.#servePublic(context, name, definition.views);
|
|
597
731
|
let inertiaApi;
|
|
598
732
|
if (definition.inertia) {
|
|
599
733
|
inertiaApi = await engine('inertia', name).scope({
|
|
600
734
|
...definition.inertia,
|
|
735
|
+
// Named in the scope's log records (INERTIA_VERSION_DEFAULT says which app).
|
|
736
|
+
app: name,
|
|
601
737
|
// SSR would write the props of a sealed host as plain HTML: refused (D-0062).
|
|
602
738
|
...(appSealed ? { sealed: true } : {}),
|
|
603
739
|
shared: (request) => {
|
|
@@ -625,16 +761,22 @@ class AppRuntime {
|
|
|
625
761
|
...appChain(template),
|
|
626
762
|
];
|
|
627
763
|
};
|
|
628
|
-
// `sealed
|
|
629
|
-
// shared data under the page data, computed once per
|
|
630
|
-
// its own `errors` and `old` and leaves the flash to the
|
|
631
|
-
|
|
764
|
+
// `sealed` and `seal` (D-0092), the session flash (`errors`, `old`, `flash`; D-0074
|
|
765
|
+
// addendum 1), the plugins' view data (D-0076 §5) and the app's shared data under the page data, computed once per
|
|
766
|
+
// render call. An error view passes its own `errors` and `old` and leaves the flash to the
|
|
767
|
+
// next page.
|
|
768
|
+
const withShared = (view, request, info, sealed, pageFlash = true,
|
|
769
|
+
/** The view data of plugins and the app's `shared` (false for a 503 error view, D-0102). */
|
|
770
|
+
withData = true) => {
|
|
632
771
|
const data = async (own) => {
|
|
633
772
|
const taken = (pageFlash ? await flashOf(request) : undefined) ?? viewFlash(undefined);
|
|
634
773
|
const result = {
|
|
635
774
|
sealed,
|
|
775
|
+
// D-0092 §1.5: the layout's `<%- data.seal.head %>` (empty on a plain host).
|
|
776
|
+
seal: sealed ? SEALED_VIEW : PLAIN_VIEW,
|
|
636
777
|
...taken,
|
|
637
|
-
...(await
|
|
778
|
+
...(withData && pageData.keys.length ? await pageData.values(request) : undefined),
|
|
779
|
+
...(withData ? await definition.shared?.(request, { app: info }) : undefined),
|
|
638
780
|
...own,
|
|
639
781
|
};
|
|
640
782
|
// The handler's own `errors` and `old` win field by field.
|
|
@@ -706,21 +848,26 @@ class AppRuntime {
|
|
|
706
848
|
});
|
|
707
849
|
};
|
|
708
850
|
/** The scope of one realtime route: the full path, the app constraint and tenant rule. */
|
|
709
|
-
const scopeOf = (
|
|
710
|
-
path,
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
:
|
|
717
|
-
|
|
851
|
+
const scopeOf = (route, base, kind) => {
|
|
852
|
+
const path = joinPath(base, route.path);
|
|
853
|
+
// D-0140: the route id, for the refusal log; the transport hands `config` to dokebi-web.
|
|
854
|
+
const id = route.config?.id;
|
|
855
|
+
return Object.freeze({
|
|
856
|
+
path,
|
|
857
|
+
constraints: Object.freeze({ [APP_CONSTRAINT]: name }),
|
|
858
|
+
identity: scoped(kind, path, typeof id === 'string' ? id : null),
|
|
859
|
+
// The request's host decides (D-0059 §4); only when a host of this app seals.
|
|
860
|
+
...(appSealed
|
|
861
|
+
? { seal: (request) => hostEntry(request)?.sealed === true }
|
|
862
|
+
: {}),
|
|
863
|
+
});
|
|
864
|
+
};
|
|
718
865
|
const mountSockets = (routes, base, owner) => {
|
|
719
866
|
for (const route of routes) {
|
|
720
867
|
if (!sockets)
|
|
721
868
|
throw new AppError('REALTIME_UNAVAILABLE', `${owner} has sockets; add @dokebi/websocket`);
|
|
722
869
|
socketCount++;
|
|
723
|
-
sockets.mount(route, scopeOf(
|
|
870
|
+
sockets.mount(route, scopeOf(route, base, 'socket'));
|
|
724
871
|
}
|
|
725
872
|
};
|
|
726
873
|
const mountEvents = (routes, base, owner) => {
|
|
@@ -728,7 +875,7 @@ class AppRuntime {
|
|
|
728
875
|
if (!streams)
|
|
729
876
|
throw new AppError('REALTIME_UNAVAILABLE', `${owner} has event streams; add @dokebi/sse`);
|
|
730
877
|
eventCount++;
|
|
731
|
-
streams.mount(route, scopeOf(
|
|
878
|
+
streams.mount(route, scopeOf(route, base, 'stream'));
|
|
732
879
|
}
|
|
733
880
|
};
|
|
734
881
|
// D-0074 §3-4: the error answers of this app's hosts. Inertia first (the validation
|
|
@@ -762,7 +909,16 @@ class AppRuntime {
|
|
|
762
909
|
if (!page)
|
|
763
910
|
return false;
|
|
764
911
|
const fields = Array.isArray(body.fields) ? body.fields : [];
|
|
765
|
-
|
|
912
|
+
// D-0102: a 503 (a store, database or Redis down or overloaded) renders from the error
|
|
913
|
+
// alone: the view data (auth, csrf, i18n) and `shared` may read the store that failed.
|
|
914
|
+
const bare = status === 503;
|
|
915
|
+
if (bare && logger.isEnabled('debug'))
|
|
916
|
+
logger.log('debug', 'App error view without view data', {
|
|
917
|
+
app: name,
|
|
918
|
+
view: page,
|
|
919
|
+
status,
|
|
920
|
+
});
|
|
921
|
+
await withShared(view, request, info, sealed, false, !bare).reply(reply, page, {
|
|
766
922
|
status,
|
|
767
923
|
title: `${status} ${STATUS_CODES[status] ?? 'Error'}`,
|
|
768
924
|
error: body.error,
|
|
@@ -772,7 +928,7 @@ class AppRuntime {
|
|
|
772
928
|
// A refused form without a way back (no session, no Referer of this host): an
|
|
773
929
|
// errors/422.ejs can show the form again with these (D-0074 addendum 1).
|
|
774
930
|
errors: formFieldErrors(body) ?? {},
|
|
775
|
-
old: (status === 422 && formOldInput(request.body)) || {},
|
|
931
|
+
old: (status === 422 && formOldInput(request.body, http.formLimits)) || {},
|
|
776
932
|
// Development only (dokebi-web already cut `fix` from a production body).
|
|
777
933
|
fix: typeof body.fix === 'string' ? body.fix : null,
|
|
778
934
|
stack: !production && status >= 500 && error instanceof Error ? (error.stack ?? null) : null,
|
|
@@ -826,9 +982,60 @@ class AppRuntime {
|
|
|
826
982
|
const answer = entry ? answers.get(entry.info.name) : undefined;
|
|
827
983
|
return entry && answer ? answer(response, entry) : false;
|
|
828
984
|
});
|
|
985
|
+
// D-0077 B: only `dokebi describe` (runtime.describing) asks; a normal start adds nothing.
|
|
986
|
+
if (context.runtime.describing)
|
|
987
|
+
this.#describe(context);
|
|
829
988
|
return Object.freeze({
|
|
830
989
|
names: Object.freeze([...this.apps.keys()]),
|
|
831
990
|
resolve: (request) => hostEntry(request)?.info,
|
|
991
|
+
seal: (request) => hostEntry(request)?.sealed === true ? SEALED_VIEW : PLAIN_VIEW,
|
|
992
|
+
});
|
|
993
|
+
}
|
|
994
|
+
/** The apps, domains and pages of describe mode (D-0077 B), read once when asked. */
|
|
995
|
+
#describe(context) {
|
|
996
|
+
let read;
|
|
997
|
+
const described = () => {
|
|
998
|
+
read ??= (async () => {
|
|
999
|
+
const apps = [];
|
|
1000
|
+
const pages = [];
|
|
1001
|
+
for (const [name, definition] of this.apps) {
|
|
1002
|
+
const found = await appPages(name, definition.views, definition.inertia !== undefined);
|
|
1003
|
+
pages.push(...found.pages);
|
|
1004
|
+
apps.push({
|
|
1005
|
+
name,
|
|
1006
|
+
engine: definition.inertia ? 'inertia' : definition.views ? 'ejs' : null,
|
|
1007
|
+
views: found.folder,
|
|
1008
|
+
templates: found.templates,
|
|
1009
|
+
modules: Object.entries(definition.modules ?? {}).map(([prefix, plugin]) => ({
|
|
1010
|
+
prefix,
|
|
1011
|
+
module: mountOf(plugin)?.name ?? plugin.metadata.name,
|
|
1012
|
+
})),
|
|
1013
|
+
requires: (definition.requires ?? []).map((item) => requirement(item).name),
|
|
1014
|
+
namespaces: [...(this.options.apps.get(name)?.namespaces ?? [name])],
|
|
1015
|
+
});
|
|
1016
|
+
}
|
|
1017
|
+
return { apps, pages };
|
|
1018
|
+
})();
|
|
1019
|
+
return read;
|
|
1020
|
+
};
|
|
1021
|
+
context.contribute(describePoint, {
|
|
1022
|
+
section: 'app',
|
|
1023
|
+
describe: async () => ({
|
|
1024
|
+
// Routes of an app carry this Fastify constraint with the app's name.
|
|
1025
|
+
constraint: APP_CONSTRAINT,
|
|
1026
|
+
apps: (await described()).apps,
|
|
1027
|
+
domains: [...this.options.domains].map(([host, target]) => ({
|
|
1028
|
+
host,
|
|
1029
|
+
app: target.app,
|
|
1030
|
+
template: target.template,
|
|
1031
|
+
seal: target.seal,
|
|
1032
|
+
})),
|
|
1033
|
+
unknownDomain: this.options.unknownDomain ?? 'reject',
|
|
1034
|
+
}),
|
|
1035
|
+
});
|
|
1036
|
+
context.contribute(describePoint, {
|
|
1037
|
+
section: 'pages',
|
|
1038
|
+
describe: async () => (await described()).pages,
|
|
832
1039
|
});
|
|
833
1040
|
}
|
|
834
1041
|
/** Every template a domain selects must exist as a folder, and `default` always must. */
|
|
@@ -863,7 +1070,8 @@ class AppRuntime {
|
|
|
863
1070
|
}
|
|
864
1071
|
}
|
|
865
1072
|
async drain() {
|
|
866
|
-
|
|
1073
|
+
// Every app drains; each failure reaches the stop (Promise.all kept only the first, D-0047).
|
|
1074
|
+
const results = await Promise.allSettled(this.#mounted.map(async ({ name, definition, context }) => {
|
|
867
1075
|
if (!definition.drain)
|
|
868
1076
|
return;
|
|
869
1077
|
const begin = performance.now();
|
|
@@ -873,6 +1081,15 @@ class AppRuntime {
|
|
|
873
1081
|
ms: Math.round(performance.now() - begin),
|
|
874
1082
|
});
|
|
875
1083
|
}));
|
|
1084
|
+
const failed = [];
|
|
1085
|
+
results.forEach((result, index) => {
|
|
1086
|
+
if (result.status === 'rejected')
|
|
1087
|
+
failed.push({ app: this.#mounted[index]?.name ?? 'unknown', reason: result.reason });
|
|
1088
|
+
});
|
|
1089
|
+
if (failed.length === 1)
|
|
1090
|
+
throw failed[0]?.reason;
|
|
1091
|
+
if (failed.length)
|
|
1092
|
+
throw new AggregateError(failed.map((failure) => failure.reason), `Drain of apps ${failed.map((failure) => failure.app).join(', ')} failed`);
|
|
876
1093
|
}
|
|
877
1094
|
}
|
|
878
1095
|
function missingViews(name) {
|
|
@@ -889,26 +1106,136 @@ function missingViews(name) {
|
|
|
889
1106
|
}
|
|
890
1107
|
export const createPlugin = definePlugin({
|
|
891
1108
|
name: 'dokebi-app',
|
|
892
|
-
version: '0.4.
|
|
1109
|
+
version: '0.4.5',
|
|
893
1110
|
core: '^0.4.0',
|
|
894
1111
|
options: declaration,
|
|
895
1112
|
entry: parseEntry,
|
|
896
1113
|
// Template and realtime plugins are found through these points, not by name (D-0063 §5).
|
|
897
|
-
collects: [viewEngines, realtime],
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
const list = [web, seal, session];
|
|
901
|
-
for (const app of apps)
|
|
902
|
-
for (const item of [...(app.requires ?? []), ...Object.values(app.modules ?? {})]) {
|
|
903
|
-
const dependency = requirement(item);
|
|
904
|
-
const index = list.findIndex((existing) => existing.name === dependency.name);
|
|
905
|
-
if (index === -1)
|
|
906
|
-
list.push(dependency);
|
|
907
|
-
// An app that requires an optional provider (session, seal) makes it required.
|
|
908
|
-
else if (list[index]?.optional && !dependency.optional)
|
|
909
|
-
list[index] = dependency;
|
|
910
|
-
}
|
|
911
|
-
return list;
|
|
912
|
-
},
|
|
1114
|
+
collects: [viewEngines, realtime, viewData],
|
|
1115
|
+
contributes: [describePoint],
|
|
1116
|
+
dependencies: ({ entry }) => mergeRequirements(entry ?? new Map()),
|
|
913
1117
|
instance: ({ options, entry, dependencies }) => new AppRuntime(settings(options), entry ?? new Map(), dependencies),
|
|
914
1118
|
});
|
|
1119
|
+
/**
|
|
1120
|
+
* Core takes one requirement per plugin name, so the requirements of every app (and dokebi-app's
|
|
1121
|
+
* own web, seal and session) are merged per name (ISSUE-0006 A12): the version is the semver AND
|
|
1122
|
+
* of every distinct range (`andRanges`: satisfied by exactly the versions that satisfy each app's
|
|
1123
|
+
* range, prerelease rules included, so core's check is the check of every app), the result is optional only when every consumer is optional, and the factory (`create`) of the
|
|
1124
|
+
* first consumer that has one is kept. Ranges that cannot meet are refused here, before start,
|
|
1125
|
+
* with `DEPENDENCY_CONFLICT` naming the apps: no provider version could satisfy both.
|
|
1126
|
+
*/
|
|
1127
|
+
function mergeRequirements(apps) {
|
|
1128
|
+
const needs = new Map();
|
|
1129
|
+
const add = (consumer, dependency) => {
|
|
1130
|
+
if (!validRange(dependency.version))
|
|
1131
|
+
throw new AppError('INVALID_DEFINITION', `${consumer === 'dokebi-app' ? 'dokebi-app' : `App ${consumer}`} requires ${dependency.name} with an invalid version range: ${JSON.stringify(dependency.version)}`);
|
|
1132
|
+
const list = needs.get(dependency.name);
|
|
1133
|
+
if (list)
|
|
1134
|
+
list.push({ consumer, dependency });
|
|
1135
|
+
else
|
|
1136
|
+
needs.set(dependency.name, [{ consumer, dependency }]);
|
|
1137
|
+
};
|
|
1138
|
+
for (const dependency of [web, seal, session, files])
|
|
1139
|
+
add('dokebi-app', dependency);
|
|
1140
|
+
for (const [name, app] of apps)
|
|
1141
|
+
for (const item of [...(app.requires ?? []), ...Object.values(app.modules ?? {})])
|
|
1142
|
+
add(name, requirement(item));
|
|
1143
|
+
const merged = [];
|
|
1144
|
+
for (const [name, list] of needs) {
|
|
1145
|
+
const first = list[0];
|
|
1146
|
+
const ranges = [];
|
|
1147
|
+
// The AND of every distinct range; `||` alternatives are combined pairwise (andRanges).
|
|
1148
|
+
let combined = '';
|
|
1149
|
+
for (const need of list) {
|
|
1150
|
+
if (ranges.includes(need.dependency.version))
|
|
1151
|
+
continue;
|
|
1152
|
+
const next = ranges.length
|
|
1153
|
+
? andRanges(combined, need.dependency.version)
|
|
1154
|
+
: need.dependency.version;
|
|
1155
|
+
if (!next) {
|
|
1156
|
+
// Name the consumer it clashes with; when only the combination fails, name them all.
|
|
1157
|
+
const earlier = list.slice(0, list.indexOf(need));
|
|
1158
|
+
const clash = earlier.find((other) => !andRanges(other.dependency.version, need.dependency.version));
|
|
1159
|
+
const others = clash ? [clash] : earlier;
|
|
1160
|
+
throw new AppError('DEPENDENCY_CONFLICT', `No version of ${name} satisfies both ${others.map(label).join(' and ')} and ${label(need)}`, {
|
|
1161
|
+
details: {
|
|
1162
|
+
plugin: name,
|
|
1163
|
+
needs: list.map((each) => ({
|
|
1164
|
+
consumer: each.consumer,
|
|
1165
|
+
version: each.dependency.version,
|
|
1166
|
+
optional: each.dependency.optional === true,
|
|
1167
|
+
})),
|
|
1168
|
+
},
|
|
1169
|
+
});
|
|
1170
|
+
}
|
|
1171
|
+
ranges.push(need.dependency.version);
|
|
1172
|
+
combined = next;
|
|
1173
|
+
}
|
|
1174
|
+
const optional = list.every((need) => need.dependency.optional);
|
|
1175
|
+
const create = list.find((need) => need.dependency.create)?.dependency.create;
|
|
1176
|
+
// One consumer, or all the same: keep the descriptor object itself.
|
|
1177
|
+
const same = list.every((need) => need.dependency.version === first.dependency.version &&
|
|
1178
|
+
Boolean(need.dependency.optional) === optional);
|
|
1179
|
+
if (same && (first.dependency.create || !create)) {
|
|
1180
|
+
merged.push(first.dependency);
|
|
1181
|
+
continue;
|
|
1182
|
+
}
|
|
1183
|
+
merged.push(Object.freeze({
|
|
1184
|
+
name,
|
|
1185
|
+
version: combined,
|
|
1186
|
+
...(optional ? { optional: true } : {}),
|
|
1187
|
+
...(create ? { create } : {}),
|
|
1188
|
+
}));
|
|
1189
|
+
}
|
|
1190
|
+
return merged;
|
|
1191
|
+
}
|
|
1192
|
+
/**
|
|
1193
|
+
* The semver AND of two ranges, `||` included: every pair of alternatives (comparator sets)
|
|
1194
|
+
* joined with a space, unsatisfiable pairs left out. Joining whole ranges with a space is wrong
|
|
1195
|
+
* for `||` (`^1 || ^2` and `^2` would read as `^1 || (^2 ^2)` and accept 1.x; ISSUE-0006 recheck).
|
|
1196
|
+
* An empty string: no version satisfies both.
|
|
1197
|
+
*
|
|
1198
|
+
* Joining two sets must also keep each side's prerelease rule (ISSUE-0006 recheck R03): semver
|
|
1199
|
+
* admits a prerelease only when a comparator of its set carries a prerelease of the same
|
|
1200
|
+
* major.minor.patch, so a joined set would let one side's `>=1.1.0-beta.1` admit `1.1.0-beta.2`
|
|
1201
|
+
* for a side (`>=1.0.0 <2.0.0`) that refuses it. A prerelease comparator whose major.minor.patch
|
|
1202
|
+
* is not carried by both sides is therefore written as its release form (`>=X-p` and `>X-p` as
|
|
1203
|
+
* `>=X`, `<X-p` and `<=X-p` as `<X`, `=X-p` as no version): the same answer for every version
|
|
1204
|
+
* outside X, and no prerelease of X is admitted any more. The result is satisfied by exactly the
|
|
1205
|
+
* versions that satisfy both `a` and `b` (default semver options, as core checks).
|
|
1206
|
+
*/
|
|
1207
|
+
export function andRanges(a, b) {
|
|
1208
|
+
const parts = [];
|
|
1209
|
+
for (const left of new Range(a).set)
|
|
1210
|
+
for (const right of new Range(b).set) {
|
|
1211
|
+
const theirs = prereleaseTuples(right);
|
|
1212
|
+
const both = [...prereleaseTuples(left)].filter((tuple) => theirs.has(tuple));
|
|
1213
|
+
const comparators = [];
|
|
1214
|
+
let possible = true;
|
|
1215
|
+
for (const comparator of [...left, ...right]) {
|
|
1216
|
+
if (!comparator.value)
|
|
1217
|
+
continue; // `*`
|
|
1218
|
+
const version = comparator.semver;
|
|
1219
|
+
const tuple = `${version.major}.${version.minor}.${version.patch}`;
|
|
1220
|
+
if (!version.prerelease.length || both.includes(tuple))
|
|
1221
|
+
comparators.push(comparator.value);
|
|
1222
|
+
else if (comparator.operator === '>=' || comparator.operator === '>')
|
|
1223
|
+
comparators.push(`>=${tuple}`);
|
|
1224
|
+
else if (comparator.operator === '<' || comparator.operator === '<=')
|
|
1225
|
+
comparators.push(`<${tuple}`);
|
|
1226
|
+
else
|
|
1227
|
+
possible = false; // exactly one prerelease the other side never admits
|
|
1228
|
+
}
|
|
1229
|
+
const combo = comparators.join(' ') || '*';
|
|
1230
|
+
if (possible && minVersion(combo) !== null && !parts.includes(combo))
|
|
1231
|
+
parts.push(combo);
|
|
1232
|
+
}
|
|
1233
|
+
return parts.join(' || ');
|
|
1234
|
+
}
|
|
1235
|
+
/** The major.minor.patch of every prerelease comparator in one comparator set. */
|
|
1236
|
+
function prereleaseTuples(set) {
|
|
1237
|
+
return new Set(set
|
|
1238
|
+
.filter((comparator) => comparator.value && comparator.semver.prerelease.length)
|
|
1239
|
+
.map(({ semver: v }) => `${v.major}.${v.minor}.${v.patch}`));
|
|
1240
|
+
}
|
|
1241
|
+
const label = (need) => `${need.consumer === 'dokebi-app' ? 'dokebi-app' : `app ${need.consumer}`} (${need.dependency.version})`;
|