@dokebi/app 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 +112 -0
- package/LICENSE +21 -0
- package/README.md +101 -2
- package/dist/index.d.ts +107 -0
- package/dist/index.js +443 -0
- package/options.schema.json +34 -0
- package/package.json +99 -4
- package/templates/app/app.ts +15 -0
- package/templates/app/controllers/home.ts +10 -0
- package/templates/app/models/site.ts +6 -0
- package/templates/app/routes.ts +10 -0
- package/templates/app/views/default/home.ejs +4 -0
- package/templates/app-inertia/app.ts +24 -0
- package/templates/app-inertia/controllers/home.ts +10 -0
- package/templates/app-inertia/models/site.ts +6 -0
- package/templates/app-inertia/routes.ts +15 -0
- package/templates/app-inertia/views/app.js +27 -0
- package/templates/app-inertia/views/default/Layout.vue +6 -0
- package/templates/app-inertia/views/default/Pages/Home.vue +7 -0
- package/templates/app-inertia-ssr/app.ts +26 -0
- package/templates/app-inertia-ssr/views/ssr.js +25 -0
- package/templates/inertia-build/build.json +12 -0
- package/templates/inertia-build/vite.config.ts +25 -0
- package/templates/inertia-build/vite.ssr.config.ts +26 -0
package/AI.md
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# AI 작업 안내 — @dokebi/app 0.1.1
|
|
2
|
+
|
|
3
|
+
한 프로젝트에 앱을 여러 개 두고, **요청 도메인으로 앱과 템플릿을 고르는** 플러그인이다(D-0030). 앱 하나는 `src/apps/<앱>/` 폴더 하나이고 `defineApp`으로 정의한다. Node >=24.0.0, core ^0.2.0. 사람용 설명은 [README](README.md)다.
|
|
4
|
+
|
|
5
|
+
## 1. 설치와 만드는 것
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npx dokebi add @dokebi/app # web·controller·template-ejs 함께 설치, 첫 앱 src/apps/main, localhost → main
|
|
9
|
+
npx dokebi app add shop --domain a.com --domain www.a.com
|
|
10
|
+
npx dokebi app add admin --inertia [--ssr] --domain admin.a.com # Vue 앱(+서버 렌더링)
|
|
11
|
+
npx dokebi app link shop b.com --template christmas
|
|
12
|
+
npx dokebi app unlink b.com
|
|
13
|
+
npx dokebi app remove shop # 그 앱을 가리키는 도메인을 먼저 unlink. 폴더는 남는다
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
- 앱 폴더를 손으로 만들면 등록되지 않는다. 생성 등록 코드가 `.dokebi/state.json`의 앱 목록대로 `./apps/<앱>/app.ts`를 import해 entry `{ apps }`로 넘긴다.
|
|
17
|
+
- Inertia·WebSocket을 쓰는 앱이 있으면 `@dokebi/template-inertia`, `@dokebi/websocket`을 따로 add한다(없으면 시작 실패: `App <앱> uses Inertia; add @dokebi/template-inertia`, `has sockets; add @dokebi/websocket`).
|
|
18
|
+
- 이름 규칙: 앱·템플릿 `^[a-z][a-z0-9-]{0,31}$`, 도메인은 포트 없는 소문자 호스트.
|
|
19
|
+
|
|
20
|
+
## 2. 앱 폴더
|
|
21
|
+
|
|
22
|
+
```
|
|
23
|
+
src/apps/<앱>/
|
|
24
|
+
app.ts export default defineApp({ ... })
|
|
25
|
+
routes.ts 라우트
|
|
26
|
+
controllers/ 이 앱의 defineController
|
|
27
|
+
models/ 일반 코드
|
|
28
|
+
views/default/ 기본 템플릿(필수). EJS: home.ejs / Inertia: Layout.vue, Pages/*.vue
|
|
29
|
+
views/<템플릿>/ 바꿀 파일만
|
|
30
|
+
views/app.js (Inertia) 브라우저 진입 views/ssr.js (--ssr) 서버 진입
|
|
31
|
+
sockets/ (선택) defineSocket
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
여러 앱이 같이 쓰는 기능은 앱에 두지 말고 기능 모듈(`npx dokebi module add <이름>` → `src/shared/modules/<이름>`, @dokebi/module)로 만든다.
|
|
35
|
+
|
|
36
|
+
## 3. 설정 `options.dokebi-app`
|
|
37
|
+
|
|
38
|
+
| 키 | 형식 | 뜻 |
|
|
39
|
+
|---|---|---|
|
|
40
|
+
| `domains` (필수) | `{ <host>: { app, template? } }`, 최대 1024 | 호스트 → 앱·템플릿(생략은 default) |
|
|
41
|
+
| `unknownDomain` | `reject`(기본) 또는 domains의 키 하나 | 모르는 호스트: 404, 또는 그 도메인의 설정으로 응답 |
|
|
42
|
+
|
|
43
|
+
호스트는 dokebi-web `requestHost()`(trustProxy면 `X-Forwarded-Host`)에서 포트를 떼고 소문자로 **정확히** 비교한다. 와일드카드·경로 접두사는 없다. 프락시 뒤면 dokebi-web `trustProxy`에 프락시 주소를 넣는다.
|
|
44
|
+
|
|
45
|
+
## 4. defineApp
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
import { defineApp } from '@dokebi/app';
|
|
49
|
+
import { dependency as db } from '@dokebi/db';
|
|
50
|
+
import board from '../../shared/modules/board/module.ts';
|
|
51
|
+
import { productController } from './controllers/product.ts';
|
|
52
|
+
|
|
53
|
+
export default defineApp({
|
|
54
|
+
requires: [db], // 이 앱이 쓰는 플러그인·모듈. 이 밖은 get 불가
|
|
55
|
+
controllers: [productController],
|
|
56
|
+
views: new URL('./views/', import.meta.url), // file: URL, views/default 필수
|
|
57
|
+
inertia: { title: 'Shop', vite: { manifest: 'dist/.vite/manifest.json', entry: 'src/apps/shop/views/app.js', base: '/build/' } },
|
|
58
|
+
modules: { '/board': board }, // 모듈의 routes·sockets·views를 이 앱 도메인에 붙임
|
|
59
|
+
shared: (request, page) => ({ menu: MENU }), // 모든 EJS 페이지 데이터 밑에 합침(페이지 값이 이김)
|
|
60
|
+
routes(route, app) {
|
|
61
|
+
route.get('/', async (request, reply, page) =>
|
|
62
|
+
page.view.reply(reply, 'home', { items: await app.controller(productController).list() }, { layout: 'layouts/main' }),
|
|
63
|
+
);
|
|
64
|
+
},
|
|
65
|
+
sockets: (app) => [chatSocket(app)],
|
|
66
|
+
setup(app) {}, start(app) {}, drain(app) {},
|
|
67
|
+
});
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
- `route`: `get`·`post`·`put`·`patch`·`delete(url, handler, options?)`, `route(options)`. 핸들러는 `(request, reply, page)`.
|
|
71
|
+
- `page`: `{ app: { name, template, domain }, module, base, view, inertia }`. 앱 라우트에서 `module`은 undefined, `base`는 `''`.
|
|
72
|
+
- `view`: EJS 렌더러. 찾는 순서 `<앱>/<템플릿>` → `<앱>/default` → `src/shared/views`(레이아웃·`$include`도 같음).
|
|
73
|
+
- `inertia`: 앱의 문서 설정을 쓰는 Inertia 렌더러(앱에 `inertia`가 있을 때). 공통 props에 `app`(`{ name, template, domain }`)을 더한다.
|
|
74
|
+
- `app`(AppContext): `name`·`logger`·`signal`·`get`·`getDependency`·`getOptionalDependency`·`controller`·`defer`. **`requires`에 없는 것을 꺼내면 오류**(`App <앱> does not list <플러그인> in requires`). 컨트롤러 팩토리도 같은 제한을 받는다.
|
|
75
|
+
- `inertia.ssr: { bundle: 'dist/ssr/<앱>/ssr.js' }`면 첫 HTML을 서버에서 그린다(D-0039, template-inertia AI.md).
|
|
76
|
+
|
|
77
|
+
### 모듈 붙이기(D-0032)
|
|
78
|
+
|
|
79
|
+
- `modules: { '/접두사': 모듈 }`. 접두사는 `/` 또는 `/a/b`(소문자·숫자·`.`·`_`·`~`·`-`).
|
|
80
|
+
- 모듈의 라우트·소켓이 이 앱의 도메인·접두사로 등록되고 `page.module`·`page.base`가 채워진다. 같은 모듈을 여러 앱이 다른 접두사로 붙일 수 있다. 붙인 모듈은 `requires`에 넣지 않아도 `app.get(모듈)`로 API를 읽는다.
|
|
81
|
+
- 모듈 화면 찾는 순서는 다음과 같다. 그래서 모듈 화면이 앱 레이아웃 안에 그려진다. 앱이 모듈 화면을 바꾸려면 `views/<템플릿>/<모듈>/`에 같은 파일을 둔다.
|
|
82
|
+
1. `<앱>/<템플릿>/<모듈>`
|
|
83
|
+
2. `<앱>/default/<모듈>`
|
|
84
|
+
3. 모듈의 `<템플릿>`
|
|
85
|
+
4. 모듈의 `default`
|
|
86
|
+
5. 앱 views
|
|
87
|
+
6. 공통
|
|
88
|
+
|
|
89
|
+
### 라우팅과 WebSocket
|
|
90
|
+
|
|
91
|
+
- 앱 라우트는 Fastify 제약 `dokebiApp`(`APP_CONSTRAINT`)으로 등록된다. 여러 앱이 같은 경로를 가질 수 있다. 제약 없는 라우트(헬스 체크, `@dokebi/router` API)는 모든 도메인에서 응답한다.
|
|
92
|
+
- 앱 소켓도 같은 제약을 쓴다. 허브 tenant는 `<앱>:<tenant>`로 앱마다 나뉘며 세션 `identity.tenant`도 그 값이다. 메시지는 `defineSocket`의 `{ type, data, id? }` 형식.
|
|
93
|
+
|
|
94
|
+
## 5. API
|
|
95
|
+
|
|
96
|
+
`createPlugin`의 API는 `{ names, resolve(request) }`. `resolve`는 요청의 `{ name, template, domain }` 또는 모르는 호스트면 undefined. `APP_CONSTRAINT`, `hostOf(request)`(Host 헤더에서 포트 뗀 값, 프락시 무시)도 내보낸다. 앱 판정에는 `resolve`를 쓴다.
|
|
97
|
+
|
|
98
|
+
## 6. 시작 때 거절되는 것
|
|
99
|
+
|
|
100
|
+
없는 앱을 가리키는 도메인, 등록 안 된 앱, `views` 폴더나 `views/default/`·도메인이 고른 `views/<템플릿>/` 누락, `defineApp`의 모르는 필드, 잘못된 모듈 접두사, `defineModule`로 만들지 않은 모듈.
|
|
101
|
+
|
|
102
|
+
## 7. 주의 사항
|
|
103
|
+
|
|
104
|
+
- 코드에서 Host 헤더로 분기하지 않는다. 도메인 → 앱·템플릿은 dokebi.yaml에만 두고 핸들러는 `page.app`을 읽는다.
|
|
105
|
+
- `views/default/`를 지우지 않는다. 템플릿 폴더에는 바꿀 파일만 둔다.
|
|
106
|
+
- 앱끼리 서로 import하지 않는다. 공통 코드는 `src/shared/`(모델·뷰) 또는 모듈.
|
|
107
|
+
- 생성 등록 코드와 `.dokebi/state.json`을 고치지 않는다. 앱·도메인 변경은 `dokebi app` 명령으로 한다(dokebi.example.yaml에도 같이 남는다).
|
|
108
|
+
- Inertia 앱의 빌드 파일이 없으면 시작이 실패한다. `npm run build`를 먼저 한다.
|
|
109
|
+
|
|
110
|
+
## 8. 근거
|
|
111
|
+
|
|
112
|
+
`examples/25-playground`(vue·ejs 두 앱, 도메인·템플릿, 모듈, 소켓), `examples/26-scaffold`(CLI 생성 반복 검증), D-0030·D-0031·D-0032·D-0039.
|
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,102 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @dokebi/app 0.1.1
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
한 프로젝트 안에 여러 앱을 두고, 요청 도메인으로 앱과 템플릿을 고르는 선택 플러그인이다. Node >=24.0.0, core ^0.2.0의 선택 패키지다(npm 공개). 설계는 [D-0030](../../docs/decisions/D-0030-multi-app-and-domains.md)이다.
|
|
4
|
+
|
|
5
|
+
## 설치
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
dokebi add @dokebi/app
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
필수 플러그인 dokebi-web·dokebi-controller·dokebi-template-ejs가 같은 변경에서 함께 설치되고(결과 `autoInstalled`), 첫 앱 `src/apps/main`과 `domains: { localhost: { app: main } }`가 만들어진다. 앱을 더 만들 때:
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
dokebi app add shop --domain a.com --domain www.a.com
|
|
15
|
+
dokebi app link shop b.com --template christmas # 기존 앱에 도메인 더하기
|
|
16
|
+
dokebi app unlink b.com
|
|
17
|
+
dokebi app list
|
|
18
|
+
dokebi app remove shop # 그 앱을 가리키는 도메인을 먼저 지운다. 폴더는 남는다.
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
도메인 연결은 dokebi.yaml과 dokebi.example.yaml에 함께 남는다. Inertia 화면이나 WebSocket을 쓰는 앱이 있으면 `dokebi add @dokebi/template-inertia`, `dokebi add @dokebi/websocket`을 따로 한다.
|
|
22
|
+
|
|
23
|
+
## 폴더 구조
|
|
24
|
+
|
|
25
|
+
[D-0031](../../docs/decisions/D-0031-project-layout.md)을 따른다. 앱 폴더는 `dokebi app add`가 만든다.
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
src/apps/<앱>/
|
|
29
|
+
app.ts export default defineApp({ ... })
|
|
30
|
+
routes.ts 라우트
|
|
31
|
+
controllers/ defineController 토큰(이 앱 전용)
|
|
32
|
+
models/ 일반 코드(플러그인 아님)
|
|
33
|
+
views/default/ 기본 템플릿(필수). EJS 앱은 home.ejs, Inertia 앱은 Layout.vue·Pages/Home.vue
|
|
34
|
+
views/<템플릿>/ 바꿀 파일만 둔다. 없으면 default → 공통 src/shared/views 순서로 찾는다.
|
|
35
|
+
views/app.js (Inertia 앱만) Vite 진입: 템플릿별 페이지·레이아웃을 같은 순서로 찾는다
|
|
36
|
+
sockets/ 이 앱의 WebSocket(defineSocket), 필요할 때 만든다
|
|
37
|
+
src/shared/ 여러 앱이 같이 쓰는 컨트롤러·모델·모듈(dokebi-module)·공통 뷰
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
- `dokebi app add <앱> --inertia`는 Inertia 골격을 만들고 빌드 준비(`vite.config.ts`, `build` 스크립트, Vite·Vue 개발 의존성, `.gitignore`의 `dist/`)도 한다. 그 뒤 `npm run build`를 한다.
|
|
41
|
+
- `--ssr`을 더하면([D-0039](../../docs/decisions/D-0039-inertia-ssr.md)) 서버 진입 `views/ssr.js`, app.ts의 `inertia.ssr: { bundle: 'dist/ssr/<앱>/ssr.js' }`, 프로젝트의 `vite.ssr.config.ts`를 만들고 `build`가 브라우저·서버 빌드를 함께 한다(앞서 만든 `vite build`만 있던 스크립트는 둘 다로 바뀌고, 직접 쓴 스크립트는 `BUILD_SCRIPT_KEPT`로 남긴다). 브라우저 진입 `views/app.js`는 서버가 그린 페이지를 `createSSRApp`으로 hydration한다. 레이아웃은 페이지 모듈을 바꾸지 않고 `layout` 옵션으로 고른다(서버에서 템플릿이 다른 요청이 동시에 그려지므로).
|
|
42
|
+
- 빌드 파일은 @dokebi/template-inertia가 `/build/`로 내보낸다. 자세한 내용은 [CLI 문서](../../docs/cli/README.md)에 있다.
|
|
43
|
+
|
|
44
|
+
앱 이름은 폴더 이름이다. 생성 등록 코드(src/dokebi.generated.ts)가 `.dokebi/state.json`의 앱 목록대로 `./apps/<앱>/app.ts`를 가져와 이 플러그인의 entry `{ apps: { <앱>: ... } }`로 넘긴다.
|
|
45
|
+
|
|
46
|
+
## 설정
|
|
47
|
+
|
|
48
|
+
```yaml
|
|
49
|
+
dokebi-app:
|
|
50
|
+
domains:
|
|
51
|
+
a.com: { app: shop } # template 생략 = default
|
|
52
|
+
b.com: { app: shop, template: christmas }
|
|
53
|
+
c.com: { app: admin }
|
|
54
|
+
unknownDomain: reject # 기본. 또는 domains의 키 하나(그 설정으로 응답)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
dokebi-web `requestHost()`가 준 호스트(신뢰 프락시면 `X-Forwarded-Host`)에서 포트를 떼고 소문자로 정확히 비교한다. 프락시 뒤라면 dokebi-web `trustProxy`에 프락시 주소를 적는다. 와일드카드·경로 접두사는 아직 없다. 시작할 때 없는 앱, 없는 템플릿 폴더, `views/default/` 누락을 거부한다.
|
|
58
|
+
|
|
59
|
+
## defineApp
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
import { defineApp } from '@dokebi/app';
|
|
63
|
+
import { dependency as db } from '@dokebi/db';
|
|
64
|
+
|
|
65
|
+
export default defineApp({
|
|
66
|
+
requires: [db], // 이 앱이 쓰는 플러그인·공통 모듈
|
|
67
|
+
controllers: [productController],
|
|
68
|
+
views: new URL('./views/', import.meta.url),
|
|
69
|
+
inertia: { vite: { manifest: 'dist/.vite/manifest.json', entry: 'src/apps/shop/views/app.js', base: '/build/' } },
|
|
70
|
+
modules: { '/board': board }, // 기능 모듈을 접두사로 붙인다(D-0032)
|
|
71
|
+
shared: (request, page) => ({ menu: MENU }), // 이 앱의 모든 EJS 페이지에 합칠 데이터
|
|
72
|
+
routes(route, app) {
|
|
73
|
+
route.get('/', (request, reply, page) =>
|
|
74
|
+
page.view.reply(reply, 'home', app.controller(productController).list(), { layout: 'layouts/main' }),
|
|
75
|
+
);
|
|
76
|
+
},
|
|
77
|
+
sockets: (app) => [chatSocket(app)], // defineSocket(...) 결과
|
|
78
|
+
setup(app) {}, start(app) {}, drain(app) {},
|
|
79
|
+
});
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
- 핸들러의 `page`는 `{ app: { name, template, domain }, module, base, view, inertia }`다. 앱 라우트에서 `module`은 undefined, `base`는 `''`다. `view`는 `<앱>/<템플릿>` → `<앱>/default` → 공통 src/shared/views 순서로 찾는 EJS 렌더러이고, 레이아웃과 `$include`도 같은 순서를 따른다. `inertia`는 앱의 문서 설정(Vite 진입점 등)을 쓰고 공통 props에 `app`을 더한다.
|
|
83
|
+
- **모듈 붙이기([D-0032](../../docs/decisions/D-0032-feature-modules.md)):** `modules: { '/접두사': 모듈 }`. 모듈은 `defineModule`로 만든 것이다.
|
|
84
|
+
- 모듈의 `routes`는 이 앱의 라우트 제약과 접두사로 등록된다. 핸들러 `page.module`·`page.base`가 채워진다.
|
|
85
|
+
- 모듈의 `sockets`는 접두사 아래 경로로 등록된다. tenant는 `<앱>:<tenant>`다.
|
|
86
|
+
- 같은 모듈을 여러 앱이 다른 접두사로 붙일 수 있다. 붙인 모듈은 `requires`에 넣지 않아도 `app.get(모듈)`로 API를 읽는다.
|
|
87
|
+
- 접두사는 `/` 또는 `/a/b`(소문자·숫자·`.`·`_`·`~`·`-`)다.
|
|
88
|
+
- 모듈 페이지의 화면 찾는 순서는 다음과 같다. 그래서 모듈 화면은 앱 레이아웃 안에 그려진다.
|
|
89
|
+
1. `<앱>/<템플릿>/<모듈>`
|
|
90
|
+
2. `<앱>/default/<모듈>`
|
|
91
|
+
3. 모듈의 `<템플릿>`
|
|
92
|
+
4. 모듈의 `default`
|
|
93
|
+
5. 앱 views
|
|
94
|
+
6. 공통
|
|
95
|
+
- **`shared(request, { app })`:** 이 앱이 그리는 모든 EJS 페이지(앱 라우트와 모듈 라우트)의 데이터 밑에 합쳐진다. 겹치는 키는 페이지 데이터가 이긴다. 레이아웃이 쓰는 메뉴·사용자 같은 앱 데이터를 여기에 둔다. Inertia 공통 props에 해당한다.
|
|
96
|
+
- 앱 문맥(`app`)의 `get`·`getDependency`는 `requires`에 넣은 플러그인만 허용한다. 컨트롤러 팩토리도 같은 제한을 받는다.
|
|
97
|
+
- 앱 라우트는 Fastify 라우트 제약(`dokebiApp`)으로 등록되어 여러 앱이 같은 경로를 가질 수 있다. 제약 없는 공통 라우트(헬스 체크, 모듈 API)는 모든 도메인에서 응답한다.
|
|
98
|
+
- 앱의 WebSocket 라우트도 같은 제약으로 등록된다. 허브의 tenant는 `<앱>:<tenant>`가 되어 접속자 목록·방송이 앱 밖으로 나가지 않는다. 세션의 `identity.tenant`도 이 값이다.
|
|
99
|
+
|
|
100
|
+
## API
|
|
101
|
+
|
|
102
|
+
`createPlugin`이 돌려주는 API는 `{ names, resolve(request) }`다. `resolve`는 요청의 앱·템플릿·도메인을, 모르는 Host면 undefined를 돌려준다. `APP_CONSTRAINT`(`'dokebiApp'`)와 `hostOf(request)`도 공개한다.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
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, InertiaScopeOptions } from '@dokebi/template-inertia';
|
|
5
|
+
import type { WebRoute } from '@dokebi/web';
|
|
6
|
+
import type { WebsocketRoute } from '@dokebi/websocket';
|
|
7
|
+
import type { FastifyReply, FastifyRequest } from 'fastify';
|
|
8
|
+
/** The Fastify route constraint that selects an app by request host. */
|
|
9
|
+
export declare const APP_CONSTRAINT = "dokebiApp";
|
|
10
|
+
/** Which app answered a request, with the template and the host it came in on. */
|
|
11
|
+
export interface AppInfo {
|
|
12
|
+
readonly name: string;
|
|
13
|
+
readonly template: string;
|
|
14
|
+
readonly domain: string;
|
|
15
|
+
}
|
|
16
|
+
/** What an app route handler receives besides the Fastify request and reply. */
|
|
17
|
+
export interface AppPage {
|
|
18
|
+
readonly app: AppInfo;
|
|
19
|
+
/** The module whose route answered (`defineApp({ modules })`), or undefined for app routes. */
|
|
20
|
+
readonly module: string | undefined;
|
|
21
|
+
/** The prefix the module is mounted at (`''` for app routes and root mounts), for links. */
|
|
22
|
+
readonly base: string;
|
|
23
|
+
/** EJS renderer scoped to `<app>/<template>` → `<app>/default` → shared views. */
|
|
24
|
+
readonly view: TemplateApi;
|
|
25
|
+
/** Inertia renderer of this app; present when the app sets `inertia`. */
|
|
26
|
+
readonly inertia: InertiaApi | undefined;
|
|
27
|
+
}
|
|
28
|
+
export type AppHandler = (request: FastifyRequest, reply: FastifyReply, page: AppPage) => unknown | Promise<unknown>;
|
|
29
|
+
/** Fastify route options of an app route; `handler` receives the app page as well. */
|
|
30
|
+
export type AppRouteOptions = Omit<WebRoute, 'handler' | 'constraints'> & {
|
|
31
|
+
readonly handler: AppHandler;
|
|
32
|
+
};
|
|
33
|
+
export interface AppRouter {
|
|
34
|
+
route(options: AppRouteOptions): void;
|
|
35
|
+
get(url: string, handler: AppHandler, options?: Partial<AppRouteOptions>): void;
|
|
36
|
+
post(url: string, handler: AppHandler, options?: Partial<AppRouteOptions>): void;
|
|
37
|
+
put(url: string, handler: AppHandler, options?: Partial<AppRouteOptions>): void;
|
|
38
|
+
patch(url: string, handler: AppHandler, options?: Partial<AppRouteOptions>): void;
|
|
39
|
+
delete(url: string, handler: AppHandler, options?: Partial<AppRouteOptions>): void;
|
|
40
|
+
}
|
|
41
|
+
/** The view of the Application an app gets: only the plugins it lists in `requires`. */
|
|
42
|
+
export interface AppContext {
|
|
43
|
+
readonly name: string;
|
|
44
|
+
readonly logger: PluginContext['logger'];
|
|
45
|
+
readonly signal: AbortSignal;
|
|
46
|
+
get<T>(plugin: Plugin<T>): T;
|
|
47
|
+
getDependency<T>(dependency: PluginDependency<T>): T;
|
|
48
|
+
getOptionalDependency<T>(dependency: PluginDependency<T>): T | undefined;
|
|
49
|
+
controller<T>(definition: ControllerDefinition<T>): T;
|
|
50
|
+
defer(cleanup: () => Awaitable<void>): void;
|
|
51
|
+
}
|
|
52
|
+
export type AppRequirement = Plugin<unknown> | PluginDependency;
|
|
53
|
+
export interface AppDefinition {
|
|
54
|
+
/** Plugins and shared modules this app uses (instances or dependency descriptors). */
|
|
55
|
+
readonly requires?: readonly AppRequirement[];
|
|
56
|
+
/** `defineController` tokens built with this app's context. */
|
|
57
|
+
readonly controllers?: readonly ControllerDefinition<unknown>[];
|
|
58
|
+
/** Folder with one sub-folder per template (`default/` is required). */
|
|
59
|
+
readonly views?: URL;
|
|
60
|
+
/** Document settings of this app's Inertia pages (see template-inertia `scope`). */
|
|
61
|
+
readonly inertia?: Omit<InertiaScopeOptions, 'shared'>;
|
|
62
|
+
/**
|
|
63
|
+
* Modules (D-0032) mounted under a prefix: `{ '/board': boardModule }`. Their routes and
|
|
64
|
+
* sockets answer on this app's domains only; they need not be listed in `requires`.
|
|
65
|
+
*/
|
|
66
|
+
readonly modules?: Readonly<Record<string, Plugin<unknown>>>;
|
|
67
|
+
/**
|
|
68
|
+
* Data merged under the data of every EJS page this app renders, its own and its modules'
|
|
69
|
+
* (like Inertia shared props): what the app layout needs, such as the menu. Page data wins.
|
|
70
|
+
*/
|
|
71
|
+
shared?(request: FastifyRequest, page: {
|
|
72
|
+
readonly app: AppInfo;
|
|
73
|
+
}): Awaitable<Record<string, unknown>>;
|
|
74
|
+
routes?(route: AppRouter, app: AppContext): Awaitable<void>;
|
|
75
|
+
/** WebSocket routes (e.g. `defineSocket`) registered for this app's domains only. */
|
|
76
|
+
sockets?(app: AppContext): Awaitable<readonly WebsocketRoute[]>;
|
|
77
|
+
setup?(app: AppContext): Awaitable<void>;
|
|
78
|
+
start?(app: AppContext): Awaitable<void>;
|
|
79
|
+
drain?(app: AppContext): Awaitable<void>;
|
|
80
|
+
}
|
|
81
|
+
/** Declares one app. Its name is the key under which the generated code registers it. */
|
|
82
|
+
export declare function defineApp(definition: AppDefinition): AppDefinition;
|
|
83
|
+
interface DomainTarget {
|
|
84
|
+
readonly app: string;
|
|
85
|
+
readonly template: string;
|
|
86
|
+
}
|
|
87
|
+
export interface AppOptions {
|
|
88
|
+
readonly domains: ReadonlyMap<string, DomainTarget>;
|
|
89
|
+
readonly unknownDomain: string | undefined;
|
|
90
|
+
}
|
|
91
|
+
/** `{ apps: { <name>: defineApp(...) } }`, written by the CLI in src/dokebi.generated.ts. */
|
|
92
|
+
export interface AppEntry {
|
|
93
|
+
readonly apps: Readonly<Record<string, AppDefinition>>;
|
|
94
|
+
}
|
|
95
|
+
/** A host without its port, lower case; IPv6 literals keep their brackets. */
|
|
96
|
+
export declare function withoutPort(host: string): string;
|
|
97
|
+
/** The Host header without port. Apps use dokebi-web `requestHost`, which honours trustProxy. */
|
|
98
|
+
export declare function hostOf(request: {
|
|
99
|
+
headers: Record<string, string | string[] | undefined>;
|
|
100
|
+
}): string;
|
|
101
|
+
export interface AppGroupApi {
|
|
102
|
+
readonly names: readonly string[];
|
|
103
|
+
/** The app, template and domain for a request; undefined for an unknown host. */
|
|
104
|
+
resolve(request: FastifyRequest): AppInfo | undefined;
|
|
105
|
+
}
|
|
106
|
+
export declare const createPlugin: import("@dokebi/core").PluginFactory<AppGroupApi>;
|
|
107
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
import { stat } from 'node:fs/promises';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { types } from 'node:util';
|
|
4
|
+
import { createControllers, } from '@dokebi/controller';
|
|
5
|
+
import { definePlugin, dependencyOf, optionalDependency, providerDependency, } from '@dokebi/core';
|
|
6
|
+
const NAME = /^[a-z][a-z0-9-]{0,31}$/;
|
|
7
|
+
const HOST = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
|
|
8
|
+
const DEFAULT_TEMPLATE = 'default';
|
|
9
|
+
/** A module mount prefix: `/` or `/a/b`. */
|
|
10
|
+
const PREFIX = /^\/(?:[a-z0-9][a-z0-9._~-]*(?:\/[a-z0-9][a-z0-9._~-]*)*)?$/;
|
|
11
|
+
/** Read without importing @dokebi/module (see its MODULE_MOUNT). */
|
|
12
|
+
const MODULE_MOUNT = Symbol.for('dokebi.module.mount');
|
|
13
|
+
function mountOf(plugin) {
|
|
14
|
+
return plugin !== null && typeof plugin === 'object'
|
|
15
|
+
? plugin[MODULE_MOUNT]
|
|
16
|
+
: undefined;
|
|
17
|
+
}
|
|
18
|
+
/** `/board` + `/` → `/board`, `/board` + `/x` → `/board/x`, `/` + `/x` → `/x`. */
|
|
19
|
+
function joinPath(base, path) {
|
|
20
|
+
if (!base)
|
|
21
|
+
return path;
|
|
22
|
+
return path === '/' || path === '' ? base : base + (path.startsWith('/') ? path : '/' + path);
|
|
23
|
+
}
|
|
24
|
+
/** The Fastify route constraint that selects an app by request host. */
|
|
25
|
+
export const APP_CONSTRAINT = 'dokebiApp';
|
|
26
|
+
const defined = new WeakSet();
|
|
27
|
+
/** Declares one app. Its name is the key under which the generated code registers it. */
|
|
28
|
+
export function defineApp(definition) {
|
|
29
|
+
if (definition === null || typeof definition !== 'object' || types.isProxy(definition))
|
|
30
|
+
throw new TypeError('Invalid app definition');
|
|
31
|
+
for (const key of Object.keys(definition))
|
|
32
|
+
if (![
|
|
33
|
+
'requires',
|
|
34
|
+
'controllers',
|
|
35
|
+
'views',
|
|
36
|
+
'inertia',
|
|
37
|
+
'modules',
|
|
38
|
+
'shared',
|
|
39
|
+
'routes',
|
|
40
|
+
'sockets',
|
|
41
|
+
'setup',
|
|
42
|
+
'start',
|
|
43
|
+
'drain',
|
|
44
|
+
].includes(key))
|
|
45
|
+
throw new TypeError('Unknown app definition field: ' + key);
|
|
46
|
+
if (definition.requires !== undefined && !Array.isArray(definition.requires))
|
|
47
|
+
throw new TypeError('App requires must be an array');
|
|
48
|
+
if (definition.controllers !== undefined && !Array.isArray(definition.controllers))
|
|
49
|
+
throw new TypeError('App controllers must be an array');
|
|
50
|
+
if (definition.views !== undefined &&
|
|
51
|
+
(!(definition.views instanceof URL) || definition.views.protocol !== 'file:'))
|
|
52
|
+
throw new TypeError('App views must be a file: URL');
|
|
53
|
+
if (definition.modules !== undefined) {
|
|
54
|
+
if (!plain(definition.modules))
|
|
55
|
+
throw new TypeError('App modules must be a plain object');
|
|
56
|
+
for (const [prefix, plugin] of Object.entries(definition.modules)) {
|
|
57
|
+
if (!PREFIX.test(prefix))
|
|
58
|
+
throw new TypeError('Invalid module prefix: ' + prefix);
|
|
59
|
+
if (!mountOf(plugin))
|
|
60
|
+
throw new TypeError('App modules must be made with defineModule');
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
for (const hook of ['shared', 'routes', 'sockets', 'setup', 'start', 'drain'])
|
|
64
|
+
if (definition[hook] !== undefined && typeof definition[hook] !== 'function')
|
|
65
|
+
throw new TypeError(`App ${hook} must be a function`);
|
|
66
|
+
const frozen = Object.freeze({ ...definition });
|
|
67
|
+
defined.add(frozen);
|
|
68
|
+
return frozen;
|
|
69
|
+
}
|
|
70
|
+
function plain(value) {
|
|
71
|
+
return (value !== null &&
|
|
72
|
+
typeof value === 'object' &&
|
|
73
|
+
!Array.isArray(value) &&
|
|
74
|
+
!types.isProxy(value) &&
|
|
75
|
+
[Object.prototype, null].includes(Object.getPrototypeOf(value)));
|
|
76
|
+
}
|
|
77
|
+
function parseOptions(input) {
|
|
78
|
+
if (!plain(input))
|
|
79
|
+
throw new TypeError('Invalid dokebi-app options');
|
|
80
|
+
const { domains, unknownDomain, ...rest } = input;
|
|
81
|
+
if (Object.keys(rest).length || !plain(domains))
|
|
82
|
+
throw new TypeError('Invalid dokebi-app options');
|
|
83
|
+
const map = new Map();
|
|
84
|
+
for (const [host, target] of Object.entries(domains)) {
|
|
85
|
+
if (host.length > 253 || !HOST.test(host) || !plain(target))
|
|
86
|
+
throw new TypeError('Invalid domain entry');
|
|
87
|
+
const { app, template = DEFAULT_TEMPLATE, ...extra } = target;
|
|
88
|
+
if (Object.keys(extra).length ||
|
|
89
|
+
typeof app !== 'string' ||
|
|
90
|
+
!NAME.test(app) ||
|
|
91
|
+
typeof template !== 'string' ||
|
|
92
|
+
!NAME.test(template))
|
|
93
|
+
throw new TypeError('Invalid domain entry');
|
|
94
|
+
map.set(host, Object.freeze({ app, template }));
|
|
95
|
+
}
|
|
96
|
+
if (map.size > 1024)
|
|
97
|
+
throw new TypeError('Too many domains');
|
|
98
|
+
if (unknownDomain !== undefined && unknownDomain !== 'reject') {
|
|
99
|
+
if (typeof unknownDomain !== 'string' || !map.has(unknownDomain))
|
|
100
|
+
throw new TypeError('unknownDomain must be reject or a configured domain');
|
|
101
|
+
}
|
|
102
|
+
return Object.freeze({
|
|
103
|
+
domains: map,
|
|
104
|
+
unknownDomain: unknownDomain === 'reject' ? undefined : unknownDomain,
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
function parseEntry(input) {
|
|
108
|
+
if (input === undefined)
|
|
109
|
+
return new Map();
|
|
110
|
+
if (!plain(input) || Object.keys(input).some((key) => key !== 'apps') || !plain(input.apps))
|
|
111
|
+
throw new TypeError('Invalid dokebi-app entry');
|
|
112
|
+
const apps = new Map();
|
|
113
|
+
for (const [name, definition] of Object.entries(input.apps)) {
|
|
114
|
+
if (!NAME.test(name) || !defined.has(definition))
|
|
115
|
+
throw new TypeError('Apps must be made with defineApp and named ' + NAME.source);
|
|
116
|
+
apps.set(name, definition);
|
|
117
|
+
}
|
|
118
|
+
return apps;
|
|
119
|
+
}
|
|
120
|
+
const web = providerDependency({
|
|
121
|
+
name: 'dokebi-web',
|
|
122
|
+
version: '^0.1.0',
|
|
123
|
+
packageName: '@dokebi/web',
|
|
124
|
+
load: () => import('@dokebi/web'),
|
|
125
|
+
});
|
|
126
|
+
const ejs = providerDependency({
|
|
127
|
+
name: 'dokebi-template-ejs',
|
|
128
|
+
version: '^0.1.0',
|
|
129
|
+
packageName: '@dokebi/template-ejs',
|
|
130
|
+
load: () => import('@dokebi/template-ejs'),
|
|
131
|
+
});
|
|
132
|
+
const inertia = optionalDependency({
|
|
133
|
+
name: 'dokebi-template-inertia',
|
|
134
|
+
version: '^0.1.0',
|
|
135
|
+
});
|
|
136
|
+
const websocket = optionalDependency({ name: 'dokebi-websocket', version: '^0.1.0' });
|
|
137
|
+
const descriptors = new WeakMap();
|
|
138
|
+
/** Stable descriptor per requirement, so declared and runtime lookups use the same object. */
|
|
139
|
+
function requirement(value) {
|
|
140
|
+
if (value !== null &&
|
|
141
|
+
typeof value === 'object' &&
|
|
142
|
+
typeof value.setup === 'function') {
|
|
143
|
+
let descriptor = descriptors.get(value);
|
|
144
|
+
if (!descriptor) {
|
|
145
|
+
descriptor = dependencyOf(value);
|
|
146
|
+
descriptors.set(value, descriptor);
|
|
147
|
+
}
|
|
148
|
+
return descriptor;
|
|
149
|
+
}
|
|
150
|
+
if (value === null ||
|
|
151
|
+
typeof value !== 'object' ||
|
|
152
|
+
typeof value.name !== 'string')
|
|
153
|
+
throw new TypeError('Invalid app requirement');
|
|
154
|
+
return value;
|
|
155
|
+
}
|
|
156
|
+
/** A host without its port, lower case; IPv6 literals keep their brackets. */
|
|
157
|
+
export function withoutPort(host) {
|
|
158
|
+
const raw = host.toLowerCase();
|
|
159
|
+
if (raw.startsWith('['))
|
|
160
|
+
return raw.slice(0, raw.indexOf(']') + 1);
|
|
161
|
+
const colon = raw.lastIndexOf(':');
|
|
162
|
+
return colon === -1 ? raw : raw.slice(0, colon);
|
|
163
|
+
}
|
|
164
|
+
/** The Host header without port. Apps use dokebi-web `requestHost`, which honours trustProxy. */
|
|
165
|
+
export function hostOf(request) {
|
|
166
|
+
return withoutPort(String(request.headers.host ?? ''));
|
|
167
|
+
}
|
|
168
|
+
class AppRuntime {
|
|
169
|
+
options;
|
|
170
|
+
apps;
|
|
171
|
+
#mounted = [];
|
|
172
|
+
#declared;
|
|
173
|
+
constructor(options, apps, declared) {
|
|
174
|
+
this.options = options;
|
|
175
|
+
this.apps = apps;
|
|
176
|
+
this.#declared = new Map(declared.map((dependency) => [dependency.name, dependency]));
|
|
177
|
+
}
|
|
178
|
+
/** The descriptor this plugin declared under the same name (core requires that object). */
|
|
179
|
+
#declaredFor(name) {
|
|
180
|
+
const dependency = this.#declared.get(name);
|
|
181
|
+
if (!dependency)
|
|
182
|
+
throw new Error(`Plugin ${name} is not declared by dokebi-app`);
|
|
183
|
+
return dependency;
|
|
184
|
+
}
|
|
185
|
+
resolve(host) {
|
|
186
|
+
const domain = this.options.domains.has(host) ? host : this.options.unknownDomain;
|
|
187
|
+
const target = domain === undefined ? undefined : this.options.domains.get(domain);
|
|
188
|
+
return target ? { name: target.app, template: target.template, domain: host } : undefined;
|
|
189
|
+
}
|
|
190
|
+
async setup(context) {
|
|
191
|
+
for (const [host, target] of this.options.domains)
|
|
192
|
+
if (!this.apps.has(target.app))
|
|
193
|
+
throw new Error(`Domain ${host} points to app ${target.app}, which is not registered`);
|
|
194
|
+
const http = context.getDependency(web);
|
|
195
|
+
// Behind a trusted proxy (dokebi-web trustProxy) the forwarded host picks the app.
|
|
196
|
+
const host = (request) => withoutPort(http.requestHost(request));
|
|
197
|
+
http.constraint({
|
|
198
|
+
name: APP_CONSTRAINT,
|
|
199
|
+
storage() {
|
|
200
|
+
const values = new Map();
|
|
201
|
+
return {
|
|
202
|
+
get: (key) => (values.get(key) ?? null),
|
|
203
|
+
set: (key, value) => {
|
|
204
|
+
values.set(key, value);
|
|
205
|
+
},
|
|
206
|
+
};
|
|
207
|
+
},
|
|
208
|
+
deriveConstraint: (request) => this.resolve(host(request))?.name,
|
|
209
|
+
// Requests of a known app may still reach shared (unconstrained) routes.
|
|
210
|
+
mustMatchWhenDerived: false,
|
|
211
|
+
});
|
|
212
|
+
const pages = context.getOptionalDependency(inertia);
|
|
213
|
+
const sockets = context.getOptionalDependency(websocket);
|
|
214
|
+
for (const [name, definition] of this.apps) {
|
|
215
|
+
context.signal.throwIfAborted();
|
|
216
|
+
const allowed = new Set([...(definition.requires ?? []), ...Object.values(definition.modules ?? {})].map((item) => requirement(item).name));
|
|
217
|
+
let controllers;
|
|
218
|
+
const appContext = Object.freeze({
|
|
219
|
+
name,
|
|
220
|
+
logger: context.logger,
|
|
221
|
+
signal: context.signal,
|
|
222
|
+
get: (plugin) => {
|
|
223
|
+
if (!allowed.has(plugin.metadata.name))
|
|
224
|
+
throw new Error(`App ${name} does not list ${plugin.metadata.name} in requires`);
|
|
225
|
+
return context.get(plugin);
|
|
226
|
+
},
|
|
227
|
+
getDependency: (dependency) => {
|
|
228
|
+
if (!allowed.has(dependency.name))
|
|
229
|
+
throw new Error(`App ${name} does not list ${dependency.name} in requires`);
|
|
230
|
+
return context.getDependency(this.#declaredFor(dependency.name));
|
|
231
|
+
},
|
|
232
|
+
getOptionalDependency: (dependency) => {
|
|
233
|
+
if (!allowed.has(dependency.name))
|
|
234
|
+
throw new Error(`App ${name} does not list ${dependency.name} in requires`);
|
|
235
|
+
return context.getOptionalDependency(this.#declaredFor(dependency.name));
|
|
236
|
+
},
|
|
237
|
+
controller: (token) => {
|
|
238
|
+
if (!controllers)
|
|
239
|
+
throw new Error(`App ${name} has no controllers yet`);
|
|
240
|
+
return controllers.get(token);
|
|
241
|
+
},
|
|
242
|
+
defer: (cleanup) => context.defer(cleanup),
|
|
243
|
+
});
|
|
244
|
+
// Controller factories read plugins through the same restricted view.
|
|
245
|
+
const factoryContext = Object.freeze({
|
|
246
|
+
...context,
|
|
247
|
+
app: context.app,
|
|
248
|
+
logger: context.logger,
|
|
249
|
+
signal: context.signal,
|
|
250
|
+
drainSignal: context.drainSignal,
|
|
251
|
+
get: appContext.get,
|
|
252
|
+
getDependency: appContext.getDependency,
|
|
253
|
+
getOptionalDependency: appContext.getOptionalDependency,
|
|
254
|
+
defer: appContext.defer,
|
|
255
|
+
});
|
|
256
|
+
controllers = await createControllers(factoryContext, definition.controllers ?? []);
|
|
257
|
+
const templates = new Set();
|
|
258
|
+
let templateApi;
|
|
259
|
+
if (definition.views) {
|
|
260
|
+
templateApi = context.getDependency(ejs);
|
|
261
|
+
await templateApi.addDirectory(definition.views, name);
|
|
262
|
+
await this.#checkTemplates(name, definition.views, templates);
|
|
263
|
+
}
|
|
264
|
+
let inertiaApi;
|
|
265
|
+
if (definition.inertia) {
|
|
266
|
+
if (!pages)
|
|
267
|
+
throw new Error(`App ${name} uses Inertia; add @dokebi/template-inertia`);
|
|
268
|
+
inertiaApi = await pages.scope({
|
|
269
|
+
...definition.inertia,
|
|
270
|
+
shared: (request) => {
|
|
271
|
+
const info = this.resolve(host(request));
|
|
272
|
+
return { app: info ? { ...info } : null };
|
|
273
|
+
},
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
// Names are looked up in the app's templates; a module page looks first in the app's
|
|
277
|
+
// overrides for that module, then in the module's own views (D-0032 §4).
|
|
278
|
+
const appChain = (template) => template === DEFAULT_TEMPLATE
|
|
279
|
+
? [`${name}/${DEFAULT_TEMPLATE}`]
|
|
280
|
+
: [`${name}/${template}`, `${name}/${DEFAULT_TEMPLATE}`];
|
|
281
|
+
const chain = (template, module) => {
|
|
282
|
+
if (!module)
|
|
283
|
+
return appChain(template);
|
|
284
|
+
const own = module.views
|
|
285
|
+
? template === DEFAULT_TEMPLATE
|
|
286
|
+
? [`${module.views}/${DEFAULT_TEMPLATE}`]
|
|
287
|
+
: [`${module.views}/${template}`, `${module.views}/${DEFAULT_TEMPLATE}`]
|
|
288
|
+
: [];
|
|
289
|
+
return [
|
|
290
|
+
...appChain(template).map((prefix) => `${prefix}/${module.name}`),
|
|
291
|
+
...own,
|
|
292
|
+
...appChain(template),
|
|
293
|
+
];
|
|
294
|
+
};
|
|
295
|
+
// The app's shared data under the page data, computed once per render call.
|
|
296
|
+
const withShared = (view, request, info) => {
|
|
297
|
+
const data = async (own) => ({
|
|
298
|
+
...(await definition.shared?.(request, { app: info })),
|
|
299
|
+
...own,
|
|
300
|
+
});
|
|
301
|
+
return Object.freeze({
|
|
302
|
+
render: async (name, own, options) => view.render(name, await data(own), options),
|
|
303
|
+
reply: async (reply, name, own, options) => view.reply(reply, name, await data(own), options),
|
|
304
|
+
scope: (prefixes) => view.scope(prefixes),
|
|
305
|
+
});
|
|
306
|
+
};
|
|
307
|
+
const pageFor = (module) => {
|
|
308
|
+
const scopes = new Map();
|
|
309
|
+
const hasViews = Boolean(definition.views || module?.views);
|
|
310
|
+
return (request) => {
|
|
311
|
+
const info = this.resolve(host(request)) ?? {
|
|
312
|
+
name,
|
|
313
|
+
template: DEFAULT_TEMPLATE,
|
|
314
|
+
domain: host(request),
|
|
315
|
+
};
|
|
316
|
+
let view = scopes.get(info.template);
|
|
317
|
+
if (!view) {
|
|
318
|
+
templateApi ??= hasViews ? context.getDependency(ejs) : undefined;
|
|
319
|
+
view =
|
|
320
|
+
templateApi && hasViews
|
|
321
|
+
? templateApi.scope(chain(info.template, module))
|
|
322
|
+
: missingViews(name);
|
|
323
|
+
scopes.set(info.template, view);
|
|
324
|
+
}
|
|
325
|
+
return Object.freeze({
|
|
326
|
+
app: info,
|
|
327
|
+
module: module?.name,
|
|
328
|
+
base: module?.base ?? '',
|
|
329
|
+
view: definition.shared ? withShared(view, request, info) : view,
|
|
330
|
+
inertia: inertiaApi,
|
|
331
|
+
});
|
|
332
|
+
};
|
|
333
|
+
};
|
|
334
|
+
const routerFor = (page, base) => {
|
|
335
|
+
const add = (options) => {
|
|
336
|
+
const { handler, ...rest } = options;
|
|
337
|
+
http.route({
|
|
338
|
+
...rest,
|
|
339
|
+
url: joinPath(base, rest.url),
|
|
340
|
+
constraints: { [APP_CONSTRAINT]: name },
|
|
341
|
+
handler(request, reply) {
|
|
342
|
+
return handler(request, reply, page(request));
|
|
343
|
+
},
|
|
344
|
+
});
|
|
345
|
+
};
|
|
346
|
+
const method = (verb) => (url, handler, options = {}) => add({ ...options, method: verb, url, handler });
|
|
347
|
+
return Object.freeze({
|
|
348
|
+
route: add,
|
|
349
|
+
get: method('GET'),
|
|
350
|
+
post: method('POST'),
|
|
351
|
+
put: method('PUT'),
|
|
352
|
+
patch: method('PATCH'),
|
|
353
|
+
delete: method('DELETE'),
|
|
354
|
+
});
|
|
355
|
+
};
|
|
356
|
+
const mountSockets = (routes, base, owner) => {
|
|
357
|
+
for (const route of routes) {
|
|
358
|
+
if (!sockets)
|
|
359
|
+
throw new Error(`${owner} has sockets; add @dokebi/websocket`);
|
|
360
|
+
sockets.route({
|
|
361
|
+
...route,
|
|
362
|
+
path: joinPath(base, route.path),
|
|
363
|
+
constraints: { ...(route.constraints ?? {}), [APP_CONSTRAINT]: name },
|
|
364
|
+
// Each app is its own tenant space in the hub: presence and broadcasts stay inside.
|
|
365
|
+
authenticate: async (request) => {
|
|
366
|
+
const identity = await route.authenticate(request);
|
|
367
|
+
return identity ? { ...identity, tenant: `${name}:${identity.tenant}` } : undefined;
|
|
368
|
+
},
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
await definition.setup?.(appContext);
|
|
373
|
+
await definition.routes?.(routerFor(pageFor(), ''), appContext);
|
|
374
|
+
mountSockets((await definition.sockets?.(appContext)) ?? [], '', `App ${name}`);
|
|
375
|
+
// Mounted modules (D-0032): their routes and sockets under the prefix, on this app only.
|
|
376
|
+
for (const [prefix, plugin] of Object.entries(definition.modules ?? {})) {
|
|
377
|
+
const mount = mountOf(plugin);
|
|
378
|
+
const base = prefix === '/' ? '' : prefix;
|
|
379
|
+
const module = mount.context();
|
|
380
|
+
const page = pageFor({ name: mount.name, views: mount.views, base });
|
|
381
|
+
await mount.routes?.(routerFor(page, base), module);
|
|
382
|
+
mountSockets(
|
|
383
|
+
// defineSocket results; the module types them by shape only.
|
|
384
|
+
((await mount.sockets?.(module)) ?? []), base, `Module ${mount.name} (app ${name})`);
|
|
385
|
+
}
|
|
386
|
+
this.#mounted.push({ name, definition, context: appContext });
|
|
387
|
+
}
|
|
388
|
+
return Object.freeze({
|
|
389
|
+
names: Object.freeze([...this.apps.keys()]),
|
|
390
|
+
resolve: (request) => this.resolve(host(request)),
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
/** Every template a domain selects must exist as a folder, and `default` always must. */
|
|
394
|
+
async #checkTemplates(name, views, found) {
|
|
395
|
+
const wanted = new Set([DEFAULT_TEMPLATE]);
|
|
396
|
+
for (const target of this.options.domains.values())
|
|
397
|
+
if (target.app === name)
|
|
398
|
+
wanted.add(target.template);
|
|
399
|
+
for (const template of wanted) {
|
|
400
|
+
const folder = fileURLToPath(new URL(`${template}/`, views));
|
|
401
|
+
const info = await stat(folder).catch(() => undefined);
|
|
402
|
+
if (!info?.isDirectory())
|
|
403
|
+
throw new Error(`App ${name} has no views/${template}/ folder`);
|
|
404
|
+
found.add(template);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
async start() {
|
|
408
|
+
for (const { definition, context } of this.#mounted)
|
|
409
|
+
await definition.start?.(context);
|
|
410
|
+
}
|
|
411
|
+
async drain() {
|
|
412
|
+
await Promise.all(this.#mounted.map(({ definition, context }) => definition.drain?.(context)));
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
function missingViews(name) {
|
|
416
|
+
const fail = async () => {
|
|
417
|
+
throw new Error(`App ${name} has no views folder`);
|
|
418
|
+
};
|
|
419
|
+
const api = Object.freeze({ render: fail, reply: fail, scope: () => api });
|
|
420
|
+
return api;
|
|
421
|
+
}
|
|
422
|
+
export const createPlugin = definePlugin({
|
|
423
|
+
name: 'dokebi-app',
|
|
424
|
+
version: '0.1.1',
|
|
425
|
+
core: '^0.2.0',
|
|
426
|
+
options: parseOptions,
|
|
427
|
+
entry: parseEntry,
|
|
428
|
+
dependencies: ({ entry }) => {
|
|
429
|
+
const apps = [...(entry ?? new Map()).values()];
|
|
430
|
+
const list = [web];
|
|
431
|
+
if (apps.some((app) => app.views || Object.values(app.modules ?? {}).some((module) => mountOf(module)?.views)))
|
|
432
|
+
list.push(ejs);
|
|
433
|
+
list.push(inertia, websocket);
|
|
434
|
+
for (const app of apps)
|
|
435
|
+
for (const item of [...(app.requires ?? []), ...Object.values(app.modules ?? {})]) {
|
|
436
|
+
const dependency = requirement(item);
|
|
437
|
+
if (!list.some((existing) => existing.name === dependency.name))
|
|
438
|
+
list.push(dependency);
|
|
439
|
+
}
|
|
440
|
+
return list;
|
|
441
|
+
},
|
|
442
|
+
instance: ({ options, entry, dependencies }) => new AppRuntime(options, entry ?? new Map(), dependencies),
|
|
443
|
+
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"type": "object",
|
|
4
|
+
"additionalProperties": false,
|
|
5
|
+
"required": ["domains"],
|
|
6
|
+
"properties": {
|
|
7
|
+
"domains": {
|
|
8
|
+
"type": "object",
|
|
9
|
+
"description": "Host name (no port, lower case) -> the app and template that answer it",
|
|
10
|
+
"maxProperties": 1024,
|
|
11
|
+
"propertyNames": {
|
|
12
|
+
"pattern": "^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$",
|
|
13
|
+
"maxLength": 253
|
|
14
|
+
},
|
|
15
|
+
"additionalProperties": {
|
|
16
|
+
"type": "object",
|
|
17
|
+
"additionalProperties": false,
|
|
18
|
+
"required": ["app"],
|
|
19
|
+
"properties": {
|
|
20
|
+
"app": { "type": "string", "pattern": "^[a-z][a-z0-9-]{0,31}$" },
|
|
21
|
+
"template": {
|
|
22
|
+
"type": "string",
|
|
23
|
+
"pattern": "^[a-z][a-z0-9-]{0,31}$",
|
|
24
|
+
"description": "Folder under the app views; default: default"
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"unknownDomain": {
|
|
30
|
+
"type": "string",
|
|
31
|
+
"description": "reject (404, default) or a key of domains whose app and template answer unknown hosts"
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,101 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dokebi/app",
|
|
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/module": "^0.1.0",
|
|
35
|
+
"@dokebi/template-ejs": "^0.1.0",
|
|
36
|
+
"@dokebi/template-inertia": "^0.1.0",
|
|
37
|
+
"@dokebi/web": "^0.1.0",
|
|
38
|
+
"@dokebi/websocket": "^0.1.0",
|
|
39
|
+
"fastify": "^5.12.7"
|
|
40
|
+
},
|
|
41
|
+
"peerDependenciesMeta": {
|
|
42
|
+
"@dokebi/template-inertia": {
|
|
43
|
+
"optional": true
|
|
44
|
+
},
|
|
45
|
+
"@dokebi/websocket": {
|
|
46
|
+
"optional": true
|
|
47
|
+
},
|
|
48
|
+
"@dokebi/module": {
|
|
49
|
+
"optional": true
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
"devDependencies": {
|
|
53
|
+
"@dokebi/module": "^0.1.0",
|
|
54
|
+
"@dokebi/template-inertia": "^0.1.0",
|
|
55
|
+
"@dokebi/websocket": "^0.1.0"
|
|
56
|
+
},
|
|
57
|
+
"dokebi": {
|
|
58
|
+
"schemaVersion": 2,
|
|
59
|
+
"id": "dokebi-app",
|
|
60
|
+
"core": "^0.2.0",
|
|
61
|
+
"dependencies": [
|
|
62
|
+
{
|
|
63
|
+
"name": "dokebi-web",
|
|
64
|
+
"version": "^0.1.0",
|
|
65
|
+
"package": "@dokebi/web"
|
|
66
|
+
},
|
|
67
|
+
{
|
|
68
|
+
"name": "dokebi-controller",
|
|
69
|
+
"version": "^0.1.0",
|
|
70
|
+
"package": "@dokebi/controller"
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
"name": "dokebi-template-ejs",
|
|
74
|
+
"version": "^0.1.0",
|
|
75
|
+
"package": "@dokebi/template-ejs"
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
"name": "dokebi-template-inertia",
|
|
79
|
+
"version": "^0.1.0",
|
|
80
|
+
"optional": true
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
"name": "dokebi-websocket",
|
|
84
|
+
"version": "^0.1.0",
|
|
85
|
+
"optional": true
|
|
86
|
+
}
|
|
87
|
+
],
|
|
88
|
+
"optionsSchema": "options.schema.json",
|
|
89
|
+
"documentation": "AI.md",
|
|
90
|
+
"install": {
|
|
91
|
+
"directories": [
|
|
92
|
+
"src/apps",
|
|
93
|
+
"src/shared/models"
|
|
94
|
+
]
|
|
95
|
+
}
|
|
96
|
+
},
|
|
97
|
+
"publishConfig": {
|
|
98
|
+
"access": "public",
|
|
99
|
+
"registry": "https://registry.npmjs.org/"
|
|
100
|
+
}
|
|
101
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// One app of this project (D-0030). Its name is the folder name; the domains that show it are
|
|
2
|
+
// listed in dokebi.yaml under options.dokebi-app.domains.
|
|
3
|
+
import { defineApp } from '@dokebi/app';
|
|
4
|
+
import { homeController } from './controllers/home.ts';
|
|
5
|
+
import { routes } from './routes.ts';
|
|
6
|
+
|
|
7
|
+
export default defineApp({
|
|
8
|
+
// Plugins and shared modules (src/shared/modules) this app uses, e.g. [dependency] from @dokebi/db.
|
|
9
|
+
requires: [],
|
|
10
|
+
controllers: [homeController],
|
|
11
|
+
// One folder per template; `default` is required, others hold only the files they change.
|
|
12
|
+
// Names not found here come from src/shared/views (for example layouts/main).
|
|
13
|
+
views: new URL('./views/', import.meta.url),
|
|
14
|
+
routes,
|
|
15
|
+
});
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { AppInfo } from '@dokebi/app';
|
|
2
|
+
import { defineController } from '@dokebi/controller';
|
|
3
|
+
import { describe } from '../models/site.ts';
|
|
4
|
+
|
|
5
|
+
export class HomeController {
|
|
6
|
+
home(app: AppInfo) {
|
|
7
|
+
return { title: app.name, message: describe(app) };
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export const homeController = defineController('home', () => new HomeController());
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { AppContext, AppRouter } from '@dokebi/app';
|
|
2
|
+
import { homeController } from './controllers/home.ts';
|
|
3
|
+
|
|
4
|
+
export function routes(route: AppRouter, app: AppContext): void {
|
|
5
|
+
// `page` knows which app, template and domain answered, and renders with that template.
|
|
6
|
+
// The layout (layouts/main) comes from src/shared/views unless this app's views have one.
|
|
7
|
+
route.get('/', (_request, reply, page) =>
|
|
8
|
+
page.view.reply(reply, 'home', app.controller(homeController).home(page.app)),
|
|
9
|
+
);
|
|
10
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// One Inertia app of this project (D-0030, D-0031). Its name is the folder name; the domains
|
|
2
|
+
// that show it are listed in dokebi.yaml under options.dokebi-app.domains.
|
|
3
|
+
import { defineApp } from '@dokebi/app';
|
|
4
|
+
import { homeController } from './controllers/home.ts';
|
|
5
|
+
import { routes } from './routes.ts';
|
|
6
|
+
|
|
7
|
+
export default defineApp({
|
|
8
|
+
// Plugins and shared modules (src/shared/modules) this app uses.
|
|
9
|
+
requires: [],
|
|
10
|
+
controllers: [homeController],
|
|
11
|
+
// views/<template>/ holds the Vue pages; `default` is required, others hold only what changes.
|
|
12
|
+
views: new URL('./views/', import.meta.url),
|
|
13
|
+
// The page title, and the Vite build of views/app.js (`npm run build`, see vite.config.ts).
|
|
14
|
+
// @dokebi/template-inertia serves the built files at /build/.
|
|
15
|
+
inertia: {
|
|
16
|
+
title: '{{app}}',
|
|
17
|
+
vite: {
|
|
18
|
+
manifest: 'dist/.vite/manifest.json',
|
|
19
|
+
entry: 'src/apps/{{app}}/views/app.js',
|
|
20
|
+
base: '/build/',
|
|
21
|
+
},
|
|
22
|
+
},
|
|
23
|
+
routes,
|
|
24
|
+
});
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { AppInfo } from '@dokebi/app';
|
|
2
|
+
import { defineController } from '@dokebi/controller';
|
|
3
|
+
import { describe } from '../models/site.ts';
|
|
4
|
+
|
|
5
|
+
export class HomeController {
|
|
6
|
+
home(app: AppInfo) {
|
|
7
|
+
return { title: app.name, message: describe(app) };
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export const homeController = defineController('home', () => new HomeController());
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { AppContext, AppRouter } from '@dokebi/app';
|
|
2
|
+
import { homeController } from './controllers/home.ts';
|
|
3
|
+
|
|
4
|
+
export function routes(route: AppRouter, app: AppContext): void {
|
|
5
|
+
// Inertia renders views/<template>/Pages/Home.vue (falling back to views/default/).
|
|
6
|
+
route.get('/', (request, reply, page) => {
|
|
7
|
+
if (!page.inertia) throw new Error('Add @dokebi/template-inertia for this app');
|
|
8
|
+
return page.inertia.render(
|
|
9
|
+
request,
|
|
10
|
+
reply,
|
|
11
|
+
'Home',
|
|
12
|
+
app.controller(homeController).home(page.app),
|
|
13
|
+
);
|
|
14
|
+
});
|
|
15
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// Browser entry of this app (Vite input). Pages and the layout are looked up in the template the
|
|
2
|
+
// domain selected and then in `default`, like the EJS views. The template comes from the shared
|
|
3
|
+
// prop `app.template` (dokebi-app) of the first page; it is fixed for a domain.
|
|
4
|
+
import { createInertiaApp } from '@inertiajs/vue3';
|
|
5
|
+
import { createApp, createSSRApp, h } from 'vue';
|
|
6
|
+
|
|
7
|
+
const files = import.meta.glob('./*/{Layout,Pages/*}.vue', { eager: true });
|
|
8
|
+
const first = JSON.parse(document.querySelector('script[data-page]')?.textContent || '{}');
|
|
9
|
+
const template = first.props?.app?.template ?? 'default';
|
|
10
|
+
const pick = (path) => files[`./${template}/${path}.vue`] ?? files[`./default/${path}.vue`];
|
|
11
|
+
|
|
12
|
+
createInertiaApp({
|
|
13
|
+
resolve(name) {
|
|
14
|
+
const page = pick(`Pages/${name}`);
|
|
15
|
+
if (!page) throw new Error(`Unknown page: ${name}`);
|
|
16
|
+
return page;
|
|
17
|
+
},
|
|
18
|
+
// The layout of the domain's template, unless a page sets its own (same as views/ssr.js).
|
|
19
|
+
layout: () => pick('Layout')?.default,
|
|
20
|
+
setup({ el, App, props, plugin }) {
|
|
21
|
+
// A page rendered on the server (`dokebi app add --inertia --ssr`) is hydrated in place.
|
|
22
|
+
const create = el.hasAttribute('data-server-rendered') ? createSSRApp : createApp;
|
|
23
|
+
create({ render: () => h(App, props) })
|
|
24
|
+
.use(plugin)
|
|
25
|
+
.mount(el);
|
|
26
|
+
},
|
|
27
|
+
});
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// One Inertia app of this project (D-0030, D-0031). Its name is the folder name; the domains
|
|
2
|
+
// that show it are listed in dokebi.yaml under options.dokebi-app.domains.
|
|
3
|
+
import { defineApp } from '@dokebi/app';
|
|
4
|
+
import { homeController } from './controllers/home.ts';
|
|
5
|
+
import { routes } from './routes.ts';
|
|
6
|
+
|
|
7
|
+
export default defineApp({
|
|
8
|
+
// Plugins and shared modules (src/shared/modules) this app uses.
|
|
9
|
+
requires: [],
|
|
10
|
+
controllers: [homeController],
|
|
11
|
+
// views/<template>/ holds the Vue pages; `default` is required, others hold only what changes.
|
|
12
|
+
views: new URL('./views/', import.meta.url),
|
|
13
|
+
// The page title, the Vite build of views/app.js (`npm run build`, see vite.config.ts) and the
|
|
14
|
+
// server build of views/ssr.js that renders the first HTML of a page (D-0039,
|
|
15
|
+
// vite.ssr.config.ts). @dokebi/template-inertia serves the browser files at /build/.
|
|
16
|
+
inertia: {
|
|
17
|
+
title: '{{app}}',
|
|
18
|
+
ssr: { bundle: 'dist/ssr/{{app}}/ssr.js' },
|
|
19
|
+
vite: {
|
|
20
|
+
manifest: 'dist/.vite/manifest.json',
|
|
21
|
+
entry: 'src/apps/{{app}}/views/app.js',
|
|
22
|
+
base: '/build/',
|
|
23
|
+
},
|
|
24
|
+
},
|
|
25
|
+
routes,
|
|
26
|
+
});
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Server entry of this app (D-0039). `npm run build` bakes it into dist/ssr/{{app}}/ssr.js (see
|
|
2
|
+
// vite.ssr.config.ts); app.ts names that file in `inertia.ssr.bundle`, and
|
|
3
|
+
// @dokebi/template-inertia calls render(page) for the first HTML of every page. Pages and the
|
|
4
|
+
// layout are looked up as views/app.js does in the browser, so both draw the same markup.
|
|
5
|
+
import { createInertiaApp } from '@inertiajs/vue3';
|
|
6
|
+
import { renderToString } from 'vue/server-renderer';
|
|
7
|
+
|
|
8
|
+
const files = import.meta.glob('./*/{Layout,Pages/*}.vue', { eager: true });
|
|
9
|
+
|
|
10
|
+
export async function render(page) {
|
|
11
|
+
const template = page.props?.app?.template ?? 'default';
|
|
12
|
+
const pick = (path) => files[`./${template}/${path}.vue`] ?? files[`./default/${path}.vue`];
|
|
13
|
+
// On the server, createInertiaApp without `page` returns (page, renderToString).
|
|
14
|
+
const app = await createInertiaApp({
|
|
15
|
+
resolve(name) {
|
|
16
|
+
const found = pick(`Pages/${name}`);
|
|
17
|
+
if (!found) throw new Error(`Unknown page: ${name}`);
|
|
18
|
+
return found;
|
|
19
|
+
},
|
|
20
|
+
// Requests of different templates render at the same time, so the page modules are not
|
|
21
|
+
// changed: the layout of this request's template is the default layout.
|
|
22
|
+
layout: () => pick('Layout')?.default,
|
|
23
|
+
});
|
|
24
|
+
return app(page, renderToString);
|
|
25
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Builds the browser side of every Inertia app (src/apps/<app>/views/app.js) into dist/ with a
|
|
2
|
+
// manifest. Each app reads the manifest through `inertia.vite` in its app.ts, and
|
|
3
|
+
// @dokebi/template-inertia serves the built files at /build/. New Inertia apps are found
|
|
4
|
+
// automatically. Written once by `dokebi app add --inertia`; this file is yours to change.
|
|
5
|
+
import { existsSync, readdirSync } from 'node:fs';
|
|
6
|
+
import vue from '@vitejs/plugin-vue';
|
|
7
|
+
import { defineConfig } from 'vite';
|
|
8
|
+
|
|
9
|
+
const apps = readdirSync('src/apps', { withFileTypes: true })
|
|
10
|
+
.filter((entry) => entry.isDirectory() && existsSync(`src/apps/${entry.name}/views/app.js`))
|
|
11
|
+
.map((entry) => entry.name);
|
|
12
|
+
|
|
13
|
+
export default defineConfig({
|
|
14
|
+
base: '/build/',
|
|
15
|
+
publicDir: false,
|
|
16
|
+
plugins: [vue()],
|
|
17
|
+
build: {
|
|
18
|
+
outDir: 'dist',
|
|
19
|
+
emptyOutDir: true,
|
|
20
|
+
manifest: true,
|
|
21
|
+
rollupOptions: {
|
|
22
|
+
input: Object.fromEntries(apps.map((app) => [app, `src/apps/${app}/views/app.js`])),
|
|
23
|
+
},
|
|
24
|
+
},
|
|
25
|
+
});
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Server build of every Inertia app that renders its first HTML on the server (D-0039):
|
|
2
|
+
// src/apps/<app>/views/ssr.js becomes dist/ssr/<app>/ssr.js, which the app names in
|
|
3
|
+
// `inertia.ssr.bundle`. Runs after the browser build (`npm run build`), whose emptyOutDir clears
|
|
4
|
+
// dist/ first. dist/ssr/ is not served: @dokebi/template-inertia serves only the manifest's
|
|
5
|
+
// files. Written once by `dokebi app add --inertia --ssr`; this file is yours to change.
|
|
6
|
+
import { existsSync, readdirSync } from 'node:fs';
|
|
7
|
+
import vue from '@vitejs/plugin-vue';
|
|
8
|
+
import { defineConfig } from 'vite';
|
|
9
|
+
|
|
10
|
+
const apps = readdirSync('src/apps', { withFileTypes: true })
|
|
11
|
+
.filter((entry) => entry.isDirectory() && existsSync(`src/apps/${entry.name}/views/ssr.js`))
|
|
12
|
+
.map((entry) => entry.name);
|
|
13
|
+
|
|
14
|
+
export default defineConfig({
|
|
15
|
+
publicDir: false,
|
|
16
|
+
plugins: [vue()],
|
|
17
|
+
build: {
|
|
18
|
+
outDir: 'dist/ssr',
|
|
19
|
+
emptyOutDir: true,
|
|
20
|
+
ssr: true,
|
|
21
|
+
rollupOptions: {
|
|
22
|
+
input: Object.fromEntries(apps.map((app) => [app, `src/apps/${app}/views/ssr.js`])),
|
|
23
|
+
output: { entryFileNames: '[name]/ssr.js' },
|
|
24
|
+
},
|
|
25
|
+
},
|
|
26
|
+
});
|