@dokebi/module 0.0.0-stage → 0.1.1
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 +85 -0
- package/LICENSE +21 -0
- package/README.md +74 -2
- package/dist/index.d.ts +99 -0
- package/dist/index.js +198 -0
- package/options.schema.json +6 -0
- package/package.json +77 -4
- package/templates/module/controllers/items.ts +11 -0
- package/templates/module/models/summary.ts +6 -0
- package/templates/module/module.ts +18 -0
- package/templates/module/routes.ts +10 -0
- package/templates/module/views/default/index.ejs +4 -0
- package/templates/module-api/controllers/items.ts +11 -0
- package/templates/module-api/models/summary.ts +6 -0
- package/templates/module-api/module.ts +16 -0
- package/templates/module-api/routes.ts +7 -0
package/AI.md
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# AI 작업 안내 — @dokebi/module 0.1.1
|
|
2
|
+
|
|
3
|
+
모듈은 **기능 하나의 업무 단위**다(D-0032). 컨트롤러·모델·뷰·라우트·소켓을 한 폴더에 담고, 앱이 접두사로 붙인다. 웹이 없는 업무(Job handler, 이벤트 구독, 공통 API)도 모듈로 만든다. Node >=24.0.0, core ^0.2.0. 세부는 [README](README.md)다.
|
|
4
|
+
|
|
5
|
+
## 1. 만들기
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npx dokebi add @dokebi/module # src/shared/modules/ 준비
|
|
9
|
+
npx dokebi module add board # 화면 있는 모듈(views/default 포함)
|
|
10
|
+
npx dokebi module add stats --no-views # 라우트가 JSON을 돌려주는 모듈
|
|
11
|
+
npx dokebi module remove board # 등록만 지우고 폴더는 남김
|
|
12
|
+
npx dokebi module list
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
모듈 폴더를 손으로 만들면 등록되지 않는다. 생성 등록 코드가 각 모듈의 default export를 묶음 플러그인 entry로 넘긴다.
|
|
16
|
+
|
|
17
|
+
```
|
|
18
|
+
src/shared/modules/<모듈>/
|
|
19
|
+
module.ts export default defineModule({ ... })
|
|
20
|
+
routes.ts 앱에 붙을 때 등록되는 라우트
|
|
21
|
+
controllers/ models/ views/default/(화면 모듈) sockets/(필요할 때)
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
컨트롤러·모델·뷰를 층별 폴더(`src/shared/controllers` 등)로 흩지 않는다.
|
|
25
|
+
|
|
26
|
+
## 2. defineModule
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { defineModule } from '@dokebi/module';
|
|
30
|
+
import { dependency as db } from '@dokebi/db';
|
|
31
|
+
import { postsController } from './controllers/posts.ts';
|
|
32
|
+
|
|
33
|
+
export default defineModule({
|
|
34
|
+
name: 'board', // 폴더 이름. 플러그인 id는 dokebi-module.board
|
|
35
|
+
requires: [db], // 인스턴스·descriptor·다른 모듈
|
|
36
|
+
controllers: [postsController],
|
|
37
|
+
views: new URL('./views/', import.meta.url), // default/ 필수(지정하면 template-ejs 의존 추가)
|
|
38
|
+
routes(route, module) { // 붙인 앱마다 그 앱의 도메인·접두사로 등록
|
|
39
|
+
route.get('/', async (request, reply, page) =>
|
|
40
|
+
page.view.reply(reply, 'index', { posts: await module.controller(postsController).list(), base: page.base }),
|
|
41
|
+
);
|
|
42
|
+
route.post('/', async (request, reply, page) => { /* ... */ });
|
|
43
|
+
},
|
|
44
|
+
sockets: (module) => [boardSocket(module)], // defineSocket 결과. tenant는 <앱>:<tenant>
|
|
45
|
+
setup(module) { return { count: () => module.controller(postsController).count() }; }, // 다른 쪽이 받는 API
|
|
46
|
+
start(module) {}, drain(module) {},
|
|
47
|
+
});
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
- `module`(ModuleContext) = PluginContext + `module`(이름) + `controller(token)`. `requires`에 선언한 것만 `get`·`getDependency`로 읽는다.
|
|
51
|
+
- `page`(ModulePage) = `{ app: { name, template, domain }, module, base, view, inertia }`. 링크는 `page.base`를 붙여 만든다(앱마다 접두사가 다를 수 있다).
|
|
52
|
+
- `version`은 정확한 semver(기본 `'0.1.0'`). 같은 이름의 requires는 거부한다.
|
|
53
|
+
- 컨트롤러 없이 `module.controller()`를 부르면 `declares no controllers` 오류.
|
|
54
|
+
|
|
55
|
+
## 3. 앱에 붙이기와 공통 API
|
|
56
|
+
|
|
57
|
+
- 앱: `defineApp({ modules: { '/board': board } })`. 라우트·소켓은 **그 앱의 도메인과 접두사에서만** 응답한다. 같은 모듈을 여러 앱이 다른 접두사로 붙일 수 있다.
|
|
58
|
+
- 모든 도메인에서 응답해야 하는 API(예: `/api/*`)는 `routes`가 아니라 `setup`에서 `@dokebi/router`(`mount`)나 web으로 직접 등록한다.
|
|
59
|
+
- 다른 모듈·플러그인이 이 모듈의 API를 쓰려면 `requires`에 이 모듈을 넣고 `get(모듈)` 하면 `setup`의 반환값을 받는다.
|
|
60
|
+
|
|
61
|
+
## 4. 화면 찾는 순서(앱이 모듈 화면을 바꾸는 법)
|
|
62
|
+
|
|
63
|
+
1. `<앱>/<템플릿>/<모듈>/…`
|
|
64
|
+
2. `<앱>/default/<모듈>/…`
|
|
65
|
+
3. 모듈의 `<템플릿>/…`
|
|
66
|
+
4. 모듈의 `default/…`
|
|
67
|
+
5. 앱 views(레이아웃·부분 템플릿)
|
|
68
|
+
6. 공통 `src/shared/views`
|
|
69
|
+
|
|
70
|
+
앱이 모듈 화면을 바꿀 때는 모듈 파일을 고치지 말고 `src/apps/<앱>/views/<템플릿>/<모듈>/`에 같은 이름 파일을 둔다. Inertia 앱이 붙이면 모듈은 `page.inertia.render(request, reply, '컴포넌트', props)`로 props를 내고, Vue 페이지는 앱의 `views/<템플릿>/Pages/`에 둔다.
|
|
71
|
+
|
|
72
|
+
## 5. 묶음 플러그인과 수명주기
|
|
73
|
+
|
|
74
|
+
- `createPlugin({ app, entry: { modules } })`: 여러 모듈을 의존성 그래프로 묶는다. API는 `{ names }`. `defineModule`이 만든 것만 받고 중복은 `INVALID_PLUGIN_INPUT`.
|
|
75
|
+
- 훅: setup(라우트 등록·API 반환) → start → drain(새 유입 차단, 진행 업무 대기) → defer 정리. drain은 의존 역순(이 모듈에 의존하는 모듈이 먼저), 무관한 모듈은 동시에.
|
|
76
|
+
- 모듈 인스턴스는 Application 하나에만 쓴다. 실행 중 자동 검색·동적 import·hot reload는 없다.
|
|
77
|
+
|
|
78
|
+
## 6. 주의 사항
|
|
79
|
+
|
|
80
|
+
- 모듈은 앱에 의존하지 않는다(앱 이름으로 분기하지 않는다). 앱별 차이는 `page.app`과 앱의 화면 덮어쓰기로 처리한다.
|
|
81
|
+
- `moduleMount`·`MODULE_MOUNT`는 @dokebi/app이 쓰는 내부 연결이다. 앱 코드에서 쓰지 않는다.
|
|
82
|
+
- 소켓 타입은 모양으로만 정해져 있어 소켓 없는 프로젝트는 @dokebi/websocket이 필요 없다. 소켓을 쓰면 websocket을 add한다.
|
|
83
|
+
- 응답 종료·연결 끊김을 업무 완료로 보지 않는다. 요청 밖으로 떼어 낸 작업은 모듈 `drain`에서 기다린다.
|
|
84
|
+
|
|
85
|
+
근거: `examples/26-scaffold`(생성·붙이기·덮어쓰기 반복), `examples/25-playground`(기능 모듈 일곱 개), `examples/22-web/main.ts`(코드 조합), D-0022·D-0032.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dokebi contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,75 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @dokebi/module 0.1.1
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Node >=24.0.0, core ^0.2.0의 선택 패키지다(npm 공개). 모듈은 **기능 하나의 MVC 업무 단위**다([D-0022](../../docs/decisions/D-0022-plugin-boundaries-and-db.md), [D-0032](../../docs/decisions/D-0032-feature-modules.md)). 컨트롤러·모델·뷰·라우트·소켓을 한 폴더에 담고, 앱이 접두사로 붙인다. HTTP 전용 묶음이 아니어서 웹 없는 업무(Job 처리, 이벤트 구독)도 모듈로 만든다.
|
|
4
|
+
|
|
5
|
+
## 폴더
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
src/shared/modules/<모듈>/
|
|
9
|
+
module.ts export default defineModule({ ... })
|
|
10
|
+
routes.ts 앱에 붙을 때 등록되는 라우트
|
|
11
|
+
controllers/ 이 모듈의 컨트롤러(모듈 setup에서 한 번 만든다)
|
|
12
|
+
models/ 이 모듈의 모델(일반 코드)
|
|
13
|
+
views/default/ (화면이 있는 모듈만) EJS 화면. 다른 템플릿은 바꿀 파일만
|
|
14
|
+
sockets/ (필요할 때) defineSocket
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
`dokebi module add <이름>`이 골격을 만들고 생성 등록 코드에 넣는다. 화면 없는 모듈은 `--no-views`로 만든다. 이때 라우트는 JSON을 돌려준다. `dokebi module remove <이름>`은 등록만 지우고 폴더를 남긴다. `dokebi module list`는 목록을 보여 준다. `dokebi add @dokebi/module`은 `src/shared/modules/` 폴더만 만든다.
|
|
18
|
+
|
|
19
|
+
## defineModule
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
export default defineModule({
|
|
23
|
+
name: 'board', // 폴더 이름. ID는 dokebi-module.board
|
|
24
|
+
requires: [db, other], // 플러그인 인스턴스·descriptor·다른 모듈
|
|
25
|
+
controllers: [postsController], // 모듈 문맥으로 한 번 만든다
|
|
26
|
+
views: new URL('./views/', import.meta.url), // default/ 필수, 템플릿 이름 접두사 module.board
|
|
27
|
+
routes(route, module) { // 앱마다(붙을 때) 등록. page = { app, module, base, view, inertia }
|
|
28
|
+
route.get('/', (request, reply, page) =>
|
|
29
|
+
page.view.reply(reply, 'index', module.controller(postsController).list(page)));
|
|
30
|
+
},
|
|
31
|
+
sockets: (module) => [boardSocket(module)], // 앱마다 접두사 아래 등록, tenant는 <앱>:<tenant>
|
|
32
|
+
setup(module) { return api; }, // 선택. 반환값이 이 모듈을 requires한 쪽이 받는 API
|
|
33
|
+
start(module) {}, drain(module) {},
|
|
34
|
+
});
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
- **`module`(ModuleContext):** PluginContext에 `module`(이름)과 `controller(token)`을 더한 것이다.
|
|
38
|
+
- 선언한 `requires`만 읽는다.
|
|
39
|
+
- 컨트롤러 factory가 descriptor 객체를 새로 만들어 넘겨도 이름으로 선언한 descriptor를 찾아 준다.
|
|
40
|
+
- **`version`:** 정확한 semver이며 기본값은 `'0.1.0'`이다. 같은 이름의 requires는 거부한다.
|
|
41
|
+
- **`views`:** 지정하면 template-ejs 의존이 자동으로 더해진다. `views/default/`가 없으면 시작이 실패한다.
|
|
42
|
+
- **`controllers`:** 지정하면 @dokebi/controller를 쓴다(선택 peer). 컨트롤러 없이 `module.controller()`를 부르면 `declares no controllers` 오류가 난다.
|
|
43
|
+
- **`setup`:** 선택이다. 기존 `setup(context)` 형태도 그대로 동작한다.
|
|
44
|
+
- **공통 API:** 모든 도메인에서 응답해야 하는 API는 setup에서 router·web으로 직접 등록한다. 예: 플레이그라운드의 `/api/*`.
|
|
45
|
+
- **앱에 붙이기:** `defineApp({ modules: { '/board': board } })`. 라우트·소켓이 그 앱의 도메인과 접두사에서만 응답한다. 붙인 모듈은 앱의 `requires`에 넣지 않아도 `app.get(board)`로 API를 읽을 수 있다. 자세한 내용은 [@dokebi/app](../dokebi-app/README.md)에 있다.
|
|
46
|
+
- **화면 찾는 순서:**
|
|
47
|
+
1. `<앱>/<템플릿>/<모듈>/…`
|
|
48
|
+
2. `<앱>/default/<모듈>/…`
|
|
49
|
+
3. 모듈의 `<템플릿>/…`
|
|
50
|
+
4. 모듈의 `default/…`
|
|
51
|
+
5. 앱 views(레이아웃·부분 템플릿)
|
|
52
|
+
6. 공통 `src/shared/views`
|
|
53
|
+
|
|
54
|
+
그래서 앱은 모듈 화면의 파일 하나만 바꿀 수 있다. 예: `src/apps/<앱>/views/christmas/<모듈>/heading.ejs`.
|
|
55
|
+
- **Inertia 앱:** 모듈이 `page.inertia.render(request, reply, '컴포넌트', props)`로 props를 낸다. Vue 페이지는 앱이 `views/<템플릿>/Pages/`에 둔다.
|
|
56
|
+
- **소켓:** `sockets`의 반환 타입은 모양(`ModuleSocketRoute`)으로만 정한다. 그래서 소켓이 없는 프로젝트는 @dokebi/websocket이 없어도 된다.
|
|
57
|
+
- **`moduleMount(plugin)`·`MODULE_MOUNT`:** 앱 플러그인이 붙이기 정보를 읽는 길이다. 앱 코드에서 쓸 일은 없다.
|
|
58
|
+
|
|
59
|
+
## 묶음 플러그인
|
|
60
|
+
|
|
61
|
+
`createPlugin({ app: app.view, entry: { modules: [...] } })`는 여러 모듈을 의존성 그래프로 묶고 frozen `names`를 공개한다(플러그인 계약 v2, [D-0028](../../docs/decisions/D-0028-plugin-contract-v2.md)).
|
|
62
|
+
|
|
63
|
+
- **생성 코드:** `dokebi module add`로 등록한 모듈의 default export를 이 entry로 넘긴다. 예전 진입 파일 `src/shared/modules/index.ts`가 있는 프로젝트는 그 `modules` 목록 뒤에 이어 붙인다.
|
|
64
|
+
- **허용하는 모듈:** `defineModule`이 만든 것만(ID가 `dokebi-module.`으로 시작) 받는다. 중복은 `INVALID_PLUGIN_INPUT`이다. 단일 모듈은 app.register로 직접 등록해도 된다.
|
|
65
|
+
- **수명주기:** setup에서 라우트를 등록하고, start는 실행 준비, drain은 유입 차단과 진행 업무 대기, context.defer는 전체 drain 이후 정리다.
|
|
66
|
+
- **drain 순서:** 의존 역순이다. 어떤 모듈의 drain은 그 모듈에 의존하는 모듈의 drain이 끝난 뒤 시작한다. 서로 무관한 모듈은 동시에 진행한다.
|
|
67
|
+
- **인스턴스:** 모듈 이름은 겹칠 수 없다. 하나의 모듈 인스턴스는 Application 하나에만 쓴다.
|
|
68
|
+
- **제공하지 않는 것:** 실행 중 자동 검색·동적 import·hot reload·폴더 스캔은 없다. 등록은 CLI가 생성 코드에 적는다.
|
|
69
|
+
- **설정:** YAML 설정은 빈 객체다.
|
|
70
|
+
|
|
71
|
+
예제:
|
|
72
|
+
|
|
73
|
+
- [examples/26-scaffold](../../examples/26-scaffold/README.md): 생성·붙이기·덮어쓰기 반복 검증
|
|
74
|
+
- [examples/25-playground](../../examples/25-playground/README.md): 기능 모듈 일곱 개
|
|
75
|
+
- examples/22-web/main.ts: 코드로 직접 조합
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { ControllerDefinition } from '@dokebi/controller';
|
|
2
|
+
import { type Awaitable, type Plugin, type PluginContext, type PluginDependency } from '@dokebi/core';
|
|
3
|
+
import type { TemplateApi } from '@dokebi/template-ejs';
|
|
4
|
+
import type { InertiaApi } from '@dokebi/template-inertia';
|
|
5
|
+
import type { WebRoute } from '@dokebi/web';
|
|
6
|
+
import type { FastifyReply, FastifyRequest } from 'fastify';
|
|
7
|
+
/** A plugin instance (read with context.get) or a descriptor (read with context.getDependency). */
|
|
8
|
+
export type ModuleRequirement = Plugin<unknown> | PluginDependency;
|
|
9
|
+
/** The plugin context of a module, plus the controllers the module declares. */
|
|
10
|
+
export interface ModuleContext extends PluginContext {
|
|
11
|
+
/** The module name (the folder name under src/shared/modules). */
|
|
12
|
+
readonly module: string;
|
|
13
|
+
controller<T>(definition: ControllerDefinition<T>): T;
|
|
14
|
+
}
|
|
15
|
+
/** What a module route handler receives besides the Fastify request and reply (D-0032). */
|
|
16
|
+
export interface ModulePage {
|
|
17
|
+
/** The app that mounted the module, with the template and host of the request. */
|
|
18
|
+
readonly app: {
|
|
19
|
+
readonly name: string;
|
|
20
|
+
readonly template: string;
|
|
21
|
+
readonly domain: string;
|
|
22
|
+
};
|
|
23
|
+
readonly module: string;
|
|
24
|
+
/** The prefix the app mounted the module at (`''` at the root), for links. */
|
|
25
|
+
readonly base: string;
|
|
26
|
+
/**
|
|
27
|
+
* EJS renderer: `<app>/<template>/<module>` → `<app>/default/<module>` → the module's
|
|
28
|
+
* `<template>` → the module's `default` → the app's views (layouts) → shared views.
|
|
29
|
+
*/
|
|
30
|
+
readonly view: TemplateApi;
|
|
31
|
+
/** The Inertia renderer of the mounting app, when it has one. */
|
|
32
|
+
readonly inertia: InertiaApi | undefined;
|
|
33
|
+
}
|
|
34
|
+
export type ModuleHandler = (request: FastifyRequest, reply: FastifyReply, page: ModulePage) => unknown | Promise<unknown>;
|
|
35
|
+
export type ModuleRouteOptions = Omit<WebRoute, 'handler' | 'constraints'> & {
|
|
36
|
+
readonly handler: ModuleHandler;
|
|
37
|
+
};
|
|
38
|
+
/** Routes of a module; an app that mounts the module adds its prefix and domain constraint. */
|
|
39
|
+
export interface ModuleRouter {
|
|
40
|
+
route(options: ModuleRouteOptions): void;
|
|
41
|
+
get(url: string, handler: ModuleHandler, options?: Partial<ModuleRouteOptions>): void;
|
|
42
|
+
post(url: string, handler: ModuleHandler, options?: Partial<ModuleRouteOptions>): void;
|
|
43
|
+
put(url: string, handler: ModuleHandler, options?: Partial<ModuleRouteOptions>): void;
|
|
44
|
+
patch(url: string, handler: ModuleHandler, options?: Partial<ModuleRouteOptions>): void;
|
|
45
|
+
delete(url: string, handler: ModuleHandler, options?: Partial<ModuleRouteOptions>): void;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* A WebSocket route of a module, as `defineSocket` of @dokebi/websocket returns it. Typed by
|
|
49
|
+
* shape so projects whose modules have no sockets need not install @dokebi/websocket.
|
|
50
|
+
*/
|
|
51
|
+
export interface ModuleSocketRoute {
|
|
52
|
+
readonly path: string;
|
|
53
|
+
readonly constraints?: Readonly<Record<string, unknown>>;
|
|
54
|
+
authenticate(request: FastifyRequest): Awaitable<{
|
|
55
|
+
readonly tenant: string;
|
|
56
|
+
} | undefined>;
|
|
57
|
+
}
|
|
58
|
+
export interface ModuleDefinition<T> {
|
|
59
|
+
readonly name: string;
|
|
60
|
+
/** Exact plugin version of this module. Default '0.1.0'. */
|
|
61
|
+
readonly version?: string;
|
|
62
|
+
readonly requires?: readonly ModuleRequirement[];
|
|
63
|
+
/** `defineController` tokens, built once with this module's context. */
|
|
64
|
+
readonly controllers?: readonly ControllerDefinition<unknown>[];
|
|
65
|
+
/** Folder with one sub-folder per template (`default/` is required). */
|
|
66
|
+
readonly views?: URL;
|
|
67
|
+
/** Routes registered by every app that mounts this module (`defineApp({ modules })`). */
|
|
68
|
+
routes?(route: ModuleRouter, module: ModuleContext): Awaitable<void>;
|
|
69
|
+
/** WebSocket routes registered by every app that mounts this module, under its prefix. */
|
|
70
|
+
sockets?(module: ModuleContext): Awaitable<readonly ModuleSocketRoute[]>;
|
|
71
|
+
/** Optional; the result is the API of this module for plugins and modules that require it. */
|
|
72
|
+
setup?(module: ModuleContext): Awaitable<T>;
|
|
73
|
+
start?(module: ModuleContext): Awaitable<void>;
|
|
74
|
+
drain?(module: ModuleContext): Awaitable<void>;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* What @dokebi/app reads from a module plugin to mount it (`Symbol.for('dokebi.module.mount')`),
|
|
78
|
+
* so the app package needs no runtime import of this one.
|
|
79
|
+
*/
|
|
80
|
+
export interface ModuleMount {
|
|
81
|
+
readonly name: string;
|
|
82
|
+
/** Template prefix of the module views (`module.<name>`), when the module has views. */
|
|
83
|
+
readonly views: string | undefined;
|
|
84
|
+
readonly routes: ModuleDefinition<unknown>['routes'];
|
|
85
|
+
readonly sockets: ModuleDefinition<unknown>['sockets'];
|
|
86
|
+
/** The module context; available once the module has been set up. */
|
|
87
|
+
context(): ModuleContext;
|
|
88
|
+
}
|
|
89
|
+
export declare const MODULE_MOUNT: unique symbol;
|
|
90
|
+
export declare function defineModule<T = void>(definition: ModuleDefinition<T>): Plugin<T>;
|
|
91
|
+
/** The mount information of a module plugin made by defineModule, or undefined. */
|
|
92
|
+
export declare function moduleMount(plugin: unknown): ModuleMount | undefined;
|
|
93
|
+
export interface ModuleEntry {
|
|
94
|
+
readonly modules: readonly Plugin<unknown>[];
|
|
95
|
+
}
|
|
96
|
+
export interface ModuleGroupApi {
|
|
97
|
+
readonly names: readonly string[];
|
|
98
|
+
}
|
|
99
|
+
export declare const createPlugin: import("@dokebi/core").PluginFactory<ModuleGroupApi>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { stat } from 'node:fs/promises';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { types } from 'node:util';
|
|
4
|
+
import { definePlugin, dependencyOf, providerDependency, } from '@dokebi/core';
|
|
5
|
+
export const MODULE_MOUNT = Symbol.for('dokebi.module.mount');
|
|
6
|
+
const NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
7
|
+
const DEFINITION_KEYS = new Set([
|
|
8
|
+
'name',
|
|
9
|
+
'version',
|
|
10
|
+
'requires',
|
|
11
|
+
'controllers',
|
|
12
|
+
'views',
|
|
13
|
+
'routes',
|
|
14
|
+
'sockets',
|
|
15
|
+
'setup',
|
|
16
|
+
'start',
|
|
17
|
+
'drain',
|
|
18
|
+
]);
|
|
19
|
+
const ejs = providerDependency({
|
|
20
|
+
name: 'dokebi-template-ejs',
|
|
21
|
+
version: '^0.1.0',
|
|
22
|
+
packageName: '@dokebi/template-ejs',
|
|
23
|
+
load: () => import('@dokebi/template-ejs'),
|
|
24
|
+
});
|
|
25
|
+
function requirement(value) {
|
|
26
|
+
if (value === null || typeof value !== 'object')
|
|
27
|
+
throw new TypeError('Invalid module requirement');
|
|
28
|
+
if (typeof value.setup === 'function')
|
|
29
|
+
return dependencyOf(value);
|
|
30
|
+
if (typeof value.name !== 'string')
|
|
31
|
+
throw new TypeError('Invalid module requirement');
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
function moduleContext(context, name, declared, controllers) {
|
|
35
|
+
// core accepts only the descriptor object this module declared; look it up by name.
|
|
36
|
+
const own = (dependency) => declared.get(dependency?.name) ?? dependency;
|
|
37
|
+
return Object.freeze({
|
|
38
|
+
module: name,
|
|
39
|
+
get app() {
|
|
40
|
+
return context.app;
|
|
41
|
+
},
|
|
42
|
+
get logger() {
|
|
43
|
+
return context.logger;
|
|
44
|
+
},
|
|
45
|
+
get signal() {
|
|
46
|
+
return context.signal;
|
|
47
|
+
},
|
|
48
|
+
get drainSignal() {
|
|
49
|
+
return context.drainSignal;
|
|
50
|
+
},
|
|
51
|
+
get: (plugin) => context.get(plugin),
|
|
52
|
+
getDependency: (dependency) => context.getDependency(own(dependency)),
|
|
53
|
+
getOptionalDependency: (dependency) => context.getOptionalDependency(own(dependency)),
|
|
54
|
+
defer: (cleanup) => context.defer(cleanup),
|
|
55
|
+
controller: (definition) => {
|
|
56
|
+
const api = controllers();
|
|
57
|
+
if (!api)
|
|
58
|
+
throw new Error(`Module ${name} declares no controllers`);
|
|
59
|
+
return api.get(definition);
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
export function defineModule(definition) {
|
|
64
|
+
const version = definition.version ?? '0.1.0';
|
|
65
|
+
if (definition === null ||
|
|
66
|
+
typeof definition !== 'object' ||
|
|
67
|
+
types.isProxy(definition) ||
|
|
68
|
+
Object.keys(definition).some((key) => !DEFINITION_KEYS.has(key)) ||
|
|
69
|
+
typeof definition.name !== 'string' ||
|
|
70
|
+
!NAME.test(definition.name) ||
|
|
71
|
+
typeof version !== 'string' ||
|
|
72
|
+
(definition.requires !== undefined && !Array.isArray(definition.requires)) ||
|
|
73
|
+
(definition.controllers !== undefined && !Array.isArray(definition.controllers)) ||
|
|
74
|
+
(definition.views !== undefined &&
|
|
75
|
+
(!(definition.views instanceof URL) || definition.views.protocol !== 'file:')) ||
|
|
76
|
+
['routes', 'sockets', 'setup', 'start', 'drain'].some((hook) => definition[hook] !== undefined && typeof definition[hook] !== 'function'))
|
|
77
|
+
throw new TypeError('Invalid module definition');
|
|
78
|
+
const { name, views } = definition;
|
|
79
|
+
const dependencies = (definition.requires ?? []).map(requirement);
|
|
80
|
+
if (new Set(dependencies.map((dependency) => dependency.name)).size !== dependencies.length)
|
|
81
|
+
throw new TypeError('Duplicate module requirement');
|
|
82
|
+
if (views && !dependencies.some((dependency) => dependency.name === ejs.name))
|
|
83
|
+
dependencies.push(ejs);
|
|
84
|
+
// core needs the declared descriptor object itself (the module's own or the one in requires).
|
|
85
|
+
const templates = dependencies.find((dependency) => dependency.name === ejs.name);
|
|
86
|
+
const declared = new Map(dependencies.map((dependency) => [dependency.name, dependency]));
|
|
87
|
+
let started = false;
|
|
88
|
+
let controllers;
|
|
89
|
+
let current;
|
|
90
|
+
const prefix = `module.${name}`;
|
|
91
|
+
const hook = (key) => (context) => definition[key]?.(current ?? moduleContext(context, name, declared, () => controllers));
|
|
92
|
+
const plugin = {
|
|
93
|
+
metadata: Object.freeze({
|
|
94
|
+
name: 'dokebi-module.' + name,
|
|
95
|
+
version,
|
|
96
|
+
core: '^0.2.0',
|
|
97
|
+
dependencies: Object.freeze(dependencies),
|
|
98
|
+
}),
|
|
99
|
+
async setup(context) {
|
|
100
|
+
if (started)
|
|
101
|
+
throw new Error('Create one module instance per Application');
|
|
102
|
+
started = true;
|
|
103
|
+
current = moduleContext(context, name, declared, () => controllers);
|
|
104
|
+
if (definition.controllers?.length) {
|
|
105
|
+
const { createControllers } = await import('@dokebi/controller');
|
|
106
|
+
controllers = await createControllers(current, definition.controllers);
|
|
107
|
+
}
|
|
108
|
+
if (views) {
|
|
109
|
+
const folder = fileURLToPath(new URL('default/', views));
|
|
110
|
+
if (!(await stat(folder).catch(() => undefined))?.isDirectory())
|
|
111
|
+
throw new Error(`Module ${name} has no views/default/ folder`);
|
|
112
|
+
await context.getDependency(templates ?? ejs).addDirectory(views, prefix);
|
|
113
|
+
}
|
|
114
|
+
return (await definition.setup?.(current));
|
|
115
|
+
},
|
|
116
|
+
...(definition.start ? { start: hook('start') } : {}),
|
|
117
|
+
...(definition.drain ? { drain: hook('drain') } : {}),
|
|
118
|
+
};
|
|
119
|
+
const mount = Object.freeze({
|
|
120
|
+
name,
|
|
121
|
+
views: views ? prefix : undefined,
|
|
122
|
+
routes: definition.routes?.bind(definition),
|
|
123
|
+
sockets: definition.sockets?.bind(definition),
|
|
124
|
+
context: () => {
|
|
125
|
+
if (!current)
|
|
126
|
+
throw new Error(`Module ${name} is not set up yet`);
|
|
127
|
+
return current;
|
|
128
|
+
},
|
|
129
|
+
});
|
|
130
|
+
Object.defineProperty(plugin, MODULE_MOUNT, { value: mount });
|
|
131
|
+
return Object.freeze(plugin);
|
|
132
|
+
}
|
|
133
|
+
/** The mount information of a module plugin made by defineModule, or undefined. */
|
|
134
|
+
export function moduleMount(plugin) {
|
|
135
|
+
return plugin !== null && typeof plugin === 'object'
|
|
136
|
+
? plugin[MODULE_MOUNT]
|
|
137
|
+
: undefined;
|
|
138
|
+
}
|
|
139
|
+
const LIMIT = 1024;
|
|
140
|
+
/**
|
|
141
|
+
* Accepts a plain object or a module namespace with `modules`. The generated code passes the
|
|
142
|
+
* modules registered by `dokebi module add` (D-0032), plus the list of an older entry file.
|
|
143
|
+
*/
|
|
144
|
+
function parseEntry(input) {
|
|
145
|
+
if (input === undefined)
|
|
146
|
+
return [];
|
|
147
|
+
if (input === null ||
|
|
148
|
+
typeof input !== 'object' ||
|
|
149
|
+
Array.isArray(input) ||
|
|
150
|
+
types.isProxy(input) ||
|
|
151
|
+
![Object.prototype, null].includes(Object.getPrototypeOf(input)))
|
|
152
|
+
throw new TypeError('Invalid module entry');
|
|
153
|
+
let modules;
|
|
154
|
+
for (const key of Reflect.ownKeys(input)) {
|
|
155
|
+
// Module namespaces carry Symbol.toStringTag; only string exports are entry fields.
|
|
156
|
+
if (typeof key !== 'string')
|
|
157
|
+
continue;
|
|
158
|
+
const descriptor = Object.getOwnPropertyDescriptor(input, key);
|
|
159
|
+
if (key !== 'modules' || !descriptor || !('value' in descriptor))
|
|
160
|
+
throw new TypeError('Invalid module entry');
|
|
161
|
+
modules = descriptor.value;
|
|
162
|
+
}
|
|
163
|
+
if (!Array.isArray(modules) || modules.length > LIMIT)
|
|
164
|
+
throw new TypeError('Expected a modules array');
|
|
165
|
+
const names = modules.map((module) => module?.metadata?.name);
|
|
166
|
+
if (names.some((name) => typeof name !== 'string' || !name.startsWith('dokebi-module.')) ||
|
|
167
|
+
new Set(names).size !== names.length)
|
|
168
|
+
throw new TypeError('Expected distinct module plugins');
|
|
169
|
+
return [...modules];
|
|
170
|
+
}
|
|
171
|
+
function parseOptions(input) {
|
|
172
|
+
if (input === null ||
|
|
173
|
+
typeof input !== 'object' ||
|
|
174
|
+
Array.isArray(input) ||
|
|
175
|
+
types.isProxy(input) ||
|
|
176
|
+
![Object.prototype, null].includes(Object.getPrototypeOf(input)) ||
|
|
177
|
+
Reflect.ownKeys(input).length)
|
|
178
|
+
throw new TypeError('dokebi-module accepts no options');
|
|
179
|
+
return Object.freeze({});
|
|
180
|
+
}
|
|
181
|
+
class ModuleGroupRuntime {
|
|
182
|
+
names;
|
|
183
|
+
constructor(names) {
|
|
184
|
+
this.names = names;
|
|
185
|
+
}
|
|
186
|
+
setup() {
|
|
187
|
+
return Object.freeze({ names: this.names });
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
export const createPlugin = definePlugin({
|
|
191
|
+
name: 'dokebi-module',
|
|
192
|
+
version: '0.1.1',
|
|
193
|
+
core: '^0.2.0',
|
|
194
|
+
options: parseOptions,
|
|
195
|
+
entry: parseEntry,
|
|
196
|
+
dependencies: ({ entry }) => (entry ?? []).map((module) => dependencyOf(module)),
|
|
197
|
+
instance: ({ dependencies }) => new ModuleGroupRuntime(Object.freeze(dependencies.map((dependency) => dependency.name))),
|
|
198
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,79 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dokebi/module",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"private": false,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"templates",
|
|
18
|
+
"options.schema.json",
|
|
19
|
+
"README.md",
|
|
20
|
+
"AI.md",
|
|
21
|
+
"LICENSE"
|
|
22
|
+
],
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=24.0.0"
|
|
25
|
+
},
|
|
26
|
+
"scripts": {
|
|
27
|
+
"build": "tsc -p tsconfig.json",
|
|
28
|
+
"typecheck": "tsc -p tsconfig.test.json --noEmit",
|
|
29
|
+
"test": "tsc -p tsconfig.test.json && node --test .tmp/tests/tests/*.test.js"
|
|
30
|
+
},
|
|
31
|
+
"peerDependencies": {
|
|
32
|
+
"@dokebi/controller": "^0.1.0",
|
|
33
|
+
"@dokebi/core": "^0.2.0",
|
|
34
|
+
"@dokebi/template-ejs": "^0.1.0",
|
|
35
|
+
"@dokebi/template-inertia": "^0.1.0",
|
|
36
|
+
"@dokebi/web": "^0.1.0",
|
|
37
|
+
"fastify": "^5.12.7"
|
|
38
|
+
},
|
|
39
|
+
"dokebi": {
|
|
40
|
+
"schemaVersion": 2,
|
|
41
|
+
"id": "dokebi-module",
|
|
42
|
+
"core": "^0.2.0",
|
|
43
|
+
"dependencies": [],
|
|
44
|
+
"install": {
|
|
45
|
+
"directories": [
|
|
46
|
+
"src/shared/modules"
|
|
47
|
+
]
|
|
48
|
+
},
|
|
49
|
+
"optionsSchema": "options.schema.json",
|
|
50
|
+
"documentation": "AI.md"
|
|
51
|
+
},
|
|
52
|
+
"peerDependenciesMeta": {
|
|
53
|
+
"@dokebi/controller": {
|
|
54
|
+
"optional": true
|
|
55
|
+
},
|
|
56
|
+
"@dokebi/template-ejs": {
|
|
57
|
+
"optional": true
|
|
58
|
+
},
|
|
59
|
+
"@dokebi/template-inertia": {
|
|
60
|
+
"optional": true
|
|
61
|
+
},
|
|
62
|
+
"@dokebi/web": {
|
|
63
|
+
"optional": true
|
|
64
|
+
},
|
|
65
|
+
"fastify": {
|
|
66
|
+
"optional": true
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
"devDependencies": {
|
|
70
|
+
"@dokebi/controller": "0.1.1",
|
|
71
|
+
"@dokebi/template-ejs": "0.1.1",
|
|
72
|
+
"@dokebi/template-inertia": "0.1.1",
|
|
73
|
+
"@dokebi/web": "0.1.1"
|
|
74
|
+
},
|
|
75
|
+
"publishConfig": {
|
|
76
|
+
"access": "public",
|
|
77
|
+
"registry": "https://registry.npmjs.org/"
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { defineController } from '@dokebi/controller';
|
|
2
|
+
import type { ModulePage } from '@dokebi/module';
|
|
3
|
+
import { summary } from '../models/summary.ts';
|
|
4
|
+
|
|
5
|
+
export class ItemsController {
|
|
6
|
+
list(page: ModulePage) {
|
|
7
|
+
return { title: '{{module}}', message: summary(page) };
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
// Built once with this module's context; read it with module.controller(itemsController).
|
|
11
|
+
export const itemsController = defineController('items', () => new ItemsController());
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { ModulePage } from '@dokebi/module';
|
|
2
|
+
|
|
3
|
+
/** Models are plain code; controllers pass them what they need. */
|
|
4
|
+
export function summary(page: ModulePage): string {
|
|
5
|
+
return `{{module}} module in app ${page.app.name} at ${page.base || '/'} (template: ${page.app.template})`;
|
|
6
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// One module of this project (D-0032): a feature with its own controllers, models, views and
|
|
2
|
+
// routes. An app mounts it under a prefix, and its routes answer on that app's domains only:
|
|
3
|
+
// import feature from '../../shared/modules/{{module}}/module.ts';
|
|
4
|
+
// defineApp({ modules: { '/{{module}}': feature } })
|
|
5
|
+
import { defineModule } from '@dokebi/module';
|
|
6
|
+
import { itemsController } from './controllers/items.ts';
|
|
7
|
+
import { routes } from './routes.ts';
|
|
8
|
+
|
|
9
|
+
export default defineModule({
|
|
10
|
+
name: '{{module}}',
|
|
11
|
+
// Plugins and other modules this module uses (instances or dependency descriptors).
|
|
12
|
+
requires: [],
|
|
13
|
+
controllers: [itemsController],
|
|
14
|
+
// One folder per template; `default` is required. An app replaces a file of this module by
|
|
15
|
+
// putting it in src/apps/<app>/views/<template>/{{module}}/.
|
|
16
|
+
views: new URL('./views/', import.meta.url),
|
|
17
|
+
routes,
|
|
18
|
+
});
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { ModuleContext, ModuleRouter } from '@dokebi/module';
|
|
2
|
+
import { itemsController } from './controllers/items.ts';
|
|
3
|
+
|
|
4
|
+
export function routes(route: ModuleRouter, module: ModuleContext): void {
|
|
5
|
+
// Paths are relative to where an app mounts this module; `page.base` is that prefix.
|
|
6
|
+
// The page is rendered inside the app's layout (layouts/main of the app or src/shared/views).
|
|
7
|
+
route.get('/', (_request, reply, page) =>
|
|
8
|
+
page.view.reply(reply, 'index', module.controller(itemsController).list(page)),
|
|
9
|
+
);
|
|
10
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { defineController } from '@dokebi/controller';
|
|
2
|
+
import type { ModulePage } from '@dokebi/module';
|
|
3
|
+
import { summary } from '../models/summary.ts';
|
|
4
|
+
|
|
5
|
+
export class ItemsController {
|
|
6
|
+
list(page: ModulePage) {
|
|
7
|
+
return { title: '{{module}}', message: summary(page) };
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
// Built once with this module's context; read it with module.controller(itemsController).
|
|
11
|
+
export const itemsController = defineController('items', () => new ItemsController());
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { ModulePage } from '@dokebi/module';
|
|
2
|
+
|
|
3
|
+
/** Models are plain code; controllers pass them what they need. */
|
|
4
|
+
export function summary(page: ModulePage): string {
|
|
5
|
+
return `{{module}} module in app ${page.app.name} at ${page.base || '/'} (template: ${page.app.template})`;
|
|
6
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// One module of this project (D-0032): a feature with its own controllers, models and routes
|
|
2
|
+
// (no views; its routes answer JSON). An app mounts it under a prefix, and its routes answer on
|
|
3
|
+
// that app's domains only:
|
|
4
|
+
// import feature from '../../shared/modules/{{module}}/module.ts';
|
|
5
|
+
// defineApp({ modules: { '/{{module}}': feature } })
|
|
6
|
+
import { defineModule } from '@dokebi/module';
|
|
7
|
+
import { itemsController } from './controllers/items.ts';
|
|
8
|
+
import { routes } from './routes.ts';
|
|
9
|
+
|
|
10
|
+
export default defineModule({
|
|
11
|
+
name: '{{module}}',
|
|
12
|
+
// Plugins and other modules this module uses (instances or dependency descriptors).
|
|
13
|
+
requires: [],
|
|
14
|
+
controllers: [itemsController],
|
|
15
|
+
routes,
|
|
16
|
+
});
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ModuleContext, ModuleRouter } from '@dokebi/module';
|
|
2
|
+
import { itemsController } from './controllers/items.ts';
|
|
3
|
+
|
|
4
|
+
export function routes(route: ModuleRouter, module: ModuleContext): void {
|
|
5
|
+
// Paths are relative to where an app mounts this module; `page.base` is that prefix.
|
|
6
|
+
route.get('/', (_request, _reply, page) => module.controller(itemsController).list(page));
|
|
7
|
+
}
|