@dokebi/module 0.4.4 → 0.4.6

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 CHANGED
@@ -52,7 +52,7 @@ export default defineModule({
52
52
  });
53
53
  ```
54
54
 
55
- - `module` (ModuleContext) = PluginContext + `module` (the name) + `controller(token)`. Only what `requires` declares can be read with `get` or `getDependency`. When a controller factory passes a freshly built descriptor object, the declared descriptor with that name is found.
55
+ - `module` (ModuleContext) = PluginContext + `module` (the name) + `controller(token)` + `enabled()` (the switch, §2b). Only what `requires` declares can be read with `get` or `getDependency`. When a controller factory passes a freshly built descriptor object, the declared descriptor with that name is found.
56
56
  - `page` (ModulePage) = `{ app: { name, template, domain }, module, base, view, inertia }`. Build links with `page.base` (each app may use a different prefix).
57
57
  - `version` is an exact semver (default `'0.1.0'`). Requires with duplicate names are refused.
58
58
  - `views`: adds a template-ejs dependency automatically; the start fails without `views/default/`. Template names get the prefix `module.<name>`.
@@ -61,6 +61,73 @@ export default defineModule({
61
61
  - Route options are `WebRoute` options without `handler` and `constraints` (`ModuleRouteOptions`, so `seal` works).
62
62
  - `contributes`: the points of other plugins this module contributes to (§3a). Without it `module.contribute` is `UNDECLARED_POINT`.
63
63
 
64
+ ## 2a. Pages for each audience: named sets (0.4.5)
65
+
66
+ One feature often has pages for several audiences: a board has the members' list and writing, and the operators' moderation. Keep them in **one module** and declare its routes as **named sets**; each app says which set it shows when it mounts the module ([D-0216](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0216-module-sets.md)).
67
+
68
+ ```ts snippet
69
+ import { defineModule } from '@dokebi/module';
70
+ import { Posts } from './services/posts.ts';
71
+
72
+ const posts = new Posts();
73
+
74
+ export default defineModule({
75
+ name: 'board',
76
+ views: new URL('./views/', import.meta.url), // views/default/site/…, views/default/admin/…
77
+ routes: {
78
+ site(route) { // members, resellers: the list and writing
79
+ route.get('/', (request, reply, page) => page.view.reply(reply, 'site/list', { posts: posts.visible() }));
80
+ route.post('/', (request) => posts.write((request.body as { title: string }).title));
81
+ },
82
+ admin(route) { // operators: moderation
83
+ route.get('/', (request, reply, page) => page.view.reply(reply, 'admin/manage', { posts: posts.all() }));
84
+ route.post('/:id/hide', (request) => posts.hide(Number((request.params as { id: string }).id)));
85
+ },
86
+ },
87
+ sockets: { admin: () => [] }, // sockets and events take the same sets
88
+ });
89
+ ```
90
+
91
+ The apps (@dokebi/app 0.4.8 or later):
92
+
93
+ ```ts snippet
94
+ import { defineApp } from '@dokebi/app';
95
+ import board from '../../shared/modules/board/module.ts';
96
+
97
+ export const member = defineApp({ modules: { '/board': { module: board, use: 'site' } } });
98
+ export const admin = defineApp({ modules: { '/board': { module: board, use: 'admin' }, '/preview': { module: board, use: 'site' } } });
99
+ ```
100
+
101
+ - **A set an app does not choose is not a route, socket or event stream of that app**: the moderation page is not a route of the member site (404, and absent from its route table and from `npx dokebi describe`). Never guard pages by `page.app.name` instead: every page would be a route of every app, and one forgotten check opens it.
102
+ - **One shape for the three hooks**: `routes`, `sockets` and `events` are all functions (the module is mounted whole, as before) or all named sets; a hook may leave a set out (`sockets: { admin }` only). Set names are lower-case (`a-z`, `0-9`, `.`, `_`, `-`), 1 to 16 per hook (`INVALID_DEFINITION`).
103
+ - **The app chooses**: `{ module, use: 'admin' }` or `use: ['site', 'admin']` (both in one mount, in that order). A module of sets mounted whole, an unknown set, an empty or repeated choice and `use` on a module without sets fail `defineApp` (`INVALID_DEFINITION` of @dokebi/app). One app may mount two sets of one module at two prefixes; route ids must still be unique in the app, so give each set's routes ids of their own.
104
+ - **One module, one service**: every set runs in the same module context, with the same controllers, views folder and `setup` API. Lay the views out per set (`views/default/site/list.ejs`) and render `'site/list'`. App overrides work as for any module page (`src/apps/<app>/views/<template>/board/site/list.ejs`).
105
+ - **An older app package**: an @dokebi/app before 0.4.8 does not know sets; mounting a module of sets there fails the start with `INVALID_DEFINITION` (`fix`: update @dokebi/app) instead of mounting nothing.
106
+ - **Splitting instead**: a feature can also be one module per audience over a shared core module (`requires: [boardCore]`). It works with any version, at the cost of a folder and a module per audience; prefer sets when the audiences share one service.
107
+
108
+ ## 2b. Switching a module on and off while the app runs (0.4.5)
109
+
110
+ An instance may run a feature or not, decided while it runs (the center switches modules per tenant instance). Give the module `enabled`; it is asked on every request to the module's routes, sockets and event streams, in every app that mounts it.
111
+
112
+ ```ts snippet
113
+ import { defineModule } from '@dokebi/module';
114
+ import { dependency as settings } from '@dokebi/runtime-settings/dependency';
115
+
116
+ export default defineModule({
117
+ name: 'board',
118
+ requires: [settings],
119
+ // Synchronous, from memory: runtime-settings keeps its values in every worker and refreshes them.
120
+ enabled: (module) => module.getDependency(settings).get<string[]>('modules.enabled').includes('board'),
121
+ routes: { site(route) { /* … */ }, admin(route) { /* … */ } },
122
+ });
123
+ ```
124
+
125
+ - **Off** means: the module's routes answer the 404 of an unknown path of that app (its own `errors/404` page for a browser, the JSON 404 otherwise), as their **first step**: before login checks, body parsing and the route's own hooks. New WebSocket upgrades and SSE streams of the module are 404 too. `enabled` returns true again and they answer again, without a restart.
126
+ - **What it does not close**: a WebSocket or an SSE stream opened while the module was on stays open; background work of the module (job handlers, event subscriptions, timers) and its API to other modules (`get(board)`) keep running. The module reads `module.enabled()` itself where that work must stop.
127
+ - **Synchronous and cheap**: it runs per request. Read a value in memory (a @dokebi/runtime-settings `get`, an option), never a database. A throw, a value that is not a boolean and a Promise count as **off** and are logged at error once per window (`MODULE_SWITCH_FAILED`); a change seen between two requests is logged once at info (`MODULE_SWITCHED_OFF`, `MODULE_SWITCHED_ON`). Before the module has set up it is off.
128
+ - **Menus and permission lists**: `modules()` of the group plugin (`createPlugin({ app, entry: { modules } })`, the API of `dokebi-module`) answers `[{ name, enabled }]` now; `module.enabled()` answers for one module. An app builds its menu from them so a switched-off feature leaves the menu too.
129
+ - A module without `enabled` is always on, as before. The switch works with or without named sets; with sets it closes every set of the module in every app at once.
130
+
64
131
  ## 3. Mounting on apps and shared APIs
65
132
 
66
133
  - App: `defineApp({ modules: { '/board': board } })`. Routes, sockets and SSE routes answer **only on that app's domains and prefix**. Several apps can mount the same module under different prefixes. The root route (`'/'`) answers `/board` and `/board/`; other paths match exactly. Build links with `page.base` (for example `${page.base}/new`).
@@ -107,24 +174,35 @@ export default defineModule({
107
174
  5. the app's views (layouts and partials)
108
175
  6. shared `src/shared/views`
109
176
 
110
- To change a module page, an app never edits the module file; it puts a file with the same name into `src/apps/<app>/views/<template>/<module>/`. When an Inertia app mounts the module, the module produces props with `page.inertia.render(request, reply, 'Component', props)` and the Vue pages live in the app's `views/<template>/Pages/`.
177
+ To change a module page, an app never edits the module file; it puts a file with the same name into `src/apps/<app>/views/<template>/<module>/`.
178
+
179
+ ### 4a. Inertia (Vue) pages of a module (D-0218, @dokebi/module 0.4.6, @dokebi/app 0.4.9, @dokebi/template-inertia 0.4.8)
180
+
181
+ A module keeps its Vue pages in its own views folder, beside its EJS views: `views/<template>/Pages/**/*.vue` (`views/default/` is still required). They travel with the module, and an app that does not mount the module (or a set of it) does not carry them.
182
+
183
+ - **Name**: a page is named after the module: the module renders `page.inertia.render(request, reply, 'board/List', props)` and the file is `<module>/views/<template>/Pages/List.vue`. Components the pages import with a relative path (`../components/Row.vue`) come along.
184
+ - **Lookup** (the same order as the EJS views above): the app's `views/<template>/Pages/board/List.vue`, the app's `views/default/Pages/board/List.vue`, the module's `views/<template>/Pages/List.vue`, the module's `views/default/Pages/List.vue`. To change a module page an app puts a file of the same name under its own `Pages/<module>/`. A module page the app overrides in `default` is left out of the app's bundle.
185
+ - **Sets** (§2a): in a module of named sets, the first folder under `Pages/` that names a set holds that set's pages (`Pages/site/List.vue` is `board/site/List`); an app bundles only the sets it mounts. Other files under `Pages/` belong to every app that mounts the module.
186
+ - **Build**: `dokebiInertia()` of `@dokebi/template-inertia/vite` writes `virtual:dokebi/module-pages` for each app's `views/app.js` and `views/ssr.js`: it imports the app's `app.ts` and reads the views folders of the modules in its `modules`. The files `dokebi app add --inertia` writes (@dokebi/app 0.4.9) use it; an older `app.js` and `ssr.js` look up the app's own pages only, and `npx dokebi doctor` names them (`TEMPLATE_FIX_MISSING`, `module-pages`). `vite.ssr.config.ts` needs `dokebiInertia()` as well (`module-pages-plugin`).
187
+ - **Switch** (§2b): a switched-off module answers 404, so its pages are not reachable; they stay in the build (a running bundle cannot drop files). An app that should never carry them does not mount the module.
188
+ - `dokebi dev` reloads the browser when a page is added to or removed from a module folder; a change to `app.ts` (a module mounted or removed) is read again too.
111
189
 
112
190
  ## 5. Group plugin and lifecycle
113
191
 
114
- - `createPlugin({ app, entry: { modules } })`: groups several modules into a dependency graph. The API is `{ names }` (`ModuleGroupApi`). It accepts only what `defineModule` made; duplicates are `INVALID_PLUGIN_INPUT`. A single module may also be registered directly with `app.register`.
192
+ - `createPlugin({ app, entry: { modules } })`: groups several modules into a dependency graph. The API is `{ names, modules() }` (`ModuleGroupApi`; `modules()` lists each module with its switch, §2b). It accepts only what `defineModule` made; duplicates are `INVALID_PLUGIN_INPUT`. A single module may also be registered directly with `app.register`.
115
193
  - Hooks: setup (register routes, return the API) → start → drain (stop new input, wait for work in progress) → deferred cleanup. Drain runs in reverse dependency order (modules that depend on this one first); unrelated modules drain at the same time.
116
194
  - A module instance is used by one Application only. There is no automatic discovery, dynamic import or hot reload while running.
117
195
  - Options of the group plugin are an empty object.
118
- - Debug logs (D-0047): `Modules registered` (the group), `Module set up` (requires, number of controllers, contributes, views prefix, whether routes, sockets and events exist, ms), `Module start finished`, `Module drain finished`. A missing or unreadable `views/default/` fails the start, with the original file error kept as `cause`.
196
+ - Debug logs (D-0047): `Modules registered` (the group), `Module set up` (requires, number of controllers, contributes, views prefix, whether routes, sockets and events exist, `sets`, `switch`, ms), `Module start finished`, `Module drain finished`. A missing or unreadable `views/default/` fails the start, with the original file error kept as `cause`.
119
197
 
120
198
  ## 6. Errors
121
199
 
122
200
  <!-- docs-check: complete-error-codes ModuleErrorCode -->
123
- `DokebiError` (`plugin: 'dokebi-module'`, a `fix` that says how to repair it): `INVALID_DEFINITION` (arguments of `defineModule`), `INVALID_REQUIREMENT` (shape of requires, duplicate names), `INVALID_ENTRY` (the group entry file; at registration the cause of `INVALID_PLUGIN_INPUT`), `ALREADY_SET_UP` (one instance in two apps), `NOT_SET_UP` (context used before setup), `NO_CONTROLLERS`, `VIEWS_MISSING` (no `views/default/`; the file error is the `cause`), `INVALID_CONTRIBUTION` (`contributes` is not a list of distinct points made by `definePoint`, or has more than 64), `UNDECLARED_POINT` (`module.contribute` to a point missing from `contributes`, or `module.collect`; the `fix` names the module). Warn log `POINT_NOT_COLLECTED` (core): values no registered plugin collects were dropped. Options of the group plugin other than an empty object are `INVALID_PLUGIN_OPTIONS` (cause `INVALID_OPTIONS`). The `defineOptions` declaration in `src/options.ts` is the parser, and the build writes `options.schema.json` from it (D-0063 §3; never edit it by hand). Before 0.4.0 the codes had a `MODULE_` prefix (D-0071).
201
+ `DokebiError` (`plugin: 'dokebi-module'`, a `fix` that says how to repair it): `INVALID_DEFINITION` (arguments of `defineModule`, named sets outside their rule, a module of sets mounted by an app package that does not know sets), `INVALID_REQUIREMENT` (shape of requires, duplicate names), `INVALID_ENTRY` (the group entry file; at registration the cause of `INVALID_PLUGIN_INPUT`), `ALREADY_SET_UP` (one instance in two apps), `NOT_SET_UP` (context used before setup), `NO_CONTROLLERS`, `VIEWS_MISSING` (no `views/default/`; the file error is the `cause`), `INVALID_CONTRIBUTION` (`contributes` is not a list of distinct points made by `definePoint`, or has more than 64), `UNDECLARED_POINT` (`module.contribute` to a point missing from `contributes`, or `module.collect`; the `fix` names the module). Warn log `POINT_NOT_COLLECTED` (core): values no registered plugin collects were dropped. Options of the group plugin other than an empty object are `INVALID_PLUGIN_OPTIONS` (cause `INVALID_OPTIONS`). The `defineOptions` declaration in `src/options.ts` is the parser, and the build writes `options.schema.json` from it (D-0063 §3; never edit it by hand). Before 0.4.0 the codes had a `MODULE_` prefix (D-0071).
124
202
 
125
203
  ## 7. Cautions
126
204
 
127
- - A module does not depend on apps (never branch on an app name). Handle per-app differences with `page.app` and the app's view overrides.
205
+ - A module does not depend on apps (never branch on an app name). Pages of different audiences are named sets the app chooses (§2a); smaller per-app differences use `page.app` and the app's view overrides.
128
206
  - `moduleMount` and `MODULE_MOUNT` are the internal link @dokebi/app uses. App code does not use them.
129
207
  - Socket and SSE route types (`ModuleSocketRoute`, `ModuleEventRoute`) are defined by shape only, so projects that do not use them need neither @dokebi/websocket nor @dokebi/sse. When used, add that package (otherwise the app start fails: `has sockets; add @dokebi/websocket`, `has event streams; add @dokebi/sse`). Both take `config: { id }`, the route id (D-0140), like the module's routes: it must be unique among the routes, sockets and streams of each app that mounts the module (`DUPLICATE_ROUTE_ID` at start otherwise).
130
208
  - Do not treat the end of a response or a dropped connection as the work being done. Work detached from the request is awaited in the module's `drain`.
package/README.md CHANGED
@@ -1,7 +1,9 @@
1
- # @dokebi/module 0.4.1
1
+ # @dokebi/module 0.4.5
2
2
 
3
3
  An optional package for Node >=24.0.0 and core ^0.4.0 (public on npm). A module is **one feature as an MVC unit of business code** ([D-0022](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0022-plugin-boundaries-and-db.md), [D-0032](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0032-feature-modules.md)). It keeps controllers, services, models, views, routes and sockets in one folder, and apps mount it under a prefix. It is not an HTTP-only bundle, so business code without a web side (job processing, event subscriptions) is a module too.
4
4
 
5
+ Since 0.4.5 a module may declare its routes, sockets and event streams as named sets (one per audience: `site`, `admin`), and each app mounts the sets it shows: `{ module, use: 'admin' }` with @dokebi/app 0.4.8 ([D-0216](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0216-module-sets.md)).
6
+
5
7
  ## Folder
6
8
 
7
9
  ```
package/dist/index.d.ts CHANGED
@@ -13,6 +13,12 @@ export interface ModuleContext extends PluginContext {
13
13
  /** The module name (the folder name under src/shared/modules). */
14
14
  readonly module: string;
15
15
  controller<T>(definition: ControllerDefinition<T>): T;
16
+ /**
17
+ * D-0216 (0.4.5): whether the module is switched on now (its `enabled`; true without one). Its
18
+ * own background work (job handlers, subscriptions) reads it: the switch closes only routes,
19
+ * sockets and event streams by itself.
20
+ */
21
+ enabled(): boolean;
16
22
  }
17
23
  /** What a module route handler receives besides the Fastify request and reply (D-0032). */
18
24
  export interface ModulePage {
@@ -83,6 +89,15 @@ export interface ModuleEventRoute {
83
89
  readonly namespace?: string;
84
90
  } | undefined>;
85
91
  }
92
+ export type ModuleRoutesHook = (route: ModuleRouter, module: ModuleContext) => Awaitable<void>;
93
+ export type ModuleSocketsHook = (module: ModuleContext) => Awaitable<readonly ModuleSocketRoute[]>;
94
+ export type ModuleEventsHook = (module: ModuleContext) => Awaitable<readonly ModuleEventRoute[]>;
95
+ /**
96
+ * D-0216: one hook, mounted whole by every app, or **named sets** of it (`{ site, admin }`): an
97
+ * app that mounts the module names the sets it shows (`{ module, use: 'admin' }`), and only
98
+ * their routes, sockets and event streams are registered on that app's domains.
99
+ */
100
+ export type ModuleHook<H> = H | Readonly<Record<string, H>>;
86
101
  export interface ModuleDefinition<T> {
87
102
  readonly name: string;
88
103
  /** Exact plugin version of this module. Default '0.1.0'. */
@@ -99,12 +114,22 @@ export interface ModuleDefinition<T> {
99
114
  readonly contributes?: readonly Pick<ContributionPoint<unknown>, 'name'>[];
100
115
  /** Folder with one sub-folder per template (`default/` is required). */
101
116
  readonly views?: URL;
102
- /** Routes registered by every app that mounts this module (`defineApp({ modules })`). */
103
- routes?(route: ModuleRouter, module: ModuleContext): Awaitable<void>;
104
- /** WebSocket routes registered by every app that mounts this module, under its prefix. */
105
- sockets?(module: ModuleContext): Awaitable<readonly ModuleSocketRoute[]>;
106
- /** SSE routes (@dokebi/sse) registered by every app that mounts this module, under its prefix. */
107
- events?(module: ModuleContext): Awaitable<readonly ModuleEventRoute[]>;
117
+ /**
118
+ * Routes registered by every app that mounts this module (`defineApp({ modules })`), or named
119
+ * sets of them (D-0216): `{ site(route, module) {…}, admin(route, module) {…} }`.
120
+ */
121
+ readonly routes?: ModuleHook<ModuleRoutesHook>;
122
+ /** WebSocket routes under the mount's prefix; named sets as `routes` (one shape for all three). */
123
+ readonly sockets?: ModuleHook<ModuleSocketsHook>;
124
+ /** SSE routes (@dokebi/sse) under the mount's prefix; named sets as `routes`. */
125
+ readonly events?: ModuleHook<ModuleEventsHook>;
126
+ /**
127
+ * D-0216 (0.4.5): whether the module is switched on, asked on every request to its routes,
128
+ * sockets and event streams in every app that mounts it. Synchronous and cheap (a value in
129
+ * memory, such as a @dokebi/runtime-settings `get`). False: they answer the 404 of an unknown
130
+ * path. A throw or a value that is not a boolean counts as off (error MODULE_SWITCH_FAILED).
131
+ */
132
+ enabled?(module: ModuleContext): boolean;
108
133
  /** Optional; the result is the API of this module for plugins and modules that require it. */
109
134
  setup?(module: ModuleContext): Awaitable<T>;
110
135
  start?(module: ModuleContext): Awaitable<void>;
@@ -118,12 +143,34 @@ export interface ModuleMount {
118
143
  readonly name: string;
119
144
  /** Template prefix of the module views (`module.<name>`), when the module has views. */
120
145
  readonly views: string | undefined;
121
- readonly routes: ModuleDefinition<unknown>['routes'];
122
- readonly sockets: ModuleDefinition<unknown>['sockets'];
146
+ /**
147
+ * D-0218 (0.4.6): the module's views folder (`views` of the definition), where its Inertia pages
148
+ * live (`<template>/Pages/**`); undefined without views (and in older module packages).
149
+ */
150
+ readonly folder?: URL | undefined;
151
+ /**
152
+ * The hooks of a module mounted whole. For a module of named sets these are guards that fail
153
+ * the start: an app package older than the sets (before @dokebi/app 0.4.8) would call them.
154
+ */
155
+ readonly routes: ModuleRoutesHook | undefined;
156
+ readonly sockets: ModuleSocketsHook | undefined;
123
157
  /** SSE routes (0.1.3); undefined for a module without them (and in older module packages). */
124
- readonly events: ModuleDefinition<unknown>['events'];
158
+ readonly events: ModuleEventsHook | undefined;
159
+ /**
160
+ * D-0216 (0.4.5): the set names of a module that declares named sets, in declaration order;
161
+ * undefined for a module mounted whole (and in older module packages).
162
+ */
163
+ readonly sets?: readonly string[] | undefined;
164
+ /** D-0216 (0.4.5): the hooks of the chosen sets, in the order chosen (sets without one skipped). */
165
+ hooks?(sets: readonly string[]): {
166
+ readonly routes: readonly ModuleRoutesHook[];
167
+ readonly sockets: readonly ModuleSocketsHook[];
168
+ readonly events: readonly ModuleEventsHook[];
169
+ };
125
170
  /** The module context; available once the module has been set up. */
126
171
  context(): ModuleContext;
172
+ /** D-0216 (0.4.5): the switch (`enabled` of the definition; true without one). */
173
+ enabled?(): boolean;
127
174
  }
128
175
  export declare const MODULE_MOUNT: unique symbol;
129
176
  export declare function defineModule<T = void>(definition: ModuleDefinition<T>): Plugin<T>;
@@ -134,5 +181,13 @@ export interface ModuleEntry {
134
181
  }
135
182
  export interface ModuleGroupApi {
136
183
  readonly names: readonly string[];
184
+ /**
185
+ * D-0216 (0.4.5): every module of the group with its switch now (an app's menu, a permission
186
+ * list, the center's view of an instance).
187
+ */
188
+ modules(): readonly {
189
+ readonly name: string;
190
+ readonly enabled: boolean;
191
+ }[];
137
192
  }
138
193
  export declare const createPlugin: import("@dokebi/core").PluginFactory<ModuleGroupApi>;
package/dist/index.js CHANGED
@@ -2,9 +2,10 @@ import { stat } from 'node:fs/promises';
2
2
  import { fileURLToPath } from 'node:url';
3
3
  import { types } from 'node:util';
4
4
  import { DokebiError, definePlugin, dependencyOf, providerDependency, } from '@dokebi/core';
5
+ import { diagnostics } from '@dokebi/core/libraries';
5
6
  import { options } from './options.js';
6
7
  const FIX = {
7
- INVALID_DEFINITION: 'Pass defineModule a lower-case name (a-z, 0-9, ., _, -) and only the documented fields: requires and controllers arrays, views as a file: URL, hooks as functions.',
8
+ INVALID_DEFINITION: 'Pass defineModule a lower-case name (a-z, 0-9, ., _, -) and only the documented fields: requires and controllers arrays, views as a file: URL, hooks as functions; routes, sockets and events either all functions or all named sets ({ site() {…}, admin() {…} }, 1 to 16 lower-case names).',
8
9
  INVALID_REQUIREMENT: 'List plugin instances or dependency descriptors ({ name, version }) in requires, each name once.',
9
10
  INVALID_ENTRY: 'Export modules: an array of distinct defineModule plugins (at most 1024) from src/shared/modules/index.ts (npx dokebi module add <name> writes it).',
10
11
  ALREADY_SET_UP: 'Create the module plugin once per Application (call defineModule for each application).',
@@ -26,6 +27,8 @@ const NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/;
26
27
  /** core's point name (`<owner plugin>:<name>`) and its limit per plugin (D-0063). */
27
28
  const POINT_NAME = /^[a-z0-9][a-z0-9._/-]{0,95}:[a-z0-9][a-z0-9._-]{0,63}$/;
28
29
  const POINT_LIMIT = 64;
30
+ /** Named sets of one hook (D-0216): audiences of a module, not pages, so a few. */
31
+ const SET_LIMIT = 16;
29
32
  const DEFINITION_KEYS = new Set([
30
33
  'name',
31
34
  'version',
@@ -36,6 +39,7 @@ const DEFINITION_KEYS = new Set([
36
39
  'routes',
37
40
  'sockets',
38
41
  'events',
42
+ 'enabled',
39
43
  'setup',
40
44
  'start',
41
45
  'drain',
@@ -75,7 +79,7 @@ function contributedPoints(value, module) {
75
79
  }
76
80
  return Object.freeze([...names]);
77
81
  }
78
- function moduleContext(context, name, declared, controllers, points) {
82
+ function moduleContext(context, name, declared, controllers, points, enabled) {
79
83
  // core accepts only the descriptor object this module declared; look it up by name.
80
84
  const own = (dependency) => declared.get(dependency?.name) ?? dependency;
81
85
  return Object.freeze({
@@ -115,6 +119,7 @@ function moduleContext(context, name, declared, controllers, points) {
115
119
  const pointName = point?.name;
116
120
  throw moduleError('UNDECLARED_POINT', `Module ${name} cannot collect ${typeof pointName === 'string' ? pointName : 'a point'}`, undefined, 'Modules only contribute. Collect the point in a plugin that declares it in collects (definePlugin), and give the module what it needs through requires.');
117
121
  },
122
+ enabled,
118
123
  controller: (definition) => {
119
124
  const api = controllers();
120
125
  if (!api)
@@ -138,7 +143,28 @@ export function defineModule(definition) {
138
143
  (definition.controllers !== undefined && !Array.isArray(definition.controllers)) ||
139
144
  (definition.views !== undefined &&
140
145
  (!(definition.views instanceof URL) || definition.views.protocol !== 'file:')) ||
141
- ['routes', 'sockets', 'events', 'setup', 'start', 'drain'].some((hook) => definition[hook] !== undefined && typeof definition[hook] !== 'function'))
146
+ ['enabled', 'setup', 'start', 'drain'].some((hook) => definition[hook] !== undefined && typeof definition[hook] !== 'function') ||
147
+ ['routes', 'sockets', 'events'].some((hook) => {
148
+ const value = definition[hook];
149
+ if (value === undefined || typeof value === 'function')
150
+ return false;
151
+ // Named sets (D-0216): a plain object of 1 to 16 set names, each a function.
152
+ if (value === null ||
153
+ typeof value !== 'object' ||
154
+ Array.isArray(value) ||
155
+ types.isProxy(value) ||
156
+ ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
157
+ return true;
158
+ const entries = Object.entries(value);
159
+ return (entries.length === 0 ||
160
+ entries.length > SET_LIMIT ||
161
+ entries.some(([set, fn]) => !NAME.test(set) || typeof fn !== 'function'));
162
+ }) ||
163
+ // One shape for the three: all plain functions, or all named sets.
164
+ new Set(['routes', 'sockets', 'events']
165
+ .map((hook) => definition[hook])
166
+ .filter((value) => value !== undefined)
167
+ .map((value) => typeof value === 'function')).size > 1)
142
168
  throw moduleError('INVALID_DEFINITION', 'Invalid module definition');
143
169
  const { name, views } = definition;
144
170
  const points = contributedPoints(definition.contributes, name);
@@ -154,10 +180,49 @@ export function defineModule(definition) {
154
180
  let started = false;
155
181
  let controllers;
156
182
  let current;
183
+ let repeats;
184
+ let last;
185
+ /**
186
+ * The switch (D-0216), asked per request: `enabled` of the definition with the module context.
187
+ * A failure closes the module rather than opening it, and is logged once per window; a change
188
+ * of state is logged once.
189
+ */
190
+ const switchOn = () => {
191
+ const ask = definition.enabled;
192
+ if (!ask)
193
+ return true;
194
+ const context = current;
195
+ // Before setup nothing of the module is served.
196
+ if (!context)
197
+ return false;
198
+ let value;
199
+ let failure;
200
+ try {
201
+ value = ask.call(definition, context);
202
+ }
203
+ catch (error) {
204
+ failure = error;
205
+ }
206
+ if (failure !== undefined || typeof value !== 'boolean') {
207
+ repeats ??= new diagnostics.Repeats({ logger: context.logger });
208
+ repeats.log('error', 'Module switch failed; the module answers as switched off.', 'MODULE_SWITCH_FAILED', failure ??
209
+ moduleError('INVALID_DEFINITION', `enabled of module ${name} returned ${value instanceof Promise ? 'a Promise' : typeof value}, not a boolean (it must be synchronous)`), { module: name });
210
+ value = false;
211
+ }
212
+ if (value !== last) {
213
+ if (last !== undefined)
214
+ context.logger.log('info', value ? 'Module switched on' : 'Module switched off', {
215
+ code: value ? 'MODULE_SWITCHED_ON' : 'MODULE_SWITCHED_OFF',
216
+ module: name,
217
+ });
218
+ last = value;
219
+ }
220
+ return value;
221
+ };
157
222
  const prefix = `module.${name}`;
158
223
  const hook = (key) => async (context) => {
159
224
  const begin = performance.now();
160
- await definition[key]?.(current ?? moduleContext(context, name, declared, () => controllers, pointSet));
225
+ await definition[key]?.(current ?? moduleContext(context, name, declared, () => controllers, pointSet, switchOn));
161
226
  context.logger.log('debug', `Module ${key} finished`, {
162
227
  module: name,
163
228
  ms: Math.round(performance.now() - begin),
@@ -176,7 +241,11 @@ export function defineModule(definition) {
176
241
  if (started)
177
242
  throw moduleError('ALREADY_SET_UP', 'Create one module instance per Application');
178
243
  started = true;
179
- current = moduleContext(context, name, declared, () => controllers, pointSet);
244
+ current = moduleContext(context, name, declared, () => controllers, pointSet, switchOn);
245
+ // Counted failures of the switch are written before the module goes away.
246
+ context.defer(() => {
247
+ repeats?.flush();
248
+ });
180
249
  const begin = performance.now();
181
250
  if (definition.controllers?.length) {
182
251
  const { createControllers } = await import('@dokebi/controller');
@@ -203,6 +272,8 @@ export function defineModule(definition) {
203
272
  contributes: points,
204
273
  views: views ? prefix : false,
205
274
  routes: Boolean(definition.routes),
275
+ sets: sets ?? false,
276
+ switch: Boolean(definition.enabled),
206
277
  sockets: Boolean(definition.sockets),
207
278
  events: Boolean(definition.events),
208
279
  ms: Math.round(performance.now() - begin),
@@ -212,17 +283,54 @@ export function defineModule(definition) {
212
283
  ...(definition.start ? { start: hook('start') } : {}),
213
284
  ...(definition.drain ? { drain: hook('drain') } : {}),
214
285
  };
286
+ const asSets = (value) => value !== undefined && typeof value !== 'function'
287
+ ? value
288
+ : undefined;
289
+ const routeSets = asSets(definition.routes);
290
+ const socketSets = asSets(definition.sockets);
291
+ const eventSets = asSets(definition.events);
292
+ const sets = routeSets || socketSets || eventSets
293
+ ? Object.freeze([
294
+ ...new Set([
295
+ ...Object.keys(routeSets ?? {}),
296
+ ...Object.keys(socketSets ?? {}),
297
+ ...Object.keys(eventSets ?? {}),
298
+ ]),
299
+ ])
300
+ : undefined;
301
+ // A module of sets read by an app package that does not know sets would mount nothing and
302
+ // answer 404 everywhere without a word: its whole-module hooks refuse instead.
303
+ const tooOld = () => {
304
+ throw moduleError('INVALID_DEFINITION', `Module ${name} declares the sets ${sets?.join(', ')}; the app package mounting it does not know sets`, undefined, 'Update @dokebi/app to 0.4.8 or later, and mount the module as { module, use: "<set>" }.');
305
+ };
306
+ const whole = (value) => typeof value === 'function'
307
+ ? value.bind(definition)
308
+ : sets
309
+ ? tooOld
310
+ : undefined;
311
+ const chosenOf = (table, chosen) => Object.freeze(chosen.flatMap((set) => {
312
+ const hook = table && Object.hasOwn(table, set) ? table[set] : undefined;
313
+ return hook ? [hook.bind(definition)] : [];
314
+ }));
215
315
  const mount = Object.freeze({
216
316
  name,
217
317
  views: views ? prefix : undefined,
218
- routes: definition.routes?.bind(definition),
219
- sockets: definition.sockets?.bind(definition),
220
- events: definition.events?.bind(definition),
318
+ folder: views ? new URL(views.href) : undefined,
319
+ routes: whole(definition.routes),
320
+ sockets: whole(definition.sockets),
321
+ events: whole(definition.events),
322
+ sets,
323
+ hooks: (chosen) => Object.freeze({
324
+ routes: chosenOf(routeSets, chosen),
325
+ sockets: chosenOf(socketSets, chosen),
326
+ events: chosenOf(eventSets, chosen),
327
+ }),
221
328
  context: () => {
222
329
  if (!current)
223
330
  throw moduleError('NOT_SET_UP', `Module ${name} is not set up yet`);
224
331
  return current;
225
332
  },
333
+ enabled: switchOn,
226
334
  });
227
335
  Object.defineProperty(plugin, MODULE_MOUNT, { value: mount });
228
336
  return Object.freeze(plugin);
@@ -267,20 +375,29 @@ function parseEntry(input) {
267
375
  }
268
376
  class ModuleGroupRuntime {
269
377
  names;
270
- constructor(names) {
378
+ mounts;
379
+ constructor(names, mounts) {
271
380
  this.names = names;
381
+ this.mounts = mounts;
272
382
  }
273
383
  setup(context) {
274
384
  context.logger.log('debug', 'Modules registered', { modules: this.names });
275
- return Object.freeze({ names: this.names });
385
+ const mounts = this.mounts;
386
+ return Object.freeze({
387
+ names: this.names,
388
+ modules: () => Object.freeze(mounts.map((mount) => Object.freeze({ name: mount.name, enabled: mount.enabled?.() ?? true }))),
389
+ });
276
390
  }
277
391
  }
278
392
  export const createPlugin = definePlugin({
279
393
  name: 'dokebi-module',
280
- version: '0.4.4',
394
+ version: '0.4.6',
281
395
  core: '^0.4.0',
282
396
  options,
283
397
  entry: parseEntry,
284
398
  dependencies: ({ entry }) => (entry ?? []).map((module) => dependencyOf(module)),
285
- instance: ({ dependencies }) => new ModuleGroupRuntime(Object.freeze(dependencies.map((dependency) => dependency.name))),
399
+ instance: ({ dependencies, entry }) => new ModuleGroupRuntime(Object.freeze(dependencies.map((dependency) => dependency.name)), Object.freeze((entry ?? []).flatMap((module) => {
400
+ const mount = moduleMount(module);
401
+ return mount ? [mount] : [];
402
+ }))),
286
403
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/module",
3
- "version": "0.4.4",
3
+ "version": "0.4.6",
4
4
  "description": "Feature modules for Dokebi apps: controllers, models, views and routes in one folder mounted under a prefix.",
5
5
  "keywords": [
6
6
  "dokebi",
@@ -95,7 +95,7 @@
95
95
  "devDependencies": {
96
96
  "@dokebi/controller": "0.4.2",
97
97
  "@dokebi/template-ejs": "0.4.3",
98
- "@dokebi/template-inertia": "0.4.7",
98
+ "@dokebi/template-inertia": "0.4.8",
99
99
  "@dokebi/web": "0.4.7"
100
100
  },
101
101
  "publishConfig": {