dreaction-client-core 1.2.1 → 1.3.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.
Files changed (48) hide show
  1. package/lib/core.d.ts +30 -0
  2. package/lib/core.d.ts.map +1 -0
  3. package/lib/core.js +317 -0
  4. package/lib/index.d.ts +14 -194
  5. package/lib/index.d.ts.map +1 -1
  6. package/lib/index.js +20 -461
  7. package/lib/plugins/api-response.d.ts +1 -1
  8. package/lib/plugins/api-response.d.ts.map +1 -1
  9. package/lib/plugins/benchmark.d.ts +1 -1
  10. package/lib/plugins/benchmark.d.ts.map +1 -1
  11. package/lib/plugins/clear.d.ts +1 -1
  12. package/lib/plugins/clear.d.ts.map +1 -1
  13. package/lib/plugins/image.d.ts +1 -1
  14. package/lib/plugins/image.d.ts.map +1 -1
  15. package/lib/plugins/index.d.ts +53 -0
  16. package/lib/plugins/index.d.ts.map +1 -0
  17. package/lib/plugins/index.js +36 -0
  18. package/lib/plugins/issue.d.ts +19 -0
  19. package/lib/plugins/issue.d.ts.map +1 -0
  20. package/lib/plugins/issue.js +20 -0
  21. package/lib/plugins/logger.d.ts +21 -5
  22. package/lib/plugins/logger.d.ts.map +1 -1
  23. package/lib/plugins/logger.js +11 -23
  24. package/lib/plugins/repl.d.ts +1 -1
  25. package/lib/plugins/repl.d.ts.map +1 -1
  26. package/lib/plugins/state-responses.d.ts +17 -5
  27. package/lib/plugins/state-responses.d.ts.map +1 -1
  28. package/lib/plugins/state-responses.js +10 -19
  29. package/lib/types.d.ts +73 -0
  30. package/lib/types.d.ts.map +1 -0
  31. package/lib/types.js +3 -0
  32. package/lib/utils/plugin-guard.d.ts +12 -0
  33. package/lib/utils/plugin-guard.d.ts.map +1 -0
  34. package/lib/utils/plugin-guard.js +19 -0
  35. package/package.json +2 -2
  36. package/src/core.ts +428 -0
  37. package/src/index.ts +36 -720
  38. package/src/plugins/api-response.ts +1 -1
  39. package/src/plugins/benchmark.ts +1 -1
  40. package/src/plugins/clear.ts +1 -1
  41. package/src/plugins/image.ts +1 -1
  42. package/src/plugins/index.ts +26 -0
  43. package/src/plugins/issue.ts +25 -0
  44. package/src/plugins/logger.ts +19 -35
  45. package/src/plugins/state-responses.ts +19 -29
  46. package/src/types.ts +127 -0
  47. package/src/utils/plugin-guard.ts +31 -0
  48. package/src/plugins/repl.ts +0 -63
package/lib/core.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ import WebSocket from 'ws';
2
+ import type { CommandMap, CommandTypeKey } from 'dreaction-protocol';
3
+ import type { ClientOptions } from './client-options';
4
+ import type { CustomCommand, DisplayConfig, DReactionCore, InferFeatures, Plugin, PluginCreator } from './types';
5
+ export declare class DReactionImpl implements Omit<DReactionCore, 'options' | 'plugins' | 'configure' | 'connect' | 'use' | 'close'> {
6
+ options: ClientOptions<DReactionCore>;
7
+ connected: boolean;
8
+ socket: WebSocket;
9
+ plugins: Plugin<this>[];
10
+ sendQueue: string[];
11
+ isReady: boolean;
12
+ lastMessageDate: Date;
13
+ customCommands: CustomCommand[];
14
+ customCommandLatestId: number;
15
+ private connectPromiseResolve;
16
+ private connectPromiseReject;
17
+ private connectPromise;
18
+ startTimer: () => () => number;
19
+ configure(options?: ClientOptions<this>): ClientOptions<this>['plugins'] extends PluginCreator<this>[] ? this & InferFeatures<ClientOptions<this>['plugins']> : this;
20
+ close(): this;
21
+ connect(): this;
22
+ send: <Type extends CommandTypeKey>(type: Type, payload?: CommandMap[Type]["payload"], important?: boolean) => void;
23
+ display(config: DisplayConfig): void;
24
+ reportError(this: any, error: Error): void;
25
+ use<P extends PluginCreator<this>>(pluginCreator: P): this & InferFeatures<P>;
26
+ registerCustomCommand(config: CustomCommand, optHandler?: () => void): () => void;
27
+ waitForConnect(): Promise<void>;
28
+ }
29
+ export declare function createClient<Client extends DReactionCore = DReactionCore>(options?: ClientOptions<Client>): Client;
30
+ //# sourceMappingURL=core.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core.d.ts","s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,aAAa;IAc7B,WAAW,CAAC,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK;IAInC,GAAG,CAAC,CAAC,SAAS,aAAa,CAAC,IAAI,CAAC,EAC/B,aAAa,EAAE,CAAC,GACf,IAAI,GAAG,aAAa,CAAC,CAAC,CAAC;IAqC1B,qBAAqB,CACnB,MAAM,EAAE,aAAa,EACrB,UAAU,CAAC,EAAE,MAAM,IAAI,GACtB,MAAM,IAAI;IAoFb,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC;CAKhC;AAED,wBAAgB,YAAY,CAAC,MAAM,SAAS,aAAa,GAAG,aAAa,EACvE,OAAO,CAAC,EAAE,aAAa,CAAC,MAAM,CAAC,GAGyB,MAAM,CAC/D"}
package/lib/core.js ADDED
@@ -0,0 +1,317 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.DReactionImpl = void 0;
7
+ exports.createClient = createClient;
8
+ const validate_1 = __importDefault(require("./validate"));
9
+ const serialize_1 = __importDefault(require("./serialize"));
10
+ const stopwatch_1 = require("./stopwatch");
11
+ const plugins_1 = require("./plugins");
12
+ const RESERVED_FEATURES = [
13
+ 'configure',
14
+ 'connect',
15
+ 'connected',
16
+ 'options',
17
+ 'plugins',
18
+ 'send',
19
+ 'socket',
20
+ 'startTimer',
21
+ 'use',
22
+ ];
23
+ const isReservedFeature = (value) => RESERVED_FEATURES.includes(value);
24
+ function emptyPromise() {
25
+ return Promise.resolve('');
26
+ }
27
+ class DReactionImpl {
28
+ options;
29
+ connected = false;
30
+ socket = null;
31
+ plugins = [];
32
+ sendQueue = [];
33
+ isReady = false;
34
+ lastMessageDate = new Date();
35
+ customCommands = [];
36
+ customCommandLatestId = 1;
37
+ connectPromiseResolve = null;
38
+ connectPromiseReject = null;
39
+ connectPromise = null;
40
+ startTimer = () => (0, stopwatch_1.start)();
41
+ configure(options = {}) {
42
+ const newOptions = {
43
+ createSocket: null,
44
+ host: 'localhost',
45
+ port: 9600,
46
+ name: 'dreaction-core-client',
47
+ secure: false,
48
+ plugins: plugins_1.corePlugins,
49
+ safeRecursion: true,
50
+ onCommand: () => null,
51
+ onConnect: () => null,
52
+ onDisconnect: () => null,
53
+ ...this.options,
54
+ ...options,
55
+ };
56
+ (0, validate_1.default)(newOptions);
57
+ this.options = newOptions;
58
+ if (Array.isArray(this.options.plugins)) {
59
+ this.options.plugins.forEach((p) => this.use(p));
60
+ }
61
+ return this;
62
+ }
63
+ close() {
64
+ this.connected = false;
65
+ this.socket?.close?.();
66
+ if (this.connectPromiseReject) {
67
+ this.connectPromiseReject(new Error('Connection closed'));
68
+ this.connectPromiseResolve = null;
69
+ this.connectPromiseReject = null;
70
+ }
71
+ return this;
72
+ }
73
+ connect() {
74
+ this.connected = true;
75
+ this.connectPromise = new Promise((resolve, reject) => {
76
+ this.connectPromiseResolve = resolve;
77
+ this.connectPromiseReject = reject;
78
+ });
79
+ const { createSocket, secure, host, environment, port, name, client = {}, info = {}, getClientId, onCommand, onConnect, onDisconnect, } = this.options;
80
+ if (!host) {
81
+ console.log('host is not config, skip connect.');
82
+ if (this.connectPromiseReject) {
83
+ this.connectPromiseReject(new Error('Host is not configured'));
84
+ this.connectPromiseResolve = null;
85
+ this.connectPromiseReject = null;
86
+ }
87
+ return this;
88
+ }
89
+ const protocol = secure ? 'wss' : 'ws';
90
+ const socket = createSocket(`${protocol}://${host}:${port}`);
91
+ const onOpen = () => {
92
+ onConnect?.();
93
+ this.plugins.forEach((p) => p.onConnect?.());
94
+ if (this.connectPromiseResolve) {
95
+ this.connectPromiseResolve();
96
+ this.connectPromiseResolve = null;
97
+ this.connectPromiseReject = null;
98
+ }
99
+ const getClientIdPromise = getClientId || emptyPromise;
100
+ getClientIdPromise(name).then((clientId) => {
101
+ this.isReady = true;
102
+ this.send('client.intro', {
103
+ environment,
104
+ ...client,
105
+ ...info,
106
+ name,
107
+ clientId,
108
+ dreactionCoreClientVersion: 'DREACTION_CORE_CLIENT_VERSION',
109
+ });
110
+ while (this.sendQueue.length > 0) {
111
+ const h = this.sendQueue.shift();
112
+ this.socket.send(h);
113
+ }
114
+ });
115
+ };
116
+ const onClose = () => {
117
+ this.isReady = false;
118
+ if (this.connectPromiseReject) {
119
+ this.connectPromiseReject(new Error('Connection failed or closed'));
120
+ this.connectPromiseResolve = null;
121
+ this.connectPromiseReject = null;
122
+ }
123
+ onDisconnect?.();
124
+ this.plugins.forEach((p) => p.onDisconnect?.());
125
+ };
126
+ const decodeCommandData = (data) => {
127
+ if (typeof data === 'string')
128
+ return JSON.parse(data);
129
+ if (Buffer.isBuffer(data))
130
+ return JSON.parse(data.toString());
131
+ return data;
132
+ };
133
+ const onMessage = (data) => {
134
+ const command = decodeCommandData(data);
135
+ onCommand?.(command);
136
+ this.plugins.forEach((p) => p.onCommand?.(command));
137
+ if (command.type === 'custom') {
138
+ this.customCommands
139
+ .filter((cc) => typeof command.payload === 'string'
140
+ ? cc.command === command.payload
141
+ : cc.command === command.payload.command)
142
+ .forEach(async (cc) => {
143
+ const res = await cc.handler(typeof command.payload === 'object' ? command.payload.args : {});
144
+ if (res) {
145
+ this.send('customCommand.response', {
146
+ command: cc.command,
147
+ payload: res,
148
+ });
149
+ }
150
+ });
151
+ }
152
+ else if (command.type === 'setClientId') {
153
+ this.options.setClientId?.(command.payload);
154
+ }
155
+ };
156
+ if ('on' in socket && typeof socket.on === 'function') {
157
+ const nodeWebSocket = socket;
158
+ nodeWebSocket.on('open', onOpen);
159
+ nodeWebSocket.on('close', onClose);
160
+ nodeWebSocket.on('message', onMessage);
161
+ this.socket = socket;
162
+ }
163
+ else {
164
+ const browserWebSocket = socket;
165
+ socket.onopen = onOpen;
166
+ socket.onclose = onClose;
167
+ socket.onmessage = (evt) => onMessage(evt.data);
168
+ this.socket = browserWebSocket;
169
+ }
170
+ return this;
171
+ }
172
+ send = (type, payload, important) => {
173
+ const date = new Date();
174
+ let deltaTime = date.getTime() - this.lastMessageDate.getTime();
175
+ if (deltaTime < 0)
176
+ deltaTime = 0;
177
+ this.lastMessageDate = date;
178
+ const fullMessage = {
179
+ type,
180
+ payload,
181
+ important: !!important,
182
+ date: date.toISOString(),
183
+ deltaTime,
184
+ };
185
+ const serializedMessage = (0, serialize_1.default)(fullMessage, this.options.proxyHack);
186
+ if (this.isReady) {
187
+ try {
188
+ this.socket.send(serializedMessage);
189
+ }
190
+ catch {
191
+ this.isReady = false;
192
+ console.log('An error occurred communicating with dreaction. Please reload your app');
193
+ }
194
+ }
195
+ else {
196
+ this.sendQueue.push(serializedMessage);
197
+ }
198
+ };
199
+ display(config) {
200
+ const { name, value, preview, image: img, important = false } = config;
201
+ this.send('display', {
202
+ name,
203
+ value: value || null,
204
+ preview: preview || null,
205
+ image: img || null,
206
+ }, important);
207
+ }
208
+ reportError(error) {
209
+ this.error(error);
210
+ }
211
+ use(pluginCreator) {
212
+ if (typeof pluginCreator !== 'function') {
213
+ throw new Error('plugins must be a function');
214
+ }
215
+ const plugin = pluginCreator.bind(this)(this);
216
+ if (typeof plugin !== 'object') {
217
+ throw new Error('plugins must return an object');
218
+ }
219
+ if (plugin.features) {
220
+ if (typeof plugin.features !== 'object') {
221
+ throw new Error('features must be an object');
222
+ }
223
+ Object.keys(plugin.features).forEach((key) => {
224
+ const featureFunction = plugin.features[key];
225
+ if (typeof featureFunction !== 'function') {
226
+ throw new Error(`feature ${key} is not a function`);
227
+ }
228
+ if (isReservedFeature(key)) {
229
+ throw new Error(`feature ${key} is a reserved name`);
230
+ }
231
+ this[key] = featureFunction;
232
+ });
233
+ }
234
+ this.plugins.push(plugin);
235
+ plugin.onPlugin?.bind(this)(this);
236
+ return this;
237
+ }
238
+ registerCustomCommand(config, optHandler) {
239
+ let command;
240
+ let handler;
241
+ let title;
242
+ let description;
243
+ let args;
244
+ if (typeof config === 'string') {
245
+ command = config;
246
+ handler = optHandler;
247
+ }
248
+ else {
249
+ command = config.command;
250
+ handler = config.handler;
251
+ title = config.title;
252
+ description = config.description;
253
+ args = config.args;
254
+ }
255
+ if (!command)
256
+ throw new Error('A command is required');
257
+ if (!handler)
258
+ throw new Error(`A handler is required for command "${command}"`);
259
+ const existingCommands = this.customCommands.filter((cc) => cc.command === command);
260
+ existingCommands.forEach((cmd) => {
261
+ this.customCommands = this.customCommands.filter((cc) => cc.id !== cmd.id);
262
+ this.send('customCommand.unregister', {
263
+ id: cmd.id,
264
+ command: cmd.command,
265
+ });
266
+ });
267
+ if (args) {
268
+ const argNames = [];
269
+ args.forEach((arg) => {
270
+ if (!arg.name) {
271
+ throw new Error(`A arg on the command "${command}" is missing a name`);
272
+ }
273
+ if (argNames.includes(arg.name)) {
274
+ throw new Error(`A arg with the name "${arg.name}" already exists in the command "${command}"`);
275
+ }
276
+ argNames.push(arg.name);
277
+ });
278
+ }
279
+ const customHandler = {
280
+ id: this.customCommandLatestId++,
281
+ command,
282
+ handler,
283
+ title,
284
+ description,
285
+ args,
286
+ responseViewType: config.responseViewType,
287
+ };
288
+ this.customCommands.push(customHandler);
289
+ this.send('customCommand.register', {
290
+ id: customHandler.id,
291
+ command: customHandler.command,
292
+ title: customHandler.title,
293
+ description: customHandler.description,
294
+ args: customHandler.args,
295
+ responseViewType: customHandler.responseViewType,
296
+ });
297
+ return () => {
298
+ this.customCommands = this.customCommands.filter((cc) => cc.id !== customHandler.id);
299
+ this.send('customCommand.unregister', {
300
+ id: customHandler.id,
301
+ command: customHandler.command,
302
+ });
303
+ };
304
+ }
305
+ waitForConnect() {
306
+ if (this.isReady)
307
+ return Promise.resolve();
308
+ if (this.connectPromise)
309
+ return this.connectPromise;
310
+ return Promise.reject(new Error('Not connected. Call connect() first.'));
311
+ }
312
+ }
313
+ exports.DReactionImpl = DReactionImpl;
314
+ function createClient(options) {
315
+ const client = new DReactionImpl();
316
+ return client.configure(options);
317
+ }
package/lib/index.d.ts CHANGED
@@ -1,199 +1,19 @@
1
- import WebSocket from 'ws';
2
- import type { Command, CommandMap, CommandTypeKey, CustomCommandArg, CustomCommandRegisterPayload } from 'dreaction-protocol';
3
- import { ClientOptions } from './client-options';
4
- export type { ClientOptions };
5
- export { assertHasLoggerPlugin } from './plugins/logger';
6
- export type { LoggerPlugin } from './plugins/logger';
1
+ export type { ClientOptions } from './client-options';
2
+ export type { CustomCommand, CustomCommandArgs, DisplayConfig, DReactionCore, InferFeatures, InferFeaturesFromPlugins, LifeCycleMethods, Plugin, PluginCreator, } from './types';
3
+ export { DReactionImpl, createClient } from './core';
4
+ export { corePlugins } from './plugins';
5
+ export { assertHasLoggerPlugin, hasLoggerPlugin } from './plugins/logger';
6
+ export type { LoggerPlugin, LoggerFeatures } from './plugins/logger';
7
7
  export { assertHasStateResponsePlugin, hasStateResponsePlugin, } from './plugins/state-responses';
8
- export type { StateResponsePlugin } from './plugins/state-responses';
8
+ export type { StateResponsePlugin, StateResponseFeatures, } from './plugins/state-responses';
9
+ export { assertHasIssuePlugin, hasIssuePlugin } from './plugins/issue';
10
+ export type { IssuePlugin, IssueFeatures } from './plugins/issue';
9
11
  export { runFPSMeter } from './utils/fps';
10
- export interface LifeCycleMethods {
11
- onCommand?: (command: Command) => void;
12
- onConnect?: () => void;
13
- onDisconnect?: () => void;
14
- }
15
- type AnyFunction = (...args: any[]) => any;
16
- export interface Plugin<Client> extends LifeCycleMethods {
17
- features?: {
18
- [key: string]: AnyFunction;
19
- };
20
- onPlugin?: (client: Client) => void;
21
- }
22
- export type PluginCreator<Client> = (client: Client) => Plugin<Client>;
23
- interface DisplayConfig {
24
- name: string;
25
- value?: object | string | number | boolean | null | undefined;
26
- preview?: string;
27
- image?: string | {
28
- uri: string;
29
- };
30
- important?: boolean;
31
- }
32
- interface ArgTypeMap {
33
- string: string;
34
- }
35
- type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
36
- export type CustomCommandArgs<Args extends CustomCommandArg[]> = UnionToIntersection<Args extends Array<infer U> ? U extends CustomCommandArg ? {
37
- [K in U as U['name']]: ArgTypeMap[U['type']];
38
- } : never : never>;
39
- export interface CustomCommand<Args extends CustomCommandArg[] = CustomCommandArg[]> extends Omit<CustomCommandRegisterPayload, 'id' | 'args'> {
40
- id?: number;
41
- handler: (args: CustomCommandArgs<Args>) => any | Promise<any>;
42
- args?: Args;
43
- }
44
- type ExtractFeatures<T> = T extends {
45
- features: infer U;
46
- } ? U : never;
47
- type PluginFeatures<Client, P extends PluginCreator<Client>> = ExtractFeatures<ReturnType<P>>;
48
- export type InferFeaturesFromPlugins<Client, Plugins extends PluginCreator<Client>[]> = UnionToIntersection<PluginFeatures<Client, Plugins[number]>>;
49
- type InferFeaturesFromPlugin<Client, P extends PluginCreator<Client>> = UnionToIntersection<PluginFeatures<Client, P>>;
50
- export interface DReactionCore {
51
- connected: boolean;
52
- isReady: boolean;
53
- options: ClientOptions<this>;
54
- plugins: Plugin<this>[];
55
- startTimer: () => () => number;
56
- close: () => this;
57
- send: <Type extends keyof CommandMap>(type: Type, payload?: CommandMap[Type], important?: boolean) => void;
58
- display: (config: DisplayConfig) => void;
59
- registerCustomCommand: <Args extends CustomCommandArg[] = Exclude<CustomCommand['args'], undefined>>(config: CustomCommand<Args>) => () => void | ((config: string, optHandler?: () => void) => () => void);
60
- /**
61
- * Set the configuration options.
62
- */
63
- configure: (options?: ClientOptions<this>) => ClientOptions<this>['plugins'] extends PluginCreator<this>[] ? this & InferFeaturesFromPlugins<this, ClientOptions<this>['plugins']> : this;
64
- use: <P extends PluginCreator<this>>(pluginCreator: P) => this & InferFeaturesFromPlugin<this, P>;
65
- connect: () => this;
66
- /**
67
- * Wait for connection to be established
68
- */
69
- waitForConnect: () => Promise<void>;
70
- }
71
- export type InferFeatures<Client = DReactionCore, PC extends PluginCreator<Client> = PluginCreator<Client>> = PC extends (client: Client) => {
72
- features: infer U;
73
- } ? U : never;
74
- export declare const corePlugins: (((dreaction: DReactionCore) => {
75
- features: {
76
- log: (...args: any[]) => void;
77
- logImportant: (...args: any[]) => void;
78
- debug: (message: any, important?: any) => void;
79
- warn: (message: any) => void;
80
- error: (message: any, stack: any) => void;
81
- };
82
- }) | ((dreaction: DReactionCore) => {
83
- features: {
84
- image: (payload: import("./plugins/image").ImagePayload) => void;
85
- };
86
- }) | ((dreaction: DReactionCore) => {
87
- features: {
88
- benchmark: (title: string) => {
89
- step: (stepTitle: string) => void;
90
- stop: (stopTitle: string) => void;
91
- last: (stopTitle: string) => void;
92
- };
93
- };
94
- }) | ((dreaction: DReactionCore) => {
95
- features: {
96
- stateActionComplete: (name: import("dreaction-protocol").StateActionCompletePayload["name"], action: import("dreaction-protocol").StateActionCompletePayload["action"], important?: any) => void;
97
- stateValuesResponse: (path: import("dreaction-protocol").StateValuesResponsePayload["path"], value: import("dreaction-protocol").StateValuesResponsePayload["value"], valid?: import("dreaction-protocol").StateValuesResponsePayload["value"]) => void;
98
- stateKeysResponse: (path: import("dreaction-protocol").StateKeysResponsePayload["path"], keys: import("dreaction-protocol").StateKeysResponsePayload["keys"], valid?: import("dreaction-protocol").StateKeysResponsePayload["valid"]) => void;
99
- stateValuesChange: (changes: import("dreaction-protocol").StateValuesChangePayload["changes"]) => false | void;
100
- stateBackupResponse: (state: import("dreaction-protocol").StateBackupResponsePayload["state"]) => void;
101
- };
102
- }) | ((dreaction: DReactionCore) => {
103
- features: {
104
- apiResponse: (request: {
105
- status: number;
106
- }, response: any, duration: number) => void;
107
- };
108
- }) | ((dreaction: DReactionCore) => {
109
- features: {
110
- clear: () => void;
111
- };
112
- }) | ((dreaction: DReactionCore) => {
113
- onCommand: ({ type, payload }: Command) => void;
114
- features: {
115
- repl: (name: string, value: import("./plugins/repl").AcceptableRepls) => void;
116
- };
117
- }))[];
118
- export type InferPluginsFromCreators<Client, PC extends PluginCreator<Client>[]> = PC extends Array<infer P extends PluginCreator<Client>> ? ReturnType<P>[] : never;
119
- export type CorePluginFeatures = InferFeaturesFromPlugins<DReactionCore, typeof corePlugins>;
12
+ export { createPluginGuard } from './utils/plugin-guard';
13
+ import type { InferFeatures } from './types';
14
+ import type { corePlugins } from './plugins';
15
+ export type CorePluginFeatures = InferFeatures<typeof corePlugins>;
16
+ import type { DReactionCore } from './types';
120
17
  export interface DReaction extends DReactionCore, CorePluginFeatures {
121
18
  }
122
- export declare class DReactionImpl implements Omit<DReactionCore, 'options' | 'plugins' | 'configure' | 'connect' | 'use' | 'close'> {
123
- options: ClientOptions<DReactionCore>;
124
- /**
125
- * Are we connected to a server?
126
- */
127
- connected: boolean;
128
- /**
129
- * The socket we're using.
130
- */
131
- socket: WebSocket;
132
- /**
133
- * Available plugins.
134
- */
135
- plugins: Plugin<this>[];
136
- /**
137
- * Messages that need to be sent.
138
- */
139
- sendQueue: string[];
140
- /**
141
- * Are we ready to start communicating?
142
- */
143
- isReady: boolean;
144
- /**
145
- * The last time we sent a message.
146
- */
147
- lastMessageDate: Date;
148
- /**
149
- * The registered custom commands
150
- */
151
- customCommands: CustomCommand[];
152
- /**
153
- * The current ID for custom commands
154
- */
155
- customCommandLatestId: number;
156
- /**
157
- * Promise resolvers for connection wait
158
- */
159
- private connectPromiseResolve;
160
- private connectPromiseReject;
161
- private connectPromise;
162
- /**
163
- * Starts a timer and returns a function you can call to stop it and return the elapsed time.
164
- */
165
- startTimer: () => () => number;
166
- /**
167
- * Set the configuration options.
168
- */
169
- configure(options?: ClientOptions<this>): ClientOptions<this>['plugins'] extends PluginCreator<this>[] ? this & InferFeaturesFromPlugins<this, ClientOptions<this>['plugins']> : this;
170
- close(): this;
171
- /**
172
- * Connect to the DReaction server.
173
- */
174
- connect(): this;
175
- /**
176
- * Sends a command to the server
177
- */
178
- send: <Type extends CommandTypeKey>(type: Type, payload?: CommandMap[Type]["payload"], important?: boolean) => void;
179
- /**
180
- * Sends a custom command to the server to displays nicely.
181
- */
182
- display(config: DisplayConfig): void;
183
- /**
184
- * Client libraries can hijack this to report errors.
185
- */
186
- reportError(this: any, error: Error): void;
187
- /**
188
- * Adds a plugin to the system
189
- */
190
- use(pluginCreator: PluginCreator<this>): this & PluginFeatures<this, typeof pluginCreator>;
191
- registerCustomCommand(config: CustomCommand, optHandler?: () => void): () => void;
192
- /**
193
- * Wait for connection to be established.
194
- * Returns a promise that resolves when the connection is ready.
195
- */
196
- waitForConnect(): Promise<void>;
197
- }
198
- export declare function createClient<Client extends DReactionCore = DReactionCore>(options?: ClientOptions<Client>): Client;
199
19
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,IAAI,CAAC;AAC3B,OAAO,KAAK,EACV,OAAO,EACP,UAAU,EACV,cAAc,EACd,gBAAgB,EAChB,4BAA4B,EAC7B,MAAM,oBAAoB,CAAC;AAW5B,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD,YAAY,EAAE,aAAa,EAAE,CAAC;AAC9B,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AACzD,YAAY,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EACL,4BAA4B,EAC5B,sBAAsB,GACvB,MAAM,2BAA2B,CAAC;AACnC,YAAY,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAG1C,MAAM,WAAW,gBAAgB;IAC/B,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,CAAC;IACvC,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC;IACvB,YAAY,CAAC,EAAE,MAAM,IAAI,CAAC;CAC3B;AAED,KAAK,WAAW,GAAG,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC;AAC3C,MAAM,WAAW,MAAM,CAAC,MAAM,CAAE,SAAQ,gBAAgB;IACtD,QAAQ,CAAC,EAAE;QACT,CAAC,GAAG,E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