@dokebi/app 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AI.md CHANGED
@@ -1,4 +1,4 @@
1
- # AI 작업 안내 — @dokebi/app 0.1.1
1
+ # AI 작업 안내 — @dokebi/app 0.2.0
2
2
 
3
3
  한 프로젝트에 앱을 여러 개 두고, **요청 도메인으로 앱과 템플릿을 고르는** 플러그인이다(D-0030). 앱 하나는 `src/apps/<앱>/` 폴더 하나이고 `defineApp`으로 정의한다. Node >=24.0.0, core ^0.2.0. 사람용 설명은 [README](README.md)다.
4
4
 
@@ -14,7 +14,7 @@ npx dokebi app remove shop # 그 앱을 가리키는 도메인을 먼
14
14
  ```
15
15
 
16
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`).
17
+ - Inertia·WebSocket·SSE를 쓰는 앱이 있으면 `@dokebi/template-inertia`, `@dokebi/websocket`, `@dokebi/sse`를 따로 add한다(없으면 시작 실패: `App <앱> uses Inertia; add @dokebi/template-inertia`, `has sockets; add @dokebi/websocket`, `has event streams; add @dokebi/sse`).
18
18
  - 이름 규칙: 앱·템플릿 `^[a-z][a-z0-9-]{0,31}$`, 도메인은 포트 없는 소문자 호스트.
19
19
 
20
20
  ## 2. 앱 폴더
@@ -37,8 +37,10 @@ src/apps/<앱>/
37
37
 
38
38
  | 키 | 형식 | 뜻 |
39
39
  |---|---|---|
40
- | `domains` (필수) | `{ <host>: { app, template? } }`, 최대 1024 | 호스트 → 앱·템플릿(생략은 default) |
40
+ | `domains` (필수) | `{ <host>: { app, template?, seal? } }`, 최대 1024 | 호스트 → 앱·템플릿(생략은 default). `seal: true`면 그 호스트의 WebSocket 프레임과 HTTP 데이터(JSON 본문·Inertia 페이지·SSE data)를 봉인(§4 봉인 호스트, 기본 false) |
41
41
  | `unknownDomain` | `reject`(기본) 또는 domains의 키 하나 | 모르는 호스트: 404, 또는 그 도메인의 설정으로 응답 |
42
+ | `apps` | `{ <앱>: { realtime?: { namespaces } } }` | 앱별 설정. **키는 정의된 앱 이름**이어야 한다(없는 앱이면 시작 실패 `UNKNOWN_APP`) |
43
+ | `apps.<앱>.realtime.namespaces` | 이름 1~32개(`^[a-z][a-z0-9-]{0,31}$`, 중복 금지), 기본 `[<앱>]` | 이 앱의 실시간 공간(§4 실시간 네임스페이스, D-0061) |
42
44
 
43
45
  호스트는 dokebi-web `requestHost()`(trustProxy면 `X-Forwarded-Host`)에서 포트를 떼고 소문자로 **정확히** 비교한다. 와일드카드·경로 접두사는 없다. 프락시 뒤면 dokebi-web `trustProxy`에 프락시 주소를 넣는다.
44
46
 
@@ -63,21 +65,23 @@ export default defineApp({
63
65
  );
64
66
  },
65
67
  sockets: (app) => [chatSocket(app)],
68
+ events: (app) => [orderStream(app)], // @dokebi/sse 라우트(SseRoute). 소켓과 같은 제약·네임스페이스
66
69
  setup(app) {}, start(app) {}, drain(app) {},
67
70
  });
68
71
  ```
69
72
 
70
73
  - `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`는 `''`.
74
+ - `page`: `{ app: { name, template, domain }, module, base, view, inertia, sealed }`. 앱 라우트에서 `module`은 undefined, `base`는 `''`.
72
75
  - `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`). 컨트롤러 팩토리도 같은 제한을 받는다.
76
+ - `inertia`: 앱의 문서 설정을 쓰는 Inertia 렌더러(앱에 `inertia`가 있을 때). 공통 props에 `app`(`{ name, template, domain }`)과 `sealed`를 더한다.
77
+ - `sealed`: 요청 호스트가 `seal: true`인가. EJS 데이터에도 `sealed`로 들어간다(앱 `shared`·페이지 데이터가 이김).
78
+ - `app`(AppContext): `name`·`logger`·`signal`·`get`·`getDependency`·`getOptionalDependency`·`controller`·`defer`·`realtime(namespace?)`(§4 실시간 네임스페이스). **`requires`에 없는 것을 꺼내면 오류**(`App <앱> does not list <플러그인> in requires`). 컨트롤러 팩토리도 같은 제한을 받는다.
75
79
  - `inertia.ssr: { bundle: 'dist/ssr/<앱>/ssr.js' }`면 첫 HTML을 서버에서 그린다(D-0039, template-inertia AI.md).
76
80
 
77
81
  ### 모듈 붙이기(D-0032)
78
82
 
79
83
  - `modules: { '/접두사': 모듈 }`. 접두사는 `/` 또는 `/a/b`(소문자·숫자·`.`·`_`·`~`·`-`).
80
- - 모듈의 라우트·소켓이 이 앱의 도메인·접두사로 등록되고 `page.module`·`page.base`가 채워진다. 같은 모듈을 여러 앱이 다른 접두사로 붙일 수 있다. 붙인 모듈은 `requires`에 넣지 않아도 `app.get(모듈)`로 API를 읽는다.
84
+ - 모듈의 라우트·소켓·SSE 라우트(`events`, @dokebi/module 0.1.3)가 이 앱의 도메인·접두사로 등록되고 `page.module`·`page.base`가 채워진다. 같은 모듈을 여러 앱이 다른 접두사로 붙일 수 있다. 붙인 모듈은 `requires`에 넣지 않아도 `app.get(모듈)`로 API를 읽는다.
81
85
  - 모듈 화면 찾는 순서는 다음과 같다. 그래서 모듈 화면이 앱 레이아웃 안에 그려진다. 앱이 모듈 화면을 바꾸려면 `views/<템플릿>/<모듈>/`에 같은 파일을 둔다.
82
86
  1. `<앱>/<템플릿>/<모듈>`
83
87
  2. `<앱>/default/<모듈>`
@@ -89,7 +93,115 @@ export default defineApp({
89
93
  ### 라우팅과 WebSocket
90
94
 
91
95
  - 앱 라우트는 Fastify 제약 `dokebiApp`(`APP_CONSTRAINT`)으로 등록된다. 여러 앱이 같은 경로를 가질 수 있다. 제약 없는 라우트(헬스 체크, `@dokebi/router` API)는 모든 도메인에서 응답한다.
92
- - 앱 소켓도 같은 제약을 쓴다. 허브 tenant는 `<앱>:<tenant>`로 앱마다 나뉘며 세션 `identity.tenant`도 그 값이다. 메시지는 `defineSocket`의 `{ type, data, id? }` 형식.
96
+ - 앱 소켓도 같은 제약을 쓴다. 허브 tenant는 `<네임스페이스>:<tenant>`(기본 네임스페이스는 앱 이름이라 설정이 없으면 `<앱>:<tenant>`)이며 세션 `identity.tenant`도 그 값이다. 메시지는 `defineSocket`의 `{ type, data, id? }` 형식.
97
+ - 앱 `events`(SSE, @dokebi/sse)도 같은 제약·같은 tenant 규칙으로 붙는다(`stream.tenant`가 `<네임스페이스>:<tenant>`). @dokebi/sse가 없으면 시작 실패 `App <앱> has event streams; add @dokebi/sse`. 붙인 모듈의 `events`(@dokebi/module 0.1.3)도 모듈 접두사 아래에 같은 규칙으로 붙는다(`Module <모듈> (app <앱>) has event streams; add @dokebi/sse`).
98
+
99
+ ### 실시간 네임스페이스 (0.2.0, [D-0061](../../docs/decisions/D-0061-realtime-namespaces.md))
100
+
101
+ 접속자 목록·방송·SSE 발행이 갈리는 단위는 **앱이 아니라 네임스페이스**다. 같은 네임스페이스를 가진 앱끼리 접속자·방송·채팅을 함께 쓴다. 허브의 `namespace`(Redis 키 접두, 클러스터 단위)와는 다른 것이다.
102
+
103
+ ```yaml
104
+ dokebi-app:
105
+ domains:
106
+ www.a.com: { app: shop }
107
+ m.a.com: { app: mobile }
108
+ admin.a.com: { app: admin }
109
+ apps:
110
+ shop: { realtime: { namespaces: [front] } }
111
+ mobile: { realtime: { namespaces: [front] } } # shop과 같은 공간
112
+ admin: { realtime: { namespaces: [admin, front] } } # 첫째가 자기 소켓의 기본
113
+ ```
114
+
115
+ - **연결 하나 = 네임스페이스 하나**: 소켓·SSE 스트림의 허브 tenant는 `<네임스페이스>:<인증 tenant>`. `authenticate`가 `namespace`를 돌려주면 그 공간(앱 목록 안이어야 함)으로, 없으면 목록의 첫째로 들어간다. 목록 밖이면 401과 warn `Realtime namespace refused`(code `NAMESPACE_FORBIDDEN`, `app`·`kind`(socket·stream)·`path`·`namespace`·`allowed`). `namespace`는 앱이 지우므로 세션 `identity`·`stream.identity`에는 없다(공간은 `identity.tenant`의 접두로 안다).
116
+ - **서버 코드의 핸들** `app.realtime(namespace?)`(생략하면 첫째, 목록 밖이면 즉시 `NAMESPACE_FORBIDDEN`). 대상 `{ tenant?, member?, room? }`의 tenant는 접두 없는 인증 tenant다. **tenant를 빼면 그 네임스페이스의 모든 tenant**.
117
+ - `list(filter?)` → 연결 목록(`tenant`(접두 없음)·`member`·`connection`·`ownerEpoch`·`clientId?`·`rooms`·`metadata`). tenant가 있으면 허브에 묻고(클러스터 전체, 실패는 허브 code), 없으면 이 서버가 받은 presence(모든 서버, 조금 늦을 수 있음, start 전에는 빈 목록)에서 읽는다.
118
+ - `send(target, type, data?)` → defineSocket 방송과 같은 `{ type, data }` 텍스트 프레임을 허브로(많아야 한 번, 봉인 소켓은 소켓마다 봉인). 영수증 `{ ids, recipients }`. tenant를 빼면 tenant마다 방송 하나.
119
+ - `kick(target, code?, reason?)` → 모든 서버에서 그 연결을 닫음(4000~4999, 기본 4403).
120
+ - `onPresence(listener)` → 그 공간 tenant의 입·퇴장(`{ tenant, joined, left }`, tenant 접두 없음). 돌려준 함수로 끊는다. 던지거나 거부한 listener는 websocket이 error `PRESENCE_LISTENER_FAILED`로 남긴다.
121
+ - `publish(target, event, data?)` → @dokebi/sse 발행(그 공간의 스트림, 버스가 있으면 모든 프로세스). tenant를 빼면 모든 프로세스가 자기 스트림 중 접두가 맞는 tenant에 쓴다.
122
+ - 필요한 플러그인이 없으면 `REALTIME_UNAVAILABLE`(소켓 쪽은 @dokebi/websocket 0.3 이상, publish는 @dokebi/sse).
123
+ - **권한은 앱이 정한다**: 같은 공간 안에서 누가 누구를 볼지는 rooms·역할·앱 코드로 정한다. 네임스페이스는 공간을 나누는 것만 한다. 관리자 앱이 프론트 공간에 접속자로 보이지 않으려면 자기 소켓을 자기 공간(`admin`)에 두고 서버 코드에서 `realtime('front')`로 모아 본다.
124
+ - 모듈 소켓·SSE 라우트(`events`)는 붙인 앱의 네임스페이스 규칙을 그대로 따른다. 모듈 문맥(ModuleContext)에는 `realtime`이 없다(모듈은 여러 앱에 붙으므로 앱 문맥이 아니다).
125
+
126
+ #### 예: 프론트 두 공간을 지켜보고 사용자와 채팅하는 관리자 앱
127
+
128
+ ```yaml
129
+ dokebi-app:
130
+ apps:
131
+ shop: { realtime: { namespaces: [shop] } }
132
+ blog: { realtime: { namespaces: [blog] } }
133
+ admin: { realtime: { namespaces: [admin, shop, blog] } }
134
+ ```
135
+
136
+ ```ts
137
+ // src/apps/admin/app.ts
138
+ import { type AppContext, defineApp } from '@dokebi/app';
139
+ import { defineSocket } from '@dokebi/websocket';
140
+ import { staffOf } from './models/staff.ts';
141
+
142
+ const WATCHED = ['shop', 'blog'] as const;
143
+ type Watched = (typeof WATCHED)[number];
144
+
145
+ export default defineApp({
146
+ // 관리자 화면들은 admin 공간 하나에 붙는다(프론트 접속자 목록에 보이지 않음).
147
+ sockets: (app) => [
148
+ defineSocket({
149
+ path: '/ws',
150
+ authenticate: async (request) => {
151
+ const staff = await staffOf(request); // 직원 세션 확인. 아니면 undefined → 401
152
+ return staff && { tenant: 'staff', member: staff.id, namespace: 'admin' };
153
+ },
154
+ on: {
155
+ // 화면이 열릴 때 두 공간의 현재 접속자를 한 번에 읽는다.
156
+ 'users.list': async () =>
157
+ Object.fromEntries(
158
+ await Promise.all(WATCHED.map(async (space) => [space, await app.realtime(space).list()])),
159
+ ),
160
+ // 관리자 → 프론트 사용자 한 명(그 사람의 모든 탭).
161
+ 'chat.send': async (data, socket) => {
162
+ const { space, tenant, member, text } = data as { space: Watched; tenant: string; member: string; text: string };
163
+ if (!WATCHED.includes(space)) throw Object.assign(new Error('bad space'), { code: 'BAD_SPACE' });
164
+ const receipt = await app.realtime(space).send({ tenant, member }, 'chat.message', {
165
+ from: socket.identity.member, text,
166
+ });
167
+ return { recipients: receipt.recipients.length }; // 0이면 이미 나간 사용자
168
+ },
169
+ // 공지: 그 공간의 모든 tenant.
170
+ 'notice.send': async (data) => {
171
+ const { space, text } = data as { space: Watched; text: string };
172
+ await app.realtime(space).send({}, 'notice', { text });
173
+ },
174
+ },
175
+ }),
176
+ ],
177
+ // 프론트의 입·퇴장을 관리자 화면들에 실시간으로 넘긴다.
178
+ start(app) {
179
+ for (const space of WATCHED) {
180
+ const stop = app.realtime(space).onPresence((change) =>
181
+ app.realtime('admin').send({ tenant: 'staff' }, 'users.changed', { space, ...change }),
182
+ );
183
+ app.defer(stop);
184
+ }
185
+ },
186
+ });
187
+ ```
188
+
189
+ - 프론트 앱(shop·blog)의 소켓은 바꿀 것이 없다. 사용자의 답장을 직원 화면에 보내려면 shop의 namespaces를 `[shop, admin]`으로 하고 shop 핸들러가 `app.realtime('admin').send({ tenant: 'staff' }, 'chat.reply', …)`를 부른다(첫째가 shop이라 사용자 소켓은 그대로 shop 공간). 그러면 shop 서버 코드가 관리자 공간에 쓸 수 있으므로 무엇을 보낼지는 앱 코드로 제한한다.
190
+ - 관리자 화면이 프론트 사용자로도 보여야 하면(대화방에 함께 있는 직원) 그 화면의 소켓이 `namespace: 'shop'`으로 붙으면 된다.
191
+
192
+ ### 봉인 호스트 (0.2.0, D-0059 §4)
193
+
194
+ ```yaml
195
+ dokebi-app:
196
+ domains:
197
+ secure.example.com: { app: shop, seal: true } # 이 호스트의 소켓은 모든 프레임을 봉인
198
+ www.example.com: { app: shop } # 같은 앱·같은 소켓 경로라도 평문
199
+ ```
200
+
201
+ - 앱 소켓의 `route.seal`을 요청 호스트로 채운다(그 앱의 호스트 중 하나라도 봉인일 때만; 라우트 자신의 `seal`은 평문 호스트에서도 유지). 알고리즘·`/dokebi/seal/*` 정적 파일은 **`@dokebi/seal` 플러그인**(`dokebi-seal`)이 맡는다. 이 공개 패키지는 이름으로만 찾는다.
202
+ - 페이지: `sealed`가 true면 `/dokebi/seal/seal.mjs`·`socket.mjs`를 불러 `initSeal()` 뒤 `connectChannel({ path, seal: sealBridge })`로 붙는다. (다리를 늘 줘도 된다: 클라이언트가 `dokebi.seal`·`dokebi.plain`을 함께 제안하고 평문 호스트는 `dokebi.plain`을 골라 평문으로 돈다. `sealed`는 wasm을 미리 받을지 정하는 데 쓴다.) 봉인 호스트에 다리 없이 붙으면 4415(재접속 안 함), 열리지 않는 프레임은 4400. 세부는 @dokebi/websocket AI.md §4a·@dokebi/seal README.
203
+ - 같은 앱 = 같은 허브 tenant라서 봉인 호스트에서 보낸 방송도 평문 호스트 소켓에는 평문으로, 봉인 소켓에는 봉인되어 간다.
204
+ - **HTTP(D-0062)**: 봉인 도메인이 있으면 dokebi-web에 `sealRequests(호스트가 봉인인가)`를 등록한다. 그 호스트의 모든 HTTP 요청(앱 라우트든 모듈이 web에 직접 단 `/api/*`든): JSON 응답 봉인, 평문 JSON 본문 415, Inertia 첫 화면 봉인, SSE data 봉인. 앱 라우트 옵션 `seal: false`(`route.post('/hook', handler, { seal: false })`)면 평문(웹훅·서버 사이), dokebi-web `sealExclude`도 같다. EJS HTML은 그대로이고, 네이티브 폼을 받는 라우트는 `seal: false`로 둔다. 봉인 도메인 앱의 Inertia 범위에는 `sealed: true`를 넘겨 SSR과 겹치면 시작 실패(`SEAL_SSR_CONFLICT`). 브라우저: `@dokebi/seal/http`의 `sealInertia`·`sealedFetch`·`currentSealBridge`(CLI 템플릿 `views/app.js`가 봉인 페이지일 때 `/dokebi/seal/http.mjs`를 불러 `sealInertia(http)`를 부른다).
93
205
 
94
206
  ## 5. API
95
207
 
@@ -97,7 +209,13 @@ export default defineApp({
97
209
 
98
210
  ## 6. 시작 때 거절되는 것
99
211
 
100
- 없는 앱을 가리키는 도메인, 등록 안 된 앱, `views` 폴더나 `views/default/`·도메인이 고른 `views/<템플릿>/` 누락, `defineApp`의 모르는 필드, 잘못된 모듈 접두사, `defineModule`로 만들지 않은 모듈.
212
+ 없는 앱을 가리키는 도메인, 등록 안 된 앱, 정의되지 않은 앱 이름의 `apps.<앱>`(`UNKNOWN_APP`), 잘못된 `realtime.namespaces`(빈 목록·중복·형식·33개 이상), `seal: true` 도메인이 있는데 `dokebi-seal` 플러그인이 없음(`SEAL_PROVIDER_MISSING`, 소켓이 없어도), 봉인 도메인의 앱이 소켓을 붙이는데 @dokebi/websocket이 봉인을 모르는 옛 판(0.3 미만, 같은 code), 잘못된 `seal` 값(boolean 아님), `views` 폴더나 `views/default/`·도메인이 고른 `views/<템플릿>/` 누락(원래 파일 오류는 `cause`), `defineApp`의 모르는 필드, 잘못된 모듈 접두사, `defineModule`로 만들지 않은 모듈.
213
+
214
+ (0.2.0 안에서 바뀜: 소켓 없는 봉인 앱의 warn `SEAL_WITHOUT_SOCKETS`는 없앴다 — 이제 HTTP도 봉인되므로 소켓이 없어도 봉인할 것이 있다, D-0062.)
215
+
216
+ warn: 인증이 목록 밖 네임스페이스를 고름(`Realtime namespace refused`, code `NAMESPACE_FORBIDDEN`, 401).
217
+
218
+ debug 로그(D-0047): `App domains configured`(도메인 → 앱/템플릿, 봉인 표시 `(sealed)`·봉인 도메인 수 `sealed`, 64개까지)·`App set up`(requires·템플릿·inertia·모듈·라우트·소켓·SSE 라우트 수 `events`·`namespaces`·ms)·`App realtime handle created`(앱·네임스페이스·websocket/sse 유무, 네임스페이스마다 한 번)·연결마다 `Realtime namespace chosen`(debug가 켜졌을 때만)·`App start finished`·`App drain finished`, 요청마다는 설정에 없는 호스트일 때만 `App domain not configured`(debug가 켜졌을 때만 만든다).
101
219
 
102
220
  ## 7. 주의 사항
103
221
 
@@ -109,4 +227,4 @@ export default defineApp({
109
227
 
110
228
  ## 8. 근거
111
229
 
112
- `examples/25-playground`(vue·ejs 두 앱, 도메인·템플릿, 모듈, 소켓), `examples/26-scaffold`(CLI 생성 반복 검증), D-0030·D-0031·D-0032·D-0039.
230
+ `examples/25-playground`(vue·ejs·admin 앱, 도메인·템플릿, 모듈, 소켓, 네임스페이스: admin이 vue·ejs 접속자를 보고 채팅·SSE 발행), `examples/26-scaffold`(CLI 생성 반복 검증), D-0030·D-0031·D-0032·D-0039·D-0059(봉인 호스트 — 플레이그라운드 `sealed.localhost`, 실제 서버·Chromium 검사는 @dokebi/seal의 `seal:test`·`seal:browser-check`).
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # @dokebi/app 0.1.1
1
+ # @dokebi/app 0.2.0
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
4
 
@@ -18,7 +18,7 @@ dokebi app list
18
18
  dokebi app remove shop # 그 앱을 가리키는 도메인을 먼저 지운다. 폴더는 남는다.
19
19
  ```
20
20
 
21
- 도메인 연결은 dokebi.yaml과 dokebi.example.yaml에 함께 남는다. Inertia 화면이나 WebSocket을 쓰는 앱이 있으면 `dokebi add @dokebi/template-inertia`, `dokebi add @dokebi/websocket`을 따로 한다.
21
+ 도메인 연결은 dokebi.yaml과 dokebi.example.yaml에 함께 남는다. Inertia 화면, WebSocket, SSE를 쓰는 앱이 있으면 `dokebi add @dokebi/template-inertia`, `dokebi add @dokebi/websocket`, `dokebi add @dokebi/sse`를 따로 한다.
22
22
 
23
23
  ## 폴더 구조
24
24
 
@@ -51,7 +51,11 @@ dokebi-app:
51
51
  a.com: { app: shop } # template 생략 = default
52
52
  b.com: { app: shop, template: christmas }
53
53
  c.com: { app: admin }
54
+ s.com: { app: shop, seal: true } # 이 호스트의 WebSocket 프레임을 모두 봉인(아래)
54
55
  unknownDomain: reject # 기본. 또는 domains의 키 하나(그 설정으로 응답)
56
+ apps: # 선택. 키는 정의된 앱 이름(아니면 시작 실패 UNKNOWN_APP)
57
+ shop: { realtime: { namespaces: [front] } } # 기본은 [<앱>]
58
+ admin: { realtime: { namespaces: [admin, front] } } # 아래 「실시간 네임스페이스」
55
59
  ```
56
60
 
57
61
  dokebi-web `requestHost()`가 준 호스트(신뢰 프락시면 `X-Forwarded-Host`)에서 포트를 떼고 소문자로 정확히 비교한다. 프락시 뒤라면 dokebi-web `trustProxy`에 프락시 주소를 적는다. 와일드카드·경로 접두사는 아직 없다. 시작할 때 없는 앱, 없는 템플릿 폴더, `views/default/` 누락을 거부한다.
@@ -75,14 +79,15 @@ export default defineApp({
75
79
  );
76
80
  },
77
81
  sockets: (app) => [chatSocket(app)], // defineSocket(...) 결과
82
+ events: (app) => [ordersStream(app)], // @dokebi/sse 라우트(SseRoute)
78
83
  setup(app) {}, start(app) {}, drain(app) {},
79
84
  });
80
85
  ```
81
86
 
82
- - 핸들러의 `page`는 `{ app: { name, template, domain }, module, base, view, inertia }`다. 앱 라우트에서 `module`은 undefined, `base`는 `''`다. `view`는 `<앱>/<템플릿>` → `<앱>/default` → 공통 src/shared/views 순서로 찾는 EJS 렌더러이고, 레이아웃과 `$include`도 같은 순서를 따른다. `inertia`는 앱의 문서 설정(Vite 진입점 등)을 쓰고 공통 props에 `app`을 더한다.
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`을 더한다.
83
88
  - **모듈 붙이기([D-0032](../../docs/decisions/D-0032-feature-modules.md)):** `modules: { '/접두사': 모듈 }`. 모듈은 `defineModule`로 만든 것이다.
84
89
  - 모듈의 `routes`는 이 앱의 라우트 제약과 접두사로 등록된다. 핸들러 `page.module`·`page.base`가 채워진다.
85
- - 모듈의 `sockets`는 접두사 아래 경로로 등록된다. tenant는 `<앱>:<tenant>`다.
90
+ - 모듈의 `sockets`는 접두사 아래 경로로 등록된다. tenant는 앱 소켓과 같은 `<네임스페이스>:<tenant>`다.
86
91
  - 같은 모듈을 여러 앱이 다른 접두사로 붙일 수 있다. 붙인 모듈은 `requires`에 넣지 않아도 `app.get(모듈)`로 API를 읽는다.
87
92
  - 접두사는 `/` 또는 `/a/b`(소문자·숫자·`.`·`_`·`~`·`-`)다.
88
93
  - 모듈 페이지의 화면 찾는 순서는 다음과 같다. 그래서 모듈 화면은 앱 레이아웃 안에 그려진다.
@@ -95,7 +100,36 @@ export default defineApp({
95
100
  - **`shared(request, { app })`:** 이 앱이 그리는 모든 EJS 페이지(앱 라우트와 모듈 라우트)의 데이터 밑에 합쳐진다. 겹치는 키는 페이지 데이터가 이긴다. 레이아웃이 쓰는 메뉴·사용자 같은 앱 데이터를 여기에 둔다. Inertia 공통 props에 해당한다.
96
101
  - 앱 문맥(`app`)의 `get`·`getDependency`는 `requires`에 넣은 플러그인만 허용한다. 컨트롤러 팩토리도 같은 제한을 받는다.
97
102
  - 앱 라우트는 Fastify 라우트 제약(`dokebiApp`)으로 등록되어 여러 앱이 같은 경로를 가질 수 있다. 제약 없는 공통 라우트(헬스 체크, 모듈 API)는 모든 도메인에서 응답한다.
98
- - 앱의 WebSocket 라우트도 같은 제약으로 등록된다. 허브의 tenant는 `<앱>:<tenant>`가 되어 접속자 목록·방송이 앱 밖으로 나가지 않는다. 세션의 `identity.tenant`도 이 값이다.
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
113
+ const front = app.realtime('front');
114
+ await front.list(); // 모든 서버의 연결(tenant·member·rooms…)
115
+ 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.kick({ tenant: 'shop-1', member: 'u42' });
119
+ const stop = front.onPresence(({ tenant, joined, left }) => {});
120
+ await front.publish({ tenant: 'shop-1' }, 'order.changed', { id: 7 }); // @dokebi/sse
121
+ ```
122
+
123
+ - `send`는 defineSocket 방송과 같은 `{ type, data }` 프레임이고 많아야 한 번(D-0057), 봉인 소켓에는 소켓마다 봉인되어 간다. 필요한 플러그인이 없으면 `REALTIME_UNAVAILABLE`.
124
+ - 관리자 앱 예(두 프론트 공간을 지켜보며 사용자와 채팅)는 [AI.md](AI.md) §4 「실시간 네임스페이스」에 있다.
125
+
126
+ ## 봉인 호스트 (0.2.0, [D-0059](../../docs/decisions/D-0059-seal-and-websocket-client.md) §4)
127
+
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`)으로만 찾는다.
129
+
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의 「호스트별 봉인」을 따른다.
99
133
 
100
134
  ## API
101
135
 
package/dist/index.d.ts CHANGED
@@ -1,9 +1,10 @@
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';
3
4
  import type { TemplateApi } from '@dokebi/template-ejs';
4
5
  import type { InertiaApi, InertiaScopeOptions } from '@dokebi/template-inertia';
5
6
  import type { WebRoute } from '@dokebi/web';
6
- import type { WebsocketRoute } from '@dokebi/websocket';
7
+ import type { WebsocketConnectionInfo, WebsocketKickReceipt, WebsocketPeer, WebsocketReceipt, WebsocketRoute } from '@dokebi/websocket';
7
8
  import type { FastifyReply, FastifyRequest } from 'fastify';
8
9
  /** The Fastify route constraint that selects an app by request host. */
9
10
  export declare const APP_CONSTRAINT = "dokebiApp";
@@ -24,9 +25,19 @@ export interface AppPage {
24
25
  readonly view: TemplateApi;
25
26
  /** Inertia renderer of this app; present when the app sets `inertia`. */
26
27
  readonly inertia: InertiaApi | undefined;
28
+ /**
29
+ * The request host has `seal: true` (D-0059 §4, D-0062): its sockets seal every frame and its
30
+ * HTTP JSON bodies, Inertia pages and SSE data are sealed, so the page should load
31
+ * `/dokebi/seal/*` and use the seal bridge. Also in EJS data and the Inertia shared props as
32
+ * `sealed`. EJS HTML itself stays plain.
33
+ */
34
+ readonly sealed: boolean;
27
35
  }
28
36
  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. */
37
+ /**
38
+ * Fastify route options of an app route; `handler` receives the app page as well. `seal: false`
39
+ * keeps the route plain on a seal host (webhooks, server-to-server; D-0062).
40
+ */
30
41
  export type AppRouteOptions = Omit<WebRoute, 'handler' | 'constraints'> & {
31
42
  readonly handler: AppHandler;
32
43
  };
@@ -38,6 +49,49 @@ export interface AppRouter {
38
49
  patch(url: string, handler: AppHandler, options?: Partial<AppRouteOptions>): void;
39
50
  delete(url: string, handler: AppHandler, options?: Partial<AppRouteOptions>): void;
40
51
  }
52
+ /**
53
+ * Whom a realtime call is about (D-0061), inside one namespace: a tenant (as `authenticate`
54
+ * returned it, without the namespace), or every tenant of the namespace when `tenant` is left
55
+ * out; narrowed to a room, a member, or a member in a room. Strings are 1 to 256 characters.
56
+ */
57
+ export interface RealtimeTarget {
58
+ readonly tenant?: string;
59
+ readonly member?: string;
60
+ readonly room?: string;
61
+ }
62
+ /** A WebSocket connection of a namespace; `tenant` is without the `<namespace>:` prefix. */
63
+ export type RealtimeConnection = WebsocketConnectionInfo;
64
+ /** Joins and leaves of one tenant of a namespace; `tenant` is without the prefix. */
65
+ export interface RealtimePresence {
66
+ readonly tenant: string;
67
+ readonly joined: readonly WebsocketPeer[];
68
+ readonly left: readonly WebsocketPeer[];
69
+ }
70
+ /**
71
+ * One realtime namespace as app server code sees it (D-0061, `app.realtime(namespace)`): the
72
+ * 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).
75
+ */
76
+ export interface RealtimeHandle {
77
+ readonly namespace: string;
78
+ /**
79
+ * Connections of the cluster. With `tenant`: from the hub. Without: every tenant of the
80
+ * namespace, from the presence the hub reported to this server (eventually consistent).
81
+ */
82
+ list(filter?: RealtimeTarget): Promise<readonly RealtimeConnection[]>;
83
+ /**
84
+ * Sends the `{ type, data }` text frame of defineSocket broadcasts through the hub: at most
85
+ * once (D-0057), sealed per sealed socket. Without `tenant`: one broadcast per known tenant.
86
+ */
87
+ send(target: RealtimeTarget, type: string, data?: unknown): Promise<WebsocketReceipt>;
88
+ /** Closes the matching connections on every server (code 4000-4999, default 4403). */
89
+ kick(target: RealtimeTarget, code?: number, reason?: string): Promise<WebsocketKickReceipt>;
90
+ /** Joins and leaves of this namespace's tenants until the returned function is called. */
91
+ onPresence(listener: (change: RealtimePresence) => unknown): () => void;
92
+ /** 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>;
94
+ }
41
95
  /** The view of the Application an app gets: only the plugins it lists in `requires`. */
42
96
  export interface AppContext {
43
97
  readonly name: string;
@@ -48,6 +102,11 @@ export interface AppContext {
48
102
  getOptionalDependency<T>(dependency: PluginDependency<T>): T | undefined;
49
103
  controller<T>(definition: ControllerDefinition<T>): T;
50
104
  defer(cleanup: () => Awaitable<void>): void;
105
+ /**
106
+ * The realtime namespace `namespace` (default: the app's first) of this app's
107
+ * `realtime.namespaces` (D-0061). Another namespace throws NAMESPACE_FORBIDDEN.
108
+ */
109
+ realtime(namespace?: string): RealtimeHandle;
51
110
  }
52
111
  export type AppRequirement = Plugin<unknown> | PluginDependency;
53
112
  export interface AppDefinition {
@@ -72,8 +131,17 @@ export interface AppDefinition {
72
131
  readonly app: AppInfo;
73
132
  }): Awaitable<Record<string, unknown>>;
74
133
  routes?(route: AppRouter, app: AppContext): Awaitable<void>;
75
- /** WebSocket routes (e.g. `defineSocket`) registered for this app's domains only. */
134
+ /**
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.
138
+ */
76
139
  sockets?(app: AppContext): Awaitable<readonly WebsocketRoute[]>;
140
+ /**
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).
143
+ */
144
+ events?(app: AppContext): Awaitable<readonly SseRoute[]>;
77
145
  setup?(app: AppContext): Awaitable<void>;
78
146
  start?(app: AppContext): Awaitable<void>;
79
147
  drain?(app: AppContext): Awaitable<void>;
@@ -83,10 +151,22 @@ export declare function defineApp(definition: AppDefinition): AppDefinition;
83
151
  interface DomainTarget {
84
152
  readonly app: string;
85
153
  readonly template: string;
154
+ /**
155
+ * Seal this host (needs the dokebi-seal plugin): WebSocket frames (D-0059 §4), HTTP JSON
156
+ * bodies, Inertia pages and SSE data (D-0062).
157
+ */
158
+ readonly seal: boolean;
159
+ }
160
+ /** `apps.<app>` of the options: settings of one defined app. */
161
+ interface AppSettings {
162
+ /** `realtime.namespaces` (D-0061); undefined means `[<app>]`. */
163
+ readonly namespaces: readonly string[] | undefined;
86
164
  }
87
165
  export interface AppOptions {
88
166
  readonly domains: ReadonlyMap<string, DomainTarget>;
89
167
  readonly unknownDomain: string | undefined;
168
+ /** `apps`: per app settings; every key must be a defined app (checked at setup). */
169
+ readonly apps: ReadonlyMap<string, AppSettings>;
90
170
  }
91
171
  /** `{ apps: { <name>: defineApp(...) } }`, written by the CLI in src/dokebi.generated.ts. */
92
172
  export interface AppEntry {
package/dist/index.js CHANGED
@@ -38,6 +38,7 @@ export function defineApp(definition) {
38
38
  'shared',
39
39
  'routes',
40
40
  'sockets',
41
+ 'events',
41
42
  'setup',
42
43
  'start',
43
44
  'drain',
@@ -60,13 +61,46 @@ export function defineApp(definition) {
60
61
  throw new TypeError('App modules must be made with defineModule');
61
62
  }
62
63
  }
63
- for (const hook of ['shared', 'routes', 'sockets', 'setup', 'start', 'drain'])
64
+ for (const hook of ['shared', 'routes', 'sockets', 'events', 'setup', 'start', 'drain'])
64
65
  if (definition[hook] !== undefined && typeof definition[hook] !== 'function')
65
66
  throw new TypeError(`App ${hook} must be a function`);
66
67
  const frozen = Object.freeze({ ...definition });
67
68
  defined.add(frozen);
68
69
  return frozen;
69
70
  }
71
+ /** Most namespaces one app may list. */
72
+ const MAX_NAMESPACES = 32;
73
+ function parseApps(input) {
74
+ const result = new Map();
75
+ if (input === undefined)
76
+ return result;
77
+ if (!plain(input))
78
+ throw new TypeError('Invalid dokebi-app apps');
79
+ for (const [app, settings] of Object.entries(input)) {
80
+ if (!NAME.test(app) || !plain(settings))
81
+ throw new TypeError('Invalid apps entry: ' + app);
82
+ const { realtime, ...extra } = settings;
83
+ if (Object.keys(extra).length)
84
+ throw new TypeError('Invalid apps entry: ' + app);
85
+ let namespaces;
86
+ if (realtime !== undefined) {
87
+ if (!plain(realtime))
88
+ throw new TypeError('Invalid realtime settings of app ' + app);
89
+ const { namespaces: list, ...more } = realtime;
90
+ if (Object.keys(more).length ||
91
+ !Array.isArray(list) ||
92
+ types.isProxy(list) ||
93
+ list.length < 1 ||
94
+ list.length > MAX_NAMESPACES ||
95
+ list.some((item) => typeof item !== 'string' || !NAME.test(item)) ||
96
+ new Set(list).size !== list.length)
97
+ throw new TypeError(`apps.${app}.realtime.namespaces must list 1 to ${MAX_NAMESPACES} distinct names matching ${NAME.source}`);
98
+ namespaces = Object.freeze([...list]);
99
+ }
100
+ result.set(app, Object.freeze({ namespaces }));
101
+ }
102
+ return result;
103
+ }
70
104
  function plain(value) {
71
105
  return (value !== null &&
72
106
  typeof value === 'object' &&
@@ -77,21 +111,22 @@ function plain(value) {
77
111
  function parseOptions(input) {
78
112
  if (!plain(input))
79
113
  throw new TypeError('Invalid dokebi-app options');
80
- const { domains, unknownDomain, ...rest } = input;
114
+ const { domains, unknownDomain, apps, ...rest } = input;
81
115
  if (Object.keys(rest).length || !plain(domains))
82
116
  throw new TypeError('Invalid dokebi-app options');
83
117
  const map = new Map();
84
118
  for (const [host, target] of Object.entries(domains)) {
85
119
  if (host.length > 253 || !HOST.test(host) || !plain(target))
86
120
  throw new TypeError('Invalid domain entry');
87
- const { app, template = DEFAULT_TEMPLATE, ...extra } = target;
121
+ const { app, template = DEFAULT_TEMPLATE, seal = false, ...extra } = target;
88
122
  if (Object.keys(extra).length ||
89
123
  typeof app !== 'string' ||
90
124
  !NAME.test(app) ||
91
125
  typeof template !== 'string' ||
92
- !NAME.test(template))
126
+ !NAME.test(template) ||
127
+ typeof seal !== 'boolean')
93
128
  throw new TypeError('Invalid domain entry');
94
- map.set(host, Object.freeze({ app, template }));
129
+ map.set(host, Object.freeze({ app, template, seal }));
95
130
  }
96
131
  if (map.size > 1024)
97
132
  throw new TypeError('Too many domains');
@@ -102,6 +137,7 @@ function parseOptions(input) {
102
137
  return Object.freeze({
103
138
  domains: map,
104
139
  unknownDomain: unknownDomain === 'reject' ? undefined : unknownDomain,
140
+ apps: parseApps(apps),
105
141
  });
106
142
  }
107
143
  function parseEntry(input) {
@@ -119,7 +155,7 @@ function parseEntry(input) {
119
155
  }
120
156
  const web = providerDependency({
121
157
  name: 'dokebi-web',
122
- version: '^0.1.0',
158
+ version: '^0.2.0',
123
159
  packageName: '@dokebi/web',
124
160
  load: () => import('@dokebi/web'),
125
161
  });
@@ -131,9 +167,81 @@ const ejs = providerDependency({
131
167
  });
132
168
  const inertia = optionalDependency({
133
169
  name: 'dokebi-template-inertia',
134
- version: '^0.1.0',
170
+ version: '^0.2.0',
171
+ });
172
+ const websocket = optionalDependency({
173
+ name: 'dokebi-websocket',
174
+ version: '^0.1.0 || ^0.2.0 || ^0.3.0',
135
175
  });
136
- const websocket = optionalDependency({ name: 'dokebi-websocket', version: '^0.1.0' });
176
+ /**
177
+ * The seal plugin (D-0059 §4, D-0062), looked up by name only: a host with `seal: true` needs it
178
+ * (it serves `/dokebi/seal/*`, seals the sockets through @dokebi/websocket and fills the HTTP
179
+ * seal slot of @dokebi/web).
180
+ */
181
+ const seal = optionalDependency({ name: 'dokebi-seal', version: '^0.1.0' });
182
+ /** Server-sent events (@dokebi/sse): app and module `events` routes and `realtime().publish`. */
183
+ const sse = optionalDependency({ name: 'dokebi-sse', version: '^0.1.0' });
184
+ function coded(message, code) {
185
+ return Object.assign(new Error(message), { code });
186
+ }
187
+ /** A realtime target string: 1 to 256 characters. */
188
+ function targetText(value) {
189
+ return typeof value === 'string' && value.length > 0 && value.length <= 256;
190
+ }
191
+ function checkTarget(target) {
192
+ const value = target;
193
+ if (!value ||
194
+ typeof value !== 'object' ||
195
+ (value.tenant !== undefined && !targetText(value.tenant)) ||
196
+ (value.member !== undefined && !targetText(value.member)) ||
197
+ (value.room !== undefined && !targetText(value.room)))
198
+ throw coded('A realtime target is { tenant?, member?, room? } with strings of 1 to 256 characters', 'INVALID_TARGET');
199
+ return value;
200
+ }
201
+ /** The handle of one namespace (D-0061): the namespace prefix on the way in, off on the way out. */
202
+ function realtimeHandle(app, namespace, sockets, streams) {
203
+ const prefix = `${namespace}:`;
204
+ const websocket = () => {
205
+ if (!sockets || typeof sockets.list !== 'function')
206
+ throw coded(`App ${app}: realtime sockets need @dokebi/websocket 0.3 or later`, 'REALTIME_UNAVAILABLE');
207
+ return sockets;
208
+ };
209
+ const filter = (target) => ({
210
+ ...(target.tenant === undefined
211
+ ? { tenantPrefix: prefix }
212
+ : { tenant: prefix + target.tenant }),
213
+ ...(target.room === undefined ? {} : { room: target.room }),
214
+ ...(target.member === undefined ? {} : { member: target.member }),
215
+ });
216
+ return Object.freeze({
217
+ namespace,
218
+ list: async (target = {}) => {
219
+ const connections = await websocket().list(filter(checkTarget(target)));
220
+ return Object.freeze(connections.map((connection) => Object.freeze({ ...connection, tenant: connection.tenant.slice(prefix.length) })));
221
+ },
222
+ send: async (target, type, data) => websocket().send(filter(checkTarget(target)), type, data),
223
+ kick: async (target, code, reason) => websocket().kick(filter(checkTarget(target)), code, reason),
224
+ onPresence: (listener) => {
225
+ if (typeof listener !== 'function')
226
+ throw new TypeError('Invalid presence listener');
227
+ return websocket().onPresence((change) => change.tenant.startsWith(prefix)
228
+ ? listener(Object.freeze({ ...change, tenant: change.tenant.slice(prefix.length) }))
229
+ : undefined);
230
+ },
231
+ publish: async (target, event, data) => {
232
+ if (!streams)
233
+ throw coded(`App ${app}: realtime publish needs @dokebi/sse`, 'REALTIME_UNAVAILABLE');
234
+ const checked = checkTarget(target);
235
+ return streams.publish({
236
+ ...(checked.tenant === undefined
237
+ ? { tenantPrefix: prefix }
238
+ : { tenant: prefix + checked.tenant }),
239
+ ...(checked.room === undefined ? {} : { room: checked.room }),
240
+ ...(checked.member === undefined ? {} : { member: checked.member }),
241
+ }, event, data);
242
+ },
243
+ });
244
+ }
137
245
  const descriptors = new WeakMap();
138
246
  /** Stable descriptor per requirement, so declared and runtime lookups use the same object. */
139
247
  function requirement(value) {
@@ -183,17 +291,47 @@ class AppRuntime {
183
291
  return dependency;
184
292
  }
185
293
  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);
294
+ const target = this.#target(host);
188
295
  return target ? { name: target.app, template: target.template, domain: host } : undefined;
189
296
  }
297
+ #target(host) {
298
+ const domain = this.options.domains.has(host) ? host : this.options.unknownDomain;
299
+ return domain === undefined ? undefined : this.options.domains.get(domain);
300
+ }
301
+ /** The host's `seal` flag (an unknown host answered by `unknownDomain` takes that entry's). */
302
+ sealed(host) {
303
+ return this.#target(host)?.seal === true;
304
+ }
190
305
  async setup(context) {
191
306
  for (const [host, target] of this.options.domains)
192
307
  if (!this.apps.has(target.app))
193
308
  throw new Error(`Domain ${host} points to app ${target.app}, which is not registered`);
309
+ for (const app of this.options.apps.keys())
310
+ if (!this.apps.has(app))
311
+ throw coded(`dokebi-app apps.${app} names an app that is not defined (defined: ${[...this.apps.keys()].join(', ') || 'none'})`, 'UNKNOWN_APP');
194
312
  const http = context.getDependency(web);
313
+ const logger = context.logger;
314
+ const sealedDomains = [...this.options.domains]
315
+ .filter(([, target]) => target.seal)
316
+ .map(([domain]) => domain);
317
+ logger.log('debug', 'App domains configured', {
318
+ apps: [...this.apps.keys()],
319
+ domains: [...this.options.domains]
320
+ .slice(0, 64)
321
+ .map(([domain, target]) => `${domain} -> ${target.app}/${target.template}${target.seal ? ' (sealed)' : ''}`),
322
+ count: this.options.domains.size,
323
+ unknownDomain: this.options.unknownDomain ?? 'reject',
324
+ sealed: sealedDomains.length,
325
+ });
326
+ // Fail closed (D-0059 §4): a sealed host without the seal plugin would talk plain text.
327
+ if (sealedDomains.length && context.getOptionalDependency(seal) === undefined)
328
+ throw Object.assign(new Error(`Domains ${sealedDomains.slice(0, 8).join(', ')} set seal: true; register the dokebi-seal plugin`), { code: 'SEAL_PROVIDER_MISSING' });
195
329
  // Behind a trusted proxy (dokebi-web trustProxy) the forwarded host picks the app.
196
330
  const host = (request) => withoutPort(http.requestHost(request));
331
+ // D-0062: every HTTP request of a sealed host is sealed by dokebi-web (JSON bodies both ways,
332
+ // the Inertia page, SSE data), except routes with seal: false and dokebi-web sealExclude.
333
+ if (sealedDomains.length)
334
+ http.sealRequests((request) => this.sealed(host(request)));
197
335
  http.constraint({
198
336
  name: APP_CONSTRAINT,
199
337
  storage() {
@@ -205,14 +343,64 @@ class AppRuntime {
205
343
  },
206
344
  };
207
345
  },
208
- deriveConstraint: (request) => this.resolve(host(request))?.name,
346
+ deriveConstraint: (request) => {
347
+ const requested = host(request);
348
+ const name = this.resolve(requested)?.name;
349
+ // Per request: only built when debug is on (D-0047).
350
+ if (name === undefined && logger.isEnabled('debug'))
351
+ logger.log('debug', 'App domain not configured', { host: requested.slice(0, 253) });
352
+ return name;
353
+ },
209
354
  // Requests of a known app may still reach shared (unconstrained) routes.
210
355
  mustMatchWhenDerived: false,
211
356
  });
212
357
  const pages = context.getOptionalDependency(inertia);
213
358
  const sockets = context.getOptionalDependency(websocket);
359
+ const streams = context.getOptionalDependency(sse);
360
+ /** Every route of a sealed host seals; other hosts keep what the route itself says. */
361
+ const sealFor = (own) => (request) => this.sealed(host(request)) || own === true || (typeof own === 'function' && own(request));
214
362
  for (const [name, definition] of this.apps) {
215
363
  context.signal.throwIfAborted();
364
+ const begin = performance.now();
365
+ // An app answers its own hosts, and unknown ones when it is the unknownDomain target.
366
+ const appSealed = [...this.options.domains.values()].some((target) => target.app === name && target.seal);
367
+ let routeCount = 0;
368
+ let socketCount = 0;
369
+ let eventCount = 0;
370
+ // D-0061: hub tenants are `<namespace>:<tenant>`; the first namespace is the default.
371
+ const namespaces = this.options.apps.get(name)?.namespaces ?? [name];
372
+ const handles = new Map();
373
+ /** The namespace an authenticated connection joins, or undefined (401) for one not listed. */
374
+ const namespaceOf = (wanted, kind, path) => {
375
+ if (wanted === undefined)
376
+ return namespaces[0];
377
+ if (typeof wanted === 'string' && namespaces.includes(wanted))
378
+ return wanted;
379
+ logger.log('warn', 'Realtime namespace refused', {
380
+ code: 'NAMESPACE_FORBIDDEN',
381
+ app: name,
382
+ kind,
383
+ path,
384
+ namespace: typeof wanted === 'string' ? wanted.slice(0, 64) : null,
385
+ allowed: [...namespaces],
386
+ });
387
+ return undefined;
388
+ };
389
+ /** `identity` in the chosen namespace: tenant prefixed, `namespace` removed. */
390
+ const scoped = (identity, kind, path) => {
391
+ const chosen = namespaceOf(identity.namespace, kind, path);
392
+ if (chosen === undefined)
393
+ return undefined;
394
+ const { namespace: _namespace, ...rest } = identity;
395
+ if (logger.isEnabled('debug'))
396
+ logger.log('debug', 'Realtime namespace chosen', {
397
+ app: name,
398
+ kind,
399
+ path,
400
+ namespace: chosen,
401
+ });
402
+ return { ...rest, tenant: `${chosen}:${identity.tenant}` };
403
+ };
216
404
  const allowed = new Set([...(definition.requires ?? []), ...Object.values(definition.modules ?? {})].map((item) => requirement(item).name));
217
405
  let controllers;
218
406
  const appContext = Object.freeze({
@@ -240,6 +428,22 @@ class AppRuntime {
240
428
  return controllers.get(token);
241
429
  },
242
430
  defer: (cleanup) => context.defer(cleanup),
431
+ realtime: (namespace = namespaces[0]) => {
432
+ let handle = handles.get(namespace);
433
+ if (handle)
434
+ return handle;
435
+ if (!namespaces.includes(namespace))
436
+ throw coded(`App ${name} may use realtime namespaces ${namespaces.join(', ')}, not ${String(namespace).slice(0, 64)}`, 'NAMESPACE_FORBIDDEN');
437
+ handle = realtimeHandle(name, namespace, sockets, streams);
438
+ handles.set(namespace, handle);
439
+ logger.log('debug', 'App realtime handle created', {
440
+ app: name,
441
+ namespace,
442
+ websocket: typeof sockets?.list === 'function',
443
+ sse: streams !== undefined,
444
+ });
445
+ return handle;
446
+ },
243
447
  });
244
448
  // Controller factories read plugins through the same restricted view.
245
449
  const factoryContext = Object.freeze({
@@ -267,9 +471,12 @@ class AppRuntime {
267
471
  throw new Error(`App ${name} uses Inertia; add @dokebi/template-inertia`);
268
472
  inertiaApi = await pages.scope({
269
473
  ...definition.inertia,
474
+ // SSR would write the props of a sealed host as plain HTML: refused (D-0062).
475
+ ...(appSealed ? { sealed: true } : {}),
270
476
  shared: (request) => {
271
- const info = this.resolve(host(request));
272
- return { app: info ? { ...info } : null };
477
+ const requested = host(request);
478
+ const info = this.resolve(requested);
479
+ return { app: info ? { ...info } : null, sealed: this.sealed(requested) };
273
480
  },
274
481
  });
275
482
  }
@@ -292,9 +499,10 @@ class AppRuntime {
292
499
  ...appChain(template),
293
500
  ];
294
501
  };
295
- // The app's shared data under the page data, computed once per render call.
296
- const withShared = (view, request, info) => {
502
+ // `sealed` and the app's shared data under the page data, computed once per render call.
503
+ const withShared = (view, request, info, sealed) => {
297
504
  const data = async (own) => ({
505
+ sealed,
298
506
  ...(await definition.shared?.(request, { app: info })),
299
507
  ...own,
300
508
  });
@@ -308,11 +516,13 @@ class AppRuntime {
308
516
  const scopes = new Map();
309
517
  const hasViews = Boolean(definition.views || module?.views);
310
518
  return (request) => {
311
- const info = this.resolve(host(request)) ?? {
519
+ const requested = host(request);
520
+ const info = this.resolve(requested) ?? {
312
521
  name,
313
522
  template: DEFAULT_TEMPLATE,
314
- domain: host(request),
523
+ domain: requested,
315
524
  };
525
+ const sealed = this.sealed(requested);
316
526
  let view = scopes.get(info.template);
317
527
  if (!view) {
318
528
  templateApi ??= hasViews ? context.getDependency(ejs) : undefined;
@@ -326,14 +536,16 @@ class AppRuntime {
326
536
  app: info,
327
537
  module: module?.name,
328
538
  base: module?.base ?? '',
329
- view: definition.shared ? withShared(view, request, info) : view,
539
+ view: withShared(view, request, info, sealed),
330
540
  inertia: inertiaApi,
541
+ sealed,
331
542
  });
332
543
  };
333
544
  };
334
545
  const routerFor = (page, base) => {
335
546
  const add = (options) => {
336
547
  const { handler, ...rest } = options;
548
+ routeCount++;
337
549
  http.route({
338
550
  ...rest,
339
551
  url: joinPath(base, rest.url),
@@ -357,14 +569,39 @@ class AppRuntime {
357
569
  for (const route of routes) {
358
570
  if (!sockets)
359
571
  throw new Error(`${owner} has sockets; add @dokebi/websocket`);
572
+ // An older @dokebi/websocket ignores route.seal: refuse rather than run plain text.
573
+ if (appSealed && sockets.sealing !== true)
574
+ throw Object.assign(new Error(`${owner} has sealed domains; use @dokebi/websocket 0.3 or later`), { code: 'SEAL_PROVIDER_MISSING' });
575
+ socketCount++;
576
+ const path = joinPath(base, route.path);
360
577
  sockets.route({
361
578
  ...route,
362
- path: joinPath(base, route.path),
579
+ path,
580
+ constraints: { ...(route.constraints ?? {}), [APP_CONSTRAINT]: name },
581
+ // The request's host decides (D-0059 §4); set only when a host of this app seals.
582
+ ...(appSealed ? { seal: sealFor(route.seal) } : {}),
583
+ // Each namespace is its own tenant space in the hub (D-0061): apps that share a
584
+ // namespace share presence and broadcasts; the app's own name is the default.
585
+ authenticate: async (request) => {
586
+ const identity = await route.authenticate(request);
587
+ return identity ? scoped(identity, 'socket', path) : undefined;
588
+ },
589
+ });
590
+ }
591
+ };
592
+ const mountEvents = (routes, base, owner) => {
593
+ for (const route of routes) {
594
+ if (!streams)
595
+ throw new Error(`${owner} has event streams; add @dokebi/sse`);
596
+ eventCount++;
597
+ const path = joinPath(base, route.path);
598
+ streams.route({
599
+ ...route,
600
+ path,
363
601
  constraints: { ...(route.constraints ?? {}), [APP_CONSTRAINT]: name },
364
- // Each app is its own tenant space in the hub: presence and broadcasts stay inside.
365
602
  authenticate: async (request) => {
366
603
  const identity = await route.authenticate(request);
367
- return identity ? { ...identity, tenant: `${name}:${identity.tenant}` } : undefined;
604
+ return identity ? scoped(identity, 'stream', path) : undefined;
368
605
  },
369
606
  });
370
607
  }
@@ -372,7 +609,8 @@ class AppRuntime {
372
609
  await definition.setup?.(appContext);
373
610
  await definition.routes?.(routerFor(pageFor(), ''), appContext);
374
611
  mountSockets((await definition.sockets?.(appContext)) ?? [], '', `App ${name}`);
375
- // Mounted modules (D-0032): their routes and sockets under the prefix, on this app only.
612
+ mountEvents((await definition.events?.(appContext)) ?? [], '', `App ${name}`);
613
+ // Mounted modules (D-0032): their routes, sockets and SSE routes under the prefix, here only.
376
614
  for (const [prefix, plugin] of Object.entries(definition.modules ?? {})) {
377
615
  const mount = mountOf(plugin);
378
616
  const base = prefix === '/' ? '' : prefix;
@@ -382,8 +620,24 @@ class AppRuntime {
382
620
  mountSockets(
383
621
  // defineSocket results; the module types them by shape only.
384
622
  ((await mount.sockets?.(module)) ?? []), base, `Module ${mount.name} (app ${name})`);
623
+ // SSE routes of the module (@dokebi/module 0.1.3; older modules have no `events`).
624
+ mountEvents(((await mount.events?.(module)) ?? []), base, `Module ${mount.name} (app ${name})`);
385
625
  }
386
626
  this.#mounted.push({ name, definition, context: appContext });
627
+ logger.log('debug', 'App set up', {
628
+ app: name,
629
+ requires: [...allowed],
630
+ controllers: definition.controllers?.length ?? 0,
631
+ templates: [...templates],
632
+ inertia: Boolean(inertiaApi),
633
+ modules: Object.entries(definition.modules ?? {}).map(([prefix, plugin]) => `${prefix} -> ${mountOf(plugin).name}`),
634
+ routes: routeCount,
635
+ sockets: socketCount,
636
+ events: eventCount,
637
+ namespaces: [...namespaces],
638
+ sealed: appSealed,
639
+ ms: Math.round(performance.now() - begin),
640
+ });
387
641
  }
388
642
  return Object.freeze({
389
643
  names: Object.freeze([...this.apps.keys()]),
@@ -398,18 +652,40 @@ class AppRuntime {
398
652
  wanted.add(target.template);
399
653
  for (const template of wanted) {
400
654
  const folder = fileURLToPath(new URL(`${template}/`, views));
401
- const info = await stat(folder).catch(() => undefined);
655
+ // A missing folder and an unreadable one both stop setup; the stat error is the cause.
656
+ let failure;
657
+ const info = await stat(folder).catch((cause) => {
658
+ failure = cause;
659
+ return undefined;
660
+ });
402
661
  if (!info?.isDirectory())
403
- throw new Error(`App ${name} has no views/${template}/ folder`);
662
+ throw new Error(`App ${name} has no views/${template}/ folder`, failure === undefined ? undefined : { cause: failure });
404
663
  found.add(template);
405
664
  }
406
665
  }
407
666
  async start() {
408
- for (const { definition, context } of this.#mounted)
409
- await definition.start?.(context);
667
+ for (const { name, definition, context } of this.#mounted) {
668
+ if (!definition.start)
669
+ continue;
670
+ const begin = performance.now();
671
+ await definition.start(context);
672
+ context.logger.log('debug', 'App start finished', {
673
+ app: name,
674
+ ms: Math.round(performance.now() - begin),
675
+ });
676
+ }
410
677
  }
411
678
  async drain() {
412
- await Promise.all(this.#mounted.map(({ definition, context }) => definition.drain?.(context)));
679
+ await Promise.all(this.#mounted.map(async ({ name, definition, context }) => {
680
+ if (!definition.drain)
681
+ return;
682
+ const begin = performance.now();
683
+ await definition.drain(context);
684
+ context.logger.log('debug', 'App drain finished', {
685
+ app: name,
686
+ ms: Math.round(performance.now() - begin),
687
+ });
688
+ }));
413
689
  }
414
690
  }
415
691
  function missingViews(name) {
@@ -421,7 +697,7 @@ function missingViews(name) {
421
697
  }
422
698
  export const createPlugin = definePlugin({
423
699
  name: 'dokebi-app',
424
- version: '0.1.1',
700
+ version: '0.2.0',
425
701
  core: '^0.2.0',
426
702
  options: parseOptions,
427
703
  entry: parseEntry,
@@ -430,7 +706,7 @@ export const createPlugin = definePlugin({
430
706
  const list = [web];
431
707
  if (apps.some((app) => app.views || Object.values(app.modules ?? {}).some((module) => mountOf(module)?.views)))
432
708
  list.push(ejs);
433
- list.push(inertia, websocket);
709
+ list.push(inertia, websocket, seal, sse);
434
710
  for (const app of apps)
435
711
  for (const item of [...(app.requires ?? []), ...Object.values(app.modules ?? {})]) {
436
712
  const dependency = requirement(item);
@@ -22,6 +22,11 @@
22
22
  "type": "string",
23
23
  "pattern": "^[a-z][a-z0-9-]{0,31}$",
24
24
  "description": "Folder under the app views; default: default"
25
+ },
26
+ "seal": {
27
+ "type": "boolean",
28
+ "default": false,
29
+ "description": "Seal every WebSocket frame on this host (D-0059): needs the private dokebi-seal plugin (startup fails with SEAL_PROVIDER_MISSING without it); clients must use the seal bridge or are closed with 4415. Pages get `sealed`."
25
30
  }
26
31
  }
27
32
  }
@@ -29,6 +34,37 @@
29
34
  "unknownDomain": {
30
35
  "type": "string",
31
36
  "description": "reject (404, default) or a key of domains whose app and template answer unknown hosts"
37
+ },
38
+ "apps": {
39
+ "type": "object",
40
+ "description": "Settings per defined app (key = app name; a key that is not a defined app stops startup with UNKNOWN_APP)",
41
+ "propertyNames": {
42
+ "pattern": "^[a-z][a-z0-9-]{0,31}$"
43
+ },
44
+ "additionalProperties": {
45
+ "type": "object",
46
+ "additionalProperties": false,
47
+ "properties": {
48
+ "realtime": {
49
+ "type": "object",
50
+ "additionalProperties": false,
51
+ "required": ["namespaces"],
52
+ "properties": {
53
+ "namespaces": {
54
+ "type": "array",
55
+ "minItems": 1,
56
+ "maxItems": 32,
57
+ "uniqueItems": true,
58
+ "items": {
59
+ "type": "string",
60
+ "pattern": "^[a-z][a-z0-9-]{0,31}$"
61
+ },
62
+ "description": "Realtime namespaces of this app (D-0061); default [<app>]. WebSocket and SSE hub tenants are <namespace>:<tenant>; authenticate may pick one with `namespace` (default the first). Apps sharing a namespace share presence, broadcasts and SSE publications; app.realtime(namespace) reaches any listed one."
63
+ }
64
+ }
65
+ }
66
+ }
67
+ }
32
68
  }
33
69
  }
34
70
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/app",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -32,10 +32,11 @@
32
32
  "@dokebi/controller": "^0.1.0",
33
33
  "@dokebi/core": "^0.2.0",
34
34
  "@dokebi/module": "^0.1.0",
35
+ "@dokebi/sse": "^0.1.0",
35
36
  "@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",
37
+ "@dokebi/template-inertia": "^0.2.0",
38
+ "@dokebi/web": "^0.2.0",
39
+ "@dokebi/websocket": "^0.1.0 || ^0.2.0 || ^0.3.0",
39
40
  "fastify": "^5.12.7"
40
41
  },
41
42
  "peerDependenciesMeta": {
@@ -47,12 +48,18 @@
47
48
  },
48
49
  "@dokebi/module": {
49
50
  "optional": true
51
+ },
52
+ "@dokebi/sse": {
53
+ "optional": true
50
54
  }
51
55
  },
52
56
  "devDependencies": {
53
57
  "@dokebi/module": "^0.1.0",
54
- "@dokebi/template-inertia": "^0.1.0",
55
- "@dokebi/websocket": "^0.1.0"
58
+ "@dokebi/sse": "^0.1.0",
59
+ "@dokebi/template-inertia": "^0.2.0",
60
+ "@dokebi/websocket": "^0.1.0 || ^0.2.0 || ^0.3.0",
61
+ "@dokebi/websocket-hub": "^0.3.0",
62
+ "ws": "8.22.0"
56
63
  },
57
64
  "dokebi": {
58
65
  "schemaVersion": 2,
@@ -61,7 +68,7 @@
61
68
  "dependencies": [
62
69
  {
63
70
  "name": "dokebi-web",
64
- "version": "^0.1.0",
71
+ "version": "^0.2.0",
65
72
  "package": "@dokebi/web"
66
73
  },
67
74
  {
@@ -76,11 +83,21 @@
76
83
  },
77
84
  {
78
85
  "name": "dokebi-template-inertia",
79
- "version": "^0.1.0",
86
+ "version": "^0.2.0",
80
87
  "optional": true
81
88
  },
82
89
  {
83
90
  "name": "dokebi-websocket",
91
+ "version": "^0.1.0 || ^0.2.0 || ^0.3.0",
92
+ "optional": true
93
+ },
94
+ {
95
+ "name": "dokebi-seal",
96
+ "version": "^0.1.0",
97
+ "optional": true
98
+ },
99
+ {
100
+ "name": "dokebi-sse",
84
101
  "version": "^0.1.0",
85
102
  "optional": true
86
103
  }
@@ -1,9 +1,15 @@
1
1
  // Browser entry of this app (Vite input). Pages and the layout are looked up in the template the
2
2
  // domain selected and then in `default`, like the EJS views. The template comes from the shared
3
3
  // prop `app.template` (dokebi-app) of the first page; it is fixed for a domain.
4
- import { createInertiaApp } from '@inertiajs/vue3';
4
+ import { createInertiaApp, http } from '@inertiajs/vue3';
5
5
  import { createApp, createSSRApp, h } from 'vue';
6
6
 
7
+ // A seal host (`seal: true` in dokebi-app domains, D-0062) sends the first page sealed. The
8
+ // @dokebi/seal plugin serves its browser module: it opens the page and seals every later visit.
9
+ // Plain pages skip this, so a project without @dokebi/seal never loads it.
10
+ if (document.querySelector('script[data-page][data-sealed="true"]'))
11
+ await (await import(/* @vite-ignore */ '/dokebi/seal/http.mjs')).sealInertia(http);
12
+
7
13
  const files = import.meta.glob('./*/{Layout,Pages/*}.vue', { eager: true });
8
14
  const first = JSON.parse(document.querySelector('script[data-page]')?.textContent || '{}');
9
15
  const template = first.props?.app?.template ?? 'default';