@dokebi/app 0.2.0 → 0.4.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/README.md CHANGED
@@ -1,136 +1,138 @@
1
- # @dokebi/app 0.2.0
1
+ # @dokebi/app 0.4.1
2
2
 
3
- 한 프로젝트 안에 여러 앱을 두고, 요청 도메인으로 앱과 템플릿을 고르는 선택 플러그인이다. Node >=24.0.0, core ^0.2.0의 선택 패키지다(npm 공개). 설계는 [D-0030](../../docs/decisions/D-0030-multi-app-and-domains.md)이다.
3
+ An optional plugin for several apps in one project that picks the app and template by request domain. An optional package for Node >=24.0.0 and core ^0.4.0 (public on npm). The design is [D-0030](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0030-multi-app-and-domains.md).
4
4
 
5
- ## 설치
5
+ ## Install
6
6
 
7
7
  ```sh
8
8
  dokebi add @dokebi/app
9
9
  ```
10
10
 
11
- 필수 플러그인 dokebi-web·dokebi-controller·dokebi-template-ejs가 같은 변경에서 함께 설치되고(결과 `autoInstalled`), 첫 앱 `src/apps/main`과 `domains: { localhost: { app: main } }`가 만들어진다. 앱을 더 만들 때:
11
+ The required plugins dokebi-web, dokebi-controller and dokebi-template-ejs are installed in the same change (result `autoInstalled`), and the first app `src/apps/main` and `domains: { localhost: { app: main } }` are created. template-ejs comes along at install time because the first app is an EJS skeleton. At run time app collects view engines (`ejs`, `inertia`) and realtime transports (`websocket`, `sse`) by name from @dokebi/web's contribution points and never imports those packages (D-0063 §5). Errors are `AppError` (`VIEW_ENGINE_MISSING`, `REALTIME_UNAVAILABLE` and so on, [AI.md](AI.md) §6). To add more apps:
12
12
 
13
13
  ```sh
14
14
  dokebi app add shop --domain a.com --domain www.a.com
15
- dokebi app link shop b.com --template christmas # 기존 앱에 도메인 더하기
15
+ dokebi app link shop b.com --template christmas # add a domain to an existing app
16
16
  dokebi app unlink b.com
17
17
  dokebi app list
18
- dokebi app remove shop # 그 앱을 가리키는 도메인을 먼저 지운다. 폴더는 남는다.
18
+ dokebi app remove shop # remove the domains pointing at the app first; the folder stays
19
19
  ```
20
20
 
21
- 도메인 연결은 dokebi.yaml과 dokebi.example.yaml에 함께 남는다. Inertia 화면, WebSocket, SSE를 쓰는 앱이 있으면 `dokebi add @dokebi/template-inertia`, `dokebi add @dokebi/websocket`, `dokebi add @dokebi/sse`를 따로 한다.
21
+ Domain links are recorded in both dokebi.yaml and dokebi.example.yaml. When an app uses Inertia pages, WebSocket or SSE, run `dokebi add @dokebi/template-inertia`, `dokebi add @dokebi/websocket` or `dokebi add @dokebi/sse` separately.
22
22
 
23
- ## 폴더 구조
23
+ ## Folder layout
24
24
 
25
- [D-0031](../../docs/decisions/D-0031-project-layout.md)을 따른다. 앱 폴더는 `dokebi app add`가 만든다.
25
+ It follows [D-0031](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0031-project-layout.md). `dokebi app add` creates the app folder.
26
26
 
27
27
  ```
28
- src/apps/<앱>/
28
+ src/apps/<app>/
29
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)·공통 뷰
30
+ routes.ts routes
31
+ controllers/ defineController tokens (this app only)
32
+ models/ plain code (not plugins)
33
+ views/default/ the default template (required). EJS apps: home.ejs; Inertia apps: Layout.vue, Pages/Home.vue
34
+ views/<template>/ only the files that change; missing files are looked up in default, then shared src/shared/views
35
+ views/app.js (Inertia apps only) Vite entry: finds per-template pages and layouts in the same order
36
+ sockets/ this app's WebSocket routes (defineSocket), created when needed
37
+ src/shared/ controllers, models, modules (dokebi-module) and views shared by several apps
38
38
  ```
39
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)에 있다.
40
+ - `dokebi app add <app> --inertia` creates an Inertia skeleton and prepares the build (`vite.config.ts`, the `build` script, Vite and Vue dev dependencies, `dist/` in `.gitignore`). Run `npm run build` afterwards.
41
+ - With `--ssr` ([D-0039](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0039-inertia-ssr.md)) it also creates the server entry `views/ssr.js`, `inertia.ssr: { bundle: 'dist/ssr/<app>/ssr.js' }` in app.ts and the project's `vite.ssr.config.ts`, and `build` runs both the browser and the server build (a previously generated script with only `vite build` becomes both; a script you wrote yourself is kept and reported as `BUILD_SCRIPT_KEPT`). The browser entry `views/app.js` hydrates the server-rendered page with `createSSRApp`. Layouts are chosen with the `layout` option instead of changing the page module (requests with different templates render on the server at the same time).
42
+ - @dokebi/template-inertia serves the build files under `/build/`. Details are in the [CLI docs](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/cli/README.md).
43
43
 
44
- 앱 이름은 폴더 이름이다. 생성 등록 코드(src/dokebi.generated.ts)가 `.dokebi/state.json`의 앱 목록대로 `./apps/<앱>/app.ts`를 가져와 이 플러그인의 entry `{ apps: { <앱>: ... } }`로 넘긴다.
44
+ The app name is the folder name. The generated registration code (src/dokebi.generated.ts) imports `./apps/<app>/app.ts` for every app listed in `.dokebi/state.json` and passes them to this plugin as entry `{ apps: { <app>: ... } }`.
45
45
 
46
- ## 설정
46
+ ## Configuration
47
47
 
48
48
  ```yaml
49
49
  dokebi-app:
50
50
  domains:
51
- a.com: { app: shop } # template 생략 = default
51
+ a.com: { app: shop } # no template = default
52
52
  b.com: { app: shop, template: christmas }
53
53
  c.com: { app: admin }
54
- s.com: { app: shop, seal: true } # 이 호스트의 WebSocket 프레임을 모두 봉인(아래)
55
- unknownDomain: reject # 기본. 또는 domains의 키 하나(그 설정으로 응답)
56
- apps: # 선택. 키는 정의된 앱 이름(아니면 시작 실패 UNKNOWN_APP)
57
- shop: { realtime: { namespaces: [front] } } # 기본은 [<앱>]
58
- admin: { realtime: { namespaces: [admin, front] } } # 아래 「실시간 네임스페이스」
54
+ s.com: { app: shop, seal: true } # seal every WebSocket frame of this host (below)
55
+ unknownDomain: reject # default; or a key of domains (answered with those settings)
56
+ apps: # optional; keys are defined app names (otherwise the start fails with UNKNOWN_APP)
57
+ shop: { realtime: { namespaces: [front] } } # default [<app>]
58
+ admin: { realtime: { namespaces: [admin, front] } } # see "Realtime namespaces" below
59
59
  ```
60
60
 
61
- dokebi-web `requestHost()`가 준 호스트(신뢰 프락시면 `X-Forwarded-Host`)에서 포트를 떼고 소문자로 정확히 비교한다. 프락시 뒤라면 dokebi-web `trustProxy`에 프락시 주소를 적는다. 와일드카드·경로 접두사는 아직 없다. 시작할 때 없는 앱, 없는 템플릿 폴더, `views/default/` 누락을 거부한다.
61
+ The host from dokebi-web's `requestHost()` (`X-Forwarded-Host` from a trusted proxy) is compared exactly, without the port and in lower case. Behind a proxy, list the proxy addresses in dokebi-web `trustProxy`. There are no wildcards or path prefixes yet. The start refuses unknown apps, missing template folders and a missing `views/default/`.
62
62
 
63
63
  ## defineApp
64
64
 
65
- ```ts
65
+ ```ts snippet
66
66
  import { defineApp } from '@dokebi/app';
67
67
  import { dependency as db } from '@dokebi/db';
68
68
 
69
69
  export default defineApp({
70
- requires: [db], // 이 앱이 쓰는 플러그인·공통 모듈
70
+ requires: [db], // plugins and shared modules this app uses
71
71
  controllers: [productController],
72
72
  views: new URL('./views/', import.meta.url),
73
73
  inertia: { vite: { manifest: 'dist/.vite/manifest.json', entry: 'src/apps/shop/views/app.js', base: '/build/' } },
74
- modules: { '/board': board }, // 기능 모듈을 접두사로 붙인다(D-0032)
75
- shared: (request, page) => ({ menu: MENU }), // 이 앱의 모든 EJS 페이지에 합칠 데이터
74
+ modules: { '/board': board }, // mounts a feature module under a prefix (D-0032)
75
+ shared: (request, page) => ({ menu: MENU }), // data merged into every EJS page of this app
76
76
  routes(route, app) {
77
77
  route.get('/', (request, reply, page) =>
78
78
  page.view.reply(reply, 'home', app.controller(productController).list(), { layout: 'layouts/main' }),
79
79
  );
80
80
  },
81
- sockets: (app) => [chatSocket(app)], // defineSocket(...) 결과
82
- events: (app) => [ordersStream(app)], // @dokebi/sse 라우트(SseRoute)
81
+ sockets: (app) => [chatSocket(app)], // results of defineSocket(...)
82
+ events: (app) => [ordersStream(app)], // @dokebi/sse routes (SseRoute)
83
83
  setup(app) {}, start(app) {}, drain(app) {},
84
84
  });
85
85
  ```
86
86
 
87
- - 핸들러의 `page`는 `{ app: { name, template, domain }, module, base, view, inertia, sealed }`다. 앱 라우트에서 `module`은 undefined, `base`는 `''`다. `view`는 `<앱>/<템플릿>` → `<앱>/default` → 공통 src/shared/views 순서로 찾는 EJS 렌더러이고, 레이아웃과 `$include`도 같은 순서를 따른다. `inertia`는 앱의 문서 설정(Vite 진입점 등)을 쓰고 공통 props에 `app`을 더한다.
88
- - **모듈 붙이기([D-0032](../../docs/decisions/D-0032-feature-modules.md)):** `modules: { '/접두사': 모듈 }`. 모듈은 `defineModule`로 만든 것이다.
89
- - 모듈의 `routes`는 이 앱의 라우트 제약과 접두사로 등록된다. 핸들러 `page.module`·`page.base`가 채워진다.
90
- - 모듈의 `sockets`는 접두사 아래 경로로 등록된다. tenant는 앱 소켓과 같은 `<네임스페이스>:<tenant>`다.
91
- - 같은 모듈을 여러 앱이 다른 접두사로 붙일 수 있다. 붙인 모듈은 `requires`에 넣지 않아도 `app.get(모듈)`로 API를 읽는다.
92
- - 접두사는 `/` 또는 `/a/b`(소문자·숫자·`.`·`_`·`~`·`-`)다.
93
- - 모듈 페이지의 화면 찾는 순서는 다음과 같다. 그래서 모듈 화면은 앱 레이아웃 안에 그려진다.
94
- 1. `<앱>/<템플릿>/<모듈>`
95
- 2. `<앱>/default/<모듈>`
96
- 3. 모듈의 `<템플릿>`
97
- 4. 모듈의 `default`
98
- 5. 앱 views
99
- 6. 공통
100
- - **`shared(request, { app })`:** 이 앱이 그리는 모든 EJS 페이지(앱 라우트와 모듈 라우트)의 데이터 밑에 합쳐진다. 겹치는 키는 페이지 데이터가 이긴다. 레이아웃이 쓰는 메뉴·사용자 같은 앱 데이터를 여기에 둔다. Inertia 공통 props에 해당한다.
101
- - 앱 문맥(`app`)의 `get`·`getDependency`는 `requires`에 넣은 플러그인만 허용한다. 컨트롤러 팩토리도 같은 제한을 받는다.
102
- - 앱 라우트는 Fastify 라우트 제약(`dokebiApp`)으로 등록되어 여러 앱이 같은 경로를 가질 수 있다. 제약 없는 공통 라우트(헬스 체크, 모듈 API)는 모든 도메인에서 응답한다.
103
- - 앱의 WebSocket 라우트(`sockets`)와 SSE 라우트(`events`, @dokebi/sse)도 같은 제약으로 등록된다. 허브의 tenant는 `<네임스페이스>:<tenant>`이고 기본 네임스페이스가 앱 이름이라, 설정하지 않으면 지금처럼 `<앱>:<tenant>`로 앱마다 나뉜다. 세션의 `identity.tenant`·`stream.tenant`도 이 값이다.
104
-
105
- ## 실시간 네임스페이스 (0.2.0, [D-0061](../../docs/decisions/D-0061-realtime-namespaces.md))
106
-
107
- 접속자 목록·방송·SSE 발행은 앱이 아니라 **네임스페이스** 단위로 갈린다. `apps.<앱>.realtime.namespaces`(1~32개, 기본 `[<앱>]`)가 그 앱이 쓸 수 있는 공간이다. 같은 네임스페이스를 가진 앱끼리 접속자·방송·채팅을 함께 쓴다(허브 설정의 `namespace`와는 다른 것).
108
-
109
- - **연결 하나 = 네임스페이스 하나.** 소켓·SSE `authenticate`가 `namespace`를 돌려주면 그 공간(앱 목록 안)에, 없으면 목록의 첫째에 들어간다. 목록 밖이면 401과 warn `NAMESPACE_FORBIDDEN`. 세션 identity에는 `namespace`가 남지 않는다.
110
- - **서버 코드:** `app.realtime(namespace?)`가 그 공간의 핸들을 준다(목록 밖이면 `NAMESPACE_FORBIDDEN`). 대상의 tenant는 접두 없는 인증 tenant이고, 빼면 공간의 모든 tenant다.
111
-
112
- ```ts
87
+ - A handler's `page` is `{ app: { name, template, domain }, module, base, view, inertia, sealed }`. In app routes `module` is undefined and `base` is `''`. `view` is an EJS renderer that looks in `<app>/<template>` → `<app>/default` → shared src/shared/views; layouts and `$include` follow the same order. `inertia` uses the app's document settings (Vite entry and so on) and adds `app` to the shared props.
88
+ - **Error pages ([D-0074](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0074-error-responses.md)):** errors on an app's hosts (unknown routes included) go through the app first. An Inertia app answers Inertia validation errors with the redirect back (`errors`) and other errors with `inertia.errorPage` (for example `Error`); for a browser page an EJS app renders `views/<template>/errors/<status>.ejs`, else `errors/error.ejs` (same lookup as pages, with `status`, `title`, `error`, `message`, `hint`, `fields`), else @dokebi/web's small page. JSON clients always get JSON. The `app add` skeletons include `errors/404.ejs` and `errors/error.ejs` (EJS) or `Pages/Error.vue` with `errorPage: 'Error'` (Inertia). Refuse input with `throw validationError({ name: 'Already taken' })` from @dokebi/web.
89
+ - **HTML forms come back (0.4.1, D-0074 addendum 1):** with [@dokebi/session](https://git.nyx-zone.com/dokebi/framework/-/blob/main/plugins/dokebi-session/README.md) registered, an HTML form post refused with 422 `VALIDATION_FAILED` flashes `errors` and `old` (without password-like fields) and answers 303 to the `Referer` of the same host, and every EJS page gets `data.errors`, `data.old` and `data.flash` (always objects, the flash read once per request), so the form shows `<%= data.old.title ?? '' %>` and `data.errors.title`. Without a session, or without a same-host Referer, the refused form gets `errors/422.ejs` (else `errors/error.ejs`) with `fields`, `errors` and `old`. Scripts (`fetch`, XHR, Bearer, JSON, Inertia) keep their JSON. Needs @dokebi/web ^0.4.1.
90
+ - **Mounting modules ([D-0032](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0032-feature-modules.md)):** `modules: { '/prefix': module }`, where the module was made with `defineModule`.
91
+ - The module's `routes` are registered with this app's route constraint and the prefix; handlers get `page.module` and `page.base`.
92
+ - The module's `sockets` are registered under the prefix. Their tenant is `<namespace>:<tenant>`, as for app sockets.
93
+ - Several apps can mount the same module under different prefixes. A mounted module's API is readable with `app.get(module)` without listing it in `requires`.
94
+ - The prefix is `/` or `/a/b` (lower-case letters, digits, `.`, `_`, `~`, `-`).
95
+ - Module pages look for views in this order, so module pages render inside the app layout:
96
+ 1. `<app>/<template>/<module>`
97
+ 2. `<app>/default/<module>`
98
+ 3. the module's `<template>`
99
+ 4. the module's `default`
100
+ 5. the app's views
101
+ 6. shared views
102
+ - **`shared(request, { app })`:** merged under the data of every EJS page this app renders (app routes and module routes). On overlapping keys the page data wins. Put app data the layout needs, such as the menu or the user, here. It corresponds to Inertia's shared props.
103
+ - `get` and `getDependency` of the app context (`app`) allow only the plugins listed in `requires`. Controller factories have the same limit.
104
+ - App routes are registered with a Fastify route constraint (`dokebiApp`), so several apps can own the same path. Shared routes without the constraint (health checks, module APIs) answer on every domain.
105
+ - The app's WebSocket routes (`sockets`) and SSE routes (`events`, @dokebi/sse) use the same constraint. The hub tenant is `<namespace>:<tenant>` and the default namespace is the app name, so without settings it stays `<app>:<tenant>`, one per app. The session's `identity.tenant` and `stream.tenant` hold this value.
106
+
107
+ ## Realtime namespaces (0.2.0, [D-0061](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0061-realtime-namespaces.md))
108
+
109
+ Presence lists, broadcasts and SSE publishing are divided by **namespace**, not by app. `apps.<app>.realtime.namespaces` (1 to 32, default `[<app>]`) are the spaces the app may use. Apps with the same namespace share presence, broadcasts and chat (this is not the `namespace` of the hub settings).
110
+
111
+ - **One connection = one namespace.** When a socket's or SSE route's `authenticate` returns `namespace`, the connection joins that space (it must be in the app's list), otherwise the first in the list. Outside the list: 401 and warn `NAMESPACE_FORBIDDEN`. `namespace` does not stay in the session identity.
112
+ - **Server code:** `app.realtime(namespace?)` gives the handle of that space (`NAMESPACE_FORBIDDEN` outside the list). A target's tenant is the authenticated tenant without the prefix; leaving it out means every tenant of the space.
113
+
114
+ ```ts snippet
113
115
  const front = app.realtime('front');
114
- await front.list(); // 모든 서버의 연결(tenant·member·rooms…)
116
+ await front.list(); // connections on every server (tenant, member, rooms…)
115
117
  await front.list({ tenant: 'shop-1', room: 'vip' });
116
- await front.send({ tenant: 'shop-1', member: 'u42' }, 'chat.message', { text: '안녕하세요' });
117
- await front.send({}, 'notice', { text: '점검' }); // 공간 전체
118
+ await front.send({ tenant: 'shop-1', member: 'u42' }, 'chat.message', { text: 'Hello' });
119
+ await front.send({}, 'notice', { text: 'Maintenance' }); // the whole space
118
120
  await front.kick({ tenant: 'shop-1', member: 'u42' });
119
121
  const stop = front.onPresence(({ tenant, joined, left }) => {});
120
122
  await front.publish({ tenant: 'shop-1' }, 'order.changed', { id: 7 }); // @dokebi/sse
121
123
  ```
122
124
 
123
- - `send`는 defineSocket 방송과 같은 `{ type, data }` 프레임이고 많아야 한 번(D-0057), 봉인 소켓에는 소켓마다 봉인되어 간다. 필요한 플러그인이 없으면 `REALTIME_UNAVAILABLE`.
124
- - 관리자 앱 예(두 프론트 공간을 지켜보며 사용자와 채팅)는 [AI.md](AI.md) §4 「실시간 네임스페이스」에 있다.
125
+ - `send` uses the same `{ type, data }` frame as defineSocket broadcasts, at most once (D-0057), sealed per socket for sealed sockets. Without the needed plugin it throws `REALTIME_UNAVAILABLE`.
126
+ - The admin app example (watching two front spaces and chatting with users) is in [AI.md](AI.md) §4 "Realtime namespaces".
125
127
 
126
- ## 봉인 호스트 (0.2.0, [D-0059](../../docs/decisions/D-0059-seal-and-websocket-client.md) §4)
128
+ ## Seal hosts (0.2.0, [D-0059](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0059-seal-and-websocket-client.md) §4)
127
129
 
128
- `domains.<host>.seal: true`(기본 false)면 그 호스트로 붙은 앱 소켓은 모든 프레임을 봉인하고, 그 호스트의 HTTP 데이터(REST JSON 요청·응답, Inertia 첫 화면·방문, SSE data)도 봉인된다(dokebi-web 봉인 자리, [D-0062](../../docs/decisions/D-0062-http-seal.md)). 라우트 `seal: false`·dokebi-web `sealExclude`는 평문 예외, EJS HTML은 그대로다. 앱이 소켓의 `route.seal`을 요청 호스트로 채우고, 실제 봉인과 `/dokebi/seal/*`(브라우저 로더·소켓 번들·wasm) 정적 서빙은 **`@dokebi/seal` 플러그인**이 맡는다. 이 공개 패키지는 그 플러그인을 이름(`dokebi-seal`)으로만 찾는다.
130
+ With `domains.<host>.seal: true` (default false), app sockets connected through that host seal every frame, and the host's HTTP data (REST JSON requests and responses, the Inertia first page and visits, SSE data) is sealed too (the dokebi-web seal slot, [D-0062](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0062-http-seal.md)). Route `seal: false` and dokebi-web `sealExclude` are plain exceptions; EJS HTML stays as it is. app fills a socket's `route.seal` from the request host; the actual sealing and the static files under `/dokebi/seal/*` (browser loader, socket bundle, wasm) are the **`@dokebi/seal` plugin**'s job. This public package looks that plugin up only by name (`dokebi-seal`).
129
131
 
130
- - 페이지에 `sealed`가 들어간다: 핸들러 `page.sealed`, EJS 데이터 `sealed`(앱 `shared`·페이지 데이터가 이김), Inertia 공통 props `sealed`. 페이지는 `sealed`일 때 봉인 로더(wasm)를 미리 불러 봉인 다리로 붙는다. 다리를 준 클라이언트는 `dokebi.seal`·`dokebi.plain`을 함께 제안하므로 평문 호스트에서는 `dokebi.plain`이 골라져 평문으로 돈다.
131
- - 시작 거절(fail closed): `seal: true` 도메인이 있는데 `dokebi-seal` 플러그인이 없으면 `SEAL_PROVIDER_MISSING`. 봉인 도메인의 앱이 소켓을 붙이는데 @dokebi/websocket이 0.3 미만이면 같은 code. (소켓 없는 봉인 앱의 warn `SEAL_WITHOUT_SOCKETS`는 D-0062에서 없앴다: HTTP도 봉인된다.)
132
- - 봉인 연결의 규칙(4415·4400·hello·방송)은 @dokebi/websocket README의 「호스트별 봉인」을 따른다.
132
+ - Pages get `sealed`: `page.sealed` in handlers, `sealed` in EJS data (the app's `shared` and page data win), `sealed` in Inertia shared props. A sealed page preloads the seal loader (wasm) and connects with the seal bridge. A client given the bridge offers both `dokebi.seal` and `dokebi.plain`, so on a plain host `dokebi.plain` is picked and it runs in plain text.
133
+ - Refused at start (fail closed): a `seal: true` domain without the `dokebi-seal` plugin is `SEAL_PROVIDER_MISSING`. An app on a sealed domain that has sockets with @dokebi/websocket older than 0.3 gets the same code. (The warn `SEAL_WITHOUT_SOCKETS` for sealed apps without sockets was removed by D-0062: HTTP is sealed too.)
134
+ - The rules of sealed connections (4415, 4400, hello, broadcasts) follow "Sealing per host" in the @dokebi/websocket README.
133
135
 
134
136
  ## API
135
137
 
136
- `createPlugin`이 돌려주는 API는 `{ names, resolve(request) }`다. `resolve`는 요청의 앱·템플릿·도메인을, 모르는 Host면 undefined를 돌려준다. `APP_CONSTRAINT`(`'dokebiApp'`)와 `hostOf(request)`도 공개한다.
138
+ `createPlugin` returns the API `{ names, resolve(request) }`. `resolve` returns the request's app, template and domain, or undefined for an unknown Host. `APP_CONSTRAINT` (`'dokebiApp'`), `hostOf(request)` and `withoutPort(host)` are public too.
@@ -0,0 +1,7 @@
1
+ import { DokebiError, type DokebiErrorOptions } from '@dokebi/core';
2
+ /** Codes of the errors this plugin throws (`AppError`, `plugin: 'dokebi-app'`). */
3
+ export type AppErrorCode = 'INVALID_DEFINITION' | 'INVALID_ENTRY' | 'UNKNOWN_APP' | 'SEAL_PROVIDER_MISSING' | 'VIEW_ENGINE_MISSING' | 'VIEWS_MISSING' | 'REALTIME_UNAVAILABLE' | 'NAMESPACE_FORBIDDEN' | 'INVALID_TARGET' | 'NOT_REQUIRED' | 'NOT_READY';
4
+ /** Errors of @dokebi/app; compare `code`, not the class (another installed copy may throw). */
5
+ export declare class AppError extends DokebiError<AppErrorCode> {
6
+ constructor(code: AppErrorCode, message: string, options?: DokebiErrorOptions);
7
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,21 @@
1
+ import { DokebiError } from '@dokebi/core';
2
+ const FIX = {
3
+ INVALID_DEFINITION: 'defineApp takes requires, controllers, views (a file: URL), inertia, modules ({ "/prefix": defineModule(...) }), shared, routes, sockets, events, setup, start and drain; hooks are functions.',
4
+ INVALID_ENTRY: 'Pass { apps: { <name>: defineApp(...) } } (src/dokebi.generated.ts does); names match ^[a-z][a-z0-9-]{0,31}$.',
5
+ UNKNOWN_APP: 'Every app named in options.dokebi-app.domains.<host>.app and options.dokebi-app.apps must be defined (npx dokebi app add <name>, or remove the entry from dokebi.yaml).',
6
+ SEAL_PROVIDER_MISSING: 'Register the dokebi-seal plugin (npx dokebi add @dokebi/seal), or remove seal: true from options.dokebi-app.domains.',
7
+ VIEW_ENGINE_MISSING: 'Install the view plugin the app uses: npx dokebi add @dokebi/template-ejs (views) or npx dokebi add @dokebi/template-inertia (inertia).',
8
+ VIEWS_MISSING: 'Create src/apps/<app>/views/<template>/ for every template a domain selects (default/ is always needed), or drop views from defineApp.',
9
+ REALTIME_UNAVAILABLE: 'Install the transport the app uses: npx dokebi add @dokebi/websocket (sockets, list/send/kick/onPresence) or npx dokebi add @dokebi/sse (events, publish).',
10
+ NAMESPACE_FORBIDDEN: 'List the namespace in options.dokebi-app.apps.<app>.realtime.namespaces, or use one that is listed.',
11
+ INVALID_TARGET: 'A realtime target is { tenant?, member?, room? } with strings of 1 to 256 characters.',
12
+ NOT_REQUIRED: 'Add the plugin to requires of defineApp (src/apps/<app>/app.ts).',
13
+ NOT_READY: 'Read controllers from routes, socket handlers or start, after the app was set up.',
14
+ };
15
+ /** Errors of @dokebi/app; compare `code`, not the class (another installed copy may throw). */
16
+ export class AppError extends DokebiError {
17
+ constructor(code, message, options = {}) {
18
+ super(code, message, { plugin: 'dokebi-app', fix: FIX[code], ...options });
19
+ this.name = 'AppError';
20
+ }
21
+ }
package/dist/index.d.ts CHANGED
@@ -1,11 +1,9 @@
1
1
  import { type ControllerDefinition } from '@dokebi/controller';
2
2
  import { type Awaitable, type Plugin, type PluginContext, type PluginDependency } from '@dokebi/core';
3
- import type { SsePublishResult, SseRoute } from '@dokebi/sse';
4
- import type { TemplateApi } from '@dokebi/template-ejs';
5
- import type { InertiaApi, InertiaScopeOptions } from '@dokebi/template-inertia';
6
- import type { WebRoute } from '@dokebi/web';
7
- import type { WebsocketConnectionInfo, WebsocketKickReceipt, WebsocketPeer, WebsocketReceipt, WebsocketRoute } from '@dokebi/websocket';
3
+ import { type WebErrorResponse, type WebRoute } from '@dokebi/web';
8
4
  import type { FastifyReply, FastifyRequest } from 'fastify';
5
+ export { AppError, type AppErrorCode } from './errors.js';
6
+ export { type AppPluginOptions, options } from './options.js';
9
7
  /** The Fastify route constraint that selects an app by request host. */
10
8
  export declare const APP_CONSTRAINT = "dokebiApp";
11
9
  /** Which app answered a request, with the template and the host it came in on. */
@@ -14,6 +12,70 @@ export interface AppInfo {
14
12
  readonly template: string;
15
13
  readonly domain: string;
16
14
  }
15
+ /** What `view.reply` needs of a reply (a Fastify reply has it). */
16
+ export interface AppViewReply {
17
+ type(value: string): unknown;
18
+ send(payload: string): unknown;
19
+ }
20
+ /**
21
+ * The EJS renderer of a page, from the `ejs` view engine (@dokebi/template-ejs `TemplateApi`).
22
+ * Names are looked up in `<app>/<template>` → `<app>/default` → shared views.
23
+ */
24
+ export interface AppView {
25
+ render(name: string, data: Readonly<Record<string, unknown>>, options?: {
26
+ readonly layout?: string | false;
27
+ }): Promise<string>;
28
+ /** Renders, sets text/html, sends the HTML and resolves to the same reply. */
29
+ reply<TReply extends AppViewReply>(reply: TReply, name: string, data: Readonly<Record<string, unknown>>, options?: {
30
+ readonly layout?: string | false;
31
+ }): Promise<TReply>;
32
+ /** A renderer that looks names up under each prefix in order first. */
33
+ scope(prefixes: readonly string[]): AppView;
34
+ /** True when the name resolves in this renderer's lookup order (D-0074 error views). */
35
+ has(name: string): boolean;
36
+ }
37
+ /** The Inertia renderer of an app, from the `inertia` view engine (@dokebi/template-inertia). */
38
+ export interface AppInertia {
39
+ render(request: FastifyRequest, reply: FastifyReply, component: string, props?: Readonly<Record<string, unknown>>, options?: {
40
+ readonly encryptHistory?: boolean;
41
+ readonly clearHistory?: boolean;
42
+ }): Promise<FastifyReply>;
43
+ redirect(request: FastifyRequest, reply: FastifyReply, url: string): FastifyReply;
44
+ location(request: FastifyRequest, reply: FastifyReply, url: string): FastifyReply;
45
+ /**
46
+ * Answers an error of this app's requests (D-0074): the validation redirect of an Inertia
47
+ * request, or the app's error page component. dokebi-app calls it; false when it wrote nothing.
48
+ */
49
+ answerError(response: WebErrorResponse): Promise<boolean>;
50
+ }
51
+ /**
52
+ * Document settings of an app's Inertia pages (@dokebi/template-inertia `InertiaScopeOptions`
53
+ * without `shared`, which dokebi-app sets).
54
+ */
55
+ export interface AppInertiaOptions {
56
+ readonly title?: string;
57
+ readonly rootId?: string;
58
+ readonly version?: string;
59
+ readonly scripts?: readonly string[];
60
+ readonly styles?: readonly string[];
61
+ readonly vite?: {
62
+ readonly manifest: string;
63
+ readonly entry: string;
64
+ readonly base?: string;
65
+ };
66
+ readonly ssr?: {
67
+ readonly bundle: string;
68
+ readonly failure?: 'fallback' | 'error';
69
+ readonly entry?: string;
70
+ } | false;
71
+ readonly encryptHistory?: boolean | 'sealed';
72
+ /**
73
+ * The page component of this app's error answers (D-0074), for example `Error`: rendered with
74
+ * `{ status, error, message, hint }` for Inertia visits and page loads. Unset: the plugin's
75
+ * `errorPage`; `false`: none (JSON for visits, the error views or a small page for page loads).
76
+ */
77
+ readonly errorPage?: string | false;
78
+ }
17
79
  /** What an app route handler receives besides the Fastify request and reply. */
18
80
  export interface AppPage {
19
81
  readonly app: AppInfo;
@@ -22,9 +84,9 @@ export interface AppPage {
22
84
  /** The prefix the module is mounted at (`''` for app routes and root mounts), for links. */
23
85
  readonly base: string;
24
86
  /** EJS renderer scoped to `<app>/<template>` → `<app>/default` → shared views. */
25
- readonly view: TemplateApi;
87
+ readonly view: AppView;
26
88
  /** Inertia renderer of this app; present when the app sets `inertia`. */
27
- readonly inertia: InertiaApi | undefined;
89
+ readonly inertia: AppInertia | undefined;
28
90
  /**
29
91
  * The request host has `seal: true` (D-0059 §4, D-0062): its sockets seal every frame and its
30
92
  * HTTP JSON bodies, Inertia pages and SSE data are sealed, so the page should load
@@ -49,6 +111,19 @@ export interface AppRouter {
49
111
  patch(url: string, handler: AppHandler, options?: Partial<AppRouteOptions>): void;
50
112
  delete(url: string, handler: AppHandler, options?: Partial<AppRouteOptions>): void;
51
113
  }
114
+ /**
115
+ * A realtime route of an app or module (`defineSocket` of @dokebi/websocket, an `SseRoute` of
116
+ * @dokebi/sse): the transport that mounts it reads the rest. `authenticate` may return
117
+ * `namespace`, one of the app's `realtime.namespaces` (D-0061).
118
+ */
119
+ export interface AppRealtimeRoute {
120
+ readonly path: string;
121
+ readonly constraints?: Readonly<Record<string, unknown>>;
122
+ authenticate(request: FastifyRequest): Awaitable<{
123
+ readonly tenant: string;
124
+ readonly namespace?: string;
125
+ } | undefined>;
126
+ }
52
127
  /**
53
128
  * Whom a realtime call is about (D-0061), inside one namespace: a tenant (as `authenticate`
54
129
  * returned it, without the namespace), or every tenant of the namespace when `tenant` is left
@@ -59,19 +134,46 @@ export interface RealtimeTarget {
59
134
  readonly member?: string;
60
135
  readonly room?: string;
61
136
  }
137
+ /** A connection of the hub as presence reports it (@dokebi/websocket `WebsocketPeer`). */
138
+ export interface RealtimePeer {
139
+ readonly member: string;
140
+ readonly connection: string;
141
+ readonly ownerEpoch: string;
142
+ readonly clientId?: string;
143
+ readonly metadata: Readonly<Record<string, string>>;
144
+ }
62
145
  /** A WebSocket connection of a namespace; `tenant` is without the `<namespace>:` prefix. */
63
- export type RealtimeConnection = WebsocketConnectionInfo;
146
+ export interface RealtimeConnection extends RealtimePeer {
147
+ readonly tenant: string;
148
+ readonly rooms: readonly string[];
149
+ }
64
150
  /** Joins and leaves of one tenant of a namespace; `tenant` is without the prefix. */
65
151
  export interface RealtimePresence {
66
152
  readonly tenant: string;
67
- readonly joined: readonly WebsocketPeer[];
68
- readonly left: readonly WebsocketPeer[];
153
+ readonly joined: readonly RealtimePeer[];
154
+ readonly left: readonly RealtimePeer[];
155
+ }
156
+ /** What `send` resolves with: one hub broadcast per tenant (D-0057: matched, not confirmed). */
157
+ export interface RealtimeReceipt {
158
+ readonly ids: readonly string[];
159
+ readonly recipients: readonly string[];
160
+ }
161
+ /** What `kick` resolves with: one hub kick per tenant. */
162
+ export interface RealtimeKickReceipt {
163
+ readonly ids: readonly string[];
164
+ }
165
+ /** What `publish` resolves with (@dokebi/sse). */
166
+ export interface RealtimePublishResult {
167
+ /** The event id every recipient sees as `lastEventId`. */
168
+ readonly id: string;
169
+ /** Streams of this process the event was written to. */
170
+ readonly local: number;
69
171
  }
70
172
  /**
71
173
  * One realtime namespace as app server code sees it (D-0061, `app.realtime(namespace)`): the
72
174
  * WebSocket connections and SSE streams whose hub tenant is `<namespace>:<tenant>`, on every
73
- * server. Calls fail with REALTIME_UNAVAILABLE when the plugin they need is not registered
74
- * (@dokebi/websocket 0.3 or later, @dokebi/sse).
175
+ * server. Calls fail with REALTIME_UNAVAILABLE when no plugin offers the transport they need
176
+ * (@dokebi/websocket, @dokebi/sse).
75
177
  */
76
178
  export interface RealtimeHandle {
77
179
  readonly namespace: string;
@@ -84,13 +186,13 @@ export interface RealtimeHandle {
84
186
  * Sends the `{ type, data }` text frame of defineSocket broadcasts through the hub: at most
85
187
  * once (D-0057), sealed per sealed socket. Without `tenant`: one broadcast per known tenant.
86
188
  */
87
- send(target: RealtimeTarget, type: string, data?: unknown): Promise<WebsocketReceipt>;
189
+ send(target: RealtimeTarget, type: string, data?: unknown): Promise<RealtimeReceipt>;
88
190
  /** Closes the matching connections on every server (code 4000-4999, default 4403). */
89
- kick(target: RealtimeTarget, code?: number, reason?: string): Promise<WebsocketKickReceipt>;
191
+ kick(target: RealtimeTarget, code?: number, reason?: string): Promise<RealtimeKickReceipt>;
90
192
  /** Joins and leaves of this namespace's tenants until the returned function is called. */
91
193
  onPresence(listener: (change: RealtimePresence) => unknown): () => void;
92
194
  /** Publishes one SSE event to this namespace's streams (@dokebi/sse; every process on its bus). */
93
- publish(target: RealtimeTarget, event: string, data?: unknown): Promise<SsePublishResult>;
195
+ publish(target: RealtimeTarget, event: string, data?: unknown): Promise<RealtimePublishResult>;
94
196
  }
95
197
  /** The view of the Application an app gets: only the plugins it lists in `requires`. */
96
198
  export interface AppContext {
@@ -114,10 +216,10 @@ export interface AppDefinition {
114
216
  readonly requires?: readonly AppRequirement[];
115
217
  /** `defineController` tokens built with this app's context. */
116
218
  readonly controllers?: readonly ControllerDefinition<unknown>[];
117
- /** Folder with one sub-folder per template (`default/` is required). */
219
+ /** Folder with one sub-folder per template (`default/` is required). Needs the `ejs` engine. */
118
220
  readonly views?: URL;
119
- /** Document settings of this app's Inertia pages (see template-inertia `scope`). */
120
- readonly inertia?: Omit<InertiaScopeOptions, 'shared'>;
221
+ /** Document settings of this app's Inertia pages. Needs the `inertia` engine. */
222
+ readonly inertia?: AppInertiaOptions;
121
223
  /**
122
224
  * Modules (D-0032) mounted under a prefix: `{ '/board': boardModule }`. Their routes and
123
225
  * sockets answer on this app's domains only; they need not be listed in `requires`.
@@ -132,16 +234,17 @@ export interface AppDefinition {
132
234
  }): Awaitable<Record<string, unknown>>;
133
235
  routes?(route: AppRouter, app: AppContext): Awaitable<void>;
134
236
  /**
135
- * WebSocket routes (e.g. `defineSocket`) registered for this app's domains only. Their hub
136
- * tenant is `<namespace>:<tenant>` (D-0061): `authenticate` may return `namespace`, one of the
137
- * app's `realtime.namespaces` (default the first); another one answers 401.
237
+ * WebSocket routes (e.g. `defineSocket`) registered for this app's domains only, through the
238
+ * `websocket` realtime transport. Their hub tenant is `<namespace>:<tenant>` (D-0061):
239
+ * `authenticate` may return `namespace`, one of the app's `realtime.namespaces` (default the
240
+ * first); another one answers 401.
138
241
  */
139
- sockets?(app: AppContext): Awaitable<readonly WebsocketRoute[]>;
242
+ sockets?(app: AppContext): Awaitable<readonly AppRealtimeRoute[]>;
140
243
  /**
141
- * Server-sent event routes (@dokebi/sse) registered for this app's domains only, with the
142
- * same namespace and tenant rule as `sockets` (D-0061).
244
+ * Server-sent event routes (@dokebi/sse) registered for this app's domains only, through the
245
+ * `sse` realtime transport, with the same namespace and tenant rule as `sockets` (D-0061).
143
246
  */
144
- events?(app: AppContext): Awaitable<readonly SseRoute[]>;
247
+ events?(app: AppContext): Awaitable<readonly AppRealtimeRoute[]>;
145
248
  setup?(app: AppContext): Awaitable<void>;
146
249
  start?(app: AppContext): Awaitable<void>;
147
250
  drain?(app: AppContext): Awaitable<void>;
@@ -184,4 +287,3 @@ export interface AppGroupApi {
184
287
  resolve(request: FastifyRequest): AppInfo | undefined;
185
288
  }
186
289
  export declare const createPlugin: import("@dokebi/core").PluginFactory<AppGroupApi>;
187
- export {};