@colyseus/sdk 0.17.32 → 0.17.34
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/LICENSE +2 -1
- package/README.md +27 -0
- package/build/3rd_party/discord.cjs +1 -1
- package/build/3rd_party/discord.mjs +1 -1
- package/build/Auth.cjs +1 -1
- package/build/Auth.mjs +1 -1
- package/build/Client.cjs +1 -1
- package/build/Client.mjs +1 -1
- package/build/Connection.cjs +1 -1
- package/build/Connection.mjs +1 -1
- package/build/HTTP.bkp.d.ts +103 -0
- package/build/HTTP.cjs +1 -1
- package/build/HTTP.mjs +1 -1
- package/build/HTTP_bkp.d.ts +18 -0
- package/build/Protocol.cjs +34 -0
- package/build/Protocol.cjs.map +1 -0
- package/build/Protocol.d.ts +21 -0
- package/build/Protocol.mjs +34 -0
- package/build/Protocol.mjs.map +1 -0
- package/build/Room.cjs +1 -1
- package/build/Room.mjs +1 -1
- package/build/Storage.cjs +1 -1
- package/build/Storage.mjs +1 -1
- package/build/core/nanoevents.cjs +1 -1
- package/build/core/nanoevents.mjs +1 -1
- package/build/core/signal.cjs +1 -1
- package/build/core/signal.mjs +1 -1
- package/build/core/utils.cjs +1 -1
- package/build/core/utils.mjs +1 -1
- package/build/debug.cjs +5 -26
- package/build/debug.cjs.map +1 -1
- package/build/debug.mjs +5 -26
- package/build/debug.mjs.map +1 -1
- package/build/errors/Errors.cjs +1 -1
- package/build/errors/Errors.mjs +1 -1
- package/build/index.cjs +1 -1
- package/build/index.mjs +1 -1
- package/build/legacy.cjs +1 -1
- package/build/legacy.mjs +1 -1
- package/build/serializer/NoneSerializer.cjs +1 -1
- package/build/serializer/NoneSerializer.mjs +1 -1
- package/build/serializer/SchemaSerializer.cjs +1 -1
- package/build/serializer/SchemaSerializer.mjs +1 -1
- package/build/serializer/Serializer.cjs +1 -1
- package/build/serializer/Serializer.mjs +1 -1
- package/build/transport/H3Transport.cjs +1 -1
- package/build/transport/H3Transport.mjs +1 -1
- package/build/transport/WebSocketTransport.cjs +1 -1
- package/build/transport/WebSocketTransport.mjs +1 -1
- package/dist/colyseus-cocos-creator.js +16 -4
- package/dist/colyseus-cocos-creator.js.map +1 -1
- package/dist/colyseus.d.ts +4148 -0
- package/dist/colyseus.js +16 -4
- package/dist/colyseus.js.map +1 -1
- package/dist/debug.js +5 -26
- package/dist/debug.js.map +1 -1
- package/package.json +3 -3
- package/src/debug.ts +4 -28
|
@@ -0,0 +1,4148 @@
|
|
|
1
|
+
// Generated by dts-bundle-generator v9.5.1
|
|
2
|
+
|
|
3
|
+
interface StandardTypedV1<Input = unknown, Output = Input> {
|
|
4
|
+
/** The Standard properties. */
|
|
5
|
+
readonly "~standard": StandardTypedV1.Props<Input, Output>;
|
|
6
|
+
}
|
|
7
|
+
declare namespace StandardTypedV1 {
|
|
8
|
+
/** The Standard Typed properties interface. */
|
|
9
|
+
interface Props<Input = unknown, Output = Input> {
|
|
10
|
+
/** The version number of the standard. */
|
|
11
|
+
readonly version: 1;
|
|
12
|
+
/** The vendor name of the schema library. */
|
|
13
|
+
readonly vendor: string;
|
|
14
|
+
/** Inferred types associated with the schema. */
|
|
15
|
+
readonly types?: Types<Input, Output> | undefined;
|
|
16
|
+
}
|
|
17
|
+
/** The Standard Typed types interface. */
|
|
18
|
+
interface Types<Input = unknown, Output = Input> {
|
|
19
|
+
/** The input type of the schema. */
|
|
20
|
+
readonly input: Input;
|
|
21
|
+
/** The output type of the schema. */
|
|
22
|
+
readonly output: Output;
|
|
23
|
+
}
|
|
24
|
+
/** Infers the input type of a Standard Typed. */
|
|
25
|
+
type InferInput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["input"];
|
|
26
|
+
/** Infers the output type of a Standard Typed. */
|
|
27
|
+
type InferOutput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["output"];
|
|
28
|
+
}
|
|
29
|
+
interface StandardSchemaV1<Input = unknown, Output = Input> {
|
|
30
|
+
/** The Standard Schema properties. */
|
|
31
|
+
readonly "~standard": StandardSchemaV1.Props<Input, Output>;
|
|
32
|
+
}
|
|
33
|
+
declare namespace StandardSchemaV1 {
|
|
34
|
+
/** The Standard Schema properties interface. */
|
|
35
|
+
interface Props<Input = unknown, Output = Input> extends StandardTypedV1.Props<Input, Output> {
|
|
36
|
+
/** Validates unknown input values. */
|
|
37
|
+
readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => Result<Output> | Promise<Result<Output>>;
|
|
38
|
+
}
|
|
39
|
+
/** The result interface of the validate function. */
|
|
40
|
+
type Result<Output> = SuccessResult<Output> | FailureResult;
|
|
41
|
+
/** The result interface if validation succeeds. */
|
|
42
|
+
interface SuccessResult<Output> {
|
|
43
|
+
/** The typed output value. */
|
|
44
|
+
readonly value: Output;
|
|
45
|
+
/** A falsy value for `issues` indicates success. */
|
|
46
|
+
readonly issues?: undefined;
|
|
47
|
+
}
|
|
48
|
+
interface Options {
|
|
49
|
+
/** Explicit support for additional vendor-specific parameters, if needed. */
|
|
50
|
+
readonly libraryOptions?: Record<string, unknown> | undefined;
|
|
51
|
+
}
|
|
52
|
+
/** The result interface if validation fails. */
|
|
53
|
+
interface FailureResult {
|
|
54
|
+
/** The issues of failed validation. */
|
|
55
|
+
readonly issues: ReadonlyArray<Issue>;
|
|
56
|
+
}
|
|
57
|
+
/** The issue interface of the failure output. */
|
|
58
|
+
interface Issue {
|
|
59
|
+
/** The error message of the issue. */
|
|
60
|
+
readonly message: string;
|
|
61
|
+
/** The path of the issue, if any. */
|
|
62
|
+
readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
|
|
63
|
+
}
|
|
64
|
+
/** The path segment interface of the issue. */
|
|
65
|
+
interface PathSegment {
|
|
66
|
+
/** The key representing a path segment. */
|
|
67
|
+
readonly key: PropertyKey;
|
|
68
|
+
}
|
|
69
|
+
/** The Standard types interface. */
|
|
70
|
+
interface Types<Input = unknown, Output = Input> extends StandardTypedV1.Types<Input, Output> {
|
|
71
|
+
}
|
|
72
|
+
/** Infers the input type of a Standard. */
|
|
73
|
+
type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;
|
|
74
|
+
/** Infers the output type of a Standard. */
|
|
75
|
+
type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Colyseus protocol codes range between 0~100
|
|
79
|
+
* Use codes between 0~127 for lesser throughput (1 byte)
|
|
80
|
+
*/
|
|
81
|
+
export declare const Protocol: {
|
|
82
|
+
readonly JOIN_ROOM: 10;
|
|
83
|
+
readonly ERROR: 11;
|
|
84
|
+
readonly LEAVE_ROOM: 12;
|
|
85
|
+
readonly ROOM_DATA: 13;
|
|
86
|
+
readonly ROOM_STATE: 14;
|
|
87
|
+
readonly ROOM_STATE_PATCH: 15;
|
|
88
|
+
readonly ROOM_DATA_SCHEMA: 16;
|
|
89
|
+
readonly ROOM_DATA_BYTES: 17;
|
|
90
|
+
readonly PING: 18;
|
|
91
|
+
};
|
|
92
|
+
export type Protocol = typeof Protocol[keyof typeof Protocol];
|
|
93
|
+
/**
|
|
94
|
+
* HTTP MatchMaking Error Codes
|
|
95
|
+
*/
|
|
96
|
+
export declare const ErrorCode: {
|
|
97
|
+
readonly MATCHMAKE_NO_HANDLER: 520;
|
|
98
|
+
readonly MATCHMAKE_INVALID_CRITERIA: 521;
|
|
99
|
+
readonly MATCHMAKE_INVALID_ROOM_ID: 522;
|
|
100
|
+
readonly MATCHMAKE_UNHANDLED: 523;
|
|
101
|
+
readonly MATCHMAKE_EXPIRED: 524;
|
|
102
|
+
readonly AUTH_FAILED: 525;
|
|
103
|
+
readonly APPLICATION_ERROR: 526;
|
|
104
|
+
readonly INVALID_PAYLOAD: 4217;
|
|
105
|
+
};
|
|
106
|
+
export type ErrorCode = typeof ErrorCode[keyof typeof ErrorCode];
|
|
107
|
+
/**
|
|
108
|
+
* WebSocket close codes
|
|
109
|
+
* (See https://github.com/Luka967/websocket-close-codes)
|
|
110
|
+
*/
|
|
111
|
+
export declare const CloseCode: {
|
|
112
|
+
readonly NORMAL_CLOSURE: 1000;
|
|
113
|
+
readonly GOING_AWAY: 1001;
|
|
114
|
+
readonly NO_STATUS_RECEIVED: 1005;
|
|
115
|
+
readonly ABNORMAL_CLOSURE: 1006;
|
|
116
|
+
readonly CONSENTED: 4000;
|
|
117
|
+
readonly SERVER_SHUTDOWN: 4001;
|
|
118
|
+
readonly WITH_ERROR: 4002;
|
|
119
|
+
readonly FAILED_TO_RECONNECT: 4003;
|
|
120
|
+
readonly MAY_TRY_RECONNECT: 4010;
|
|
121
|
+
};
|
|
122
|
+
export type CloseCode = typeof CloseCode[keyof typeof CloseCode];
|
|
123
|
+
interface ServerRoomLike<State = any, Options = any> {
|
|
124
|
+
state: State;
|
|
125
|
+
onJoin?: (client: any, options?: Options, auth?: any) => any;
|
|
126
|
+
messages?: Record<string, any>;
|
|
127
|
+
"~client"?: {
|
|
128
|
+
"~messages"?: Record<string, any>;
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Seat reservation returned by matchmaking operations.
|
|
133
|
+
*/
|
|
134
|
+
interface ISeatReservation {
|
|
135
|
+
name: string;
|
|
136
|
+
sessionId: string;
|
|
137
|
+
roomId: string;
|
|
138
|
+
publicAddress?: string;
|
|
139
|
+
processId?: string;
|
|
140
|
+
reconnectionToken?: string;
|
|
141
|
+
devMode?: boolean;
|
|
142
|
+
}
|
|
143
|
+
type Instantiate<T> = T extends abstract new (...args: any) => infer I ? I : T;
|
|
144
|
+
type IsSchema<T> = "~refId" extends keyof T ? true : false;
|
|
145
|
+
type HasUsefulStatePhantom<T> = T extends {
|
|
146
|
+
"~state": infer S;
|
|
147
|
+
} ? [
|
|
148
|
+
S
|
|
149
|
+
] extends [
|
|
150
|
+
never
|
|
151
|
+
] ? false : unknown extends S ? false : S extends object ? [
|
|
152
|
+
keyof S
|
|
153
|
+
] extends [
|
|
154
|
+
never
|
|
155
|
+
] ? false : true : false : false;
|
|
156
|
+
type ExtractStateFromRoom<T> = T extends {
|
|
157
|
+
"~state": infer S;
|
|
158
|
+
} ? HasUsefulStatePhantom<T> extends true ? S : T extends {
|
|
159
|
+
state: infer St;
|
|
160
|
+
} ? IsSchema<St> extends true ? St : T : T : T extends {
|
|
161
|
+
state: infer S;
|
|
162
|
+
} ? IsSchema<S> extends true ? S : T : T;
|
|
163
|
+
type InferState<T, S> = [
|
|
164
|
+
S
|
|
165
|
+
] extends [
|
|
166
|
+
never
|
|
167
|
+
] ? Instantiate<T> extends infer I ? IsSchema<I> extends true ? I : ExtractStateFromRoom<I> : never : S;
|
|
168
|
+
type NormalizeRoomType<T> = Instantiate<T> extends {
|
|
169
|
+
"~state": any;
|
|
170
|
+
} ? T : any;
|
|
171
|
+
type ExtractRoomMessages<T> = Instantiate<T> extends {
|
|
172
|
+
messages: infer M;
|
|
173
|
+
} ? M : {};
|
|
174
|
+
type ExtractRoomClientMessages<T> = Instantiate<T> extends {
|
|
175
|
+
"~client": {
|
|
176
|
+
"~messages": infer M;
|
|
177
|
+
};
|
|
178
|
+
} ? M : {};
|
|
179
|
+
type MessageHandlerWithFormat<T extends StandardSchemaV1 = any, Client = any, This = any> = {
|
|
180
|
+
format: T;
|
|
181
|
+
handler: (this: This, client: Client, message: StandardSchemaV1.InferOutput<T>) => void;
|
|
182
|
+
};
|
|
183
|
+
type MessageHandler<Client = any, This = any> = ((this: This, client: Client, message: any) => void) | MessageHandlerWithFormat<any, Client, This>;
|
|
184
|
+
type ExtractMessageType<T> = T extends {
|
|
185
|
+
format: infer Format extends StandardSchemaV1;
|
|
186
|
+
handler: any;
|
|
187
|
+
} ? StandardSchemaV1.InferOutput<Format> : T extends (this: any, client: any, message: infer Message) => void ? Message : any;
|
|
188
|
+
type FallbackMessageHandler<Client = any, This = any> = (this: This, client: Client, type: string, message: any) => void;
|
|
189
|
+
type AnyMessageHandler<Client = any, This = any> = MessageHandler<Client, This> | FallbackMessageHandler<Client, This>;
|
|
190
|
+
type Messages<Room = any, Client = any> = Record<string, AnyMessageHandler<Client, Room>> & ThisType<Room>;
|
|
191
|
+
interface SDKTypes<RoomTypes extends Record<string, any> = any, Routes = any> {
|
|
192
|
+
"~rooms": RoomTypes;
|
|
193
|
+
"~routes": Routes;
|
|
194
|
+
}
|
|
195
|
+
declare enum OPERATION {
|
|
196
|
+
ADD = 128,// (10000000) add new structure/primitive
|
|
197
|
+
REPLACE = 0,// (00000001) replace structure/primitive
|
|
198
|
+
DELETE = 64,// (01000000) delete field
|
|
199
|
+
DELETE_AND_MOVE = 96,// () ArraySchema only
|
|
200
|
+
MOVE_AND_ADD = 160,// () ArraySchema only
|
|
201
|
+
DELETE_AND_ADD = 192,// (11000000) DELETE field, followed by an ADD
|
|
202
|
+
/**
|
|
203
|
+
* Collection operations
|
|
204
|
+
*/
|
|
205
|
+
CLEAR = 10,
|
|
206
|
+
/**
|
|
207
|
+
* ArraySchema operations
|
|
208
|
+
*/
|
|
209
|
+
REVERSE = 15,
|
|
210
|
+
MOVE = 32,
|
|
211
|
+
DELETE_BY_REFID = 33,// This operation is only used at ENCODING time. During DECODING, DELETE_BY_REFID is converted to DELETE
|
|
212
|
+
ADD_BY_REFID = 129
|
|
213
|
+
}
|
|
214
|
+
declare const $refId = "~refId";
|
|
215
|
+
declare const $track = "~track";
|
|
216
|
+
declare const $encoder = "~encoder";
|
|
217
|
+
declare const $decoder = "~decoder";
|
|
218
|
+
declare const $filter = "~filter";
|
|
219
|
+
declare const $getByIndex = "~getByIndex";
|
|
220
|
+
declare const $deleteByIndex = "~deleteByIndex";
|
|
221
|
+
declare const $changes = "~changes";
|
|
222
|
+
declare const $childType = "~childType";
|
|
223
|
+
declare const $onEncodeEnd = "~onEncodeEnd";
|
|
224
|
+
declare const $onDecodeEnd = "~onDecodeEnd";
|
|
225
|
+
declare const $descriptors = "~descriptors";
|
|
226
|
+
declare const $numFields = "~__numFields";
|
|
227
|
+
declare const $refTypeFieldIndexes = "~__refTypeFieldIndexes";
|
|
228
|
+
declare const $viewFieldIndexes = "~__viewFieldIndexes";
|
|
229
|
+
declare const $fieldIndexesByViewTag = "$__fieldIndexesByViewTag";
|
|
230
|
+
declare class StateView {
|
|
231
|
+
iterable: boolean;
|
|
232
|
+
/**
|
|
233
|
+
* Iterable list of items that are visible to this view
|
|
234
|
+
* (Available only if constructed with `iterable: true`)
|
|
235
|
+
*/
|
|
236
|
+
items: Ref[];
|
|
237
|
+
/**
|
|
238
|
+
* List of ChangeTree's that are visible to this view
|
|
239
|
+
*/
|
|
240
|
+
visible: WeakSet<ChangeTree>;
|
|
241
|
+
/**
|
|
242
|
+
* List of ChangeTree's that are invisible to this view
|
|
243
|
+
*/
|
|
244
|
+
invisible: WeakSet<ChangeTree>;
|
|
245
|
+
tags?: WeakMap<ChangeTree, Set<number>>;
|
|
246
|
+
/**
|
|
247
|
+
* Manual "ADD" operations for changes per ChangeTree, specific to this view.
|
|
248
|
+
* (This is used to force encoding a property, even if it was not changed)
|
|
249
|
+
*/
|
|
250
|
+
changes: Map<number, IndexedOperations>;
|
|
251
|
+
constructor(iterable?: boolean);
|
|
252
|
+
add(obj: Ref, tag?: number, checkIncludeParent?: boolean): boolean;
|
|
253
|
+
protected addParentOf(childChangeTree: ChangeTree, tag: number): void;
|
|
254
|
+
remove(obj: Ref, tag?: number): this;
|
|
255
|
+
remove(obj: Ref, tag?: number, _isClear?: boolean): this;
|
|
256
|
+
has(obj: Ref): boolean;
|
|
257
|
+
hasTag(ob: Ref, tag?: number): boolean;
|
|
258
|
+
clear(): void;
|
|
259
|
+
isChangeTreeVisible(changeTree: ChangeTree): boolean;
|
|
260
|
+
protected _recursiveDeleteVisibleChangeTree(changeTree: ChangeTree): void;
|
|
261
|
+
}
|
|
262
|
+
declare class TypeContext {
|
|
263
|
+
types: {
|
|
264
|
+
[id: number]: typeof Schema;
|
|
265
|
+
};
|
|
266
|
+
schemas: Map<typeof Schema, number>;
|
|
267
|
+
hasFilters: boolean;
|
|
268
|
+
parentFiltered: {
|
|
269
|
+
[typeIdAndParentIndex: string]: boolean;
|
|
270
|
+
};
|
|
271
|
+
/**
|
|
272
|
+
* For inheritance support
|
|
273
|
+
* Keeps track of which classes extends which. (parent -> children)
|
|
274
|
+
*/
|
|
275
|
+
static inheritedTypes: Map<typeof Schema, Set<typeof Schema>>;
|
|
276
|
+
static cachedContexts: Map<typeof Schema, TypeContext>;
|
|
277
|
+
static register(target: typeof Schema): void;
|
|
278
|
+
static cache(rootClass: typeof Schema): TypeContext;
|
|
279
|
+
constructor(rootClass?: typeof Schema);
|
|
280
|
+
has(schema: typeof Schema): boolean;
|
|
281
|
+
get(typeid: number): typeof Schema;
|
|
282
|
+
add(schema: typeof Schema, typeid?: number): boolean;
|
|
283
|
+
getTypeId(klass: typeof Schema): number;
|
|
284
|
+
private discoverTypes;
|
|
285
|
+
/**
|
|
286
|
+
* Keep track of which classes have filters applied.
|
|
287
|
+
* Format: `${typeid}-${parentTypeid}-${parentIndex}`
|
|
288
|
+
*/
|
|
289
|
+
private registerFilteredByParent;
|
|
290
|
+
debug(): string;
|
|
291
|
+
}
|
|
292
|
+
interface Iterator$1 {
|
|
293
|
+
offset: number;
|
|
294
|
+
}
|
|
295
|
+
declare class Root {
|
|
296
|
+
types: TypeContext;
|
|
297
|
+
protected nextUniqueId: number;
|
|
298
|
+
refCount: {
|
|
299
|
+
[id: number]: number;
|
|
300
|
+
};
|
|
301
|
+
changeTrees: {
|
|
302
|
+
[refId: number]: ChangeTree;
|
|
303
|
+
};
|
|
304
|
+
allChanges: ChangeTreeList;
|
|
305
|
+
allFilteredChanges: ChangeTreeList;
|
|
306
|
+
changes: ChangeTreeList;
|
|
307
|
+
filteredChanges: ChangeTreeList;
|
|
308
|
+
constructor(types: TypeContext);
|
|
309
|
+
getNextUniqueId(): number;
|
|
310
|
+
add(changeTree: ChangeTree): boolean;
|
|
311
|
+
remove(changeTree: ChangeTree): number;
|
|
312
|
+
recursivelyMoveNextToParent(changeTree: ChangeTree): void;
|
|
313
|
+
moveNextToParent(changeTree: ChangeTree): void;
|
|
314
|
+
moveNextToParentInChangeTreeList(changeSetName: ChangeSetName, changeTree: ChangeTree): void;
|
|
315
|
+
enqueueChangeTree(changeTree: ChangeTree, changeSet: "changes" | "filteredChanges" | "allFilteredChanges" | "allChanges", queueRootNode?: ChangeTreeNode): void;
|
|
316
|
+
protected addToChangeTreeList(list: ChangeTreeList, changeTree: ChangeTree): ChangeTreeNode;
|
|
317
|
+
protected updatePositionsAfterRemoval(list: ChangeTreeList, removedPosition: number): void;
|
|
318
|
+
protected updatePositionsAfterMove(list: ChangeTreeList, node: ChangeTreeNode, newPosition: number): void;
|
|
319
|
+
removeChangeFromChangeSet(changeSetName: ChangeSetName, changeTree: ChangeTree): boolean;
|
|
320
|
+
}
|
|
321
|
+
declare class Encoder<T extends Schema = any> {
|
|
322
|
+
static BUFFER_SIZE: number;
|
|
323
|
+
sharedBuffer: Uint8Array;
|
|
324
|
+
context: TypeContext;
|
|
325
|
+
state: T;
|
|
326
|
+
root: Root;
|
|
327
|
+
constructor(state: T);
|
|
328
|
+
protected setState(state: T): void;
|
|
329
|
+
encode(it?: Iterator$1, view?: StateView, buffer?: Uint8Array, changeSetName?: ChangeSetName, isEncodeAll?: boolean, initialOffset?: number): Uint8Array;
|
|
330
|
+
encodeAll(it?: Iterator$1, buffer?: Uint8Array): Uint8Array<ArrayBufferLike>;
|
|
331
|
+
encodeAllView(view: StateView, sharedOffset: number, it: Iterator$1, bytes?: Uint8Array): Uint8Array<ArrayBufferLike>;
|
|
332
|
+
encodeView(view: StateView, sharedOffset: number, it: Iterator$1, bytes?: Uint8Array): Uint8Array<ArrayBufferLike>;
|
|
333
|
+
discardChanges(): void;
|
|
334
|
+
tryEncodeTypeId(bytes: Uint8Array, baseType: typeof Schema, targetType: typeof Schema, it: Iterator$1): void;
|
|
335
|
+
get hasChanges(): boolean;
|
|
336
|
+
}
|
|
337
|
+
type MetadataField = {
|
|
338
|
+
type: DefinitionType;
|
|
339
|
+
name: string;
|
|
340
|
+
index: number;
|
|
341
|
+
tag?: number;
|
|
342
|
+
unreliable?: boolean;
|
|
343
|
+
deprecated?: boolean;
|
|
344
|
+
};
|
|
345
|
+
type Metadata = {
|
|
346
|
+
[$numFields]: number;
|
|
347
|
+
} & // number of fields
|
|
348
|
+
{
|
|
349
|
+
[$viewFieldIndexes]: number[];
|
|
350
|
+
} & // all field indexes with "view" tag
|
|
351
|
+
{
|
|
352
|
+
[$fieldIndexesByViewTag]: {
|
|
353
|
+
[tag: number]: number[];
|
|
354
|
+
};
|
|
355
|
+
} & // field indexes by "view" tag
|
|
356
|
+
{
|
|
357
|
+
[$refTypeFieldIndexes]: number[];
|
|
358
|
+
} & // all field indexes containing Ref types (Schema, ArraySchema, MapSchema, etc)
|
|
359
|
+
{
|
|
360
|
+
[field: number]: MetadataField;
|
|
361
|
+
} & // index => field name
|
|
362
|
+
{
|
|
363
|
+
[field: string]: number;
|
|
364
|
+
} & // field name => field metadata
|
|
365
|
+
{
|
|
366
|
+
[$descriptors]: {
|
|
367
|
+
[field: string]: PropertyDescriptor;
|
|
368
|
+
};
|
|
369
|
+
};
|
|
370
|
+
declare const Metadata: {
|
|
371
|
+
addField(metadata: any, index: number, name: string, type: DefinitionType, descriptor?: PropertyDescriptor): void;
|
|
372
|
+
setTag(metadata: Metadata, fieldName: string, tag: number): void;
|
|
373
|
+
setFields<T extends {
|
|
374
|
+
new (...args: any[]): InstanceType<T>;
|
|
375
|
+
} = any>(target: T, fields: {
|
|
376
|
+
[field in keyof InstanceType<T>]?: DefinitionType;
|
|
377
|
+
}): T;
|
|
378
|
+
isDeprecated(metadata: any, field: string): boolean;
|
|
379
|
+
init(klass: any): void;
|
|
380
|
+
initialize(constructor: any): Metadata;
|
|
381
|
+
isValidInstance(klass: any): boolean;
|
|
382
|
+
getFields(klass: any): any;
|
|
383
|
+
hasViewTagAtIndex(metadata: Metadata, index: number): boolean;
|
|
384
|
+
};
|
|
385
|
+
type EncodeOperation<T extends Ref = any> = (encoder: Encoder, bytes: Uint8Array, changeTree: ChangeTree<T>, index: number, operation: OPERATION, it: Iterator$1, isEncodeAll: boolean, hasView: boolean, metadata?: Metadata) => void;
|
|
386
|
+
type SchemaCallbacks = {
|
|
387
|
+
[field: string | number]: Function[];
|
|
388
|
+
};
|
|
389
|
+
declare class ReferenceTracker {
|
|
390
|
+
refs: Map<number, IRef>;
|
|
391
|
+
refCount: {
|
|
392
|
+
[refId: number]: number;
|
|
393
|
+
};
|
|
394
|
+
deletedRefs: Set<number>;
|
|
395
|
+
callbacks: {
|
|
396
|
+
[refId: number]: SchemaCallbacks;
|
|
397
|
+
};
|
|
398
|
+
protected nextUniqueId: number;
|
|
399
|
+
getNextUniqueId(): number;
|
|
400
|
+
addRef(refId: number, ref: IRef, incrementCount?: boolean): void;
|
|
401
|
+
removeRef(refId: number): void;
|
|
402
|
+
clearRefs(): void;
|
|
403
|
+
garbageCollectDeletedRefs(): void;
|
|
404
|
+
addCallback(refId: number, fieldOrOperation: string | number, callback: Function): () => void;
|
|
405
|
+
removeCallback(refId: number, field: string | number, callback: Function): void;
|
|
406
|
+
}
|
|
407
|
+
declare class Decoder<T extends IRef = any> {
|
|
408
|
+
context: TypeContext;
|
|
409
|
+
state: T;
|
|
410
|
+
root: ReferenceTracker;
|
|
411
|
+
currentRefId: number;
|
|
412
|
+
triggerChanges?: (allChanges: DataChange[]) => void;
|
|
413
|
+
constructor(root: T, context?: TypeContext);
|
|
414
|
+
protected setState(root: T): void;
|
|
415
|
+
decode(bytes: Uint8Array, it?: Iterator$1, ref?: IRef): DataChange<any, string>[];
|
|
416
|
+
skipCurrentStructure(bytes: Uint8Array, it: Iterator$1, totalBytes: number): void;
|
|
417
|
+
getInstanceType(bytes: Uint8Array, it: Iterator$1, defaultType: typeof Schema): typeof Schema;
|
|
418
|
+
createInstanceOfType(type: typeof Schema): Schema;
|
|
419
|
+
removeChildRefs(ref: Collection, allChanges: DataChange[]): void;
|
|
420
|
+
}
|
|
421
|
+
interface DataChange<T = any, F = string> {
|
|
422
|
+
ref: IRef;
|
|
423
|
+
refId: number;
|
|
424
|
+
op: OPERATION;
|
|
425
|
+
field: F;
|
|
426
|
+
dynamicIndex?: number | string;
|
|
427
|
+
value: T;
|
|
428
|
+
previousValue: T;
|
|
429
|
+
}
|
|
430
|
+
type DecodeOperation<T extends Schema = any> = (decoder: Decoder<T>, bytes: Uint8Array, it: Iterator$1, ref: IRef, allChanges: DataChange[]) => number | void;
|
|
431
|
+
type K = number;
|
|
432
|
+
declare class CollectionSchema<V = any> implements Collection<K, V>, IRef {
|
|
433
|
+
[$changes]: ChangeTree;
|
|
434
|
+
[$refId]?: number;
|
|
435
|
+
protected [$childType]: string | typeof Schema;
|
|
436
|
+
protected $items: Map<number, V>;
|
|
437
|
+
protected $indexes: Map<number, number>;
|
|
438
|
+
protected deletedItems: {
|
|
439
|
+
[field: string]: V;
|
|
440
|
+
};
|
|
441
|
+
protected $refId: number;
|
|
442
|
+
static [$encoder]: EncodeOperation<any>;
|
|
443
|
+
static [$decoder]: DecodeOperation<any>;
|
|
444
|
+
/**
|
|
445
|
+
* Determine if a property must be filtered.
|
|
446
|
+
* - If returns false, the property is NOT going to be encoded.
|
|
447
|
+
* - If returns true, the property is going to be encoded.
|
|
448
|
+
*
|
|
449
|
+
* Encoding with "filters" happens in two steps:
|
|
450
|
+
* - First, the encoder iterates over all "not owned" properties and encodes them.
|
|
451
|
+
* - Then, the encoder iterates over all "owned" properties per instance and encodes them.
|
|
452
|
+
*/
|
|
453
|
+
static [$filter](ref: CollectionSchema, index: number, view: StateView): boolean;
|
|
454
|
+
static is(type: any): boolean;
|
|
455
|
+
constructor(initialValues?: Array<V>);
|
|
456
|
+
add(value: V): number;
|
|
457
|
+
at(index: number): V | undefined;
|
|
458
|
+
entries(): MapIterator<[
|
|
459
|
+
number,
|
|
460
|
+
V
|
|
461
|
+
]>;
|
|
462
|
+
delete(item: V): boolean;
|
|
463
|
+
clear(): void;
|
|
464
|
+
has(value: V): boolean;
|
|
465
|
+
forEach(callbackfn: (value: V, key: K, collection: CollectionSchema<V>) => void): void;
|
|
466
|
+
values(): MapIterator<V>;
|
|
467
|
+
get size(): number;
|
|
468
|
+
/** Iterator */
|
|
469
|
+
[Symbol.iterator](): IterableIterator<V>;
|
|
470
|
+
protected setIndex(index: number, key: number): void;
|
|
471
|
+
protected getIndex(index: number): number;
|
|
472
|
+
[$getByIndex](index: number): any;
|
|
473
|
+
[$deleteByIndex](index: number): void;
|
|
474
|
+
protected [$onEncodeEnd](): void;
|
|
475
|
+
toArray(): V[];
|
|
476
|
+
toJSON(): V[];
|
|
477
|
+
clone(isDecoding?: boolean): CollectionSchema<V>;
|
|
478
|
+
}
|
|
479
|
+
declare class SetSchema<V = any> implements Collection<number, V>, IRef {
|
|
480
|
+
[$changes]: ChangeTree;
|
|
481
|
+
[$refId]?: number;
|
|
482
|
+
protected [$childType]: string | typeof Schema;
|
|
483
|
+
protected $items: Map<number, V>;
|
|
484
|
+
protected $indexes: Map<number, number>;
|
|
485
|
+
protected deletedItems: {
|
|
486
|
+
[field: string]: V;
|
|
487
|
+
};
|
|
488
|
+
protected $refId: number;
|
|
489
|
+
static [$encoder]: EncodeOperation<any>;
|
|
490
|
+
static [$decoder]: DecodeOperation<any>;
|
|
491
|
+
/**
|
|
492
|
+
* Determine if a property must be filtered.
|
|
493
|
+
* - If returns false, the property is NOT going to be encoded.
|
|
494
|
+
* - If returns true, the property is going to be encoded.
|
|
495
|
+
*
|
|
496
|
+
* Encoding with "filters" happens in two steps:
|
|
497
|
+
* - First, the encoder iterates over all "not owned" properties and encodes them.
|
|
498
|
+
* - Then, the encoder iterates over all "owned" properties per instance and encodes them.
|
|
499
|
+
*/
|
|
500
|
+
static [$filter](ref: SetSchema, index: number, view: StateView): boolean;
|
|
501
|
+
static is(type: any): boolean;
|
|
502
|
+
constructor(initialValues?: Array<V>);
|
|
503
|
+
add(value: V): number | false;
|
|
504
|
+
entries(): MapIterator<[
|
|
505
|
+
number,
|
|
506
|
+
V
|
|
507
|
+
]>;
|
|
508
|
+
delete(item: V): boolean;
|
|
509
|
+
clear(): void;
|
|
510
|
+
has(value: V): boolean;
|
|
511
|
+
forEach(callbackfn: (value: V, key: number, collection: SetSchema<V>) => void): void;
|
|
512
|
+
values(): MapIterator<V>;
|
|
513
|
+
get size(): number;
|
|
514
|
+
/** Iterator */
|
|
515
|
+
[Symbol.iterator](): IterableIterator<V>;
|
|
516
|
+
protected setIndex(index: number, key: number): void;
|
|
517
|
+
protected getIndex(index: number): number;
|
|
518
|
+
[$getByIndex](index: number): any;
|
|
519
|
+
[$deleteByIndex](index: number): void;
|
|
520
|
+
protected [$onEncodeEnd](): void;
|
|
521
|
+
toArray(): V[];
|
|
522
|
+
toJSON(): V[];
|
|
523
|
+
clone(isDecoding?: boolean): SetSchema<V>;
|
|
524
|
+
}
|
|
525
|
+
type Constructor<T = {}> = new (...args: any[]) => T;
|
|
526
|
+
type PrimitiveStringToType<T> = T extends "string" ? string : T extends "number" | "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32" | "int64" | "uint64" | "float32" | "float64" ? number : T extends "boolean" ? boolean : T;
|
|
527
|
+
interface Collection<K = any, V = any, IT = V> {
|
|
528
|
+
[Symbol.iterator](): IterableIterator<IT>;
|
|
529
|
+
forEach(callback: Function): void;
|
|
530
|
+
entries(): IterableIterator<[
|
|
531
|
+
K,
|
|
532
|
+
V
|
|
533
|
+
]>;
|
|
534
|
+
}
|
|
535
|
+
type InferValueType<T extends DefinitionType> = T extends "string" ? string : T extends "number" ? number : T extends "int8" ? number : T extends "uint8" ? number : T extends "int16" ? number : T extends "uint16" ? number : T extends "int32" ? number : T extends "uint32" ? number : T extends "int64" ? number : T extends "uint64" ? number : T extends "float32" ? number : T extends "float64" ? number : T extends "boolean" ? boolean : T extends {
|
|
536
|
+
type: infer ChildType extends PrimitiveType;
|
|
537
|
+
} ? InferValueType<ChildType> : T extends {
|
|
538
|
+
type: infer ChildType extends Constructor;
|
|
539
|
+
} ? InstanceType<ChildType> : T extends {
|
|
540
|
+
type: Array<infer ChildType>;
|
|
541
|
+
} ? (ChildType extends Record<string | number, string | number> ? ChildType[keyof ChildType][] : ChildType[]) : T extends {
|
|
542
|
+
type: {
|
|
543
|
+
map: infer ChildType;
|
|
544
|
+
};
|
|
545
|
+
} ? (ChildType extends Record<string | number, string | number> ? MapSchema<ChildType[keyof ChildType]> : MapSchema<ChildType>) : T extends {
|
|
546
|
+
type: {
|
|
547
|
+
set: infer ChildType;
|
|
548
|
+
};
|
|
549
|
+
} ? (ChildType extends Record<string | number, string | number> ? SetSchema<ChildType[keyof ChildType]> : SetSchema<ChildType>) : T extends {
|
|
550
|
+
type: {
|
|
551
|
+
collection: infer ChildType;
|
|
552
|
+
};
|
|
553
|
+
} ? (ChildType extends Record<string | number, string | number> ? CollectionSchema<ChildType[keyof ChildType]> : CollectionSchema<ChildType>) : T extends {
|
|
554
|
+
type: infer ChildType;
|
|
555
|
+
} ? (ChildType extends Record<string | number, string | number> ? ChildType[keyof ChildType] : ChildType) : T extends Array<infer ChildType extends Constructor> ? ArraySchema<InstanceType<ChildType>> : T extends Array<infer ChildType> ? (ChildType extends Record<string | number, string | number> ? ArraySchema<ChildType[keyof ChildType]> : ArraySchema<PrimitiveStringToType<ChildType>>) : T extends {
|
|
556
|
+
array: infer ChildType extends Constructor;
|
|
557
|
+
} ? ArraySchema<InstanceType<ChildType>> : T extends {
|
|
558
|
+
array: infer ChildType;
|
|
559
|
+
} ? (ChildType extends Record<string | number, string | number> ? ArraySchema<ChildType[keyof ChildType]> : ArraySchema<PrimitiveStringToType<ChildType>>) : T extends {
|
|
560
|
+
map: infer ChildType extends Constructor;
|
|
561
|
+
} ? MapSchema<InstanceType<ChildType>> : T extends {
|
|
562
|
+
map: infer ChildType;
|
|
563
|
+
} ? (ChildType extends Record<string | number, string | number> ? MapSchema<ChildType[keyof ChildType]> : MapSchema<PrimitiveStringToType<ChildType>>) : T extends {
|
|
564
|
+
set: infer ChildType extends Constructor;
|
|
565
|
+
} ? SetSchema<InstanceType<ChildType>> : T extends {
|
|
566
|
+
set: infer ChildType extends RawPrimitiveType;
|
|
567
|
+
} ? SetSchema<InferValueType<ChildType>> : T extends {
|
|
568
|
+
set: infer ChildType;
|
|
569
|
+
} ? (ChildType extends Record<string | number, string | number> ? SetSchema<ChildType[keyof ChildType]> : SetSchema<ChildType>) : T extends {
|
|
570
|
+
collection: infer ChildType extends Constructor;
|
|
571
|
+
} ? CollectionSchema<InstanceType<ChildType>> : T extends {
|
|
572
|
+
collection: infer ChildType extends RawPrimitiveType;
|
|
573
|
+
} ? CollectionSchema<InferValueType<ChildType>> : T extends {
|
|
574
|
+
collection: infer ChildType;
|
|
575
|
+
} ? (ChildType extends Record<string | number, string | number> ? CollectionSchema<ChildType[keyof ChildType]> : CollectionSchema<ChildType>) : T extends Constructor ? InstanceType<T> : T extends Record<string | number, string | number> ? T[keyof T] : T extends PrimitiveType ? T : never;
|
|
576
|
+
type NonFunctionProps<T> = Omit<T, {
|
|
577
|
+
[K in keyof T]: T[K] extends Function ? K : never;
|
|
578
|
+
}[keyof T]>;
|
|
579
|
+
type NonFunctionPropNames<T> = {
|
|
580
|
+
[K in keyof T]: T[K] extends Function ? never : K;
|
|
581
|
+
}[keyof T];
|
|
582
|
+
type NonFunctionNonPrimitivePropNames<T> = {
|
|
583
|
+
[K in keyof T]: T[K] extends Function ? never : T[K] extends number | string | boolean ? never : K;
|
|
584
|
+
}[keyof T];
|
|
585
|
+
type ToJSONValue<U> = U extends Schema ? ToJSON<U> : PrimitiveStringToType<U>;
|
|
586
|
+
type ToJSON<T> = NonFunctionProps<{
|
|
587
|
+
[K in keyof T]: T[K] extends MapSchema<infer U> ? Record<string, ToJSONValue<U>> : T[K] extends Map<string, infer U> ? Record<string, ToJSONValue<U>> : T[K] extends ArraySchema<infer U> ? ToJSONValue<U>[] : T[K] extends SetSchema<infer U> ? ToJSONValue<U>[] : T[K] extends CollectionSchema<infer U> ? ToJSONValue<U>[] : T[K] extends Schema ? ToJSON<T[K]> : T[K];
|
|
588
|
+
}>;
|
|
589
|
+
type AssignableProps<T> = {
|
|
590
|
+
[K in NonFunctionPropNames<T>]?: T[K] extends MapSchema<infer U> ? MapSchema<U> | Record<string, U extends Schema ? (U | AssignableProps<U>) : U> : T[K] extends ArraySchema<infer U> ? ArraySchema<U> | (U extends Schema ? (U | AssignableProps<U>)[] : U[]) : T[K] extends SetSchema<infer U> ? SetSchema<U> | Set<U> | (U extends Schema ? (U | AssignableProps<U>)[] : U[]) : T[K] extends CollectionSchema<infer U> ? CollectionSchema<U> | (U extends Schema ? (U | AssignableProps<U>)[] : U[]) : T[K] extends Schema ? T[K] | AssignableProps<T[K]> : T[K];
|
|
591
|
+
};
|
|
592
|
+
declare class MapSchema<V = any, K extends string = string> implements Map<K, V>, Collection<K, V, [
|
|
593
|
+
K,
|
|
594
|
+
V
|
|
595
|
+
]>, IRef {
|
|
596
|
+
[$changes]: ChangeTree;
|
|
597
|
+
[$refId]?: number;
|
|
598
|
+
protected childType: new () => V;
|
|
599
|
+
protected [$childType]: string | typeof Schema;
|
|
600
|
+
protected $items: Map<K, V>;
|
|
601
|
+
protected $indexes: Map<number, K>;
|
|
602
|
+
protected deletedItems: {
|
|
603
|
+
[index: string]: V;
|
|
604
|
+
};
|
|
605
|
+
static [$encoder]: EncodeOperation<any>;
|
|
606
|
+
static [$decoder]: DecodeOperation<any>;
|
|
607
|
+
/**
|
|
608
|
+
* Determine if a property must be filtered.
|
|
609
|
+
* - If returns false, the property is NOT going to be encoded.
|
|
610
|
+
* - If returns true, the property is going to be encoded.
|
|
611
|
+
*
|
|
612
|
+
* Encoding with "filters" happens in two steps:
|
|
613
|
+
* - First, the encoder iterates over all "not owned" properties and encodes them.
|
|
614
|
+
* - Then, the encoder iterates over all "owned" properties per instance and encodes them.
|
|
615
|
+
*/
|
|
616
|
+
static [$filter](ref: MapSchema, index: number, view: StateView): boolean;
|
|
617
|
+
static is(type: any): boolean;
|
|
618
|
+
constructor(initialValues?: Map<K, V> | Record<K, V>);
|
|
619
|
+
/** Iterator */
|
|
620
|
+
[Symbol.iterator](): IterableIterator<[
|
|
621
|
+
K,
|
|
622
|
+
V
|
|
623
|
+
]>;
|
|
624
|
+
get [Symbol.toStringTag](): string;
|
|
625
|
+
static get [Symbol.species](): typeof MapSchema;
|
|
626
|
+
set(key: K, value: V): this;
|
|
627
|
+
get(key: K): V | undefined;
|
|
628
|
+
delete(key: K): boolean;
|
|
629
|
+
clear(): void;
|
|
630
|
+
has(key: K): boolean;
|
|
631
|
+
forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void): void;
|
|
632
|
+
entries(): MapIterator<[
|
|
633
|
+
K,
|
|
634
|
+
V
|
|
635
|
+
]>;
|
|
636
|
+
keys(): MapIterator<K>;
|
|
637
|
+
values(): MapIterator<V>;
|
|
638
|
+
get size(): number;
|
|
639
|
+
protected setIndex(index: number, key: K): void;
|
|
640
|
+
protected getIndex(index: number): K;
|
|
641
|
+
[$getByIndex](index: number): V | undefined;
|
|
642
|
+
[$deleteByIndex](index: number): void;
|
|
643
|
+
protected [$onEncodeEnd](): void;
|
|
644
|
+
toJSON(): any;
|
|
645
|
+
clone(isDecoding?: boolean): MapSchema<V>;
|
|
646
|
+
}
|
|
647
|
+
interface IRef {
|
|
648
|
+
[$refId]?: number;
|
|
649
|
+
[$getByIndex]?: (index: number, isEncodeAll?: boolean) => any;
|
|
650
|
+
[$deleteByIndex]?: (index: number) => void;
|
|
651
|
+
}
|
|
652
|
+
type Ref = Schema | ArraySchema | MapSchema | CollectionSchema | SetSchema;
|
|
653
|
+
type ChangeSetName = "changes" | "allChanges" | "filteredChanges" | "allFilteredChanges";
|
|
654
|
+
interface IndexedOperations {
|
|
655
|
+
[index: number]: OPERATION;
|
|
656
|
+
}
|
|
657
|
+
interface ChangeTreeNode {
|
|
658
|
+
changeTree: ChangeTree;
|
|
659
|
+
next?: ChangeTreeNode;
|
|
660
|
+
prev?: ChangeTreeNode;
|
|
661
|
+
position: number;
|
|
662
|
+
}
|
|
663
|
+
interface ChangeTreeList {
|
|
664
|
+
next?: ChangeTreeNode;
|
|
665
|
+
tail?: ChangeTreeNode;
|
|
666
|
+
}
|
|
667
|
+
interface ChangeSet {
|
|
668
|
+
indexes: {
|
|
669
|
+
[index: number]: number;
|
|
670
|
+
};
|
|
671
|
+
operations: number[];
|
|
672
|
+
queueRootNode?: ChangeTreeNode;
|
|
673
|
+
}
|
|
674
|
+
interface ParentChain {
|
|
675
|
+
ref: Ref;
|
|
676
|
+
index: number;
|
|
677
|
+
next?: ParentChain;
|
|
678
|
+
}
|
|
679
|
+
declare class ChangeTree<T extends Ref = any> {
|
|
680
|
+
ref: T;
|
|
681
|
+
metadata: Metadata;
|
|
682
|
+
root?: Root;
|
|
683
|
+
parentChain?: ParentChain;
|
|
684
|
+
/**
|
|
685
|
+
* Whether this structure is parent of a filtered structure.
|
|
686
|
+
*/
|
|
687
|
+
isFiltered: boolean;
|
|
688
|
+
isVisibilitySharedWithParent?: boolean;
|
|
689
|
+
indexedOperations: IndexedOperations;
|
|
690
|
+
changes: ChangeSet;
|
|
691
|
+
allChanges: ChangeSet;
|
|
692
|
+
filteredChanges: ChangeSet;
|
|
693
|
+
allFilteredChanges: ChangeSet;
|
|
694
|
+
indexes: {
|
|
695
|
+
[index: string]: any;
|
|
696
|
+
};
|
|
697
|
+
/**
|
|
698
|
+
* Is this a new instance? Used on ArraySchema to determine OPERATION.MOVE_AND_ADD operation.
|
|
699
|
+
*/
|
|
700
|
+
isNew: boolean;
|
|
701
|
+
constructor(ref: T);
|
|
702
|
+
setRoot(root: Root): void;
|
|
703
|
+
setParent(parent: Ref, root?: Root, parentIndex?: number): void;
|
|
704
|
+
forEachChild(callback: (change: ChangeTree, at: any) => void): void;
|
|
705
|
+
operation(op: OPERATION): void;
|
|
706
|
+
change(index: number, operation?: OPERATION): void;
|
|
707
|
+
shiftChangeIndexes(shiftIndex: number): void;
|
|
708
|
+
shiftAllChangeIndexes(shiftIndex: number, startIndex?: number): void;
|
|
709
|
+
private _shiftAllChangeIndexes;
|
|
710
|
+
indexedOperation(index: number, operation: OPERATION, allChangesIndex?: number): void;
|
|
711
|
+
getType(index?: number): any;
|
|
712
|
+
getChange(index: number): OPERATION;
|
|
713
|
+
getValue(index: number, isEncodeAll?: boolean): any;
|
|
714
|
+
delete(index: number, operation?: OPERATION, allChangesIndex?: number): any;
|
|
715
|
+
endEncode(changeSetName: ChangeSetName): void;
|
|
716
|
+
discard(discardAll?: boolean): void;
|
|
717
|
+
/**
|
|
718
|
+
* Recursively discard all changes from this, and child structures.
|
|
719
|
+
* (Used in tests only)
|
|
720
|
+
*/
|
|
721
|
+
discardAll(): void;
|
|
722
|
+
get changed(): boolean;
|
|
723
|
+
protected checkIsFiltered(parent: Ref, parentIndex: number, isNewChangeTree: boolean): void;
|
|
724
|
+
protected _checkFilteredByParent(parent: Ref, parentIndex: number): void;
|
|
725
|
+
/**
|
|
726
|
+
* Get the immediate parent
|
|
727
|
+
*/
|
|
728
|
+
get parent(): Ref | undefined;
|
|
729
|
+
/**
|
|
730
|
+
* Get the immediate parent index
|
|
731
|
+
*/
|
|
732
|
+
get parentIndex(): number | undefined;
|
|
733
|
+
/**
|
|
734
|
+
* Add a parent to the chain
|
|
735
|
+
*/
|
|
736
|
+
addParent(parent: Ref, index: number): void;
|
|
737
|
+
/**
|
|
738
|
+
* Remove a parent from the chain
|
|
739
|
+
* @param parent - The parent to remove
|
|
740
|
+
* @returns true if parent was removed
|
|
741
|
+
*/
|
|
742
|
+
removeParent(parent?: Ref): boolean;
|
|
743
|
+
/**
|
|
744
|
+
* Find a specific parent in the chain
|
|
745
|
+
*/
|
|
746
|
+
findParent(predicate: (parent: Ref, index: number) => boolean): ParentChain | undefined;
|
|
747
|
+
/**
|
|
748
|
+
* Check if this ChangeTree has a specific parent
|
|
749
|
+
*/
|
|
750
|
+
hasParent(predicate: (parent: Ref, index: number) => boolean): boolean;
|
|
751
|
+
/**
|
|
752
|
+
* Get all parents as an array (for debugging/testing)
|
|
753
|
+
*/
|
|
754
|
+
getAllParents(): Array<{
|
|
755
|
+
ref: Ref;
|
|
756
|
+
index: number;
|
|
757
|
+
}>;
|
|
758
|
+
}
|
|
759
|
+
declare class ArraySchema<V = any> implements Array<V>, Collection<number, V>, IRef {
|
|
760
|
+
[n: number]: V;
|
|
761
|
+
[$changes]: ChangeTree;
|
|
762
|
+
[$refId]?: number;
|
|
763
|
+
protected [$childType]: string | typeof Schema;
|
|
764
|
+
protected items: V[];
|
|
765
|
+
protected tmpItems: V[];
|
|
766
|
+
protected deletedIndexes: {
|
|
767
|
+
[index: number]: boolean;
|
|
768
|
+
};
|
|
769
|
+
protected isMovingItems: boolean;
|
|
770
|
+
static [$encoder]: EncodeOperation<any>;
|
|
771
|
+
static [$decoder]: DecodeOperation<any>;
|
|
772
|
+
/**
|
|
773
|
+
* Determine if a property must be filtered.
|
|
774
|
+
* - If returns false, the property is NOT going to be encoded.
|
|
775
|
+
* - If returns true, the property is going to be encoded.
|
|
776
|
+
*
|
|
777
|
+
* Encoding with "filters" happens in two steps:
|
|
778
|
+
* - First, the encoder iterates over all "not owned" properties and encodes them.
|
|
779
|
+
* - Then, the encoder iterates over all "owned" properties per instance and encodes them.
|
|
780
|
+
*/
|
|
781
|
+
static [$filter](ref: ArraySchema, index: number, view: StateView): boolean;
|
|
782
|
+
static is(type: any): boolean;
|
|
783
|
+
static from<T>(iterable: Iterable<T> | ArrayLike<T>): ArraySchema<T>;
|
|
784
|
+
constructor(...items: V[]);
|
|
785
|
+
set length(newLength: number);
|
|
786
|
+
get length(): number;
|
|
787
|
+
push(...values: V[]): number;
|
|
788
|
+
/**
|
|
789
|
+
* Removes the last element from an array and returns it.
|
|
790
|
+
*/
|
|
791
|
+
pop(): V | undefined;
|
|
792
|
+
at(index: number): V;
|
|
793
|
+
protected $changeAt(index: number, value: V): void;
|
|
794
|
+
protected $deleteAt(index: number, operation?: OPERATION): void;
|
|
795
|
+
protected $setAt(index: number, value: V, operation: OPERATION): void;
|
|
796
|
+
clear(): void;
|
|
797
|
+
/**
|
|
798
|
+
* Combines two or more arrays.
|
|
799
|
+
* @param items Additional items to add to the end of array1.
|
|
800
|
+
*/
|
|
801
|
+
concat(...items: (V | ConcatArray<V>)[]): ArraySchema<V>;
|
|
802
|
+
/**
|
|
803
|
+
* Adds all the elements of an array separated by the specified separator string.
|
|
804
|
+
* @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma.
|
|
805
|
+
*/
|
|
806
|
+
join(separator?: string): string;
|
|
807
|
+
/**
|
|
808
|
+
* Reverses the elements in an Array.
|
|
809
|
+
*/
|
|
810
|
+
reverse(): ArraySchema<V>;
|
|
811
|
+
/**
|
|
812
|
+
* Removes the first element from an array and returns it.
|
|
813
|
+
*/
|
|
814
|
+
shift(): V | undefined;
|
|
815
|
+
/**
|
|
816
|
+
* Returns a section of an array.
|
|
817
|
+
* @param start The beginning of the specified portion of the array.
|
|
818
|
+
* @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.
|
|
819
|
+
*/
|
|
820
|
+
slice(start?: number, end?: number): V[];
|
|
821
|
+
/**
|
|
822
|
+
* Sorts an array.
|
|
823
|
+
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
|
824
|
+
* a negative value if first argument is less than second argument, zero if they're equal and a positive
|
|
825
|
+
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
|
|
826
|
+
* ```ts
|
|
827
|
+
* [11,2,22,1].sort((a, b) => a - b)
|
|
828
|
+
* ```
|
|
829
|
+
*/
|
|
830
|
+
sort(compareFn?: (a: V, b: V) => number): this;
|
|
831
|
+
/**
|
|
832
|
+
* Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
|
|
833
|
+
* @param start The zero-based location in the array from which to start removing elements.
|
|
834
|
+
* @param deleteCount The number of elements to remove.
|
|
835
|
+
* @param insertItems Elements to insert into the array in place of the deleted elements.
|
|
836
|
+
*/
|
|
837
|
+
splice(start: number, deleteCount?: number, ...insertItems: V[]): V[];
|
|
838
|
+
/**
|
|
839
|
+
* Inserts new elements at the start of an array.
|
|
840
|
+
* @param items Elements to insert at the start of the Array.
|
|
841
|
+
*/
|
|
842
|
+
unshift(...items: V[]): number;
|
|
843
|
+
/**
|
|
844
|
+
* Returns the index of the first occurrence of a value in an array.
|
|
845
|
+
* @param searchElement The value to locate in the array.
|
|
846
|
+
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
|
|
847
|
+
*/
|
|
848
|
+
indexOf(searchElement: V, fromIndex?: number): number;
|
|
849
|
+
/**
|
|
850
|
+
* Returns the index of the last occurrence of a specified value in an array.
|
|
851
|
+
* @param searchElement The value to locate in the array.
|
|
852
|
+
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array.
|
|
853
|
+
*/
|
|
854
|
+
lastIndexOf(searchElement: V, fromIndex?: number): number;
|
|
855
|
+
/**
|
|
856
|
+
* Determines whether all the members of an array satisfy the specified test.
|
|
857
|
+
* @param callbackfn A function that accepts up to three arguments. The every method calls
|
|
858
|
+
* the callbackfn function for each element in the array until the callbackfn returns a value
|
|
859
|
+
* which is coercible to the Boolean value false, or until the end of the array.
|
|
860
|
+
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
|
861
|
+
* If thisArg is omitted, undefined is used as the this value.
|
|
862
|
+
*/
|
|
863
|
+
every<S extends V>(predicate: (value: V, index: number, array: V[]) => value is S, thisArg?: any): this is S[];
|
|
864
|
+
every(callbackfn: (value: V, index: number, array: V[]) => unknown, thisArg?: any): boolean;
|
|
865
|
+
/**
|
|
866
|
+
* Determines whether the specified callback function returns true for any element of an array.
|
|
867
|
+
* @param callbackfn A function that accepts up to three arguments. The some method calls
|
|
868
|
+
* the callbackfn function for each element in the array until the callbackfn returns a value
|
|
869
|
+
* which is coercible to the Boolean value true, or until the end of the array.
|
|
870
|
+
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
|
871
|
+
* If thisArg is omitted, undefined is used as the this value.
|
|
872
|
+
*/
|
|
873
|
+
some(callbackfn: (value: V, index: number, array: V[]) => unknown, thisArg?: any): boolean;
|
|
874
|
+
/**
|
|
875
|
+
* Performs the specified action for each element in an array.
|
|
876
|
+
* @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
|
|
877
|
+
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
|
|
878
|
+
*/
|
|
879
|
+
forEach(callbackfn: (value: V, index: number, array: V[]) => void, thisArg?: any): void;
|
|
880
|
+
/**
|
|
881
|
+
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
|
|
882
|
+
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
|
|
883
|
+
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
|
|
884
|
+
*/
|
|
885
|
+
map<U>(callbackfn: (value: V, index: number, array: V[]) => U, thisArg?: any): U[];
|
|
886
|
+
/**
|
|
887
|
+
* Returns the elements of an array that meet the condition specified in a callback function.
|
|
888
|
+
* @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.
|
|
889
|
+
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
|
|
890
|
+
*/
|
|
891
|
+
filter(callbackfn: (value: V, index: number, array: V[]) => unknown, thisArg?: any): V[];
|
|
892
|
+
/**
|
|
893
|
+
* Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
|
|
894
|
+
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
|
|
895
|
+
* @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
|
|
896
|
+
*/
|
|
897
|
+
reduce<U = V>(callbackfn: (previousValue: U, currentValue: V, currentIndex: number, array: V[]) => U, initialValue?: U): U;
|
|
898
|
+
/**
|
|
899
|
+
* Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
|
|
900
|
+
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
|
|
901
|
+
* @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
|
|
902
|
+
*/
|
|
903
|
+
reduceRight<U = V>(callbackfn: (previousValue: U, currentValue: V, currentIndex: number, array: V[]) => U, initialValue?: U): U;
|
|
904
|
+
/**
|
|
905
|
+
* Returns the value of the first element in the array where predicate is true, and undefined
|
|
906
|
+
* otherwise.
|
|
907
|
+
* @param predicate find calls predicate once for each element of the array, in ascending
|
|
908
|
+
* order, until it finds one where predicate returns true. If such an element is found, find
|
|
909
|
+
* immediately returns that element value. Otherwise, find returns undefined.
|
|
910
|
+
* @param thisArg If provided, it will be used as the this value for each invocation of
|
|
911
|
+
* predicate. If it is not provided, undefined is used instead.
|
|
912
|
+
*/
|
|
913
|
+
find(predicate: (value: V, index: number, obj: V[]) => boolean, thisArg?: any): V | undefined;
|
|
914
|
+
/**
|
|
915
|
+
* Returns the index of the first element in the array where predicate is true, and -1
|
|
916
|
+
* otherwise.
|
|
917
|
+
* @param predicate find calls predicate once for each element of the array, in ascending
|
|
918
|
+
* order, until it finds one where predicate returns true. If such an element is found,
|
|
919
|
+
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
|
|
920
|
+
* @param thisArg If provided, it will be used as the this value for each invocation of
|
|
921
|
+
* predicate. If it is not provided, undefined is used instead.
|
|
922
|
+
*/
|
|
923
|
+
findIndex(predicate: (value: V, index: number, obj: V[]) => unknown, thisArg?: any): number;
|
|
924
|
+
/**
|
|
925
|
+
* Returns the this object after filling the section identified by start and end with value
|
|
926
|
+
* @param value value to fill array section with
|
|
927
|
+
* @param start index to start filling the array at. If start is negative, it is treated as
|
|
928
|
+
* length+start where length is the length of the array.
|
|
929
|
+
* @param end index to stop filling the array at. If end is negative, it is treated as
|
|
930
|
+
* length+end.
|
|
931
|
+
*/
|
|
932
|
+
fill(value: V, start?: number, end?: number): this;
|
|
933
|
+
/**
|
|
934
|
+
* Returns the this object after copying a section of the array identified by start and end
|
|
935
|
+
* to the same array starting at position target
|
|
936
|
+
* @param target If target is negative, it is treated as length+target where length is the
|
|
937
|
+
* length of the array.
|
|
938
|
+
* @param start If start is negative, it is treated as length+start. If end is negative, it
|
|
939
|
+
* is treated as length+end.
|
|
940
|
+
* @param end If not specified, length of the this object is used as its default value.
|
|
941
|
+
*/
|
|
942
|
+
copyWithin(target: number, start: number, end?: number): this;
|
|
943
|
+
/**
|
|
944
|
+
* Returns a string representation of an array.
|
|
945
|
+
*/
|
|
946
|
+
toString(): string;
|
|
947
|
+
/**
|
|
948
|
+
* Returns a string representation of an array. The elements are converted to string using their toLocalString methods.
|
|
949
|
+
*/
|
|
950
|
+
toLocaleString(): string;
|
|
951
|
+
/** Iterator */
|
|
952
|
+
[Symbol.iterator](): ArrayIterator<V>;
|
|
953
|
+
static get [Symbol.species](): typeof ArraySchema;
|
|
954
|
+
[Symbol.unscopables]: any;
|
|
955
|
+
/**
|
|
956
|
+
* Returns an iterable of key, value pairs for every entry in the array
|
|
957
|
+
*/
|
|
958
|
+
entries(): ArrayIterator<[
|
|
959
|
+
number,
|
|
960
|
+
V
|
|
961
|
+
]>;
|
|
962
|
+
/**
|
|
963
|
+
* Returns an iterable of keys in the array
|
|
964
|
+
*/
|
|
965
|
+
keys(): ArrayIterator<number>;
|
|
966
|
+
/**
|
|
967
|
+
* Returns an iterable of values in the array
|
|
968
|
+
*/
|
|
969
|
+
values(): ArrayIterator<V>;
|
|
970
|
+
/**
|
|
971
|
+
* Determines whether an array includes a certain element, returning true or false as appropriate.
|
|
972
|
+
* @param searchElement The element to search for.
|
|
973
|
+
* @param fromIndex The position in this array at which to begin searching for searchElement.
|
|
974
|
+
*/
|
|
975
|
+
includes(searchElement: V, fromIndex?: number): boolean;
|
|
976
|
+
/**
|
|
977
|
+
* Calls a defined callback function on each element of an array. Then, flattens the result into
|
|
978
|
+
* a new array.
|
|
979
|
+
* This is identical to a map followed by flat with depth 1.
|
|
980
|
+
*
|
|
981
|
+
* @param callback A function that accepts up to three arguments. The flatMap method calls the
|
|
982
|
+
* callback function one time for each element in the array.
|
|
983
|
+
* @param thisArg An object to which the this keyword can refer in the callback function. If
|
|
984
|
+
* thisArg is omitted, undefined is used as the this value.
|
|
985
|
+
*/
|
|
986
|
+
flatMap<U, This = undefined>(callback: (this: This, value: V, index: number, array: V[]) => U | ReadonlyArray<U>, thisArg?: This): U[];
|
|
987
|
+
/**
|
|
988
|
+
* Returns a new array with all sub-array elements concatenated into it recursively up to the
|
|
989
|
+
* specified depth.
|
|
990
|
+
*
|
|
991
|
+
* @param depth The maximum recursion depth
|
|
992
|
+
*/
|
|
993
|
+
flat<A, D extends number = 1>(this: A, depth?: D): any;
|
|
994
|
+
findLast(): any;
|
|
995
|
+
findLastIndex(...args: any[]): any;
|
|
996
|
+
with(index: number, value: V): ArraySchema<V>;
|
|
997
|
+
toReversed(): V[];
|
|
998
|
+
toSorted(compareFn?: (a: V, b: V) => number): V[];
|
|
999
|
+
toSpliced(start: number, deleteCount: number, ...items: V[]): V[];
|
|
1000
|
+
toSpliced(start: number, deleteCount?: number): V[];
|
|
1001
|
+
shuffle(): this;
|
|
1002
|
+
/**
|
|
1003
|
+
* Allows to move items around in the array.
|
|
1004
|
+
*
|
|
1005
|
+
* Example:
|
|
1006
|
+
* state.cards.move((cards) => {
|
|
1007
|
+
* [cards[4], cards[3]] = [cards[3], cards[4]];
|
|
1008
|
+
* [cards[3], cards[2]] = [cards[2], cards[3]];
|
|
1009
|
+
* [cards[2], cards[0]] = [cards[0], cards[2]];
|
|
1010
|
+
* [cards[1], cards[1]] = [cards[1], cards[1]];
|
|
1011
|
+
* [cards[0], cards[0]] = [cards[0], cards[0]];
|
|
1012
|
+
* })
|
|
1013
|
+
*
|
|
1014
|
+
* @param cb
|
|
1015
|
+
* @returns
|
|
1016
|
+
*/
|
|
1017
|
+
move(cb: (arr: this) => void): this;
|
|
1018
|
+
[$getByIndex](index: number, isEncodeAll?: boolean): any;
|
|
1019
|
+
[$deleteByIndex](index: number): void;
|
|
1020
|
+
protected [$onEncodeEnd](): void;
|
|
1021
|
+
protected [$onDecodeEnd](): void;
|
|
1022
|
+
toArray(): V[];
|
|
1023
|
+
toJSON(): any[];
|
|
1024
|
+
clone(isDecoding?: boolean): ArraySchema<V>;
|
|
1025
|
+
}
|
|
1026
|
+
type RawPrimitiveType = "string" | "number" | "boolean" | "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32" | "int64" | "uint64" | "float32" | "float64" | "bigint64" | "biguint64";
|
|
1027
|
+
type PrimitiveType = RawPrimitiveType | typeof Schema | object;
|
|
1028
|
+
type DefinitionType<T extends PrimitiveType = PrimitiveType> = T | T[] | {
|
|
1029
|
+
type: T;
|
|
1030
|
+
default?: InferValueType<T>;
|
|
1031
|
+
view?: boolean | number;
|
|
1032
|
+
sync?: boolean;
|
|
1033
|
+
} | {
|
|
1034
|
+
array: T;
|
|
1035
|
+
default?: ArraySchema<InferValueType<T>>;
|
|
1036
|
+
view?: boolean | number;
|
|
1037
|
+
sync?: boolean;
|
|
1038
|
+
} | {
|
|
1039
|
+
map: T;
|
|
1040
|
+
default?: MapSchema<InferValueType<T>>;
|
|
1041
|
+
view?: boolean | number;
|
|
1042
|
+
sync?: boolean;
|
|
1043
|
+
} | {
|
|
1044
|
+
collection: T;
|
|
1045
|
+
default?: CollectionSchema<InferValueType<T>>;
|
|
1046
|
+
view?: boolean | number;
|
|
1047
|
+
sync?: boolean;
|
|
1048
|
+
} | {
|
|
1049
|
+
set: T;
|
|
1050
|
+
default?: SetSchema<InferValueType<T>>;
|
|
1051
|
+
view?: boolean | number;
|
|
1052
|
+
sync?: boolean;
|
|
1053
|
+
};
|
|
1054
|
+
declare class Schema<C = any> implements IRef {
|
|
1055
|
+
static [Symbol.metadata]: Metadata;
|
|
1056
|
+
static [$encoder]: EncodeOperation<any>;
|
|
1057
|
+
static [$decoder]: DecodeOperation<any>;
|
|
1058
|
+
[$refId]?: number;
|
|
1059
|
+
/**
|
|
1060
|
+
* Assign the property descriptors required to track changes on this instance.
|
|
1061
|
+
* @param instance
|
|
1062
|
+
*/
|
|
1063
|
+
static initialize(instance: any): void;
|
|
1064
|
+
static is(type: DefinitionType): boolean;
|
|
1065
|
+
/**
|
|
1066
|
+
* Check if a value is an instance of Schema.
|
|
1067
|
+
* This method uses duck-typing to avoid issues with multiple @colyseus/schema versions.
|
|
1068
|
+
* @param obj Value to check
|
|
1069
|
+
* @returns true if the value is a Schema instance
|
|
1070
|
+
*/
|
|
1071
|
+
static isSchema(obj: any): obj is Schema;
|
|
1072
|
+
/**
|
|
1073
|
+
* Track property changes
|
|
1074
|
+
*/
|
|
1075
|
+
static [$track](changeTree: ChangeTree, index: number, operation?: OPERATION): void;
|
|
1076
|
+
/**
|
|
1077
|
+
* Determine if a property must be filtered.
|
|
1078
|
+
* - If returns false, the property is NOT going to be encoded.
|
|
1079
|
+
* - If returns true, the property is going to be encoded.
|
|
1080
|
+
*
|
|
1081
|
+
* Encoding with "filters" happens in two steps:
|
|
1082
|
+
* - First, the encoder iterates over all "not owned" properties and encodes them.
|
|
1083
|
+
* - Then, the encoder iterates over all "owned" properties per instance and encodes them.
|
|
1084
|
+
*/
|
|
1085
|
+
static [$filter](ref: Schema, index: number, view: StateView): boolean;
|
|
1086
|
+
constructor(arg?: C);
|
|
1087
|
+
/**
|
|
1088
|
+
* Assign properties to the instance.
|
|
1089
|
+
* @param props Properties to assign to the instance
|
|
1090
|
+
* @returns
|
|
1091
|
+
*/
|
|
1092
|
+
assign<T extends Partial<this>>(props: AssignableProps<T>): this;
|
|
1093
|
+
/**
|
|
1094
|
+
* Restore the instance from JSON data.
|
|
1095
|
+
* @param jsonData JSON data to restore the instance from
|
|
1096
|
+
* @returns
|
|
1097
|
+
*/
|
|
1098
|
+
restore(jsonData: ToJSON<this>): this;
|
|
1099
|
+
/**
|
|
1100
|
+
* (Server-side): Flag a property to be encoded for the next patch.
|
|
1101
|
+
* @param instance Schema instance
|
|
1102
|
+
* @param property string representing the property name, or number representing the index of the property.
|
|
1103
|
+
* @param operation OPERATION to perform (detected automatically)
|
|
1104
|
+
*/
|
|
1105
|
+
setDirty<K extends NonFunctionPropNames<this>>(property: K | number, operation?: OPERATION): void;
|
|
1106
|
+
clone(): this;
|
|
1107
|
+
toJSON(this: any): ToJSON<this>;
|
|
1108
|
+
/**
|
|
1109
|
+
* Used in tests only
|
|
1110
|
+
* @internal
|
|
1111
|
+
*/
|
|
1112
|
+
discardAllChanges(): void;
|
|
1113
|
+
[$getByIndex](index: number): any;
|
|
1114
|
+
[$deleteByIndex](index: number): void;
|
|
1115
|
+
/**
|
|
1116
|
+
* Inspect the `refId` of all Schema instances in the tree. Optionally display the contents of the instance.
|
|
1117
|
+
*
|
|
1118
|
+
* @param ref Schema instance
|
|
1119
|
+
* @param showContents display JSON contents of the instance
|
|
1120
|
+
* @returns
|
|
1121
|
+
*/
|
|
1122
|
+
static debugRefIds<T extends Schema>(ref: T, showContents?: boolean, level?: number, decoder?: Decoder, keyPrefix?: string): string;
|
|
1123
|
+
static debugRefIdEncodingOrder<T extends Ref>(ref: T, changeSet?: ChangeSetName): number[];
|
|
1124
|
+
static debugRefIdsFromDecoder(decoder: Decoder): string;
|
|
1125
|
+
/**
|
|
1126
|
+
* Return a string representation of the changes on a Schema instance.
|
|
1127
|
+
* The list of changes is cleared after each encode.
|
|
1128
|
+
*
|
|
1129
|
+
* @param instance Schema instance
|
|
1130
|
+
* @param isEncodeAll Return "full encode" instead of current change set.
|
|
1131
|
+
* @returns
|
|
1132
|
+
*/
|
|
1133
|
+
static debugChanges<T extends Ref>(instance: T, isEncodeAll?: boolean): string;
|
|
1134
|
+
static debugChangesDeep<T extends Schema>(ref: T, changeSetName?: "changes" | "allChanges" | "allFilteredChanges" | "filteredChanges"): string;
|
|
1135
|
+
}
|
|
1136
|
+
type SchemaCallbackProxy<RoomState> = (<T>(instance: T) => CallbackProxy<T>);
|
|
1137
|
+
type CallbackProxy<T> = unknown extends T ? SchemaCallback<T> & CollectionCallback<any, any> : T extends Collection<infer K, infer V, infer _> ? CollectionCallback<K, V> : SchemaCallback<T>;
|
|
1138
|
+
type SchemaCallback<T> = {
|
|
1139
|
+
/**
|
|
1140
|
+
* Trigger callback when value of a property changes.
|
|
1141
|
+
*
|
|
1142
|
+
* @param prop name of the property
|
|
1143
|
+
* @param callback callback to be triggered on property change
|
|
1144
|
+
* @param immediate trigger immediatelly if property has been already set.
|
|
1145
|
+
* @return callback to detach the listener
|
|
1146
|
+
*/
|
|
1147
|
+
listen<K extends NonFunctionPropNames<T>>(prop: K, callback: (value: T[K], previousValue: T[K]) => void, immediate?: boolean): () => void;
|
|
1148
|
+
/**
|
|
1149
|
+
* Trigger callback whenever any property changed within this instance.
|
|
1150
|
+
*
|
|
1151
|
+
* @param prop name of the property
|
|
1152
|
+
* @param callback callback to be triggered on property change
|
|
1153
|
+
* @param immediate trigger immediatelly if property has been already set.
|
|
1154
|
+
* @return callback to detach the listener
|
|
1155
|
+
*/
|
|
1156
|
+
onChange(callback: () => void): () => void;
|
|
1157
|
+
/**
|
|
1158
|
+
* Bind properties to another object. Changes on the properties will be reflected on the target object.
|
|
1159
|
+
*
|
|
1160
|
+
* @param targetObject object to bind properties to
|
|
1161
|
+
* @param properties list of properties to bind. If not provided, all properties will be bound.
|
|
1162
|
+
*/
|
|
1163
|
+
bindTo(targetObject: any, properties?: Array<NonFunctionPropNames<T>>): void;
|
|
1164
|
+
} & {
|
|
1165
|
+
[K in NonFunctionNonPrimitivePropNames<T>]: CallbackProxy<T[K]>;
|
|
1166
|
+
};
|
|
1167
|
+
type CollectionCallback<K, V> = {
|
|
1168
|
+
/**
|
|
1169
|
+
* Trigger callback when an item has been added to the collection.
|
|
1170
|
+
*
|
|
1171
|
+
* @param callback
|
|
1172
|
+
* @param immediate
|
|
1173
|
+
* @return callback to detach the onAdd listener
|
|
1174
|
+
*/
|
|
1175
|
+
onAdd(callback: (item: V, index: K) => void, immediate?: boolean): () => void;
|
|
1176
|
+
/**
|
|
1177
|
+
* Trigger callback when an item has been removed to the collection.
|
|
1178
|
+
*
|
|
1179
|
+
* @param callback
|
|
1180
|
+
* @return callback to detach the onRemove listener
|
|
1181
|
+
*/
|
|
1182
|
+
onRemove(callback: (item: V, index: K) => void): () => void;
|
|
1183
|
+
/**
|
|
1184
|
+
* Trigger callback when the value on a key has changed.
|
|
1185
|
+
*
|
|
1186
|
+
* THIS METHOD IS NOT RECURSIVE!
|
|
1187
|
+
* If you want to listen to changes on individual items, you need to attach callbacks to the them directly inside the `onAdd` callback.
|
|
1188
|
+
*
|
|
1189
|
+
* @param callback
|
|
1190
|
+
* @return callback to detach the onChange listener
|
|
1191
|
+
*/
|
|
1192
|
+
onChange(callback: (item: V, index: K) => void): () => void;
|
|
1193
|
+
};
|
|
1194
|
+
type PropertyChangeCallback<K> = (currentValue: K, previousValue: K) => void;
|
|
1195
|
+
type KeyValueCallback<K, V> = (key: K, value: V) => void;
|
|
1196
|
+
type ValueKeyCallback<V, K> = (value: V, key: K) => void;
|
|
1197
|
+
type InstanceChangeCallback = () => void;
|
|
1198
|
+
type PublicPropNames<T> = Exclude<NonFunctionPropNames<T>, typeof $refId> & string;
|
|
1199
|
+
type CollectionPropNames<T> = Exclude<{
|
|
1200
|
+
[K in keyof T]: T[K] extends Collection<any, any> ? K : never;
|
|
1201
|
+
}[keyof T] & string, typeof $refId>;
|
|
1202
|
+
type CollectionValueType<T, K extends keyof T> = T[K] extends MapSchema<infer V, any> ? V : T[K] extends ArraySchema<infer V> ? V : T[K] extends Collection<any, infer V, any> ? V : never;
|
|
1203
|
+
type CollectionKeyType<T, K extends keyof T> = T[K] extends MapSchema<any, infer Key> ? Key : T[K] extends ArraySchema<any> ? number : T[K] extends Collection<infer Key, any, any> ? Key : never;
|
|
1204
|
+
declare class StateCallbackStrategy<TState extends IRef> {
|
|
1205
|
+
protected decoder: Decoder<TState>;
|
|
1206
|
+
protected uniqueRefIds: Set<number>;
|
|
1207
|
+
protected isTriggering: boolean;
|
|
1208
|
+
constructor(decoder: Decoder<TState>);
|
|
1209
|
+
protected get callbacks(): {
|
|
1210
|
+
[refId: number]: SchemaCallbacks;
|
|
1211
|
+
};
|
|
1212
|
+
protected get state(): TState;
|
|
1213
|
+
protected addCallback(refId: number, operationOrProperty: OPERATION | string, handler: Function): () => void;
|
|
1214
|
+
protected addCallbackOrWaitCollectionAvailable<TInstance extends IRef, TReturn extends Ref>(instance: TInstance, propertyName: string, operation: OPERATION, handler: Function, immediate?: boolean): () => void;
|
|
1215
|
+
/**
|
|
1216
|
+
* Listen to property changes on the root state.
|
|
1217
|
+
*/
|
|
1218
|
+
listen<K extends PublicPropNames<TState>>(property: K, handler: PropertyChangeCallback<TState[K]>, immediate?: boolean): () => void;
|
|
1219
|
+
/**
|
|
1220
|
+
* Listen to property changes on a nested instance.
|
|
1221
|
+
*/
|
|
1222
|
+
listen<TInstance extends Schema, K extends PublicPropNames<TInstance>>(instance: TInstance, property: K, handler: PropertyChangeCallback<TInstance[K]>, immediate?: boolean): () => void;
|
|
1223
|
+
protected listenInstance<TInstance extends IRef>(instance: TInstance, propertyName: string, handler: PropertyChangeCallback<any>, immediate?: boolean): () => void;
|
|
1224
|
+
/**
|
|
1225
|
+
* Listen to any property change on an instance.
|
|
1226
|
+
*/
|
|
1227
|
+
onChange<TInstance extends Schema>(instance: TInstance, handler: InstanceChangeCallback): () => void;
|
|
1228
|
+
/**
|
|
1229
|
+
* Listen to item changes in a collection on root state.
|
|
1230
|
+
*/
|
|
1231
|
+
onChange<K extends CollectionPropNames<TState>>(property: K, handler: KeyValueCallback<CollectionKeyType<TState, K>, CollectionValueType<TState, K>>): () => void;
|
|
1232
|
+
/**
|
|
1233
|
+
* Listen to item changes in a nested collection.
|
|
1234
|
+
*/
|
|
1235
|
+
onChange<TInstance extends Schema, K extends CollectionPropNames<TInstance>>(instance: TInstance, property: K, handler: KeyValueCallback<CollectionKeyType<TInstance, K>, CollectionValueType<TInstance, K>>): () => void;
|
|
1236
|
+
/**
|
|
1237
|
+
* Listen to items added to a collection on root state.
|
|
1238
|
+
*/
|
|
1239
|
+
onAdd<K extends CollectionPropNames<TState>>(property: K, handler: ValueKeyCallback<CollectionValueType<TState, K>, CollectionKeyType<TState, K>>, immediate?: boolean): () => void;
|
|
1240
|
+
/**
|
|
1241
|
+
* Listen to items added to a nested collection.
|
|
1242
|
+
*/
|
|
1243
|
+
onAdd<TInstance extends Schema, K extends CollectionPropNames<TInstance>>(instance: TInstance, property: K, handler: ValueKeyCallback<CollectionValueType<TInstance, K>, CollectionKeyType<TInstance, K>>, immediate?: boolean): () => void;
|
|
1244
|
+
/**
|
|
1245
|
+
* Listen to items removed from a collection on root state.
|
|
1246
|
+
*/
|
|
1247
|
+
onRemove<K extends CollectionPropNames<TState>>(property: K, handler: ValueKeyCallback<CollectionValueType<TState, K>, CollectionKeyType<TState, K>>): () => void;
|
|
1248
|
+
/**
|
|
1249
|
+
* Listen to items removed from a nested collection.
|
|
1250
|
+
*/
|
|
1251
|
+
onRemove<TInstance extends Schema, K extends CollectionPropNames<TInstance>>(instance: TInstance, property: K, handler: ValueKeyCallback<CollectionValueType<TInstance, K>, CollectionKeyType<TInstance, K>>): () => void;
|
|
1252
|
+
/**
|
|
1253
|
+
* Bind properties from a Schema instance to a target object.
|
|
1254
|
+
* Changes will be automatically reflected on the target object.
|
|
1255
|
+
*/
|
|
1256
|
+
bindTo<TInstance extends Schema, TTarget>(from: TInstance, to: TTarget, properties?: string[], immediate?: boolean): () => void;
|
|
1257
|
+
protected triggerChanges(allChanges: DataChange[]): void;
|
|
1258
|
+
}
|
|
1259
|
+
/**
|
|
1260
|
+
* Factory class for retrieving the callbacks API.
|
|
1261
|
+
*/
|
|
1262
|
+
export declare const Callbacks: {
|
|
1263
|
+
/**
|
|
1264
|
+
* Get the new callbacks standard API.
|
|
1265
|
+
*
|
|
1266
|
+
* Usage:
|
|
1267
|
+
* ```ts
|
|
1268
|
+
* const callbacks = Callbacks.get(roomOrDecoder);
|
|
1269
|
+
*
|
|
1270
|
+
* // Listen to property changes
|
|
1271
|
+
* callbacks.listen("currentTurn", (currentValue, previousValue) => { ... });
|
|
1272
|
+
*
|
|
1273
|
+
* // Listen to collection additions
|
|
1274
|
+
* callbacks.onAdd("entities", (entity, sessionId) => {
|
|
1275
|
+
* // Nested property listening
|
|
1276
|
+
* callbacks.listen(entity, "hp", (currentHp, previousHp) => { ... });
|
|
1277
|
+
* });
|
|
1278
|
+
*
|
|
1279
|
+
* // Listen to collection removals
|
|
1280
|
+
* callbacks.onRemove("entities", (entity, sessionId) => { ... });
|
|
1281
|
+
*
|
|
1282
|
+
* // Listen to any property change on an instance
|
|
1283
|
+
* callbacks.onChange(entity, () => { ... });
|
|
1284
|
+
*
|
|
1285
|
+
* // Bind properties to another object
|
|
1286
|
+
* callbacks.bindTo(player, playerVisual);
|
|
1287
|
+
* ```
|
|
1288
|
+
*
|
|
1289
|
+
* @param roomOrDecoder - Room or Decoder instance to get the callbacks for.
|
|
1290
|
+
* @returns the new callbacks standard API.
|
|
1291
|
+
*/
|
|
1292
|
+
get<T extends IRef>(roomOrDecoder: Decoder<T> | {
|
|
1293
|
+
serializer: {
|
|
1294
|
+
decoder: Decoder<T>;
|
|
1295
|
+
};
|
|
1296
|
+
} | {
|
|
1297
|
+
state: T;
|
|
1298
|
+
serializer: object;
|
|
1299
|
+
}): StateCallbackStrategy<T>;
|
|
1300
|
+
/**
|
|
1301
|
+
* Get the legacy callbacks API.
|
|
1302
|
+
*
|
|
1303
|
+
* We aim to deprecate this API on 1.0, and iterate on improving Callbacks.get() API.
|
|
1304
|
+
*
|
|
1305
|
+
* @param roomOrDecoder - Room or Decoder instance to get the legacy callbacks for.
|
|
1306
|
+
* @returns the legacy callbacks API.
|
|
1307
|
+
*/
|
|
1308
|
+
getLegacy<T extends Schema>(roomOrDecoder: Decoder<T> | {
|
|
1309
|
+
serializer: {
|
|
1310
|
+
decoder: Decoder<T>;
|
|
1311
|
+
};
|
|
1312
|
+
} | {
|
|
1313
|
+
state: T;
|
|
1314
|
+
serializer: object;
|
|
1315
|
+
}): SchemaCallbackProxy<T>;
|
|
1316
|
+
getRawChanges(decoder: Decoder, callback: (changes: DataChange[]) => void): void;
|
|
1317
|
+
};
|
|
1318
|
+
declare enum FLOAT32_OPTIONS {
|
|
1319
|
+
NEVER = 0,
|
|
1320
|
+
ALWAYS = 1,
|
|
1321
|
+
DECIMAL_ROUND = 3,
|
|
1322
|
+
DECIMAL_FIT = 4
|
|
1323
|
+
}
|
|
1324
|
+
interface Options {
|
|
1325
|
+
useFloat32?: FLOAT32_OPTIONS;
|
|
1326
|
+
useRecords?: boolean | ((value: any) => boolean);
|
|
1327
|
+
structures?: {}[];
|
|
1328
|
+
moreTypes?: boolean;
|
|
1329
|
+
sequential?: boolean;
|
|
1330
|
+
structuredClone?: boolean;
|
|
1331
|
+
mapsAsObjects?: boolean;
|
|
1332
|
+
variableMapSize?: boolean;
|
|
1333
|
+
coercibleKeyAsNumber?: boolean;
|
|
1334
|
+
copyBuffers?: boolean;
|
|
1335
|
+
bundleStrings?: boolean;
|
|
1336
|
+
useTimestamp32?: boolean;
|
|
1337
|
+
largeBigIntToFloat?: boolean;
|
|
1338
|
+
largeBigIntToString?: boolean;
|
|
1339
|
+
useBigIntExtension?: boolean;
|
|
1340
|
+
encodeUndefinedAsNil?: boolean;
|
|
1341
|
+
maxSharedStructures?: number;
|
|
1342
|
+
maxOwnStructures?: number;
|
|
1343
|
+
mapAsEmptyObject?: boolean;
|
|
1344
|
+
setAsEmptyObject?: boolean;
|
|
1345
|
+
allowArraysInMapKeys?: boolean;
|
|
1346
|
+
writeFunction?: () => any;
|
|
1347
|
+
/** @deprecated use int64AsType: 'number' */
|
|
1348
|
+
int64AsNumber?: boolean;
|
|
1349
|
+
int64AsType?: "bigint" | "number" | "string";
|
|
1350
|
+
shouldShareStructure?: (keys: string[]) => boolean;
|
|
1351
|
+
getStructures?(): {}[];
|
|
1352
|
+
saveStructures?(structures: {}[]): boolean | void;
|
|
1353
|
+
onInvalidDate?: () => any;
|
|
1354
|
+
}
|
|
1355
|
+
type UnpackOptions = {
|
|
1356
|
+
start?: number;
|
|
1357
|
+
end?: number;
|
|
1358
|
+
lazy?: boolean;
|
|
1359
|
+
} | number;
|
|
1360
|
+
declare class Unpackr {
|
|
1361
|
+
constructor(options?: Options);
|
|
1362
|
+
unpack(messagePack: Buffer | Uint8Array, options?: UnpackOptions): any;
|
|
1363
|
+
decode(messagePack: Buffer | Uint8Array, options?: UnpackOptions): any;
|
|
1364
|
+
unpackMultiple(messagePack: Buffer | Uint8Array): any[];
|
|
1365
|
+
unpackMultiple(messagePack: Buffer | Uint8Array, forEach: (value: any, start?: number, end?: number) => any): void;
|
|
1366
|
+
}
|
|
1367
|
+
declare class Packr extends Unpackr {
|
|
1368
|
+
offset: number;
|
|
1369
|
+
position: number;
|
|
1370
|
+
buffer: Buffer | Uint8Array;
|
|
1371
|
+
pack(value: any, encodeOptions?: number): Buffer;
|
|
1372
|
+
encode(value: any, encodeOptions?: number): Buffer;
|
|
1373
|
+
useBuffer(buffer: Buffer | Uint8Array): void;
|
|
1374
|
+
clearSharedData(): void;
|
|
1375
|
+
}
|
|
1376
|
+
interface ITransportEventMap {
|
|
1377
|
+
onopen?: ((ev: any) => any) | null;
|
|
1378
|
+
onmessage?: ((ev: any) => any) | null;
|
|
1379
|
+
onclose?: ((ev: any) => any) | null;
|
|
1380
|
+
onerror?: ((ev: any) => any) | null;
|
|
1381
|
+
}
|
|
1382
|
+
interface ITransport {
|
|
1383
|
+
isOpen: boolean;
|
|
1384
|
+
send(data: Buffer | Uint8Array): void;
|
|
1385
|
+
sendUnreliable(data: Buffer | Uint8Array): void;
|
|
1386
|
+
connect(url: string, options?: any): void;
|
|
1387
|
+
close(code?: number, reason?: string): void;
|
|
1388
|
+
}
|
|
1389
|
+
declare class Connection implements ITransport {
|
|
1390
|
+
#private;
|
|
1391
|
+
transport: ITransport;
|
|
1392
|
+
events: ITransportEventMap;
|
|
1393
|
+
url?: string;
|
|
1394
|
+
options?: any;
|
|
1395
|
+
constructor(protocol?: string);
|
|
1396
|
+
connect(url: string, options?: any): void;
|
|
1397
|
+
send(data: Buffer | Uint8Array): void;
|
|
1398
|
+
sendUnreliable(data: Buffer | Uint8Array): void;
|
|
1399
|
+
reconnect(queryParams: {
|
|
1400
|
+
reconnectionToken: string;
|
|
1401
|
+
skipHandshake?: boolean;
|
|
1402
|
+
}): void;
|
|
1403
|
+
close(code?: number, reason?: string): void;
|
|
1404
|
+
get isOpen(): boolean;
|
|
1405
|
+
}
|
|
1406
|
+
interface Serializer<State> {
|
|
1407
|
+
setState(data: Uint8Array, it?: Iterator$1): void;
|
|
1408
|
+
getState(): State;
|
|
1409
|
+
patch(data: Uint8Array, it?: Iterator$1): void;
|
|
1410
|
+
teardown(): void;
|
|
1411
|
+
handshake?(bytes: Uint8Array, it?: any): void;
|
|
1412
|
+
}
|
|
1413
|
+
export declare function registerSerializer(id: string, serializer: any): void;
|
|
1414
|
+
type SchemaConstructor<T = Schema> = new (...args: any[]) => T;
|
|
1415
|
+
export declare function getStateCallbacks<T>(room: Room<any, T>): SchemaCallbackProxy<T>;
|
|
1416
|
+
export declare class SchemaSerializer<T extends Schema = any> implements Serializer<T> {
|
|
1417
|
+
state: T;
|
|
1418
|
+
decoder: Decoder<T>;
|
|
1419
|
+
setState(encodedState: Uint8Array, it?: Iterator$1): void;
|
|
1420
|
+
getState(): T;
|
|
1421
|
+
patch(patches: Uint8Array, it?: Iterator$1): DataChange<any, string>[];
|
|
1422
|
+
teardown(): void;
|
|
1423
|
+
handshake(bytes: Uint8Array, it?: Iterator$1): void;
|
|
1424
|
+
}
|
|
1425
|
+
type FunctionParameters<T extends (...args: any[]) => any> = T extends (...args: infer P) => any ? P : never;
|
|
1426
|
+
declare class EventEmitter<CallbackSignature extends (...args: any[]) => any> {
|
|
1427
|
+
handlers: Array<CallbackSignature>;
|
|
1428
|
+
register(cb: CallbackSignature, once?: boolean): this;
|
|
1429
|
+
invoke(...args: FunctionParameters<CallbackSignature>): void;
|
|
1430
|
+
invokeAsync(...args: FunctionParameters<CallbackSignature>): Promise<any[]>;
|
|
1431
|
+
remove(cb: CallbackSignature): void;
|
|
1432
|
+
clear(): void;
|
|
1433
|
+
}
|
|
1434
|
+
type EventsMap = Record<string, (...args: any[]) => void>;
|
|
1435
|
+
interface Emitter<Events extends EventsMap> {
|
|
1436
|
+
events: {
|
|
1437
|
+
[K in keyof Events]?: Array<Events[K]>;
|
|
1438
|
+
};
|
|
1439
|
+
emit<K extends keyof Events>(event: K, ...args: Parameters<Events[K]>): void;
|
|
1440
|
+
on<K extends keyof Events>(event: K, cb: Events[K]): () => void;
|
|
1441
|
+
}
|
|
1442
|
+
type InferSerializer<State> = [
|
|
1443
|
+
State
|
|
1444
|
+
] extends [
|
|
1445
|
+
Schema
|
|
1446
|
+
] ? SchemaSerializer<State> : Serializer<State>;
|
|
1447
|
+
export interface RoomAvailable<Metadata = any> {
|
|
1448
|
+
name: string;
|
|
1449
|
+
roomId: string;
|
|
1450
|
+
clients: number;
|
|
1451
|
+
maxClients: number;
|
|
1452
|
+
metadata?: Metadata;
|
|
1453
|
+
}
|
|
1454
|
+
interface ReconnectionOptions {
|
|
1455
|
+
/**
|
|
1456
|
+
* The maximum number of reconnection attempts.
|
|
1457
|
+
*/
|
|
1458
|
+
maxRetries: number;
|
|
1459
|
+
/**
|
|
1460
|
+
* The minimum delay between reconnection attempts.
|
|
1461
|
+
*/
|
|
1462
|
+
minDelay: number;
|
|
1463
|
+
/**
|
|
1464
|
+
* The maximum delay between reconnection attempts.
|
|
1465
|
+
*/
|
|
1466
|
+
maxDelay: number;
|
|
1467
|
+
/**
|
|
1468
|
+
* The minimum uptime of the room before reconnection attempts can be made.
|
|
1469
|
+
*/
|
|
1470
|
+
minUptime: number;
|
|
1471
|
+
/**
|
|
1472
|
+
* The current number of reconnection attempts.
|
|
1473
|
+
*/
|
|
1474
|
+
retryCount: number;
|
|
1475
|
+
/**
|
|
1476
|
+
* The initial delay between reconnection attempts.
|
|
1477
|
+
*/
|
|
1478
|
+
delay: number;
|
|
1479
|
+
/**
|
|
1480
|
+
* The function to calculate the delay between reconnection attempts.
|
|
1481
|
+
* @param attempt - The current attempt number.
|
|
1482
|
+
* @param delay - The initial delay between reconnection attempts.
|
|
1483
|
+
* @returns The delay between reconnection attempts.
|
|
1484
|
+
*/
|
|
1485
|
+
backoff: (attempt: number, delay: number) => number;
|
|
1486
|
+
/**
|
|
1487
|
+
* The maximum number of enqueued messages to buffer.
|
|
1488
|
+
*/
|
|
1489
|
+
maxEnqueuedMessages: number;
|
|
1490
|
+
/**
|
|
1491
|
+
* Buffer for messages sent while connection is not open.
|
|
1492
|
+
* These messages will be sent once the connection is re-established.
|
|
1493
|
+
*/
|
|
1494
|
+
enqueuedMessages: Array<{
|
|
1495
|
+
data: Uint8Array;
|
|
1496
|
+
}>;
|
|
1497
|
+
/**
|
|
1498
|
+
* Whether the room is currently reconnecting.
|
|
1499
|
+
*/
|
|
1500
|
+
isReconnecting: boolean;
|
|
1501
|
+
}
|
|
1502
|
+
export declare class Room<T = any, State = InferState<T, never>> {
|
|
1503
|
+
#private;
|
|
1504
|
+
roomId: string;
|
|
1505
|
+
sessionId: string;
|
|
1506
|
+
reconnectionToken: string;
|
|
1507
|
+
name: string;
|
|
1508
|
+
connection: Connection;
|
|
1509
|
+
onStateChange: {
|
|
1510
|
+
once: (cb: (state: State) => void) => void;
|
|
1511
|
+
remove: (cb: (state: State) => void) => void;
|
|
1512
|
+
invoke: (state: State) => void;
|
|
1513
|
+
invokeAsync: (state: State) => Promise<any[]>;
|
|
1514
|
+
clear: () => void;
|
|
1515
|
+
} & ((this: any, cb: (state: State) => void) => EventEmitter<(state: State) => void>);
|
|
1516
|
+
onError: {
|
|
1517
|
+
once: (cb: (code: number, message?: string) => void) => void;
|
|
1518
|
+
remove: (cb: (code: number, message?: string) => void) => void;
|
|
1519
|
+
invoke: (code: number, message?: string) => void;
|
|
1520
|
+
invokeAsync: (code: number, message?: string) => Promise<any[]>;
|
|
1521
|
+
clear: () => void;
|
|
1522
|
+
} & ((this: any, cb: (code: number, message?: string) => void) => EventEmitter<(code: number, message?: string) => void>);
|
|
1523
|
+
onLeave: {
|
|
1524
|
+
once: (cb: (code: number, reason?: string) => void) => void;
|
|
1525
|
+
remove: (cb: (code: number, reason?: string) => void) => void;
|
|
1526
|
+
invoke: (code: number, reason?: string) => void;
|
|
1527
|
+
invokeAsync: (code: number, reason?: string) => Promise<any[]>;
|
|
1528
|
+
clear: () => void;
|
|
1529
|
+
} & ((this: any, cb: (code: number, reason?: string) => void) => EventEmitter<(code: number, reason?: string) => void>);
|
|
1530
|
+
onReconnect: {
|
|
1531
|
+
once: (cb: () => void) => void;
|
|
1532
|
+
remove: (cb: () => void) => void;
|
|
1533
|
+
invoke: () => void;
|
|
1534
|
+
invokeAsync: () => Promise<any[]>;
|
|
1535
|
+
clear: () => void;
|
|
1536
|
+
} & ((this: any, cb: () => void) => EventEmitter<() => void>);
|
|
1537
|
+
onDrop: {
|
|
1538
|
+
once: (cb: (code: number, reason?: string) => void) => void;
|
|
1539
|
+
remove: (cb: (code: number, reason?: string) => void) => void;
|
|
1540
|
+
invoke: (code: number, reason?: string) => void;
|
|
1541
|
+
invokeAsync: (code: number, reason?: string) => Promise<any[]>;
|
|
1542
|
+
clear: () => void;
|
|
1543
|
+
} & ((this: any, cb: (code: number, reason?: string) => void) => EventEmitter<(code: number, reason?: string) => void>);
|
|
1544
|
+
protected onJoin: {
|
|
1545
|
+
once: (cb: (...args: any[]) => void | Promise<any>) => void;
|
|
1546
|
+
remove: (cb: (...args: any[]) => void | Promise<any>) => void;
|
|
1547
|
+
invoke: (...args: any[]) => void;
|
|
1548
|
+
invokeAsync: (...args: any[]) => Promise<any[]>;
|
|
1549
|
+
clear: () => void;
|
|
1550
|
+
} & ((this: any, cb: (...args: any[]) => void | Promise<any>) => EventEmitter<(...args: any[]) => void | Promise<any>>);
|
|
1551
|
+
serializerId: string;
|
|
1552
|
+
serializer: InferSerializer<State>;
|
|
1553
|
+
reconnection: ReconnectionOptions;
|
|
1554
|
+
protected joinedAtTime: number;
|
|
1555
|
+
protected onMessageHandlers: Emitter<EventsMap>;
|
|
1556
|
+
protected packr: Packr;
|
|
1557
|
+
constructor(name: string, rootSchema?: SchemaConstructor<State>);
|
|
1558
|
+
connect(endpoint: string, options?: any, headers?: any): void;
|
|
1559
|
+
leave(consented?: boolean): Promise<number>;
|
|
1560
|
+
onMessage<MessageType extends keyof ExtractRoomClientMessages<NormalizeRoomType<T>>>(message: MessageType, callback: (payload: ExtractRoomClientMessages<NormalizeRoomType<T>>[MessageType]) => void): () => void;
|
|
1561
|
+
onMessage<Payload = any>(type: "*", callback: (messageType: string | number, payload: Payload) => void): () => void;
|
|
1562
|
+
onMessage<Payload = any>(type: [
|
|
1563
|
+
keyof ExtractRoomClientMessages<NormalizeRoomType<T>>
|
|
1564
|
+
] extends [
|
|
1565
|
+
never
|
|
1566
|
+
] ? (string | number) : never, callback: (payload: Payload) => void): () => void;
|
|
1567
|
+
ping(callback: (ms: number) => void): void;
|
|
1568
|
+
send<MessageType extends keyof ExtractRoomMessages<NormalizeRoomType<T>>>(messageType: MessageType, payload?: ExtractMessageType<ExtractRoomMessages<NormalizeRoomType<T>>[MessageType]>): void;
|
|
1569
|
+
send<Payload = any>(messageType: [
|
|
1570
|
+
keyof ExtractRoomMessages<NormalizeRoomType<T>>
|
|
1571
|
+
] extends [
|
|
1572
|
+
never
|
|
1573
|
+
] ? (string | number) : never, payload?: Payload): void;
|
|
1574
|
+
sendUnreliable<T = any>(type: string | number, message?: T): void;
|
|
1575
|
+
sendBytes(type: string | number, bytes: Uint8Array): void;
|
|
1576
|
+
get state(): State;
|
|
1577
|
+
removeAllListeners(): void;
|
|
1578
|
+
protected onMessageCallback(event: MessageEvent): void;
|
|
1579
|
+
private dispatchMessage;
|
|
1580
|
+
private destroy;
|
|
1581
|
+
private getMessageHandlerKey;
|
|
1582
|
+
private handleReconnection;
|
|
1583
|
+
private retryReconnection;
|
|
1584
|
+
}
|
|
1585
|
+
type RequiredKeysOf<BaseType extends object> = Exclude<{
|
|
1586
|
+
[Key in keyof BaseType]: BaseType extends Record<Key, BaseType[Key]> ? Key : never;
|
|
1587
|
+
}[keyof BaseType], undefined>;
|
|
1588
|
+
type HasRequiredKeys<BaseType extends object> = RequiredKeysOf<BaseType> extends never ? false : true;
|
|
1589
|
+
type Prettify<T> = {
|
|
1590
|
+
[K in keyof T]: T[K];
|
|
1591
|
+
} & {};
|
|
1592
|
+
type UnionToIntersection<Union> = (Union extends unknown ? (distributedUnion: Union) => void : never) extends ((mergedIntersection: infer Intersection) => void) ? Intersection & Union : never;
|
|
1593
|
+
interface StandardSchemaV1$1<Input = unknown, Output = Input> {
|
|
1594
|
+
/** The Standard Schema properties. */
|
|
1595
|
+
readonly "~standard": StandardSchemaV1$1.Props<Input, Output>;
|
|
1596
|
+
}
|
|
1597
|
+
declare namespace StandardSchemaV1$1 {
|
|
1598
|
+
/** The Standard Schema properties interface. */
|
|
1599
|
+
interface Props<Input = unknown, Output = Input> {
|
|
1600
|
+
/** The version number of the standard. */
|
|
1601
|
+
readonly version: 1;
|
|
1602
|
+
/** The vendor name of the schema library. */
|
|
1603
|
+
readonly vendor: string;
|
|
1604
|
+
/** Validates unknown input values. */
|
|
1605
|
+
readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
|
|
1606
|
+
/** Inferred types associated with the schema. */
|
|
1607
|
+
readonly types?: Types<Input, Output> | undefined;
|
|
1608
|
+
}
|
|
1609
|
+
/** The result interface of the validate function. */
|
|
1610
|
+
type Result<Output> = SuccessResult<Output> | FailureResult;
|
|
1611
|
+
/** The result interface if validation succeeds. */
|
|
1612
|
+
interface SuccessResult<Output> {
|
|
1613
|
+
/** The typed output value. */
|
|
1614
|
+
readonly value: Output;
|
|
1615
|
+
/** The non-existent issues. */
|
|
1616
|
+
readonly issues?: undefined;
|
|
1617
|
+
}
|
|
1618
|
+
/** The result interface if validation fails. */
|
|
1619
|
+
interface FailureResult {
|
|
1620
|
+
/** The issues of failed validation. */
|
|
1621
|
+
readonly issues: ReadonlyArray<Issue>;
|
|
1622
|
+
}
|
|
1623
|
+
/** The issue interface of the failure output. */
|
|
1624
|
+
interface Issue {
|
|
1625
|
+
/** The error message of the issue. */
|
|
1626
|
+
readonly message: string;
|
|
1627
|
+
/** The path of the issue, if any. */
|
|
1628
|
+
readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
|
|
1629
|
+
}
|
|
1630
|
+
/** The path segment interface of the issue. */
|
|
1631
|
+
interface PathSegment {
|
|
1632
|
+
/** The key representing a path segment. */
|
|
1633
|
+
readonly key: PropertyKey;
|
|
1634
|
+
}
|
|
1635
|
+
/** The Standard Schema types interface. */
|
|
1636
|
+
interface Types<Input = unknown, Output = Input> {
|
|
1637
|
+
/** The input type of the schema. */
|
|
1638
|
+
readonly input: Input;
|
|
1639
|
+
/** The output type of the schema. */
|
|
1640
|
+
readonly output: Output;
|
|
1641
|
+
}
|
|
1642
|
+
/** Infers the input type of a Standard Schema. */
|
|
1643
|
+
type InferInput<Schema extends StandardSchemaV1$1> = NonNullable<Schema["~standard"]["types"]>["input"];
|
|
1644
|
+
/** Infers the output type of a Standard Schema. */
|
|
1645
|
+
type InferOutput<Schema extends StandardSchemaV1$1> = NonNullable<Schema["~standard"]["types"]>["output"];
|
|
1646
|
+
}
|
|
1647
|
+
declare const statusCodes: {
|
|
1648
|
+
OK: number;
|
|
1649
|
+
CREATED: number;
|
|
1650
|
+
ACCEPTED: number;
|
|
1651
|
+
NO_CONTENT: number;
|
|
1652
|
+
MULTIPLE_CHOICES: number;
|
|
1653
|
+
MOVED_PERMANENTLY: number;
|
|
1654
|
+
FOUND: number;
|
|
1655
|
+
SEE_OTHER: number;
|
|
1656
|
+
NOT_MODIFIED: number;
|
|
1657
|
+
TEMPORARY_REDIRECT: number;
|
|
1658
|
+
BAD_REQUEST: number;
|
|
1659
|
+
UNAUTHORIZED: number;
|
|
1660
|
+
PAYMENT_REQUIRED: number;
|
|
1661
|
+
FORBIDDEN: number;
|
|
1662
|
+
NOT_FOUND: number;
|
|
1663
|
+
METHOD_NOT_ALLOWED: number;
|
|
1664
|
+
NOT_ACCEPTABLE: number;
|
|
1665
|
+
PROXY_AUTHENTICATION_REQUIRED: number;
|
|
1666
|
+
REQUEST_TIMEOUT: number;
|
|
1667
|
+
CONFLICT: number;
|
|
1668
|
+
GONE: number;
|
|
1669
|
+
LENGTH_REQUIRED: number;
|
|
1670
|
+
PRECONDITION_FAILED: number;
|
|
1671
|
+
PAYLOAD_TOO_LARGE: number;
|
|
1672
|
+
URI_TOO_LONG: number;
|
|
1673
|
+
UNSUPPORTED_MEDIA_TYPE: number;
|
|
1674
|
+
RANGE_NOT_SATISFIABLE: number;
|
|
1675
|
+
EXPECTATION_FAILED: number;
|
|
1676
|
+
"I'M_A_TEAPOT": number;
|
|
1677
|
+
MISDIRECTED_REQUEST: number;
|
|
1678
|
+
UNPROCESSABLE_ENTITY: number;
|
|
1679
|
+
LOCKED: number;
|
|
1680
|
+
FAILED_DEPENDENCY: number;
|
|
1681
|
+
TOO_EARLY: number;
|
|
1682
|
+
UPGRADE_REQUIRED: number;
|
|
1683
|
+
PRECONDITION_REQUIRED: number;
|
|
1684
|
+
TOO_MANY_REQUESTS: number;
|
|
1685
|
+
REQUEST_HEADER_FIELDS_TOO_LARGE: number;
|
|
1686
|
+
UNAVAILABLE_FOR_LEGAL_REASONS: number;
|
|
1687
|
+
INTERNAL_SERVER_ERROR: number;
|
|
1688
|
+
NOT_IMPLEMENTED: number;
|
|
1689
|
+
BAD_GATEWAY: number;
|
|
1690
|
+
SERVICE_UNAVAILABLE: number;
|
|
1691
|
+
GATEWAY_TIMEOUT: number;
|
|
1692
|
+
HTTP_VERSION_NOT_SUPPORTED: number;
|
|
1693
|
+
VARIANT_ALSO_NEGOTIATES: number;
|
|
1694
|
+
INSUFFICIENT_STORAGE: number;
|
|
1695
|
+
LOOP_DETECTED: number;
|
|
1696
|
+
NOT_EXTENDED: number;
|
|
1697
|
+
NETWORK_AUTHENTICATION_REQUIRED: number;
|
|
1698
|
+
};
|
|
1699
|
+
type Status = 100 | 101 | 102 | 103 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 226 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511;
|
|
1700
|
+
declare class InternalAPIError extends Error {
|
|
1701
|
+
status: keyof typeof statusCodes | Status;
|
|
1702
|
+
body: ({
|
|
1703
|
+
message?: string;
|
|
1704
|
+
code?: string;
|
|
1705
|
+
cause?: unknown;
|
|
1706
|
+
} & Record<string, any>) | undefined;
|
|
1707
|
+
headers: HeadersInit;
|
|
1708
|
+
statusCode: number;
|
|
1709
|
+
constructor(status?: keyof typeof statusCodes | Status, body?: ({
|
|
1710
|
+
message?: string;
|
|
1711
|
+
code?: string;
|
|
1712
|
+
cause?: unknown;
|
|
1713
|
+
} & Record<string, any>) | undefined, headers?: HeadersInit, statusCode?: number);
|
|
1714
|
+
}
|
|
1715
|
+
type APIError = InstanceType<typeof InternalAPIError>;
|
|
1716
|
+
declare const APIError: new (status?: "OK" | "CREATED" | "ACCEPTED" | "NO_CONTENT" | "MULTIPLE_CHOICES" | "MOVED_PERMANENTLY" | "FOUND" | "SEE_OTHER" | "NOT_MODIFIED" | "TEMPORARY_REDIRECT" | "BAD_REQUEST" | "UNAUTHORIZED" | "PAYMENT_REQUIRED" | "FORBIDDEN" | "NOT_FOUND" | "METHOD_NOT_ALLOWED" | "NOT_ACCEPTABLE" | "PROXY_AUTHENTICATION_REQUIRED" | "REQUEST_TIMEOUT" | "CONFLICT" | "GONE" | "LENGTH_REQUIRED" | "PRECONDITION_FAILED" | "PAYLOAD_TOO_LARGE" | "URI_TOO_LONG" | "UNSUPPORTED_MEDIA_TYPE" | "RANGE_NOT_SATISFIABLE" | "EXPECTATION_FAILED" | "I'M_A_TEAPOT" | "MISDIRECTED_REQUEST" | "UNPROCESSABLE_ENTITY" | "LOCKED" | "FAILED_DEPENDENCY" | "TOO_EARLY" | "UPGRADE_REQUIRED" | "PRECONDITION_REQUIRED" | "TOO_MANY_REQUESTS" | "REQUEST_HEADER_FIELDS_TOO_LARGE" | "UNAVAILABLE_FOR_LEGAL_REASONS" | "INTERNAL_SERVER_ERROR" | "NOT_IMPLEMENTED" | "BAD_GATEWAY" | "SERVICE_UNAVAILABLE" | "GATEWAY_TIMEOUT" | "HTTP_VERSION_NOT_SUPPORTED" | "VARIANT_ALSO_NEGOTIATES" | "INSUFFICIENT_STORAGE" | "LOOP_DETECTED" | "NOT_EXTENDED" | "NETWORK_AUTHENTICATION_REQUIRED" | Status | undefined, body?: ({
|
|
1717
|
+
message?: string;
|
|
1718
|
+
code?: string;
|
|
1719
|
+
cause?: unknown;
|
|
1720
|
+
} & Record<string, any>) | undefined, headers?: HeadersInit | undefined, statusCode?: number | undefined) => InternalAPIError & {
|
|
1721
|
+
errorStack: string | undefined;
|
|
1722
|
+
};
|
|
1723
|
+
type OpenAPISchemaType = "string" | "number" | "integer" | "boolean" | "array" | "object";
|
|
1724
|
+
interface OpenAPIParameter {
|
|
1725
|
+
in: "query" | "path" | "header" | "cookie";
|
|
1726
|
+
name?: string;
|
|
1727
|
+
description?: string;
|
|
1728
|
+
required?: boolean;
|
|
1729
|
+
schema?: {
|
|
1730
|
+
type: OpenAPISchemaType;
|
|
1731
|
+
format?: string;
|
|
1732
|
+
items?: {
|
|
1733
|
+
type: OpenAPISchemaType;
|
|
1734
|
+
};
|
|
1735
|
+
enum?: string[];
|
|
1736
|
+
minLength?: number;
|
|
1737
|
+
description?: string;
|
|
1738
|
+
default?: string;
|
|
1739
|
+
example?: string;
|
|
1740
|
+
};
|
|
1741
|
+
}
|
|
1742
|
+
interface EndpointBaseOptions {
|
|
1743
|
+
/**
|
|
1744
|
+
* Query Schema
|
|
1745
|
+
*/
|
|
1746
|
+
query?: StandardSchemaV1$1;
|
|
1747
|
+
/**
|
|
1748
|
+
* Error Schema
|
|
1749
|
+
*/
|
|
1750
|
+
error?: StandardSchemaV1$1;
|
|
1751
|
+
/**
|
|
1752
|
+
* If true headers will be required to be passed in the context
|
|
1753
|
+
*/
|
|
1754
|
+
requireHeaders?: boolean;
|
|
1755
|
+
/**
|
|
1756
|
+
* If true request object will be required
|
|
1757
|
+
*/
|
|
1758
|
+
requireRequest?: boolean;
|
|
1759
|
+
/**
|
|
1760
|
+
* Clone the request object from the router
|
|
1761
|
+
*/
|
|
1762
|
+
cloneRequest?: boolean;
|
|
1763
|
+
/**
|
|
1764
|
+
* If true the body will be undefined
|
|
1765
|
+
*/
|
|
1766
|
+
disableBody?: boolean;
|
|
1767
|
+
/**
|
|
1768
|
+
* Endpoint metadata
|
|
1769
|
+
*/
|
|
1770
|
+
metadata?: {
|
|
1771
|
+
/**
|
|
1772
|
+
* Open API definition
|
|
1773
|
+
*/
|
|
1774
|
+
openapi?: {
|
|
1775
|
+
summary?: string;
|
|
1776
|
+
description?: string;
|
|
1777
|
+
tags?: string[];
|
|
1778
|
+
operationId?: string;
|
|
1779
|
+
parameters?: OpenAPIParameter[];
|
|
1780
|
+
requestBody?: {
|
|
1781
|
+
content: {
|
|
1782
|
+
"application/json": {
|
|
1783
|
+
schema: {
|
|
1784
|
+
type?: OpenAPISchemaType;
|
|
1785
|
+
properties?: Record<string, any>;
|
|
1786
|
+
required?: string[];
|
|
1787
|
+
$ref?: string;
|
|
1788
|
+
};
|
|
1789
|
+
};
|
|
1790
|
+
};
|
|
1791
|
+
};
|
|
1792
|
+
responses?: {
|
|
1793
|
+
[status: string]: {
|
|
1794
|
+
description: string;
|
|
1795
|
+
content?: {
|
|
1796
|
+
"application/json"?: {
|
|
1797
|
+
schema: {
|
|
1798
|
+
type?: OpenAPISchemaType;
|
|
1799
|
+
properties?: Record<string, any>;
|
|
1800
|
+
required?: string[];
|
|
1801
|
+
$ref?: string;
|
|
1802
|
+
};
|
|
1803
|
+
};
|
|
1804
|
+
"text/plain"?: {
|
|
1805
|
+
schema?: {
|
|
1806
|
+
type?: OpenAPISchemaType;
|
|
1807
|
+
properties?: Record<string, any>;
|
|
1808
|
+
required?: string[];
|
|
1809
|
+
$ref?: string;
|
|
1810
|
+
};
|
|
1811
|
+
};
|
|
1812
|
+
"text/html"?: {
|
|
1813
|
+
schema?: {
|
|
1814
|
+
type?: OpenAPISchemaType;
|
|
1815
|
+
properties?: Record<string, any>;
|
|
1816
|
+
required?: string[];
|
|
1817
|
+
$ref?: string;
|
|
1818
|
+
};
|
|
1819
|
+
};
|
|
1820
|
+
};
|
|
1821
|
+
};
|
|
1822
|
+
};
|
|
1823
|
+
};
|
|
1824
|
+
/**
|
|
1825
|
+
* Infer body and query type from ts interface
|
|
1826
|
+
*
|
|
1827
|
+
* useful for generic and dynamic types
|
|
1828
|
+
*
|
|
1829
|
+
* @example
|
|
1830
|
+
* ```ts
|
|
1831
|
+
* const endpoint = createEndpoint("/path", {
|
|
1832
|
+
* method: "POST",
|
|
1833
|
+
* body: z.record(z.string()),
|
|
1834
|
+
* $Infer: {
|
|
1835
|
+
* body: {} as {
|
|
1836
|
+
* type: InferTypeFromOptions<Option> // custom type inference
|
|
1837
|
+
* }
|
|
1838
|
+
* }
|
|
1839
|
+
* }, async(ctx)=>{
|
|
1840
|
+
* const body = ctx.body
|
|
1841
|
+
* })
|
|
1842
|
+
* ```
|
|
1843
|
+
*/
|
|
1844
|
+
$Infer?: {
|
|
1845
|
+
/**
|
|
1846
|
+
* Body
|
|
1847
|
+
*/
|
|
1848
|
+
body?: any;
|
|
1849
|
+
/**
|
|
1850
|
+
* Query
|
|
1851
|
+
*/
|
|
1852
|
+
query?: Record<string, any>;
|
|
1853
|
+
};
|
|
1854
|
+
/**
|
|
1855
|
+
* If enabled, endpoint won't be exposed over a router
|
|
1856
|
+
* @deprecated Use path-less endpoints instead
|
|
1857
|
+
*/
|
|
1858
|
+
SERVER_ONLY?: boolean;
|
|
1859
|
+
/**
|
|
1860
|
+
* If enabled, endpoint won't be exposed as an action to the client
|
|
1861
|
+
* @deprecated Use path-less endpoints instead
|
|
1862
|
+
*/
|
|
1863
|
+
isAction?: boolean;
|
|
1864
|
+
/**
|
|
1865
|
+
* Defines the places where the endpoint will be available
|
|
1866
|
+
*
|
|
1867
|
+
* Possible options:
|
|
1868
|
+
* - `rpc` - the endpoint is exposed to the router, can be invoked directly and is available to the client
|
|
1869
|
+
* - `server` - the endpoint is exposed to the router, can be invoked directly, but is not available to the client
|
|
1870
|
+
* - `http` - the endpoint is only exposed to the router
|
|
1871
|
+
* @default "rpc"
|
|
1872
|
+
*/
|
|
1873
|
+
scope?: "rpc" | "server" | "http";
|
|
1874
|
+
/**
|
|
1875
|
+
* List of allowed media types (MIME types) for the endpoint
|
|
1876
|
+
*
|
|
1877
|
+
* if provided, only the media types in the list will be allowed to be passed in the body
|
|
1878
|
+
*
|
|
1879
|
+
* @example
|
|
1880
|
+
* ```ts
|
|
1881
|
+
* const endpoint = createEndpoint("/path", {
|
|
1882
|
+
* method: "POST",
|
|
1883
|
+
* allowedMediaTypes: ["application/json", "application/x-www-form-urlencoded"],
|
|
1884
|
+
* }, async(ctx)=>{
|
|
1885
|
+
* const body = ctx.body
|
|
1886
|
+
* })
|
|
1887
|
+
* ```
|
|
1888
|
+
*/
|
|
1889
|
+
allowedMediaTypes?: string[];
|
|
1890
|
+
/**
|
|
1891
|
+
* Extra metadata
|
|
1892
|
+
*/
|
|
1893
|
+
[key: string]: any;
|
|
1894
|
+
};
|
|
1895
|
+
/**
|
|
1896
|
+
* List of middlewares to use
|
|
1897
|
+
*/
|
|
1898
|
+
use?: Middleware[];
|
|
1899
|
+
/**
|
|
1900
|
+
* A callback to run before any API error is throw or returned
|
|
1901
|
+
*
|
|
1902
|
+
* @param e - The API error
|
|
1903
|
+
* @returns - The response to return
|
|
1904
|
+
*/
|
|
1905
|
+
onAPIError?: (e: APIError) => void | Promise<void>;
|
|
1906
|
+
/**
|
|
1907
|
+
* A callback to run before a validation error is thrown
|
|
1908
|
+
* You can customize the validation error message by throwing your own APIError
|
|
1909
|
+
*/
|
|
1910
|
+
onValidationError?: ({ issues, message }: {
|
|
1911
|
+
message: string;
|
|
1912
|
+
issues: readonly StandardSchemaV1$1.Issue[];
|
|
1913
|
+
}) => void | Promise<void>;
|
|
1914
|
+
}
|
|
1915
|
+
type EndpointBodyMethodOptions = {
|
|
1916
|
+
/**
|
|
1917
|
+
* Request Method
|
|
1918
|
+
*/
|
|
1919
|
+
method: "POST" | "PUT" | "DELETE" | "PATCH" | ("POST" | "PUT" | "DELETE" | "PATCH")[];
|
|
1920
|
+
/**
|
|
1921
|
+
* Body Schema
|
|
1922
|
+
*/
|
|
1923
|
+
body?: StandardSchemaV1$1;
|
|
1924
|
+
} | {
|
|
1925
|
+
/**
|
|
1926
|
+
* Request Method
|
|
1927
|
+
*/
|
|
1928
|
+
method: "GET" | "HEAD" | ("GET" | "HEAD")[];
|
|
1929
|
+
/**
|
|
1930
|
+
* Body Schema
|
|
1931
|
+
*/
|
|
1932
|
+
body?: never;
|
|
1933
|
+
} | {
|
|
1934
|
+
/**
|
|
1935
|
+
* Request Method
|
|
1936
|
+
*/
|
|
1937
|
+
method: "*";
|
|
1938
|
+
/**
|
|
1939
|
+
* Body Schema
|
|
1940
|
+
*/
|
|
1941
|
+
body?: StandardSchemaV1$1;
|
|
1942
|
+
} | {
|
|
1943
|
+
/**
|
|
1944
|
+
* Request Method
|
|
1945
|
+
*/
|
|
1946
|
+
method: ("POST" | "PUT" | "DELETE" | "PATCH" | "GET" | "HEAD")[];
|
|
1947
|
+
/**
|
|
1948
|
+
* Body Schema
|
|
1949
|
+
*/
|
|
1950
|
+
body?: StandardSchemaV1$1;
|
|
1951
|
+
};
|
|
1952
|
+
type EndpointOptions = EndpointBaseOptions & EndpointBodyMethodOptions;
|
|
1953
|
+
type Endpoint<Path extends string = string, Options extends EndpointOptions = EndpointOptions, Handler extends (inputCtx: any) => Promise<any> = (inputCtx: any) => Promise<any>> = Handler & {
|
|
1954
|
+
options: Options;
|
|
1955
|
+
path: Path;
|
|
1956
|
+
};
|
|
1957
|
+
interface MiddlewareOptions extends Omit<EndpointOptions, "method"> {
|
|
1958
|
+
}
|
|
1959
|
+
type Middleware<Options extends MiddlewareOptions = MiddlewareOptions, Handler extends (inputCtx: any) => Promise<any> = any> = Handler & {
|
|
1960
|
+
options: Options;
|
|
1961
|
+
};
|
|
1962
|
+
type HTTPMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
|
|
1963
|
+
interface RouterConfig {
|
|
1964
|
+
throwError?: boolean;
|
|
1965
|
+
onError?: (e: unknown) => void | Promise<void> | Response | Promise<Response>;
|
|
1966
|
+
basePath?: string;
|
|
1967
|
+
routerMiddleware?: Array<{
|
|
1968
|
+
path: string;
|
|
1969
|
+
middleware: Middleware;
|
|
1970
|
+
}>;
|
|
1971
|
+
/**
|
|
1972
|
+
* additional Context that needs to passed to endpoints
|
|
1973
|
+
*
|
|
1974
|
+
* this will be available on `ctx.context` on endpoints
|
|
1975
|
+
*/
|
|
1976
|
+
routerContext?: Record<string, any>;
|
|
1977
|
+
/**
|
|
1978
|
+
* A callback to run before any response
|
|
1979
|
+
*/
|
|
1980
|
+
onResponse?: (res: Response) => any | Promise<any>;
|
|
1981
|
+
/**
|
|
1982
|
+
* A callback to run before any request
|
|
1983
|
+
*/
|
|
1984
|
+
onRequest?: (req: Request) => any | Promise<any>;
|
|
1985
|
+
/**
|
|
1986
|
+
* List of allowed media types (MIME types) for the router
|
|
1987
|
+
*
|
|
1988
|
+
* if provided, only the media types in the list will be allowed to be passed in the body.
|
|
1989
|
+
*
|
|
1990
|
+
* If an endpoint has allowed media types, it will override the router's allowed media types.
|
|
1991
|
+
*
|
|
1992
|
+
* @example
|
|
1993
|
+
* ```ts
|
|
1994
|
+
* const router = createRouter({
|
|
1995
|
+
* allowedMediaTypes: ["application/json", "application/x-www-form-urlencoded"],
|
|
1996
|
+
* })
|
|
1997
|
+
*/
|
|
1998
|
+
allowedMediaTypes?: string[];
|
|
1999
|
+
/**
|
|
2000
|
+
* Skip trailing slashes
|
|
2001
|
+
*
|
|
2002
|
+
* @default false
|
|
2003
|
+
*/
|
|
2004
|
+
skipTrailingSlashes?: boolean;
|
|
2005
|
+
/**
|
|
2006
|
+
* Open API route configuration
|
|
2007
|
+
*/
|
|
2008
|
+
openapi?: {
|
|
2009
|
+
/**
|
|
2010
|
+
* Disable openapi route
|
|
2011
|
+
*
|
|
2012
|
+
* @default false
|
|
2013
|
+
*/
|
|
2014
|
+
disabled?: boolean;
|
|
2015
|
+
/**
|
|
2016
|
+
* A path to display open api using scalar
|
|
2017
|
+
*
|
|
2018
|
+
* @default "/api/reference"
|
|
2019
|
+
*/
|
|
2020
|
+
path?: string;
|
|
2021
|
+
/**
|
|
2022
|
+
* Scalar Configuration
|
|
2023
|
+
*/
|
|
2024
|
+
scalar?: {
|
|
2025
|
+
/**
|
|
2026
|
+
* Title
|
|
2027
|
+
* @default "Open API Reference"
|
|
2028
|
+
*/
|
|
2029
|
+
title?: string;
|
|
2030
|
+
/**
|
|
2031
|
+
* Description
|
|
2032
|
+
*
|
|
2033
|
+
* @default "Better Call Open API Reference"
|
|
2034
|
+
*/
|
|
2035
|
+
description?: string;
|
|
2036
|
+
/**
|
|
2037
|
+
* Logo URL
|
|
2038
|
+
*/
|
|
2039
|
+
logo?: string;
|
|
2040
|
+
/**
|
|
2041
|
+
* Scalar theme
|
|
2042
|
+
* @default "saturn"
|
|
2043
|
+
*/
|
|
2044
|
+
theme?: string;
|
|
2045
|
+
};
|
|
2046
|
+
};
|
|
2047
|
+
}
|
|
2048
|
+
declare const createRouter: <E extends Record<string, Endpoint>, Config extends RouterConfig>(endpoints: E, config?: Config) => {
|
|
2049
|
+
handler: (request: Request) => Promise<Response>;
|
|
2050
|
+
endpoints: E;
|
|
2051
|
+
/**
|
|
2052
|
+
* Add a new endpoint to the router.
|
|
2053
|
+
* This is useful if you want to add an endpoint to the router after it has been created.
|
|
2054
|
+
*/
|
|
2055
|
+
addEndpoint: (endpoint: Endpoint) => void;
|
|
2056
|
+
/**
|
|
2057
|
+
* Find a route in the router.
|
|
2058
|
+
* @param method - The HTTP method of the route.
|
|
2059
|
+
* @param path - The path of the route.
|
|
2060
|
+
* @returns The route data and parameters.
|
|
2061
|
+
*/
|
|
2062
|
+
findRoute: (method: string, path: string) => {
|
|
2063
|
+
data: Endpoint & {
|
|
2064
|
+
path: string;
|
|
2065
|
+
};
|
|
2066
|
+
params: Record<string, string>;
|
|
2067
|
+
};
|
|
2068
|
+
/**
|
|
2069
|
+
* Extend the router with new endpoints
|
|
2070
|
+
* @param newEndpoints new endpoints to extend the router with
|
|
2071
|
+
* @returns new router with additional endpoints
|
|
2072
|
+
*/
|
|
2073
|
+
extend: <NE extends Record<string, Endpoint>>(newEndpoints: NE) => {
|
|
2074
|
+
handler: (request: Request) => Promise<Response>;
|
|
2075
|
+
endpoints: E & NE;
|
|
2076
|
+
/**
|
|
2077
|
+
* Add a new endpoint to the router.
|
|
2078
|
+
* This is useful if you want to add an endpoint to the router after it has been created.
|
|
2079
|
+
*/
|
|
2080
|
+
addEndpoint: (endpoint: Endpoint) => void;
|
|
2081
|
+
/**
|
|
2082
|
+
* Find a route in the router.
|
|
2083
|
+
* @param method - The HTTP method of the route.
|
|
2084
|
+
* @param path - The path of the route.
|
|
2085
|
+
* @returns The route data and parameters.
|
|
2086
|
+
*/
|
|
2087
|
+
findRoute: (method: string, path: string) => {
|
|
2088
|
+
data: ((inputCtx: any) => Promise<any>) & {
|
|
2089
|
+
options: EndpointOptions;
|
|
2090
|
+
path: string;
|
|
2091
|
+
} & {
|
|
2092
|
+
path: string;
|
|
2093
|
+
};
|
|
2094
|
+
params: Record<string, string>;
|
|
2095
|
+
};
|
|
2096
|
+
extend: <NE_1 extends Record<string, Endpoint>>(newEndpoints: NE_1) => {
|
|
2097
|
+
handler: (request: Request) => Promise<Response>;
|
|
2098
|
+
endpoints: E & NE & NE_1;
|
|
2099
|
+
/**
|
|
2100
|
+
* Add a new endpoint to the router.
|
|
2101
|
+
* This is useful if you want to add an endpoint to the router after it has been created.
|
|
2102
|
+
*/
|
|
2103
|
+
addEndpoint: (endpoint: Endpoint) => void;
|
|
2104
|
+
/**
|
|
2105
|
+
* Find a route in the router.
|
|
2106
|
+
* @param method - The HTTP method of the route.
|
|
2107
|
+
* @param path - The path of the route.
|
|
2108
|
+
* @returns The route data and parameters.
|
|
2109
|
+
*/
|
|
2110
|
+
findRoute: (method: string, path: string) => {
|
|
2111
|
+
data: ((inputCtx: any) => Promise<any>) & {
|
|
2112
|
+
options: EndpointOptions;
|
|
2113
|
+
path: string;
|
|
2114
|
+
} & {
|
|
2115
|
+
path: string;
|
|
2116
|
+
};
|
|
2117
|
+
params: Record<string, string>;
|
|
2118
|
+
};
|
|
2119
|
+
extend: <NE_2 extends Record<string, Endpoint>>(newEndpoints: NE_2) => {
|
|
2120
|
+
handler: (request: Request) => Promise<Response>;
|
|
2121
|
+
endpoints: E & NE & NE_1 & NE_2;
|
|
2122
|
+
/**
|
|
2123
|
+
* Add a new endpoint to the router.
|
|
2124
|
+
* This is useful if you want to add an endpoint to the router after it has been created.
|
|
2125
|
+
*/
|
|
2126
|
+
addEndpoint: (endpoint: Endpoint) => void;
|
|
2127
|
+
/**
|
|
2128
|
+
* Find a route in the router.
|
|
2129
|
+
* @param method - The HTTP method of the route.
|
|
2130
|
+
* @param path - The path of the route.
|
|
2131
|
+
* @returns The route data and parameters.
|
|
2132
|
+
*/
|
|
2133
|
+
findRoute: (method: string, path: string) => {
|
|
2134
|
+
data: ((inputCtx: any) => Promise<any>) & {
|
|
2135
|
+
options: EndpointOptions;
|
|
2136
|
+
path: string;
|
|
2137
|
+
} & {
|
|
2138
|
+
path: string;
|
|
2139
|
+
};
|
|
2140
|
+
params: Record<string, string>;
|
|
2141
|
+
};
|
|
2142
|
+
extend: <NE_3 extends Record<string, Endpoint>>(newEndpoints: NE_3) => {
|
|
2143
|
+
handler: (request: Request) => Promise<Response>;
|
|
2144
|
+
endpoints: E & NE & NE_1 & NE_2 & NE_3;
|
|
2145
|
+
/**
|
|
2146
|
+
* Add a new endpoint to the router.
|
|
2147
|
+
* This is useful if you want to add an endpoint to the router after it has been created.
|
|
2148
|
+
*/
|
|
2149
|
+
addEndpoint: (endpoint: Endpoint) => void;
|
|
2150
|
+
/**
|
|
2151
|
+
* Find a route in the router.
|
|
2152
|
+
* @param method - The HTTP method of the route.
|
|
2153
|
+
* @param path - The path of the route.
|
|
2154
|
+
* @returns The route data and parameters.
|
|
2155
|
+
*/
|
|
2156
|
+
findRoute: (method: string, path: string) => {
|
|
2157
|
+
data: ((inputCtx: any) => Promise<any>) & {
|
|
2158
|
+
options: EndpointOptions;
|
|
2159
|
+
path: string;
|
|
2160
|
+
} & {
|
|
2161
|
+
path: string;
|
|
2162
|
+
};
|
|
2163
|
+
params: Record<string, string>;
|
|
2164
|
+
};
|
|
2165
|
+
extend: <NE_4 extends Record<string, Endpoint>>(newEndpoints: NE_4) => {
|
|
2166
|
+
handler: (request: Request) => Promise<Response>;
|
|
2167
|
+
endpoints: E & NE & NE_1 & NE_2 & NE_3 & NE_4;
|
|
2168
|
+
/**
|
|
2169
|
+
* Add a new endpoint to the router.
|
|
2170
|
+
* This is useful if you want to add an endpoint to the router after it has been created.
|
|
2171
|
+
*/
|
|
2172
|
+
addEndpoint: (endpoint: Endpoint) => void;
|
|
2173
|
+
/**
|
|
2174
|
+
* Find a route in the router.
|
|
2175
|
+
* @param method - The HTTP method of the route.
|
|
2176
|
+
* @param path - The path of the route.
|
|
2177
|
+
* @returns The route data and parameters.
|
|
2178
|
+
*/
|
|
2179
|
+
findRoute: (method: string, path: string) => {
|
|
2180
|
+
data: ((inputCtx: any) => Promise<any>) & {
|
|
2181
|
+
options: EndpointOptions;
|
|
2182
|
+
path: string;
|
|
2183
|
+
} & {
|
|
2184
|
+
path: string;
|
|
2185
|
+
};
|
|
2186
|
+
params: Record<string, string>;
|
|
2187
|
+
};
|
|
2188
|
+
extend: <NE_5 extends Record<string, Endpoint>>(newEndpoints: NE_5) => {
|
|
2189
|
+
handler: (request: Request) => Promise<Response>;
|
|
2190
|
+
endpoints: E & NE & NE_1 & NE_2 & NE_3 & NE_4 & NE_5;
|
|
2191
|
+
/**
|
|
2192
|
+
* Add a new endpoint to the router.
|
|
2193
|
+
* This is useful if you want to add an endpoint to the router after it has been created.
|
|
2194
|
+
*/
|
|
2195
|
+
addEndpoint: (endpoint: Endpoint) => void;
|
|
2196
|
+
/**
|
|
2197
|
+
* Find a route in the router.
|
|
2198
|
+
* @param method - The HTTP method of the route.
|
|
2199
|
+
* @param path - The path of the route.
|
|
2200
|
+
* @returns The route data and parameters.
|
|
2201
|
+
*/
|
|
2202
|
+
findRoute: (method: string, path: string) => {
|
|
2203
|
+
data: ((inputCtx: any) => Promise<any>) & {
|
|
2204
|
+
options: EndpointOptions;
|
|
2205
|
+
path: string;
|
|
2206
|
+
} & {
|
|
2207
|
+
path: string;
|
|
2208
|
+
};
|
|
2209
|
+
params: Record<string, string>;
|
|
2210
|
+
};
|
|
2211
|
+
extend: <NE_6 extends Record<string, Endpoint>>(newEndpoints: NE_6) => {
|
|
2212
|
+
handler: (request: Request) => Promise<Response>;
|
|
2213
|
+
endpoints: E & NE & NE_1 & NE_2 & NE_3 & NE_4 & NE_5 & NE_6;
|
|
2214
|
+
/**
|
|
2215
|
+
* Add a new endpoint to the router.
|
|
2216
|
+
* This is useful if you want to add an endpoint to the router after it has been created.
|
|
2217
|
+
*/
|
|
2218
|
+
addEndpoint: (endpoint: Endpoint) => void;
|
|
2219
|
+
/**
|
|
2220
|
+
* Find a route in the router.
|
|
2221
|
+
* @param method - The HTTP method of the route.
|
|
2222
|
+
* @param path - The path of the route.
|
|
2223
|
+
* @returns The route data and parameters.
|
|
2224
|
+
*/
|
|
2225
|
+
findRoute: (method: string, path: string) => {
|
|
2226
|
+
data: ((inputCtx: any) => Promise<any>) & {
|
|
2227
|
+
options: EndpointOptions;
|
|
2228
|
+
path: string;
|
|
2229
|
+
} & {
|
|
2230
|
+
path: string;
|
|
2231
|
+
};
|
|
2232
|
+
params: Record<string, string>;
|
|
2233
|
+
};
|
|
2234
|
+
extend: <NE_7 extends Record<string, Endpoint>>(newEndpoints: NE_7) => {
|
|
2235
|
+
handler: (request: Request) => Promise<Response>;
|
|
2236
|
+
endpoints: E & NE & NE_1 & NE_2 & NE_3 & NE_4 & NE_5 & NE_6 & NE_7;
|
|
2237
|
+
/**
|
|
2238
|
+
* Add a new endpoint to the router.
|
|
2239
|
+
* This is useful if you want to add an endpoint to the router after it has been created.
|
|
2240
|
+
*/
|
|
2241
|
+
addEndpoint: (endpoint: Endpoint) => void;
|
|
2242
|
+
/**
|
|
2243
|
+
* Find a route in the router.
|
|
2244
|
+
* @param method - The HTTP method of the route.
|
|
2245
|
+
* @param path - The path of the route.
|
|
2246
|
+
* @returns The route data and parameters.
|
|
2247
|
+
*/
|
|
2248
|
+
findRoute: (method: string, path: string) => {
|
|
2249
|
+
data: ((inputCtx: any) => Promise<any>) & {
|
|
2250
|
+
options: EndpointOptions;
|
|
2251
|
+
path: string;
|
|
2252
|
+
} & {
|
|
2253
|
+
path: string;
|
|
2254
|
+
};
|
|
2255
|
+
params: Record<string, string>;
|
|
2256
|
+
};
|
|
2257
|
+
extend: <NE_8 extends Record<string, Endpoint>>(newEndpoints: NE_8) => {
|
|
2258
|
+
handler: (request: Request) => Promise<Response>;
|
|
2259
|
+
endpoints: E & NE & NE_1 & NE_2 & NE_3 & NE_4 & NE_5 & NE_6 & NE_7 & NE_8;
|
|
2260
|
+
/**
|
|
2261
|
+
* Add a new endpoint to the router.
|
|
2262
|
+
* This is useful if you want to add an endpoint to the router after it has been created.
|
|
2263
|
+
*/
|
|
2264
|
+
addEndpoint: (endpoint: Endpoint) => void;
|
|
2265
|
+
/**
|
|
2266
|
+
* Find a route in the router.
|
|
2267
|
+
* @param method - The HTTP method of the route.
|
|
2268
|
+
* @param path - The path of the route.
|
|
2269
|
+
* @returns The route data and parameters.
|
|
2270
|
+
*/
|
|
2271
|
+
findRoute: (method: string, path: string) => {
|
|
2272
|
+
data: ((inputCtx: any) => Promise<any>) & {
|
|
2273
|
+
options: EndpointOptions;
|
|
2274
|
+
path: string;
|
|
2275
|
+
} & {
|
|
2276
|
+
path: string;
|
|
2277
|
+
};
|
|
2278
|
+
params: Record<string, string>;
|
|
2279
|
+
};
|
|
2280
|
+
extend: <NE_9 extends Record<string, Endpoint>>(newEndpoints: NE_9) => {
|
|
2281
|
+
handler: (request: Request) => Promise<Response>;
|
|
2282
|
+
endpoints: E & NE & NE_1 & NE_2 & NE_3 & NE_4 & NE_5 & NE_6 & NE_7 & NE_8 & NE_9;
|
|
2283
|
+
/**
|
|
2284
|
+
* Add a new endpoint to the router.
|
|
2285
|
+
* This is useful if you want to add an endpoint to the router after it has been created.
|
|
2286
|
+
*/
|
|
2287
|
+
addEndpoint: (endpoint: Endpoint) => void;
|
|
2288
|
+
/**
|
|
2289
|
+
* Find a route in the router.
|
|
2290
|
+
* @param method - The HTTP method of the route.
|
|
2291
|
+
* @param path - The path of the route.
|
|
2292
|
+
* @returns The route data and parameters.
|
|
2293
|
+
*/
|
|
2294
|
+
findRoute: (method: string, path: string) => {
|
|
2295
|
+
data: ((inputCtx: any) => Promise<any>) & {
|
|
2296
|
+
options: EndpointOptions;
|
|
2297
|
+
path: string;
|
|
2298
|
+
} & {
|
|
2299
|
+
path: string;
|
|
2300
|
+
};
|
|
2301
|
+
params: Record<string, string>;
|
|
2302
|
+
};
|
|
2303
|
+
extend: <NE_10 extends Record<string, Endpoint>>(newEndpoints: NE_10) => any;
|
|
2304
|
+
};
|
|
2305
|
+
};
|
|
2306
|
+
};
|
|
2307
|
+
};
|
|
2308
|
+
};
|
|
2309
|
+
};
|
|
2310
|
+
};
|
|
2311
|
+
};
|
|
2312
|
+
};
|
|
2313
|
+
};
|
|
2314
|
+
};
|
|
2315
|
+
type Router = ReturnType<typeof createRouter>;
|
|
2316
|
+
type IsAny<T> = 0 extends 1 & T ? true : false;
|
|
2317
|
+
type IsAnyOrAnyIndexed<T> = IsAny<T> extends true ? true : (string extends keyof T ? true : (number extends keyof T ? (symbol extends keyof T ? true : false) : false));
|
|
2318
|
+
type HasRequired<T extends {
|
|
2319
|
+
body?: any;
|
|
2320
|
+
query?: any;
|
|
2321
|
+
params?: any;
|
|
2322
|
+
}> = T["body"] extends object ? HasRequiredKeys<T["body"]> extends true ? true : T["query"] extends object ? HasRequiredKeys<T["query"]> extends true ? true : T["params"] extends object ? HasRequiredKeys<T["params"]> : false : T["params"] extends object ? HasRequiredKeys<T["params"]> : false : T["query"] extends object ? HasRequiredKeys<T["query"]> extends true ? true : T["params"] extends object ? HasRequiredKeys<T["params"]> : false : T["params"] extends object ? HasRequiredKeys<T["params"]> : false;
|
|
2323
|
+
type InferContext<T> = T extends (ctx: infer Ctx) => any ? Ctx extends object ? Ctx : never : never;
|
|
2324
|
+
type WithRequired<T, K extends keyof any> = Prettify<T & {
|
|
2325
|
+
[P in K & keyof T]-?: NonNullable<T[P]>;
|
|
2326
|
+
}>;
|
|
2327
|
+
type WithoutServerOnly<T extends Record<string, Endpoint>> = {
|
|
2328
|
+
[K in keyof T]: T[K] extends Endpoint<any, infer O> ? O extends {
|
|
2329
|
+
metadata: {
|
|
2330
|
+
SERVER_ONLY: true;
|
|
2331
|
+
};
|
|
2332
|
+
} ? never : T[K] : T[K];
|
|
2333
|
+
};
|
|
2334
|
+
type MethodOptions<API, M extends HTTPMethod> = API extends {
|
|
2335
|
+
[key: string]: infer T;
|
|
2336
|
+
} ? T extends Endpoint<any, infer O> ? O["method"] extends M ? {
|
|
2337
|
+
[key in T["path"]]: T;
|
|
2338
|
+
} : O["method"] extends M[] ? M extends O["method"][number] ? {
|
|
2339
|
+
[key in T["path"]]: T;
|
|
2340
|
+
} : {} : O["method"] extends "*" ? {
|
|
2341
|
+
[key in T["path"]]: T;
|
|
2342
|
+
} : {} : {} : {};
|
|
2343
|
+
type RequiredOptionKeys<C extends {
|
|
2344
|
+
body?: any;
|
|
2345
|
+
query?: any;
|
|
2346
|
+
params?: any;
|
|
2347
|
+
}> = (C["body"] extends object ? HasRequiredKeys<C["body"]> extends true ? {
|
|
2348
|
+
body: true;
|
|
2349
|
+
} : {} : {}) & (C["query"] extends object ? HasRequiredKeys<C["query"]> extends true ? {
|
|
2350
|
+
query: true;
|
|
2351
|
+
} : {} : {}) & (C["params"] extends object ? HasRequiredKeys<C["params"]> extends true ? {
|
|
2352
|
+
params: true;
|
|
2353
|
+
} : {} : {});
|
|
2354
|
+
type CommonHeaders = {
|
|
2355
|
+
accept: "application/json" | "text/plain" | "application/octet-stream";
|
|
2356
|
+
"content-type": "application/json" | "text/plain" | "application/x-www-form-urlencoded" | "multipart/form-data" | "application/octet-stream";
|
|
2357
|
+
authorization: "Bearer" | "Basic";
|
|
2358
|
+
};
|
|
2359
|
+
type FetchRequestOptions<Body = any, Query extends Record<string, any> = any, Params extends Record<string, any> | Array<string> | undefined = any, Res = any, ExtraOptions extends Record<string, any> = {}> = Prettify<ExtraOptions & Omit<RequestInit, "body"> & {
|
|
2360
|
+
/**
|
|
2361
|
+
* Headers
|
|
2362
|
+
*/
|
|
2363
|
+
headers?: CommonHeaders | Headers | HeadersInit;
|
|
2364
|
+
/**
|
|
2365
|
+
* Body
|
|
2366
|
+
*/
|
|
2367
|
+
body?: Body;
|
|
2368
|
+
/**
|
|
2369
|
+
* Query parameters (key-value pairs)
|
|
2370
|
+
*/
|
|
2371
|
+
query?: Query;
|
|
2372
|
+
/**
|
|
2373
|
+
* Dynamic parameters.
|
|
2374
|
+
*
|
|
2375
|
+
* If url is defined as /path/:id, params will be { id: string }
|
|
2376
|
+
*/
|
|
2377
|
+
params?: Params;
|
|
2378
|
+
}>;
|
|
2379
|
+
type FetchResponse<T> = {
|
|
2380
|
+
raw: Response;
|
|
2381
|
+
data: T;
|
|
2382
|
+
headers: Headers;
|
|
2383
|
+
status: number;
|
|
2384
|
+
statusText: string;
|
|
2385
|
+
};
|
|
2386
|
+
type InferredAPI<R> = R extends {
|
|
2387
|
+
endpoints: Record<string, Endpoint>;
|
|
2388
|
+
} ? WithoutServerOnly<R["endpoints"]> : WithoutServerOnly<R & Record<string, Endpoint>>;
|
|
2389
|
+
type InferReturnType<R, OPT, K extends keyof OPT> = IsAnyOrAnyIndexed<R> extends true ? any : Awaited<ReturnType<OPT[K] extends Endpoint ? OPT[K] : never>>;
|
|
2390
|
+
declare class HTTP<R extends Router | Router["endpoints"]> {
|
|
2391
|
+
authToken: string | undefined;
|
|
2392
|
+
options: FetchRequestOptions;
|
|
2393
|
+
private sdk;
|
|
2394
|
+
del: {
|
|
2395
|
+
<API extends InferredAPI<R> = InferredAPI<R>, OPT extends Prettify<UnionToIntersection<MethodOptions<API, "DELETE">>> = UnionToIntersection<MethodOptions<API, "DELETE">> extends infer T ? {
|
|
2396
|
+
[K_1 in keyof T]: T[K_1];
|
|
2397
|
+
} : never, K extends keyof OPT = keyof OPT, C extends InferContext<OPT[K]> = InferContext<OPT[K]>>(path: IsAnyOrAnyIndexed<R> extends true ? string : (HasRequired<C> extends true ? K : never), options: IsAnyOrAnyIndexed<R> extends true ? FetchRequestOptions<any, any, any> : WithRequired<FetchRequestOptions<C["body"], C["query"], C["params"]>, keyof RequiredOptionKeys<C>>): Promise<FetchResponse<InferReturnType<R, OPT, K>>>;
|
|
2398
|
+
<API extends InferredAPI<R> = InferredAPI<R>, OPT extends Prettify<UnionToIntersection<MethodOptions<API, "DELETE">>> = UnionToIntersection<MethodOptions<API, "DELETE">> extends infer T ? {
|
|
2399
|
+
[K_1 in keyof T]: T[K_1];
|
|
2400
|
+
} : never, K extends keyof OPT = keyof OPT, C extends InferContext<OPT[K]> = InferContext<OPT[K]>>(path: IsAnyOrAnyIndexed<R> extends true ? string : (HasRequired<C> extends false ? K : never), options?: IsAnyOrAnyIndexed<R> extends true ? FetchRequestOptions<any, any, any> : FetchRequestOptions<C["body"], C["query"], C["params"]>): Promise<FetchResponse<InferReturnType<R, OPT, K>>>;
|
|
2401
|
+
};
|
|
2402
|
+
constructor(sdk: ColyseusSDK, baseOptions: FetchRequestOptions);
|
|
2403
|
+
private request;
|
|
2404
|
+
get<API extends InferredAPI<R> = InferredAPI<R>, OPT extends Prettify<UnionToIntersection<MethodOptions<API, "GET">>> = Prettify<UnionToIntersection<MethodOptions<API, "GET">>>, K extends keyof OPT = keyof OPT, C extends InferContext<OPT[K]> = InferContext<OPT[K]>>(path: IsAnyOrAnyIndexed<R> extends true ? string : (HasRequired<C> extends true ? K : never), options: IsAnyOrAnyIndexed<R> extends true ? FetchRequestOptions<any, any, any> : WithRequired<FetchRequestOptions<C["body"], C["query"], C["params"]>, keyof RequiredOptionKeys<C>>): Promise<FetchResponse<InferReturnType<R, OPT, K>>>;
|
|
2405
|
+
get<API extends InferredAPI<R> = InferredAPI<R>, OPT extends Prettify<UnionToIntersection<MethodOptions<API, "GET">>> = Prettify<UnionToIntersection<MethodOptions<API, "GET">>>, K extends keyof OPT = keyof OPT, C extends InferContext<OPT[K]> = InferContext<OPT[K]>>(path: IsAnyOrAnyIndexed<R> extends true ? string : (HasRequired<C> extends false ? K : never), options?: IsAnyOrAnyIndexed<R> extends true ? FetchRequestOptions<any, any, any> : FetchRequestOptions<C["body"], C["query"], C["params"]>): Promise<FetchResponse<InferReturnType<R, OPT, K>>>;
|
|
2406
|
+
post<API extends InferredAPI<R> = InferredAPI<R>, OPT extends Prettify<UnionToIntersection<MethodOptions<API, "POST">>> = Prettify<UnionToIntersection<MethodOptions<API, "POST">>>, K extends keyof OPT = keyof OPT, C extends InferContext<OPT[K]> = InferContext<OPT[K]>>(path: (IsAnyOrAnyIndexed<R> extends true ? string : never) | (IsAny<API> extends true ? string : never) | (HasRequired<C> extends true ? K : never), options: IsAnyOrAnyIndexed<R> extends true ? FetchRequestOptions<any, any, any> : (IsAny<API> extends true ? FetchRequestOptions<any, any, any> : WithRequired<FetchRequestOptions<C["body"], C["query"], C["params"]>, keyof RequiredOptionKeys<C>>)): Promise<FetchResponse<InferReturnType<R, OPT, K>>>;
|
|
2407
|
+
post<API extends InferredAPI<R> = InferredAPI<R>, OPT extends Prettify<UnionToIntersection<MethodOptions<API, "POST">>> = Prettify<UnionToIntersection<MethodOptions<API, "POST">>>, K extends keyof OPT = keyof OPT, C extends InferContext<OPT[K]> = InferContext<OPT[K]>>(path: (IsAnyOrAnyIndexed<R> extends true ? string : never) | (IsAny<API> extends true ? string : never) | (HasRequired<C> extends false ? K : never), options?: IsAnyOrAnyIndexed<R> extends true ? FetchRequestOptions<any, any, any> : (IsAny<API> extends true ? FetchRequestOptions<any, any, any> : FetchRequestOptions<C["body"], C["query"], C["params"]>)): Promise<FetchResponse<InferReturnType<R, OPT, K>>>;
|
|
2408
|
+
delete<API extends InferredAPI<R> = InferredAPI<R>, OPT extends Prettify<UnionToIntersection<MethodOptions<API, "DELETE">>> = Prettify<UnionToIntersection<MethodOptions<API, "DELETE">>>, K extends keyof OPT = keyof OPT, C extends InferContext<OPT[K]> = InferContext<OPT[K]>>(path: IsAnyOrAnyIndexed<R> extends true ? string : (HasRequired<C> extends true ? K : never), options: IsAnyOrAnyIndexed<R> extends true ? FetchRequestOptions<any, any, any> : WithRequired<FetchRequestOptions<C["body"], C["query"], C["params"]>, keyof RequiredOptionKeys<C>>): Promise<FetchResponse<InferReturnType<R, OPT, K>>>;
|
|
2409
|
+
delete<API extends InferredAPI<R> = InferredAPI<R>, OPT extends Prettify<UnionToIntersection<MethodOptions<API, "DELETE">>> = Prettify<UnionToIntersection<MethodOptions<API, "DELETE">>>, K extends keyof OPT = keyof OPT, C extends InferContext<OPT[K]> = InferContext<OPT[K]>>(path: IsAnyOrAnyIndexed<R> extends true ? string : (HasRequired<C> extends false ? K : never), options?: IsAnyOrAnyIndexed<R> extends true ? FetchRequestOptions<any, any, any> : FetchRequestOptions<C["body"], C["query"], C["params"]>): Promise<FetchResponse<InferReturnType<R, OPT, K>>>;
|
|
2410
|
+
patch<API extends InferredAPI<R> = InferredAPI<R>, OPT extends Prettify<UnionToIntersection<MethodOptions<API, "PATCH">>> = Prettify<UnionToIntersection<MethodOptions<API, "PATCH">>>, K extends keyof OPT = keyof OPT, C extends InferContext<OPT[K]> = InferContext<OPT[K]>>(path: IsAnyOrAnyIndexed<R> extends true ? string : (HasRequired<C> extends true ? K : never), options: IsAnyOrAnyIndexed<R> extends true ? FetchRequestOptions<any, any, any> : WithRequired<FetchRequestOptions<C["body"], C["query"], C["params"]>, keyof RequiredOptionKeys<C>>): Promise<FetchResponse<InferReturnType<R, OPT, K>>>;
|
|
2411
|
+
patch<API extends InferredAPI<R> = InferredAPI<R>, OPT extends Prettify<UnionToIntersection<MethodOptions<API, "PATCH">>> = Prettify<UnionToIntersection<MethodOptions<API, "PATCH">>>, K extends keyof OPT = keyof OPT, C extends InferContext<OPT[K]> = InferContext<OPT[K]>>(path: IsAnyOrAnyIndexed<R> extends true ? string : (HasRequired<C> extends false ? K : never), options?: IsAnyOrAnyIndexed<R> extends true ? FetchRequestOptions<any, any, any> : FetchRequestOptions<C["body"], C["query"], C["params"]>): Promise<FetchResponse<InferReturnType<R, OPT, K>>>;
|
|
2412
|
+
put<API extends InferredAPI<R> = InferredAPI<R>, OPT extends Prettify<UnionToIntersection<MethodOptions<API, "PUT">>> = Prettify<UnionToIntersection<MethodOptions<API, "PUT">>>, K extends keyof OPT = keyof OPT, C extends InferContext<OPT[K]> = InferContext<OPT[K]>>(path: IsAnyOrAnyIndexed<R> extends true ? string : (HasRequired<C> extends true ? K : never), options: IsAnyOrAnyIndexed<R> extends true ? FetchRequestOptions<any, any, any> : WithRequired<FetchRequestOptions<C["body"], C["query"], C["params"]>, keyof RequiredOptionKeys<C>>): Promise<FetchResponse<InferReturnType<R, OPT, K>>>;
|
|
2413
|
+
put<API extends InferredAPI<R> = InferredAPI<R>, OPT extends Prettify<UnionToIntersection<MethodOptions<API, "PUT">>> = Prettify<UnionToIntersection<MethodOptions<API, "PUT">>>, K extends keyof OPT = keyof OPT, C extends InferContext<OPT[K]> = InferContext<OPT[K]>>(path: IsAnyOrAnyIndexed<R> extends true ? string : (HasRequired<C> extends false ? K : never), options?: IsAnyOrAnyIndexed<R> extends true ? FetchRequestOptions<any, any, any> : FetchRequestOptions<C["body"], C["query"], C["params"]>): Promise<FetchResponse<InferReturnType<R, OPT, K>>>;
|
|
2414
|
+
protected executeRequest<M extends HTTPMethod>(method: M, path: any, requestOptions?: any): Promise<any>;
|
|
2415
|
+
}
|
|
2416
|
+
export interface AuthSettings {
|
|
2417
|
+
path: string;
|
|
2418
|
+
key: string;
|
|
2419
|
+
}
|
|
2420
|
+
export interface PopupSettings {
|
|
2421
|
+
prefix: string;
|
|
2422
|
+
width: number;
|
|
2423
|
+
height: number;
|
|
2424
|
+
}
|
|
2425
|
+
/**
|
|
2426
|
+
* Response from getUserData()
|
|
2427
|
+
*/
|
|
2428
|
+
export interface UserDataResponse<UserData = any> {
|
|
2429
|
+
user: UserData;
|
|
2430
|
+
}
|
|
2431
|
+
/**
|
|
2432
|
+
* Response from authentication methods (login, register, anonymous, OAuth)
|
|
2433
|
+
*/
|
|
2434
|
+
export interface AuthResponse<UserData = any> {
|
|
2435
|
+
user: UserData;
|
|
2436
|
+
token: string;
|
|
2437
|
+
}
|
|
2438
|
+
/**
|
|
2439
|
+
* Response from sendPasswordResetEmail()
|
|
2440
|
+
*/
|
|
2441
|
+
export type ForgotPasswordResponse = boolean | unknown;
|
|
2442
|
+
/**
|
|
2443
|
+
* @deprecated Use AuthResponse instead
|
|
2444
|
+
*/
|
|
2445
|
+
export type AuthData<UserData = any> = AuthResponse<UserData>;
|
|
2446
|
+
export declare class Auth<UserData = any> {
|
|
2447
|
+
#private;
|
|
2448
|
+
settings: AuthSettings;
|
|
2449
|
+
protected http: HTTP<any>;
|
|
2450
|
+
constructor(http: HTTP<any>);
|
|
2451
|
+
set token(token: string);
|
|
2452
|
+
get token(): string | undefined;
|
|
2453
|
+
onChange<U = UserData>(callback: (response: AuthResponse<U | null>) => void): () => void;
|
|
2454
|
+
getUserData<U = UserData>(): Promise<UserDataResponse<U>>;
|
|
2455
|
+
registerWithEmailAndPassword<U = UserData>(email: string, password: string, options?: any): Promise<AuthResponse<U>>;
|
|
2456
|
+
signInWithEmailAndPassword<U = UserData>(email: string, password: string): Promise<AuthResponse<U>>;
|
|
2457
|
+
signInAnonymously<U = UserData>(options?: any): Promise<AuthResponse<U>>;
|
|
2458
|
+
sendPasswordResetEmail(email: string): Promise<ForgotPasswordResponse>;
|
|
2459
|
+
signInWithProvider<U = UserData>(providerName: string, settings?: Partial<PopupSettings>): Promise<AuthResponse<U>>;
|
|
2460
|
+
signOut(): Promise<void>;
|
|
2461
|
+
private emitChange;
|
|
2462
|
+
}
|
|
2463
|
+
export type JoinOptions = any;
|
|
2464
|
+
export interface EndpointSettings {
|
|
2465
|
+
hostname: string;
|
|
2466
|
+
secure: boolean;
|
|
2467
|
+
port?: number;
|
|
2468
|
+
pathname?: string;
|
|
2469
|
+
searchParams?: string;
|
|
2470
|
+
protocol?: "ws" | "h3";
|
|
2471
|
+
}
|
|
2472
|
+
export interface ClientOptions {
|
|
2473
|
+
headers?: {
|
|
2474
|
+
[id: string]: string;
|
|
2475
|
+
};
|
|
2476
|
+
urlBuilder?: (url: URL) => string;
|
|
2477
|
+
protocol?: "ws" | "h3";
|
|
2478
|
+
}
|
|
2479
|
+
interface LatencyOptions {
|
|
2480
|
+
/** "ws" for WebSocket, "h3" for WebTransport (default: "ws") */
|
|
2481
|
+
protocol?: "ws" | "h3";
|
|
2482
|
+
/** Number of pings to send (default: 1). Returns the average latency when > 1. */
|
|
2483
|
+
pingCount?: number;
|
|
2484
|
+
}
|
|
2485
|
+
export declare class ColyseusSDK<ServerType extends SDKTypes = any, UserData = any> {
|
|
2486
|
+
static VERSION: string;
|
|
2487
|
+
/**
|
|
2488
|
+
* The HTTP client to make requests to the server.
|
|
2489
|
+
*/
|
|
2490
|
+
http: HTTP<ServerType["~routes"]>;
|
|
2491
|
+
/**
|
|
2492
|
+
* The authentication module to authenticate into requests and rooms.
|
|
2493
|
+
*/
|
|
2494
|
+
auth: Auth<UserData>;
|
|
2495
|
+
/**
|
|
2496
|
+
* The settings used to connect to the server.
|
|
2497
|
+
*/
|
|
2498
|
+
settings: EndpointSettings;
|
|
2499
|
+
protected urlBuilder: (url: URL) => string;
|
|
2500
|
+
constructor(settings?: string | EndpointSettings, options?: ClientOptions);
|
|
2501
|
+
/**
|
|
2502
|
+
* Select the endpoint with the lowest latency.
|
|
2503
|
+
* @param endpoints Array of endpoints to select from.
|
|
2504
|
+
* @param options Client options.
|
|
2505
|
+
* @param latencyOptions Latency measurement options (protocol, pingCount).
|
|
2506
|
+
* @returns The client with the lowest latency.
|
|
2507
|
+
*/
|
|
2508
|
+
static selectByLatency<ServerType extends SDKTypes = any, UserData = any>(endpoints: Array<string | EndpointSettings>, options?: ClientOptions, latencyOptions?: LatencyOptions): Promise<ColyseusSDK<ServerType, UserData>>;
|
|
2509
|
+
joinOrCreate<R extends keyof ServerType["~rooms"], State = InferState<ServerType["~rooms"][R]["~room"], never>>(roomName: R, options?: Parameters<ServerType["~rooms"][R]["~room"]["onJoin"]>[1], rootSchema?: SchemaConstructor<State>): Promise<Room<ServerType["~rooms"][R]["~room"], State>>;
|
|
2510
|
+
joinOrCreate<RoomType extends ServerRoomLike>(roomName: string, options?: Parameters<NonNullable<RoomType["onJoin"]>>[1], rootSchema?: SchemaConstructor<RoomType["state"]>): Promise<Room<RoomType, RoomType["state"]>>;
|
|
2511
|
+
joinOrCreate<State = any>(roomName: string, options?: JoinOptions, rootSchema?: SchemaConstructor<State>): Promise<Room<any, State>>;
|
|
2512
|
+
create<R extends keyof ServerType["~rooms"], State = InferState<ServerType["~rooms"][R]["~room"], never>>(roomName: R, options?: Parameters<ServerType["~rooms"][R]["~room"]["onJoin"]>[1], rootSchema?: SchemaConstructor<State>): Promise<Room<ServerType["~rooms"][R]["~room"], State>>;
|
|
2513
|
+
create<RoomType extends ServerRoomLike>(roomName: string, options?: Parameters<NonNullable<RoomType["onJoin"]>>[1], rootSchema?: SchemaConstructor<RoomType["state"]>): Promise<Room<RoomType, RoomType["state"]>>;
|
|
2514
|
+
create<State = any>(roomName: string, options?: JoinOptions, rootSchema?: SchemaConstructor<State>): Promise<Room<any, State>>;
|
|
2515
|
+
join<R extends keyof ServerType["~rooms"], State = InferState<ServerType["~rooms"][R]["~room"], never>>(roomName: R, options?: Parameters<ServerType["~rooms"][R]["~room"]["onJoin"]>[1], rootSchema?: SchemaConstructor<State>): Promise<Room<ServerType["~rooms"][R]["~room"], State>>;
|
|
2516
|
+
join<RoomType extends ServerRoomLike>(roomName: string, options?: Parameters<NonNullable<RoomType["onJoin"]>>[1], rootSchema?: SchemaConstructor<RoomType["state"]>): Promise<Room<RoomType, RoomType["state"]>>;
|
|
2517
|
+
join<State = any>(roomName: string, options?: JoinOptions, rootSchema?: SchemaConstructor<State>): Promise<Room<any, State>>;
|
|
2518
|
+
joinById<R extends keyof ServerType["~rooms"], State = InferState<ServerType["~rooms"][R]["~room"], never>>(roomName: R, options?: Parameters<ServerType["~rooms"][R]["~room"]["onJoin"]>[1], rootSchema?: SchemaConstructor<State>): Promise<Room<ServerType["~rooms"][R]["~room"], State>>;
|
|
2519
|
+
joinById<RoomType extends ServerRoomLike>(roomId: string, options?: Parameters<NonNullable<RoomType["onJoin"]>>[1], rootSchema?: SchemaConstructor<RoomType["state"]>): Promise<Room<RoomType, RoomType["state"]>>;
|
|
2520
|
+
joinById<State = any>(roomId: string, options?: JoinOptions, rootSchema?: SchemaConstructor<State>): Promise<Room<any, State>>;
|
|
2521
|
+
/**
|
|
2522
|
+
* Re-establish connection with a room this client was previously connected to.
|
|
2523
|
+
*
|
|
2524
|
+
* @param reconnectionToken The `room.reconnectionToken` from previously connected room.
|
|
2525
|
+
* @param rootSchema (optional) Concrete root schema definition
|
|
2526
|
+
* @returns Promise<Room>
|
|
2527
|
+
*/
|
|
2528
|
+
reconnect<R extends keyof ServerType["~rooms"]>(reconnectionToken: string, roomName?: R): Promise<Room<ServerType["~rooms"][R]["~room"]>>;
|
|
2529
|
+
reconnect<RoomType extends ServerRoomLike>(reconnectionToken: string, rootSchema?: SchemaConstructor<RoomType["state"]>): Promise<Room<RoomType, RoomType["state"]>>;
|
|
2530
|
+
reconnect<State = any>(reconnectionToken: string, rootSchema?: SchemaConstructor<State>): Promise<Room<any, State>>;
|
|
2531
|
+
consumeSeatReservation<T>(response: ISeatReservation, rootSchema?: SchemaConstructor<T>): Promise<Room<any, T>>;
|
|
2532
|
+
/**
|
|
2533
|
+
* Create a new connection with the server, and measure the latency.
|
|
2534
|
+
* @param options Latency measurement options (protocol, pingCount).
|
|
2535
|
+
*/
|
|
2536
|
+
getLatency(options?: LatencyOptions): Promise<number>;
|
|
2537
|
+
protected createMatchMakeRequest<T>(method: string, roomName: string, options?: JoinOptions, rootSchema?: SchemaConstructor<T>): Promise<Room<any, T>>;
|
|
2538
|
+
protected createRoom<T>(roomName: string, rootSchema?: SchemaConstructor<T>): Room<any, T>;
|
|
2539
|
+
protected buildEndpoint(seatReservation: ISeatReservation, options?: any): string;
|
|
2540
|
+
protected getHttpEndpoint(segments?: string): string;
|
|
2541
|
+
protected getEndpointPort(): string;
|
|
2542
|
+
}
|
|
2543
|
+
export declare const Client: typeof ColyseusSDK;
|
|
2544
|
+
export type Client<ServerType extends SDKTypes = any, UserData = any> = InstanceType<typeof ColyseusSDK<ServerType, UserData>>;
|
|
2545
|
+
export declare class ServerError<DATA = any> extends Error {
|
|
2546
|
+
code: number;
|
|
2547
|
+
headers?: Headers;
|
|
2548
|
+
status?: number;
|
|
2549
|
+
response?: Response;
|
|
2550
|
+
data?: DATA;
|
|
2551
|
+
constructor(code: number, message: string, opts?: {
|
|
2552
|
+
headers?: Headers;
|
|
2553
|
+
status?: number;
|
|
2554
|
+
response?: Response;
|
|
2555
|
+
data?: any;
|
|
2556
|
+
});
|
|
2557
|
+
}
|
|
2558
|
+
export declare class AbortError extends Error {
|
|
2559
|
+
constructor(message: string);
|
|
2560
|
+
}
|
|
2561
|
+
export declare class MatchMakeError extends Error {
|
|
2562
|
+
code: number;
|
|
2563
|
+
constructor(message: string, code: number);
|
|
2564
|
+
}
|
|
2565
|
+
declare class Delayed {
|
|
2566
|
+
active: boolean;
|
|
2567
|
+
paused: boolean;
|
|
2568
|
+
time: number;
|
|
2569
|
+
elapsedTime: number;
|
|
2570
|
+
protected handler: Function;
|
|
2571
|
+
protected args: any;
|
|
2572
|
+
protected type: number;
|
|
2573
|
+
constructor(handler: Function, args: any, time: number, type: number);
|
|
2574
|
+
tick(deltaTime: number): void;
|
|
2575
|
+
execute(): void;
|
|
2576
|
+
reset(): void;
|
|
2577
|
+
pause(): void;
|
|
2578
|
+
resume(): void;
|
|
2579
|
+
clear(): void;
|
|
2580
|
+
}
|
|
2581
|
+
declare class Clock {
|
|
2582
|
+
running: boolean;
|
|
2583
|
+
deltaTime: number;
|
|
2584
|
+
currentTime: number;
|
|
2585
|
+
elapsedTime: number;
|
|
2586
|
+
protected now: Function;
|
|
2587
|
+
protected _interval: any;
|
|
2588
|
+
constructor(useInterval?: boolean);
|
|
2589
|
+
start(useInterval?: boolean): void;
|
|
2590
|
+
stop(): void;
|
|
2591
|
+
tick(newTime?: any): void;
|
|
2592
|
+
}
|
|
2593
|
+
declare class ClockTimer extends Clock {
|
|
2594
|
+
/**
|
|
2595
|
+
* An array of all the scheduled timeouts and intervals.
|
|
2596
|
+
* @private For compatibility it's public but avoid modifying it directly.
|
|
2597
|
+
*/
|
|
2598
|
+
delayed: Delayed[];
|
|
2599
|
+
constructor(autoStart?: boolean);
|
|
2600
|
+
/**
|
|
2601
|
+
* Re-evaluate all the scheduled timeouts and intervals and execute appropriate handlers.
|
|
2602
|
+
* Use this in your own context or not if your passed `autoStart` as `true` in the constructor.
|
|
2603
|
+
*/
|
|
2604
|
+
tick(): void;
|
|
2605
|
+
/**
|
|
2606
|
+
* Schedule a function to be called every `time` milliseconds.
|
|
2607
|
+
* This `time` minimum value will be tied to the `tick` method of the clock. This means if you use the default `autoStart` value from the constructor, the minimum value will be 16ms. Otherwise it will depend on your `tick` method call.
|
|
2608
|
+
*
|
|
2609
|
+
* Returns a {@link Delayed} object that can be used to clear the timeout or play around with it.
|
|
2610
|
+
*/
|
|
2611
|
+
setInterval(handler: Function, time: number, ...args: any[]): Delayed;
|
|
2612
|
+
/**
|
|
2613
|
+
* Schedule a function to be called after a delay.
|
|
2614
|
+
*
|
|
2615
|
+
* This `time` minimum value will be tied to the `tick` method of the clock. This means if you use the default `autoStart` value from the constructor, the minimum value will be 16ms. Otherwise it will depend on your `tick` method call.
|
|
2616
|
+
*
|
|
2617
|
+
* Returns a {@link Delayed} object that can be used to clear the timeout or play around with it.
|
|
2618
|
+
*/
|
|
2619
|
+
setTimeout(handler: Function, time: number, ...args: any[]): Delayed;
|
|
2620
|
+
/**
|
|
2621
|
+
* A promise that schedule a timeout that will resolves after the given time.
|
|
2622
|
+
*
|
|
2623
|
+
* If the {@link Delayed} instance is cleared before the time, the promise will be rejected. This happens when the {@link ClockTimer.clear} method is called.
|
|
2624
|
+
*
|
|
2625
|
+
* For the sake of simplicity of this API, you can only cancel a timeout scheduled with this method with {@link ClockTimer.clear} method (which clears all scheduled timeouts and intervals).
|
|
2626
|
+
* If you need fine-tuned control over the timeout, use the {@link ClockTimer.setTimeout} method instead.
|
|
2627
|
+
*
|
|
2628
|
+
* @example **Inside an async function**
|
|
2629
|
+
* ```typescript
|
|
2630
|
+
* const timer = new Clock(true);
|
|
2631
|
+
* await timer.duration(1000);
|
|
2632
|
+
* console.log("1 second later");
|
|
2633
|
+
* ```
|
|
2634
|
+
*
|
|
2635
|
+
* @example **Using the promise**
|
|
2636
|
+
* ```typescript
|
|
2637
|
+
* const timer = new Clock(true);
|
|
2638
|
+
* timer.duration(1000).then(() => console.log("1 second later"));
|
|
2639
|
+
* ```
|
|
2640
|
+
*
|
|
2641
|
+
* @example **Using the promise with error**
|
|
2642
|
+
* ```typescript
|
|
2643
|
+
* const timer = new Clock(true);
|
|
2644
|
+
* timer.duration(1000).then(() => console.log("1 second later")).catch(() => console.log("Timer cleared"));
|
|
2645
|
+
* timer.clear();
|
|
2646
|
+
* ```
|
|
2647
|
+
*
|
|
2648
|
+
*
|
|
2649
|
+
* @param ms the duration in milliseconds in which the promise will be resolved
|
|
2650
|
+
*/
|
|
2651
|
+
duration(ms: number): Promise<void>;
|
|
2652
|
+
/**
|
|
2653
|
+
* Delete any scheduled timeout or interval. That will never be executed.
|
|
2654
|
+
*
|
|
2655
|
+
* If some of the timeouts/intervals are already executed, they will be removed from the list and callback will be garbage collected.
|
|
2656
|
+
* For timeout created with {@link ClockTimer.duration}, the promise will be rejected and therefore the unused resolving callback will be garbage collected.
|
|
2657
|
+
*/
|
|
2658
|
+
clear(): void;
|
|
2659
|
+
}
|
|
2660
|
+
interface EventEmitterOptions {
|
|
2661
|
+
/**
|
|
2662
|
+
* Enables automatic capturing of promise rejection.
|
|
2663
|
+
*/
|
|
2664
|
+
captureRejections?: boolean | undefined;
|
|
2665
|
+
}
|
|
2666
|
+
interface StaticEventEmitterOptions {
|
|
2667
|
+
/**
|
|
2668
|
+
* Can be used to cancel awaiting events.
|
|
2669
|
+
*/
|
|
2670
|
+
signal?: AbortSignal | undefined;
|
|
2671
|
+
}
|
|
2672
|
+
interface StaticEventEmitterIteratorOptions extends StaticEventEmitterOptions {
|
|
2673
|
+
/**
|
|
2674
|
+
* Names of events that will end the iteration.
|
|
2675
|
+
*/
|
|
2676
|
+
close?: string[] | undefined;
|
|
2677
|
+
/**
|
|
2678
|
+
* The high watermark. The emitter is paused every time the size of events being buffered is higher than it.
|
|
2679
|
+
* Supported only on emitters implementing `pause()` and `resume()` methods.
|
|
2680
|
+
* @default Number.MAX_SAFE_INTEGER
|
|
2681
|
+
*/
|
|
2682
|
+
highWaterMark?: number | undefined;
|
|
2683
|
+
/**
|
|
2684
|
+
* The low watermark. The emitter is resumed every time the size of events being buffered is lower than it.
|
|
2685
|
+
* Supported only on emitters implementing `pause()` and `resume()` methods.
|
|
2686
|
+
* @default 1
|
|
2687
|
+
*/
|
|
2688
|
+
lowWaterMark?: number | undefined;
|
|
2689
|
+
}
|
|
2690
|
+
interface EventEmitter$1<T extends EventMap<T> = DefaultEventMap> extends NodeJS.EventEmitter<T> {
|
|
2691
|
+
}
|
|
2692
|
+
type EventMap<T> = Record<keyof T, any[]> | DefaultEventMap;
|
|
2693
|
+
type DefaultEventMap = [
|
|
2694
|
+
never
|
|
2695
|
+
];
|
|
2696
|
+
type AnyRest = [
|
|
2697
|
+
...args: any[]
|
|
2698
|
+
];
|
|
2699
|
+
type Args<K, T> = T extends DefaultEventMap ? AnyRest : (K extends keyof T ? T[K] : never);
|
|
2700
|
+
type Key<K, T> = T extends DefaultEventMap ? string | symbol : K | keyof T;
|
|
2701
|
+
declare class EventEmitter$1<T extends EventMap<T> = DefaultEventMap> {
|
|
2702
|
+
constructor(options?: EventEmitterOptions);
|
|
2703
|
+
[EventEmitter$1.captureRejectionSymbol]?<K>(error: Error, event: Key<K, T>, ...args: Args<K, T>): void;
|
|
2704
|
+
/**
|
|
2705
|
+
* Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given
|
|
2706
|
+
* event or that is rejected if the `EventEmitter` emits `'error'` while waiting.
|
|
2707
|
+
* The `Promise` will resolve with an array of all the arguments emitted to the
|
|
2708
|
+
* given event.
|
|
2709
|
+
*
|
|
2710
|
+
* This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event
|
|
2711
|
+
* semantics and does not listen to the `'error'` event.
|
|
2712
|
+
*
|
|
2713
|
+
* ```js
|
|
2714
|
+
* import { once, EventEmitter } from 'node:events';
|
|
2715
|
+
* import process from 'node:process';
|
|
2716
|
+
*
|
|
2717
|
+
* const ee = new EventEmitter();
|
|
2718
|
+
*
|
|
2719
|
+
* process.nextTick(() => {
|
|
2720
|
+
* ee.emit('myevent', 42);
|
|
2721
|
+
* });
|
|
2722
|
+
*
|
|
2723
|
+
* const [value] = await once(ee, 'myevent');
|
|
2724
|
+
* console.log(value);
|
|
2725
|
+
*
|
|
2726
|
+
* const err = new Error('kaboom');
|
|
2727
|
+
* process.nextTick(() => {
|
|
2728
|
+
* ee.emit('error', err);
|
|
2729
|
+
* });
|
|
2730
|
+
*
|
|
2731
|
+
* try {
|
|
2732
|
+
* await once(ee, 'myevent');
|
|
2733
|
+
* } catch (err) {
|
|
2734
|
+
* console.error('error happened', err);
|
|
2735
|
+
* }
|
|
2736
|
+
* ```
|
|
2737
|
+
*
|
|
2738
|
+
* The special handling of the `'error'` event is only used when `events.once()` is used to wait for another event. If `events.once()` is used to wait for the
|
|
2739
|
+
* '`error'` event itself, then it is treated as any other kind of event without
|
|
2740
|
+
* special handling:
|
|
2741
|
+
*
|
|
2742
|
+
* ```js
|
|
2743
|
+
* import { EventEmitter, once } from 'node:events';
|
|
2744
|
+
*
|
|
2745
|
+
* const ee = new EventEmitter();
|
|
2746
|
+
*
|
|
2747
|
+
* once(ee, 'error')
|
|
2748
|
+
* .then(([err]) => console.log('ok', err.message))
|
|
2749
|
+
* .catch((err) => console.error('error', err.message));
|
|
2750
|
+
*
|
|
2751
|
+
* ee.emit('error', new Error('boom'));
|
|
2752
|
+
*
|
|
2753
|
+
* // Prints: ok boom
|
|
2754
|
+
* ```
|
|
2755
|
+
*
|
|
2756
|
+
* An `AbortSignal` can be used to cancel waiting for the event:
|
|
2757
|
+
*
|
|
2758
|
+
* ```js
|
|
2759
|
+
* import { EventEmitter, once } from 'node:events';
|
|
2760
|
+
*
|
|
2761
|
+
* const ee = new EventEmitter();
|
|
2762
|
+
* const ac = new AbortController();
|
|
2763
|
+
*
|
|
2764
|
+
* async function foo(emitter, event, signal) {
|
|
2765
|
+
* try {
|
|
2766
|
+
* await once(emitter, event, { signal });
|
|
2767
|
+
* console.log('event emitted!');
|
|
2768
|
+
* } catch (error) {
|
|
2769
|
+
* if (error.name === 'AbortError') {
|
|
2770
|
+
* console.error('Waiting for the event was canceled!');
|
|
2771
|
+
* } else {
|
|
2772
|
+
* console.error('There was an error', error.message);
|
|
2773
|
+
* }
|
|
2774
|
+
* }
|
|
2775
|
+
* }
|
|
2776
|
+
*
|
|
2777
|
+
* foo(ee, 'foo', ac.signal);
|
|
2778
|
+
* ac.abort(); // Abort waiting for the event
|
|
2779
|
+
* ee.emit('foo'); // Prints: Waiting for the event was canceled!
|
|
2780
|
+
* ```
|
|
2781
|
+
* @since v11.13.0, v10.16.0
|
|
2782
|
+
*/
|
|
2783
|
+
static once(emitter: NodeJS.EventEmitter, eventName: string | symbol, options?: StaticEventEmitterOptions): Promise<any[]>;
|
|
2784
|
+
static once(emitter: EventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise<any[]>;
|
|
2785
|
+
/**
|
|
2786
|
+
* ```js
|
|
2787
|
+
* import { on, EventEmitter } from 'node:events';
|
|
2788
|
+
* import process from 'node:process';
|
|
2789
|
+
*
|
|
2790
|
+
* const ee = new EventEmitter();
|
|
2791
|
+
*
|
|
2792
|
+
* // Emit later on
|
|
2793
|
+
* process.nextTick(() => {
|
|
2794
|
+
* ee.emit('foo', 'bar');
|
|
2795
|
+
* ee.emit('foo', 42);
|
|
2796
|
+
* });
|
|
2797
|
+
*
|
|
2798
|
+
* for await (const event of on(ee, 'foo')) {
|
|
2799
|
+
* // The execution of this inner block is synchronous and it
|
|
2800
|
+
* // processes one event at a time (even with await). Do not use
|
|
2801
|
+
* // if concurrent execution is required.
|
|
2802
|
+
* console.log(event); // prints ['bar'] [42]
|
|
2803
|
+
* }
|
|
2804
|
+
* // Unreachable here
|
|
2805
|
+
* ```
|
|
2806
|
+
*
|
|
2807
|
+
* Returns an `AsyncIterator` that iterates `eventName` events. It will throw
|
|
2808
|
+
* if the `EventEmitter` emits `'error'`. It removes all listeners when
|
|
2809
|
+
* exiting the loop. The `value` returned by each iteration is an array
|
|
2810
|
+
* composed of the emitted event arguments.
|
|
2811
|
+
*
|
|
2812
|
+
* An `AbortSignal` can be used to cancel waiting on events:
|
|
2813
|
+
*
|
|
2814
|
+
* ```js
|
|
2815
|
+
* import { on, EventEmitter } from 'node:events';
|
|
2816
|
+
* import process from 'node:process';
|
|
2817
|
+
*
|
|
2818
|
+
* const ac = new AbortController();
|
|
2819
|
+
*
|
|
2820
|
+
* (async () => {
|
|
2821
|
+
* const ee = new EventEmitter();
|
|
2822
|
+
*
|
|
2823
|
+
* // Emit later on
|
|
2824
|
+
* process.nextTick(() => {
|
|
2825
|
+
* ee.emit('foo', 'bar');
|
|
2826
|
+
* ee.emit('foo', 42);
|
|
2827
|
+
* });
|
|
2828
|
+
*
|
|
2829
|
+
* for await (const event of on(ee, 'foo', { signal: ac.signal })) {
|
|
2830
|
+
* // The execution of this inner block is synchronous and it
|
|
2831
|
+
* // processes one event at a time (even with await). Do not use
|
|
2832
|
+
* // if concurrent execution is required.
|
|
2833
|
+
* console.log(event); // prints ['bar'] [42]
|
|
2834
|
+
* }
|
|
2835
|
+
* // Unreachable here
|
|
2836
|
+
* })();
|
|
2837
|
+
*
|
|
2838
|
+
* process.nextTick(() => ac.abort());
|
|
2839
|
+
* ```
|
|
2840
|
+
*
|
|
2841
|
+
* Use the `close` option to specify an array of event names that will end the iteration:
|
|
2842
|
+
*
|
|
2843
|
+
* ```js
|
|
2844
|
+
* import { on, EventEmitter } from 'node:events';
|
|
2845
|
+
* import process from 'node:process';
|
|
2846
|
+
*
|
|
2847
|
+
* const ee = new EventEmitter();
|
|
2848
|
+
*
|
|
2849
|
+
* // Emit later on
|
|
2850
|
+
* process.nextTick(() => {
|
|
2851
|
+
* ee.emit('foo', 'bar');
|
|
2852
|
+
* ee.emit('foo', 42);
|
|
2853
|
+
* ee.emit('close');
|
|
2854
|
+
* });
|
|
2855
|
+
*
|
|
2856
|
+
* for await (const event of on(ee, 'foo', { close: ['close'] })) {
|
|
2857
|
+
* console.log(event); // prints ['bar'] [42]
|
|
2858
|
+
* }
|
|
2859
|
+
* // the loop will exit after 'close' is emitted
|
|
2860
|
+
* console.log('done'); // prints 'done'
|
|
2861
|
+
* ```
|
|
2862
|
+
* @since v13.6.0, v12.16.0
|
|
2863
|
+
* @return An `AsyncIterator` that iterates `eventName` events emitted by the `emitter`
|
|
2864
|
+
*/
|
|
2865
|
+
static on(emitter: NodeJS.EventEmitter, eventName: string | symbol, options?: StaticEventEmitterIteratorOptions): NodeJS.AsyncIterator<any[]>;
|
|
2866
|
+
static on(emitter: EventTarget, eventName: string, options?: StaticEventEmitterIteratorOptions): NodeJS.AsyncIterator<any[]>;
|
|
2867
|
+
/**
|
|
2868
|
+
* A class method that returns the number of listeners for the given `eventName` registered on the given `emitter`.
|
|
2869
|
+
*
|
|
2870
|
+
* ```js
|
|
2871
|
+
* import { EventEmitter, listenerCount } from 'node:events';
|
|
2872
|
+
*
|
|
2873
|
+
* const myEmitter = new EventEmitter();
|
|
2874
|
+
* myEmitter.on('event', () => {});
|
|
2875
|
+
* myEmitter.on('event', () => {});
|
|
2876
|
+
* console.log(listenerCount(myEmitter, 'event'));
|
|
2877
|
+
* // Prints: 2
|
|
2878
|
+
* ```
|
|
2879
|
+
* @since v0.9.12
|
|
2880
|
+
* @deprecated Since v3.2.0 - Use `listenerCount` instead.
|
|
2881
|
+
* @param emitter The emitter to query
|
|
2882
|
+
* @param eventName The event name
|
|
2883
|
+
*/
|
|
2884
|
+
static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number;
|
|
2885
|
+
/**
|
|
2886
|
+
* Returns a copy of the array of listeners for the event named `eventName`.
|
|
2887
|
+
*
|
|
2888
|
+
* For `EventEmitter`s this behaves exactly the same as calling `.listeners` on
|
|
2889
|
+
* the emitter.
|
|
2890
|
+
*
|
|
2891
|
+
* For `EventTarget`s this is the only way to get the event listeners for the
|
|
2892
|
+
* event target. This is useful for debugging and diagnostic purposes.
|
|
2893
|
+
*
|
|
2894
|
+
* ```js
|
|
2895
|
+
* import { getEventListeners, EventEmitter } from 'node:events';
|
|
2896
|
+
*
|
|
2897
|
+
* {
|
|
2898
|
+
* const ee = new EventEmitter();
|
|
2899
|
+
* const listener = () => console.log('Events are fun');
|
|
2900
|
+
* ee.on('foo', listener);
|
|
2901
|
+
* console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
|
|
2902
|
+
* }
|
|
2903
|
+
* {
|
|
2904
|
+
* const et = new EventTarget();
|
|
2905
|
+
* const listener = () => console.log('Events are fun');
|
|
2906
|
+
* et.addEventListener('foo', listener);
|
|
2907
|
+
* console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
|
|
2908
|
+
* }
|
|
2909
|
+
* ```
|
|
2910
|
+
* @since v15.2.0, v14.17.0
|
|
2911
|
+
*/
|
|
2912
|
+
static getEventListeners(emitter: EventTarget | NodeJS.EventEmitter, name: string | symbol): Function[];
|
|
2913
|
+
/**
|
|
2914
|
+
* Returns the currently set max amount of listeners.
|
|
2915
|
+
*
|
|
2916
|
+
* For `EventEmitter`s this behaves exactly the same as calling `.getMaxListeners` on
|
|
2917
|
+
* the emitter.
|
|
2918
|
+
*
|
|
2919
|
+
* For `EventTarget`s this is the only way to get the max event listeners for the
|
|
2920
|
+
* event target. If the number of event handlers on a single EventTarget exceeds
|
|
2921
|
+
* the max set, the EventTarget will print a warning.
|
|
2922
|
+
*
|
|
2923
|
+
* ```js
|
|
2924
|
+
* import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
|
|
2925
|
+
*
|
|
2926
|
+
* {
|
|
2927
|
+
* const ee = new EventEmitter();
|
|
2928
|
+
* console.log(getMaxListeners(ee)); // 10
|
|
2929
|
+
* setMaxListeners(11, ee);
|
|
2930
|
+
* console.log(getMaxListeners(ee)); // 11
|
|
2931
|
+
* }
|
|
2932
|
+
* {
|
|
2933
|
+
* const et = new EventTarget();
|
|
2934
|
+
* console.log(getMaxListeners(et)); // 10
|
|
2935
|
+
* setMaxListeners(11, et);
|
|
2936
|
+
* console.log(getMaxListeners(et)); // 11
|
|
2937
|
+
* }
|
|
2938
|
+
* ```
|
|
2939
|
+
* @since v19.9.0
|
|
2940
|
+
*/
|
|
2941
|
+
static getMaxListeners(emitter: EventTarget | NodeJS.EventEmitter): number;
|
|
2942
|
+
/**
|
|
2943
|
+
* ```js
|
|
2944
|
+
* import { setMaxListeners, EventEmitter } from 'node:events';
|
|
2945
|
+
*
|
|
2946
|
+
* const target = new EventTarget();
|
|
2947
|
+
* const emitter = new EventEmitter();
|
|
2948
|
+
*
|
|
2949
|
+
* setMaxListeners(5, target, emitter);
|
|
2950
|
+
* ```
|
|
2951
|
+
* @since v15.4.0
|
|
2952
|
+
* @param n A non-negative number. The maximum number of listeners per `EventTarget` event.
|
|
2953
|
+
* @param eventTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter}
|
|
2954
|
+
* objects.
|
|
2955
|
+
*/
|
|
2956
|
+
static setMaxListeners(n?: number, ...eventTargets: Array<EventTarget | NodeJS.EventEmitter>): void;
|
|
2957
|
+
/**
|
|
2958
|
+
* Listens once to the `abort` event on the provided `signal`.
|
|
2959
|
+
*
|
|
2960
|
+
* Listening to the `abort` event on abort signals is unsafe and may
|
|
2961
|
+
* lead to resource leaks since another third party with the signal can
|
|
2962
|
+
* call `e.stopImmediatePropagation()`. Unfortunately Node.js cannot change
|
|
2963
|
+
* this since it would violate the web standard. Additionally, the original
|
|
2964
|
+
* API makes it easy to forget to remove listeners.
|
|
2965
|
+
*
|
|
2966
|
+
* This API allows safely using `AbortSignal`s in Node.js APIs by solving these
|
|
2967
|
+
* two issues by listening to the event such that `stopImmediatePropagation` does
|
|
2968
|
+
* not prevent the listener from running.
|
|
2969
|
+
*
|
|
2970
|
+
* Returns a disposable so that it may be unsubscribed from more easily.
|
|
2971
|
+
*
|
|
2972
|
+
* ```js
|
|
2973
|
+
* import { addAbortListener } from 'node:events';
|
|
2974
|
+
*
|
|
2975
|
+
* function example(signal) {
|
|
2976
|
+
* let disposable;
|
|
2977
|
+
* try {
|
|
2978
|
+
* signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
|
|
2979
|
+
* disposable = addAbortListener(signal, (e) => {
|
|
2980
|
+
* // Do something when signal is aborted.
|
|
2981
|
+
* });
|
|
2982
|
+
* } finally {
|
|
2983
|
+
* disposable?.[Symbol.dispose]();
|
|
2984
|
+
* }
|
|
2985
|
+
* }
|
|
2986
|
+
* ```
|
|
2987
|
+
* @since v20.5.0
|
|
2988
|
+
* @return Disposable that removes the `abort` listener.
|
|
2989
|
+
*/
|
|
2990
|
+
static addAbortListener(signal: AbortSignal, resource: (event: Event) => void): Disposable;
|
|
2991
|
+
/**
|
|
2992
|
+
* This symbol shall be used to install a listener for only monitoring `'error'` events. Listeners installed using this symbol are called before the regular `'error'` listeners are called.
|
|
2993
|
+
*
|
|
2994
|
+
* Installing a listener using this symbol does not change the behavior once an `'error'` event is emitted. Therefore, the process will still crash if no
|
|
2995
|
+
* regular `'error'` listener is installed.
|
|
2996
|
+
* @since v13.6.0, v12.17.0
|
|
2997
|
+
*/
|
|
2998
|
+
static readonly errorMonitor: unique symbol;
|
|
2999
|
+
/**
|
|
3000
|
+
* Value: `Symbol.for('nodejs.rejection')`
|
|
3001
|
+
*
|
|
3002
|
+
* See how to write a custom `rejection handler`.
|
|
3003
|
+
* @since v13.4.0, v12.16.0
|
|
3004
|
+
*/
|
|
3005
|
+
static readonly captureRejectionSymbol: unique symbol;
|
|
3006
|
+
/**
|
|
3007
|
+
* Value: [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
|
|
3008
|
+
*
|
|
3009
|
+
* Change the default `captureRejections` option on all new `EventEmitter` objects.
|
|
3010
|
+
* @since v13.4.0, v12.16.0
|
|
3011
|
+
*/
|
|
3012
|
+
static captureRejections: boolean;
|
|
3013
|
+
/**
|
|
3014
|
+
* By default, a maximum of `10` listeners can be registered for any single
|
|
3015
|
+
* event. This limit can be changed for individual `EventEmitter` instances
|
|
3016
|
+
* using the `emitter.setMaxListeners(n)` method. To change the default
|
|
3017
|
+
* for _all_`EventEmitter` instances, the `events.defaultMaxListeners` property
|
|
3018
|
+
* can be used. If this value is not a positive number, a `RangeError` is thrown.
|
|
3019
|
+
*
|
|
3020
|
+
* Take caution when setting the `events.defaultMaxListeners` because the
|
|
3021
|
+
* change affects _all_ `EventEmitter` instances, including those created before
|
|
3022
|
+
* the change is made. However, calling `emitter.setMaxListeners(n)` still has
|
|
3023
|
+
* precedence over `events.defaultMaxListeners`.
|
|
3024
|
+
*
|
|
3025
|
+
* This is not a hard limit. The `EventEmitter` instance will allow
|
|
3026
|
+
* more listeners to be added but will output a trace warning to stderr indicating
|
|
3027
|
+
* that a "possible EventEmitter memory leak" has been detected. For any single
|
|
3028
|
+
* `EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()` methods can be used to
|
|
3029
|
+
* temporarily avoid this warning:
|
|
3030
|
+
*
|
|
3031
|
+
* ```js
|
|
3032
|
+
* import { EventEmitter } from 'node:events';
|
|
3033
|
+
* const emitter = new EventEmitter();
|
|
3034
|
+
* emitter.setMaxListeners(emitter.getMaxListeners() + 1);
|
|
3035
|
+
* emitter.once('event', () => {
|
|
3036
|
+
* // do stuff
|
|
3037
|
+
* emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
|
|
3038
|
+
* });
|
|
3039
|
+
* ```
|
|
3040
|
+
*
|
|
3041
|
+
* The `--trace-warnings` command-line flag can be used to display the
|
|
3042
|
+
* stack trace for such warnings.
|
|
3043
|
+
*
|
|
3044
|
+
* The emitted warning can be inspected with `process.on('warning')` and will
|
|
3045
|
+
* have the additional `emitter`, `type`, and `count` properties, referring to
|
|
3046
|
+
* the event emitter instance, the event's name and the number of attached
|
|
3047
|
+
* listeners, respectively.
|
|
3048
|
+
* Its `name` property is set to `'MaxListenersExceededWarning'`.
|
|
3049
|
+
* @since v0.11.2
|
|
3050
|
+
*/
|
|
3051
|
+
static defaultMaxListeners: number;
|
|
3052
|
+
}
|
|
3053
|
+
declare namespace EventEmitter$1 {
|
|
3054
|
+
// Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4
|
|
3055
|
+
export { EventEmitter$1 as EventEmitter$1 };
|
|
3056
|
+
export interface Abortable {
|
|
3057
|
+
/**
|
|
3058
|
+
* When provided the corresponding `AbortController` can be used to cancel an asynchronous action.
|
|
3059
|
+
*/
|
|
3060
|
+
signal?: AbortSignal | undefined;
|
|
3061
|
+
}
|
|
3062
|
+
export interface EventEmitterReferencingAsyncResource extends AsyncResource {
|
|
3063
|
+
readonly eventEmitter: EventEmitterAsyncResource;
|
|
3064
|
+
}
|
|
3065
|
+
export interface EventEmitterAsyncResourceOptions extends AsyncResourceOptions, EventEmitterOptions {
|
|
3066
|
+
/**
|
|
3067
|
+
* The type of async event, this is required when instantiating `EventEmitterAsyncResource`
|
|
3068
|
+
* directly rather than as a child class.
|
|
3069
|
+
* @default new.target.name if instantiated as a child class.
|
|
3070
|
+
*/
|
|
3071
|
+
name?: string | undefined;
|
|
3072
|
+
}
|
|
3073
|
+
/**
|
|
3074
|
+
* Integrates `EventEmitter` with `AsyncResource` for `EventEmitter`s that
|
|
3075
|
+
* require manual async tracking. Specifically, all events emitted by instances
|
|
3076
|
+
* of `events.EventEmitterAsyncResource` will run within its `async context`.
|
|
3077
|
+
*
|
|
3078
|
+
* ```js
|
|
3079
|
+
* import { EventEmitterAsyncResource, EventEmitter } from 'node:events';
|
|
3080
|
+
* import { notStrictEqual, strictEqual } from 'node:assert';
|
|
3081
|
+
* import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';
|
|
3082
|
+
*
|
|
3083
|
+
* // Async tracking tooling will identify this as 'Q'.
|
|
3084
|
+
* const ee1 = new EventEmitterAsyncResource({ name: 'Q' });
|
|
3085
|
+
*
|
|
3086
|
+
* // 'foo' listeners will run in the EventEmitters async context.
|
|
3087
|
+
* ee1.on('foo', () => {
|
|
3088
|
+
* strictEqual(executionAsyncId(), ee1.asyncId);
|
|
3089
|
+
* strictEqual(triggerAsyncId(), ee1.triggerAsyncId);
|
|
3090
|
+
* });
|
|
3091
|
+
*
|
|
3092
|
+
* const ee2 = new EventEmitter();
|
|
3093
|
+
*
|
|
3094
|
+
* // 'foo' listeners on ordinary EventEmitters that do not track async
|
|
3095
|
+
* // context, however, run in the same async context as the emit().
|
|
3096
|
+
* ee2.on('foo', () => {
|
|
3097
|
+
* notStrictEqual(executionAsyncId(), ee2.asyncId);
|
|
3098
|
+
* notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId);
|
|
3099
|
+
* });
|
|
3100
|
+
*
|
|
3101
|
+
* Promise.resolve().then(() => {
|
|
3102
|
+
* ee1.emit('foo');
|
|
3103
|
+
* ee2.emit('foo');
|
|
3104
|
+
* });
|
|
3105
|
+
* ```
|
|
3106
|
+
*
|
|
3107
|
+
* The `EventEmitterAsyncResource` class has the same methods and takes the
|
|
3108
|
+
* same options as `EventEmitter` and `AsyncResource` themselves.
|
|
3109
|
+
* @since v17.4.0, v16.14.0
|
|
3110
|
+
*/
|
|
3111
|
+
export class EventEmitterAsyncResource extends EventEmitter$1 {
|
|
3112
|
+
/**
|
|
3113
|
+
* @param options Only optional in child class.
|
|
3114
|
+
*/
|
|
3115
|
+
constructor(options?: EventEmitterAsyncResourceOptions);
|
|
3116
|
+
/**
|
|
3117
|
+
* Call all `destroy` hooks. This should only ever be called once. An error will
|
|
3118
|
+
* be thrown if it is called more than once. This **must** be manually called. If
|
|
3119
|
+
* the resource is left to be collected by the GC then the `destroy` hooks will
|
|
3120
|
+
* never be called.
|
|
3121
|
+
*/
|
|
3122
|
+
emitDestroy(): void;
|
|
3123
|
+
/**
|
|
3124
|
+
* The unique `asyncId` assigned to the resource.
|
|
3125
|
+
*/
|
|
3126
|
+
readonly asyncId: number;
|
|
3127
|
+
/**
|
|
3128
|
+
* The same triggerAsyncId that is passed to the AsyncResource constructor.
|
|
3129
|
+
*/
|
|
3130
|
+
readonly triggerAsyncId: number;
|
|
3131
|
+
/**
|
|
3132
|
+
* The returned `AsyncResource` object has an additional `eventEmitter` property
|
|
3133
|
+
* that provides a reference to this `EventEmitterAsyncResource`.
|
|
3134
|
+
*/
|
|
3135
|
+
readonly asyncResource: EventEmitterReferencingAsyncResource;
|
|
3136
|
+
}
|
|
3137
|
+
/**
|
|
3138
|
+
* The `NodeEventTarget` is a Node.js-specific extension to `EventTarget`
|
|
3139
|
+
* that emulates a subset of the `EventEmitter` API.
|
|
3140
|
+
* @since v14.5.0
|
|
3141
|
+
*/
|
|
3142
|
+
export interface NodeEventTarget extends EventTarget {
|
|
3143
|
+
/**
|
|
3144
|
+
* Node.js-specific extension to the `EventTarget` class that emulates the
|
|
3145
|
+
* equivalent `EventEmitter` API. The only difference between `addListener()` and
|
|
3146
|
+
* `addEventListener()` is that `addListener()` will return a reference to the
|
|
3147
|
+
* `EventTarget`.
|
|
3148
|
+
* @since v14.5.0
|
|
3149
|
+
*/
|
|
3150
|
+
addListener(type: string, listener: (arg: any) => void): this;
|
|
3151
|
+
/**
|
|
3152
|
+
* Node.js-specific extension to the `EventTarget` class that dispatches the
|
|
3153
|
+
* `arg` to the list of handlers for `type`.
|
|
3154
|
+
* @since v15.2.0
|
|
3155
|
+
* @returns `true` if event listeners registered for the `type` exist,
|
|
3156
|
+
* otherwise `false`.
|
|
3157
|
+
*/
|
|
3158
|
+
emit(type: string, arg: any): boolean;
|
|
3159
|
+
/**
|
|
3160
|
+
* Node.js-specific extension to the `EventTarget` class that returns an array
|
|
3161
|
+
* of event `type` names for which event listeners are registered.
|
|
3162
|
+
* @since 14.5.0
|
|
3163
|
+
*/
|
|
3164
|
+
eventNames(): string[];
|
|
3165
|
+
/**
|
|
3166
|
+
* Node.js-specific extension to the `EventTarget` class that returns the number
|
|
3167
|
+
* of event listeners registered for the `type`.
|
|
3168
|
+
* @since v14.5.0
|
|
3169
|
+
*/
|
|
3170
|
+
listenerCount(type: string): number;
|
|
3171
|
+
/**
|
|
3172
|
+
* Node.js-specific extension to the `EventTarget` class that sets the number
|
|
3173
|
+
* of max event listeners as `n`.
|
|
3174
|
+
* @since v14.5.0
|
|
3175
|
+
*/
|
|
3176
|
+
setMaxListeners(n: number): void;
|
|
3177
|
+
/**
|
|
3178
|
+
* Node.js-specific extension to the `EventTarget` class that returns the number
|
|
3179
|
+
* of max event listeners.
|
|
3180
|
+
* @since v14.5.0
|
|
3181
|
+
*/
|
|
3182
|
+
getMaxListeners(): number;
|
|
3183
|
+
/**
|
|
3184
|
+
* Node.js-specific alias for `eventTarget.removeEventListener()`.
|
|
3185
|
+
* @since v14.5.0
|
|
3186
|
+
*/
|
|
3187
|
+
off(type: string, listener: (arg: any) => void, options?: EventListenerOptions): this;
|
|
3188
|
+
/**
|
|
3189
|
+
* Node.js-specific alias for `eventTarget.addEventListener()`.
|
|
3190
|
+
* @since v14.5.0
|
|
3191
|
+
*/
|
|
3192
|
+
on(type: string, listener: (arg: any) => void): this;
|
|
3193
|
+
/**
|
|
3194
|
+
* Node.js-specific extension to the `EventTarget` class that adds a `once`
|
|
3195
|
+
* listener for the given event `type`. This is equivalent to calling `on`
|
|
3196
|
+
* with the `once` option set to `true`.
|
|
3197
|
+
* @since v14.5.0
|
|
3198
|
+
*/
|
|
3199
|
+
once(type: string, listener: (arg: any) => void): this;
|
|
3200
|
+
/**
|
|
3201
|
+
* Node.js-specific extension to the `EventTarget` class. If `type` is specified,
|
|
3202
|
+
* removes all registered listeners for `type`, otherwise removes all registered
|
|
3203
|
+
* listeners.
|
|
3204
|
+
* @since v14.5.0
|
|
3205
|
+
*/
|
|
3206
|
+
removeAllListeners(type?: string): this;
|
|
3207
|
+
/**
|
|
3208
|
+
* Node.js-specific extension to the `EventTarget` class that removes the
|
|
3209
|
+
* `listener` for the given `type`. The only difference between `removeListener()`
|
|
3210
|
+
* and `removeEventListener()` is that `removeListener()` will return a reference
|
|
3211
|
+
* to the `EventTarget`.
|
|
3212
|
+
* @since v14.5.0
|
|
3213
|
+
*/
|
|
3214
|
+
removeListener(type: string, listener: (arg: any) => void, options?: EventListenerOptions): this;
|
|
3215
|
+
}
|
|
3216
|
+
}
|
|
3217
|
+
interface Presence {
|
|
3218
|
+
/**
|
|
3219
|
+
* Subscribes to the given topic. The callback will be triggered whenever a message is published on topic.
|
|
3220
|
+
*
|
|
3221
|
+
* @param topic - Topic name.
|
|
3222
|
+
* @param callback - Callback to trigger on subscribing.
|
|
3223
|
+
*/
|
|
3224
|
+
subscribe(topic: string, callback: Function): Promise<this>;
|
|
3225
|
+
/**
|
|
3226
|
+
* Unsubscribe from given topic.
|
|
3227
|
+
*
|
|
3228
|
+
* @param topic - Topic name.
|
|
3229
|
+
* @param callback - Callback to trigger on topic unsubscribing.
|
|
3230
|
+
*/
|
|
3231
|
+
unsubscribe(topic: string, callback?: Function): any;
|
|
3232
|
+
/**
|
|
3233
|
+
* Lists the currently active channels / subscriptions
|
|
3234
|
+
* @param pattern
|
|
3235
|
+
*/
|
|
3236
|
+
channels(pattern?: string): Promise<string[]>;
|
|
3237
|
+
/**
|
|
3238
|
+
* Posts a message to given topic.
|
|
3239
|
+
*
|
|
3240
|
+
* @param topic - Topic name.
|
|
3241
|
+
* @param data - Message body/object.
|
|
3242
|
+
*/
|
|
3243
|
+
publish(topic: string, data: any): any;
|
|
3244
|
+
/**
|
|
3245
|
+
* Returns if key exists.
|
|
3246
|
+
*
|
|
3247
|
+
* @param key
|
|
3248
|
+
*/
|
|
3249
|
+
exists(key: string): Promise<boolean>;
|
|
3250
|
+
/**
|
|
3251
|
+
* Set key to hold the string value.
|
|
3252
|
+
*
|
|
3253
|
+
* @param key - Identifier.
|
|
3254
|
+
* @param value - Message body/object.
|
|
3255
|
+
*/
|
|
3256
|
+
set(key: string, value: string): any;
|
|
3257
|
+
/**
|
|
3258
|
+
* Set key to hold the string value and set key to timeout after a given number of seconds.
|
|
3259
|
+
*
|
|
3260
|
+
* @param key - Identifier.
|
|
3261
|
+
* @param value - Message body/object.
|
|
3262
|
+
* @param seconds - Timeout value.
|
|
3263
|
+
*/
|
|
3264
|
+
setex(key: string, value: string, seconds: number): any;
|
|
3265
|
+
/**
|
|
3266
|
+
* Expire the key in seconds.
|
|
3267
|
+
*
|
|
3268
|
+
* @param key - Identifier.
|
|
3269
|
+
* @param seconds - Seconds to expire the key.
|
|
3270
|
+
*/
|
|
3271
|
+
expire(key: string, seconds: number): any;
|
|
3272
|
+
/**
|
|
3273
|
+
* Get the value of key.
|
|
3274
|
+
*
|
|
3275
|
+
* @param key - Identifier.
|
|
3276
|
+
*/
|
|
3277
|
+
get(key: string): any;
|
|
3278
|
+
/**
|
|
3279
|
+
* Removes the specified key.
|
|
3280
|
+
*
|
|
3281
|
+
* @param key - Identifier of the object to removed.
|
|
3282
|
+
*/
|
|
3283
|
+
del(key: string): void;
|
|
3284
|
+
/**
|
|
3285
|
+
* Add the specified members to the set stored at key. Specified members that are already
|
|
3286
|
+
* a member of this set are ignored. If key does not exist, a new set is created before
|
|
3287
|
+
* adding the specified members.
|
|
3288
|
+
*
|
|
3289
|
+
* @param key - Name/Identifier of the set.
|
|
3290
|
+
* @param value - Message body/object.
|
|
3291
|
+
*/
|
|
3292
|
+
sadd(key: string, value: any): any;
|
|
3293
|
+
/**
|
|
3294
|
+
* Returns all the members of the set value stored at key.
|
|
3295
|
+
*
|
|
3296
|
+
* @param key - Name/Identifier of the set.
|
|
3297
|
+
*/
|
|
3298
|
+
smembers(key: string): Promise<string[]>;
|
|
3299
|
+
/**
|
|
3300
|
+
* Returns if member is a member of the set stored at key.
|
|
3301
|
+
*
|
|
3302
|
+
* @param key - Name/Identifier of the set.
|
|
3303
|
+
* @param field - Key value within the set.
|
|
3304
|
+
* @returns `1` if the element is a member of the set else `0`.
|
|
3305
|
+
*/
|
|
3306
|
+
sismember(key: string, field: string): any;
|
|
3307
|
+
/**
|
|
3308
|
+
* Remove the specified members from the set stored at key. Specified members that are not a
|
|
3309
|
+
* member of this set are ignored. If key does not exist, it is treated as an empty set
|
|
3310
|
+
* and this command returns 0.
|
|
3311
|
+
*
|
|
3312
|
+
* @param key - Name/Identifier of the set.
|
|
3313
|
+
* @param value - Key value within the set.
|
|
3314
|
+
*/
|
|
3315
|
+
srem(key: string, value: any): any;
|
|
3316
|
+
/**
|
|
3317
|
+
* Returns the set cardinality (number of elements) of the set stored at key.
|
|
3318
|
+
*
|
|
3319
|
+
* @param key - Name/Identifier of the set.
|
|
3320
|
+
*/
|
|
3321
|
+
scard(key: string): any;
|
|
3322
|
+
/**
|
|
3323
|
+
* Returns the members of the set resulting from the intersection of all the given sets.
|
|
3324
|
+
*
|
|
3325
|
+
* @param keys - Key values within the set.
|
|
3326
|
+
*/
|
|
3327
|
+
sinter(...keys: string[]): Promise<string[]>;
|
|
3328
|
+
/**
|
|
3329
|
+
* Sets field in the hash stored at key to value. If key does not exist, a new key holding a hash is created.
|
|
3330
|
+
* If field already exists in the hash, it is overwritten.
|
|
3331
|
+
*/
|
|
3332
|
+
hset(key: string, field: string, value: string): Promise<boolean>;
|
|
3333
|
+
/**
|
|
3334
|
+
* Increments the number stored at field in the hash stored at key by increment. If key does not exist, a new key
|
|
3335
|
+
* holding a hash is created. If field does not exist the value is set to 0 before the operation is performed.
|
|
3336
|
+
*/
|
|
3337
|
+
hincrby(key: string, field: string, value: number): Promise<number>;
|
|
3338
|
+
/**
|
|
3339
|
+
* WARNING: DO NOT USE THIS METHOD. It is meant for internal use only.
|
|
3340
|
+
* @private
|
|
3341
|
+
*/
|
|
3342
|
+
hincrbyex(key: string, field: string, value: number, expireInSeconds: number): Promise<number>;
|
|
3343
|
+
/**
|
|
3344
|
+
* Returns the value associated with field in the hash stored at key.
|
|
3345
|
+
*/
|
|
3346
|
+
hget(key: string, field: string): Promise<string | null>;
|
|
3347
|
+
/**
|
|
3348
|
+
* Returns all fields and values of the hash stored at key.
|
|
3349
|
+
*/
|
|
3350
|
+
hgetall(key: string): Promise<{
|
|
3351
|
+
[key: string]: string;
|
|
3352
|
+
}>;
|
|
3353
|
+
/**
|
|
3354
|
+
* Removes the specified fields from the hash stored at key. Specified fields that do not exist within
|
|
3355
|
+
* this hash are ignored. If key does not exist, it is treated as an empty hash and this command returns 0.
|
|
3356
|
+
*/
|
|
3357
|
+
hdel(key: string, field: string): Promise<boolean>;
|
|
3358
|
+
/**
|
|
3359
|
+
* Returns the number of fields contained in the hash stored at key
|
|
3360
|
+
*/
|
|
3361
|
+
hlen(key: string): Promise<number>;
|
|
3362
|
+
/**
|
|
3363
|
+
* Increments the number stored at key by one. If the key does not exist, it is set to 0 before performing
|
|
3364
|
+
* the operation. An error is returned if the key contains a value of the wrong type or
|
|
3365
|
+
* contains a string that can not be represented as integer. This operation is limited to 64-bit signed integers.
|
|
3366
|
+
*/
|
|
3367
|
+
incr(key: string): Promise<number>;
|
|
3368
|
+
/**
|
|
3369
|
+
* Decrements the number stored at key by one. If the key does not exist, it is set to 0 before performing
|
|
3370
|
+
* the operation. An error is returned if the key contains a value of the wrong type or contains a string
|
|
3371
|
+
* that can not be represented as integer. This operation is limited to 64-bit signed integers.
|
|
3372
|
+
*/
|
|
3373
|
+
decr(key: string): Promise<number>;
|
|
3374
|
+
/**
|
|
3375
|
+
* Returns the length of the list stored at key.
|
|
3376
|
+
*/
|
|
3377
|
+
llen(key: string): Promise<number>;
|
|
3378
|
+
/**
|
|
3379
|
+
* Adds the string value to the end of the list stored at key. If key does not exist, it is created as empty list before performing the push operation.
|
|
3380
|
+
*/
|
|
3381
|
+
rpush(key: string, ...values: string[]): Promise<number>;
|
|
3382
|
+
/**
|
|
3383
|
+
* Adds the string value to the begginning of the list stored at key. If key does not exist, it is created as empty list before performing the push operation.
|
|
3384
|
+
*/
|
|
3385
|
+
lpush(key: string, ...values: string[]): Promise<number>;
|
|
3386
|
+
/**
|
|
3387
|
+
* Removes and returns the last element of the list stored at key.
|
|
3388
|
+
*/
|
|
3389
|
+
rpop(key: string): Promise<string | null>;
|
|
3390
|
+
/**
|
|
3391
|
+
* Removes and returns the first element of the list stored at key.
|
|
3392
|
+
*/
|
|
3393
|
+
lpop(key: string): Promise<string | null>;
|
|
3394
|
+
/**
|
|
3395
|
+
* Removes and returns the last element of the list stored at key. If the list is empty, the execution is halted until an element is available or the timeout is reached.
|
|
3396
|
+
*/
|
|
3397
|
+
brpop(...args: [
|
|
3398
|
+
...keys: string[],
|
|
3399
|
+
timeoutInSeconds: number
|
|
3400
|
+
]): Promise<[
|
|
3401
|
+
string,
|
|
3402
|
+
string
|
|
3403
|
+
] | null>;
|
|
3404
|
+
setMaxListeners(number: number): void;
|
|
3405
|
+
shutdown(): void;
|
|
3406
|
+
}
|
|
3407
|
+
type AuthContext = {
|
|
3408
|
+
token?: string;
|
|
3409
|
+
headers: Headers;
|
|
3410
|
+
ip: string | string[];
|
|
3411
|
+
req?: any;
|
|
3412
|
+
};
|
|
3413
|
+
interface ISendOptions {
|
|
3414
|
+
afterNextPatch?: boolean;
|
|
3415
|
+
}
|
|
3416
|
+
declare const ClientState: {
|
|
3417
|
+
readonly JOINING: 0;
|
|
3418
|
+
readonly JOINED: 1;
|
|
3419
|
+
readonly RECONNECTING: 2;
|
|
3420
|
+
readonly RECONNECTED: 3;
|
|
3421
|
+
readonly LEAVING: 4;
|
|
3422
|
+
readonly CLOSED: 5;
|
|
3423
|
+
};
|
|
3424
|
+
type ClientState = (typeof ClientState)[keyof typeof ClientState];
|
|
3425
|
+
type ExtractClientUserData<T> = T extends {
|
|
3426
|
+
userData: infer U;
|
|
3427
|
+
} ? U : T;
|
|
3428
|
+
type ExtractClientAuth<T> = T extends {
|
|
3429
|
+
auth: infer A;
|
|
3430
|
+
} ? A : any;
|
|
3431
|
+
type ExtractClientMessages<T> = T extends {
|
|
3432
|
+
messages: infer M;
|
|
3433
|
+
} ? M : any;
|
|
3434
|
+
type MessageArgs<M, Options> = unknown extends M ? [
|
|
3435
|
+
message?: M,
|
|
3436
|
+
options?: Options
|
|
3437
|
+
] : [
|
|
3438
|
+
M
|
|
3439
|
+
] extends [
|
|
3440
|
+
never
|
|
3441
|
+
] ? [
|
|
3442
|
+
message?: M,
|
|
3443
|
+
options?: Options
|
|
3444
|
+
] : [
|
|
3445
|
+
M
|
|
3446
|
+
] extends [
|
|
3447
|
+
void
|
|
3448
|
+
] ? [
|
|
3449
|
+
message?: M,
|
|
3450
|
+
options?: Options
|
|
3451
|
+
] : [
|
|
3452
|
+
M
|
|
3453
|
+
] extends [
|
|
3454
|
+
undefined
|
|
3455
|
+
] ? [
|
|
3456
|
+
message?: M,
|
|
3457
|
+
options?: Options
|
|
3458
|
+
] : undefined extends M ? [
|
|
3459
|
+
message?: M,
|
|
3460
|
+
options?: Options
|
|
3461
|
+
] : [
|
|
3462
|
+
message: M,
|
|
3463
|
+
options?: Options
|
|
3464
|
+
];
|
|
3465
|
+
interface Client$1<T extends {
|
|
3466
|
+
userData?: any;
|
|
3467
|
+
auth?: any;
|
|
3468
|
+
messages?: Record<string | number, any>;
|
|
3469
|
+
} = any> {
|
|
3470
|
+
"~messages": ExtractClientMessages<T>;
|
|
3471
|
+
ref: EventEmitter$1;
|
|
3472
|
+
/**
|
|
3473
|
+
* @deprecated use `sessionId` instead.
|
|
3474
|
+
*/
|
|
3475
|
+
id: string;
|
|
3476
|
+
/**
|
|
3477
|
+
* Unique id per session.
|
|
3478
|
+
*/
|
|
3479
|
+
sessionId: string;
|
|
3480
|
+
/**
|
|
3481
|
+
* Connection state
|
|
3482
|
+
*/
|
|
3483
|
+
state: ClientState;
|
|
3484
|
+
/**
|
|
3485
|
+
* Optional: when using `@view()` decorator in your state properties, this will be the view instance for this client.
|
|
3486
|
+
*/
|
|
3487
|
+
view?: StateView;
|
|
3488
|
+
/**
|
|
3489
|
+
* User-defined data can be attached to the Client instance through this variable.
|
|
3490
|
+
* - Can be used to store custom data about the client's connection. userData is not synchronized with the client,
|
|
3491
|
+
* and should be used only to keep player-specific with its connection.
|
|
3492
|
+
*/
|
|
3493
|
+
userData?: ExtractClientUserData<T>;
|
|
3494
|
+
/**
|
|
3495
|
+
* auth data provided by your `onAuth`
|
|
3496
|
+
*/
|
|
3497
|
+
auth?: ExtractClientAuth<T>;
|
|
3498
|
+
/**
|
|
3499
|
+
* Reconnection token used to re-join the room after onLeave + allowReconnection().
|
|
3500
|
+
*
|
|
3501
|
+
* IMPORTANT:
|
|
3502
|
+
* This is not the full reconnection token the client provides for the server.
|
|
3503
|
+
* The format provided by .reconnect() from the client-side must follow: "${roomId}:${reconnectionToken}"
|
|
3504
|
+
*/
|
|
3505
|
+
reconnectionToken: string;
|
|
3506
|
+
raw(data: Uint8Array | Buffer, options?: ISendOptions, cb?: (err?: Error) => void): void;
|
|
3507
|
+
enqueueRaw(data: Uint8Array | Buffer, options?: ISendOptions): void;
|
|
3508
|
+
/**
|
|
3509
|
+
* Send a type of message to the client. Messages are encoded with MsgPack and can hold any
|
|
3510
|
+
* JSON-serializable data structure.
|
|
3511
|
+
*
|
|
3512
|
+
* @param type String or Number identifier the client SDK will use to receive this message
|
|
3513
|
+
* @param message Message payload. (automatically encoded with msgpack.)
|
|
3514
|
+
* @param options
|
|
3515
|
+
*/
|
|
3516
|
+
send<K extends keyof this["~messages"]>(type: K, ...args: MessageArgs<this["~messages"][K], ISendOptions>): void;
|
|
3517
|
+
/**
|
|
3518
|
+
* Send raw bytes to this specific client.
|
|
3519
|
+
*
|
|
3520
|
+
* @param type String or Number identifier the client SDK will use to receive this message
|
|
3521
|
+
* @param bytes Raw byte array payload
|
|
3522
|
+
* @param options
|
|
3523
|
+
*/
|
|
3524
|
+
sendBytes(type: string | number, bytes: Buffer | Uint8Array, options?: ISendOptions): void;
|
|
3525
|
+
/**
|
|
3526
|
+
* Disconnect this client from the room.
|
|
3527
|
+
*
|
|
3528
|
+
* @param code Custom close code. Default value is 1000.
|
|
3529
|
+
* @param data
|
|
3530
|
+
* @see [Leave room](https://docs.colyseus.io/room#leave-room)
|
|
3531
|
+
*/
|
|
3532
|
+
leave(code?: number, data?: string): void;
|
|
3533
|
+
/**
|
|
3534
|
+
* @deprecated Use .leave() instead.
|
|
3535
|
+
*/
|
|
3536
|
+
close(code?: number, data?: string): void;
|
|
3537
|
+
/**
|
|
3538
|
+
* Triggers `onError` with specified code to the client-side.
|
|
3539
|
+
*
|
|
3540
|
+
* @param code
|
|
3541
|
+
* @param message
|
|
3542
|
+
*/
|
|
3543
|
+
error(code: number, message?: string): void;
|
|
3544
|
+
}
|
|
3545
|
+
declare class ClientArray<C extends Client$1 = Client$1> extends Array<C> {
|
|
3546
|
+
getById(sessionId: string): C | undefined;
|
|
3547
|
+
delete(client: C): boolean;
|
|
3548
|
+
}
|
|
3549
|
+
interface Serializer$1<T> {
|
|
3550
|
+
id: string;
|
|
3551
|
+
reset(data: any): void;
|
|
3552
|
+
getFullState(client?: Client$1): Uint8Array;
|
|
3553
|
+
applyPatches(clients: Client$1[], state: T): boolean;
|
|
3554
|
+
handshake?(): Uint8Array;
|
|
3555
|
+
}
|
|
3556
|
+
type SimulationCallback = (deltaTime: number) => void;
|
|
3557
|
+
interface RoomOptions {
|
|
3558
|
+
state?: object;
|
|
3559
|
+
metadata?: any;
|
|
3560
|
+
client?: Client$1;
|
|
3561
|
+
}
|
|
3562
|
+
type ExtractRoomState<T> = T extends {
|
|
3563
|
+
state?: infer S extends object;
|
|
3564
|
+
} ? S : any;
|
|
3565
|
+
type ExtractRoomMetadata<T> = T extends {
|
|
3566
|
+
metadata?: infer M;
|
|
3567
|
+
} ? M : any;
|
|
3568
|
+
type ExtractRoomClient<T> = T extends {
|
|
3569
|
+
client?: infer C extends Client$1;
|
|
3570
|
+
} ? C : Client$1;
|
|
3571
|
+
interface IBroadcastOptions extends ISendOptions {
|
|
3572
|
+
except?: Client$1 | Client$1[];
|
|
3573
|
+
}
|
|
3574
|
+
type Messages$1<This extends Room$1> = Messages<This, Client$1>;
|
|
3575
|
+
declare class Room$1<T extends RoomOptions = RoomOptions> {
|
|
3576
|
+
#private;
|
|
3577
|
+
"~client": ExtractRoomClient<T>;
|
|
3578
|
+
"~state": ExtractRoomState<T>;
|
|
3579
|
+
"~metadata": ExtractRoomMetadata<T>;
|
|
3580
|
+
/**
|
|
3581
|
+
* This property will change on these situations:
|
|
3582
|
+
* - The maximum number of allowed clients has been reached (`maxClients`)
|
|
3583
|
+
* - You manually locked, or unlocked the room using lock() or `unlock()`.
|
|
3584
|
+
*
|
|
3585
|
+
* @readonly
|
|
3586
|
+
*/
|
|
3587
|
+
get locked(): boolean;
|
|
3588
|
+
/**
|
|
3589
|
+
* Get the room's matchmaking metadata.
|
|
3590
|
+
*/
|
|
3591
|
+
get metadata(): ExtractRoomMetadata<T>;
|
|
3592
|
+
/**
|
|
3593
|
+
* Set the room's matchmaking metadata.
|
|
3594
|
+
*
|
|
3595
|
+
* **Note**: This setter does NOT automatically persist. Use `setMatchmaking()` for automatic persistence.
|
|
3596
|
+
*
|
|
3597
|
+
* @example
|
|
3598
|
+
* ```typescript
|
|
3599
|
+
* class MyRoom extends Room<{ metadata: { difficulty: string; rating: number } }> {
|
|
3600
|
+
* async onCreate() {
|
|
3601
|
+
* this.metadata = { difficulty: "hard", rating: 1500 };
|
|
3602
|
+
* }
|
|
3603
|
+
* }
|
|
3604
|
+
* ```
|
|
3605
|
+
*/
|
|
3606
|
+
set metadata(meta: ExtractRoomMetadata<T>);
|
|
3607
|
+
/**
|
|
3608
|
+
* The room listing cache for matchmaking.
|
|
3609
|
+
* @internal
|
|
3610
|
+
*/
|
|
3611
|
+
private _listing;
|
|
3612
|
+
/**
|
|
3613
|
+
* Timing events tied to the room instance.
|
|
3614
|
+
* Intervals and timeouts are cleared when the room is disposed.
|
|
3615
|
+
*/
|
|
3616
|
+
clock: ClockTimer;
|
|
3617
|
+
/**
|
|
3618
|
+
* Maximum number of clients allowed to connect into the room. When room reaches this limit,
|
|
3619
|
+
* it is locked automatically. Unless the room was explicitly locked by you via `lock()` method,
|
|
3620
|
+
* the room will be unlocked as soon as a client disconnects from it.
|
|
3621
|
+
*/
|
|
3622
|
+
maxClients: number;
|
|
3623
|
+
/**
|
|
3624
|
+
* Automatically dispose the room when last client disconnects.
|
|
3625
|
+
*
|
|
3626
|
+
* @default true
|
|
3627
|
+
*/
|
|
3628
|
+
autoDispose: boolean;
|
|
3629
|
+
/**
|
|
3630
|
+
* Frequency to send the room state to connected clients, in milliseconds.
|
|
3631
|
+
*
|
|
3632
|
+
* @default 50ms (20fps)
|
|
3633
|
+
*/
|
|
3634
|
+
patchRate: number | null;
|
|
3635
|
+
/**
|
|
3636
|
+
* Maximum number of messages a client can send to the server per second.
|
|
3637
|
+
* If a client sends more messages than this, it will be disconnected.
|
|
3638
|
+
*
|
|
3639
|
+
* @default Infinity
|
|
3640
|
+
*/
|
|
3641
|
+
maxMessagesPerSecond: number;
|
|
3642
|
+
/**
|
|
3643
|
+
* The state instance you provided to `setState()`.
|
|
3644
|
+
*/
|
|
3645
|
+
state: ExtractRoomState<T>;
|
|
3646
|
+
/**
|
|
3647
|
+
* The presence instance. Check Presence API for more details.
|
|
3648
|
+
*
|
|
3649
|
+
* @see [Presence API](https://docs.colyseus.io/server/presence)
|
|
3650
|
+
*/
|
|
3651
|
+
presence: Presence;
|
|
3652
|
+
/**
|
|
3653
|
+
* The array of connected clients.
|
|
3654
|
+
*
|
|
3655
|
+
* @see [Client instance](https://docs.colyseus.io/room#client)
|
|
3656
|
+
*/
|
|
3657
|
+
clients: ClientArray<ExtractRoomClient<T>>;
|
|
3658
|
+
/**
|
|
3659
|
+
* Set the number of seconds a room can wait for a client to effectively join the room.
|
|
3660
|
+
* You should consider how long your `onAuth()` will have to wait for setting a different seat reservation time.
|
|
3661
|
+
* The default value is 15 seconds. You may set the `COLYSEUS_SEAT_RESERVATION_TIME`
|
|
3662
|
+
* environment variable if you'd like to change the seat reservation time globally.
|
|
3663
|
+
*
|
|
3664
|
+
* @default 15 seconds
|
|
3665
|
+
*/
|
|
3666
|
+
seatReservationTimeout: number;
|
|
3667
|
+
private _events;
|
|
3668
|
+
private _reservedSeats;
|
|
3669
|
+
private _reservedSeatTimeouts;
|
|
3670
|
+
private _reconnections;
|
|
3671
|
+
private _reconnectionAttempts;
|
|
3672
|
+
messages?: Messages$1<any>;
|
|
3673
|
+
private onMessageEvents;
|
|
3674
|
+
private onMessageValidators;
|
|
3675
|
+
private onMessageFallbacks;
|
|
3676
|
+
private _serializer;
|
|
3677
|
+
private _afterNextPatchQueue;
|
|
3678
|
+
private _simulationInterval;
|
|
3679
|
+
private _internalState;
|
|
3680
|
+
private _lockedExplicitly;
|
|
3681
|
+
private _autoDisposeTimeout;
|
|
3682
|
+
constructor();
|
|
3683
|
+
/**
|
|
3684
|
+
* This method is called by the MatchMaker before onCreate()
|
|
3685
|
+
* @internal
|
|
3686
|
+
*/
|
|
3687
|
+
private __init;
|
|
3688
|
+
/**
|
|
3689
|
+
* The name of the room you provided as first argument for `gameServer.define()`.
|
|
3690
|
+
*
|
|
3691
|
+
* @returns roomName string
|
|
3692
|
+
*/
|
|
3693
|
+
get roomName(): string;
|
|
3694
|
+
/**
|
|
3695
|
+
* Setting the name of the room. Overwriting this property is restricted.
|
|
3696
|
+
*
|
|
3697
|
+
* @param roomName
|
|
3698
|
+
*/
|
|
3699
|
+
set roomName(roomName: string);
|
|
3700
|
+
/**
|
|
3701
|
+
* A unique, auto-generated, 9-character-long id of the room.
|
|
3702
|
+
* You may replace `this.roomId` during `onCreate()`.
|
|
3703
|
+
*
|
|
3704
|
+
* @returns roomId string
|
|
3705
|
+
*/
|
|
3706
|
+
get roomId(): string;
|
|
3707
|
+
/**
|
|
3708
|
+
* Setting the roomId, is restricted in room lifetime except upon room creation.
|
|
3709
|
+
*
|
|
3710
|
+
* @param roomId
|
|
3711
|
+
* @returns roomId string
|
|
3712
|
+
*/
|
|
3713
|
+
set roomId(roomId: string);
|
|
3714
|
+
/**
|
|
3715
|
+
* This method is called before the latest version of the room's state is broadcasted to all clients.
|
|
3716
|
+
*/
|
|
3717
|
+
onBeforePatch?(state: ExtractRoomState<T>): void | Promise<any>;
|
|
3718
|
+
/**
|
|
3719
|
+
* This method is called when the room is created.
|
|
3720
|
+
* @param options - The options passed to the room when it is created.
|
|
3721
|
+
*/
|
|
3722
|
+
onCreate?(options: any): void | Promise<any>;
|
|
3723
|
+
/**
|
|
3724
|
+
* This method is called when a client joins the room.
|
|
3725
|
+
* @param client - The client that joined the room.
|
|
3726
|
+
* @param options - The options passed to the client when it joined the room.
|
|
3727
|
+
* @param auth - The data returned by the `onAuth` method - (Deprecated: use `client.auth` instead)
|
|
3728
|
+
*/
|
|
3729
|
+
onJoin?(client: ExtractRoomClient<T>, options?: any, auth?: any): void | Promise<any>;
|
|
3730
|
+
/**
|
|
3731
|
+
* This method is called when a client leaves the room without consent.
|
|
3732
|
+
* You may allow the client to reconnect by calling `allowReconnection` within this method.
|
|
3733
|
+
*
|
|
3734
|
+
* @param client - The client that was dropped from the room.
|
|
3735
|
+
* @param code - The close code of the leave event.
|
|
3736
|
+
*/
|
|
3737
|
+
onDrop?(client: ExtractRoomClient<T>, code?: number): void | Promise<any>;
|
|
3738
|
+
/**
|
|
3739
|
+
* This method is called when a client reconnects to the room.
|
|
3740
|
+
* @param client - The client that reconnected to the room.
|
|
3741
|
+
*/
|
|
3742
|
+
onReconnect?(client: ExtractRoomClient<T>): void | Promise<any>;
|
|
3743
|
+
/**
|
|
3744
|
+
* This method is called when a client effectively leaves the room.
|
|
3745
|
+
* @param client - The client that left the room.
|
|
3746
|
+
* @param code - The close code of the leave event.
|
|
3747
|
+
*/
|
|
3748
|
+
onLeave?(client: ExtractRoomClient<T>, code?: number): void | Promise<any>;
|
|
3749
|
+
/**
|
|
3750
|
+
* This method is called when the room is disposed.
|
|
3751
|
+
*/
|
|
3752
|
+
onDispose?(): void | Promise<any>;
|
|
3753
|
+
/**
|
|
3754
|
+
* Define a custom exception handler.
|
|
3755
|
+
* If defined, all lifecycle hooks will be wrapped by try/catch, and the exception will be forwarded to this method.
|
|
3756
|
+
*
|
|
3757
|
+
* These methods will be wrapped by try/catch:
|
|
3758
|
+
* - `onMessage`
|
|
3759
|
+
* - `onAuth` / `onJoin` / `onLeave` / `onCreate` / `onDispose`
|
|
3760
|
+
* - `clock.setTimeout` / `clock.setInterval`
|
|
3761
|
+
* - `setSimulationInterval`
|
|
3762
|
+
*
|
|
3763
|
+
* (Experimental: this feature is subject to change in the future - we're currently getting feedback to improve it)
|
|
3764
|
+
*/
|
|
3765
|
+
onUncaughtException?(error: RoomException, methodName: RoomMethodName): void;
|
|
3766
|
+
/**
|
|
3767
|
+
* This method is called before onJoin() - this is where you should authenticate the client
|
|
3768
|
+
* @param client - The client that is authenticating.
|
|
3769
|
+
* @param options - The options passed to the client when it is authenticating.
|
|
3770
|
+
* @param context - The authentication context, including the token and the client's IP address.
|
|
3771
|
+
* @returns The authentication result.
|
|
3772
|
+
*
|
|
3773
|
+
* @example
|
|
3774
|
+
* ```typescript
|
|
3775
|
+
* return {
|
|
3776
|
+
* userId: 123,
|
|
3777
|
+
* username: "John Doe",
|
|
3778
|
+
* email: "john.doe@example.com",
|
|
3779
|
+
* };
|
|
3780
|
+
* ```
|
|
3781
|
+
*/
|
|
3782
|
+
onAuth(client: Client$1, options: any, context: AuthContext): any | Promise<any>;
|
|
3783
|
+
static onAuth(token: string, options: any, context: AuthContext): Promise<unknown>;
|
|
3784
|
+
/**
|
|
3785
|
+
* This method is called during graceful shutdown of the server process
|
|
3786
|
+
* You may override this method to dispose the room in your own way.
|
|
3787
|
+
*
|
|
3788
|
+
* Once process reaches room count of 0, the room process will be terminated.
|
|
3789
|
+
*/
|
|
3790
|
+
onBeforeShutdown(): void;
|
|
3791
|
+
/**
|
|
3792
|
+
* devMode: When `devMode` is enabled, `onCacheRoom` method is called during
|
|
3793
|
+
* graceful shutdown.
|
|
3794
|
+
*
|
|
3795
|
+
* Implement this method to return custom data to be cached. `onRestoreRoom`
|
|
3796
|
+
* will be called with the data returned by `onCacheRoom`
|
|
3797
|
+
*/
|
|
3798
|
+
onCacheRoom?(): any;
|
|
3799
|
+
/**
|
|
3800
|
+
* devMode: When `devMode` is enabled, `onRestoreRoom` method is called during
|
|
3801
|
+
* process startup, with the data returned by the `onCacheRoom` method.
|
|
3802
|
+
*/
|
|
3803
|
+
onRestoreRoom?(cached?: any): void;
|
|
3804
|
+
/**
|
|
3805
|
+
* Returns whether the sum of connected clients and reserved seats exceeds maximum number of clients.
|
|
3806
|
+
*
|
|
3807
|
+
* @returns boolean
|
|
3808
|
+
*/
|
|
3809
|
+
hasReachedMaxClients(): boolean;
|
|
3810
|
+
/**
|
|
3811
|
+
* @deprecated Use `seatReservationTimeout=` instead.
|
|
3812
|
+
*/
|
|
3813
|
+
setSeatReservationTime(seconds: number): this;
|
|
3814
|
+
hasReservedSeat(sessionId: string, reconnectionToken?: string): boolean;
|
|
3815
|
+
checkReconnectionToken(reconnectionToken: string): string;
|
|
3816
|
+
/**
|
|
3817
|
+
* (Optional) Set a simulation interval that can change the state of the game.
|
|
3818
|
+
* The simulation interval is your game loop.
|
|
3819
|
+
*
|
|
3820
|
+
* @default 16.6ms (60fps)
|
|
3821
|
+
*
|
|
3822
|
+
* @param onTickCallback - You can implement your physics or world updates here!
|
|
3823
|
+
* This is a good place to update the room state.
|
|
3824
|
+
* @param delay - Interval delay on executing `onTickCallback` in milliseconds.
|
|
3825
|
+
*/
|
|
3826
|
+
setSimulationInterval(onTickCallback?: SimulationCallback, delay?: number): void;
|
|
3827
|
+
/**
|
|
3828
|
+
* @deprecated Use `.patchRate=` instead.
|
|
3829
|
+
*/
|
|
3830
|
+
setPatchRate(milliseconds: number | null): void;
|
|
3831
|
+
/**
|
|
3832
|
+
* @deprecated Use `.state =` instead.
|
|
3833
|
+
*/
|
|
3834
|
+
setState(newState: ExtractRoomState<T>): void;
|
|
3835
|
+
setSerializer(serializer: Serializer$1<ExtractRoomState<T>>): void;
|
|
3836
|
+
setMetadata(meta: Partial<ExtractRoomMetadata<T>>, persist?: boolean): Promise<void>;
|
|
3837
|
+
setPrivate(bool?: boolean, persist?: boolean): Promise<void>;
|
|
3838
|
+
/**
|
|
3839
|
+
* Update multiple matchmaking/listing properties at once with a single persist operation.
|
|
3840
|
+
* This is the recommended way to update room listing properties.
|
|
3841
|
+
*
|
|
3842
|
+
* @param updates - Object containing the properties to update
|
|
3843
|
+
*
|
|
3844
|
+
* @example
|
|
3845
|
+
* ```typescript
|
|
3846
|
+
* // Update multiple properties at once
|
|
3847
|
+
* await this.setMatchmaking({
|
|
3848
|
+
* metadata: { difficulty: "hard", rating: 1500 },
|
|
3849
|
+
* private: true,
|
|
3850
|
+
* locked: true,
|
|
3851
|
+
* maxClients: 10
|
|
3852
|
+
* });
|
|
3853
|
+
* ```
|
|
3854
|
+
*
|
|
3855
|
+
* @example
|
|
3856
|
+
* ```typescript
|
|
3857
|
+
* // Update only metadata
|
|
3858
|
+
* await this.setMatchmaking({
|
|
3859
|
+
* metadata: { status: "in_progress" }
|
|
3860
|
+
* });
|
|
3861
|
+
* ```
|
|
3862
|
+
*
|
|
3863
|
+
* @example
|
|
3864
|
+
* ```typescript
|
|
3865
|
+
* // Partial metadata update (merges with existing)
|
|
3866
|
+
* await this.setMatchmaking({
|
|
3867
|
+
* metadata: { ...this.metadata, round: this.metadata.round + 1 }
|
|
3868
|
+
* });
|
|
3869
|
+
* ```
|
|
3870
|
+
*/
|
|
3871
|
+
setMatchmaking(updates: {
|
|
3872
|
+
metadata?: ExtractRoomMetadata<T>;
|
|
3873
|
+
private?: boolean;
|
|
3874
|
+
locked?: boolean;
|
|
3875
|
+
maxClients?: number;
|
|
3876
|
+
unlisted?: boolean;
|
|
3877
|
+
[key: string]: any;
|
|
3878
|
+
}): Promise<void>;
|
|
3879
|
+
/**
|
|
3880
|
+
* Lock the room. This prevents new clients from joining this room.
|
|
3881
|
+
*/
|
|
3882
|
+
lock(): Promise<void>;
|
|
3883
|
+
/**
|
|
3884
|
+
* Unlock the room. This allows new clients to join this room, if maxClients is not reached.
|
|
3885
|
+
*/
|
|
3886
|
+
unlock(): Promise<void>;
|
|
3887
|
+
/**
|
|
3888
|
+
* @deprecated Use `client.send(...)` instead.
|
|
3889
|
+
*/
|
|
3890
|
+
send(client: Client$1, type: string | number, message: any, options?: ISendOptions): void;
|
|
3891
|
+
/**
|
|
3892
|
+
* Broadcast a message to all connected clients.
|
|
3893
|
+
* @param type - The type of the message.
|
|
3894
|
+
* @param message - The message to broadcast.
|
|
3895
|
+
* @param options - The options for the broadcast.
|
|
3896
|
+
*
|
|
3897
|
+
* @example
|
|
3898
|
+
* ```typescript
|
|
3899
|
+
* this.broadcast('message', { message: 'Hello, world!' });
|
|
3900
|
+
* ```
|
|
3901
|
+
*/
|
|
3902
|
+
broadcast<K extends keyof ExtractRoomClient<T>["~messages"] & string | number>(type: K, ...args: MessageArgs<ExtractRoomClient<T>["~messages"][K], IBroadcastOptions>): void;
|
|
3903
|
+
/**
|
|
3904
|
+
* Broadcast bytes (UInt8Arrays) to a particular room
|
|
3905
|
+
*/
|
|
3906
|
+
broadcastBytes(type: string | number, message: Uint8Array, options: IBroadcastOptions): void;
|
|
3907
|
+
/**
|
|
3908
|
+
* Checks whether mutations have occurred in the state, and broadcast them to all connected clients.
|
|
3909
|
+
*/
|
|
3910
|
+
broadcastPatch(): boolean;
|
|
3911
|
+
/**
|
|
3912
|
+
* Register a message handler for a specific message type.
|
|
3913
|
+
* This method is used to handle messages sent by clients to the room.
|
|
3914
|
+
* @param messageType - The type of the message.
|
|
3915
|
+
* @param callback - The callback to call when the message is received.
|
|
3916
|
+
* @returns A function to unbind the callback.
|
|
3917
|
+
*
|
|
3918
|
+
* @example
|
|
3919
|
+
* ```typescript
|
|
3920
|
+
* this.onMessage('message', (client, message) => {
|
|
3921
|
+
* console.log(message);
|
|
3922
|
+
* });
|
|
3923
|
+
* ```
|
|
3924
|
+
*
|
|
3925
|
+
* @example
|
|
3926
|
+
* ```typescript
|
|
3927
|
+
* const unbind = this.onMessage('message', (client, message) => {
|
|
3928
|
+
* console.log(message);
|
|
3929
|
+
* });
|
|
3930
|
+
*
|
|
3931
|
+
* // Unbind the callback when no longer needed
|
|
3932
|
+
* unbind();
|
|
3933
|
+
* ```
|
|
3934
|
+
*/
|
|
3935
|
+
onMessage<T = any, C extends Client$1 = ExtractRoomClient<T>>(messageType: "*", callback: (client: C, type: string | number, message: T) => void): any;
|
|
3936
|
+
onMessage<T = any, C extends Client$1 = ExtractRoomClient<T>>(messageType: string | number, callback: (client: C, message: T) => void): any;
|
|
3937
|
+
onMessage<T = any, C extends Client$1 = ExtractRoomClient<T>>(messageType: string | number, validationSchema: StandardSchemaV1<T>, callback: (client: C, message: T) => void): any;
|
|
3938
|
+
onMessageBytes<T = any, C extends Client$1 = ExtractRoomClient<T>>(messageType: string | number, callback: (client: C, message: T) => void): any;
|
|
3939
|
+
onMessageBytes<T = any, C extends Client$1 = ExtractRoomClient<T>>(messageType: string | number, validationSchema: StandardSchemaV1<T>, callback: (client: C, message: T) => void): any;
|
|
3940
|
+
/**
|
|
3941
|
+
* Disconnect all connected clients, and then dispose the room.
|
|
3942
|
+
*
|
|
3943
|
+
* @param closeCode WebSocket close code (default = 4000, which is a "consented leave")
|
|
3944
|
+
* @returns Promise<void>
|
|
3945
|
+
*/
|
|
3946
|
+
disconnect(closeCode?: number): Promise<any>;
|
|
3947
|
+
private _onJoin;
|
|
3948
|
+
/**
|
|
3949
|
+
* Allow the specified client to reconnect into the room. Must be used inside `onLeave()` method.
|
|
3950
|
+
* If seconds is provided, the reconnection is going to be cancelled after the provided amount of seconds.
|
|
3951
|
+
*
|
|
3952
|
+
* @param client - The client that is allowed to reconnect into the room.
|
|
3953
|
+
* @param seconds - The time in seconds that the client is allowed to reconnect into the room.
|
|
3954
|
+
*
|
|
3955
|
+
* @returns Deferred<Client> - The differed is a promise like type.
|
|
3956
|
+
* This type can forcibly reject the promise by calling `.reject()`.
|
|
3957
|
+
*
|
|
3958
|
+
* @example
|
|
3959
|
+
* ```typescript
|
|
3960
|
+
* onDrop(client: Client, code: CloseCode) {
|
|
3961
|
+
* // Allow the client to reconnect into the room with a 15 seconds timeout.
|
|
3962
|
+
* this.allowReconnection(client, 15);
|
|
3963
|
+
* }
|
|
3964
|
+
* ```
|
|
3965
|
+
*/
|
|
3966
|
+
allowReconnection(previousClient: Client$1, seconds: number | "manual"): Deferred<Client$1>;
|
|
3967
|
+
private resetAutoDisposeTimeout;
|
|
3968
|
+
private broadcastMessageType;
|
|
3969
|
+
private sendFullState;
|
|
3970
|
+
private _dequeueAfterPatchMessages;
|
|
3971
|
+
private _reserveSeat;
|
|
3972
|
+
private _reserveMultipleSeats;
|
|
3973
|
+
private _onMessage;
|
|
3974
|
+
private _onLeave;
|
|
3975
|
+
}
|
|
3976
|
+
type RoomMethodName = "onCreate" | "onAuth" | "onJoin" | "onLeave" | "onDrop" | "onReconnect" | "onDispose" | "onMessage" | "setSimulationInterval" | "setInterval" | "setTimeout";
|
|
3977
|
+
type RoomException<R extends Room$1 = Room$1> = OnCreateException<R> | OnAuthException<R> | OnJoinException<R> | OnLeaveException<R> | OnDropException<R> | OnReconnectException<R> | OnDisposeException | OnMessageException<R> | SimulationIntervalException | TimedEventException;
|
|
3978
|
+
declare class OnCreateException<R extends Room$1 = Room$1> extends Error {
|
|
3979
|
+
options: Parameters<R["onCreate"]>[0];
|
|
3980
|
+
constructor(cause: Error, message: string, options: Parameters<R["onCreate"]>[0]);
|
|
3981
|
+
}
|
|
3982
|
+
declare class OnAuthException<R extends Room$1 = Room$1> extends Error {
|
|
3983
|
+
client: Parameters<R["onAuth"]>[0];
|
|
3984
|
+
options: Parameters<R["onAuth"]>[1];
|
|
3985
|
+
constructor(cause: Error, message: string, client: Parameters<R["onAuth"]>[0], options: Parameters<R["onAuth"]>[1]);
|
|
3986
|
+
}
|
|
3987
|
+
declare class OnJoinException<R extends Room$1 = Room$1> extends Error {
|
|
3988
|
+
client: Parameters<R["onJoin"]>[0];
|
|
3989
|
+
options: Parameters<R["onJoin"]>[1];
|
|
3990
|
+
auth: Parameters<R["onJoin"]>[2];
|
|
3991
|
+
constructor(cause: Error, message: string, client: Parameters<R["onJoin"]>[0], options: Parameters<R["onJoin"]>[1], auth: Parameters<R["onJoin"]>[2]);
|
|
3992
|
+
}
|
|
3993
|
+
declare class OnLeaveException<R extends Room$1 = Room$1> extends Error {
|
|
3994
|
+
client: Parameters<R["onLeave"]>[0];
|
|
3995
|
+
consented: Parameters<R["onLeave"]>[1];
|
|
3996
|
+
constructor(cause: Error, message: string, client: Parameters<R["onLeave"]>[0], consented: Parameters<R["onLeave"]>[1]);
|
|
3997
|
+
}
|
|
3998
|
+
declare class OnDropException<R extends Room$1 = Room$1> extends Error {
|
|
3999
|
+
client: Parameters<R["onDrop"]>[0];
|
|
4000
|
+
code: Parameters<R["onDrop"]>[1];
|
|
4001
|
+
constructor(cause: Error, message: string, client: Parameters<R["onDrop"]>[0], code: Parameters<R["onDrop"]>[1]);
|
|
4002
|
+
}
|
|
4003
|
+
declare class OnReconnectException<R extends Room$1 = Room$1> extends Error {
|
|
4004
|
+
client: Parameters<R["onReconnect"]>[0];
|
|
4005
|
+
constructor(cause: Error, message: string, client: Parameters<R["onReconnect"]>[0]);
|
|
4006
|
+
}
|
|
4007
|
+
declare class OnDisposeException extends Error {
|
|
4008
|
+
constructor(cause: Error, message: string);
|
|
4009
|
+
}
|
|
4010
|
+
declare class OnMessageException<R extends Room$1, MessageType extends keyof R["messages"] = keyof R["messages"]> extends Error {
|
|
4011
|
+
client: R["~client"];
|
|
4012
|
+
payload: ExtractMessageType<R["messages"][MessageType]>;
|
|
4013
|
+
type: MessageType;
|
|
4014
|
+
constructor(cause: Error, message: string, client: R["~client"], payload: ExtractMessageType<R["messages"][MessageType]>, type: MessageType);
|
|
4015
|
+
isType<T extends keyof R["messages"]>(type: T): this is OnMessageException<R, T>;
|
|
4016
|
+
}
|
|
4017
|
+
declare class SimulationIntervalException extends Error {
|
|
4018
|
+
constructor(cause: Error, message: string);
|
|
4019
|
+
}
|
|
4020
|
+
declare class TimedEventException extends Error {
|
|
4021
|
+
args: any[];
|
|
4022
|
+
constructor(cause: Error, message: string, ...args: any[]);
|
|
4023
|
+
}
|
|
4024
|
+
type Type<T> = new (...args: any[]) => T;
|
|
4025
|
+
declare class Deferred<T = any> {
|
|
4026
|
+
promise: Promise<T>;
|
|
4027
|
+
resolve: Function;
|
|
4028
|
+
reject: Function;
|
|
4029
|
+
constructor(promise?: Promise<T>);
|
|
4030
|
+
then(onFulfilled?: (value: T) => any, onRejected?: (reason: any) => any): Promise<any>;
|
|
4031
|
+
catch(func: (value: any) => any): Promise<any>;
|
|
4032
|
+
static reject(reason?: any): Deferred<never>;
|
|
4033
|
+
static resolve<T = any>(value?: T): Deferred<T>;
|
|
4034
|
+
}
|
|
4035
|
+
interface SortOptions {
|
|
4036
|
+
[fieldName: string]: 1 | -1 | "asc" | "desc" | "ascending" | "descending";
|
|
4037
|
+
}
|
|
4038
|
+
type IRoomCacheSortByKeys = "clients" | "maxClients" | "createdAt";
|
|
4039
|
+
type IRoomCacheFilterByKeys = "clients" | "maxClients" | "processId";
|
|
4040
|
+
type ExtractRoomCacheMetadata<RoomType extends Room$1> = RoomType["~metadata"];
|
|
4041
|
+
type FilterByKeys<RoomType extends Room$1> = IRoomCacheFilterByKeys | (ExtractRoomCacheMetadata<RoomType> extends object ? keyof ExtractRoomCacheMetadata<RoomType> & string : never);
|
|
4042
|
+
type SortByKeys<RoomType extends Room$1> = IRoomCacheSortByKeys | (ExtractRoomCacheMetadata<RoomType> extends object ? keyof ExtractRoomCacheMetadata<RoomType> & string : never);
|
|
4043
|
+
interface RegisteredHandlerEvents<RoomType extends Room$1 = any> {
|
|
4044
|
+
create: [
|
|
4045
|
+
room: RoomType
|
|
4046
|
+
];
|
|
4047
|
+
lock: [
|
|
4048
|
+
room: RoomType
|
|
4049
|
+
];
|
|
4050
|
+
unlock: [
|
|
4051
|
+
room: RoomType
|
|
4052
|
+
];
|
|
4053
|
+
join: [
|
|
4054
|
+
room: RoomType,
|
|
4055
|
+
client: Client$1
|
|
4056
|
+
];
|
|
4057
|
+
leave: [
|
|
4058
|
+
room: RoomType,
|
|
4059
|
+
client: Client$1,
|
|
4060
|
+
willDispose: boolean
|
|
4061
|
+
];
|
|
4062
|
+
dispose: [
|
|
4063
|
+
room: RoomType
|
|
4064
|
+
];
|
|
4065
|
+
"visibility-change": [
|
|
4066
|
+
room: RoomType,
|
|
4067
|
+
isVisible: boolean
|
|
4068
|
+
];
|
|
4069
|
+
"metadata-change": [
|
|
4070
|
+
room: RoomType
|
|
4071
|
+
];
|
|
4072
|
+
}
|
|
4073
|
+
declare class RegisteredHandler<RoomType extends Room$1 = any> extends EventEmitter$1<RegisteredHandlerEvents<RoomType>> {
|
|
4074
|
+
"~room": RoomType;
|
|
4075
|
+
klass: Type<RoomType>;
|
|
4076
|
+
options: any;
|
|
4077
|
+
name: string;
|
|
4078
|
+
filterOptions: Array<FilterByKeys<RoomType>>;
|
|
4079
|
+
sortOptions?: SortOptions;
|
|
4080
|
+
realtimeListingEnabled: boolean;
|
|
4081
|
+
constructor(klass: Type<RoomType>, options?: any);
|
|
4082
|
+
enableRealtimeListing(): this;
|
|
4083
|
+
/**
|
|
4084
|
+
* Define which fields should be used for filtering rooms.
|
|
4085
|
+
* Supports both onCreate options and metadata fields using dot notation.
|
|
4086
|
+
*
|
|
4087
|
+
* @example
|
|
4088
|
+
* // Filter by IRoomCache fields
|
|
4089
|
+
* .filterBy(['maxClients'])
|
|
4090
|
+
*
|
|
4091
|
+
* @example
|
|
4092
|
+
* // Filter by metadata fields
|
|
4093
|
+
* .filterBy(['difficulty', 'metadata.region'])
|
|
4094
|
+
*
|
|
4095
|
+
* @example
|
|
4096
|
+
* // Mix both
|
|
4097
|
+
* .filterBy(['mode', 'difficulty', 'maxClients'])
|
|
4098
|
+
*/
|
|
4099
|
+
filterBy<T extends FilterByKeys<RoomType>>(options: T[]): this;
|
|
4100
|
+
/**
|
|
4101
|
+
* Define how rooms should be sorted when querying.
|
|
4102
|
+
* Supports both room cache fields and metadata fields using dot notation.
|
|
4103
|
+
*
|
|
4104
|
+
* @example
|
|
4105
|
+
* // Sort by number of clients (descending)
|
|
4106
|
+
* .sortBy({ clients: -1 })
|
|
4107
|
+
*
|
|
4108
|
+
* @example
|
|
4109
|
+
* // Sort by metadata field
|
|
4110
|
+
* .sortBy({ 'metadata.rating': -1 })
|
|
4111
|
+
*
|
|
4112
|
+
* @example
|
|
4113
|
+
* // Multiple sort criteria
|
|
4114
|
+
* .sortBy({ 'metadata.skillLevel': 1, clients: -1 })
|
|
4115
|
+
*/
|
|
4116
|
+
sortBy<T extends SortByKeys<RoomType>>(options: {
|
|
4117
|
+
[K in T]: SortOptions[string];
|
|
4118
|
+
}): this;
|
|
4119
|
+
getMetadataFromOptions(options: any): {
|
|
4120
|
+
metadata: {};
|
|
4121
|
+
} | {
|
|
4122
|
+
metadata?: undefined;
|
|
4123
|
+
};
|
|
4124
|
+
/**
|
|
4125
|
+
* Extract filter options from client options.
|
|
4126
|
+
*/
|
|
4127
|
+
getFilterOptions(options: any): {};
|
|
4128
|
+
}
|
|
4129
|
+
interface SDKTypes$1<RoomTypes extends Record<string, RegisteredHandler> = any, Routes extends Router = any> extends SDKTypes<RoomTypes, Routes> {
|
|
4130
|
+
}
|
|
4131
|
+
/**
|
|
4132
|
+
* Infer the room constructor from ServerType based on the instance type.
|
|
4133
|
+
* This allows proper type inference for SDK Room methods like `send()` and `onMessage()`.
|
|
4134
|
+
*/
|
|
4135
|
+
export type InferRoomConstructor<ServerType extends SDKTypes$1, Instance> = ServerType extends SDKTypes$1<infer Rooms> ? {
|
|
4136
|
+
[K in keyof Rooms]: Instance extends InstanceType<Rooms[K]["~room"]> ? Rooms[K]["~room"] : never;
|
|
4137
|
+
}[keyof Rooms] : // Fallback: create a synthetic constructor type from the instance
|
|
4138
|
+
(typeof Room$1) & {
|
|
4139
|
+
prototype: Instance;
|
|
4140
|
+
};
|
|
4141
|
+
|
|
4142
|
+
export {
|
|
4143
|
+
ISeatReservation as SeatReservation,
|
|
4144
|
+
};
|
|
4145
|
+
|
|
4146
|
+
export as namespace Colyseus;
|
|
4147
|
+
|
|
4148
|
+
export {};
|