generated from sapphiredev/sapphire-template
/
Server.ts
257 lines (224 loc) · 6.24 KB
/
Server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import { container } from '@sapphire/pieces';
import { EventEmitter } from 'node:events';
import { Server as HttpServer, createServer as httpCreateServer, type ServerOptions as HttpOptions } from 'node:http';
import type { ListenOptions } from 'node:net';
import { MediaParserStore } from '../MediaParserStore';
import { MiddlewareStore } from '../MiddlewareStore';
import { RouteStore, type RouteMatch } from '../RouteStore';
import { ApiRequest } from '../api/ApiRequest';
import { ApiResponse } from '../api/ApiResponse';
import { Auth, type ServerOptionsAuth } from './Auth';
export enum ServerEvents {
Error = 'error',
Request = 'request',
Match = 'match',
NoMatch = 'noMatch',
RouteError = 'routeError',
MiddlewareFailure = 'middlewareFailure',
MiddlewareError = 'middlewareError',
MiddlewareSuccess = 'middlewareSuccess'
}
/**
* @since 1.0.0
*/
export class Server extends EventEmitter {
/**
* The routes this server holds.
* @since 1.0.0
*/
public readonly routes: RouteStore;
/**
* The middlewares this server holds.
* @since 1.0.0
*/
public readonly middlewares: MiddlewareStore;
/**
* The media parsers this server holds.
* @since 1.3.0
*/
public readonly mediaParsers: MediaParserStore;
/**
* The authentication system.
* @since 1.0.0
*/
public readonly auth: Auth | null;
/**
* The http.Server instance that manages the recieved HTTP requests.
* @since 1.0.0
*/
public readonly server: HttpServer;
/**
* The options for this server.
* @since 1.0.0
*/
public readonly options: AuthLessServerOptions;
/**
* @since 1.0.0
* @param options The options for this server
*/
public constructor({ auth, ...options }: ServerOptions = {}) {
super();
container.server = this;
this.options = options;
this.server = httpCreateServer({
IncomingMessage: ApiRequest,
ServerResponse: ApiResponse,
...(options.server ?? {})
});
this.routes = new RouteStore();
this.middlewares = new MiddlewareStore();
this.mediaParsers = new MediaParserStore();
this.auth = Auth.create(auth);
this.server.on('error', this.emit.bind(this, ServerEvents.Error));
this.server.on('request', this.emit.bind(this, ServerEvents.Request));
}
public connect() {
const { server } = this;
server.listen({
port: 4000,
...(this.options.listenOptions ?? {})
});
return new Promise<void>((resolve, reject) => {
function listening() {
cleanup();
resolve();
}
function error(error: Error) {
cleanup();
reject(error);
}
function close() {
cleanup();
reject(new Error('Closed unexpectedly.'));
}
function cleanup() {
server.off('listening', listening);
server.off('error', error);
server.off('close', close);
}
server.on('listening', listening);
server.on('error', error);
server.on('close', close);
});
}
public disconnect() {
return new Promise<void>((resolve, reject) => {
this.server.close((error) => (error ? resolve() : reject(error)));
});
}
}
/**
* RFC 1341 4: Defines a Content-Type's type, which follows the following structure:
*
* - `type` = `text` | `multipart` | `message` | `image` | `audio` | `video` | `application` | x-token
* - `x-token` = The two characters "X-" followed, with no intervening white space, by any token
* @since 1.3.0
*/
export type ContentTypeType = 'text' | 'multipart' | 'message' | 'image' | 'audio' | 'video' | 'application' | `X-${string}`;
/**
* RFC 1341 4: Defines a Content-Type's parameter, which follows the following structure:
*
* - `parameter` = `attribute` "=" `value`
* - `attribute` = `token`
* - `value` = `token` / `quoted-string`
* - `token` = `1*<any CHAR except "SPACE", "CTLs", or "tspecials">`
* - `tspecials` = `(` | `)` | `<` | `>` | `@` | `,` | `;` | `:` | `\` | `"` | `/` | `[` | `]` | `?` | `.` | `=`
*
* @note `tspecials` must be in quoted-string, to use within parameter values.
* @note The definition of `tspecials` is the same as the RFC 822 definition of `specials` with the addition of the
* three characters `/`, `?`, and `=`.
* @since 1.3.0
*/
export type ContentTypeParameter = `; ${string}=${string}`;
/**
* RFC 1341 4: Defines the syntax for a Content-Type field without parameters, which follows the following structure:
* `type "/" subtype`.
*/
export type MimeTypeWithoutParameters = `${ContentTypeType}/${string}`;
/**
* RFC 1341 4: Defines the syntax for a Content-Type field, which follows the following structure:
* `type "/" subtype *[";" parameter]`.
* @since 1.3.0
*/
export type MimeType = `${MimeTypeWithoutParameters}${'' | ContentTypeParameter}`;
/**
* The API options.
* @since 1.0.0
*/
export interface ServerOptions {
/**
* The prefix for all routes, e.g. `v1/`.
* @since 1.0.0
* @default ''
*/
prefix?: string;
/**
* The origin header to be set on every request at 'Access-Control-Allow-Origin'.
* @since 1.0.0
* @default '*'
*/
origin?: string;
/**
* (RFC 7230 3.3.2) The maximum decimal number of octets.
* @since 1.0.0
* @default 1024 * 1024 * 50
*/
maximumBodyLength?: number;
/**
* The accepted content types for this route. If set to null, the route will accept any data.
* @since 1.3.0
* @default null
*/
acceptedContentMimeTypes?: MimeTypeWithoutParameters[] | null;
/**
* The HTTP server options.
* @since 1.0.0
* @default {}
*/
server?: HttpOptions;
/**
* The HTTP listen options.
* @since 1.0.0
* @default { port: 4000 }
*/
listenOptions?: ListenOptions;
/**
* The auth options. If neither `auth` nor `auth.secret` are defined, auth-related routes and middlewares will be
* automatically disabled.
* @since 1.0.0
* @default {}
*/
auth?: ServerOptionsAuth;
/**
* Whether the server should connect upon being when the plugin is loaded.
* @since 3.2.0
* @default true
*/
automaticallyConnect?: boolean;
}
/**
* The {@link ServerOptions} without {@link ServerOptions.auth}.
* @since 1.0.0
*/
export type AuthLessServerOptions = Omit<ServerOptions, 'auth'>;
/**
* The context sent in the error events.
* @since 1.2.0
*/
export interface MiddlewareErrorContext {
/**
* The erroneous request.
* @since 1.2.0
*/
request: ApiRequest;
/**
* The server's response.
* @since 1.2.0
*/
response: ApiResponse;
/**
* The route match.
* @since 1.2.0
*/
match: RouteMatch;
}