@dokebi/app 0.1.2 → 0.4.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/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,10 +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 { TemplateApi } from '@dokebi/template-ejs';
4
- import type { InertiaApi, InertiaScopeOptions } from '@dokebi/template-inertia';
5
- import type { WebRoute } from '@dokebi/web';
6
- import type { WebsocketRoute } from '@dokebi/websocket';
3
+ import type { WebErrorResponse, WebRoute } from '@dokebi/web';
7
4
  import type { FastifyReply, FastifyRequest } from 'fastify';
5
+ export { AppError, type AppErrorCode } from './errors.js';
6
+ export { type AppPluginOptions, options } from './options.js';
8
7
  /** The Fastify route constraint that selects an app by request host. */
9
8
  export declare const APP_CONSTRAINT = "dokebiApp";
10
9
  /** Which app answered a request, with the template and the host it came in on. */
@@ -13,6 +12,70 @@ export interface AppInfo {
13
12
  readonly template: string;
14
13
  readonly domain: string;
15
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
+ }
16
79
  /** What an app route handler receives besides the Fastify request and reply. */
17
80
  export interface AppPage {
18
81
  readonly app: AppInfo;
@@ -21,12 +84,22 @@ export interface AppPage {
21
84
  /** The prefix the module is mounted at (`''` for app routes and root mounts), for links. */
22
85
  readonly base: string;
23
86
  /** EJS renderer scoped to `<app>/<template>` → `<app>/default` → shared views. */
24
- readonly view: TemplateApi;
87
+ readonly view: AppView;
25
88
  /** Inertia renderer of this app; present when the app sets `inertia`. */
26
- readonly inertia: InertiaApi | undefined;
89
+ readonly inertia: AppInertia | undefined;
90
+ /**
91
+ * The request host has `seal: true` (D-0059 §4, D-0062): its sockets seal every frame and its
92
+ * HTTP JSON bodies, Inertia pages and SSE data are sealed, so the page should load
93
+ * `/dokebi/seal/*` and use the seal bridge. Also in EJS data and the Inertia shared props as
94
+ * `sealed`. EJS HTML itself stays plain.
95
+ */
96
+ readonly sealed: boolean;
27
97
  }
28
98
  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. */
99
+ /**
100
+ * Fastify route options of an app route; `handler` receives the app page as well. `seal: false`
101
+ * keeps the route plain on a seal host (webhooks, server-to-server; D-0062).
102
+ */
30
103
  export type AppRouteOptions = Omit<WebRoute, 'handler' | 'constraints'> & {
31
104
  readonly handler: AppHandler;
32
105
  };
@@ -38,6 +111,89 @@ export interface AppRouter {
38
111
  patch(url: string, handler: AppHandler, options?: Partial<AppRouteOptions>): void;
39
112
  delete(url: string, handler: AppHandler, options?: Partial<AppRouteOptions>): void;
40
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
+ }
127
+ /**
128
+ * Whom a realtime call is about (D-0061), inside one namespace: a tenant (as `authenticate`
129
+ * returned it, without the namespace), or every tenant of the namespace when `tenant` is left
130
+ * out; narrowed to a room, a member, or a member in a room. Strings are 1 to 256 characters.
131
+ */
132
+ export interface RealtimeTarget {
133
+ readonly tenant?: string;
134
+ readonly member?: string;
135
+ readonly room?: string;
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
+ }
145
+ /** A WebSocket connection of a namespace; `tenant` is without the `<namespace>:` prefix. */
146
+ export interface RealtimeConnection extends RealtimePeer {
147
+ readonly tenant: string;
148
+ readonly rooms: readonly string[];
149
+ }
150
+ /** Joins and leaves of one tenant of a namespace; `tenant` is without the prefix. */
151
+ export interface RealtimePresence {
152
+ readonly tenant: string;
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;
171
+ }
172
+ /**
173
+ * One realtime namespace as app server code sees it (D-0061, `app.realtime(namespace)`): the
174
+ * WebSocket connections and SSE streams whose hub tenant is `<namespace>:<tenant>`, on every
175
+ * server. Calls fail with REALTIME_UNAVAILABLE when no plugin offers the transport they need
176
+ * (@dokebi/websocket, @dokebi/sse).
177
+ */
178
+ export interface RealtimeHandle {
179
+ readonly namespace: string;
180
+ /**
181
+ * Connections of the cluster. With `tenant`: from the hub. Without: every tenant of the
182
+ * namespace, from the presence the hub reported to this server (eventually consistent).
183
+ */
184
+ list(filter?: RealtimeTarget): Promise<readonly RealtimeConnection[]>;
185
+ /**
186
+ * Sends the `{ type, data }` text frame of defineSocket broadcasts through the hub: at most
187
+ * once (D-0057), sealed per sealed socket. Without `tenant`: one broadcast per known tenant.
188
+ */
189
+ send(target: RealtimeTarget, type: string, data?: unknown): Promise<RealtimeReceipt>;
190
+ /** Closes the matching connections on every server (code 4000-4999, default 4403). */
191
+ kick(target: RealtimeTarget, code?: number, reason?: string): Promise<RealtimeKickReceipt>;
192
+ /** Joins and leaves of this namespace's tenants until the returned function is called. */
193
+ onPresence(listener: (change: RealtimePresence) => unknown): () => void;
194
+ /** Publishes one SSE event to this namespace's streams (@dokebi/sse; every process on its bus). */
195
+ publish(target: RealtimeTarget, event: string, data?: unknown): Promise<RealtimePublishResult>;
196
+ }
41
197
  /** The view of the Application an app gets: only the plugins it lists in `requires`. */
42
198
  export interface AppContext {
43
199
  readonly name: string;
@@ -48,6 +204,11 @@ export interface AppContext {
48
204
  getOptionalDependency<T>(dependency: PluginDependency<T>): T | undefined;
49
205
  controller<T>(definition: ControllerDefinition<T>): T;
50
206
  defer(cleanup: () => Awaitable<void>): void;
207
+ /**
208
+ * The realtime namespace `namespace` (default: the app's first) of this app's
209
+ * `realtime.namespaces` (D-0061). Another namespace throws NAMESPACE_FORBIDDEN.
210
+ */
211
+ realtime(namespace?: string): RealtimeHandle;
51
212
  }
52
213
  export type AppRequirement = Plugin<unknown> | PluginDependency;
53
214
  export interface AppDefinition {
@@ -55,10 +216,10 @@ export interface AppDefinition {
55
216
  readonly requires?: readonly AppRequirement[];
56
217
  /** `defineController` tokens built with this app's context. */
57
218
  readonly controllers?: readonly ControllerDefinition<unknown>[];
58
- /** 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. */
59
220
  readonly views?: URL;
60
- /** Document settings of this app's Inertia pages (see template-inertia `scope`). */
61
- readonly inertia?: Omit<InertiaScopeOptions, 'shared'>;
221
+ /** Document settings of this app's Inertia pages. Needs the `inertia` engine. */
222
+ readonly inertia?: AppInertiaOptions;
62
223
  /**
63
224
  * Modules (D-0032) mounted under a prefix: `{ '/board': boardModule }`. Their routes and
64
225
  * sockets answer on this app's domains only; they need not be listed in `requires`.
@@ -72,8 +233,18 @@ export interface AppDefinition {
72
233
  readonly app: AppInfo;
73
234
  }): Awaitable<Record<string, unknown>>;
74
235
  routes?(route: AppRouter, app: AppContext): Awaitable<void>;
75
- /** WebSocket routes (e.g. `defineSocket`) registered for this app's domains only. */
76
- sockets?(app: AppContext): Awaitable<readonly WebsocketRoute[]>;
236
+ /**
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.
241
+ */
242
+ sockets?(app: AppContext): Awaitable<readonly AppRealtimeRoute[]>;
243
+ /**
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).
246
+ */
247
+ events?(app: AppContext): Awaitable<readonly AppRealtimeRoute[]>;
77
248
  setup?(app: AppContext): Awaitable<void>;
78
249
  start?(app: AppContext): Awaitable<void>;
79
250
  drain?(app: AppContext): Awaitable<void>;
@@ -83,10 +254,22 @@ export declare function defineApp(definition: AppDefinition): AppDefinition;
83
254
  interface DomainTarget {
84
255
  readonly app: string;
85
256
  readonly template: string;
257
+ /**
258
+ * Seal this host (needs the dokebi-seal plugin): WebSocket frames (D-0059 §4), HTTP JSON
259
+ * bodies, Inertia pages and SSE data (D-0062).
260
+ */
261
+ readonly seal: boolean;
262
+ }
263
+ /** `apps.<app>` of the options: settings of one defined app. */
264
+ interface AppSettings {
265
+ /** `realtime.namespaces` (D-0061); undefined means `[<app>]`. */
266
+ readonly namespaces: readonly string[] | undefined;
86
267
  }
87
268
  export interface AppOptions {
88
269
  readonly domains: ReadonlyMap<string, DomainTarget>;
89
270
  readonly unknownDomain: string | undefined;
271
+ /** `apps`: per app settings; every key must be a defined app (checked at setup). */
272
+ readonly apps: ReadonlyMap<string, AppSettings>;
90
273
  }
91
274
  /** `{ apps: { <name>: defineApp(...) } }`, written by the CLI in src/dokebi.generated.ts. */
92
275
  export interface AppEntry {
@@ -104,4 +287,3 @@ export interface AppGroupApi {
104
287
  resolve(request: FastifyRequest): AppInfo | undefined;
105
288
  }
106
289
  export declare const createPlugin: import("@dokebi/core").PluginFactory<AppGroupApi>;
107
- export {};